fern-api 4.48.0 → 4.48.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.
Files changed (2) hide show
  1. package/cli.cjs +5 -5
  2. package/package.json +1 -1
package/cli.cjs CHANGED
@@ -1460,7 +1460,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
1460
1460
  `)}var Ovt=class extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var rq={Debug:"debug",Info:"info",Warn:"warn",Error:"error"},hms={[rq.Debug]:1,[rq.Info]:2,[rq.Warn]:3,[rq.Error]:4},Pvt=class{debug(t,...r){console.debug(t,...r)}info(t,...r){console.info(t,...r)}warn(t,...r){console.warn(t,...r)}error(t,...r){console.error(t,...r)}},hui=class{level;logger;silent;constructor(t){this.level=hms[t.level],this.logger=t.logger,this.silent=t.silent}shouldLog(t){return!this.silent&&this.level<=hms[t]}isDebug(){return this.shouldLog(rq.Debug)}debug(t,...r){this.isDebug()&&this.logger.debug(t,...r)}isInfo(){return this.shouldLog(rq.Info)}info(t,...r){this.isInfo()&&this.logger.info(t,...r)}isWarn(){return this.shouldLog(rq.Warn)}warn(t,...r){this.isWarn()&&this.logger.warn(t,...r)}isError(){return this.shouldLog(rq.Error)}error(t,...r){this.isError()&&this.logger.error(t,...r)}};var apA=new hui({level:rq.Info,logger:new Pvt,silent:!0});var gui;(function(e){e.LogLevel=rq,e.ConsoleLogger=Pvt})(gui||(gui={}));var rk={};te(rk,{AbsoluteProductPath:()=>xtr,AiChatConfig:()=>Fvt,AiChatDatasource:()=>Str,AiChatLocation:()=>Btr,AiChatModel:()=>Ttr,AiChatWebsiteDatasource:()=>_tr,AiExamplesConfig:()=>Otr,AnalyticsConfig:()=>Qtr,AnnouncementConfig:()=>phe,ApiReferenceConfiguration:()=>Vtr,ApiReferenceEndpointConfiguration:()=>qtr,ApiReferenceLayoutItem:()=>A$,ApiReferenceOperationConfiguration:()=>Gtr,ApiReferencePackageConfiguration:()=>Wtr,ApiReferencePackageConfigurationWithOptions:()=>Htr,ApiReferenceSectionConfiguration:()=>$tr,Audience:()=>m$,AudienceId:()=>kvt,Availability:()=>yx,BackgroundImageConfiguration:()=>Jtr,BackgroundImageThemedConfig:()=>Ktr,BodyThemeConfig:()=>Ytr,ChangelogConfiguration:()=>Xtr,ChangelogFolderRelativePath:()=>wVe,CheckConfig:()=>err,CheckRuleSeverity:()=>jse,CheckRulesConfig:()=>Ztr,CollapsedStringValue:()=>jtr,CollapsedValue:()=>h$,ColorConfig:()=>eE,ColorThemedConfig:()=>trr,ColorsConfiguration:()=>rrr,ContentAlignment:()=>nrr,CssConfig:()=>irr,CustomDomain:()=>orr,CustomPageAction:()=>srr,DocsConfiguration:()=>qms,DocsInstance:()=>lrr,DocsSettingsConfig:()=>drr,DocsTypographyConfig:()=>Arr,EditThisPageConfig:()=>urr,EditThisPageLaunch:()=>arr,ExperimentalConfig:()=>yrr,ExternalProduct:()=>Zrr,FeatureFlag:()=>Nvt,FeatureFlagConfiguration:()=>ztr,FolderConfiguration:()=>fnr,FontConfig:()=>BVe,FontConfigPath:()=>hrr,FontConfigVariant:()=>mrr,FontDisplay:()=>grr,FontStyle:()=>_Ve,FontWeight:()=>SVe,FooterLinksConfig:()=>brr,FooterNavThemeConfig:()=>inr,FullStoryAnalyticsConfig:()=>Ptr,GitLibraryInputSchema:()=>Orr,GithubEditThisPageConfig:()=>crr,GoogleAnalytics4Config:()=>Dtr,GtmConfig:()=>Rtr,HeaderPosition:()=>xrr,HttpSnippetLanguage:()=>prr,HttpSnippetsConfig:()=>frr,IntegrationsConfig:()=>Err,IntercomConfig:()=>Ftr,InternalProduct:()=>enr,JsConfig:()=>Crr,JsConfigOptions:()=>Qvt,JsFileConfig:()=>Irr,JsFileConfigSettings:()=>vrr,JsRemoteConfig:()=>wrr,JsScriptStrategy:()=>TVe,Language:()=>CVe,LanguageSwitcherThemeConfig:()=>onr,LayoutConfig:()=>Brr,LibraryConfig:()=>Trr,LibraryConfiguration:()=>krr,LibraryInputConfiguration:()=>Drr,LibraryLanguage:()=>Rrr,LibraryName:()=>PVe,LibraryOutputConfiguration:()=>Frr,LibraryReferenceConfiguration:()=>dnr,LinkConfiguration:()=>IVe,LogoConfiguration:()=>Nrr,MetadataConfig:()=>jrr,NavbarDropdownConfig:()=>Mrr,NavbarGithubConfig:()=>Urr,NavbarGithubConfigWithOptions:()=>Lrr,NavbarLink:()=>zrr,NavbarLinkConfig:()=>y$,NavigationConfig:()=>dhe,NavigationItem:()=>b$,PageActionOption:()=>Krr,PageActionOptions:()=>Jrr,PageActionsConfig:()=>Yrr,PageActionsThemeConfig:()=>snr,PageConfiguration:()=>GU,PathLibraryInputSchema:()=>Prr,PlaygroundButtonSettings:()=>Mtr,PlaygroundSettings:()=>g$,PostHogConfig:()=>ktr,ProductConfig:()=>tnr,ProductConfigBase:()=>RVe,ProductFileConfig:()=>Gms,ProductPath:()=>Wms,ProductSwitcherThemeConfig:()=>anr,ProgrammingLanguage:()=>rnr,RedirectConfig:()=>nnr,RelativeProductPath:()=>hnr,Role:()=>vVe,RoleId:()=>BOe,SearchbarPlacement:()=>_rr,SectionConfiguration:()=>mnr,SegmentConfig:()=>Ntr,SidebarThemeConfig:()=>cnr,SnippetLanguageConfiguration:()=>VU,SnippetsConfiguration:()=>Utr,SwitcherPlacement:()=>Srr,TabConfig:()=>mhe,TabId:()=>WU,TabVariant:()=>qrr,TabbedNavigationConfig:()=>$rr,TabbedNavigationItem:()=>Wrr,TabbedNavigationItemWithLayout:()=>Vrr,TabbedNavigationItemWithVariants:()=>Grr,TabsAlignment:()=>unr,TabsPlacement:()=>OVe,TabsThemeConfig:()=>lnr,Target:()=>qU,ThemeConfig:()=>pnr,TitleSource:()=>xVe,TwitterCardSetting:()=>Qrr,UntabbedNavigationConfig:()=>Hrr,VersionAvailability:()=>Xrr,VersionConfig:()=>DVe,VersionFileConfig:()=>$ms,VersionedSnippetLanguageConfiguration:()=>Ltr,WithFeatureFlags:()=>Gd,WithPermissions:()=>Wd,WithViewers:()=>fhe,docs:()=>Iui});var Iui={};te(Iui,{AbsoluteProductPath:()=>xtr,AiChatConfig:()=>Fvt,AiChatDatasource:()=>Str,AiChatLocation:()=>Btr,AiChatModel:()=>Ttr,AiChatWebsiteDatasource:()=>_tr,AiExamplesConfig:()=>Otr,AnalyticsConfig:()=>Qtr,AnnouncementConfig:()=>phe,ApiReferenceConfiguration:()=>Vtr,ApiReferenceEndpointConfiguration:()=>qtr,ApiReferenceLayoutItem:()=>A$,ApiReferenceOperationConfiguration:()=>Gtr,ApiReferencePackageConfiguration:()=>Wtr,ApiReferencePackageConfigurationWithOptions:()=>Htr,ApiReferenceSectionConfiguration:()=>$tr,Audience:()=>m$,AudienceId:()=>kvt,Availability:()=>yx,BackgroundImageConfiguration:()=>Jtr,BackgroundImageThemedConfig:()=>Ktr,BodyThemeConfig:()=>Ytr,ChangelogConfiguration:()=>Xtr,ChangelogFolderRelativePath:()=>wVe,CheckConfig:()=>err,CheckRuleSeverity:()=>jse,CheckRulesConfig:()=>Ztr,CollapsedStringValue:()=>jtr,CollapsedValue:()=>h$,ColorConfig:()=>eE,ColorThemedConfig:()=>trr,ColorsConfiguration:()=>rrr,ContentAlignment:()=>nrr,CssConfig:()=>irr,CustomDomain:()=>orr,CustomPageAction:()=>srr,DocsConfiguration:()=>qms,DocsInstance:()=>lrr,DocsSettingsConfig:()=>drr,DocsTypographyConfig:()=>Arr,EditThisPageConfig:()=>urr,EditThisPageLaunch:()=>arr,ExperimentalConfig:()=>yrr,ExternalProduct:()=>Zrr,FeatureFlag:()=>Nvt,FeatureFlagConfiguration:()=>ztr,FolderConfiguration:()=>fnr,FontConfig:()=>BVe,FontConfigPath:()=>hrr,FontConfigVariant:()=>mrr,FontDisplay:()=>grr,FontStyle:()=>_Ve,FontWeight:()=>SVe,FooterLinksConfig:()=>brr,FooterNavThemeConfig:()=>inr,FullStoryAnalyticsConfig:()=>Ptr,GitLibraryInputSchema:()=>Orr,GithubEditThisPageConfig:()=>crr,GoogleAnalytics4Config:()=>Dtr,GtmConfig:()=>Rtr,HeaderPosition:()=>xrr,HttpSnippetLanguage:()=>prr,HttpSnippetsConfig:()=>frr,IntegrationsConfig:()=>Err,IntercomConfig:()=>Ftr,InternalProduct:()=>enr,JsConfig:()=>Crr,JsConfigOptions:()=>Qvt,JsFileConfig:()=>Irr,JsFileConfigSettings:()=>vrr,JsRemoteConfig:()=>wrr,JsScriptStrategy:()=>TVe,Language:()=>CVe,LanguageSwitcherThemeConfig:()=>onr,LayoutConfig:()=>Brr,LibraryConfig:()=>Trr,LibraryConfiguration:()=>krr,LibraryInputConfiguration:()=>Drr,LibraryLanguage:()=>Rrr,LibraryName:()=>PVe,LibraryOutputConfiguration:()=>Frr,LibraryReferenceConfiguration:()=>dnr,LinkConfiguration:()=>IVe,LogoConfiguration:()=>Nrr,MetadataConfig:()=>jrr,NavbarDropdownConfig:()=>Mrr,NavbarGithubConfig:()=>Urr,NavbarGithubConfigWithOptions:()=>Lrr,NavbarLink:()=>zrr,NavbarLinkConfig:()=>y$,NavigationConfig:()=>dhe,NavigationItem:()=>b$,PageActionOption:()=>Krr,PageActionOptions:()=>Jrr,PageActionsConfig:()=>Yrr,PageActionsThemeConfig:()=>snr,PageConfiguration:()=>GU,PathLibraryInputSchema:()=>Prr,PlaygroundButtonSettings:()=>Mtr,PlaygroundSettings:()=>g$,PostHogConfig:()=>ktr,ProductConfig:()=>tnr,ProductConfigBase:()=>RVe,ProductFileConfig:()=>Gms,ProductPath:()=>Wms,ProductSwitcherThemeConfig:()=>anr,ProgrammingLanguage:()=>rnr,RedirectConfig:()=>nnr,RelativeProductPath:()=>hnr,Role:()=>vVe,RoleId:()=>BOe,SearchbarPlacement:()=>_rr,SectionConfiguration:()=>mnr,SegmentConfig:()=>Ntr,SidebarThemeConfig:()=>cnr,SnippetLanguageConfiguration:()=>VU,SnippetsConfiguration:()=>Utr,SwitcherPlacement:()=>Srr,TabConfig:()=>mhe,TabId:()=>WU,TabVariant:()=>qrr,TabbedNavigationConfig:()=>$rr,TabbedNavigationItem:()=>Wrr,TabbedNavigationItemWithLayout:()=>Vrr,TabbedNavigationItemWithVariants:()=>Grr,TabsAlignment:()=>unr,TabsPlacement:()=>OVe,TabsThemeConfig:()=>lnr,Target:()=>qU,ThemeConfig:()=>pnr,TitleSource:()=>xVe,TwitterCardSetting:()=>Qrr,UntabbedNavigationConfig:()=>Hrr,VersionAvailability:()=>Xrr,VersionConfig:()=>DVe,VersionFileConfig:()=>$ms,VersionedSnippetLanguageConfiguration:()=>Ltr,WithFeatureFlags:()=>Gd,WithPermissions:()=>Wd,WithViewers:()=>fhe});var ae={};te(ae,{JsonError:()=>yVe,ParseError:()=>bVe,any:()=>Tms,bigint:()=>Ams,boolean:()=>Oms,booleanLiteral:()=>Sms,date:()=>yms,discriminant:()=>Lms,enum_:()=>Itr,getObjectLikeUtils:()=>nq,getObjectUtils:()=>SOe,getSchemaUtils:()=>qd,isProperty:()=>Qse,lazy:()=>bms,lazyObject:()=>xms,list:()=>Ctr,never:()=>Pms,number:()=>Dms,object:()=>wtr,objectWithoutOptionalProperties:()=>Cms,optional:()=>Aui,property:()=>vms,record:()=>Nms,set:()=>Qms,string:()=>Rms,stringLiteral:()=>Bms,transform:()=>yui,undiscriminatedUnion:()=>Mms,union:()=>zms,unknown:()=>Fms,withParsedProperties:()=>vui});var Iu={BIGINT:"bigint",DATE:"date",ENUM:"enum",LIST:"list",STRING_LITERAL:"stringLiteral",BOOLEAN_LITERAL:"booleanLiteral",OBJECT:"object",ANY:"any",BOOLEAN:"boolean",NUMBER:"number",STRING:"string",UNKNOWN:"unknown",NEVER:"never",RECORD:"record",SET:"set",UNION:"union",UNDISCRIMINATED_UNION:"undiscriminatedUnion",NULLABLE:"nullable",OPTIONAL:"optional",OPTIONAL_NULLABLE:"optionalNullable"};function md(e,t){return`Expected ${t}. Received ${Ngl(e)}.`}function Ngl(e){if(Array.isArray(e))return"list";if(e===null)return"null";if(e instanceof BigInt)return"BigInt";switch(typeof e){case"string":return`"${e}"`;case"bigint":case"number":case"boolean":case"undefined":return`${e}`}return typeof e}function gx(e){return{...e,json:gms(e.json),parse:gms(e.parse)}}function gms(e){return(t,r)=>{let n=e(t,r),{skipValidation:i=!1}=r??{};return!n.ok&&i?(console.warn(["Failed to validate.",...n.errors.map(o=>" - "+(o.path.length>0?`${o.path.join(".")}: ${o.message}`:o.message))].join(`
1461
1461
  `)),{ok:!0,value:t}):n}}function vtr(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var yVe=class e extends Error{errors;constructor(t){super(t.map(vtr).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var bVe=class e extends Error{errors;constructor(t){super(t.map(vtr).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function qd(e){return{nullable:()=>Qgl(e),optional:()=>Aui(e),optionalNullable:()=>jgl(e),transform:t=>yui(e,t),parseOrThrow:(t,r)=>{let n=e.parse(t,r);if(n.ok)return n.value;throw new bVe(n.errors)},jsonOrThrow:(t,r)=>{let n=e.json(t,r);if(n.ok)return n.value;throw new yVe(n.errors)}}}function Qgl(e){let t={parse:(r,n)=>r==null?{ok:!0,value:null}:e.parse(r,n),json:(r,n)=>r==null?{ok:!0,value:null}:e.json(r,n),getType:()=>Iu.NULLABLE};return{...t,...qd(t)}}function Aui(e){let t={parse:(r,n)=>r==null?{ok:!0,value:void 0}:e.parse(r,n),json:(r,n)=>n?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:e.json(r,n),getType:()=>Iu.OPTIONAL};return{...t,...qd(t)}}function jgl(e){let t={parse:(r,n)=>r===void 0?{ok:!0,value:void 0}:r===null?{ok:!0,value:null}:e.parse(r,n),json:(r,n)=>r===void 0?{ok:!0,value:void 0}:r===null?{ok:!0,value:null}:e.json(r,n),getType:()=>Iu.OPTIONAL_NULLABLE};return{...t,...qd(t)}}function yui(e,t){let r={parse:(n,i)=>{let o=e.parse(n,i);return o.ok?{ok:!0,value:t.transform(o.value)}:o},json:(n,i)=>{let o=t.untransform(n);return e.json(o,i)},getType:()=>e.getType()};return{...r,...qd(r)}}function Ams(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t=="bigint"?{ok:!0,value:t}:typeof t=="number"?{ok:!0,value:BigInt(t)}:{ok:!1,errors:[{path:r,message:md(t,"bigint | number")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="bigint"?{ok:!1,errors:[{path:r,message:md(t,"bigint")}]}:{ok:!0,value:t},getType:()=>Iu.BIGINT};return{...gx(e),...qd(e)}}var Mgl=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function yms(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:md(t,"string")}]}:Mgl.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:md(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:md(t,"Date object")}]},getType:()=>Iu.DATE};return{...gx(e),...qd(e)}}function Ax(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...gx(r),...qd(r)}}}function Itr(e){let t=new Set(e);return Ax(Iu.ENUM,(n,{allowUnrecognizedEnumValues:i,breadcrumbsPrefix:o=[]}={})=>typeof n!="string"?{ok:!1,errors:[{path:o,message:md(n,"string")}]}:!t.has(n)&&!i?{ok:!1,errors:[{path:o,message:md(n,"enum")}]}:{ok:!0,value:n})()}function bms(e){let t=bui(e);return{...t,...qd(t)}}function bui(e){return{parse:(t,r)=>EVe(e).parse(t,r),json:(t,r)=>EVe(e).json(t,r),getType:()=>EVe(e).getType()}}function EVe(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function Eui(e){return Object.entries(e)}function Dvt(e,t){let r=new Set(t);return Object.entries(e).reduce((n,[i,o])=>(r.has(i)&&(n[i]=o),n),{})}function Nse(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===null?!0:Object.getPrototypeOf(t)===null}function Rvt(e){return Object.keys(e)}function Ems(e,t){let r=[],n=[];for(let i of e)t(i)?r.push(i):n.push(i);return[r,n]}var Lgl=Object.prototype.hasOwnProperty;function nq(e){return{withParsedProperties:t=>vui(e,t)}}function vui(e,t){let r={parse:(n,i)=>{let o=e.parse(n,i);if(!o.ok)return o;let s={};for(let a in t)if(Lgl.call(t,a)){let c=t[a];s[a]=typeof c=="function"?c(o.value):c}return{ok:!0,value:{...o.value,...s}}},json:(n,i)=>{if(!Nse(n))return{ok:!1,errors:[{path:i?.breadcrumbsPrefix??[],message:md(n,"object")}]};let o=new Set(Object.keys(t)),s=Dvt(n,Object.keys(n).filter(a=>!o.has(a)));return e.json(s,i)},getType:()=>e.getType()};return{...r,...qd(r),...nq(r)}}function vms(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function Qse(e){return e.isProperty}var Ugl=Object.prototype.hasOwnProperty;function wtr(e){let t;function r(){if(t==null){t={};for(let[d,f]of Eui(e)){let m=Qse(f)?f.rawKey:d,h=Qse(f)?f.valueSchema:f;t[m]={rawKey:m,parsedKey:d,valueSchema:h}}}return t}let n,i,o,s;function a(){if(n==null){n=[],i=[];for(let[d,f]of Eui(e)){let m=Qse(f)?f.rawKey:d,h=Qse(f)?f.valueSchema:f;zgl(h)&&(n.push(m),i.push(d))}o=new Set(n),s=new Set(i)}return n}function c(){return i==null&&a(),i}function u(){return o==null&&a(),o}function l(){return s==null&&a(),s}let p={_getRawProperties:()=>Object.entries(e).map(([d,f])=>Qse(f)?f.rawKey:d),_getParsedProperties:()=>Rvt(e),parse:(d,f)=>{let m=f?.breadcrumbsPrefix??[];return Ims({value:d,requiredKeys:a(),requiredKeysSet:u(),getProperty:h=>{let g=r()[h];if(g!=null)return{transformedKey:g.parsedKey,transform:A=>{let b=[...m,h];return g.valueSchema.parse(A,{...f,breadcrumbsPrefix:b})}}},unrecognizedObjectKeys:f?.unrecognizedObjectKeys,skipValidation:f?.skipValidation,breadcrumbsPrefix:m,omitUndefined:f?.omitUndefined})},json:(d,f)=>{let m=f?.breadcrumbsPrefix??[];return Ims({value:d,requiredKeys:c(),requiredKeysSet:l(),getProperty:h=>{let g=e[h];if(g!=null)return Qse(g)?{transformedKey:g.rawKey,transform:A=>{let b=[...m,h];return g.valueSchema.json(A,{...f,breadcrumbsPrefix:b})}}:{transformedKey:h,transform:A=>{let b=[...m,h];return g.json(A,{...f,breadcrumbsPrefix:b})}}},unrecognizedObjectKeys:f?.unrecognizedObjectKeys,skipValidation:f?.skipValidation,breadcrumbsPrefix:m,omitUndefined:f?.omitUndefined})},getType:()=>Iu.OBJECT};return{...gx(p),...qd(p),...nq(p),...SOe(p)}}function Ims({value:e,requiredKeys:t,requiredKeysSet:r,getProperty:n,unrecognizedObjectKeys:i="fail",skipValidation:o=!1,breadcrumbsPrefix:s=[]}){if(!Nse(e))return{ok:!1,errors:[{path:s,message:md(e,"object")}]};let a=t.length,c=[],u={};for(let l in e){if(!Ugl.call(e,l))continue;let p=e[l],d=n(l);if(d!=null){a>0&&r.has(l)&&a--;let f=d.transform(p);f.ok?u[d.transformedKey]=f.value:(u[l]=p,c.push(...f.errors))}else switch(i){case"fail":c.push({path:[...s,l],message:`Unexpected key "${l}"`});break;case"strip":break;case"passthrough":u[l]=p;break}}if(a>0)for(let l of t)l in e||c.push({path:s,message:`Missing required key "${l}"`});return c.length===0||o?{ok:!0,value:u}:{ok:!1,errors:c}}function SOe(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(n,i)=>wms({extensionKeys:t._getRawProperties(),value:n,transformBase:o=>e.parse(o,i),transformExtension:o=>t.parse(o,i),breadcrumbsPrefix:i?.breadcrumbsPrefix}),json:(n,i)=>wms({extensionKeys:t._getParsedProperties(),value:n,transformBase:o=>e.json(o,i),transformExtension:o=>t.json(o,i),breadcrumbsPrefix:i?.breadcrumbsPrefix}),getType:()=>Iu.OBJECT};return{...r,...qd(r),...nq(r),...SOe(r)}},passthrough:()=>{let t=new Set(e._getRawProperties()),r=new Set(e._getParsedProperties()),n={_getParsedProperties:()=>e._getParsedProperties(),_getRawProperties:()=>e._getRawProperties(),parse:(i,o)=>{let s=e.parse(i,{...o,unrecognizedObjectKeys:"passthrough"});if(!s.ok)return s;let a={};if(typeof i=="object"&&i!=null)for(let[c,u]of Object.entries(i))t.has(c)||(a[c]=u);return{ok:!0,value:{...a,...s.value}}},json:(i,o)=>{let s=e.json(i,{...o,unrecognizedObjectKeys:"passthrough"});if(!s.ok)return s;let a={};if(typeof i=="object"&&i!=null)for(let[c,u]of Object.entries(i))r.has(c)||(a[c]=u);return{ok:!0,value:{...a,...s.value}}},getType:()=>Iu.OBJECT};return{...n,...qd(n),...nq(n),...SOe(n)}}}}function wms({extensionKeys:e,value:t,transformBase:r,transformExtension:n,breadcrumbsPrefix:i=[]}){if(!Nse(t))return{ok:!1,errors:[{path:i,message:md(t,"object")}]};let o=new Set(e),[s,a]=Ems(Rvt(t),l=>o.has(l)),c=r(Dvt(t,a)),u=n(Dvt(t,s));return c.ok&&u.ok?{ok:!0,value:{...c.value,...u.value}}:{ok:!1,errors:[...c.ok?[]:c.errors,...u.ok?[]:u.errors]}}function zgl(e){return!Vgl(e)}function Vgl(e){switch(e.getType()){case Iu.ANY:case Iu.UNKNOWN:case Iu.OPTIONAL:case Iu.OPTIONAL_NULLABLE:return!0;default:return!1}}function Cms(e){return wtr(e)}function xms(e){let t={...bui(e),_getRawProperties:()=>EVe(e)._getRawProperties(),_getParsedProperties:()=>EVe(e)._getParsedProperties()};return{...t,...qd(t),...nq(t),...SOe(t)}}function Ctr(e){let t={parse:(r,n)=>_ms(r,(i,o)=>e.parse(i,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`[${o}]`]})),json:(r,n)=>_ms(r,(i,o)=>e.json(i,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`[${o}]`]})),getType:()=>Iu.LIST};return{...gx(t),...qd(t)}}function _ms(e,t){if(!Array.isArray(e))return{ok:!1,errors:[{message:md(e,"list"),path:[]}]};let r=[],n=[];for(let i=0;i<e.length;i++){let o=t(e[i],i);o.ok?r.push(o.value):n.push(...o.errors)}return n.length===0?{ok:!0,value:r}:{ok:!1,errors:n}}function Sms(e){return Ax(Iu.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:n=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:n,message:md(r,`${e.toString()}`)}]})()}function Bms(e){return Ax(Iu.STRING_LITERAL,(r,{breadcrumbsPrefix:n=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:n,message:md(r,`"${e}"`)}]})()}var Tms=Ax(Iu.ANY,e=>({ok:!0,value:e}));var Oms=Ax(Iu.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:md(e,"boolean")}]});var Pms=Ax(Iu.NEVER,(e,{breadcrumbsPrefix:t=[]}={})=>({ok:!1,errors:[{path:t,message:"Expected never"}]}));var Dms=Ax(Iu.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:md(e,"number")}]});var Rms=Ax(Iu.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:md(e,"string")}]});var Fms=Ax(Iu.UNKNOWN,e=>({ok:!0,value:e}));var qgl=Object.prototype.hasOwnProperty;function Nms(e,t){let r={parse:(n,i)=>kms({value:n,isKeyNumeric:e.getType()===Iu.NUMBER,transformKey:o=>e.parse(o,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${o} (key)`]}),transformValue:(o,s)=>t.parse(o,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${s}`]}),breadcrumbsPrefix:i?.breadcrumbsPrefix}),json:(n,i)=>kms({value:n,isKeyNumeric:e.getType()===Iu.NUMBER,transformKey:o=>e.json(o,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${o} (key)`]}),transformValue:(o,s)=>t.json(o,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${s}`]}),breadcrumbsPrefix:i?.breadcrumbsPrefix}),getType:()=>Iu.RECORD};return{...gx(r),...qd(r)}}function kms({value:e,isKeyNumeric:t,transformKey:r,transformValue:n,breadcrumbsPrefix:i=[]}){if(!Nse(e))return{ok:!1,errors:[{path:i,message:md(e,"object")}]};let o={},s=[];for(let a in e){if(!qgl.call(e,a))continue;let c=e[a];if(c===void 0)continue;let u=a;if(t){let d=a.length>0?Number(a):NaN;Number.isNaN(d)||(u=d)}let l=r(u),p=n(c,u);l.ok&&p.ok?o[l.value]=p.value:(l.ok||s.push(...l.errors),p.ok||s.push(...p.errors))}return s.length===0?{ok:!0,value:o}:{ok:!1,errors:s}}function Qms(e){let t=Ctr(e),r={parse:(n,i)=>{let o=t.parse(n,i);return o.ok?{ok:!0,value:new Set(o.value)}:o},json:(n,i)=>n instanceof Set?t.json([...n],i):{ok:!1,errors:[{path:i?.breadcrumbsPrefix??[],message:md(n,"Set")}]},getType:()=>Iu.SET};return{...gx(r),...qd(r)}}function Mms(e){let t={parse:(r,n)=>jms((i,o)=>i.parse(r,o),e,n),json:(r,n)=>jms((i,o)=>i.json(r,o),e,n),getType:()=>Iu.UNDISCRIMINATED_UNION};return{...gx(t),...qd(t)}}function jms(e,t,r){let n=[];for(let[i,o]of t.entries()){let s=e(o,{...r,skipValidation:!1});if(s.ok)return s;for(let a of s.errors)n.push({path:a.path,message:`[Variant ${i}] ${a.message}`})}return{ok:!1,errors:n}}function Lms(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}var Ggl=Object.prototype.hasOwnProperty;function zms(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,n=typeof e=="string"?e:e.parsedDiscriminant,i=Itr(Rvt(t)),o={parse:(s,a)=>Ums({value:s,discriminant:r,transformedDiscriminant:n,transformDiscriminantValue:c=>i.parse(c,{allowUnrecognizedEnumValues:a?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...a?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:c=>t[c],allowUnrecognizedUnionMembers:a?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(c,u)=>u.parse(c,a),breadcrumbsPrefix:a?.breadcrumbsPrefix}),json:(s,a)=>Ums({value:s,discriminant:n,transformedDiscriminant:r,transformDiscriminantValue:c=>i.json(c,{allowUnrecognizedEnumValues:a?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...a?.breadcrumbsPrefix??[],n]}),getAdditionalPropertiesSchema:c=>t[c],allowUnrecognizedUnionMembers:a?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(c,u)=>u.json(c,a),breadcrumbsPrefix:a?.breadcrumbsPrefix}),getType:()=>Iu.UNION};return{...gx(o),...qd(o),...nq(o)}}function Ums({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:n,getAdditionalPropertiesSchema:i,allowUnrecognizedUnionMembers:o=!1,transformAdditionalProperties:s,breadcrumbsPrefix:a=[]}){if(!Nse(e))return{ok:!1,errors:[{path:a,message:md(e,"object")}]};let c=e[t],u={};for(let f in e)Ggl.call(e,f)&&f!==t&&(u[f]=e[f]);if(c==null)return{ok:!1,errors:[{path:a,message:`Missing discriminant ("${t}")`}]};let l=n(c);if(!l.ok)return{ok:!1,errors:l.errors};let p=i(l.value);if(p==null)return o?{ok:!0,value:{[r]:l.value,...u}}:{ok:!1,errors:[{path:[...a,t],message:"Unexpected discriminant value"}]};let d=s(u,p);return d.ok?{ok:!0,value:{[r]:c,...d.value}}:d}var xtr=ae.object({href:ae.string()});var _tr=ae.object({url:ae.string(),title:ae.string().optional()});var Str=ae.undiscriminatedUnion([_tr]);var Btr=ae.enum_(["docs","slack","discord"]);var Ttr=ae.enum_(["claude-3.7","claude-4","command-a"]);var Fvt=ae.object({model:Ttr.optional(),systemPrompt:ae.property("system-prompt",ae.string().optional()),location:ae.list(Btr).optional(),datasources:ae.list(Str).optional()});var Otr=ae.object({enabled:ae.boolean().optional(),style:ae.string().optional()});var Ptr=ae.object({orgId:ae.property("org-id",ae.string())});var Dtr=ae.object({measurementId:ae.property("measurement-id",ae.string())});var Rtr=ae.object({containerId:ae.property("container-id",ae.string())});var Ftr=ae.object({appId:ae.property("app-id",ae.string()),apiBase:ae.property("api-base",ae.string().optional())});var ktr=ae.object({apiKey:ae.property("api-key",ae.string()),endpoint:ae.string().optional()});var Ntr=ae.object({writeKey:ae.property("write-key",ae.string())});var Qtr=ae.object({segment:Ntr.optional(),fullstory:Ptr.optional(),intercom:Ftr.optional(),posthog:ktr.optional(),gtm:Rtr.optional(),ga4:Dtr.optional()});var phe=ae.object({message:ae.string()});var kvt=ae.string();var m$=ae.undiscriminatedUnion([kvt,ae.list(kvt)]);var yx=ae.enum_(["stable","generally-available","in-development","pre-release","deprecated","beta"]);var jtr=ae.enum_(["open-by-default"]);var h$=ae.undiscriminatedUnion([ae.boolean(),jtr]);var Mtr=ae.object({href:ae.string().optional()});var g$=ae.object({hidden:ae.boolean().optional(),environments:ae.list(ae.string()).optional(),button:Mtr.optional(),oauth:ae.boolean().optional(),limitWebsocketMessagesPerConnection:ae.property("limit-websocket-messages-per-connection",ae.number().optional())});var Ltr=ae.object({version:ae.string(),package:ae.string()});var VU=ae.undiscriminatedUnion([ae.string(),Ltr]);var Utr=ae.object({python:VU.optional(),typescript:VU.optional(),go:VU.optional(),java:VU.optional(),ruby:VU.optional(),csharp:VU.optional(),php:VU.optional(),swift:VU.optional(),rust:VU.optional()});var Nvt=ae.object({flag:ae.string(),fallbackValue:ae.property("fallback-value",ae.unknown().optional()),match:ae.unknown().optional()});var ztr=ae.undiscriminatedUnion([ae.string(),Nvt,ae.list(Nvt)]);var Gd=ae.object({featureFlag:ae.property("feature-flag",ztr.optional())});var BOe=ae.string();var vVe=ae.undiscriminatedUnion([BOe,ae.list(BOe)]);var Wd=ae.object({viewers:vVe.optional(),orphaned:ae.boolean().optional()});var Vtr=ae.object({api:ae.string(),apiName:ae.property("api-name",ae.string().optional()),openrpc:ae.string().optional(),audiences:m$.optional(),displayErrors:ae.property("display-errors",ae.boolean().optional()),tagDescriptionPages:ae.property("tag-description-pages",ae.boolean().optional()),snippets:Utr.optional(),postman:ae.string().optional(),summary:ae.string().optional(),layout:ae.list(ae.lazy(()=>A$)).optional(),collapsed:h$.optional(),icon:ae.string().optional(),slug:ae.string().optional(),hidden:ae.boolean().optional(),availability:yx.optional(),skipSlug:ae.property("skip-slug",ae.boolean().optional()),alphabetized:ae.boolean().optional(),flattened:ae.boolean().optional(),paginated:ae.boolean().optional(),playground:g$.optional()}).extend(Wd).extend(Gd);var qtr=ae.object({endpoint:ae.string(),title:ae.string().optional(),slug:ae.string().optional(),icon:ae.string().optional(),hidden:ae.boolean().optional(),availability:yx.optional(),playground:g$.optional()}).extend(Wd).extend(Gd);var Gtr=ae.object({operation:ae.string(),title:ae.string().optional(),slug:ae.string().optional(),hidden:ae.boolean().optional(),availability:yx.optional()}).extend(Wd).extend(Gd);var qU=ae.enum_(["_blank","_self","_parent","_top"]);var IVe=ae.object({link:ae.string(),href:ae.string(),icon:ae.string().optional(),target:qU.optional()});var GU=ae.object({page:ae.string(),path:ae.string(),slug:ae.string().optional(),icon:ae.string().optional(),hidden:ae.boolean().optional(),noindex:ae.boolean().optional(),availability:yx.optional()}).extend(Wd).extend(Gd);var A$=ae.undiscriminatedUnion([ae.string(),ae.record(ae.string(),ae.lazy(()=>Wtr)),ae.lazyObject(()=>$tr),qtr,Gtr,GU,IVe]);var Wtr=ae.undiscriminatedUnion([ae.list(ae.lazy(()=>A$)),ae.lazyObject(()=>Htr)]);var Htr=ae.object({title:ae.string().optional(),summary:ae.string().optional(),contents:ae.list(ae.lazy(()=>A$)).optional(),availability:yx.optional(),slug:ae.string().optional(),icon:ae.string().optional(),hidden:ae.boolean().optional(),skipSlug:ae.property("skip-slug",ae.boolean().optional()),playground:g$.optional()}).extend(Wd).extend(Gd);var $tr=ae.object({section:ae.string(),referencedPackages:ae.property("referenced-packages",ae.list(ae.string()).optional()),summary:ae.string().optional(),contents:ae.list(ae.lazy(()=>A$)).optional(),slug:ae.string().optional(),icon:ae.string().optional(),hidden:ae.boolean().optional(),skipSlug:ae.property("skip-slug",ae.boolean().optional()),collapsed:h$.optional(),collapsible:ae.boolean().optional(),collapsedByDefault:ae.property("collapsed-by-default",ae.boolean().optional()),availability:yx.optional(),playground:g$.optional()}).extend(Wd).extend(Gd);var Ktr=ae.object({dark:ae.string().optional(),light:ae.string().optional()});var Jtr=ae.undiscriminatedUnion([ae.string(),Ktr]);var Ytr=ae.enum_(["default","canvas"]);var wVe=ae.string();var Xtr=ae.object({changelog:wVe,title:ae.string().optional(),slug:ae.string().optional(),icon:ae.string().optional(),hidden:ae.boolean().optional()}).extend(Wd).extend(Gd);var jse=ae.enum_(["warn","error"]);var Ztr=ae.object({exampleValidation:ae.property("example-validation",jse.optional()),brokenLinks:ae.property("broken-links",jse.optional()),noNonComponentRefs:ae.property("no-non-component-refs",jse.optional()),validLocalReferences:ae.property("valid-local-references",jse.optional()),noCircularRedirects:ae.property("no-circular-redirects",jse.optional()),validDocsEndpoints:ae.property("valid-docs-endpoints",jse.optional())});var err=ae.object({rules:Ztr.optional()});var trr=ae.object({dark:ae.string().optional(),light:ae.string().optional()});var eE=ae.undiscriminatedUnion([ae.string(),trr]);var rrr=ae.object({accentPrimary:ae.property("accent-primary",eE.optional()),accentPrimaryDeprecated:ae.property("accentPrimary",eE.optional()),background:eE.optional(),border:eE.optional(),sidebarBackground:ae.property("sidebar-background",eE.optional()),headerBackground:ae.property("header-background",eE.optional()),cardBackground:ae.property("card-background",eE.optional()),accent1:ae.property("accent-1",eE.optional()),accent2:ae.property("accent-2",eE.optional()),accent3:ae.property("accent-3",eE.optional()),accent4:ae.property("accent-4",eE.optional()),accent5:ae.property("accent-5",eE.optional()),accent6:ae.property("accent-6",eE.optional()),accent7:ae.property("accent-7",eE.optional()),accent8:ae.property("accent-8",eE.optional()),accent9:ae.property("accent-9",eE.optional()),accent10:ae.property("accent-10",eE.optional()),accent11:ae.property("accent-11",eE.optional()),accent12:ae.property("accent-12",eE.optional())});var nrr=ae.enum_(["center","left"]);var irr=ae.undiscriminatedUnion([ae.string(),ae.list(ae.string())]);var orr=ae.undiscriminatedUnion([ae.string(),ae.list(ae.string())]);var srr=ae.object({title:ae.string(),subtitle:ae.string().optional(),url:ae.string(),icon:ae.string().optional(),default:ae.boolean().optional()});var arr=ae.enum_(["github","dashboard"]);var crr=ae.object({host:ae.string().optional(),owner:ae.string(),repo:ae.string(),branch:ae.string().optional()});var urr=ae.object({github:crr.optional(),launch:arr.optional()});var lrr=ae.object({url:ae.string(),customDomain:ae.property("custom-domain",orr.optional()),private:ae.boolean().optional(),editThisPage:ae.property("edit-this-page",urr.optional()),audiences:m$.optional()});var prr=ae.enum_(["curl","csharp","go","java","javascript","php","python","ruby","swift","typescript"]);var frr=ae.undiscriminatedUnion([ae.boolean(),ae.list(prr)]);var CVe=ae.enum_(["en","es","fr","de","it","pt","ja","zh","ko","el","no","pl","ru","sv","tr"]);var xVe=ae.enum_(["frontmatter","filename"]);var drr=ae.object({searchText:ae.property("search-text",ae.string().optional()),disableSearch:ae.property("disable-search",ae.boolean().optional()),darkModeCode:ae.property("dark-mode-code",ae.boolean().optional()),defaultSearchFilters:ae.property("default-search-filters",ae.boolean().optional()),httpSnippets:ae.property("http-snippets",frr.optional()),hide404Page:ae.property("hide-404-page",ae.boolean().optional()),useJavascriptAsTypescript:ae.property("use-javascript-as-typescript",ae.boolean().optional()),disableExplorerProxy:ae.property("disable-explorer-proxy",ae.boolean().optional()),disableAnalytics:ae.property("disable-analytics",ae.boolean().optional()),language:CVe.optional(),folderTitleSource:ae.property("folder-title-source",xVe.optional()),substituteEnvVars:ae.property("substitute-env-vars",ae.boolean().optional())});var _Ve=ae.enum_(["normal","italic"]);var SVe=ae.undiscriminatedUnion([ae.string(),ae.number()]);var mrr=ae.object({path:ae.string(),weight:SVe.optional(),style:_Ve.optional()});var hrr=ae.undiscriminatedUnion([ae.string(),mrr]);var grr=ae.enum_(["auto","block","swap","fallback","optional"]);var BVe=ae.object({name:ae.string().optional(),path:ae.string().optional(),weight:SVe.optional(),style:_Ve.optional(),paths:ae.list(hrr).optional(),display:grr.optional(),fallback:ae.list(ae.string()).optional(),fontVariationSettings:ae.property("font-variation-settings",ae.string().optional())});var Arr=ae.object({headingsFont:BVe.optional(),bodyFont:BVe.optional(),codeFont:BVe.optional()});var yrr=ae.object({mdxComponents:ae.property("mdx-components",ae.list(ae.string()).optional()),disableStreamToggle:ae.property("disable-stream-toggle",ae.boolean().optional()),openapiParserV2:ae.property("openapi-parser-v2",ae.boolean().optional()),openapiParserV3:ae.property("openapi-parser-v3",ae.boolean().optional()),dynamicSnippets:ae.property("dynamic-snippets",ae.boolean().optional()),aiExamples:ae.property("ai-examples",ae.boolean().optional()),aiExampleStyleInstructions:ae.property("ai-example-style-instructions",ae.string().optional()),excludeApis:ae.property("exclude-apis",ae.boolean().optional()),basepathAware:ae.property("basepath-aware",ae.boolean().optional())});var brr=ae.object({github:ae.string().optional(),twitter:ae.string().optional(),x:ae.string().optional(),linkedin:ae.string().optional(),youtube:ae.string().optional(),instagram:ae.string().optional(),facebook:ae.string().optional(),discord:ae.string().optional(),slack:ae.string().optional(),hackernews:ae.string().optional(),medium:ae.string().optional(),website:ae.string().optional()});var Err=ae.object({intercom:ae.string().optional()});var TVe=ae.enum_(["beforeInteractive","afterInteractive","lazyOnload"]);var vrr=ae.object({path:ae.string(),strategy:TVe.optional()});var Irr=ae.undiscriminatedUnion([ae.string(),vrr]);var wrr=ae.object({url:ae.string(),strategy:TVe.optional()});var Qvt=ae.undiscriminatedUnion([wrr,Irr]);var Crr=ae.undiscriminatedUnion([Qvt,ae.list(Qvt)]);var xrr=ae.enum_(["fixed","static"]);var _rr=ae.enum_(["header","header-tabs","sidebar"]);var Srr=ae.enum_(["header","sidebar"]);var OVe=ae.enum_(["header","sidebar"]);var Brr=ae.object({pageWidth:ae.property("page-width",ae.string().optional()),contentWidth:ae.property("content-width",ae.string().optional()),sidebarWidth:ae.property("sidebar-width",ae.string().optional()),headerHeight:ae.property("header-height",ae.string().optional()),searchbarPlacement:ae.property("searchbar-placement",_rr.optional()),tabsPlacement:ae.property("tabs-placement",OVe.optional()),switcherPlacement:ae.property("switcher-placement",Srr.optional()),contentAlignment:ae.property("content-alignment",nrr.optional()),headerPosition:ae.property("header-position",xrr.optional()),disableHeader:ae.property("disable-header",ae.boolean().optional()),hideNavLinks:ae.property("hide-nav-links",ae.boolean().optional()),hideFeedback:ae.property("hide-feedback",ae.boolean().optional())});var Trr=ae.object({doxyfile:ae.string().optional()});var Orr=ae.object({git:ae.string(),subpath:ae.string().optional()});var Prr=ae.object({path:ae.string()});var Drr=ae.undiscriminatedUnion([Orr,Prr]);var Rrr=ae.enum_(["python","cpp"]);var Frr=ae.object({path:ae.string()});var krr=ae.object({input:Drr,output:Frr,lang:Rrr,config:Trr.optional()});var PVe=ae.string();var Nrr=ae.object({dark:ae.string().optional(),light:ae.string().optional(),height:ae.number().optional(),href:ae.string().optional(),rightText:ae.property("right-text",ae.string().optional())});var Qrr=ae.enum_(["summary","summary_large_image","app","player"]);var jrr=ae.object({ogSiteName:ae.property("og:site_name",ae.string().optional()),ogTitle:ae.property("og:title",ae.string().optional()),ogDescription:ae.property("og:description",ae.string().optional()),ogUrl:ae.property("og:url",ae.string().optional()),ogImage:ae.property("og:image",ae.string().optional()),ogImageWidth:ae.property("og:image:width",ae.number().optional()),ogImageHeight:ae.property("og:image:height",ae.number().optional()),ogLocale:ae.property("og:locale",ae.string().optional()),ogLogo:ae.property("og:logo",ae.string().optional()),twitterTitle:ae.property("twitter:title",ae.string().optional()),twitterDescription:ae.property("twitter:description",ae.string().optional()),twitterHandle:ae.property("twitter:handle",ae.string().optional()),twitterImage:ae.property("twitter:image",ae.string().optional()),twitterSite:ae.property("twitter:site",ae.string().optional()),twitterUrl:ae.property("twitter:url",ae.string().optional()),twitterCard:ae.property("twitter:card",Qrr.optional()),ogDynamic:ae.property("og:dynamic",ae.boolean().optional()),ogBackgroundImage:ae.property("og:background-image",ae.string().optional()),canonicalHost:ae.property("canonical-host",ae.string().optional())});var fhe=ae.object({viewers:vVe.optional()});var y$=ae.object({href:ae.string().optional(),target:qU.optional(),url:ae.string().optional(),text:ae.string().optional(),icon:ae.string().optional(),rightIcon:ae.string().optional(),rounded:ae.boolean().optional()}).extend(fhe);var Mrr=ae.object({links:ae.list(y$),text:ae.string().optional(),icon:ae.string().optional(),rightIcon:ae.string().optional(),rounded:ae.boolean().optional()}).extend(fhe);var Lrr=ae.object({url:ae.string(),target:qU.optional()}).extend(fhe);var Urr=ae.undiscriminatedUnion([ae.string(),Lrr]);var zrr=ae.union("type",{filled:y$,outlined:y$,minimal:y$,github:ae.object({value:Urr}),dropdown:Mrr,primary:y$,secondary:y$}).transform({transform:e=>e,untransform:e=>e});var WU=ae.string();var Vrr=ae.object({tab:WU,layout:ae.list(ae.lazy(()=>b$)).optional()});var qrr=ae.object({title:ae.string(),subtitle:ae.string().optional(),icon:ae.string().optional(),layout:ae.list(ae.lazy(()=>b$)),slug:ae.string().optional(),skipSlug:ae.property("skip-slug",ae.boolean().optional()),hidden:ae.boolean().optional(),default:ae.boolean().optional()}).extend(Wd).extend(Gd);var Grr=ae.object({tab:WU,variants:ae.list(qrr)});var Wrr=ae.undiscriminatedUnion([Vrr,Grr]);var $rr=ae.list(Wrr);var Hrr=ae.list(ae.lazy(()=>b$));var dhe=ae.undiscriminatedUnion([Hrr,$rr]);var Krr=ae.enum_(["copy-page","view-as-markdown","ask-ai","chatgpt","claude","cursor","vscode"]);var Jrr=ae.object({copyPage:ae.property("copy-page",ae.boolean().optional()),viewAsMarkdown:ae.property("view-as-markdown",ae.boolean().optional()),askAi:ae.property("ask-ai",ae.boolean().optional()),chatgpt:ae.boolean().optional(),claude:ae.boolean().optional(),cursor:ae.boolean().optional(),vscode:ae.boolean().optional(),custom:ae.list(srr).optional()});var Yrr=ae.object({default:Krr.optional(),options:Jrr.optional()});var Xrr=ae.enum_(["deprecated","ga","stable","beta"]);var DVe=ae.object({displayName:ae.property("display-name",ae.string()),path:ae.string(),slug:ae.string().optional(),availability:Xrr.optional(),audiences:m$.optional(),hidden:ae.boolean().optional(),announcement:phe.optional()}).extend(Wd).extend(Gd);var RVe=ae.object({displayName:ae.property("display-name",ae.string()),subtitle:ae.string().optional(),icon:ae.string().optional(),image:ae.string().optional(),versions:ae.list(DVe).optional(),audiences:m$.optional()}).extend(Wd).extend(Gd);var Zrr=ae.object({href:ae.string(),target:qU.optional()}).extend(RVe);var enr=ae.object({path:ae.string(),slug:ae.string().optional(),announcement:phe.optional()}).extend(RVe);var tnr=ae.undiscriminatedUnion([enr,Zrr]);var rnr=ae.enum_(["typescript","javascript","python","java","go","ruby","csharp","php","swift","rust","nodets","nodejs","dotnet","curl","jvm","ts","js"]);var nnr=ae.object({source:ae.string(),destination:ae.string(),permanent:ae.boolean().optional()});var mhe=ae.object({displayName:ae.property("display-name",ae.string()),icon:ae.string().optional(),slug:ae.string().optional(),skipSlug:ae.property("skip-slug",ae.boolean().optional()),hidden:ae.boolean().optional(),href:ae.string().optional(),target:qU.optional(),changelog:wVe.optional()}).extend(Wd).extend(Gd);var inr=ae.enum_(["default","minimal"]);var onr=ae.enum_(["default","minimal"]);var snr=ae.enum_(["default","toolbar"]);var anr=ae.enum_(["default","toggle"]);var cnr=ae.enum_(["default","minimal"]);var unr=ae.enum_(["left","center"]);var Vms=ae.enum_(["default","bubble"]),Wgl=ae.object({style:Vms.optional(),alignment:unr.optional(),placement:OVe.optional()}),lnr=ae.undiscriminatedUnion([Vms,Wgl]);var pnr=ae.object({sidebar:cnr.optional(),body:Ytr.optional(),tabs:lnr.optional(),pageActions:ae.property("page-actions",snr.optional()),footerNav:ae.property("footer-nav",inr.optional()),languageSwitcher:ae.property("language-switcher",onr.optional()),productSwitcher:ae.property("product-switcher",anr.optional())});var qms=ae.object({instances:ae.list(lrr),title:ae.string().optional(),libraries:ae.record(PVe,krr).optional(),analytics:Qtr.optional(),announcement:phe.optional(),roles:ae.list(BOe).optional(),tabs:ae.record(WU,mhe).optional(),versions:ae.list(DVe).optional(),products:ae.list(tnr).optional(),landingPage:ae.property("landing-page",GU.optional()),navigation:dhe.optional(),navbarLinks:ae.property("navbar-links",ae.list(zrr).optional()),footerLinks:ae.property("footer-links",brr.optional()),pageActions:ae.property("page-actions",Yrr.optional()),experimental:yrr.optional(),defaultLanguage:ae.property("default-language",rnr.optional()),languages:ae.list(CVe).optional(),aiChat:ae.property("ai-chat",Fvt.optional()),aiSearch:ae.property("ai-search",Fvt.optional()),aiExamples:ae.property("ai-examples",Otr.optional()),metadata:jrr.optional(),redirects:ae.list(nnr).optional(),check:err.optional(),logo:Nrr.optional(),favicon:ae.string().optional(),backgroundImage:ae.property("background-image",Jtr.optional()),colors:rrr.optional(),typography:Arr.optional(),layout:Brr.optional(),settings:drr.optional(),theme:pnr.optional(),integrations:Err.optional(),css:irr.optional(),js:Crr.optional(),header:ae.string().optional(),footer:ae.string().optional()});var fnr=ae.object({folder:ae.string(),title:ae.string().optional(),titleSource:ae.property("title-source",xVe.optional()),slug:ae.string().optional(),icon:ae.string().optional(),hidden:ae.boolean().optional(),skipSlug:ae.property("skip-slug",ae.boolean().optional()),collapsed:h$.optional(),collapsible:ae.boolean().optional(),collapsedByDefault:ae.property("collapsed-by-default",ae.boolean().optional()),availability:yx.optional()}).extend(Wd).extend(Gd);var dnr=ae.object({library:PVe,title:ae.string().optional(),slug:ae.string().optional()}).extend(Wd).extend(Gd);var b$=ae.undiscriminatedUnion([GU,ae.lazyObject(()=>mnr),Vtr,dnr,IVe,Xtr,fnr]);var Gms=ae.object({tabs:ae.record(WU,mhe).optional(),landingPage:ae.property("landing-page",GU.optional()),navigation:dhe});var hnr=ae.object({displayName:ae.property("display-name",ae.string()),path:ae.string(),slug:ae.string().optional()}).extend(Wd).extend(Gd);var Wms=ae.undiscriminatedUnion([hnr,xtr]);var mnr=ae.object({section:ae.string(),path:ae.string().optional(),contents:ae.list(ae.lazy(()=>b$)),collapsed:h$.optional(),collapsible:ae.boolean().optional(),collapsedByDefault:ae.property("collapsed-by-default",ae.boolean().optional()),slug:ae.string().optional(),icon:ae.string().optional(),hidden:ae.boolean().optional(),skipSlug:ae.property("skip-slug",ae.boolean().optional()),availability:yx.optional()}).extend(Wd).extend(Gd);var $ms=ae.object({tabs:ae.record(WU,mhe).optional(),landingPage:ae.property("landing-page",GU.optional()),navigation:dhe});var Hms=require("fs/promises");var $gl=/\r?\n/;async function hhe({absolutePathToFernignore:e}){let t=(await(0,Hms.readFile)(e)).toString();return Kms(t)}function Kms(e){return[sT,...e.trim().split($gl).map(t=>{let r=t.indexOf("#");return r!==-1?t.slice(0,r).trim():t.trim()}).filter(t=>t.length>0)]}var In={};te(In,{API_ORIGIN_LOCATION_KEY:()=>Ous,API_SETTINGS_KEY:()=>Fus,ASYNC_API_LOCATION_KEY:()=>Pus,CoerceConstsTo:()=>uhs,DEFAULT_GROUP_GENERATORS_CONFIG_KEY:()=>ehe,DEFAULT_GROUP_NAME:()=>GEt,DefaultIntegerFormat:()=>lhs,ExampleStyle:()=>phs,FormParameterEncoding:()=>fhs,GenerationLanguage:()=>Jms,GithubCommitAndReleaseMode:()=>yhs,GithubLicenseType:()=>Ehs,GithubSelfhostedMode:()=>bhs,Language:()=>dhs,MessageNamingSettingsSchema:()=>mhs,ModelProvider:()=>Zms,OPENAPI_LOCATION_KEY:()=>Dus,OPENAPI_OVERRIDES_LOCATION_KEY:()=>Rus,PathParameterOrder:()=>hhs,RemoveDiscriminantsFromSchemas:()=>ghs,UnionSettingsSchema:()=>Ahs,ai:()=>Cui,fernDefinition:()=>_ui,generators:()=>Sui,getPackageName:()=>Yms,group:()=>Bui,isApiConfigurationV2Schema:()=>Yhs,isAsyncApiSpecSchema:()=>Xhs,isConjureSchema:()=>Zhs,isGraphQLSpecSchema:()=>egs,isNamespacedApiConfiguration:()=>tgs,isOpenApiSpecSchema:()=>rgs,isOpenRpcSpecSchema:()=>ngs,isProtoSpecSchema:()=>igs,isRawProtobufAPIDefinitionSchema:()=>Xms,license:()=>Tui,replay:()=>vhs,reviewers:()=>Ihs,serialization:()=>Yui});var Jms={TYPESCRIPT:"typescript",JAVA:"java",PYTHON:"python",GO:"go",RUBY:"ruby",CSHARP:"csharp",SWIFT:"swift",PHP:"php",RUST:"rust"};function Yms({generatorInvocation:e}){return e.language==="go"?Hgl(e):e.outputMode._visit({downloadFiles:()=>{},github:t=>t.publishInfo?._visit({maven:r=>r.coordinate,npm:r=>r.packageName,pypi:r=>r.packageName,postman:()=>{},rubygems:r=>r.packageName,nuget:r=>r.packageName,crates:r=>r.packageName,_other:()=>{}}),githubV2:t=>t.publishInfo?._visit({maven:r=>r.coordinate,npm:r=>r.packageName,pypi:r=>r.packageName,postman:()=>{},rubygems:r=>r.packageName,nuget:r=>r.packageName,crates:r=>r.packageName,_other:()=>{}}),publish:()=>{},publishV2:()=>{},_other:()=>{}})}function Hgl(e){return e.outputMode._visit({downloadFiles:()=>{},github:t=>`github.com/${t.owner}/${t.repo}`,githubV2:t=>`github.com/${t.owner}/${t.repo}`,publish:()=>{},publishV2:()=>{},_other:()=>{}})}function Xms(e){return typeof e!="string"&&"proto"in e}var Cui={};te(Cui,{ModelProvider:()=>Zms});var Zms={Openai:"openai",Anthropic:"anthropic",Bedrock:"bedrock"};var _ui={};te(_ui,{AvailabilityStatusSchema:()=>ths,auth:()=>ehs,availability:()=>xui,commons:()=>rhs,encoding:()=>nhs,environments:()=>ihs,file:()=>ohs,service:()=>shs,types:()=>ahs,validation:()=>chs});var ehs={};var xui={};te(xui,{AvailabilityStatusSchema:()=>ths});var ths={InDevelopment:"in-development",PreRelease:"pre-release",Deprecated:"deprecated",GenerallyAvailable:"generally-available"};var rhs={};var nhs={};var ihs={};var ohs={};var shs={};var ahs={};var chs={};var Sui={};te(Sui,{CoerceConstsTo:()=>uhs,DefaultIntegerFormat:()=>lhs,ExampleStyle:()=>phs,FormParameterEncoding:()=>fhs,Language:()=>dhs,MessageNamingSettingsSchema:()=>mhs,PathParameterOrder:()=>hhs,RemoveDiscriminantsFromSchemas:()=>ghs,UnionSettingsSchema:()=>Ahs});var uhs={Literals:"literals",Enums:"enums",EnumsCoerceableToLiterals:"enums-coerceable-to-literals"};var lhs={Int32:"int32",Int64:"int64",Uint32:"uint32",Uint64:"uint64"};var phs={Minimal:"minimal",Comprehensive:"comprehensive"};var fhs={Form:"form",Json:"json"};var dhs={Java:"java",Python:"python",Go:"go",Ruby:"ruby",Csharp:"csharp",Typescript:"typescript",Php:"php",Rust:"rust",Swift:"swift"};var mhs={V1:"v1",V2:"v2"};var hhs={UrlOrder:"url-order",SpecOrder:"spec-order"};var ghs={Always:"always",Never:"never"};var Ahs={V1:"v1"};var Bui={};te(Bui,{GithubCommitAndReleaseMode:()=>yhs,GithubSelfhostedMode:()=>bhs});var yhs={Commit:"commit",Release:"release"};var bhs={PullRequest:"pull-request",Push:"push"};var Tui={};te(Tui,{GithubLicenseType:()=>Ehs});var Ehs={Mit:"MIT",Apache:"Apache-2.0"};var vhs={};var Ihs={};var Yui={};te(Yui,{AiServicesSchema:()=>Inr,ApiConfigurationSchema:()=>Sir,ApiConfigurationSchemaInternal:()=>JVe,ApiConfigurationV2Schema:()=>xir,ApiConfigurationV2SettingsSchema:()=>ZVe,ApiConfigurationV2SpecsSchema:()=>e6e,ApiDefinitionList:()=>lir,ApiDefinitionPathSchema:()=>bhe,ApiDefinitionSchema:()=>uir,ApiDefinitionSettingsSchema:()=>WVe,ApiDefinitionWithOverridesSchema:()=>$Ve,AsyncApiSettingsSchema:()=>XVe,AsyncApiSpecSchema:()=>bir,BaseApiSettingsSchema:()=>YVe,CoerceConstsTo:()=>pir,ConjureSchema:()=>yir,CratesOutputLocationSchema:()=>Pir,DefaultIntegerFormat:()=>fir,ExampleStyle:()=>Bir,FormParameterEncoding:()=>dir,GeneratorApiSettingsSchema:()=>Oir,GeneratorGroupSchema:()=>Zir,GeneratorInvocationSchema:()=>Xir,GeneratorOutputSchema:()=>Uir,GeneratorPublishMetadataSchema:()=>zvt,GeneratorSnippetsSchema:()=>qir,GeneratorsConfigurationSchema:()=>Jhs,GeneratorsOpenApiObjectSchema:()=>tor,GeneratorsOpenApiSchema:()=>ror,GithubCommitAndReleaseMode:()=>Gir,GithubCommitAndReleaseSchema:()=>Wir,GithubConfigurationSchema:()=>Yir,GithubLicenseCustomSchema:()=>zir,GithubLicenseSchema:()=>HU,GithubLicenseType:()=>Vir,GithubPullRequestSchema:()=>$ir,GithubPushSchema:()=>Hir,GithubSelfhostedMode:()=>Kir,GithubSelfhostedSchema:()=>Jir,GraphQlSpecSchema:()=>Eir,Language:()=>nor,LocalFileSystemOutputLocationSchema:()=>Dir,MavenOutputLocationSchema:()=>Fir,MavenOutputSignatureSchema:()=>Rir,MessageNamingSettingsSchema:()=>VVe,ModelName:()=>Enr,ModelProvider:()=>vnr,NamespacedApiConfigurationSchema:()=>_ir,NpmOutputLocationSchema:()=>kir,NugetOutputLocationSchema:()=>Nir,OpenApiExampleGenerationSchema:()=>mir,OpenApiFilterSchema:()=>hir,OpenApiSettingsSchema:()=>Ehe,OpenApiSpecSchema:()=>vir,OpenRpcSpecSchema:()=>Iir,OutputMetadataAuthor:()=>Tir,OutputMetadataSchema:()=>vhe,OverridesSchema:()=>$U,PathParameterOrder:()=>qVe,PostmanOutputLocationSchema:()=>Qir,ProtobufApiDefinitionSchema:()=>KVe,ProtobufDefinitionSchema:()=>HVe,ProtobufSpecSchema:()=>wir,PypiOutputLocationSchema:()=>Mir,PypiOutputMetadataSchema:()=>jir,ReadmeCustomSectionSchema:()=>ior,ReadmeEndpointObjectSchema:()=>oor,ReadmeEndpointSchema:()=>Vvt,ReadmeSchema:()=>sor,RemoveDiscriminantsFromSchemas:()=>GVe,ReplayConfigSchema:()=>eor,RequestOrResponseExampleGenerationSchema:()=>Lvt,ResolveAliases:()=>Air,ResolveAliasesSchema:()=>gir,ReviewerSchema:()=>Uvt,ReviewersSchema:()=>Ihe,RubyGemsOutputLocationSchema:()=>Lir,SpecSchema:()=>Cir,UnionSettingsSchema:()=>cir,WhitelabelConfigurationSchema:()=>cor,WhitelabelGithubConfigurationSchema:()=>aor,ai:()=>kui,fernDefinition:()=>Gui,generators:()=>Wui,group:()=>$ui,license:()=>Hui,replay:()=>Kui,reviewers:()=>Jui});var kui={};te(kui,{AiServicesSchema:()=>Inr,ModelName:()=>Enr,ModelProvider:()=>vnr});var we={};te(we,{JsonError:()=>FVe,ParseError:()=>kVe,any:()=>Nhs,bigint:()=>Chs,boolean:()=>Qhs,booleanLiteral:()=>Fhs,date:()=>xhs,discriminant:()=>$hs,enum_:()=>Anr,getObjectLikeUtils:()=>iq,getObjectUtils:()=>TOe,getSchemaUtils:()=>$d,isProperty:()=>Lse,lazy:()=>_hs,lazyObject:()=>Dhs,list:()=>bnr,never:()=>jhs,number:()=>Mhs,object:()=>ynr,objectWithoutOptionalProperties:()=>Phs,optional:()=>Oui,property:()=>Bhs,record:()=>Vhs,set:()=>qhs,string:()=>Lhs,stringLiteral:()=>khs,transform:()=>Pui,undiscriminatedUnion:()=>Whs,union:()=>Khs,unknown:()=>Uhs,withParsedProperties:()=>Fui});var wu={BIGINT:"bigint",DATE:"date",ENUM:"enum",LIST:"list",STRING_LITERAL:"stringLiteral",BOOLEAN_LITERAL:"booleanLiteral",OBJECT:"object",ANY:"any",BOOLEAN:"boolean",NUMBER:"number",STRING:"string",UNKNOWN:"unknown",NEVER:"never",RECORD:"record",SET:"set",UNION:"union",UNDISCRIMINATED_UNION:"undiscriminatedUnion",NULLABLE:"nullable",OPTIONAL:"optional",OPTIONAL_NULLABLE:"optionalNullable"};function hd(e,t){return`Expected ${t}. Received ${Kgl(e)}.`}function Kgl(e){if(Array.isArray(e))return"list";if(e===null)return"null";if(e instanceof BigInt)return"BigInt";switch(typeof e){case"string":return`"${e}"`;case"bigint":case"number":case"boolean":case"undefined":return`${e}`}return typeof e}function Ex(e){return{...e,json:whs(e.json),parse:whs(e.parse)}}function whs(e){return(t,r)=>{let n=e(t,r),{skipValidation:i=!1}=r??{};return!n.ok&&i?(console.warn(["Failed to validate.",...n.errors.map(o=>" - "+(o.path.length>0?`${o.path.join(".")}: ${o.message}`:o.message))].join(`
1462
1462
  `)),{ok:!0,value:t}):n}}function gnr(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var FVe=class e extends Error{errors;constructor(t){super(t.map(gnr).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var kVe=class e extends Error{errors;constructor(t){super(t.map(gnr).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function $d(e){return{nullable:()=>Jgl(e),optional:()=>Oui(e),optionalNullable:()=>Ygl(e),transform:t=>Pui(e,t),parseOrThrow:(t,r)=>{let n=e.parse(t,r);if(n.ok)return n.value;throw new kVe(n.errors)},jsonOrThrow:(t,r)=>{let n=e.json(t,r);if(n.ok)return n.value;throw new FVe(n.errors)}}}function Jgl(e){let t={parse:(r,n)=>r==null?{ok:!0,value:null}:e.parse(r,n),json:(r,n)=>r==null?{ok:!0,value:null}:e.json(r,n),getType:()=>wu.NULLABLE};return{...t,...$d(t)}}function Oui(e){let t={parse:(r,n)=>r==null?{ok:!0,value:void 0}:e.parse(r,n),json:(r,n)=>n?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:e.json(r,n),getType:()=>wu.OPTIONAL};return{...t,...$d(t)}}function Ygl(e){let t={parse:(r,n)=>r===void 0?{ok:!0,value:void 0}:r===null?{ok:!0,value:null}:e.parse(r,n),json:(r,n)=>r===void 0?{ok:!0,value:void 0}:r===null?{ok:!0,value:null}:e.json(r,n),getType:()=>wu.OPTIONAL_NULLABLE};return{...t,...$d(t)}}function Pui(e,t){let r={parse:(n,i)=>{let o=e.parse(n,i);return o.ok?{ok:!0,value:t.transform(o.value)}:o},json:(n,i)=>{let o=t.untransform(n);return e.json(o,i)},getType:()=>e.getType()};return{...r,...$d(r)}}function Chs(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t=="bigint"?{ok:!0,value:t}:typeof t=="number"?{ok:!0,value:BigInt(t)}:{ok:!1,errors:[{path:r,message:hd(t,"bigint | number")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="bigint"?{ok:!1,errors:[{path:r,message:hd(t,"bigint")}]}:{ok:!0,value:t},getType:()=>wu.BIGINT};return{...Ex(e),...$d(e)}}var Xgl=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function xhs(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:hd(t,"string")}]}:Xgl.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:hd(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:hd(t,"Date object")}]},getType:()=>wu.DATE};return{...Ex(e),...$d(e)}}function vx(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{...Ex(r),...$d(r)}}}function Anr(e){let t=new Set(e);return vx(wu.ENUM,(n,{allowUnrecognizedEnumValues:i,breadcrumbsPrefix:o=[]}={})=>typeof n!="string"?{ok:!1,errors:[{path:o,message:hd(n,"string")}]}:!t.has(n)&&!i?{ok:!1,errors:[{path:o,message:hd(n,"enum")}]}:{ok:!0,value:n})()}function _hs(e){let t=Dui(e);return{...t,...$d(t)}}function Dui(e){return{parse:(t,r)=>NVe(e).parse(t,r),json:(t,r)=>NVe(e).json(t,r),getType:()=>NVe(e).getType()}}function NVe(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function Rui(e){return Object.entries(e)}function jvt(e,t){let r=new Set(t);return Object.entries(e).reduce((n,[i,o])=>(r.has(i)&&(n[i]=o),n),{})}function Mse(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===null?!0:Object.getPrototypeOf(t)===null}function Mvt(e){return Object.keys(e)}function Shs(e,t){let r=[],n=[];for(let i of e)t(i)?r.push(i):n.push(i);return[r,n]}var Zgl=Object.prototype.hasOwnProperty;function iq(e){return{withParsedProperties:t=>Fui(e,t)}}function Fui(e,t){let r={parse:(n,i)=>{let o=e.parse(n,i);if(!o.ok)return o;let s={};for(let a in t)if(Zgl.call(t,a)){let c=t[a];s[a]=typeof c=="function"?c(o.value):c}return{ok:!0,value:{...o.value,...s}}},json:(n,i)=>{if(!Mse(n))return{ok:!1,errors:[{path:i?.breadcrumbsPrefix??[],message:hd(n,"object")}]};let o=new Set(Object.keys(t)),s=jvt(n,Object.keys(n).filter(a=>!o.has(a)));return e.json(s,i)},getType:()=>e.getType()};return{...r,...$d(r),...iq(r)}}function Bhs(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function Lse(e){return e.isProperty}var eAl=Object.prototype.hasOwnProperty;function ynr(e){let t;function r(){if(t==null){t={};for(let[d,f]of Rui(e)){let m=Lse(f)?f.rawKey:d,h=Lse(f)?f.valueSchema:f;t[m]={rawKey:m,parsedKey:d,valueSchema:h}}}return t}let n,i,o,s;function a(){if(n==null){n=[],i=[];for(let[d,f]of Rui(e)){let m=Lse(f)?f.rawKey:d,h=Lse(f)?f.valueSchema:f;tAl(h)&&(n.push(m),i.push(d))}o=new Set(n),s=new Set(i)}return n}function c(){return i==null&&a(),i}function u(){return o==null&&a(),o}function l(){return s==null&&a(),s}let p={_getRawProperties:()=>Object.entries(e).map(([d,f])=>Lse(f)?f.rawKey:d),_getParsedProperties:()=>Mvt(e),parse:(d,f)=>{let m=f?.breadcrumbsPrefix??[];return Ths({value:d,requiredKeys:a(),requiredKeysSet:u(),getProperty:h=>{let g=r()[h];if(g!=null)return{transformedKey:g.parsedKey,transform:A=>{let b=[...m,h];return g.valueSchema.parse(A,{...f,breadcrumbsPrefix:b})}}},unrecognizedObjectKeys:f?.unrecognizedObjectKeys,skipValidation:f?.skipValidation,breadcrumbsPrefix:m,omitUndefined:f?.omitUndefined})},json:(d,f)=>{let m=f?.breadcrumbsPrefix??[];return Ths({value:d,requiredKeys:c(),requiredKeysSet:l(),getProperty:h=>{let g=e[h];if(g!=null)return Lse(g)?{transformedKey:g.rawKey,transform:A=>{let b=[...m,h];return g.valueSchema.json(A,{...f,breadcrumbsPrefix:b})}}:{transformedKey:h,transform:A=>{let b=[...m,h];return g.json(A,{...f,breadcrumbsPrefix:b})}}},unrecognizedObjectKeys:f?.unrecognizedObjectKeys,skipValidation:f?.skipValidation,breadcrumbsPrefix:m,omitUndefined:f?.omitUndefined})},getType:()=>wu.OBJECT};return{...Ex(p),...$d(p),...iq(p),...TOe(p)}}function Ths({value:e,requiredKeys:t,requiredKeysSet:r,getProperty:n,unrecognizedObjectKeys:i="fail",skipValidation:o=!1,breadcrumbsPrefix:s=[]}){if(!Mse(e))return{ok:!1,errors:[{path:s,message:hd(e,"object")}]};let a=t.length,c=[],u={};for(let l in e){if(!eAl.call(e,l))continue;let p=e[l],d=n(l);if(d!=null){a>0&&r.has(l)&&a--;let f=d.transform(p);f.ok?u[d.transformedKey]=f.value:(u[l]=p,c.push(...f.errors))}else switch(i){case"fail":c.push({path:[...s,l],message:`Unexpected key "${l}"`});break;case"strip":break;case"passthrough":u[l]=p;break}}if(a>0)for(let l of t)l in e||c.push({path:s,message:`Missing required key "${l}"`});return c.length===0||o?{ok:!0,value:u}:{ok:!1,errors:c}}function TOe(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(n,i)=>Ohs({extensionKeys:t._getRawProperties(),value:n,transformBase:o=>e.parse(o,i),transformExtension:o=>t.parse(o,i),breadcrumbsPrefix:i?.breadcrumbsPrefix}),json:(n,i)=>Ohs({extensionKeys:t._getParsedProperties(),value:n,transformBase:o=>e.json(o,i),transformExtension:o=>t.json(o,i),breadcrumbsPrefix:i?.breadcrumbsPrefix}),getType:()=>wu.OBJECT};return{...r,...$d(r),...iq(r),...TOe(r)}},passthrough:()=>{let t=new Set(e._getRawProperties()),r=new Set(e._getParsedProperties()),n={_getParsedProperties:()=>e._getParsedProperties(),_getRawProperties:()=>e._getRawProperties(),parse:(i,o)=>{let s=e.parse(i,{...o,unrecognizedObjectKeys:"passthrough"});if(!s.ok)return s;let a={};if(typeof i=="object"&&i!=null)for(let[c,u]of Object.entries(i))t.has(c)||(a[c]=u);return{ok:!0,value:{...a,...s.value}}},json:(i,o)=>{let s=e.json(i,{...o,unrecognizedObjectKeys:"passthrough"});if(!s.ok)return s;let a={};if(typeof i=="object"&&i!=null)for(let[c,u]of Object.entries(i))r.has(c)||(a[c]=u);return{ok:!0,value:{...a,...s.value}}},getType:()=>wu.OBJECT};return{...n,...$d(n),...iq(n),...TOe(n)}}}}function Ohs({extensionKeys:e,value:t,transformBase:r,transformExtension:n,breadcrumbsPrefix:i=[]}){if(!Mse(t))return{ok:!1,errors:[{path:i,message:hd(t,"object")}]};let o=new Set(e),[s,a]=Shs(Mvt(t),l=>o.has(l)),c=r(jvt(t,a)),u=n(jvt(t,s));return c.ok&&u.ok?{ok:!0,value:{...c.value,...u.value}}:{ok:!1,errors:[...c.ok?[]:c.errors,...u.ok?[]:u.errors]}}function tAl(e){return!rAl(e)}function rAl(e){switch(e.getType()){case wu.ANY:case wu.UNKNOWN:case wu.OPTIONAL:case wu.OPTIONAL_NULLABLE:return!0;default:return!1}}function Phs(e){return ynr(e)}function Dhs(e){let t={...Dui(e),_getRawProperties:()=>NVe(e)._getRawProperties(),_getParsedProperties:()=>NVe(e)._getParsedProperties()};return{...t,...$d(t),...iq(t),...TOe(t)}}function bnr(e){let t={parse:(r,n)=>Rhs(r,(i,o)=>e.parse(i,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`[${o}]`]})),json:(r,n)=>Rhs(r,(i,o)=>e.json(i,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`[${o}]`]})),getType:()=>wu.LIST};return{...Ex(t),...$d(t)}}function Rhs(e,t){if(!Array.isArray(e))return{ok:!1,errors:[{message:hd(e,"list"),path:[]}]};let r=[],n=[];for(let i=0;i<e.length;i++){let o=t(e[i],i);o.ok?r.push(o.value):n.push(...o.errors)}return n.length===0?{ok:!0,value:r}:{ok:!1,errors:n}}function Fhs(e){return vx(wu.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:n=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:n,message:hd(r,`${e.toString()}`)}]})()}function khs(e){return vx(wu.STRING_LITERAL,(r,{breadcrumbsPrefix:n=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:n,message:hd(r,`"${e}"`)}]})()}var Nhs=vx(wu.ANY,e=>({ok:!0,value:e}));var Qhs=vx(wu.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:hd(e,"boolean")}]});var jhs=vx(wu.NEVER,(e,{breadcrumbsPrefix:t=[]}={})=>({ok:!1,errors:[{path:t,message:"Expected never"}]}));var Mhs=vx(wu.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:hd(e,"number")}]});var Lhs=vx(wu.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:hd(e,"string")}]});var Uhs=vx(wu.UNKNOWN,e=>({ok:!0,value:e}));var nAl=Object.prototype.hasOwnProperty;function Vhs(e,t){let r={parse:(n,i)=>zhs({value:n,isKeyNumeric:e.getType()===wu.NUMBER,transformKey:o=>e.parse(o,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${o} (key)`]}),transformValue:(o,s)=>t.parse(o,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${s}`]}),breadcrumbsPrefix:i?.breadcrumbsPrefix}),json:(n,i)=>zhs({value:n,isKeyNumeric:e.getType()===wu.NUMBER,transformKey:o=>e.json(o,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${o} (key)`]}),transformValue:(o,s)=>t.json(o,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${s}`]}),breadcrumbsPrefix:i?.breadcrumbsPrefix}),getType:()=>wu.RECORD};return{...Ex(r),...$d(r)}}function zhs({value:e,isKeyNumeric:t,transformKey:r,transformValue:n,breadcrumbsPrefix:i=[]}){if(!Mse(e))return{ok:!1,errors:[{path:i,message:hd(e,"object")}]};let o={},s=[];for(let a in e){if(!nAl.call(e,a))continue;let c=e[a];if(c===void 0)continue;let u=a;if(t){let d=a.length>0?Number(a):NaN;Number.isNaN(d)||(u=d)}let l=r(u),p=n(c,u);l.ok&&p.ok?o[l.value]=p.value:(l.ok||s.push(...l.errors),p.ok||s.push(...p.errors))}return s.length===0?{ok:!0,value:o}:{ok:!1,errors:s}}function qhs(e){let t=bnr(e),r={parse:(n,i)=>{let o=t.parse(n,i);return o.ok?{ok:!0,value:new Set(o.value)}:o},json:(n,i)=>n instanceof Set?t.json([...n],i):{ok:!1,errors:[{path:i?.breadcrumbsPrefix??[],message:hd(n,"Set")}]},getType:()=>wu.SET};return{...Ex(r),...$d(r)}}function Whs(e){let t={parse:(r,n)=>Ghs((i,o)=>i.parse(r,o),e,n),json:(r,n)=>Ghs((i,o)=>i.json(r,o),e,n),getType:()=>wu.UNDISCRIMINATED_UNION};return{...Ex(t),...$d(t)}}function Ghs(e,t,r){let n=[];for(let[i,o]of t.entries()){let s=e(o,{...r,skipValidation:!1});if(s.ok)return s;for(let a of s.errors)n.push({path:a.path,message:`[Variant ${i}] ${a.message}`})}return{ok:!1,errors:n}}function $hs(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}var iAl=Object.prototype.hasOwnProperty;function Khs(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,n=typeof e=="string"?e:e.parsedDiscriminant,i=Anr(Mvt(t)),o={parse:(s,a)=>Hhs({value:s,discriminant:r,transformedDiscriminant:n,transformDiscriminantValue:c=>i.parse(c,{allowUnrecognizedEnumValues:a?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...a?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:c=>t[c],allowUnrecognizedUnionMembers:a?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(c,u)=>u.parse(c,a),breadcrumbsPrefix:a?.breadcrumbsPrefix}),json:(s,a)=>Hhs({value:s,discriminant:n,transformedDiscriminant:r,transformDiscriminantValue:c=>i.json(c,{allowUnrecognizedEnumValues:a?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...a?.breadcrumbsPrefix??[],n]}),getAdditionalPropertiesSchema:c=>t[c],allowUnrecognizedUnionMembers:a?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(c,u)=>u.json(c,a),breadcrumbsPrefix:a?.breadcrumbsPrefix}),getType:()=>wu.UNION};return{...Ex(o),...$d(o),...iq(o)}}function Hhs({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:n,getAdditionalPropertiesSchema:i,allowUnrecognizedUnionMembers:o=!1,transformAdditionalProperties:s,breadcrumbsPrefix:a=[]}){if(!Mse(e))return{ok:!1,errors:[{path:a,message:hd(e,"object")}]};let c=e[t],u={};for(let f in e)iAl.call(e,f)&&f!==t&&(u[f]=e[f]);if(c==null)return{ok:!1,errors:[{path:a,message:`Missing discriminant ("${t}")`}]};let l=n(c);if(!l.ok)return{ok:!1,errors:l.errors};let p=i(l.value);if(p==null)return o?{ok:!0,value:{[r]:l.value,...u}}:{ok:!1,errors:[{path:[...a,t],message:"Unexpected discriminant value"}]};let d=s(u,p);return d.ok?{ok:!0,value:{[r]:c,...d.value}}:d}var Enr=we.string();var vnr=we.enum_(["openai","anthropic","bedrock"]);var Inr=we.object({provider:vnr,model:Enr});var Gui={};te(Gui,{AnyAuthItem:()=>wnr,AnyAuthSchemesSchema:()=>Cnr,ApiAuthSchema:()=>jVe,AuthSchemeDeclarationSchema:()=>Ahe,AuthSchemeReferenceSchema:()=>QVe,AuthScope:()=>knr,AuthVariable:()=>OOe,AvailabilitySchema:()=>Vnr,AvailabilityStatusSchema:()=>LVe,AvailabilityUnionSchema:()=>qnr,BaseTypeReferenceSchema:()=>nir,BasicAuthSchemeSchema:()=>Snr,BearerAuthSchemeSchema:()=>Rnr,EncodingSchema:()=>$nr,EndpointSecuritySchema:()=>_nr,EndpointSecuritySchemaDetails:()=>xnr,EnvironmentSchema:()=>Jnr,HeaderAuthSchemeSchema:()=>Fnr,HttpHeaderSchema:()=>zVe,InferredAuthenticatedRequestHeader:()=>Bnr,InferredBearerAuthSchema:()=>Pnr,InferredGetTokenEndpointSchema:()=>Onr,InferredGetTokenEndpointSchemaObject:()=>Tnr,ListValidationSchema:()=>Xnr,MapValidationSchema:()=>Znr,MultipleBaseUrlsEnvironmentSchema:()=>Hnr,NumberValidationSchema:()=>eir,OAuthAccessTokenRequestPropertiesSchema:()=>Nnr,OAuthAccessTokenResponsePropertiesSchema:()=>Qnr,OAuthGetTokenEndpointSchema:()=>jnr,OAuthRefreshTokenEndpointSchema:()=>Unr,OAuthRefreshTokenRequestPropertiesSchema:()=>Mnr,OAuthRefreshTokenResponsePropertiesSchema:()=>Lnr,OAuthSchemeSchema:()=>znr,ProtobufTypeSchema:()=>Wnr,ServerVariableSchema:()=>UVe,SingleBaseUrlEnvironmentSchema:()=>Knr,StringValidationSchema:()=>tir,TokenBearerAuthSchema:()=>Dnr,TypeReferenceDeclarationWithEnvOverride:()=>sir,TypeReferenceDeclarationWithEnvOverrideSchema:()=>oir,TypeReferenceDeclarationWithName:()=>iir,ValidationSchema:()=>rir,WithAudiences:()=>yhe,WithAvailability:()=>Gnr,WithDocsSchema:()=>sb,WithEnvironmentVariable:()=>MVe,WithEnvironmentsSchema:()=>Ynr,WithHeadersSchema:()=>air,WithName:()=>ghe,auth:()=>Nui,availability:()=>Qui,commons:()=>jui,encoding:()=>Mui,environments:()=>Lui,file:()=>Uui,service:()=>zui,types:()=>Vui,validation:()=>qui});var Nui={};te(Nui,{AnyAuthItem:()=>wnr,AnyAuthSchemesSchema:()=>Cnr,ApiAuthSchema:()=>jVe,AuthSchemeDeclarationSchema:()=>Ahe,AuthSchemeReferenceSchema:()=>QVe,AuthScope:()=>knr,AuthVariable:()=>OOe,BasicAuthSchemeSchema:()=>Snr,BearerAuthSchemeSchema:()=>Rnr,EndpointSecuritySchema:()=>_nr,EndpointSecuritySchemaDetails:()=>xnr,HeaderAuthSchemeSchema:()=>Fnr,InferredAuthenticatedRequestHeader:()=>Bnr,InferredBearerAuthSchema:()=>Pnr,InferredGetTokenEndpointSchema:()=>Onr,InferredGetTokenEndpointSchemaObject:()=>Tnr,OAuthAccessTokenRequestPropertiesSchema:()=>Nnr,OAuthAccessTokenResponsePropertiesSchema:()=>Qnr,OAuthGetTokenEndpointSchema:()=>jnr,OAuthRefreshTokenEndpointSchema:()=>Unr,OAuthRefreshTokenRequestPropertiesSchema:()=>Mnr,OAuthRefreshTokenResponsePropertiesSchema:()=>Lnr,OAuthSchemeSchema:()=>znr,TokenBearerAuthSchema:()=>Dnr,WithEnvironmentVariable:()=>MVe});var sb=we.object({docs:we.string().optional()});var QVe=we.object({scheme:we.string()}).extend(sb);var wnr=we.undiscriminatedUnion([we.string(),QVe]);var Cnr=we.object({any:we.list(wnr)}).extend(sb);var xnr=we.object({});var _nr=we.object({"endpoint-security":xnr}).extend(sb);var jVe=we.undiscriminatedUnion([we.string(),QVe,Cnr,_nr]);var ghe=we.object({name:we.string().optional()});var MVe=we.object({env:we.string().optional()});var OOe=we.object({omit:we.boolean().optional()}).extend(MVe).extend(ghe);var Snr=we.object({scheme:we.stringLiteral("basic"),username:OOe.optional(),password:OOe.optional()}).extend(sb);var Bnr=we.object({"response-property":we.string(),"header-name":we.string(),"value-prefix":we.string().optional()});var Tnr=we.object({endpoint:we.string(),"expiry-response-property":we.string().optional(),"authenticated-request-headers":we.list(Bnr).optional()});var Onr=we.undiscriminatedUnion([we.string(),Tnr]);var Pnr=we.object({scheme:we.stringLiteral("bearer"),"get-token":Onr}).extend(sb);var Dnr=we.object({scheme:we.stringLiteral("bearer"),token:OOe.optional()}).extend(sb);var Rnr=we.undiscriminatedUnion([Dnr,Pnr]);var Fnr=we.object({header:we.string(),type:we.string().optional(),prefix:we.string().optional()}).extend(MVe).extend(ghe).extend(sb);var knr=we.string();var Nnr=we.object({"client-id":we.string().optional(),"client-secret":we.string().optional(),scopes:we.string().optional()});var Qnr=we.object({"access-token":we.string().optional(),"expires-in":we.string().optional(),"refresh-token":we.string().optional()});var jnr=we.object({endpoint:we.string(),"request-properties":Nnr.optional(),"response-properties":Qnr.optional()});var Mnr=we.object({"refresh-token":we.string()});var Lnr=we.object({"access-token":we.string().optional(),"expires-in":we.string().optional(),"refresh-token":we.string().optional()});var Unr=we.object({endpoint:we.string(),"request-properties":Mnr.optional(),"response-properties":Lnr.optional()});var znr=we.object({scheme:we.stringLiteral("oauth"),type:we.stringLiteral("client-credentials"),scopes:we.list(knr).optional(),"client-id-env":we.string().optional(),"client-secret-env":we.string().optional(),"token-prefix":we.string().optional(),"token-header":we.string().optional(),"get-token":jnr,"refresh-token":Unr.optional()}).extend(sb);var Ahe=we.undiscriminatedUnion([znr,Fnr,Snr,Rnr]);var Qui={};te(Qui,{AvailabilitySchema:()=>Vnr,AvailabilityStatusSchema:()=>LVe,AvailabilityUnionSchema:()=>qnr});var LVe=we.enum_(["in-development","pre-release","deprecated","generally-available"]);var Vnr=we.object({status:LVe,message:we.string().optional()});var qnr=we.undiscriminatedUnion([LVe,Vnr]);var jui={};te(jui,{WithAudiences:()=>yhe,WithAvailability:()=>Gnr,WithDocsSchema:()=>sb,WithName:()=>ghe});var yhe=we.object({audiences:we.list(we.string()).optional()});var Gnr=we.object({availability:qnr.optional()});var Mui={};te(Mui,{EncodingSchema:()=>$nr,ProtobufTypeSchema:()=>Wnr});var Wnr=we.object({type:we.string()});var $nr=we.object({proto:Wnr.optional()});var Lui={};te(Lui,{EnvironmentSchema:()=>Jnr,MultipleBaseUrlsEnvironmentSchema:()=>Hnr,ServerVariableSchema:()=>UVe,SingleBaseUrlEnvironmentSchema:()=>Knr,WithEnvironmentsSchema:()=>Ynr});var UVe=we.object({id:we.string(),default:we.string().optional(),values:we.list(we.string()).optional()});var Hnr=we.object({urls:we.record(we.string(),we.string()),"url-templates":we.record(we.string(),we.string()).optional(),"default-urls":we.record(we.string(),we.string()).optional(),variables:we.record(we.string(),we.list(UVe)).optional()}).extend(yhe).extend(sb);var Knr=we.object({url:we.string(),"default-url":we.string().optional(),"url-template":we.string().optional(),variables:we.list(UVe).optional()}).extend(yhe).extend(sb);var Jnr=we.undiscriminatedUnion([we.string(),Knr,Hnr]);var Ynr=we.object({"default-url":we.string().optional(),"default-environment":we.string().optional(),environments:we.record(we.string(),Jnr).optional()});var Uui={};te(Uui,{WithHeadersSchema:()=>air});var Xnr=we.object({minItems:we.number().optional(),maxItems:we.number().optional()});var Znr=we.object({minProperties:we.number().optional(),maxProperties:we.number().optional()});var eir=we.object({min:we.number().optional(),max:we.number().optional(),exclusiveMin:we.boolean().optional(),exclusiveMax:we.boolean().optional(),multipleOf:we.number().optional()});var tir=we.object({minLength:we.number().optional(),maxLength:we.number().optional(),pattern:we.string().optional(),format:we.string().optional()});var rir=we.undiscriminatedUnion([tir,eir,Xnr,Znr]);var nir=we.object({default:we.unknown().optional(),encoding:$nr.optional(),validation:rir.optional()}).extend(sb).extend(Gnr);var iir=we.object({type:we.string()}).extend(nir).extend(ghe).extend(yhe);var oir=we.object({env:we.string().optional()}).extend(iir);var sir=we.undiscriminatedUnion([we.string(),oir]);var zVe=sir;var air=we.object({headers:we.record(we.string(),zVe).optional()});var zui={};te(zui,{HttpHeaderSchema:()=>zVe,TypeReferenceDeclarationWithEnvOverride:()=>sir,TypeReferenceDeclarationWithEnvOverrideSchema:()=>oir});var Vui={};te(Vui,{BaseTypeReferenceSchema:()=>nir,TypeReferenceDeclarationWithName:()=>iir});var qui={};te(qui,{ListValidationSchema:()=>Xnr,MapValidationSchema:()=>Znr,NumberValidationSchema:()=>eir,StringValidationSchema:()=>tir,ValidationSchema:()=>rir});var Wui={};te(Wui,{ApiConfigurationSchema:()=>Sir,ApiConfigurationSchemaInternal:()=>JVe,ApiConfigurationV2Schema:()=>xir,ApiConfigurationV2SettingsSchema:()=>ZVe,ApiConfigurationV2SpecsSchema:()=>e6e,ApiDefinitionList:()=>lir,ApiDefinitionPathSchema:()=>bhe,ApiDefinitionSchema:()=>uir,ApiDefinitionSettingsSchema:()=>WVe,ApiDefinitionWithOverridesSchema:()=>$Ve,AsyncApiSettingsSchema:()=>XVe,AsyncApiSpecSchema:()=>bir,BaseApiSettingsSchema:()=>YVe,CoerceConstsTo:()=>pir,ConjureSchema:()=>yir,DefaultIntegerFormat:()=>fir,ExampleStyle:()=>Bir,FormParameterEncoding:()=>dir,GeneratorsConfigurationSchema:()=>Jhs,GeneratorsOpenApiObjectSchema:()=>tor,GeneratorsOpenApiSchema:()=>ror,GraphQlSpecSchema:()=>Eir,Language:()=>nor,MessageNamingSettingsSchema:()=>VVe,NamespacedApiConfigurationSchema:()=>_ir,OpenApiExampleGenerationSchema:()=>mir,OpenApiFilterSchema:()=>hir,OpenApiSettingsSchema:()=>Ehe,OpenApiSpecSchema:()=>vir,OpenRpcSpecSchema:()=>Iir,OutputMetadataAuthor:()=>Tir,OutputMetadataSchema:()=>vhe,OverridesSchema:()=>$U,PathParameterOrder:()=>qVe,ProtobufApiDefinitionSchema:()=>KVe,ProtobufDefinitionSchema:()=>HVe,ProtobufSpecSchema:()=>wir,ReadmeCustomSectionSchema:()=>ior,ReadmeEndpointObjectSchema:()=>oor,ReadmeEndpointSchema:()=>Vvt,ReadmeSchema:()=>sor,RemoveDiscriminantsFromSchemas:()=>GVe,RequestOrResponseExampleGenerationSchema:()=>Lvt,ResolveAliases:()=>Air,ResolveAliasesSchema:()=>gir,SpecSchema:()=>Cir,UnionSettingsSchema:()=>cir,WhitelabelConfigurationSchema:()=>cor,WhitelabelGithubConfigurationSchema:()=>aor});var bhe=we.string();var VVe=we.enum_(["v1","v2"]);var qVe=we.enum_(["url-order","spec-order"]);var GVe=we.enum_(["always","never"]);var cir=we.enum_(["v1"]);var WVe=we.object({"use-title":we.boolean().optional(),unions:cir.optional(),"message-naming":VVe.optional(),"respect-nullable-schemas":we.boolean().optional(),"only-include-referenced-schemas":we.boolean().optional(),"inline-path-parameters":we.boolean().optional(),"idiomatic-request-names":we.boolean().optional(),"wrap-references-to-nullable-in-optional":we.boolean().optional(),"coerce-optional-schemas-to-nullable":we.boolean().optional(),"group-environments-by-host":we.boolean().optional(),"remove-discriminants-from-schemas":GVe.optional(),"path-parameter-order":qVe.optional()});var $U=we.undiscriminatedUnion([we.string(),we.list(we.string())]);var $Ve=we.object({path:bhe,origin:we.string().optional(),overrides:$U.optional(),audiences:we.list(we.string()).optional(),settings:WVe.optional()});var HVe=we.object({target:we.string().optional(),root:we.string(),overrides:$U.optional(),"local-generation":we.boolean().optional(),"from-openapi":we.boolean().optional(),dependencies:we.list(we.string()).optional()});var KVe=we.object({proto:HVe});var uir=we.undiscriminatedUnion([bhe,$Ve,KVe]);var lir=we.list(uir);var JVe=we.undiscriminatedUnion([bhe,$Ve,lir,KVe]);var pir=we.enum_(["literals","enums","enums-coerceable-to-literals"]);var YVe=we.object({"respect-nullable-schemas":we.boolean().optional(),"title-as-schema-name":we.boolean().optional(),"optional-additional-properties":we.boolean().optional(),"coerce-enums-to-literals":we.boolean().optional(),"idiomatic-request-names":we.boolean().optional(),"wrap-references-to-nullable-in-optional":we.boolean().optional(),"coerce-optional-schemas-to-nullable":we.boolean().optional(),"group-environments-by-host":we.boolean().optional(),"remove-discriminants-from-schemas":GVe.optional(),"path-parameter-order":qVe.optional(),"resolve-schema-collisions":we.boolean().optional(),"infer-forward-compatible":we.boolean().optional(),"infer-default-environment":we.boolean().optional(),"coerce-consts-to":pir.optional()});var XVe=we.object({"message-naming":VVe.optional()}).extend(YVe);var fir=we.enum_(["int32","int64","uint32","uint64"]);var dir=we.enum_(["form","json"]);var Lvt=we.object({"max-depth":we.number().optional()});var mir=we.object({request:Lvt.optional(),response:Lvt.optional()});var hir=we.object({endpoints:we.list(we.string()).optional()});var gir=we.object({except:we.list(we.string()).optional()});var Air=we.undiscriminatedUnion([we.boolean(),gir]);var Ehe=we.object({"only-include-referenced-schemas":we.boolean().optional(),"inline-path-parameters":we.boolean().optional(),"prefer-undiscriminated-unions-with-literals":we.boolean().optional(),"object-query-parameters":we.boolean().optional(),"respect-readonly-schemas":we.boolean().optional(),"respect-forward-compatible-enums":we.boolean().optional(),"use-bytes-for-binary-response":we.boolean().optional(),"default-form-parameter-encoding":dir.optional(),filter:hir.optional(),"example-generation":mir.optional(),"additional-properties-defaults-to":we.boolean().optional(),"type-dates-as-strings":we.boolean().optional(),"preserve-single-schema-oneof":we.boolean().optional(),"inline-all-of-schemas":we.boolean().optional(),"resolve-aliases":Air.optional(),"group-multi-api-environments":we.boolean().optional(),"default-integer-format":fir.optional()}).extend(YVe);var ZVe=we.object({}).extend(Ehe).extend(XVe);var yir=we.object({conjure:we.string()});var bir=we.object({asyncapi:we.string(),origin:we.string().optional(),overrides:$U.optional(),namespace:we.string().optional(),settings:XVe.optional()});var Eir=we.object({graphql:we.string(),origin:we.string().optional(),overrides:we.string().optional(),name:we.string().optional()});var vir=we.object({openapi:we.string(),origin:we.string().optional(),overrides:$U.optional(),overlays:we.string().optional(),namespace:we.string().optional(),settings:Ehe.optional()});var Iir=we.object({openrpc:we.string(),overrides:$U.optional(),namespace:we.string().optional()});var wir=we.object({proto:HVe});var Cir=we.undiscriminatedUnion([vir,bir,wir,Iir,Eir]);var e6e=we.undiscriminatedUnion([we.list(Cir),yir]);var xir=we.object({auth:jVe.optional(),"auth-schemes":we.record(we.string(),Ahe).optional(),specs:e6e,settings:ZVe.optional()}).extend(air).extend(Ynr);var _ir=we.object({namespaces:we.record(we.string(),JVe)});var Sir=we.undiscriminatedUnion([JVe,_ir,xir]);var Bir=we.enum_(["minimal","comprehensive"]);var Tir=we.object({name:we.string(),email:we.string()});var vhe=we.object({description:we.string().optional(),authors:we.list(Tir).optional()});var Uvt=we.object({name:we.string()});var Ihe=we.object({teams:we.list(Uvt).optional(),users:we.list(Uvt).optional()});var Oir=we.object({auth:jVe.optional(),"auth-schemes":we.record(we.string(),Ahe).optional(),headers:we.record(we.string(),zVe).optional(),settings:ZVe.optional(),specs:e6e.optional()});var Pir=we.object({url:we.string().optional(),"package-name":we.string(),token:we.string().optional()});var Dir=we.object({path:we.string()});var Rir=we.object({keyId:we.string(),password:we.string(),secretKey:we.string()});var Fir=we.object({url:we.string().optional(),coordinate:we.string(),username:we.string().optional(),password:we.string().optional(),signature:Rir.optional()});var kir=we.object({url:we.string().optional(),"package-name":we.string(),token:we.string().optional()});var Nir=we.object({url:we.string().optional(),"package-name":we.string(),"api-key":we.string().optional()});var Qir=we.object({"api-key":we.string(),"workspace-id":we.string(),"collection-id":we.string().optional()});var jir=we.object({keywords:we.list(we.string()).optional(),"documentation-link":we.string().optional(),"homepage-link":we.string().optional()}).extend(vhe);var Mir=we.object({url:we.string().optional(),"package-name":we.string(),token:we.string().optional(),username:we.string().optional(),password:we.string().optional(),metadata:jir.optional()});var Lir=we.object({url:we.string().optional(),"package-name":we.string(),"api-key":we.string().optional()});var Uir=we.union("location",{npm:kir,maven:Fir,pypi:Mir,postman:Qir,"local-file-system":Dir,nuget:Nir,rubygems:Lir,crates:Pir}).transform({transform:e=>e,untransform:e=>e});var zir=we.object({custom:we.string()});var Vir=we.enum_(["MIT","Apache-2.0"]);var HU=we.undiscriminatedUnion([Vir,zir]);var zvt=we.object({"package-description":we.string().optional(),email:we.string().optional(),"reference-url":we.string().optional(),author:we.string().optional(),license:HU.optional()});var qir=we.object({path:we.string()});var Gir=we.enum_(["commit","release"]);var Wir=we.object({repository:we.string(),license:HU.optional(),mode:Gir.optional()});var $ir=we.object({repository:we.string(),branch:we.string().optional(),license:HU.optional(),mode:we.stringLiteral("pull-request"),reviewers:Ihe.optional()});var Hir=we.object({repository:we.string(),license:HU.optional(),mode:we.stringLiteral("push"),branch:we.string().optional()});var Kir=we.enum_(["pull-request","push"]);var Jir=we.object({uri:we.string(),token:we.string(),mode:Kir.optional(),branch:we.string().optional(),license:HU.optional()});var Yir=we.undiscriminatedUnion([Jir,Wir,$ir,Hir]);var Xir=we.object({name:we.string(),version:we.string(),output:Uir.optional(),github:Yir.optional(),config:we.unknown().optional(),metadata:zvt.optional(),keywords:we.list(we.string()).optional(),snippets:qir.optional(),"ir-version":we.string().optional(),"smart-casing":we.boolean().optional(),api:Oir.optional(),"disable-examples":we.boolean().optional(),"publish-metadata":zvt.optional(),autorelease:we.boolean().optional()});var Zir=we.object({audiences:we.list(we.string()).optional(),generators:we.list(Xir),metadata:vhe.optional(),reviewers:Ihe.optional()});var eor=we.object({enabled:we.boolean()});var tor=we.object({path:we.string(),origin:we.string().optional(),overrides:we.string().optional(),"disable-examples":we.boolean().optional(),settings:Ehe});var ror=we.undiscriminatedUnion([tor,we.string()]);var nor=we.enum_(["java","python","go","ruby","csharp","typescript","php","rust","swift"]);var ior=we.object({title:we.string(),language:nor,content:we.string()});var oor=we.object({method:we.string(),path:we.string(),stream:we.boolean().optional()});var Vvt=we.undiscriminatedUnion([we.string(),oor]);var sor=we.object({bannerLink:we.string().optional(),introduction:we.string().optional(),apiReferenceLink:we.string().optional(),apiName:we.string().optional(),disabledSections:we.list(we.string()).optional(),defaultEndpoint:Vvt.optional(),features:we.record(we.string(),we.list(Vvt)).optional(),customSections:we.list(ior).optional(),exampleStyle:Bir.optional()});var aor=we.object({username:we.string(),email:we.string(),token:we.string()});var cor=we.object({github:aor.optional()});var Jhs=we.object({"auth-schemes":we.record(we.string(),Ahe).optional(),api:Sir.optional(),whitelabel:cor.optional(),metadata:vhe.optional(),readme:sor.optional(),"default-group":we.string().optional(),aliases:we.record(we.string(),we.list(we.string())).optional(),groups:we.record(we.string(),Zir).optional(),reviewers:Ihe.optional(),replay:eor.optional(),ai:Inr.optional(),autorelease:we.boolean().optional(),openapi:ror.optional(),"openapi-overrides":we.string().optional(),"spec-origin":we.string().optional(),"async-api":we.string().optional(),"api-settings":WVe.optional()});var $ui={};te($ui,{CratesOutputLocationSchema:()=>Pir,GeneratorApiSettingsSchema:()=>Oir,GeneratorGroupSchema:()=>Zir,GeneratorInvocationSchema:()=>Xir,GeneratorOutputSchema:()=>Uir,GeneratorPublishMetadataSchema:()=>zvt,GeneratorSnippetsSchema:()=>qir,GithubCommitAndReleaseMode:()=>Gir,GithubCommitAndReleaseSchema:()=>Wir,GithubConfigurationSchema:()=>Yir,GithubPullRequestSchema:()=>$ir,GithubPushSchema:()=>Hir,GithubSelfhostedMode:()=>Kir,GithubSelfhostedSchema:()=>Jir,LocalFileSystemOutputLocationSchema:()=>Dir,MavenOutputLocationSchema:()=>Fir,MavenOutputSignatureSchema:()=>Rir,NpmOutputLocationSchema:()=>kir,NugetOutputLocationSchema:()=>Nir,PostmanOutputLocationSchema:()=>Qir,PypiOutputLocationSchema:()=>Mir,PypiOutputMetadataSchema:()=>jir,RubyGemsOutputLocationSchema:()=>Lir});var Hui={};te(Hui,{GithubLicenseCustomSchema:()=>zir,GithubLicenseSchema:()=>HU,GithubLicenseType:()=>Vir});var Kui={};te(Kui,{ReplayConfigSchema:()=>eor});var Jui={};te(Jui,{ReviewerSchema:()=>Uvt,ReviewersSchema:()=>Ihe});function Yhs(e){return e?.specs!=null}function Xhs(e){return e?.asyncapi!=null}function Zhs(e){return e?.conjure!=null}function egs(e){return e?.graphql!=null}function tgs(e){return e?.namespaces!=null}function rgs(e){return e?.openapi!=null}function ngs(e){return e?.openrpc!=null}function igs(e){return e?.proto!=null}var oAl={enableUniqueErrorsPerEndpoint:!1,detectGlobalHeaders:!0,objectQueryParameters:!0,respectReadonlySchemas:!1,respectNullableSchemas:!0,onlyIncludeReferencedSchemas:!1,inlinePathParameters:!0,useBytesForBinaryResponse:!1,respectForwardCompatibleEnums:!1,wrapReferencesToNullableInOptional:!1,coerceOptionalSchemasToNullable:!1,groupEnvironmentsByHost:!1,removeDiscriminantsFromSchemas:In.RemoveDiscriminantsFromSchemas.Always,inferDefaultEnvironment:!0};function sAl(e){let{defaults:t,options:r,overrides:n,overrideOnly:i=new Set,undefinedIfAbsent:o=new Set}=e,s={};for(let a of Object.keys(t))i.has(a)?s[a]=n?.[a]!==void 0?n[a]:t[a]:o.has(a)?s[a]=n?.[a]!==void 0?n[a]:r?.[a]!==void 0?r[a]:void 0:s[a]=n?.[a]??r?.[a]??t[a];return s}function POe({options:e,overrides:t}){return sAl({defaults:oAl,options:e,overrides:t})}sA();sA();St();var t6e={protobuf:e=>({...e,type:"protobuf",_visit:function(t){return t6e._visit(this,t)}}),_visit:(e,t)=>e.type==="protobuf"?t.protobuf(e):t._other(e)};var Ix={basic:e=>({...e,type:"basic",_visit:function(t){return Ix._visit(this,t)}}),bearer:e=>({...e,type:"bearer",_visit:function(t){return Ix._visit(this,t)}}),header:e=>({...e,type:"header",_visit:function(t){return Ix._visit(this,t)}}),query:e=>({...e,type:"query",_visit:function(t){return Ix._visit(this,t)}}),oauth:e=>({...e,type:"oauth",_visit:function(t){return Ix._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"basic":return t.basic(e);case"bearer":return t.bearer(e);case"header":return t.header(e);case"query":return t.query(e);case"oauth":return t.oauth(e);default:return t._other(e)}}};var lT={openapi:e=>({...e,type:"openapi",_visit:function(t){return lT._visit(this,t)}}),protobuf:e=>({...e,type:"protobuf",_visit:function(t){return lT._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"openapi":return t.openapi(e);case"protobuf":return t.protobuf(e);default:return t._other(e)}}};var lc={primitive:e=>({value:e,type:"primitive",_visit:function(t){return lc._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return lc._visit(this,t)}}),array:e=>({value:e,type:"array",_visit:function(t){return lc._visit(this,t)}}),map:e=>({value:e,type:"map",_visit:function(t){return lc._visit(this,t)}}),enum:e=>({value:e,type:"enum",_visit:function(t){return lc._visit(this,t)}}),literal:e=>({value:e,type:"literal",_visit:function(t){return lc._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return lc._visit(this,t)}}),null:e=>({...e,type:"null",_visit:function(t){return lc._visit(this,t)}}),unknown:e=>({value:e,type:"unknown",_visit:function(t){return lc._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e.value);case"object":return t.object(e);case"array":return t.array(e.value);case"map":return t.map(e.value);case"enum":return t.enum(e.value);case"literal":return t.literal(e.value);case"oneOf":return t.oneOf(e.value);case"null":return t.null(e);case"unknown":return t.unknown(e.value);default:return t._other(e)}}};var whe={discriminated:e=>({value:e,type:"discriminated",_visit:function(t){return whe._visit(this,t)}}),undiscriminated:e=>({value:e,type:"undiscriminated",_visit:function(t){return whe._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e.value);case"undiscriminated":return t.undiscriminated(e.value);default:return t._other(e)}}};var Che={boolean:e=>({value:e,type:"boolean",_visit:function(t){return Che._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return Che._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"boolean":return t.boolean(e.value);case"string":return t.string(e.value);default:return t._other(e)}}};var hs={int:e=>({value:e,type:"int",_visit:function(t){return hs._visit(this,t)}}),int64:e=>({value:e,type:"int64",_visit:function(t){return hs._visit(this,t)}}),uint:e=>({value:e,type:"uint",_visit:function(t){return hs._visit(this,t)}}),uint64:e=>({value:e,type:"uint64",_visit:function(t){return hs._visit(this,t)}}),float:e=>({value:e,type:"float",_visit:function(t){return hs._visit(this,t)}}),double:e=>({value:e,type:"double",_visit:function(t){return hs._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return hs._visit(this,t)}}),datetime:e=>({value:e,type:"datetime",_visit:function(t){return hs._visit(this,t)}}),datetimeRfc2822:e=>({value:e,type:"datetimeRfc2822",_visit:function(t){return hs._visit(this,t)}}),date:e=>({value:e,type:"date",_visit:function(t){return hs._visit(this,t)}}),base64:e=>({value:e,type:"base64",_visit:function(t){return hs._visit(this,t)}}),boolean:e=>({value:e,type:"boolean",_visit:function(t){return hs._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e.value);case"int64":return t.int64(e.value);case"uint":return t.uint(e.value);case"uint64":return t.uint64(e.value);case"float":return t.float(e.value);case"double":return t.double(e.value);case"string":return t.string(e.value);case"datetime":return t.datetime(e.value);case"datetimeRfc2822":return t.datetimeRfc2822(e.value);case"date":return t.date(e.value);case"base64":return t.base64(e.value);case"boolean":return t.boolean(e.value);default:return t._other(e)}}};var Qg={};te(Qg,{AsymmetricAlgorithm:()=>xhe,Availability:()=>wx,CustomCodeSample:()=>E$,DiscriminatorContext:()=>Xui,EndpointExample:()=>KU,EndpointResponseExample:()=>JU,HttpMethod:()=>Cx,LiteralSchemaValue:()=>fA,MultipartRequestPropertyEncoding:()=>Zui,MultipartSchema:()=>v$,OneOfSchema:()=>I$,Pagination:()=>Hw,PrimitiveSchemaValue:()=>ol,Request:()=>oq,Response:()=>XS,RetriesConfiguration:()=>qvt,Schema:()=>ba,SupportedSdkLanguage:()=>xx,WebhookHttpMethod:()=>eli,WebhookPayloadComponent:()=>Gvt,WebhookSignatureAlgorithm:()=>Wvt,WebhookSignatureEncoding:()=>tli,WebhookSignatureVerification:()=>DOe,WebhookTimestampFormat:()=>uor,WebsocketMessageOrigin:()=>rli});var aAl={RsaSha256:"rsa-sha256",RsaSha384:"rsa-sha384",RsaSha512:"rsa-sha512",EcdsaSha256:"ecdsa-sha256",EcdsaSha384:"ecdsa-sha384",EcdsaSha512:"ecdsa-sha512",Ed25519:"ed25519"},xhe={...aAl,_visit:(e,t)=>{switch(e){case xhe.RsaSha256:return t.rsaSha256();case xhe.RsaSha384:return t.rsaSha384();case xhe.RsaSha512:return t.rsaSha512();case xhe.EcdsaSha256:return t.ecdsaSha256();case xhe.EcdsaSha384:return t.ecdsaSha384();case xhe.EcdsaSha512:return t.ecdsaSha512();case xhe.Ed25519:return t.ed25519();default:return t._other()}}};var cAl={GenerallyAvailable:"GenerallyAvailable",Beta:"Beta",Deprecated:"Deprecated"},wx={...cAl,_visit:(e,t)=>{switch(e){case wx.GenerallyAvailable:return t.generallyAvailable();case wx.Beta:return t.beta();case wx.Deprecated:return t.deprecated();default:return t._other()}}};var E$={language:e=>({...e,type:"language",_visit:function(t){return E$._visit(this,t)}}),sdk:e=>({...e,type:"sdk",_visit:function(t){return E$._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"language":return t.language(e);case"sdk":return t.sdk(e);default:return t._other(e)}}};var uAl={Data:"data",Protocol:"protocol"},Xui={...uAl,_visit:(e,t)=>{switch(e){case Xui.Data:return t.data();case Xui.Protocol:return t.protocol();default:return t._other()}}};var KU={unknown:e=>({value:e,type:"unknown",_visit:function(t){return KU._visit(this,t)}}),full:e=>({...e,type:"full",_visit:function(t){return KU._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"unknown":return t.unknown(e.value);case"full":return t.full(e);default:return t._other(e)}}};var JU={withStreaming:e=>({...e,type:"withStreaming",_visit:function(t){return JU._visit(this,t)}}),withoutStreaming:e=>({value:e,type:"withoutStreaming",_visit:function(t){return JU._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"withStreaming":return t.withStreaming(e);case"withoutStreaming":return t.withoutStreaming(e.value);default:return t._other(e)}}};var lAl={Get:"GET",Post:"POST",Put:"PUT",Patch:"PATCH",Delete:"DELETE",Head:"HEAD",Options:"OPTIONS",Trace:"TRACE"},Cx={...lAl,_visit:(e,t)=>{switch(e){case Cx.Get:return t.get();case Cx.Post:return t.post();case Cx.Put:return t.put();case Cx.Patch:return t.patch();case Cx.Delete:return t.delete();case Cx.Head:return t.head();case Cx.Options:return t.options();case Cx.Trace:return t.trace();default:return t._other()}}};var fA={boolean:e=>({value:e,type:"boolean",_visit:function(t){return fA._visit(this,t)}}),string:e=>({value:e,type:"string",_visit:function(t){return fA._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"boolean":return t.boolean(e.value);case"string":return t.string(e.value);default:return t._other(e)}}};var pAl={Json:"json",Form:"form"},Zui={...pAl,_visit:(e,t)=>{switch(e){case Zui.Json:return t.json();case Zui.Form:return t.form();default:return t._other()}}};var v$={file:e=>({...e,type:"file",_visit:function(t){return v$._visit(this,t)}}),json:e=>({value:e,type:"json",_visit:function(t){return v$._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e.value);default:return t._other(e)}}};var I$={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return I$._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return I$._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var Hw={cursor:e=>({...e,type:"cursor",_visit:function(t){return Hw._visit(this,t)}}),offset:e=>({...e,type:"offset",_visit:function(t){return Hw._visit(this,t)}}),custom:e=>({...e,type:"custom",_visit:function(t){return Hw._visit(this,t)}}),uri:e=>({...e,type:"uri",_visit:function(t){return Hw._visit(this,t)}}),path:e=>({...e,type:"path",_visit:function(t){return Hw._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"cursor":return t.cursor(e);case"offset":return t.offset(e);case"custom":return t.custom(e);case"uri":return t.uri(e);case"path":return t.path(e);default:return t._other(e)}}};var ol={int:e=>({...e,type:"int",_visit:function(t){return ol._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return ol._visit(this,t)}}),uint:()=>({type:"uint",_visit:function(e){return ol._visit(this,e)}}),uint64:()=>({type:"uint64",_visit:function(e){return ol._visit(this,e)}}),float:()=>({type:"float",_visit:function(e){return ol._visit(this,e)}}),double:e=>({...e,type:"double",_visit:function(t){return ol._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return ol._visit(this,t)}}),datetime:()=>({type:"datetime",_visit:function(e){return ol._visit(this,e)}}),datetimeRfc2822:()=>({type:"datetimeRfc2822",_visit:function(e){return ol._visit(this,e)}}),date:()=>({type:"date",_visit:function(e){return ol._visit(this,e)}}),base64:()=>({type:"base64",_visit:function(e){return ol._visit(this,e)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return ol._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint();case"uint64":return t.uint64();case"float":return t.float();case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime();case"datetimeRfc2822":return t.datetimeRfc2822();case"date":return t.date();case"base64":return t.base64();case"boolean":return t.boolean(e);default:return t._other(e)}}};var oq={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return oq._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return oq._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return oq._visit(this,t)}}),formUrlEncoded:e=>({...e,type:"formUrlEncoded",_visit:function(t){return oq._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);case"formUrlEncoded":return t.formUrlEncoded(e);default:return t._other(e)}}};var XS={file:e=>({...e,type:"file",_visit:function(t){return XS._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return XS._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return XS._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return XS._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return XS._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return XS._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return XS._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var qvt={disabled:e=>({value:e,type:"disabled",_visit:function(t){return qvt._visit(this,t)}}),_visit:(e,t)=>e.type==="disabled"?t.disabled(e.value):t._other(e)};var ba={primitive:e=>({...e,type:"primitive",_visit:function(t){return ba._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return ba._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return ba._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return ba._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return ba._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return ba._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return ba._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return ba._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return ba._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return ba._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return ba._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var fAl={Curl:"curl",Python:"python",Javascript:"javascript",Typescript:"typescript",Go:"go",Ruby:"ruby",Csharp:"csharp",Java:"java",Js:"js",Node:"node",Ts:"ts",Nodets:"nodets",Golang:"golang",Dotnet:"dotnet",Jvm:"jvm"},xx={...fAl,_visit:(e,t)=>{switch(e){case xx.Curl:return t.curl();case xx.Python:return t.python();case xx.Javascript:return t.javascript();case xx.Typescript:return t.typescript();case xx.Go:return t.go();case xx.Ruby:return t.ruby();case xx.Csharp:return t.csharp();case xx.Java:return t.java();case xx.Js:return t.js();case xx.Node:return t.node();case xx.Ts:return t.ts();case xx.Nodets:return t.nodets();case xx.Golang:return t.golang();case xx.Dotnet:return t.dotnet();case xx.Jvm:return t.jvm();default:return t._other()}}};var dAl={Get:"GET",Post:"POST"},eli={...dAl,_visit:(e,t)=>{switch(e){case eli.Get:return t.get();case eli.Post:return t.post();default:return t._other()}}};var mAl={Body:"body",Timestamp:"timestamp",NotificationUrl:"notification-url",MessageId:"message-id"},Gvt={...mAl,_visit:(e,t)=>{switch(e){case Gvt.Body:return t.body();case Gvt.Timestamp:return t.timestamp();case Gvt.NotificationUrl:return t.notificationUrl();case Gvt.MessageId:return t.messageId();default:return t._other()}}};var hAl={Sha256:"sha256",Sha1:"sha1",Sha384:"sha384",Sha512:"sha512"},Wvt={...hAl,_visit:(e,t)=>{switch(e){case Wvt.Sha256:return t.sha256();case Wvt.Sha1:return t.sha1();case Wvt.Sha384:return t.sha384();case Wvt.Sha512:return t.sha512();default:return t._other()}}};var gAl={Base64:"base64",Hex:"hex"},tli={...gAl,_visit:(e,t)=>{switch(e){case tli.Base64:return t.base64();case tli.Hex:return t.hex();default:return t._other()}}};var DOe={hmac:e=>({...e,type:"hmac",_visit:function(t){return DOe._visit(this,t)}}),asymmetric:e=>({...e,type:"asymmetric",_visit:function(t){return DOe._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"hmac":return t.hmac(e);case"asymmetric":return t.asymmetric(e);default:return t._other(e)}}};var AAl={UnixSeconds:"unix-seconds",UnixMillis:"unix-millis",Iso8601:"iso8601"},uor={...AAl,_visit:(e,t)=>{switch(e){case uor.UnixSeconds:return t.unixSeconds();case uor.UnixMillis:return t.unixMillis();case uor.Iso8601:return t.iso8601();default:return t._other()}}};var yAl={Client:"client",Server:"server"},rli={...yAl,_visit:(e,t)=>{switch(e){case rli.Client:return t.client();case rli.Server:return t.server();default:return t._other()}}};var vj={discriminated:e=>({...e,type:"discriminated",_visit:function(t){return vj._visit(this,t)}}),undiscriminated:e=>({...e,type:"undiscriminated",_visit:function(t){return vj._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"discriminated":return t.discriminated(e);case"undiscriminated":return t.undiscriminated(e);default:return t._other(e)}}};var xi={int:e=>({...e,type:"int",_visit:function(t){return xi._visit(this,t)}}),int64:e=>({...e,type:"int64",_visit:function(t){return xi._visit(this,t)}}),uint:e=>({...e,type:"uint",_visit:function(t){return xi._visit(this,t)}}),uint64:e=>({...e,type:"uint64",_visit:function(t){return xi._visit(this,t)}}),float:e=>({...e,type:"float",_visit:function(t){return xi._visit(this,t)}}),double:e=>({...e,type:"double",_visit:function(t){return xi._visit(this,t)}}),string:e=>({...e,type:"string",_visit:function(t){return xi._visit(this,t)}}),datetime:e=>({...e,type:"datetime",_visit:function(t){return xi._visit(this,t)}}),datetimeRfc2822:e=>({...e,type:"datetimeRfc2822",_visit:function(t){return xi._visit(this,t)}}),date:e=>({...e,type:"date",_visit:function(t){return xi._visit(this,t)}}),base64:e=>({...e,type:"base64",_visit:function(t){return xi._visit(this,t)}}),boolean:e=>({...e,type:"boolean",_visit:function(t){return xi._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"int":return t.int(e);case"int64":return t.int64(e);case"uint":return t.uint(e);case"uint64":return t.uint64(e);case"float":return t.float(e);case"double":return t.double(e);case"string":return t.string(e);case"datetime":return t.datetime(e);case"datetimeRfc2822":return t.datetimeRfc2822(e);case"date":return t.date(e);case"base64":return t.base64(e);case"boolean":return t.boolean(e);default:return t._other(e)}}};var HP={octetStream:e=>({...e,type:"octetStream",_visit:function(t){return HP._visit(this,t)}}),multipart:e=>({...e,type:"multipart",_visit:function(t){return HP._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return HP._visit(this,t)}}),formUrlEncoded:e=>({...e,type:"formUrlEncoded",_visit:function(t){return HP._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"octetStream":return t.octetStream(e);case"multipart":return t.multipart(e);case"json":return t.json(e);case"formUrlEncoded":return t.formUrlEncoded(e);default:return t._other(e)}}};var Fh={file:e=>({...e,type:"file",_visit:function(t){return Fh._visit(this,t)}}),json:e=>({...e,type:"json",_visit:function(t){return Fh._visit(this,t)}}),text:e=>({...e,type:"text",_visit:function(t){return Fh._visit(this,t)}}),bytes:e=>({...e,type:"bytes",_visit:function(t){return Fh._visit(this,t)}}),streamingSse:e=>({...e,type:"streamingSse",_visit:function(t){return Fh._visit(this,t)}}),streamingText:e=>({...e,type:"streamingText",_visit:function(t){return Fh._visit(this,t)}}),streamingJson:e=>({...e,type:"streamingJson",_visit:function(t){return Fh._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"file":return t.file(e);case"json":return t.json(e);case"text":return t.text(e);case"bytes":return t.bytes(e);case"streamingSse":return t.streamingSse(e);case"streamingText":return t.streamingText(e);case"streamingJson":return t.streamingJson(e);default:return t._other(e)}}};var Fr={primitive:e=>({...e,type:"primitive",_visit:function(t){return Fr._visit(this,t)}}),object:e=>({...e,type:"object",_visit:function(t){return Fr._visit(this,t)}}),array:e=>({...e,type:"array",_visit:function(t){return Fr._visit(this,t)}}),map:e=>({...e,type:"map",_visit:function(t){return Fr._visit(this,t)}}),optional:e=>({...e,type:"optional",_visit:function(t){return Fr._visit(this,t)}}),enum:e=>({...e,type:"enum",_visit:function(t){return Fr._visit(this,t)}}),reference:e=>({...e,type:"reference",_visit:function(t){return Fr._visit(this,t)}}),literal:e=>({...e,type:"literal",_visit:function(t){return Fr._visit(this,t)}}),oneOf:e=>({value:e,type:"oneOf",_visit:function(t){return Fr._visit(this,t)}}),nullable:e=>({...e,type:"nullable",_visit:function(t){return Fr._visit(this,t)}}),unknown:e=>({...e,type:"unknown",_visit:function(t){return Fr._visit(this,t)}}),_visit:(e,t)=>{switch(e.type){case"primitive":return t.primitive(e);case"object":return t.object(e);case"array":return t.array(e);case"map":return t.map(e);case"optional":return t.optional(e);case"enum":return t.enum(e);case"reference":return t.reference(e);case"literal":return t.literal(e);case"oneOf":return t.oneOf(e.value);case"nullable":return t.nullable(e);case"unknown":return t.unknown(e);default:return t._other(e)}}};var Ea={};te(Ea,{AllOfPropertyConflict:()=>c6e,ArraySchema:()=>jor,ArraySchemaWithExample:()=>$sr,AsymmetricAlgorithm:()=>Mor,AsymmetricWebhookSignatureVerification:()=>Uor,Availability:()=>Ior,Base64WithExample:()=>Hsr,BasicSecurityScheme:()=>hor,BearerSecurityScheme:()=>gor,BooleanSchema:()=>zor,BooleanWithExample:()=>Ksr,BytesResponse:()=>p6e,CasingOverrides:()=>Sor,CommonProperty:()=>Vor,CommonPropertyWithExample:()=>Jsr,CursorPagination:()=>qor,CustomCodeSample:()=>Hor,CustomCodeSampleLanguage:()=>Gor,CustomCodeSampleSdk:()=>$or,CustomPagination:()=>Kor,DateWithExample:()=>Ysr,DatetimeWithExample:()=>Jvt,DiscriminatedOneOfSchema:()=>Jor,DiscriminatedOneOfSchemaWithExample:()=>Xsr,DiscriminatorContext:()=>f6e,DoubleSchema:()=>Yor,DoubleWithExample:()=>Zsr,Encoding:()=>yor,Endpoint:()=>msr,EndpointExample:()=>h6e,EndpointResponseExample:()=>esr,EndpointSdkName:()=>x$,EndpointSecurity:()=>g6e,EndpointWithExample:()=>Rgs,EnumSchema:()=>o6e,EnumSchemaWithExample:()=>aar,EnumValue:()=>She,ErrorExample:()=>nsr,FernExample:()=>Xor,FileResponse:()=>C6e,FileSchema:()=>psr,FloatWithExample:()=>car,FormUrlEncodedRequest:()=>csr,FullEndpointExample:()=>rsr,FullExample:()=>qm,FullObjectExample:()=>kor,FullOneOfExample:()=>Nor,GlobalHeader:()=>hsr,GlobalSecurity:()=>gsr,Header:()=>The,HeaderExample:()=>d6e,HeaderSecurityScheme:()=>bor,HeaderWithExample:()=>Rhe,HmacWebhookSignatureVerification:()=>Esr,HttpEndpointServer:()=>A6e,HttpError:()=>isr,HttpErrorWithExample:()=>ear,HttpMethod:()=>y6e,IdempotencyHeader:()=>vsr,Int64WithExample:()=>uar,IntSchema:()=>Isr,IntWithExample:()=>lar,JsonRequest:()=>usr,JsonRequestWithExample:()=>rar,JsonResponse:()=>x6e,JsonResponseWithExample:()=>F6e,KeyValuePair:()=>Qor,LiteralExample:()=>Ror,LiteralSchema:()=>B6e,LiteralSchemaValue:()=>wsr,LongSchema:()=>Csr,MapSchema:()=>Ssr,MapSchemaWithExample:()=>har,MultipartFormDataWebhookPayload:()=>Bsr,MultipartFormDataWebhookPayloadWithExample:()=>gar,MultipartRequest:()=>I6e,MultipartRequestProperty:()=>Ohe,MultipartRequestPropertyEncoding:()=>lsr,MultipartSchema:()=>fsr,NamedFullExample:()=>nk,Namespace:()=>Eor,NamespaceId:()=>vor,NullExample:()=>For,NullableSchema:()=>Tsr,NullableSchemaWithExample:()=>Aar,OauthSecurityScheme:()=>Bor,ObjectProperty:()=>Osr,ObjectPropertyConflictInfo:()=>T6e,ObjectPropertyWithExample:()=>yar,ObjectSchema:()=>Psr,ObjectSchemaWithExample:()=>bar,OctetStreamRequest:()=>w6e,OffsetPagination:()=>osr,OneOfSchema:()=>Dsr,OneOfSchemaWithExample:()=>Ear,OpenApiIntermediateRepresentation:()=>Dgs,OpenApiSource:()=>Cor,OptionalSchema:()=>Gsr,OptionalSchemaWithExample:()=>war,Pagination:()=>b6e,ParseFormUrlEncodedRequest:()=>nar,ParseMultipartRequest:()=>iar,ParseOctetStreamRequest:()=>oar,PathPagination:()=>ssr,PathParameter:()=>E6e,PathParameterExample:()=>tsr,PathParameterWithExample:()=>tar,PrimitiveExample:()=>s6e,PrimitiveSchema:()=>Dhe,PrimitiveSchemaValue:()=>_sr,PrimitiveSchemaValueWithExample:()=>mar,PrimitiveSchemaWithExample:()=>N6e,PropertyKey:()=>a6e,ProtobufEncoding:()=>Aor,ProtobufSource:()=>xor,QueryParameter:()=>v6e,QueryParameterExample:()=>m6e,QueryParameterWithExample:()=>R6e,QuerySecurityScheme:()=>Tor,ReferencedSchema:()=>_$,Request:()=>dsr,RequestWithExample:()=>sar,Response:()=>_6e,ResponseWithExample:()=>k6e,RetriesConfiguration:()=>S6e,Schema:()=>$u,SchemaId:()=>KP,SchemaWithExample:()=>zf,Schemas:()=>Fsr,SdkGroup:()=>wor,SdkGroupInfo:()=>ksr,SdkGroupName:()=>_he,SecurityScheme:()=>Oor,SecuritySchemeId:()=>Bhe,Server:()=>Kvt,ServerVariable:()=>Por,Source:()=>_or,StatusCode:()=>w$,StreamingResponseExample:()=>Zor,StringSchema:()=>xsr,StringSchemaWithExample:()=>par,SupportedSdkLanguage:()=>Wor,Tag:()=>Dor,TagId:()=>JP,Tags:()=>Nsr,TextResponse:()=>Phe,Uint64WithExample:()=>far,UintWithExample:()=>dar,UnDiscriminatedOneOfSchema:()=>Rsr,UnDiscriminatedOneOfSchemaWithExample:()=>Iar,UnknownSchema:()=>Wsr,UnknownSchemaWithExample:()=>Car,UriPagination:()=>asr,Webhook:()=>Qsr,WebhookExampleCall:()=>O6e,WebhookHttpMethod:()=>P6e,WebhookPayloadComponent:()=>Asr,WebhookPayloadFormat:()=>ysr,WebhookSignatureAlgorithm:()=>bsr,WebhookSignatureEncoding:()=>u6e,WebhookSignatureVerification:()=>D6e,WebhookTimestamp:()=>l6e,WebhookTimestampFormat:()=>Lor,WebhookWithExample:()=>Fgs,WebsocketChannel:()=>qsr,WebsocketHandshake:()=>jsr,WebsocketHandshakeWithExample:()=>kgs,WebsocketMessageExample:()=>zsr,WebsocketMessageOrigin:()=>Msr,WebsocketMessageSchema:()=>Lsr,WebsocketServer:()=>Usr,WebsocketSessionExample:()=>Vsr,WithAvailability:()=>us,WithDescription:()=>mn,WithEncoding:()=>Bx,WithInline:()=>Uf,WithName:()=>Nc,WithNamespace:()=>oc,WithSdkGroupName:()=>xu,WithSdkMethodName:()=>C$,WithSource:()=>$o,WithStatusCode:()=>YU,WithTitle:()=>_u,commons:()=>cli,example:()=>uli,finalIr:()=>lli,parseIr:()=>pli});var cli={};te(cli,{BasicSecurityScheme:()=>hor,BearerSecurityScheme:()=>gor,Encoding:()=>yor,HeaderSecurityScheme:()=>bor,Namespace:()=>Eor,NamespaceId:()=>vor,OauthSecurityScheme:()=>Bor,OpenApiSource:()=>Cor,ProtobufEncoding:()=>Aor,ProtobufSource:()=>xor,QuerySecurityScheme:()=>Tor,SchemaId:()=>KP,SdkGroup:()=>wor,SdkGroupName:()=>_he,SecurityScheme:()=>Oor,SecuritySchemeId:()=>Bhe,Server:()=>Kvt,ServerVariable:()=>Por,Source:()=>_or,StatusCode:()=>w$,Tag:()=>Dor,TagId:()=>JP,WithAvailability:()=>us,WithDescription:()=>mn,WithEncoding:()=>Bx,WithInline:()=>Uf,WithName:()=>Nc,WithNamespace:()=>oc,WithSdkGroupName:()=>xu,WithSdkMethodName:()=>C$,WithSource:()=>$o,WithStatusCode:()=>YU,WithTitle:()=>_u});var J={};te(J,{JsonError:()=>r6e,ParseError:()=>n6e,any:()=>ygs,bigint:()=>sgs,boolean:()=>bgs,booleanLiteral:()=>ggs,date:()=>ags,discriminant:()=>Tgs,enum_:()=>por,getObjectLikeUtils:()=>sq,getObjectUtils:()=>ROe,getSchemaUtils:()=>Hd,isProperty:()=>zse,lazy:()=>cgs,lazyObject:()=>mgs,list:()=>mor,never:()=>Egs,number:()=>vgs,object:()=>dor,objectWithoutOptionalProperties:()=>dgs,optional:()=>nli,property:()=>lgs,record:()=>xgs,set:()=>_gs,string:()=>Igs,stringLiteral:()=>Ags,transform:()=>ili,undiscriminatedUnion:()=>Bgs,union:()=>Pgs,unknown:()=>wgs,withParsedProperties:()=>ali});var Cu={BIGINT:"bigint",DATE:"date",ENUM:"enum",LIST:"list",STRING_LITERAL:"stringLiteral",BOOLEAN_LITERAL:"booleanLiteral",OBJECT:"object",ANY:"any",BOOLEAN:"boolean",NUMBER:"number",STRING:"string",UNKNOWN:"unknown",NEVER:"never",RECORD:"record",SET:"set",UNION:"union",UNDISCRIMINATED_UNION:"undiscriminatedUnion",NULLABLE:"nullable",OPTIONAL:"optional",OPTIONAL_NULLABLE:"optionalNullable"};function gd(e,t){return`Expected ${t}. Received ${bAl(e)}.`}function bAl(e){if(Array.isArray(e))return"list";if(e===null)return"null";if(e instanceof BigInt)return"BigInt";switch(typeof e){case"string":return`"${e}"`;case"bigint":case"number":case"boolean":case"undefined":return`${e}`}return typeof e}function _x(e){return{...e,json:ogs(e.json),parse:ogs(e.parse)}}function ogs(e){return(t,r)=>{let n=e(t,r),{skipValidation:i=!1}=r??{};return!n.ok&&i?(console.warn(["Failed to validate.",...n.errors.map(o=>" - "+(o.path.length>0?`${o.path.join(".")}: ${o.message}`:o.message))].join(`
1463
- `)),{ok:!0,value:t}):n}}function lor(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var r6e=class e extends Error{errors;constructor(t){super(t.map(lor).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var n6e=class e extends Error{errors;constructor(t){super(t.map(lor).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function Hd(e){return{nullable:()=>EAl(e),optional:()=>nli(e),optionalNullable:()=>vAl(e),transform:t=>ili(e,t),parseOrThrow:(t,r)=>{let n=e.parse(t,r);if(n.ok)return n.value;throw new n6e(n.errors)},jsonOrThrow:(t,r)=>{let n=e.json(t,r);if(n.ok)return n.value;throw new r6e(n.errors)}}}function EAl(e){let t={parse:(r,n)=>r==null?{ok:!0,value:null}:e.parse(r,n),json:(r,n)=>r==null?{ok:!0,value:null}:e.json(r,n),getType:()=>Cu.NULLABLE};return{...t,...Hd(t)}}function nli(e){let t={parse:(r,n)=>r==null?{ok:!0,value:void 0}:e.parse(r,n),json:(r,n)=>n?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:e.json(r,n),getType:()=>Cu.OPTIONAL};return{...t,...Hd(t)}}function vAl(e){let t={parse:(r,n)=>r===void 0?{ok:!0,value:void 0}:r===null?{ok:!0,value:null}:e.parse(r,n),json:(r,n)=>r===void 0?{ok:!0,value:void 0}:r===null?{ok:!0,value:null}:e.json(r,n),getType:()=>Cu.OPTIONAL_NULLABLE};return{...t,...Hd(t)}}function ili(e,t){let r={parse:(n,i)=>{let o=e.parse(n,i);return o.ok?{ok:!0,value:t.transform(o.value)}:o},json:(n,i)=>{let o=t.untransform(n);return e.json(o,i)},getType:()=>e.getType()};return{...r,...Hd(r)}}function sgs(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t=="bigint"?{ok:!0,value:t}:typeof t=="number"?{ok:!0,value:BigInt(t)}:{ok:!1,errors:[{path:r,message:gd(t,"bigint | number")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="bigint"?{ok:!1,errors:[{path:r,message:gd(t,"bigint")}]}:{ok:!0,value:t},getType:()=>Cu.BIGINT};return{..._x(e),...Hd(e)}}var IAl=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function ags(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:gd(t,"string")}]}:IAl.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:gd(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:gd(t,"Date object")}]},getType:()=>Cu.DATE};return{..._x(e),...Hd(e)}}function Sx(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{..._x(r),...Hd(r)}}}function por(e){let t=new Set(e);return Sx(Cu.ENUM,(n,{allowUnrecognizedEnumValues:i,breadcrumbsPrefix:o=[]}={})=>typeof n!="string"?{ok:!1,errors:[{path:o,message:gd(n,"string")}]}:!t.has(n)&&!i?{ok:!1,errors:[{path:o,message:gd(n,"enum")}]}:{ok:!0,value:n})()}function cgs(e){let t=oli(e);return{...t,...Hd(t)}}function oli(e){return{parse:(t,r)=>i6e(e).parse(t,r),json:(t,r)=>i6e(e).json(t,r),getType:()=>i6e(e).getType()}}function i6e(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function sli(e){return Object.entries(e)}function $vt(e,t){let r=new Set(t);return Object.entries(e).reduce((n,[i,o])=>(r.has(i)&&(n[i]=o),n),{})}function Use(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===null?!0:Object.getPrototypeOf(t)===null}function Hvt(e){return Object.keys(e)}function ugs(e,t){let r=[],n=[];for(let i of e)t(i)?r.push(i):n.push(i);return[r,n]}var wAl=Object.prototype.hasOwnProperty;function sq(e){return{withParsedProperties:t=>ali(e,t)}}function ali(e,t){let r={parse:(n,i)=>{let o=e.parse(n,i);if(!o.ok)return o;let s={};for(let a in t)if(wAl.call(t,a)){let c=t[a];s[a]=typeof c=="function"?c(o.value):c}return{ok:!0,value:{...o.value,...s}}},json:(n,i)=>{if(!Use(n))return{ok:!1,errors:[{path:i?.breadcrumbsPrefix??[],message:gd(n,"object")}]};let o=new Set(Object.keys(t)),s=$vt(n,Object.keys(n).filter(a=>!o.has(a)));return e.json(s,i)},getType:()=>e.getType()};return{...r,...Hd(r),...sq(r)}}function lgs(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function zse(e){return e.isProperty}var CAl=Object.prototype.hasOwnProperty;function dor(e){let t;function r(){if(t==null){t={};for(let[d,f]of sli(e)){let m=zse(f)?f.rawKey:d,h=zse(f)?f.valueSchema:f;t[m]={rawKey:m,parsedKey:d,valueSchema:h}}}return t}let n,i,o,s;function a(){if(n==null){n=[],i=[];for(let[d,f]of sli(e)){let m=zse(f)?f.rawKey:d,h=zse(f)?f.valueSchema:f;xAl(h)&&(n.push(m),i.push(d))}o=new Set(n),s=new Set(i)}return n}function c(){return i==null&&a(),i}function u(){return o==null&&a(),o}function l(){return s==null&&a(),s}let p={_getRawProperties:()=>Object.entries(e).map(([d,f])=>zse(f)?f.rawKey:d),_getParsedProperties:()=>Hvt(e),parse:(d,f)=>{let m=f?.breadcrumbsPrefix??[];return pgs({value:d,requiredKeys:a(),requiredKeysSet:u(),getProperty:h=>{let g=r()[h];if(g!=null)return{transformedKey:g.parsedKey,transform:A=>{let b=[...m,h];return g.valueSchema.parse(A,{...f,breadcrumbsPrefix:b})}}},unrecognizedObjectKeys:f?.unrecognizedObjectKeys,skipValidation:f?.skipValidation,breadcrumbsPrefix:m,omitUndefined:f?.omitUndefined})},json:(d,f)=>{let m=f?.breadcrumbsPrefix??[];return pgs({value:d,requiredKeys:c(),requiredKeysSet:l(),getProperty:h=>{let g=e[h];if(g!=null)return zse(g)?{transformedKey:g.rawKey,transform:A=>{let b=[...m,h];return g.valueSchema.json(A,{...f,breadcrumbsPrefix:b})}}:{transformedKey:h,transform:A=>{let b=[...m,h];return g.json(A,{...f,breadcrumbsPrefix:b})}}},unrecognizedObjectKeys:f?.unrecognizedObjectKeys,skipValidation:f?.skipValidation,breadcrumbsPrefix:m,omitUndefined:f?.omitUndefined})},getType:()=>Cu.OBJECT};return{..._x(p),...Hd(p),...sq(p),...ROe(p)}}function pgs({value:e,requiredKeys:t,requiredKeysSet:r,getProperty:n,unrecognizedObjectKeys:i="fail",skipValidation:o=!1,breadcrumbsPrefix:s=[]}){if(!Use(e))return{ok:!1,errors:[{path:s,message:gd(e,"object")}]};let a=t.length,c=[],u={};for(let l in e){if(!CAl.call(e,l))continue;let p=e[l],d=n(l);if(d!=null){a>0&&r.has(l)&&a--;let f=d.transform(p);f.ok?u[d.transformedKey]=f.value:(u[l]=p,c.push(...f.errors))}else switch(i){case"fail":c.push({path:[...s,l],message:`Unexpected key "${l}"`});break;case"strip":break;case"passthrough":u[l]=p;break}}if(a>0)for(let l of t)l in e||c.push({path:s,message:`Missing required key "${l}"`});return c.length===0||o?{ok:!0,value:u}:{ok:!1,errors:c}}function ROe(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(n,i)=>fgs({extensionKeys:t._getRawProperties(),value:n,transformBase:o=>e.parse(o,i),transformExtension:o=>t.parse(o,i),breadcrumbsPrefix:i?.breadcrumbsPrefix}),json:(n,i)=>fgs({extensionKeys:t._getParsedProperties(),value:n,transformBase:o=>e.json(o,i),transformExtension:o=>t.json(o,i),breadcrumbsPrefix:i?.breadcrumbsPrefix}),getType:()=>Cu.OBJECT};return{...r,...Hd(r),...sq(r),...ROe(r)}},passthrough:()=>{let t=new Set(e._getRawProperties()),r=new Set(e._getParsedProperties()),n={_getParsedProperties:()=>e._getParsedProperties(),_getRawProperties:()=>e._getRawProperties(),parse:(i,o)=>{let s=e.parse(i,{...o,unrecognizedObjectKeys:"passthrough"});if(!s.ok)return s;let a={};if(typeof i=="object"&&i!=null)for(let[c,u]of Object.entries(i))t.has(c)||(a[c]=u);return{ok:!0,value:{...a,...s.value}}},json:(i,o)=>{let s=e.json(i,{...o,unrecognizedObjectKeys:"passthrough"});if(!s.ok)return s;let a={};if(typeof i=="object"&&i!=null)for(let[c,u]of Object.entries(i))r.has(c)||(a[c]=u);return{ok:!0,value:{...a,...s.value}}},getType:()=>Cu.OBJECT};return{...n,...Hd(n),...sq(n),...ROe(n)}}}}function fgs({extensionKeys:e,value:t,transformBase:r,transformExtension:n,breadcrumbsPrefix:i=[]}){if(!Use(t))return{ok:!1,errors:[{path:i,message:gd(t,"object")}]};let o=new Set(e),[s,a]=ugs(Hvt(t),l=>o.has(l)),c=r($vt(t,a)),u=n($vt(t,s));return c.ok&&u.ok?{ok:!0,value:{...c.value,...u.value}}:{ok:!1,errors:[...c.ok?[]:c.errors,...u.ok?[]:u.errors]}}function xAl(e){return!_Al(e)}function _Al(e){switch(e.getType()){case Cu.ANY:case Cu.UNKNOWN:case Cu.OPTIONAL:case Cu.OPTIONAL_NULLABLE:return!0;default:return!1}}function dgs(e){return dor(e)}function mgs(e){let t={...oli(e),_getRawProperties:()=>i6e(e)._getRawProperties(),_getParsedProperties:()=>i6e(e)._getParsedProperties()};return{...t,...Hd(t),...sq(t),...ROe(t)}}function mor(e){let t={parse:(r,n)=>hgs(r,(i,o)=>e.parse(i,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`[${o}]`]})),json:(r,n)=>hgs(r,(i,o)=>e.json(i,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`[${o}]`]})),getType:()=>Cu.LIST};return{..._x(t),...Hd(t)}}function hgs(e,t){if(!Array.isArray(e))return{ok:!1,errors:[{message:gd(e,"list"),path:[]}]};let r=[],n=[];for(let i=0;i<e.length;i++){let o=t(e[i],i);o.ok?r.push(o.value):n.push(...o.errors)}return n.length===0?{ok:!0,value:r}:{ok:!1,errors:n}}function ggs(e){return Sx(Cu.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:n=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:n,message:gd(r,`${e.toString()}`)}]})()}function Ags(e){return Sx(Cu.STRING_LITERAL,(r,{breadcrumbsPrefix:n=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:n,message:gd(r,`"${e}"`)}]})()}var ygs=Sx(Cu.ANY,e=>({ok:!0,value:e}));var bgs=Sx(Cu.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:gd(e,"boolean")}]});var Egs=Sx(Cu.NEVER,(e,{breadcrumbsPrefix:t=[]}={})=>({ok:!1,errors:[{path:t,message:"Expected never"}]}));var vgs=Sx(Cu.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:gd(e,"number")}]});var Igs=Sx(Cu.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:gd(e,"string")}]});var wgs=Sx(Cu.UNKNOWN,e=>({ok:!0,value:e}));var SAl=Object.prototype.hasOwnProperty;function xgs(e,t){let r={parse:(n,i)=>Cgs({value:n,isKeyNumeric:e.getType()===Cu.NUMBER,transformKey:o=>e.parse(o,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${o} (key)`]}),transformValue:(o,s)=>t.parse(o,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${s}`]}),breadcrumbsPrefix:i?.breadcrumbsPrefix}),json:(n,i)=>Cgs({value:n,isKeyNumeric:e.getType()===Cu.NUMBER,transformKey:o=>e.json(o,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${o} (key)`]}),transformValue:(o,s)=>t.json(o,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${s}`]}),breadcrumbsPrefix:i?.breadcrumbsPrefix}),getType:()=>Cu.RECORD};return{..._x(r),...Hd(r)}}function Cgs({value:e,isKeyNumeric:t,transformKey:r,transformValue:n,breadcrumbsPrefix:i=[]}){if(!Use(e))return{ok:!1,errors:[{path:i,message:gd(e,"object")}]};let o={},s=[];for(let a in e){if(!SAl.call(e,a))continue;let c=e[a];if(c===void 0)continue;let u=a;if(t){let d=a.length>0?Number(a):NaN;Number.isNaN(d)||(u=d)}let l=r(u),p=n(c,u);l.ok&&p.ok?o[l.value]=p.value:(l.ok||s.push(...l.errors),p.ok||s.push(...p.errors))}return s.length===0?{ok:!0,value:o}:{ok:!1,errors:s}}function _gs(e){let t=mor(e),r={parse:(n,i)=>{let o=t.parse(n,i);return o.ok?{ok:!0,value:new Set(o.value)}:o},json:(n,i)=>n instanceof Set?t.json([...n],i):{ok:!1,errors:[{path:i?.breadcrumbsPrefix??[],message:gd(n,"Set")}]},getType:()=>Cu.SET};return{..._x(r),...Hd(r)}}function Bgs(e){let t={parse:(r,n)=>Sgs((i,o)=>i.parse(r,o),e,n),json:(r,n)=>Sgs((i,o)=>i.json(r,o),e,n),getType:()=>Cu.UNDISCRIMINATED_UNION};return{..._x(t),...Hd(t)}}function Sgs(e,t,r){let n=[];for(let[i,o]of t.entries()){let s=e(o,{...r,skipValidation:!1});if(s.ok)return s;for(let a of s.errors)n.push({path:a.path,message:`[Variant ${i}] ${a.message}`})}return{ok:!1,errors:n}}function Tgs(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}var BAl=Object.prototype.hasOwnProperty;function Pgs(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,n=typeof e=="string"?e:e.parsedDiscriminant,i=por(Hvt(t)),o={parse:(s,a)=>Ogs({value:s,discriminant:r,transformedDiscriminant:n,transformDiscriminantValue:c=>i.parse(c,{allowUnrecognizedEnumValues:a?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...a?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:c=>t[c],allowUnrecognizedUnionMembers:a?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(c,u)=>u.parse(c,a),breadcrumbsPrefix:a?.breadcrumbsPrefix}),json:(s,a)=>Ogs({value:s,discriminant:n,transformedDiscriminant:r,transformDiscriminantValue:c=>i.json(c,{allowUnrecognizedEnumValues:a?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...a?.breadcrumbsPrefix??[],n]}),getAdditionalPropertiesSchema:c=>t[c],allowUnrecognizedUnionMembers:a?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(c,u)=>u.json(c,a),breadcrumbsPrefix:a?.breadcrumbsPrefix}),getType:()=>Cu.UNION};return{..._x(o),...Hd(o),...sq(o)}}function Ogs({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:n,getAdditionalPropertiesSchema:i,allowUnrecognizedUnionMembers:o=!1,transformAdditionalProperties:s,breadcrumbsPrefix:a=[]}){if(!Use(e))return{ok:!1,errors:[{path:a,message:gd(e,"object")}]};let c=e[t],u={};for(let f in e)BAl.call(e,f)&&f!==t&&(u[f]=e[f]);if(c==null)return{ok:!1,errors:[{path:a,message:`Missing discriminant ("${t}")`}]};let l=n(c);if(!l.ok)return{ok:!1,errors:l.errors};let p=i(l.value);if(p==null)return o?{ok:!0,value:{[r]:l.value,...u}}:{ok:!1,errors:[{path:[...a,t],message:"Unexpected discriminant value"}]};let d=s(u,p);return d.ok?{ok:!0,value:{[r]:c,...d.value}}:d}var hor=J.objectWithoutOptionalProperties({usernameVariableName:J.string().optional(),usernameEnvVar:J.string().optional(),passwordVariableName:J.string().optional(),passwordEnvVar:J.string().optional()});var gor=J.objectWithoutOptionalProperties({tokenVariableName:J.string().optional(),tokenEnvVar:J.string().optional()});var Aor=J.objectWithoutOptionalProperties({typeName:J.string()});var yor=J.union("type",{protobuf:Aor}).transform({transform:e=>e.type==="protobuf"?t6e.protobuf(e):e,untransform:({_visit:e,...t})=>t});var bor=J.objectWithoutOptionalProperties({headerName:J.string(),prefix:J.string().optional(),headerVariableName:J.string().optional(),headerEnvVar:J.string().optional()});var Eor=J.objectWithoutOptionalProperties({type:J.stringLiteral("namespace"),name:J.string()});var vor=J.string();var Ior=J.enum_(["GenerallyAvailable","Beta","Deprecated"]);var us=J.objectWithoutOptionalProperties({availability:Ior.optional()});var mn=J.objectWithoutOptionalProperties({description:J.string().optional()});var Uf=J.objectWithoutOptionalProperties({inline:J.boolean().optional()});var Nc=J.objectWithoutOptionalProperties({nameOverride:J.string().optional(),generatedName:J.string()});var oc=J.objectWithoutOptionalProperties({namespace:J.string().optional()});var wor=J.undiscriminatedUnion([J.string(),Eor]);var _he=J.list(wor);var xu=J.objectWithoutOptionalProperties({groupName:_he.optional()});var Cor=J.objectWithoutOptionalProperties({file:J.string()});var xor=J.objectWithoutOptionalProperties({file:J.string()});var _or=J.union("type",{openapi:Cor,protobuf:xor}).transform({transform:e=>{switch(e.type){case"openapi":return lT.openapi(e);case"protobuf":return lT.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var $o=J.objectWithoutOptionalProperties({source:_or.optional()});var _u=J.objectWithoutOptionalProperties({title:J.string().optional()});var Sor=J.objectWithoutOptionalProperties({snake:J.string().optional(),camel:J.string().optional(),screamingSnake:J.string().optional(),pascal:J.string().optional()});var She=J.objectWithoutOptionalProperties({nameOverride:J.string().optional(),generatedName:J.string(),value:J.string(),casing:Sor.optional()}).extend(mn).extend(us);var o6e=J.objectWithoutOptionalProperties({default:She.optional(),values:J.list(She)}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend($o).extend(_u).extend(Uf);var Bor=J.objectWithoutOptionalProperties({scopesEnum:o6e.optional()});var Tor=J.objectWithoutOptionalProperties({queryParameterName:J.string()});var KP=J.string();var Oor=J.union("type",{basic:hor,bearer:gor,header:bor,query:Tor,oauth:Bor}).transform({transform:e=>{switch(e.type){case"basic":return Ix.basic(e);case"bearer":return Ix.bearer(e);case"header":return Ix.header(e);case"query":return Ix.query(e);case"oauth":return Ix.oauth(e);default:return e}},untransform:({_visit:e,...t})=>t});var Bhe=J.string();var Por=J.objectWithoutOptionalProperties({id:J.string(),default:J.string().optional(),values:J.list(J.string()).optional()});var Kvt=J.objectWithoutOptionalProperties({name:J.string().optional(),url:J.string(),audiences:J.list(J.string()).optional(),defaultUrl:J.string().optional(),urlTemplate:J.string().optional(),variables:J.list(Por).optional()}).extend(mn);var w$=J.number();var JP=J.string();var Dor=J.objectWithoutOptionalProperties({id:JP}).extend(mn);var Bx=J.objectWithoutOptionalProperties({encoding:yor.optional()});var C$=J.objectWithoutOptionalProperties({sdkMethodName:J.string().optional()});var YU=J.objectWithoutOptionalProperties({statusCode:w$.optional()});var uli={};te(uli,{FullExample:()=>qm,FullObjectExample:()=>kor,FullOneOfExample:()=>Nor,KeyValuePair:()=>Qor,LiteralExample:()=>Ror,NullExample:()=>For,PrimitiveExample:()=>s6e,PropertyKey:()=>a6e});var Ror=J.union("type",{boolean:J.object({value:J.boolean()}),string:J.object({value:J.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return Che.boolean(e.value);case"string":return Che.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var For=J.objectWithoutOptionalProperties({});var s6e=J.union("type",{int:J.object({value:J.number()}),int64:J.object({value:J.number()}),uint:J.object({value:J.number()}),uint64:J.object({value:J.number()}),float:J.object({value:J.number()}),double:J.object({value:J.number()}),string:J.object({value:J.string()}),datetime:J.object({value:J.string()}),datetimeRfc2822:J.object({value:J.string()}),date:J.object({value:J.string()}),base64:J.object({value:J.string()}),boolean:J.object({value:J.boolean()})}).transform({transform:e=>{switch(e.type){case"int":return hs.int(e.value);case"int64":return hs.int64(e.value);case"uint":return hs.uint(e.value);case"uint64":return hs.uint64(e.value);case"float":return hs.float(e.value);case"double":return hs.double(e.value);case"string":return hs.string(e.value);case"datetime":return hs.datetime(e.value);case"datetimeRfc2822":return hs.datetimeRfc2822(e.value);case"date":return hs.date(e.value);case"base64":return hs.base64(e.value);case"boolean":return hs.boolean(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var qm=J.union("type",{primitive:J.object({value:s6e}),object:J.lazyObject(()=>kor),array:J.object({value:J.list(J.lazy(()=>qm))}),map:J.object({value:J.list(J.lazyObject(()=>Qor))}),enum:J.object({value:J.string()}),literal:J.object({value:Ror}),oneOf:J.object({value:J.lazy(()=>Nor)}),null:For,unknown:J.object({value:J.lazy(()=>qm)})}).transform({transform:e=>{switch(e.type){case"primitive":return lc.primitive(e.value);case"object":return lc.object(e);case"array":return lc.array(e.value);case"map":return lc.map(e.value);case"enum":return lc.enum(e.value);case"literal":return lc.literal(e.value);case"oneOf":return lc.oneOf(e.value);case"null":return lc.null(e);case"unknown":return lc.unknown(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var a6e=J.string();var kor=J.objectWithoutOptionalProperties({properties:J.record(a6e,J.lazy(()=>qm))});var Nor=J.union("type",{discriminated:J.object({value:J.record(a6e,J.lazy(()=>qm))}),undiscriminated:J.object({value:J.lazy(()=>qm)})}).transform({transform:e=>{switch(e.type){case"discriminated":return whe.discriminated(e.value);case"undiscriminated":return whe.undiscriminated(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Qor=J.objectWithoutOptionalProperties({key:s6e,value:J.lazy(()=>qm)});var lli={};te(lli,{AllOfPropertyConflict:()=>c6e,ArraySchema:()=>jor,AsymmetricAlgorithm:()=>Mor,AsymmetricWebhookSignatureVerification:()=>Uor,Availability:()=>Ior,BooleanSchema:()=>zor,BytesResponse:()=>p6e,CasingOverrides:()=>Sor,CommonProperty:()=>Vor,CursorPagination:()=>qor,CustomCodeSample:()=>Hor,CustomCodeSampleLanguage:()=>Gor,CustomCodeSampleSdk:()=>$or,CustomPagination:()=>Kor,DiscriminatedOneOfSchema:()=>Jor,DiscriminatorContext:()=>f6e,DoubleSchema:()=>Yor,Endpoint:()=>msr,EndpointExample:()=>h6e,EndpointResponseExample:()=>esr,EndpointSdkName:()=>x$,EndpointSecurity:()=>g6e,EnumSchema:()=>o6e,EnumValue:()=>She,ErrorExample:()=>nsr,FernExample:()=>Xor,FileResponse:()=>C6e,FileSchema:()=>psr,FormUrlEncodedRequest:()=>csr,FullEndpointExample:()=>rsr,GlobalHeader:()=>hsr,GlobalSecurity:()=>gsr,Header:()=>The,HeaderExample:()=>d6e,HmacWebhookSignatureVerification:()=>Esr,HttpEndpointServer:()=>A6e,HttpError:()=>isr,HttpMethod:()=>y6e,IdempotencyHeader:()=>vsr,IntSchema:()=>Isr,JsonRequest:()=>usr,JsonResponse:()=>x6e,LiteralSchema:()=>B6e,LiteralSchemaValue:()=>wsr,LongSchema:()=>Csr,MapSchema:()=>Ssr,MultipartFormDataWebhookPayload:()=>Bsr,MultipartRequest:()=>I6e,MultipartRequestProperty:()=>Ohe,MultipartRequestPropertyEncoding:()=>lsr,MultipartSchema:()=>fsr,NullableSchema:()=>Tsr,ObjectProperty:()=>Osr,ObjectPropertyConflictInfo:()=>T6e,ObjectSchema:()=>Psr,OctetStreamRequest:()=>w6e,OffsetPagination:()=>osr,OneOfSchema:()=>Dsr,OpenApiIntermediateRepresentation:()=>Dgs,OptionalSchema:()=>Gsr,Pagination:()=>b6e,PathPagination:()=>ssr,PathParameter:()=>E6e,PathParameterExample:()=>tsr,PrimitiveSchema:()=>Dhe,PrimitiveSchemaValue:()=>_sr,QueryParameter:()=>v6e,QueryParameterExample:()=>m6e,ReferencedSchema:()=>_$,Request:()=>dsr,Response:()=>_6e,RetriesConfiguration:()=>S6e,Schema:()=>$u,Schemas:()=>Fsr,SdkGroupInfo:()=>ksr,StreamingResponseExample:()=>Zor,StringSchema:()=>xsr,SupportedSdkLanguage:()=>Wor,Tags:()=>Nsr,TextResponse:()=>Phe,UnDiscriminatedOneOfSchema:()=>Rsr,UnknownSchema:()=>Wsr,UriPagination:()=>asr,Webhook:()=>Qsr,WebhookExampleCall:()=>O6e,WebhookHttpMethod:()=>P6e,WebhookPayloadComponent:()=>Asr,WebhookPayloadFormat:()=>ysr,WebhookSignatureAlgorithm:()=>bsr,WebhookSignatureEncoding:()=>u6e,WebhookSignatureVerification:()=>D6e,WebhookTimestamp:()=>l6e,WebhookTimestampFormat:()=>Lor,WebsocketChannel:()=>qsr,WebsocketHandshake:()=>jsr,WebsocketMessageExample:()=>zsr,WebsocketMessageOrigin:()=>Msr,WebsocketMessageSchema:()=>Lsr,WebsocketServer:()=>Usr,WebsocketSessionExample:()=>Vsr});var c6e=J.objectWithoutOptionalProperties({propertyKey:J.string(),allOfSchemaIds:J.list(KP),conflictingTypeSignatures:J.boolean()});var jor=J.objectWithoutOptionalProperties({value:J.lazy(()=>$u),minItems:J.number().optional(),maxItems:J.number().optional()}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(_u).extend(Uf);var Mor=J.enum_(["rsa-sha256","rsa-sha384","rsa-sha512","ecdsa-sha256","ecdsa-sha384","ecdsa-sha512","ed25519"]);var u6e=J.enum_(["base64","hex"]);var Lor=J.enum_(["unix-seconds","unix-millis","iso8601"]);var l6e=J.objectWithoutOptionalProperties({header:J.string(),format:Lor.optional(),tolerance:J.number().optional()});var Uor=J.objectWithoutOptionalProperties({header:J.string(),asymmetricAlgorithm:Mor,encoding:u6e.optional(),signaturePrefix:J.string().optional(),jwksUrl:J.string().optional(),keyIdHeader:J.string().optional(),timestamp:l6e.optional()});var zor=J.objectWithoutOptionalProperties({default:J.boolean().optional()});var p6e=J.objectWithoutOptionalProperties({}).extend(mn).extend($o).extend(YU);var Vor=J.objectWithoutOptionalProperties({key:J.string(),schema:J.lazy(()=>$u)});var qor=J.objectWithoutOptionalProperties({cursor:J.string(),nextCursor:J.property("next_cursor",J.string()),results:J.string()});var Gor=J.objectWithoutOptionalProperties({name:J.string().optional(),language:J.string(),code:J.string(),install:J.string().optional()}).extend(mn);var Wor=J.enum_(["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm"]);var $or=J.objectWithoutOptionalProperties({name:J.string().optional(),sdk:Wor,code:J.string()}).extend(mn);var Hor=J.union("type",{language:Gor,sdk:$or}).transform({transform:e=>{switch(e.type){case"language":return E$.language(e);case"sdk":return E$.sdk(e);default:return e}},untransform:({_visit:e,...t})=>t});var Kor=J.objectWithoutOptionalProperties({results:J.string()});var f6e=J.enum_(["data","protocol"]);var Jor=J.objectWithoutOptionalProperties({discriminantProperty:J.string(),discriminantPropertyNameOverride:J.string().optional(),discriminatorContext:f6e.optional(),commonProperties:J.list(J.lazyObject(()=>Vor)),schemas:J.record(J.string(),J.lazy(()=>$u))}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(Bx).extend($o).extend(_u).extend(Uf);var Yor=J.objectWithoutOptionalProperties({default:J.number().optional(),minimum:J.number().optional(),maximum:J.number().optional(),exclusiveMinimum:J.boolean().optional(),exclusiveMaximum:J.boolean().optional(),multipleOf:J.number().optional()});var Xor=J.unknown();var Zor=J.objectWithoutOptionalProperties({sse:J.boolean(),events:J.list(J.lazy(()=>qm))});var esr=J.union("type",{withStreaming:Zor,withoutStreaming:J.object({value:J.lazy(()=>qm)})}).transform({transform:e=>{switch(e.type){case"withStreaming":return JU.withStreaming(e);case"withoutStreaming":return JU.withoutStreaming(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var d6e=J.objectWithoutOptionalProperties({name:J.string(),value:J.lazy(()=>qm)});var tsr=J.objectWithoutOptionalProperties({name:J.string(),parameterNameOverride:J.string().optional(),value:J.lazy(()=>qm)});var m6e=J.objectWithoutOptionalProperties({name:J.string(),value:J.lazy(()=>qm)});var rsr=J.objectWithoutOptionalProperties({name:J.string().optional(),pathParameters:J.list(tsr).optional(),queryParameters:J.list(m6e).optional(),headers:J.list(d6e).optional(),request:J.lazy(()=>qm).optional(),response:esr.optional(),codeSamples:J.list(Hor)}).extend(mn);var h6e=J.union("type",{unknown:J.object({value:Xor}),full:rsr}).transform({transform:e=>{switch(e.type){case"unknown":return KU.unknown(e.value);case"full":return KU.full(e);default:return e}},untransform:({_visit:e,...t})=>t});var x$=J.objectWithoutOptionalProperties({groupName:_he,methodName:J.string()});var g6e=J.list(J.record(Bhe,J.list(J.string())));var The=J.objectWithoutOptionalProperties({name:J.string(),schema:J.lazy(()=>$u),env:J.string().optional(),parameterNameOverride:J.string().optional()}).extend(mn).extend(us).extend($o);var A6e=J.objectWithoutOptionalProperties({name:J.string().optional(),url:J.string().optional(),audiences:J.list(J.string()).optional()});var nsr=J.objectWithoutOptionalProperties({name:J.string().optional(),description:J.string().optional(),example:J.lazy(()=>qm)});var isr=J.objectWithoutOptionalProperties({schema:J.lazy(()=>$u).optional(),examples:J.list(nsr).optional()}).extend(mn).extend(Nc).extend($o);var y6e=J.enum_(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS","TRACE"]);var osr=J.objectWithoutOptionalProperties({offset:J.string(),results:J.string(),step:J.string().optional(),hasNextPage:J.string().optional()});var ssr=J.objectWithoutOptionalProperties({nextPath:J.string(),results:J.string()});var asr=J.objectWithoutOptionalProperties({nextUri:J.string(),results:J.string()});var b6e=J.union("type",{cursor:qor,offset:osr,custom:Kor,uri:asr,path:ssr}).transform({transform:e=>{switch(e.type){case"cursor":return Hw.cursor(e);case"offset":return Hw.offset(e);case"custom":return Hw.custom(e);case"uri":return Hw.uri(e);case"path":return Hw.path(e);default:return e}},untransform:({_visit:e,...t})=>t});var E6e=J.objectWithoutOptionalProperties({name:J.string(),schema:J.lazy(()=>$u),variableReference:J.string().optional(),parameterNameOverride:J.string().optional()}).extend(mn).extend(us).extend($o);var v6e=J.objectWithoutOptionalProperties({name:J.string(),schema:J.lazy(()=>$u),parameterNameOverride:J.string().optional(),explode:J.boolean().optional()}).extend(mn).extend(us).extend($o);var csr=J.objectWithoutOptionalProperties({schema:J.lazy(()=>$u),contentType:J.string().optional(),additionalProperties:J.boolean()}).extend(mn).extend($o);var usr=J.objectWithoutOptionalProperties({schema:J.lazy(()=>$u),contentType:J.string().optional(),additionalProperties:J.boolean()}).extend(mn).extend($o);var lsr=J.enum_(["json","form"]);var psr=J.objectWithoutOptionalProperties({isOptional:J.boolean(),isArray:J.boolean()}).extend(mn);var fsr=J.union("type",{file:psr,json:J.object({value:J.lazy(()=>$u)})}).transform({transform:e=>{switch(e.type){case"file":return v$.file(e);case"json":return v$.json(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Ohe=J.objectWithoutOptionalProperties({key:J.string(),schema:fsr,contentType:J.string().optional(),exploded:J.boolean().optional(),encoding:lsr.optional()}).extend(mn);var I6e=J.objectWithoutOptionalProperties({name:J.string().optional(),properties:J.list(Ohe)}).extend(mn).extend($o);var w6e=J.objectWithoutOptionalProperties({contentType:J.string().optional()}).extend(mn).extend($o);var dsr=J.union("type",{octetStream:w6e,multipart:I6e,json:usr,formUrlEncoded:csr}).transform({transform:e=>{switch(e.type){case"octetStream":return oq.octetStream(e);case"multipart":return oq.multipart(e);case"json":return oq.json(e);case"formUrlEncoded":return oq.formUrlEncoded(e);default:return e}},untransform:({_visit:e,...t})=>t});var C6e=J.objectWithoutOptionalProperties({}).extend(mn).extend($o).extend(YU);var x6e=J.objectWithoutOptionalProperties({schema:J.lazy(()=>$u),responseProperty:J.string().optional(),terminator:J.string().optional()}).extend(mn).extend($o).extend(YU);var Phe=J.objectWithoutOptionalProperties({}).extend(mn).extend($o).extend(YU);var _6e=J.union("type",{file:C6e,json:x6e,text:Phe,bytes:p6e,streamingSse:x6e,streamingText:Phe,streamingJson:x6e}).transform({transform:e=>{switch(e.type){case"file":return XS.file(e);case"json":return XS.json(e);case"text":return XS.text(e);case"bytes":return XS.bytes(e);case"streamingSse":return XS.streamingSse(e);case"streamingText":return XS.streamingText(e);case"streamingJson":return XS.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var S6e=J.union("type",{disabled:J.object({value:J.boolean().optional()})}).transform({transform:e=>e.type==="disabled"?qvt.disabled(e.value):e,untransform:({_visit:e,...t})=>t});var msr=J.objectWithoutOptionalProperties({authed:J.boolean(),security:g6e.optional(),internal:J.boolean().optional(),idempotent:J.boolean().optional(),method:y6e,audiences:J.list(J.string()),path:J.string(),summary:J.string().optional(),operationId:J.string().optional(),tags:J.list(JP),pathParameters:J.list(E6e),queryParameters:J.list(v6e),headers:J.list(The),sdkName:x$.optional(),generatedRequestName:J.string(),requestNameOverride:J.string().optional(),request:dsr.optional(),response:_6e.optional(),errors:J.record(w$,isr),servers:J.list(A6e),examples:J.list(h6e),pagination:b6e.optional(),retries:S6e.optional()}).extend(mn).extend(us).extend($o).extend(oc);var hsr=J.objectWithoutOptionalProperties({header:J.string(),name:J.string().optional(),optional:J.boolean().optional(),env:J.string().optional(),schema:J.lazy(()=>$u).optional()});var gsr=J.list(J.record(Bhe,J.list(J.string())));var Asr=J.enum_(["body","timestamp","notification-url","message-id"]);var ysr=J.objectWithoutOptionalProperties({components:J.list(Asr),delimiter:J.string().optional()});var bsr=J.enum_(["sha256","sha1","sha384","sha512"]);var Esr=J.objectWithoutOptionalProperties({header:J.string(),algorithm:bsr.optional(),encoding:u6e.optional(),signaturePrefix:J.string().optional(),payloadFormat:ysr.optional(),timestamp:l6e.optional()});var vsr=J.objectWithoutOptionalProperties({header:J.string(),name:J.string().optional(),env:J.string().optional(),schema:J.lazy(()=>$u).optional()});var Isr=J.objectWithoutOptionalProperties({default:J.number().optional(),minimum:J.number().optional(),maximum:J.number().optional(),exclusiveMinimum:J.boolean().optional(),exclusiveMaximum:J.boolean().optional(),multipleOf:J.number().optional()});var wsr=J.union("type",{boolean:J.object({value:J.boolean()}),string:J.object({value:J.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return fA.boolean(e.value);case"string":return fA.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var B6e=J.objectWithoutOptionalProperties({value:wsr}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(_u);var Csr=J.objectWithoutOptionalProperties({default:J.number().optional()});var xsr=J.objectWithoutOptionalProperties({default:J.string().optional(),pattern:J.string().optional(),format:J.string().optional(),minLength:J.number().optional(),maxLength:J.number().optional()});var _sr=J.union("type",{int:Isr,int64:Csr,uint:J.object({}),uint64:J.object({}),float:J.object({}),double:Yor,string:xsr,datetime:J.object({}),datetimeRfc2822:J.object({}),date:J.object({}),base64:J.object({}),boolean:zor}).transform({transform:e=>{switch(e.type){case"int":return ol.int(e);case"int64":return ol.int64(e);case"uint":return ol.uint();case"uint64":return ol.uint64();case"float":return ol.float();case"double":return ol.double(e);case"string":return ol.string(e);case"datetime":return ol.datetime();case"datetimeRfc2822":return ol.datetimeRfc2822();case"date":return ol.date();case"base64":return ol.base64();case"boolean":return ol.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var Dhe=J.objectWithoutOptionalProperties({schema:_sr}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(_u);var Ssr=J.objectWithoutOptionalProperties({key:Dhe,value:J.lazy(()=>$u),minProperties:J.number().optional(),maxProperties:J.number().optional()}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(Bx).extend(_u).extend(Uf);var Bsr=J.objectWithoutOptionalProperties({name:J.string().optional(),properties:J.list(Ohe)}).extend(mn).extend($o);var Tsr=J.objectWithoutOptionalProperties({value:J.lazy(()=>$u)}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(_u).extend(Uf);var T6e=J.objectWithoutOptionalProperties({differentSchema:J.boolean()});var Osr=J.objectWithoutOptionalProperties({key:J.string(),schema:J.lazy(()=>$u),readonly:J.boolean().optional(),writeonly:J.boolean().optional(),conflict:J.record(KP,T6e),generatedName:J.string(),nameOverride:J.string().optional(),audiences:J.list(J.string())}).extend(us);var _$=J.objectWithoutOptionalProperties({schema:KP}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend($o).extend(_u);var Psr=J.objectWithoutOptionalProperties({allOf:J.list(_$),properties:J.list(J.lazyObject(()=>Osr)),allOfPropertyConflicts:J.list(c6e),additionalProperties:J.boolean(),minProperties:J.number().optional(),maxProperties:J.number().optional()}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(Bx).extend($o).extend(_u).extend(Uf);var Dsr=J.union("type",{discriminated:J.lazyObject(()=>Jor),undiscriminated:J.lazyObject(()=>Rsr)}).transform({transform:e=>{switch(e.type){case"discriminated":return I$.discriminated(e);case"undiscriminated":return I$.undiscriminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var Fsr=J.objectWithoutOptionalProperties({rootSchemas:J.record(KP,J.lazy(()=>$u)),namespacedSchemas:J.record(vor,J.record(KP,J.lazy(()=>$u)))});var ksr=J.objectWithoutOptionalProperties({summary:J.string().optional(),description:J.string().optional()});var Nsr=J.objectWithoutOptionalProperties({tagsById:J.record(JP,Dor),orderedTagIds:J.list(JP).optional()});var O6e=J.objectWithoutOptionalProperties({name:J.string().optional(),payload:J.lazy(()=>qm)}).extend(mn);var P6e=J.enum_(["GET","POST"]);var D6e=J.union("type",{hmac:Esr,asymmetric:Uor}).transform({transform:e=>{switch(e.type){case"hmac":return DOe.hmac(e);case"asymmetric":return DOe.asymmetric(e);default:return e}},untransform:({_visit:e,...t})=>t});var Qsr=J.objectWithoutOptionalProperties({audiences:J.list(J.string()),sdkName:x$.optional(),method:P6e,summary:J.string().optional(),operationId:J.string(),tags:J.list(JP),headers:J.list(The),generatedPayloadName:J.string(),payload:J.lazy(()=>$u),multipartFormData:Bsr.optional(),response:_6e.optional(),signatureVerification:D6e.optional(),examples:J.list(O6e)}).extend(mn).extend($o).extend(oc);var jsr=J.objectWithoutOptionalProperties({queryParameters:J.list(v6e),headers:J.list(The),pathParameters:J.list(E6e)});var Msr=J.enum_(["client","server"]);var Lsr=J.objectWithoutOptionalProperties({name:J.string(),origin:Msr,body:J.lazy(()=>$u),methodName:J.string().optional()});var Usr=J.objectWithoutOptionalProperties({name:J.string(),url:J.string()});var zsr=J.objectWithoutOptionalProperties({messageType:J.string(),payload:J.lazy(()=>qm)}).extend(mn);var Vsr=J.objectWithoutOptionalProperties({name:J.string().optional(),queryParameters:J.list(m6e).optional(),headers:J.list(d6e).optional(),messages:J.list(zsr)}).extend(mn);var qsr=J.objectWithoutOptionalProperties({audiences:J.list(J.string()),path:J.string(),groupName:_he,summary:J.string().optional(),connectMethodName:J.string().optional(),handshake:jsr,messages:J.list(Lsr),servers:J.list(Usr),examples:J.list(Vsr)}).extend(mn).extend($o);var Dgs=J.objectWithoutOptionalProperties({apiVersion:J.unknown().optional(),title:J.string().optional(),description:J.string().optional(),basePath:J.string().optional(),servers:J.list(Kvt),websocketServers:J.list(Kvt),groups:J.record(J.string(),ksr),tags:Nsr,hasEndpointsMarkedInternal:J.boolean(),endpoints:J.list(msr),webhooks:J.list(Qsr),channels:J.record(J.string(),qsr),groupedSchemas:Fsr,variables:J.record(J.string(),Dhe),nonRequestReferencedSchemas:J.set(KP),securitySchemes:J.record(Bhe,Oor),security:gsr.optional(),globalHeaders:J.list(hsr).optional(),idempotencyHeaders:J.list(vsr).optional()});var Gsr=J.objectWithoutOptionalProperties({value:J.lazy(()=>$u)}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(_u).extend(Uf);var Wsr=J.objectWithoutOptionalProperties({}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(_u);var $u=J.union("type",{primitive:Dhe,object:J.lazyObject(()=>Psr),array:J.lazyObject(()=>jor),map:J.lazyObject(()=>Ssr),optional:J.lazyObject(()=>Gsr),enum:o6e,reference:_$,literal:B6e,oneOf:J.object({value:J.lazy(()=>Dsr)}),nullable:J.lazyObject(()=>Tsr),unknown:Wsr}).transform({transform:e=>{switch(e.type){case"primitive":return ba.primitive(e);case"object":return ba.object(e);case"array":return ba.array(e);case"map":return ba.map(e);case"optional":return ba.optional(e);case"enum":return ba.enum(e);case"reference":return ba.reference(e);case"literal":return ba.literal(e);case"oneOf":return ba.oneOf(e.value);case"nullable":return ba.nullable(e);case"unknown":return ba.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var Rsr=J.objectWithoutOptionalProperties({schemas:J.list(J.lazy(()=>$u))}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(Bx).extend($o).extend(_u).extend(Uf);var pli={};te(pli,{ArraySchemaWithExample:()=>$sr,Base64WithExample:()=>Hsr,BooleanWithExample:()=>Ksr,CommonPropertyWithExample:()=>Jsr,DateWithExample:()=>Ysr,DatetimeWithExample:()=>Jvt,DiscriminatedOneOfSchemaWithExample:()=>Xsr,DoubleWithExample:()=>Zsr,EndpointWithExample:()=>Rgs,EnumSchemaWithExample:()=>aar,FloatWithExample:()=>car,HeaderWithExample:()=>Rhe,HttpErrorWithExample:()=>ear,Int64WithExample:()=>uar,IntWithExample:()=>lar,JsonRequestWithExample:()=>rar,JsonResponseWithExample:()=>F6e,MapSchemaWithExample:()=>har,MultipartFormDataWebhookPayloadWithExample:()=>gar,NamedFullExample:()=>nk,NullableSchemaWithExample:()=>Aar,ObjectPropertyWithExample:()=>yar,ObjectSchemaWithExample:()=>bar,OneOfSchemaWithExample:()=>Ear,OptionalSchemaWithExample:()=>war,ParseFormUrlEncodedRequest:()=>nar,ParseMultipartRequest:()=>iar,ParseOctetStreamRequest:()=>oar,PathParameterWithExample:()=>tar,PrimitiveSchemaValueWithExample:()=>mar,PrimitiveSchemaWithExample:()=>N6e,QueryParameterWithExample:()=>R6e,RequestWithExample:()=>sar,ResponseWithExample:()=>k6e,SchemaWithExample:()=>zf,StringSchemaWithExample:()=>par,Uint64WithExample:()=>far,UintWithExample:()=>dar,UnDiscriminatedOneOfSchemaWithExample:()=>Iar,UnknownSchemaWithExample:()=>Car,WebhookWithExample:()=>Fgs,WebsocketHandshakeWithExample:()=>kgs});var $sr=J.objectWithoutOptionalProperties({value:J.lazy(()=>zf),minItems:J.number().optional(),maxItems:J.number().optional(),example:J.list(J.unknown()).optional()}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(_u).extend(Uf);var Hsr=J.objectWithoutOptionalProperties({example:J.string().optional()});var Ksr=J.objectWithoutOptionalProperties({default:J.boolean().optional(),example:J.boolean().optional()});var Jsr=J.objectWithoutOptionalProperties({key:J.string(),schema:J.lazy(()=>zf)});var Jvt=J.objectWithoutOptionalProperties({example:J.string().optional()});var Ysr=J.objectWithoutOptionalProperties({example:J.string().optional()});var Xsr=J.objectWithoutOptionalProperties({discriminantProperty:J.string(),discriminantPropertyNameOverride:J.string().optional(),discriminatorContext:f6e.optional(),commonProperties:J.list(J.lazyObject(()=>Jsr)),schemas:J.record(J.string(),J.lazy(()=>zf))}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(Bx).extend($o).extend(_u).extend(Uf);var Zsr=J.objectWithoutOptionalProperties({default:J.number().optional(),minimum:J.number().optional(),maximum:J.number().optional(),exclusiveMinimum:J.boolean().optional(),exclusiveMaximum:J.boolean().optional(),multipleOf:J.number().optional(),example:J.number().optional()});var Rhe=J.objectWithoutOptionalProperties({name:J.string(),schema:J.lazy(()=>zf),env:J.string().optional(),parameterNameOverride:J.string().optional()}).extend(mn).extend(us).extend($o);var nk=J.objectWithoutOptionalProperties({name:J.string().optional(),value:J.unknown()}).extend(mn);var ear=J.objectWithoutOptionalProperties({statusCode:w$,schema:J.lazy(()=>zf),fullExamples:J.list(nk).optional()}).extend(mn).extend(Nc).extend($o);var tar=J.objectWithoutOptionalProperties({name:J.string(),schema:J.lazy(()=>zf),variableReference:J.string().optional(),parameterNameOverride:J.string().optional(),explode:J.boolean().optional()}).extend(mn).extend(us).extend($o);var R6e=J.objectWithoutOptionalProperties({name:J.string(),schema:J.lazy(()=>zf),parameterNameOverride:J.string().optional(),explode:J.boolean().optional()}).extend(mn).extend(us).extend($o);var rar=J.objectWithoutOptionalProperties({schema:J.lazy(()=>zf),contentType:J.string().optional(),fullExamples:J.list(nk).optional(),additionalProperties:J.boolean()}).extend(mn).extend($o).extend(C$);var nar=J.objectWithoutOptionalProperties({schema:J.lazy(()=>zf),contentType:J.string().optional(),fullExamples:J.list(nk).optional(),additionalProperties:J.boolean()}).extend(mn).extend($o).extend(C$);var iar=J.objectWithoutOptionalProperties({fullExamples:J.list(nk).optional()}).extend(I6e).extend(C$);var oar=J.objectWithoutOptionalProperties({}).extend(w6e).extend(C$);var sar=J.union("type",{octetStream:oar,multipart:iar,json:rar,formUrlEncoded:nar}).transform({transform:e=>{switch(e.type){case"octetStream":return HP.octetStream(e);case"multipart":return HP.multipart(e);case"json":return HP.json(e);case"formUrlEncoded":return HP.formUrlEncoded(e);default:return e}},untransform:({_visit:e,...t})=>t});var F6e=J.objectWithoutOptionalProperties({schema:J.lazy(()=>zf),responseProperty:J.string().optional(),terminator:J.string().optional(),fullExamples:J.list(nk).optional()}).extend(mn).extend($o).extend(YU);var k6e=J.union("type",{file:C6e,json:F6e,text:Phe,bytes:p6e,streamingSse:F6e,streamingText:Phe,streamingJson:F6e}).transform({transform:e=>{switch(e.type){case"file":return Fh.file(e);case"json":return Fh.json(e);case"text":return Fh.text(e);case"bytes":return Fh.bytes(e);case"streamingSse":return Fh.streamingSse(e);case"streamingText":return Fh.streamingText(e);case"streamingJson":return Fh.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var Rgs=J.objectWithoutOptionalProperties({authed:J.boolean(),security:g6e.optional(),internal:J.boolean().optional(),idempotent:J.boolean().optional(),method:y6e,audiences:J.list(J.string()),path:J.string(),summary:J.string().optional(),operationId:J.string().optional(),tags:J.list(JP),pathParameters:J.list(tar),queryParameters:J.list(R6e),headers:J.list(Rhe),sdkName:x$.optional(),generatedRequestName:J.string(),requestNameOverride:J.string().optional(),request:sar.optional(),response:k6e.optional(),errors:J.record(w$,ear),servers:J.list(A6e),examples:J.list(h6e),pagination:b6e.optional(),retries:S6e.optional()}).extend(mn).extend(us).extend($o).extend(oc);var aar=J.objectWithoutOptionalProperties({default:She.optional(),values:J.list(She),example:J.string().optional()}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend($o).extend(_u).extend(Uf);var car=J.objectWithoutOptionalProperties({example:J.number().optional()});var uar=J.objectWithoutOptionalProperties({default:J.number().optional(),example:J.number().optional()});var lar=J.objectWithoutOptionalProperties({default:J.number().optional(),minimum:J.number().optional(),maximum:J.number().optional(),exclusiveMinimum:J.boolean().optional(),exclusiveMaximum:J.boolean().optional(),multipleOf:J.number().optional(),example:J.number().optional()});var par=J.objectWithoutOptionalProperties({default:J.string().optional(),pattern:J.string().optional(),format:J.string().optional(),minLength:J.number().optional(),maxLength:J.number().optional(),example:J.string().optional()});var far=J.objectWithoutOptionalProperties({default:J.number().optional(),example:J.number().optional()});var dar=J.objectWithoutOptionalProperties({default:J.number().optional(),example:J.number().optional()});var mar=J.union("type",{int:lar,int64:uar,uint:dar,uint64:far,float:car,double:Zsr,string:par,datetime:Jvt,datetimeRfc2822:Jvt,date:Ysr,base64:Hsr,boolean:Ksr}).transform({transform:e=>{switch(e.type){case"int":return xi.int(e);case"int64":return xi.int64(e);case"uint":return xi.uint(e);case"uint64":return xi.uint64(e);case"float":return xi.float(e);case"double":return xi.double(e);case"string":return xi.string(e);case"datetime":return xi.datetime(e);case"datetimeRfc2822":return xi.datetimeRfc2822(e);case"date":return xi.date(e);case"base64":return xi.base64(e);case"boolean":return xi.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var N6e=J.objectWithoutOptionalProperties({schema:mar}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(_u);var har=J.objectWithoutOptionalProperties({key:N6e,value:J.lazy(()=>zf),minProperties:J.number().optional(),maxProperties:J.number().optional(),example:J.unknown().optional()}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(Bx).extend(_u).extend(Uf);var gar=J.objectWithoutOptionalProperties({name:J.string().optional(),properties:J.list(Ohe)}).extend(mn).extend($o);var Aar=J.objectWithoutOptionalProperties({value:J.lazy(()=>zf)}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(_u).extend(Uf);var yar=J.objectWithoutOptionalProperties({key:J.string(),schema:J.lazy(()=>zf),readonly:J.boolean().optional(),writeonly:J.boolean().optional(),audiences:J.list(J.string()),conflict:J.record(KP,T6e),nameOverride:J.string().optional(),generatedName:J.string()}).extend(us);var bar=J.objectWithoutOptionalProperties({allOf:J.list(_$),properties:J.list(J.lazyObject(()=>yar)),allOfPropertyConflicts:J.list(c6e),fullExamples:J.list(nk).optional(),additionalProperties:J.boolean(),minProperties:J.number().optional(),maxProperties:J.number().optional()}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(Bx).extend($o).extend(_u).extend(Uf);var Ear=J.union("type",{discriminated:J.lazyObject(()=>Xsr),undiscriminated:J.lazyObject(()=>Iar)}).transform({transform:e=>{switch(e.type){case"discriminated":return vj.discriminated(e);case"undiscriminated":return vj.undiscriminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var war=J.objectWithoutOptionalProperties({value:J.lazy(()=>zf)}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(_u).extend(Uf);var Car=J.objectWithoutOptionalProperties({example:J.unknown()}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(_u);var zf=J.union("type",{primitive:N6e,object:J.lazyObject(()=>bar),array:J.lazyObject(()=>$sr),map:J.lazyObject(()=>har),optional:J.lazyObject(()=>war),enum:aar,reference:_$,literal:B6e,oneOf:J.object({value:J.lazy(()=>Ear)}),nullable:J.lazyObject(()=>Aar),unknown:Car}).transform({transform:e=>{switch(e.type){case"primitive":return Fr.primitive(e);case"object":return Fr.object(e);case"array":return Fr.array(e);case"map":return Fr.map(e);case"optional":return Fr.optional(e);case"enum":return Fr.enum(e);case"reference":return Fr.reference(e);case"literal":return Fr.literal(e);case"oneOf":return Fr.oneOf(e.value);case"nullable":return Fr.nullable(e);case"unknown":return Fr.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var Iar=J.objectWithoutOptionalProperties({schemas:J.list(J.lazy(()=>zf))}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(Bx).extend($o).extend(_u).extend(Uf);var Fgs=J.objectWithoutOptionalProperties({audiences:J.list(J.string()),sdkName:x$.optional(),method:P6e,summary:J.string().optional(),operationId:J.string(),tags:J.list(JP),headers:J.list(Rhe),generatedPayloadName:J.string(),payload:J.lazy(()=>zf),multipartFormData:gar.optional(),response:k6e.optional(),signatureVerification:D6e.optional(),examples:J.list(O6e)}).extend(mn).extend($o).extend(oc);var kgs=J.objectWithoutOptionalProperties({queryParameters:J.list(R6e),headers:J.list(Rhe)});var Ngs=/^(\d+)/,Q6e=/^[a-zA-Z][a-zA-Z0-9_]*$/,Qgs={"<":"LESS_THAN",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL_TO","<=":"LESS_THAN_OR_EQUAL_TO","!=":"NOT_EQUALS","=":"EQUAL_TO","==":"EQUAL_TO","*":"ALL","":"EMPTY",'""':"EMPTY_STRING","-":"HYPHEN","|":"PIPE",".":"DOT","/":"SLASH"};function FOe(e){let t=["zero","one","two","three","four","five","six","seven","eight","nine"],r=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],n=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"];if(e<0||e>9999)return;if(e<10)return t[e];if(e<20)return r[e-10];if(e<100){let s=Math.floor(e/10),a=e%10;return a===0?n[s]:`${n[s]}_${t[a]}`}if(e<1e3){let s=Math.floor(e/100),a=e%100;return a===0?`${t[s]}_hundred`:`${t[s]}_hundred_${FOe(a)}`}let i=Math.floor(e/1e3),o=e%1e3;return o===0?`${t[i]}_thousand`:`${t[i]}_thousand_${FOe(o)}`}Bi();function Yvt(e){let t=e.match(Ngs);if(t&&t[0]!=null){let r=t[0],n=e.substring(r.length),i=parseFloat(r);if(!isNaN(i)&&isFinite(i)){let o=FOe(i);return n.length>0?`${o}_${n}`:o}}}function j6e(e){let t=Yvt(e),r=Qgs[e];return t!=null?gu(Vn(t)):r??(e.toLowerCase()==="n/a"?"NOT_APPLICABLE":gu(Vn(e)))}Bi();function ik(e,t){return e.type==="primitive"&&t.type==="primitive"?jgs(e.schema,t.schema):e.type==="enum"&&t.type==="enum"?TAl(e.values,t.values):e.type==="array"&&t.type==="array"?ik(e.value,t.value):e.type==="unknown"&&t.type==="unknown"?!0:e.type==="reference"&&t.type==="reference"?e.schema===t.schema:e.type==="optional"&&t.type==="optional"?ik(e.value,t.value):e.type==="oneOf"&&t.type==="oneOf"?OAl(e.value,t.value):e.type==="object"&&t.type==="object"?PAl(e,t):e.type==="map"&&t.type==="map"?jgs(e.key.schema,t.key.schema)&&ik(e.value,t.value):e.type==="literal"&&t.type==="literal"?e.value===t.value:!1}function jgs(e,t){return e.type===t.type}function TAl(e,t){let r=new Set(e.map(i=>i.value)),n=new Set(t.map(i=>i.value));return $0(r,n)}function OAl(e,t){return e.type==="discriminated"&&t.type==="discriminated"?e.discriminantProperty===t.discriminantProperty&&Object.keys(e.schemas).length===Object.keys(t.schemas).length&&Object.entries(e.schemas).every(([r,n])=>{let i=t.schemas[r];return i==null?!1:ik(n,i)}):e.type==="undiscriminated"&&t.type==="undiscriminated"?e.schemas.length===t.schemas.length&&e.schemas.every((r,n)=>{let i=t.schemas[n];return i==null?!1:ik(r,i)}):!1}function PAl(e,t){if(Object.keys(e.properties).length!==Object.keys(t.properties).length)return!1;let r=Object.fromEntries(e.properties.map(n=>[n.key,n.schema]));return Object.entries(t.properties).every(([n,i])=>{let o=r[n];return o==null?!1:ik(o,i.schema)})}St();function ab(e){switch(e){case wx.Deprecated:return"deprecated";case wx.Beta:return"pre-release";case wx.GenerallyAvailable:return"generally-available";default:return}}St();function Xvt(e){if(e.type==="protobuf")return{proto:{type:e.typeName}};Be(e.type)}St();St();sA();Bi();function Mgs(e){let t=e.match(/^(_+)/),r=e.match(/(_+)$/),n=t?.[1]??"",i=r?.[1]??"";if(n===""&&i==="")return Vn(e);if(n.length+i.length>=e.length)return e;let o=e.slice(n.length,e.length-i.length||void 0);return`${n}${Vn(o)}${i}`}function DAl(e){let t=e.find(n=>typeof n=="object"&&n.type==="namespace"),r=e.filter(n=>typeof n=="string"||n.type!=="namespace");return t?[t,...r]:r}function Lgs(e){let t=e?DAl(e):void 0;if(t==null||t.length===0)return gOe;let r=[];for(let[n,i]of t.entries())typeof i=="string"?r.push(Mgs(i)):typeof i=="object"?i.type==="namespace"?n<t.length-1?r.push(Mgs(i.name)):r.push(i.name,gOe):Be(i.type):Be(i);return r.join("/")}function Vse(e){return Qs.of(`${Lgs(e)}.yml`)}function fli({sdkName:e,namespaceOverride:t}){let r;return e==null||e.groupName.length===0&&t==null?gOe:(t!=null?r=[{type:"namespace",name:t},...e.groupName.filter(n=>typeof n=="string"||n.type!=="namespace")]:r=e.groupName,Lgs(r))}function Ugs({sdkName:e,namespaceOverride:t}){return Qs.of(`${fli({sdkName:e,namespaceOverride:t})}.yml`)}function zgs({location:e,namespaceOverride:t}){return t!=null?H0(Qs.of(t),e):e}function Vgs(e){switch(e.type){case"object":case"primitive":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":case"unknown":return xar({namespace:e.namespace,groupName:e.groupName});case"oneOf":return xar({namespace:e.value.namespace,groupName:e.value.groupName});default:Be(e)}}function xar({namespace:e,groupName:t}){return e!=null&&t!=null?Vse([{type:"namespace",name:e},...t]):e!=null?Vse([{type:"namespace",name:e}]):Vse(t)}St();function qse(e){switch(e.type){case"object":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":case"primitive":case"unknown":return e.groupName??void 0;case"oneOf":return e.value.groupName??void 0;default:Be(e)}}function bp(e){return typeof e=="string"?e:e.type}function M6e(e){if(typeof e!="string")return e.docs}function Zvt(e){if(typeof e!="string")return e.default}function dli(e){if(typeof e!="string")return e.validation}function L6e(e){let t=e.match(/^optional<\s*nullable<\s*(.+)\s*>\s*>$/);if(t!=null&&t[1]!=null)return t[1].trim();let r=e.match(/^nullable<\s*(.+)\s*>$/);return r!=null&&r[1]!=null?r[1].trim():e}function Ggs(e){let t=bp(e);return t.startsWith("nullable<")||t.startsWith("optional<nullable<")?e:typeof e=="string"?qgs(e):{...e,type:qgs(e.type)}}function qgs(e){return e.startsWith("nullable<")||e.startsWith("optional<nullable<")?e:e.startsWith("optional<")?e.replace("optional<","optional<nullable<")+">":`nullable<${e}>`}function kOe(e){return bp(e).startsWith("optional<")?e:typeof e=="string"?Wgs(e):{...e,type:Wgs(e.type)}}function Wgs(e){return e.startsWith("optional<")?e:`optional<${e}>`}var RAl=-2147483648,FAl=2147483647,kAl=-17976931348623157e292,NAl=17976931348623157e292;function pc({schema:e,fileContainingReference:t,declarationFile:r=t,context:n,namespace:i,declarationDepth:o,variant:s}){switch(n.shouldMarkSchemaAsReferenced()&&n.markSchemaAsReferenced(e,i),e.type){case"primitive":return _ar(e);case"array":return gli({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:o,variant:s});case"map":return Ali({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:o,variant:s});case"reference":return hli({schema:e,fileContainingReference:t,context:n,namespace:i,variant:s});case"unknown":return bli();case"optional":return Sar({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:o,variant:s});case"nullable":return yli({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:o,variant:s});case"enum":return GAl({schema:e,fileContainingReference:t,context:n,declarationFile:r,declarationDepth:o});case"literal":return e.value,Eli(e);case"object":return WAl({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:o,variant:s});case"oneOf":return $Al({schema:e.value,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:o,variant:s});default:Be(e)}}function _ar(e){switch(e.schema.type){case"string":return MAl({description:e.description,schema:e.schema});case"int":return LAl({description:e.description,schema:e.schema});case"float":return UAl({description:e.description,schema:e.schema});case"double":return zAl({description:e.description,schema:e.schema});case"boolean":return QAl({description:e.description,schema:e.schema});case"int64":return jAl({description:e.description,schema:e.schema})}let t=e.schema._visit({int:()=>"integer",int64:()=>"long",uint:()=>"uint",uint64:()=>"uint64",float:()=>"double",double:()=>"double",string:()=>"string",datetime:()=>"datetime",datetimeRfc2822:()=>"datetime-rfc-2822",date:()=>"date",base64:()=>"base64",boolean:()=>"boolean",_other:()=>"unknown"});return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:ab(e.availability)}:{}}}function QAl({description:e,schema:t}){let r="boolean";if(e==null&&t.default==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),n}function jAl({description:e,schema:t}){let r="long";if(e==null&&t.default==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),n}function MAl({description:e,schema:t}){let r="string",n=VAl(t);if(e==null&&t.default==null&&n==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),n!=null&&(i.validation=n),i}function LAl({description:e,schema:t}){let r="integer",n=$gs(t,r);if(e==null&&t.default==null&&n==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),n!=null&&(i.validation=n),i}function UAl({description:e,schema:t}){let r="float";if(e==null)return r;let n={type:r};return e!=null&&(n.docs=e),n}function zAl({description:e,schema:t}){let r="double",n=$gs(t,r);if(e==null&&t.default==null&&n==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),n!=null&&(i.validation=n),i}function VAl(e){if(e==null)return;let{format:t,pattern:r,minLength:n,maxLength:i}=e,o=qAl(t);if(!(o==null&&r==null&&n==null&&i==null))return{format:o,pattern:r,minLength:n,maxLength:i}}function qAl(e){switch(e){case"date":case"date-time":case"password":case"byte":case"bytes":case"binary":case"email":case"uuid":case"uri":case"hostname":case"ipv4":case"ipv6":return e;default:return}}function $gs(e,t){if(e==null)return;let{minimum:r,maximum:n,multipleOf:i}=e,{exclusiveMinimum:o,exclusiveMaximum:s}=e;if(r=mli(r,t),n=mli(n,t),i=mli(i,t),!(r==null&&n==null&&o==null&&s==null&&i==null))return{min:r,max:n,exclusiveMin:o,exclusiveMax:s,multipleOf:i}}function mli(e,t){if(e===void 0)return;let[r,n]=t==="integer"?[RAl,FAl]:[kAl,NAl];return e<r||e>n?void 0:e}function hli({schema:e,fileContainingReference:t,context:r,variant:n}){let i=r.getSchema(e.schema,e.namespace);if(i==null)return"unknown";let o=HAl(i)??e.schema,s=r.options.respectReadonlySchemas&&n!=null?r.getSchemaFinalName(o,n):o,a=qse(i),c=KAl(i),l=Bar({context:r,fileContainingReference:t,declarationFile:xar({namespace:e.namespace,groupName:a}),type:s});return i.type==="nullable"&&(l=r.options.wrapReferencesToNullableInOptional?`optional<${l}>`:`nullable<${l}>`),i.type==="optional"&&!l.startsWith("optional<")&&(l=`optional<${l}>`),e.description==null&&c==null?l:{type:l,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:ab(e.availability)}:{}}}function gli({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}){let a=pc({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}),c=`list<${bp(a)}>`;return e.description==null&&e.title==null?c:{...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:ab(e.availability)}:{},type:c}}function Ali({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}){let a=_ar(e.key),c=pc({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}),u=e.encoding!=null?Xvt(e.encoding):void 0,l=`map<${bp(a)}, ${bp(c)}>`;if(e.description==null&&u==null&&e.title==null)return l;let p={type:l};return e.description!=null&&(p.docs=e.description),e.encoding!=null&&(p.encoding=u),e.availability!=null&&(p.availability=ab(e.availability)),p}function yli({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}){if(!n.options.respectNullableSchemas)return Sar({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:o,variant:s});let a=pc({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}),c=bp(a),u=M6e(a),l=Zvt(a),p=dli(a),d=Ggs(c);if(n.options.wrapReferencesToNullableInOptional&&(d=kOe(d)),e.availability==null&&e.description==null&&u==null&&l==null&&p==null&&e.title==null)return d;let f=typeof d=="string"?{type:d}:d;return(e.description!=null||u!=null)&&(f.docs=e.description??u),l!=null&&(f.default=l),p!=null&&(f.validation=p),e.availability!=null&&(f.availability=ab(e.availability)),f}function Sar({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}){let a=pc({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}),c=bp(a),u=M6e(a),l=Zvt(a),p=dli(a),d=kOe(c);if(e.availability==null&&e.description==null&&u==null&&l==null&&p==null&&e.title==null)return d;let f=typeof d=="string"?{type:d}:d;return(e.description!=null||u!=null)&&(f.docs=e.description??u),l!=null&&(f.default=l),p!=null&&(f.validation=p),e.availability!=null&&(f.availability=ab(e.availability)),f}function bli(){return"unknown"}function Eli(e){let t;switch(e.value.type){case"boolean":{t=`literal<${e.value.value}>`;break}case"string":{t=`literal<"${e.value.value}">`;break}default:Be(e.value)}return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:ab(e.availability)}:{}}}function GAl({schema:e,fileContainingReference:t,declarationFile:r,context:n,declarationDepth:i}){let o=eIt(e,i),s=e.nameOverride??e.generatedName;n.builder.addType(r,{name:s,schema:o.schema});let a=Bar({type:s,fileContainingReference:t,declarationFile:r,context:n});if(e.description==null&&e.default==null&&e.title==null)return a;let c={type:a};return e.description!=null&&(c.docs=e.description),e.default!=null&&(c.default=e.default.value),e.availability!=null&&(c.availability=ab(e.availability)),c}function WAl({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}){let a=NOe({schema:e,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}),c=e.nameOverride??e.generatedName;n.builder.addType(r,{name:c,schema:a.schema});let u=Bar({type:c,fileContainingReference:t,declarationFile:r,context:n});return e.description==null&&e.title==null?u:{type:u,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:ab(e.availability)}:{}}}function $Al({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}){let a=vli({schema:e,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}),c=e.nameOverride??e.generatedName;n.builder.addType(r,{name:c,schema:a.schema});let u=Bar({type:c,fileContainingReference:t,declarationFile:r,context:n});return e.description==null&&e.title==null?u:{...e.title!=null?{"display-name":e.title}:{},type:u,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:ab(e.availability)}:{}}}function Bar({type:e,fileContainingReference:t,declarationFile:r,context:n}){if(r===t)return e;let i=n.builder.addImport({file:t,fileToImport:r});return i!=null?`${i}.${e}`:e}function HAl(e){return ba._visit(e,{primitive:t=>t.nameOverride??t.generatedName,object:t=>t.nameOverride??t.generatedName,array:t=>t.nameOverride??t.generatedName,map:t=>t.nameOverride??t.generatedName,enum:t=>t.nameOverride??t.generatedName,reference:t=>t.nameOverride??t.generatedName,literal:t=>t.nameOverride??t.generatedName,oneOf:t=>t.nameOverride??t.generatedName,optional:t=>t.nameOverride??t.generatedName,nullable:t=>t.nameOverride??t.generatedName,unknown:t=>t.nameOverride??t.generatedName,_other:()=>{}})}function KAl(e){return ba._visit(e,{primitive:t=>t.title,object:t=>t.title,array:t=>t.title,map:t=>t.title,enum:t=>t.title,reference:t=>t.title,literal:t=>t.title,oneOf:t=>t.title,optional:t=>t.title,nullable:t=>t.title,unknown:t=>{},_other:()=>{}})}St();function Gse(e){switch(e.type){case"openapi":return{openapi:e.file};case"protobuf":return{proto:e.file};default:Be(e)}}function Kgs({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i,variant:o}){let s;switch(e.type){case"primitive":s=XAl(e);break;case"array":s=JAl({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;case"map":s=YAl({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;case"reference":s=ZAl({schema:e,context:t,declarationFile:r,namespace:n,variant:o});break;case"unknown":s=tyl(e.nameOverride,e.generatedName,e.description);break;case"optional":s=Ygs({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;case"nullable":s=eyl({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;case"enum":s=eIt(e,i);break;case"literal":s=ryl(e,e.nameOverride,e.generatedName);break;case"object":s=NOe({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i,variant:o});break;case"oneOf":s=vli({schema:e.value,context:t,declarationFile:r,namespace:n,declarationDepth:i,variant:o});break;default:Be(e)}return s}function NOe({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i,skipReadonlyProperties:o,variant:s}){let a=o===!0||s==="write",c=!1,u={},l=new Set;for(let g of e.properties){if(g.readonly&&(c=!0),a&&g.readonly)continue;if(Object.keys(g.conflict).length>0){if(Object.entries(g.conflict).every(([x,C])=>!C.differentSchema))continue;Object.entries(g.conflict).forEach(([x])=>{Ili({property:g.key,schemaId:x,context:t,namespace:n}).forEach(_=>{l.add(_)})})}let A=pc({schema:g.schema,context:t,fileContainingReference:r,namespace:n,declarationDepth:i+1,variant:s}),b=g.audiences,v=g.nameOverride,E=ab(g.availability),I=syl(g);u[g.key]=oyl({typeReference:A,audiences:b,name:v,availability:E,propertyAccess:I})}let p=new Set;for(let g of e.allOfPropertyConflicts)g.allOfSchemaIds.forEach(A=>l.add(A)),g.conflictingTypeSignatures&&p.add(g.propertyKey);let d=[];for(let g of e.allOf){let A=Tar({schema:g.schema,context:t,namespace:n});if(A==null||l.has(g.schema)||l.has(A))continue;let b=pc({schema:ba.reference(g),context:t,fileContainingReference:r,namespace:n,declarationDepth:i+1,variant:s});d.push(L6e(bp(b)))}for(let g of l){let A=U6e(t,g,n);for(let b of A.properties)u[b.key]==null&&(p.has(b.key)&&(u[b.key]="unknown"),u[b.key]=pc({schema:b.schema,context:t,fileContainingReference:r,namespace:n,declarationDepth:i+1,variant:s}));for(let b of A.allOf){if(l.has(b.schema))continue;let v=pc({schema:ba.reference(b),context:t,fileContainingReference:r,namespace:n,declarationDepth:i+1,variant:s});d.push(L6e(bp(v)))}}let f={docs:e.description??void 0,properties:Object.fromEntries(Object.entries(u).map(([g,A])=>iyl(g)?[g,typeof A=="string"?{type:A,name:`_${g}`}:{...A,name:`_${g}`}]:[g,A]))};d.length>0&&(f.extends=d),e.additionalProperties&&(f["extra-properties"]=!0),e.availability!=null&&(f.availability=ab(e.availability)),e.source!=null&&(f.source=Gse(e.source)),e.encoding!=null&&(f.encoding=Xvt(e.encoding)),f.inline=wli(e,i);let m=e.nameOverride??e.generatedName;return{name:s==="read"&&c&&t.options.respectReadonlySchemas&&t.hasReadVariant(m)?`${m}Read`:m,schema:f}}function Ili({property:e,schemaId:t,context:r,namespace:n}){let i=r.getSchema(t,n);if(i==null)return[];if(i.type==="reference")return Ili({property:e,schemaId:i.schema,context:r,namespace:n});if(i.type==="object"){let{properties:o,allOf:s}=U6e(r,t,n),a=o.some(u=>u.key===e),c=[...s.flatMap(u=>Ili({property:e,context:r,schemaId:u.schema,namespace:n}))];if(a||c.length>0)return[t,...c]}return[]}function Jgs(e,t,r){return t.type==="object"?{properties:t.properties,allOf:t.allOf}:t.type==="reference"?U6e(e,t.schema,r):t.type==="nullable"?Jgs(e,t.value,r):{properties:[],allOf:[]}}function U6e(e,t,r){let n=e.getSchema(t,r);return n==null?{properties:[],allOf:[]}:Jgs(e,n,r)}function JAl({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){return{name:e.nameOverride??e.generatedName,schema:gli({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:n,declarationDepth:i})}}function YAl({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){return{name:e.nameOverride??e.generatedName,schema:Ali({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:n,declarationDepth:i})}}function XAl(e){let t=_ar(e);if(typeof t=="string")return{name:e.nameOverride??e.generatedName,schema:t};let{default:r,...n}=t;return{name:e.nameOverride??e.generatedName,schema:{...n}}}function Hgs(e){return e.camel==null&&e.pascal==null&&e.screamingSnake==null&&e.snake==null}function eIt(e,t){let r={enum:e.values.map(o=>{let s=o.nameOverride??o.generatedName,a=o.value;if(s===a&&o.description==null&&(o.casing==null||Hgs(o.casing)))return s;let c={value:o.value};if(s!==a&&(c.name=s),o.description!=null&&(c.docs=o.description),o.casing!=null&&!Hgs(o.casing)){let u={},l=!1;o.casing.camel!=null&&(u.camel=o.casing.camel,l=!0),o.casing.screamingSnake!=null&&(u["screaming-snake"]=o.casing.screamingSnake,l=!0),o.casing.snake!=null&&(u.snake=o.casing.snake,l=!0),o.casing.pascal!=null&&(u.pascal=o.casing.pascal,l=!0),l&&(c.casing=u)}return c})};e.description!=null&&(r.docs=e.description),e.default!=null&&(r.default=e.default.value),r.inline=wli(e,t);let n=new Set,i={...r,enum:[],source:e.source!=null?Gse(e.source):void 0};for(let o of r.enum){let s=typeof o=="string"?o:o.name??o.value;n.has(s.toLowerCase())||(i.enum.push(o),n.add(s.toLowerCase()))}return{name:e.nameOverride??e.generatedName,schema:i}}function ZAl({schema:e,context:t,declarationFile:r,namespace:n,variant:i}){return{name:e.nameOverride??e.generatedName,schema:hli({schema:e,context:t,fileContainingReference:r,namespace:n,variant:i})}}function eyl({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){return t.options.respectNullableSchemas?{name:e.nameOverride??e.generatedName,schema:yli({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:n,declarationDepth:i})}:Ygs({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i})}function Ygs({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){return{name:e.nameOverride??e.generatedName,schema:Sar({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:n,declarationDepth:i})}}function tyl(e,t,r){return r!=null?{name:e??t,schema:{type:"unknown",docs:r}}:{name:e??t,schema:bli()}}function ryl(e,t,r){return{name:t??r,schema:Eli(e)}}function vli({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i,variant:o}){let s=e.encoding!=null?Xvt(e.encoding):void 0;if(e.type==="discriminated"){let c={};for(let l of e.commonProperties)c[l.key]=pc({schema:l.schema,fileContainingReference:r,context:t,namespace:n,declarationDepth:i+1,variant:o});let u={};for(let[l,p]of Object.entries(e.schemas))u[l]=pc({schema:p,context:t,fileContainingReference:r,namespace:n,declarationDepth:i+1,variant:o});return{name:e.nameOverride??e.generatedName,schema:{discriminant:e.discriminantPropertyNameOverride!=null||e.discriminatorContext!=null?{...e.discriminantPropertyNameOverride!=null&&{name:e.discriminantPropertyNameOverride},value:e.discriminantProperty,...e.discriminatorContext!=null&&{context:e.discriminatorContext}}:e.discriminantProperty,"base-properties":c,docs:e.description??void 0,availability:e.availability!=null?ab(e.availability):void 0,union:u,encoding:s,source:e.source!=null?Gse(e.source):void 0}}}let a=[];for(let c of e.schemas)a.push(pc({schema:c,fileContainingReference:r,context:t,namespace:n,declarationDepth:i+1,variant:o}));return{name:e.nameOverride??e.generatedName,schema:{discriminated:!1,docs:e.description??void 0,union:a,encoding:s,source:e.source!=null?Gse(e.source):void 0,inline:wli(e,i)}}}var nyl=/^[0-9]/;function iyl(e){return nyl.test(e)}function Tar({schema:e,context:t,namespace:r}){let n=t.getSchema(e,r);if(n!=null)return n.type==="reference"?Tar({context:t,schema:n.schema,namespace:r}):e}function oyl({typeReference:e,audiences:t,name:r,availability:n,propertyAccess:i}){return t.length===0&&r==null&&n==null&&i==null?e:{...typeof e=="string"?{type:e}:{...e},...t.length>0?{audiences:t}:{},...r!=null?{name:r}:{},...n!=null?{availability:n}:{},...i!=null?{access:i}:{}}}function wli(e,t){return e.inline===!0||t>0?!0:void 0}function syl(e){if(!(e.readonly&&e.writeonly)){if(e.readonly)return Sm.ObjectPropertyAccess.ReadOnly;if(e.writeonly)return Sm.ObjectPropertyAccess.WriteOnly}}Bi();function Xgs(e){let t=e.replace(/^x-|^X-/,"");return Vn(t)}function Zgs(e){if(e.authOverrides!=null){for(let[r,n]of Object.entries(e.authOverrides["auth-schemes"]??{}))e.builder.addAuthScheme({name:r,schema:n});e.authOverrides.auth!=null&&e.builder.setAuth(e.authOverrides.auth);return}let t=!1;for(let[r,n]of Object.entries(e.ir.securitySchemes))if(n.type==="basic"){let i={scheme:"basic"};n.usernameVariableName!=null&&(i.username===void 0?i.username={name:n.usernameVariableName}:i.username.name=n.usernameVariableName),n.usernameEnvVar!=null&&(i.username===void 0?i.username={env:n.usernameEnvVar}:i.username.env=n.usernameEnvVar),n.passwordVariableName!=null&&(i.password===void 0?i.password={name:n.passwordVariableName}:i.password.name=n.passwordVariableName),n.passwordEnvVar!=null&&(i.password===void 0?i.password={env:n.passwordEnvVar}:i.password.env=n.passwordEnvVar),e.builder.addAuthScheme({name:r,schema:i}),t||(e.builder.setAuth(r),t=!0)}else if(n.type==="bearer"){let i={scheme:"bearer"};n.tokenVariableName!=null&&(i.token===void 0?i.token={name:n.tokenVariableName}:i.token.name=n.tokenVariableName),n.tokenEnvVar!=null&&(i.token===void 0?i.token={env:n.tokenEnvVar}:i.token.env=n.tokenEnvVar),e.builder.addAuthScheme({name:r,schema:i}),t||(e.builder.setAuth(r),t=!0)}else if(n.type==="header")if(t)e.builder.addGlobalHeader({name:n.headerName,schema:{type:"string",name:n.headerVariableName??Xgs(n.headerName),env:n.headerEnvVar}});else{let i={header:n.headerName,name:n.headerVariableName??"apiKey",type:"string"};n.headerEnvVar!=null&&(i.env=n.headerEnvVar),n.prefix!=null&&(i.prefix=n.prefix),e.builder.addAuthScheme({name:r,schema:i}),e.builder.setAuth(r),t=!0}else if(n.type==="oauth"){let i={scheme:"bearer"};e.builder.addAuthScheme({name:r,schema:i}),t||(e.builder.setAuth(r),t=!0),n.scopesEnum!=null&&n.scopesEnum.values.length>0&&e.builder.addType(Qs.of("__package__.yml"),{name:"OauthScope",schema:eIt(n.scopesEnum,0).schema})}}Bi();function S$({header:e,context:t,fileContainingReference:r,namespace:n}){let i=pc({schema:e.schema,context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),o=bp(i),s=e.name.replace(/^x-|^X-/,""),a=e.parameterNameOverride!=null?e.parameterNameOverride:Vn(s);if(e.description==null&&e.name===a&&e.env==null&&e.availability==null)return o;let c={type:o};return a!==e.name&&(c.name=a),e.description!=null&&(c.docs=e.description),e.env!=null&&(c.env=e.env),e.availability!=null&&(c.availability=ab(e.availability)),c}function Oar({pathParameter:e,context:t,fileContainingReference:r,namespace:n}){let i=pc({schema:e.schema,context:t,fileContainingReference:r,namespace:n,declarationDepth:0});if(e.variableReference==null&&e.description==null&&e.availability==null)return bp(i);let o=e.variableReference!=null?{variable:`$${e.variableReference}`}:{type:bp(i)};return e.description!=null&&(o.docs=e.description),e.availability!=null&&(o.availability=ab(e.availability)),o}sA();function Dar({queryParameter:e,context:t,fileContainingReference:r,namespace:n}){let i=Cli({schema:e.schema,context:t,fileContainingReference:r,namespace:n});if(i==null)return;let o=bp(i.value),s=Zvt(i.value);o==="unknown"?o="string":o==="optional<unknown>"&&(o="optional<string>");let a={type:o};return s!=null&&(a.default=s),i.allowMultiple&&(a["allow-multiple"]=!0),e.explode!=null&&(a.explode=e.explode),e.description!=null&&(a.docs=e.description),e.parameterNameOverride!=null&&(a.name=e.parameterNameOverride),e.availability!=null&&(a.availability=ab(e.availability)),ayl(i.value)&&i.value.validation!==void 0&&(a.validation=i.value.validation),a.default==null&&a["allow-multiple"]==null&&a.docs==null&&a.name==null&&a.availability==null&&a.validation==null&&a.explode==null?o:a}function Cli({schema:e,context:t,fileContainingReference:r,namespace:n}){if(e.type==="reference"){let i=t.getSchema(e.schema,n);if(i==null)return;if(i.type==="array")return{value:pc({schema:ba.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:i.value,description:e.description??i.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,declarationFile:Qs.of(tf),fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0};if(i.type==="oneOf"&&i.value.type==="undiscriminated"){let o=[],s=!1;for(let[a,c]of Object.entries(i.value.schemas))c.type==="primitive"&&c.schema.type==="string"&&(s=!0),c.type==="literal"&&c.value.type==="string"&&(Q6e.test(c.value.value)?o.push(c.value.value):o.push({value:c.value.value,name:j6e(c.value.value)}));if(o.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:o}}),s&&t.options.respectForwardCompatibleEnums?(t.builder.addType(r,{name:`${e.generatedName}OrString`,schema:{discriminated:!1,union:[{type:"string"},{type:e.generatedName}]}}),{value:`${e.generatedName}OrString`,allowMultiple:!1}):{value:e.generatedName,allowMultiple:!1};if(i.value.schemas.length===2){let[a,c]=i.value.schemas;if(a!=null&&c!=null&&Par({array:a,primitive:c}))return{value:pc({schema:ba.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:c,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0};if(a!=null&&c!=null&&Par({array:c,primitive:a}))return{value:pc({schema:ba.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:a,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0}}for(let[a,c]of Object.entries(i.value.schemas))return Cli({schema:c,context:t,fileContainingReference:r,namespace:n})}else if(t.options.objectQueryParameters)return{value:pc({schema:e,context:t,fileContainingReference:r,declarationFile:Qs.of(tf),namespace:n,declarationDepth:0}),allowMultiple:!1}}if(e.type==="optional"||e.type==="nullable"){let i=e.type==="optional"?ba.optional:ba.nullable;if(e.value.type==="reference"){let o=t.getSchema(e.value.schema,n);if(o==null)return;if(o.type==="array")return{value:pc({schema:i({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:o.value,description:e.description??o.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,declarationFile:Qs.of(tf),namespace:n,declarationDepth:0}),allowMultiple:!0};if(t.options.objectQueryParameters)return{value:pc({schema:e,context:t,fileContainingReference:r,declarationFile:Qs.of(tf),namespace:n,declarationDepth:0}),allowMultiple:!1}}if(e.value.type==="array")return{value:pc({schema:i({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value.value,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0};if(e.value.type==="oneOf"&&e.value.value.type==="undiscriminated"){let o=[],s=!1;for(let[a,c]of Object.entries(e.value.value.schemas))c.type==="primitive"&&c.schema.type==="string"&&(s=!0),c.type==="literal"&&c.value.type==="string"&&(Q6e.test(c.value.value)?o.push(c.value.value):o.push({value:c.value.value,name:j6e(c.value.value)}));if(o.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:o}}),s&&t.options.respectForwardCompatibleEnums?(t.builder.addType(r,{name:`${e.generatedName}OrString`,schema:{discriminated:!1,union:[{type:"string"},{type:`optional<${e.value.value.generatedName}>`}]}}),{value:`optional<${e.value.value.generatedName}OrString>`,allowMultiple:!1}):{value:`optional<${e.value.value.generatedName}>`,allowMultiple:!1};if(e.value.value.schemas.length===2){let[a,c]=e.value.value.schemas;if(a!=null&&c!=null&&Par({array:a,primitive:c}))return{value:pc({schema:i({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:c,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0};if(a!=null&&c!=null&&Par({array:c,primitive:a}))return{value:pc({schema:i({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:a,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0}}if(t.options.objectQueryParameters)return{value:pc({schema:e,context:t,fileContainingReference:r,declarationFile:Qs.of(tf),namespace:n,declarationDepth:0}),allowMultiple:!1};for(let[a,c]of Object.entries(e.value.value.schemas))return Cli({schema:i({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:c,description:void 0,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:n})}else if(e.value.type==="object")return t.options.objectQueryParameters?{value:pc({schema:e,context:t,fileContainingReference:r,declarationFile:Qs.of(tf),namespace:n,declarationDepth:0}),allowMultiple:!1}:void 0;return{value:pc({schema:e,context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!1}}return e.type==="array"?{value:pc({schema:ba.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0}:{value:pc({schema:e,context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!1}}function Par({array:e,primitive:t}){return e?.type==="array"&&e.value.type==="primitive"&&t?.type==="primitive"&&e.value.schema.type===t.schema.type}function ayl(e){return typeof e=="object"&&e!==null&&"type"in e}St();function eAs({websocketExample:e,context:t}){let r={messages:[]};e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=cyl(e.queryParameters)),e.headers!=null&&e.headers.length>0&&(r.headers=uyl({context:t,namedFullExamples:e.headers}));for(let n of e.messages){let i=Fhe(n.payload);i!=null&&r.messages.push({type:n.messageType,body:i})}return r}function cyl(e){let t={};return e.forEach(r=>{let n=Fhe(r.value);Array.isArray(n)?t[r.name]=n[0]:n!=null&&(t[r.name]=n)}),t}function uyl({context:e,namedFullExamples:t}){let r=e.builder.getGlobalHeaderNames(),n={};return t.forEach(i=>{let o=Fhe(i.value);r.has(i.name)||o!=null&&(n[i.name]=o)}),n}function Fhe(e){switch(e.type){case"primitive":return tAs(e.value);case"object":return rAs(e.properties);case"array":return lyl(e.value);case"map":return pyl(e.value);case"oneOf":return fyl(e.value);case"enum":return e.value;case"literal":return dyl(e.value);case"unknown":return Fhe(e.value);case"null":return null;default:Be(e)}}function tAs(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`${e.value.slice(1)}`:e.value;case"datetime":try{return new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"datetimeRfc2822":return e.value;case"date":return e.value;case"base64":case"boolean":return e.value;default:Be(e)}}function rAs(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Fhe(r)]))}function lyl(e){return e.map(t=>Fhe(t))}function pyl(e){return Object.fromEntries(e.map(t=>[tAs(t.key),Fhe(t.value)]))}function fyl(e){return e.type==="discriminated"?rAs(e.value):Fhe(e.value)}function dyl(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:Be(e)}}function tIt(e){try{let r=new URL(e).pathname.split("/").filter(n=>n.length>0);if(r.length>0)return r[r.length-1]}catch{}}function Rar(e){try{return new URL(e).protocol.replace(":","")}catch{return}}function Far(e,t,r=!1){let n=tIt(t);return r&&n!=null?n:e!=null&&n!=null?`${e}_${n}`:n??e??"websocket"}function Wse(e){return e.find(t=>typeof t!="string"&&t.type==="namespace")?.name}function kar(e,t){return t??(e?.groupName!=null?Wse(e.groupName):void 0)}function nAs({channel:e,context:t,declarationFile:r}){let n=e.servers[0],i=t.ir.servers.length===0&&t.ir.websocketServers.length<=1,o=n!=null&&!i?t.options.groupEnvironmentsByHost?t.getUrlId(n.url)??Far(n.name,n.url,!0):n.name:void 0;t.logger.debug(`[buildChannel] Channel path="${e.path}", server name="${n?.name}", server url="${n?.url}", resolved urlId="${o}" (from collision map: ${t.getUrlId(n?.url??"")!=null})`);let s=e.path;for(let f of e.handshake.pathParameters)f.parameterNameOverride!=null&&(s=s.replace(`{${f.name}}`,`{${f.parameterNameOverride}}`));let a=t.authOverrides?.auth!=null,c={path:s,url:o,auth:a};e.audiences!=null&&e.audiences.length>0&&(c.audiences=e.audiences),e.summary!=null&&(c["display-name"]=e.summary),e.connectMethodName!=null&&(c["connect-method-name"]=e.connectMethodName),e.description!=null&&(c.docs=e.description);let u=Wse(e.groupName),l={};if(e.handshake.pathParameters.length>0)for(let f of e.handshake.pathParameters){let m=f.parameterNameOverride??f.name;l[m]=Oar({pathParameter:f,context:t,fileContainingReference:r,namespace:u})}Object.keys(l).length>0&&(c["path-parameters"]=l);let p={};if(e.handshake.queryParameters.length>0)for(let f of e.handshake.queryParameters){let m=Dar({queryParameter:f,context:t,fileContainingReference:r,namespace:u});m!=null&&(p[f.name]=m)}Object.keys(p).length>0&&(c["query-parameters"]=p);let d={};if(e.handshake.headers.length>0)for(let f of e.handshake.headers){let m=S$({header:f,context:t,fileContainingReference:r,namespace:u});d[f.name]=m}Object.keys(d).length>0&&(c.headers=d),t.builder.addChannel(r,{channel:c});for(let f of e.messages){let m={origin:f.origin,body:pc({schema:f.body,context:t,fileContainingReference:r,namespace:u,declarationDepth:0})};f.methodName!=null&&(m["method-name"]=f.methodName),t.builder.addChannelMessage(r,{messageId:f.name,message:m})}for(let f of e.examples){let m=eAs({context:t,websocketExample:f});t.builder.addChannelExample(r,{example:m})}}function xli(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="grouped"}var CI="Base",sAs="Default";function iAs(e){try{return new URL(e).hostname}catch{return}}function oAs(e){return e??sAs}function myl(e,t){let r=new Map;for(let n of e){if(xli(n)||!("url"in n)||!n.url)continue;let i=iAs(n.url)??n.url;r.has(i)||r.set(i,{environmentName:oAs(n.name),httpServers:[],websocketServers:[]}),r.get(i)?.httpServers.push({name:n.name,url:n.url,audiences:n.audiences})}for(let n of t){let i=iAs(n.url)??n.url;r.has(i)||r.set(i,{environmentName:oAs(n.name),httpServers:[],websocketServers:[]}),r.get(i)?.websocketServers.push(n)}return r}function QOe(e){return Object.entries(e).reduce((t,[r,n])=>(WF(n)?Object.entries(n.urls).forEach(([i,o])=>{t[i]=o}):t[r]=typeof n=="string"?n:n.url,t),{})}function aAs(e){if(e.environmentOverrides!=null){for(let[E,I]of Object.entries(e.environmentOverrides.environments??{}))e.builder.addEnvironment({name:E,schema:I});e.environmentOverrides["default-environment"]!=null&&e.builder.setDefaultEnvironment(e.environmentOverrides["default-environment"]),e.environmentOverrides["default-url"]!=null&&e.builder.setDefaultUrl(e.environmentOverrides["default-url"]);return}let t={},r=[],n=e.ir.servers.some(E=>xli(E)),i=e.ir.servers;for(let E of i)if(xli(E)){let I={urls:{}},w={},x={},C={};for(let[D,z]of Object.entries(E.urls))I.urls[D]=z.defaultUrl??z.url,z.urlTemplate&&(w[D]=z.urlTemplate),z.defaultUrl&&(x[D]=z.defaultUrl),z.variables&&z.variables.length>0&&(C[D]=z.variables);(Object.keys(w).length>0||Object.keys(C).length>0)&&(I["url-templates"]=w,I["default-urls"]=x,I.variables=C),E.name&&(t[E.name]=I)}else if("url"in E&&E.url){let w=E.urlTemplate!=null&&E.variables!=null&&E.variables.length>0?{url:E.url,audiences:E.audiences,"default-url":E.defaultUrl,"url-template":E.urlTemplate,variables:E.variables?.map(x=>({id:x.id,default:x.default,values:x.values}))}:E.audiences?{url:E.url,audiences:E.audiences}:E.url;if(E.name==null){r.push(w);continue}t[E.name]=w}let o={},s={},a=[],c={},u={},l={};for(let E of e.ir.endpoints)for(let I of E.servers){if(I.url==null&&I.name!=null){o[I.name]||(o[I.name]=[]);continue}if(I.url==null)continue;let w=I,x="defaultUrl"in I&&typeof w.defaultUrl=="string"?w.defaultUrl:void 0,C="urlTemplate"in I&&typeof w.urlTemplate=="string"?w.urlTemplate:void 0,_="variables"in I&&Array.isArray(w.variables)?w.variables:void 0,D=x??I.url,z=I.audiences?{url:D,audiences:I.audiences}:D;if(I.name==null){a.push(z);continue}o[I.name]||(o[I.name]=[]),o[I.name]?.push({url:D,audiences:I.audiences}),s[I.name]=z,C&&I.name&&(c[I.name]=C),x&&I.name&&(u[I.name]=x),_&&_.length>0&&I.name&&(l[I.name]=_)}let p={},d=[];for(let E of e.ir.websocketServers){e.logger.debug(`[buildEnvironments] Processing WebSocket server: name="${E.name}", url="${E.url}"`);let I=E.audiences?{url:E.url,audiences:E.audiences}:E.url;if(E.name==null){d.push(I);continue}p[E.name]=I}let f=Object.keys(t).length,m=f>0,h=Object.keys(s).length>0,g=Object.keys(o).some(E=>o[E]?.length===0),A=Object.keys(p).length>0;if(e.options.groupEnvironmentsByHost&&A&&(m||e.ir.servers.length>0)){let E=Object.entries(p).map(([w,x])=>({name:w,url:typeof x=="string"?x:x.url,audiences:typeof x=="string"?void 0:x.audiences})),I=myl(i,E);if(I.size>0){let w=!0;for(let[x,C]of I.entries()){let _={},D=[...C.httpServers.map(q=>({...q,isHttp:!0})),...C.websocketServers.map(q=>({...q,isHttp:!1}))],z=new Map;for(let q of D){let U=tIt(q.url),$=Rar(q.url);U&&$&&(z.has(U)||z.set(U,new Set),z.get(U)?.add($))}if(C.httpServers.length>0){let q=C.httpServers[0];q!=null&&(_[CI]=q.url,e.setUrlId(q.url,CI));for(let U=1;U<C.httpServers.length;U++){let $=C.httpServers[U];if($!=null){let re=tIt($.url),V=Rar($.url),W=re?z.get(re):void 0,ge=W&&W.size>1,K=ge&&V!=="https"?`${re}_${V}`:re||`Http${U+1}`;e.logger.debug(`[buildEnvironments] HTTP server: url="${$.url}", pathSegment="${re}", protocol="${V}", hasCollision=${ge}, urlId="${K}"`),_[K]=$.url,e.setUrlId($.url,K)}}}for(let q of C.websocketServers){let U=tIt(q.url),$=Rar(q.url),re=U?z.get(U):void 0,V=re&&re.size>1,W=V?`${U}_${$}`:Far(q.name,q.url,!0);e.logger.debug(`[buildEnvironments] WebSocket server: name="${q.name}", url="${q.url}", pathSegment="${U}", protocol="${$}", hasCollision=${V}, urlId="${W}"`),_[W]=q.url,e.setUrlId(q.url,W)}if(Object.keys(_).length>1)e.builder.addEnvironment({name:C.environmentName,schema:{urls:_}});else if(Object.keys(_).length===1){let q=Object.values(_)[0];q!=null&&e.builder.addEnvironment({name:C.environmentName,schema:q})}w&&(e.options.inferDefaultEnvironment!==!1&&e.builder.setDefaultEnvironment(C.environmentName),Object.keys(_).length>1&&e.builder.setDefaultUrl(CI),w=!1)}return}}if(!m&&!h&&A&&e.ir.servers.length===0){for(let[E,I]of Object.entries(p))e.builder.addEnvironment({name:E,schema:I});e.options.inferDefaultEnvironment!==!1&&e.builder.setDefaultEnvironment(Object.keys(p)[0]),e.builder.setDefaultUrl(CI);return}if(a.length>0&&e.logger.debug(`Skipping endpoint level servers ${a.map(E=>typeof E=="string"?E:E.url).join(", ")} because x-fern-server-name was not provided.`),!m){let E=e.ir.servers[0],I=E?.url,w=E?.audiences,x=E?.defaultUrl,C=E?.urlTemplate,_=E?.variables;if(I!=null){let z=C!=null&&_!=null&&_.length>0?{url:I,audiences:w,"default-url":x,"url-template":C,variables:_?.map(q=>({id:q.id,default:q.default,values:q.values}))}:w?{url:I,audiences:w}:I;t[sAs]=z}}let b=Object.values(t).map(E=>typeof E=="string"?E:WF(E)?Object.values(E.urls)[0]:E.url),v=r.filter(E=>{let I=typeof E=="string"?E:E.url;return!b.includes(I)});if(v.length>0&&e.logger.debug(`Skipping top level servers ${v.map(E=>typeof E=="string"?E:E.url).join(", ")} because x-fern-server-name was not provided.`),n){let E=!0;for(let[I,w]of Object.entries(t))if(e.builder.addEnvironment({name:I,schema:w}),E){if(e.options.inferDefaultEnvironment!==!1&&e.builder.setDefaultEnvironment(I),WF(w)){let x=Object.keys(w.urls)[0];x&&e.builder.setDefaultUrl(x)}E=!1}return}if(!h&&!g){let E=!0;for(let[I,w]of Object.entries(t))if(E){if(A){let x=typeof w=="string"?w:WF(w)?Object.values(w.urls)[0]:w["default-url"]??w.url;x!=null&&e.setUrlId(x,CI),e.builder.addEnvironment({name:I,schema:{urls:{[CI]:x??"",...QOe(p)}}})}else e.builder.addEnvironment({name:I,schema:w});e.options.inferDefaultEnvironment!==!1&&e.builder.setDefaultEnvironment(I),E=!1}else if(A){let x=typeof w=="string"?w:WF(w)?Object.values(w.urls)[0]:w["default-url"]??w.url;x!=null&&e.setUrlId(x,CI),e.builder.addEnvironment({name:I,schema:{urls:{[CI]:x??"",...QOe(p)}}})}else e.builder.addEnvironment({name:I,schema:w});A&&e.builder.setDefaultUrl(CI)}else if(f===1){let E=Object.keys(t)[0],I=Object.values(t)[0],w=typeof I=="string"?I:WF(I)?Object.values(I.urls)[0]:I["default-url"]??I.url,x={},C={},_={};typeof I!="string"&&!WF(I)&&(I["url-template"]&&(x[CI]=I["url-template"]),I["default-url"]&&(C[CI]=I["default-url"]),I.variables&&I.variables.length>0&&(_[CI]=I.variables)),Object.assign(x,c),Object.assign(C,u),Object.assign(_,l);let D=Object.keys(x).length>0||Object.keys(_).length>0;w!=null&&e.setUrlId(w,CI);let z={urls:{[CI]:w??"",...QOe(s),...QOe(p)},...D?{"url-templates":x,"default-urls":C,variables:_}:{}};e.builder.addEnvironment({name:E,schema:z}),e.options.inferDefaultEnvironment!==!1&&e.builder.setDefaultEnvironment(E),e.builder.setDefaultUrl(CI)}else{let E=new Map;for(let I of e.ir.endpoints)for(let w of I.servers)if(w.url!=null&&w.name!=null){E.has(w.name)||E.set(w.name,new Map);let x=w.url.match(/[-]([a-z0-9]+)\./i)?.[1]?.toLowerCase()||"production",C=E.get(w.name);C&&C.set(x,w.url)}if(E.size>0){let I=!0;for(let[w,x]of Object.entries(t)){let C=typeof x=="string"?x:WF(x)?Object.values(x.urls)[0]:x["default-url"]??x.url;if(!C)continue;e.setUrlId(C,CI);let _=C.match(/[-]([a-z0-9]+)\./i)?.[1]?.toLowerCase()||"production",D={[CI]:C};for(let[z,q]of E.entries()){let U=q.get(_)||q.get("production")||q.values().next().value;U&&(D[z]=U)}A&&Object.assign(D,QOe(p)),Object.keys(D).length>1?e.builder.addEnvironment({name:w,schema:{urls:D}}):e.builder.addEnvironment({name:w,schema:C}),I&&(e.options.inferDefaultEnvironment!==!1&&e.builder.setDefaultEnvironment(w),I=!1)}E.size>0&&e.builder.setDefaultUrl(CI)}else{let I=!0;for(let[w,x]of Object.entries(t)){if(A||Object.keys(s).length>0){let C=typeof x=="string"?x:WF(x)?Object.values(x.urls)[0]:x["default-url"]??x.url;C!=null&&e.setUrlId(C,CI),e.builder.addEnvironment({name:w,schema:{urls:{[CI]:C??"",...QOe(s),...QOe(p)}}})}else e.builder.addEnvironment({name:w,schema:x});I&&(e.options.inferDefaultEnvironment!==!1&&e.builder.setDefaultEnvironment(w),I=!1)}}}}sA();Bi();var _li=class{schema;count=0;constructor(t){this.schema=t}increment(){this.count+=1}},hyl=.75,gyl=new Set(["authorization"]);function cAs(e){if(e.globalHeaderOverrides!=null){for(let[r,n]of Object.entries(e.globalHeaderOverrides.headers??{}))e.builder.addGlobalHeader({name:r,schema:n});return}let t=Object.fromEntries((e.ir.globalHeaders??[]).map(r=>[r.header,r]));for(let[r,n]of Object.entries(t)){let o=n.optional===!0?"optional<string>":"string",s=o;if(n.name==null&&n.env==null&&typeof n.schema=="string")s=n.schema;else if(n!=null){let a=n.schema?qse(n.schema):void 0,c=a!=null?Wse(a):void 0,u=Qs.of("api.yml");s={name:n.name,env:n.env,type:n.schema!=null?bp(pc({schema:n.schema,context:e,fileContainingReference:c?H0(Qs.of(Vn(c)),u):u,namespace:c,declarationDepth:0}))??o:o}}e.builder.addGlobalHeader({name:r,schema:s})}if(e.options.detectGlobalHeaders){let r={};for(let i of e.ir.endpoints)for(let o of i.headers){if(gyl.has(o.name.toLowerCase()))continue;let s=r[o.name];if(s==null){let a=t[o.name],c=S$({header:{...o,schema:a?.schema??o.schema,name:a?.name??o.name},fileContainingReference:Qs.of(Y0),context:e,namespace:void 0});s=new _li(c),r[o.name]=s}s.increment()}let n=e.ir.endpoints.length*hyl;for(let[i,o]of Object.entries(r)){let s=t[i],a=o.count===e.ir.endpoints.length,c=o.count>=n;s==null&&(a?e.builder.addGlobalHeader({name:i,schema:o.schema}):c&&e.builder.addGlobalHeader({name:i,schema:kOe(o.schema)}))}}}sA();function uAs(e){for(let t of e.ir.idempotencyHeaders??[]){let r=t.schema?qse(t.schema):void 0,n=r!=null?Wse(r):void 0,i=S$({header:{...t,schema:t.schema??ba.primitive({description:void 0,availability:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0,schema:ol.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0})}),name:t.name??t.header,parameterNameOverride:void 0,description:void 0,availability:void 0,source:void 0},fileContainingReference:Qs.of(Y0),context:e,namespace:n});e.builder.addIdempotencyHeader({name:t.header,schema:kOe(i)})}}St();sA();St();St();function pT(e){switch(e.type){case"primitive":return pAs(e.value);case"object":return fAs(e.properties);case"array":return dAs(e.value);case"map":return yyl(e.value);case"oneOf":return byl(e.value);case"enum":return typeof e.value=="string"&&e.value.startsWith("$")?`\\${e.value}`:e.value;case"literal":return Eyl(e.value);case"unknown":return pT(e.value);case"null":return null;default:Be(e)}}function lAs(e){switch(e.type){case"withStreaming":return e.sse?{stream:Ayl(e.events)}:{stream:dAs(e.events)};case"withoutStreaming":return{body:pT(e.value)};default:Be(e)}}function pAs(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`\\${e.value}`:e.value;case"datetime":try{return!e.value.endsWith("Z")&&!e.value.includes("+")&&(e.value+="Z"),new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"datetimeRfc2822":return e.value;case"date":return e.value;case"base64":case"boolean":return e.value;default:Be(e)}}function fAs(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,pT(r)]))}function Ayl(e){return e.map(t=>({event:"",data:pT(t)}))}function dAs(e){return e.map(t=>pT(t))}function yyl(e){return Object.fromEntries(e.map(t=>[pAs(t.key),pT(t.value)]))}function byl(e){return e.type==="discriminated"?fAs(e.value):pT(e.value)}function Eyl(e){switch(e.type){case"string":return e.value.startsWith("$")?`\\${e.value}`:e.value;case"boolean":return e.value;default:Be(e)}}function mAs({endpointExample:e,context:t}){let r={};if(e.type!=="full")return e.value;e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.pathParameters!=null&&e.pathParameters.length>0&&(r["path-parameters"]=vyl(e.pathParameters)),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=Iyl(e.queryParameters));let n=e.headers!=null&&e.headers.length>0,i=t.builder.getGlobalHeaders(),o=Object.keys(i).length>0,s=new Set(e.headers?.map(a=>a.name)??[]);if(n||o){let a=[];if(e.headers!=null)for(let c of e.headers)c.name!==t.builder.getAuthHeaderName()&&a.push(c);for(let[c,u]of Object.entries(i)){if(u!=null&&typeof u=="object"&&u.type!=null){let l=$E({type:u.type,_default:void 0,validation:void 0,visitor:{primitive:pt,map:pt,list:pt,optional:p=>p,nullable:p=>p,set:pt,named:pt,literal:p=>{if(p.type==="string")return p.string;if(p.type==="boolean")return p.boolean.toString()},unknown:pt}});if(l!=null){let p=a.findIndex(f=>f.name===c),d={name:c,value:lc.literal(Che.string(l))};p>=0?a[p]=d:a.push(d);continue}}s.has(c)||a.push({name:c,value:lc.primitive(hs.string(c))})}r.headers=wyl({context:t,namedFullExamples:a})}return e.request!=null&&(r.request=pT(e.request)),e.response!=null&&(r.response=lAs(e.response)),e.codeSamples!=null&&e.codeSamples.length>0&&(r["code-samples"]=e.codeSamples.map(a=>a.type==="language"?{name:a.name??void 0,docs:a.description??void 0,language:a.language,code:a.code,install:a.install??void 0}:{name:a.name??void 0,docs:a.description??void 0,sdk:a.sdk,code:a.code}).filter(ya)),r}function vyl(e){let t={};return e.forEach(r=>{let n=pT(r.value);n!=null&&(t[r.parameterNameOverride??r.name]=n)}),t}function Iyl(e){let t={};return e.forEach(r=>{let n=pT(r.value);Array.isArray(n)?t[r.name]=n[0]:n!=null&&(t[r.name]=n)}),t}function wyl({context:e,namedFullExamples:t}){let r={};return t.forEach(n=>{let i=pT(n.value);i!=null&&(r[n.name]=i)}),r}var ZS;(function(e){e[e.Channel=0]="Channel",e[e.Endpoint=1]="Endpoint",e[e.Request=2]="Request",e[e.Webhook=3]="Webhook"})(ZS||(ZS={}));function hAs(e){return Cx._visit(e,{get:()=>Sm.HttpMethodSchema.Get,post:()=>Sm.HttpMethodSchema.Post,put:()=>Sm.HttpMethodSchema.Put,patch:()=>Sm.HttpMethodSchema.Patch,delete:()=>Sm.HttpMethodSchema.Delete,head:()=>Sm.HttpMethodSchema.Head,options:()=>{throw new Error("OPTIONS is unsupported")},trace:()=>{throw new Error("TRACE is unsupported")},_other:()=>{throw new Error("Unknown http method is unsupported")}})}function Sli(e){return e==="POST"||e==="PUT"||e==="PATCH"}function gAs({endpoint:e,declarationFile:t,context:r}){let n=[],i=new Set,o=e.path,s=kar(e.sdkName,e.namespace),a={};for(let h of e.pathParameters)h.parameterNameOverride&&(o=o.replace(h.name,h.parameterNameOverride)),a[h.parameterNameOverride??h.name]=Oar({pathParameter:h,context:r,fileContainingReference:t,namespace:s}),i.add(h.name);let c={};for(let h of e.queryParameters){let g=Dar({queryParameter:h,context:r,fileContainingReference:t,namespace:s});g!=null&&(c[h.name]=g,i.add(h.name))}let u;if(e.pagination!=null)switch(e.pagination.type){case"cursor":u={cursor:e.pagination.cursor,next_cursor:e.pagination.nextCursor,results:e.pagination.results};break;case"offset":u={offset:e.pagination.offset,step:e.pagination.step,results:e.pagination.results,"has-next-page":e.pagination.hasNextPage};break;case"custom":u={type:"custom",results:e.pagination.results};break;case"uri":u={next_uri:e.pagination.nextUri,results:e.pagination.results};break;case"path":u={next_path:e.pagination.nextPath,results:e.pagination.results};break;default:Be(e.pagination)}let l={path:o,method:hAs(e.method),auth:Cyl({endpoint:e,context:r}),docs:e.description??void 0,pagination:u,source:e.source!=null?Gse(e.source):void 0};!Byl({context:r,request:e.request})&&Object.keys(a).length>0&&(l["path-parameters"]=a),e.summary!=null&&(l["display-name"]=e.summary);let p={},d=r.builder.getGlobalHeaderNames(),f=r.builder.getAuthHeaderName();f!=null&&d.add(f);let m=e.headers.filter(h=>!d.has(h.name));for(let h of m){let g=S$({header:h,context:r,fileContainingReference:t,namespace:s});p[h.name]=g,i.add(typeof g=="string"?h.name:g.name??h.name)}if(e.request!=null){r.setInState(ZS.Request);let h=Syl({endpoint:e,context:r,declarationFile:t,request:e.request,generatedRequestName:e.generatedRequestName,requestNameOverride:e.requestNameOverride??void 0,pathParameters:r.options.inlinePathParameters&&Object.keys(a).length>0?a:void 0,queryParameters:Object.keys(c).length>0?c:void 0,headers:Object.keys(p).length>0?p:void 0,usedNames:i,namespace:s});l.request=h.value,n=[...n,...h.schemaIdsToExclude??[]],r.unsetInState(ZS.Request)}else{let h=r.options.inlinePathParameters&&Object.keys(a).length>0,g=Object.keys(c).length>0,A=Object.keys(p).length>0,b={};(h||g||A)&&(b.name=e.requestNameOverride??e.generatedRequestName),h&&(b["path-parameters"]=a),g&&(b["query-parameters"]=c),A&&(b.headers=p),Object.keys(b).length>0&&(l.request=b)}if(e.response!=null&&e.response._visit({json:h=>{let g=pc({schema:h.schema,context:r,fileContainingReference:t,namespace:s,declarationDepth:0});l.response={docs:h.description??void 0,type:bp(g)},h.statusCode!=null&&(l.response["status-code"]=h.statusCode),h.responseProperty!=null&&(l.response.property=h.responseProperty)},streamingJson:h=>{let g=pc({schema:h.schema,context:r,fileContainingReference:t,namespace:s,declarationDepth:0});l["response-stream"]={docs:h.description??void 0,type:bp(g),format:"json",terminator:h.terminator??void 0}},streamingSse:h=>{let g=pc({schema:h.schema,context:r,fileContainingReference:t,namespace:s,declarationDepth:0});l["response-stream"]={docs:h.description??void 0,type:bp(g),format:"sse",terminator:h.terminator??void 0}},file:h=>{l.response={docs:h.description??void 0,type:"file","status-code":h.statusCode}},bytes:h=>{l.response={docs:h.description??void 0,type:"bytes","status-code":h.statusCode}},streamingText:h=>{l["response-stream"]={docs:h.description??void 0,type:"text"}},text:h=>{l.response={docs:h.description??void 0,type:"text","status-code":h.statusCode}},_other:()=>{throw new Error("Unrecognized Response type: "+e.response?.type)}}),r.builder.getEnvironmentType()==="multi"){let h=r.getDefaultServerName(),g=e.servers[0];if(g==null)h!=null&&(l.url=h);else{let A=g.url!=null?r.getUrlId(g.url):void 0;l.url=A??g.name??void 0}}return e.idempotent&&(l.idempotent=!0),e.availability!=null&&(l.availability=ab(e.availability)),Object.entries(e.errors).forEach(([h,g])=>{let A=g.generatedName,b=Qs.of(tf);r.builder.enableUniqueErrorsPerEndpoint&&(A=`${e.generatedRequestName}${g.generatedName}`,g.schema!=null&&(g.schema.type!=="reference"&&g.schema.type!=="oneOf"?g.schema.generatedName=`${e.generatedRequestName}${g.schema.generatedName}`:g.schema.type==="oneOf"&&(g.schema.value.generatedName=`${e.generatedRequestName}${g.schema.value.generatedName}`)));let v={"status-code":parseInt(h)},E=zgs({location:AAs,namespaceOverride:s});if(g.schema!=null){let x=pc({schema:g.schema,context:r,fileContainingReference:E,declarationFile:E,namespace:s,declarationDepth:0});v.type=bp(x),v.docs=g.description}r.builder.addError(E,{name:A,schema:r.isErrorUnknownSchema(parseInt(h))?{...v,type:"unknown"}:v}),l.errors==null&&(l.errors=[]);let I=r.builder.addImport({file:t,fileToImport:E});l.errors.push(I!=null?`${I}.${A}`:A),v.type!=null&&g.examples?.forEach(x=>{let C={value:pT(x.example),name:x.name,docs:x.description};r.builder.addErrorExample(E,{name:A,example:C})})}),e.examples.length>0&&(l.examples=xyl({endpointExamples:e.examples,context:r})),e.retries!=null&&(l.retries=_yl({retries:e.retries})),r.ir.hasEndpointsMarkedInternal&&(e.internal==null||!e.internal)?l.audiences=[Bli,...e.audiences]:e.audiences.length>0&&(l.audiences=e.audiences),{value:l,schemaIdsToExclude:n}}function Cyl({endpoint:e,context:t}){if(e.security==null)return t.authOverrides?.auth!=null?!0:t.ir.security==null?void 0:t.ir.security.length>0?!0:void 0;if(e.security.length!==0)return JSON.stringify(e.security)===JSON.stringify(t.ir.security)?!0:e.security}function xyl({endpointExamples:e,context:t}){return e.map(r=>{try{return mAs({endpointExample:r,context:t})}catch(n){throw console.error(`Error building endpoint example: ${n}`),n}})}function _yl({retries:e}){if(e!=null){if(e.type==="disabled")return{disabled:e.value??void 0};Be(e)}}function Syl({endpoint:e,declarationFile:t,context:r,request:n,requestNameOverride:i,generatedRequestName:o,pathParameters:s,queryParameters:a,headers:c,usedNames:u,namespace:l}){if(n.type==="json"||n.type==="formUrlEncoded"){let p=n.schema.type==="reference"?n.schema.schema:void 0,d=n.schema.type==="reference"?r.getSchema(n.schema.schema,l):n.schema;if(d?.type!=="object"||p!=null&&r.isResponseReachable(p)){let I=r.options.respectReadonlySchemas&&Sli(e.method)?"write":void 0,w=pc({schema:n.schema,fileContainingReference:t,context:r,namespace:l,declarationDepth:0,variant:I}),x={schemaIdsToExclude:[],value:{body:w}},C=Object.keys(s??{}).length>0,_=Object.keys(a??{}).length>0,D=Object.keys(c??{}).length>0;return C&&(x.value["path-parameters"]=s),_&&(x.value["query-parameters"]=a),D&&(x.value.headers=c),(C||_||D)&&(x.value.name=i??o),n.contentType!=null&&(x.value["content-type"]=n.contentType),n.description!=null&&(x.value.docs=n.description),x}let f=new Map;for(let E of d.allOf){let I=r.getSchema(E.schema,l);if(I==null)continue;let w=qse(I),x=Vse(w),{properties:C}=U6e(r,E.schema,l);for(let _ of C)f.set(_.key,x)}let m=Object.fromEntries(d.properties.filter(E=>E.readonly==null?!0:!(Sli(e.method)&&E.readonly)).map(E=>{let I=f.get(E.key)??t,w=pc({schema:E.schema,fileContainingReference:t,declarationFile:I,context:r,namespace:l,declarationDepth:1}),x=E.nameOverride??E.key,C=ab(E.availability);if(!u.has(x)&&E.audiences.length<=0)return u.add(x),E.nameOverride!=null?[E.key,{type:bp(w),docs:M6e(w),name:E.nameOverride,availability:C}]:[E.key,C?{...typeof w=="string"?{type:w}:w,availability:C}:w];let _={type:bp(w),docs:M6e(w)};return u.has(x)&&(_.name=E.generatedName),E.audiences.length>0&&(_.audiences=E.audiences),C!=null&&(_.availability=C),u.add(x),[E.key,_]})),h=new Set,g=new Set;for(let E of d.allOfPropertyConflicts)E.allOfSchemaIds.forEach(I=>h.add(I)),E.conflictingTypeSignatures&&g.add(E.propertyKey);let A=[];for(let E of d.allOf){let I=Tar({schema:E.schema,context:r,namespace:l});if(I==null||h.has(E.schema)||h.has(I))continue;let w=pc({schema:ba.reference(E),fileContainingReference:t,context:r,namespace:l,declarationDepth:0}),x=L6e(bp(w));x!=="unknown"&&A.push(x)}for(let E of h){let I=U6e(r,E,l),w=r.getSchema(E,l),x=w!=null?Vse(qse(w)):t;for(let C of I.properties)m[C.key]==null&&(g.has(C.key)?m[C.key]="unknown":m[C.key]=pc({schema:C.schema,fileContainingReference:t,declarationFile:x,context:r,namespace:l,declarationDepth:1}));for(let C of I.allOf){if(h.has(C.schema))continue;let _=pc({schema:ba.reference(C),fileContainingReference:t,context:r,namespace:l,declarationDepth:0}),D=L6e(bp(_));D!=="unknown"&&!A.includes(D)&&A.push(D)}}let b={properties:m};A.length>0&&(b.extends=A),n.additionalProperties&&(b["extra-properties"]=!0);let v={name:i??d.nameOverride??d.generatedName,"path-parameters":s,"query-parameters":a,headers:c,body:b};return n.contentType!=null&&(v["content-type"]=n.contentType),n.description!=null&&(v.docs=n.description),{schemaIdsToExclude:p!=null?[p]:[],value:v}}else if(n.type==="octetStream"){let p={body:"bytes","content-type":n.contentType??vf.APPLICATION_OCTET_STREAM,"query-parameters":a};return a!=null&&(p.name=i??o),n.description!=null&&(p.docs=n.description),{schemaIdsToExclude:[],value:p}}else if(n.type==="multipart"){let p=Object.fromEntries(n.properties.map(d=>{if(d.schema.type==="file"){let f=d.schema.isArray?"list<file>":"file";if(f=d.schema.isOptional?`optional<${f}>`:f,d.description!=null||d.contentType!=null){let m={type:f};if(d.description!=null&&(m.docs=d.description),d.contentType!=null){let h=d.contentType.split(",")[0];m["content-type"]=h}return[d.key,m]}return[d.key,f]}else{let f=pc({schema:d.schema.value,fileContainingReference:t,context:r,namespace:l,declarationDepth:1});if(d.contentType||d.exploded||d.encoding){let m=typeof f=="string"?{type:f}:f;d.contentType!=null&&(m["content-type"]=d.contentType),d.encoding==="form"?m.style="form":d.encoding==="json"?m.style="json":d.exploded&&(m.style="exploded"),f=m}return[d.key,f]}}));return{schemaIdsToExclude:n.name==null?[]:[n.name],value:{name:i??n.name??o,"path-parameters":s,"query-parameters":a,headers:c,body:{properties:p},"content-type":vf.MULTIPART_FORM_DATA,...n.description?{docs:n.description}:{}}}}else Be(n)}function Byl({context:e,request:t}){if(!e.options.inlinePathParameters)return!1;if(t==null)return!0;switch(t.type){case"octetStream":return!1;case"multipart":return!0;case"json":return!0;case"formUrlEncoded":return!0;default:Be(t)}}sA();Bi();function Tyl({location:e,namespaceOverride:t}){return t!=null?{...e,file:H0(Qs.of(t),e.file)}:e}function Oyl(e){let t=e.namespace,r=e.tags.filter(c=>c!==t)[0],n=e.operationId;if(n==null)return r!=null?{file:Qs.of(`${Vn(r)}.yml`),endpointId:e.summary!=null?Vn(e.summary):Vn(`${e.method}_${e.path.split("/").join("_")}`)}:e.summary!=null?{file:Qs.of(tf),endpointId:Vn(e.summary)}:{file:Qs.of(tf),endpointId:Vn(`${e.method}_${e.path.split("/").join("_")}`)};if(r==null)return{file:Qs.of(tf),endpointId:n};let i=rIt(r),o=rIt(n);if($0(i,o))return{file:Qs.of("__package__.yml"),endpointId:r};let s=Ryl({operationId:n,tag:r,path:e.path,method:e.method});if(s!=null)return s;let a=[];for(let c=0;c<i.length;++c){let u=i[c];if(u!=null&&u===o[c])a.push(u);else{let l=Vn(r);return{file:Qs.of(`${l}.yml`),endpointId:n,tag:r}}}if(a.length>=o.length)throw new Error(`Cannot get file for endpoint ${JSON.stringify(e)}`);return{file:Qs.of(Vn(a.join("_"))+".yml"),endpointId:Vn(o.slice(a.length).join("_")),tag:r}}function nIt(e){let t=e.tags[0];if(e.sdkName!=null){let r=fli({sdkName:e.sdkName,namespaceOverride:e.namespace}),n=`${r}.yml`,i=r.toLowerCase()===t?.toLowerCase().replaceAll(" ","");return{file:Qs.of(n),endpointId:e.sdkName.methodName,tag:i?t:void 0}}return Tyl({namespaceOverride:e.namespace,location:Oyl(e)})}function rIt(e){let t;return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)?t=e.split(/(?=[A-Z])/):t=e.split(/[^a-zA-Z0-9]+/),t=t.map(r=>r.toLowerCase()),t=sU(t),t}var Pyl=new RegExp("[^a-zA-Z0-9{}]+"),Dyl=new RegExp("[{}]","g");function Ryl({operationId:e,tag:t,path:r,method:n}){let o=`${r.split(Pyl).join("_").replaceAll(Dyl,"_")}_${n.toLowerCase()}`;if(e.endsWith(o))return{file:Qs.of(Vn(t)+".yml"),endpointId:Vn(e.slice(0,-1*o.length)),tag:t}}function yAs(e){let t=new Set,{endpoints:r,tags:n}=e.ir,i=[];for(let o of r){let{endpointId:s,file:a,tag:c}=nIt(o),u=a.split(".")[0];u!=null&&t.add(u);let l;if(o.sdkName!=null){let f=e.ir.groups;for(let m of o.sdkName.groupName){let h=typeof m=="string"?m:m.name,g=f[h];if(g==null)break;if(g.summary!=null||g.description!=null){l=f[h];break}}}let p=c==null?void 0:n.tagsById[c];e.setInState(ZS.Endpoint),e.setEndpointMethod(o.method);let d=gAs({context:e,endpoint:o,declarationFile:a});e.unsetEndpointMethod(),e.unsetInState(ZS.Endpoint),i=[...i,...d.schemaIdsToExclude],e.builder.addEndpoint(a,{name:s,schema:d.value,source:o.source!=null?Gse(o.source):void 0}),(p?.id!=null||p?.description!=null)&&e.builder.setServiceInfo(a,{"display-name":l?.summary??p?.id,docs:l?.description??p?.description??void 0})}return{schemaIdsToExclude:i,sdkGroups:t}}sA();function bAs(e){for(let[t,r]of Object.entries(e.ir.variables)){let n=r.groupName!=null?Wse(r.groupName):void 0,i=pc({schema:ba.primitive(r),context:e,fileContainingReference:Qs.of(tf),namespace:n,declarationDepth:0});e.builder.addVariable({name:t,schema:{type:bp(i),docs:r.description??void 0}})}}sA();Bi();function IAs(e){for(let t of e.ir.webhooks){let r=Nyl({webhook:t,context:e});if(r==null)continue;let n=kar(t.sdkName,t.namespace),i={};for(let s of t.headers)i[s.name]=S$({header:s,context:e,fileContainingReference:r.file,namespace:n});let o={audiences:t.audiences,method:t.method,"display-name":t.summary??void 0,headers:i,payload:pc({schema:t.payload,context:e,fileContainingReference:r.file,namespace:n,declarationDepth:0}),signature:Qyl(t.signatureVerification),examples:t.examples!=null?t.examples.map(s=>({docs:s.description,name:s.name,payload:pT(s.payload)})):void 0};t.response!=null&&t.response._visit({json:s=>{let a=pc({schema:s.schema,context:e,fileContainingReference:r.file,namespace:n,declarationDepth:0});o.response={docs:s.description??void 0,type:bp(a)},s.statusCode!=null&&(o.response["status-code"]=s.statusCode)},file:s=>{o.response={docs:s.description??void 0,type:"file","status-code":s.statusCode}},bytes:s=>{o.response={docs:s.description??void 0,type:"bytes","status-code":s.statusCode}},text:s=>{o.response={docs:s.description??void 0,type:"text","status-code":s.statusCode}},streamingJson:s=>{let a=pc({schema:s.schema,context:e,fileContainingReference:r.file,namespace:n,declarationDepth:0});o["response-stream"]={docs:s.description??void 0,type:bp(a),format:"json"}},streamingSse:s=>{let a=pc({schema:s.schema,context:e,fileContainingReference:r.file,namespace:n,declarationDepth:0});o["response-stream"]={docs:s.description??void 0,type:bp(a),format:"sse"}},streamingText:s=>{o["response-stream"]={docs:s.description??void 0,type:"text"}},_other:()=>{throw new Error("Unrecognized Response type: "+t.response?.type)}}),e.builder.addWebhook(r.file,{name:r.endpointId,schema:o}),t.description!=null&&(o.docs=t.description)}}function Fyl({location:e,namespaceOverride:t}){if(e!=null)return t!=null?{...e,file:H0(Qs.of(t),e.file)}:e}function kyl({webhook:e,context:t}){let r=e.tags[0],n=e.operationId;if(r==null)return{file:Qs.of(tf),endpointId:n};let i=rIt(r),o=rIt(n);if($0(i,o))return{file:Qs.of("__package__.yml"),endpointId:r};let s=[];for(let a=0;a<i.length;++a){let c=i[a];if(c!=null&&c===o[a])s.push(c);else{let u=Vn(r);return{file:Qs.of(`${u}.yml`),endpointId:n,tag:r}}}if(s.length>=o.length){t.logger.warn(`Skipping webhook ${e.operationId} because couldn't compute file location`);return}return{file:Qs.of(Vn(s.join("_"))+".yml"),endpointId:Vn(o.slice(s.length).join("_")),tag:r}}function Nyl({webhook:e,context:t}){return e.sdkName!=null?{file:Ugs({sdkName:e.sdkName,namespaceOverride:e.namespace}),endpointId:e.sdkName.methodName}:Fyl({namespaceOverride:e.namespace,location:kyl({webhook:e,context:t})})}function Qyl(e){if(e!=null)switch(e.type){case"hmac":return{type:"hmac",header:e.header,algorithm:jyl(e.algorithm),encoding:EAs(e.encoding),"signature-prefix":e.signaturePrefix,"payload-format":Lyl(e.payloadFormat),timestamp:vAs(e.timestamp)};case"asymmetric":return{type:"asymmetric",header:e.header,"asymmetric-algorithm":Myl(e.asymmetricAlgorithm),encoding:EAs(e.encoding),"signature-prefix":e.signaturePrefix,"jwks-url":e.jwksUrl,"key-id-header":e.keyIdHeader,timestamp:vAs(e.timestamp)};default:return}}function jyl(e){if(e!=null)switch(e){case"sha256":return"sha256";case"sha1":return"sha1";case"sha384":return"sha384";case"sha512":return"sha512";default:return}}function EAs(e){if(e!=null)switch(e){case"base64":return"base64";case"hex":return"hex";default:return}}function Myl(e){switch(e){case"rsa-sha256":return"rsa-sha256";case"rsa-sha384":return"rsa-sha384";case"rsa-sha512":return"rsa-sha512";case"ecdsa-sha256":return"ecdsa-sha256";case"ecdsa-sha384":return"ecdsa-sha384";case"ecdsa-sha512":return"ecdsa-sha512";case"ed25519":return"ed25519";default:return"rsa-sha256"}}function Lyl(e){if(e!=null)return{components:e.components.map(Uyl),delimiter:e.delimiter}}function Uyl(e){switch(e){case"body":return"body";case"timestamp":return"timestamp";case"notification-url":return"notification-url";case"message-id":return"message-id";default:return"body"}}function zyl(e){switch(e){case"unix-seconds":return"unix-seconds";case"unix-millis":return"unix-millis";case"iso8601":return"iso8601";default:return}}function vAs(e){if(e!=null)return{header:e.header,format:e.format!=null?zyl(e.format):void 0,tolerance:e.tolerance}}St();function khe(e,t,r){switch(e.type){case"primitive":case"enum":case"literal":case"unknown":return;case"reference":{let n=e.schema;if(r.has(n))return;r.add(n);let i=wAs(n,e.namespace,t);i!=null&&khe(i,t,r);return}case"object":for(let n of e.allOf)if(!r.has(n.schema)){r.add(n.schema);let i=wAs(n.schema,n.namespace,t);i!=null&&khe(i,t,r)}for(let n of e.properties)khe(n.schema,t,r);return;case"array":case"map":case"optional":case"nullable":khe(e.value,t,r);return;case"oneOf":Vyl(e.value,t,r);return;default:Be(e)}}function Vyl(e,t,r){switch(e.type){case"discriminated":for(let n of Object.values(e.schemas))khe(n,t,r);for(let n of e.commonProperties)khe(n.schema,t,r);return;case"undiscriminated":for(let n of e.schemas)khe(n,t,r);return;default:Be(e)}}function wAs(e,t,r){return t==null?r.rootSchemas[e]:r.namespacedSchemas[t]?.[e]}function XU(e,t,r){khe(e,t,r)}function CAs(e){let t=new Set,r=new Set,{groupedSchemas:n}=e;for(let i of e.endpoints){if(i.request!=null)switch(i.request.type){case"json":case"formUrlEncoded":XU(i.request.schema,n,t);break;case"multipart":for(let o of i.request.properties)o.schema.type==="json"&&XU(o.schema.value,n,t);break;case"octetStream":break;default:Be(i.request)}if(i.response!=null)switch(i.response.type){case"json":case"streamingJson":case"streamingSse":XU(i.response.schema,n,r);break;case"file":case"text":case"bytes":case"streamingText":break;default:Be(i.response)}for(let o of Object.values(i.errors))o.schema!=null&&XU(o.schema,n,r);for(let o of i.pathParameters)XU(o.schema,n,r);for(let o of i.queryParameters)XU(o.schema,n,r);for(let o of i.headers)XU(o.schema,n,r)}for(let i of e.webhooks)XU(i.payload,n,r);for(let i of Object.values(e.channels)){for(let o of i.messages)XU(o.body,n,r);for(let o of i.handshake.queryParameters)XU(o.schema,n,r);for(let o of i.handshake.headers)XU(o.schema,n,r);for(let o of i.handshake.pathParameters)XU(o.schema,n,r)}return{requestReachable:t,responseReachable:r}}function qyl(e){return e.type!=="object"?!1:e.properties.some(t=>t.readonly===!0)}function xAs(e,t){let r=new Set,n=new Set,i=new Set;function o(s){for(let[a,c]of Object.entries(s)){if(!qyl(c))continue;let u=t.requestReachable.has(a),l=t.responseReachable.has(a);u&&l?r.add(a):u&&!l?n.add(a):!u&&l&&i.add(a)}}o(e.groupedSchemas.rootSchemas);for(let s of Object.values(e.groupedSchemas.namespacedSchemas))o(s);return{needsBothVariants:r,requestOnlyWithReadonly:n,responseOnlyWithReadonly:i}}var Bli="external",AAs=Qs.of(tf);function _As({schemas:e,schemaIdsToExclude:t,namespace:r,context:n}){for(let[i,o]of Object.entries(e)){if(t.has(i))continue;let s=Vgs(o);if(n.options.respectReadonlySchemas&&n.needsBothVariants(i)&&o.type==="object"){let u=NOe({schema:o,context:n,declarationFile:s,namespace:r,declarationDepth:0,variant:"read"});n.builder.addType(s,{name:u.name??i,schema:u.schema});let l=NOe({schema:o,context:n,declarationFile:s,namespace:r,declarationDepth:0,skipReadonlyProperties:!0,variant:"write"});n.builder.addType(s,{name:l.name??i,schema:l.schema});continue}if(n.options.respectReadonlySchemas&&n.isRequestOnlyWithReadonly(i)&&o.type==="object"){let u=NOe({schema:o,context:n,declarationFile:s,namespace:r,declarationDepth:0,skipReadonlyProperties:!0,variant:"write"});n.builder.addType(s,{name:u.name??i,schema:u.schema});continue}let a;n.options.respectReadonlySchemas&&(a=n.isRequestOnly(i)?"write":"read");let c=Kgs({schema:o,context:n,declarationFile:s,namespace:r,declarationDepth:0,variant:a});if($me(c.schema)){let u=bp(c.schema);if(u===(c.name??i)||u===`optional<${c.name??i}>`||u===`nullable<${c.name??i}>`||u===`optional<nullable<${c.name??i}>>`)continue}n.builder.addType(s,{name:c.name??i,schema:c.schema})}}function SAs(e){e.ir.apiVersion!=null&&e.builder.setApiVersion(e.ir.apiVersion),aAs(e),cAs(e),uAs(e),Zgs(e),bAs(e),e.ir.basePath!=null&&e.builder.setBasePath(e.ir.basePath),e.ir.hasEndpointsMarkedInternal&&e.builder.addAudience(Bli);let t=yAs(e),r=t.sdkGroups;e.setInState(ZS.Webhook),IAs(e),e.unsetInState(ZS.Webhook),e.setInState(ZS.Channel);for(let i of Object.values(e.ir.channels)){let o=Vse(i.groupName);nAs({channel:i,context:e,declarationFile:o})}e.unsetInState(ZS.Channel);let n=Gyl({context:e,schemaIdsToExcludeFromServices:t.schemaIdsToExclude});if(e.options.respectReadonlySchemas){let i=CAs(e.ir),o=xAs(e.ir,i);e.setVariantPlan(o,i)}_As({schemas:e.ir.groupedSchemas.rootSchemas,schemaIdsToExclude:n,namespace:void 0,context:e});for(let[i,o]of Object.entries(e.ir.groupedSchemas.namespacedSchemas))_As({schemas:o,schemaIdsToExclude:n,namespace:i,context:e});return e.ir.tags.orderedTagIds!=null&&e.ir.tags.orderedTagIds.length>0&&e.ir.tags.orderedTagIds.every(o=>r.has(o))&&e.builder.addNavigation({navigation:e.ir.tags.orderedTagIds}),e.builder.optimizeServiceAuth(),e.builder.build()}function Gyl({context:e,schemaIdsToExcludeFromServices:t}){let r=e.getReferencedSchemaIds();if(r==null)return new Set(t);let n=new Set([...Object.keys(e.ir.groupedSchemas.rootSchemas),...Object.values(e.ir.groupedSchemas.namespacedSchemas).flatMap(o=>Object.keys(o))]),i=new Set(t);for(let o of n)r.includes(o)||i.add(o);return i}St();var iIt=class{context;constructor(t){this.context=t}};sA();Bi();sA();var Nar=class e{files={};directories={};getAllFiles(){let t={},r=(n,i)=>{for(let[s,a]of Object.entries(n.files)){let c=i!=null?Qs.of(`${i}${"/"}${s}`):Qs.of(s);t[c]=a}let o=Object.keys(n.directories).sort();for(let s of o){let a=i!=null?`${i}${"/"}${s}`:s,c=n.directories[s];r(c,a)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split("/"))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[Qs.of(t[0])]??={};let[r,...n]=t;if(r==null)throw new Error(`Internal error; cannot add file with path: ${t}`);return this.directories[r]||(this.directories[r]=new e),this.directories[r].getOrCreateFileRecursive(n)}};var jOe=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new Nar,this.rootApiFile={name:"api","error-discrimination":{strategy:"status-code"}}}setDisplayName({displayName:t}){this.rootApiFile["display-name"]=t}addNavigation({navigation:t}){this.packageMarkerFile.navigation=t}setServiceInfo(t,{auth:r,"base-path":n,"display-name":i,docs:o}){let s=this.getOrCreateFile(t);s.service==null&&(s.service={auth:!1,"base-path":"",endpoints:{}}),r!=null&&(s.service.auth=r),n!=null&&(s.service["base-path"]=n),i!=null&&(s.service["display-name"]=i),o!=null&&(s.docs=o)}addAudience(t){this.rootApiFile.audiences==null&&(this.rootApiFile.audiences=[]),this.rootApiFile.audiences.push(t)}setAuth(t){this.rootApiFile.auth=t}addAuthScheme({name:t,schema:r}){this.rootApiFile["auth-schemes"]==null&&(this.rootApiFile["auth-schemes"]={}),this.rootApiFile["auth-schemes"][t]==null&&(this.rootApiFile["auth-schemes"][t]=r)}setDefaultEnvironment(t){this.rootApiFile["default-environment"]=t}setDefaultUrl(t){this.rootApiFile["default-url"]=t}setBasePath(t){this.basePath=t}setApiVersion(t){this.rootApiFile.version=t}getEnvironmentType(){let t=Object.entries(this.rootApiFile.environments??{})[0];if(t!=null)return i$(t[1],{singleBaseUrl:()=>"single",multipleBaseUrls:()=>"multi"})}addEnvironment({name:t,schema:r}){this.rootApiFile.environments==null&&(this.rootApiFile.environments={}),this.rootApiFile.environments[t]=r}getGlobalHeaderNames(){let t=Object.keys(this.rootApiFile.headers??{});if(this.rootApiFile["auth-schemes"]!=null)for(let n of Object.values(this.rootApiFile["auth-schemes"]))BAs(n)&&t.push(n.header);let r=this.getVersionHeader();return r!=null&&t.push(r),new Set(t)}getAuthHeaderName(){if(this.rootApiFile["auth-schemes"]!=null){for(let t of Object.values(this.rootApiFile["auth-schemes"]))if(BAs(t))return t.header;return"Authorization"}}addGlobalHeader({name:t,schema:r}){let n=this.getVersionHeader();n!=null&&n===t||(this.rootApiFile.headers==null&&(this.rootApiFile.headers={}),this.rootApiFile.headers[t]=r)}getGlobalHeaders(){return this.rootApiFile.headers??{}}addIdempotencyHeader({name:t,schema:r}){this.rootApiFile["idempotency-headers"]==null&&(this.rootApiFile["idempotency-headers"]={}),this.rootApiFile["idempotency-headers"][t]=r}addVariable({name:t,schema:r}){this.rootApiFile.variables==null&&(this.rootApiFile.variables={}),this.rootApiFile.variables[t]=r}addImport({file:t,fileToImport:r,alias:n}){if(t===r)return;let i=n??Vn((gU(r)+"/"+qB(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===Qs.of(Y0))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[i]=T3e(gU(B3e.of(`/${t}`)),B3e.of(`/${r}`)),i;let o=this.getOrCreateFile(t);return o.imports==null&&(o.imports={}),o.imports[i]=T3e(gU(B3e.of(`/${t}`)),B3e.of(`/${r}`)),i}addType(t,{name:r,schema:n}){if(t===Qs.of(Y0))return;let i=this.getOrCreateFile(t);i.types==null&&(i.types={}),i.types[r]=n}addTypeExample(t,r,n){let i=this.getOrCreateFile(t);i.types==null&&(i.types={});let o=i.types[r];o!=null&&(typeof o=="string"?i.types[r]={type:o,examples:[n]}:(o.examples==null&&(o.examples=[]),o.examples.push(n)))}addError(t,{name:r,schema:n}){let i=this.getOrCreateFile(t);i.errors==null&&(i.errors={}),i.errors[r]==null?i.errors[r]=n:i.errors[r]?.type!==n.type&&(i.errors[r]={"status-code":n["status-code"],type:"unknown"})}addErrorExample(t,{name:r,example:n}){let i=this.getOrCreateFile(t);if(i.errors==null)return;let o=i.errors[r];if(o==null)return;o.examples==null&&(o.examples=[]),(o.examples.some(a=>$0(a,n))??!1)||o.examples?.push(n)}addEndpoint(t,{name:r,schema:n,source:i}){let o=this.getOrCreateFile(t);o.service==null&&(o.service={auth:!1,"base-path":"",endpoints:{}}),i!=null&&(o.service.source=i),o.service.endpoints[r]=n}addWebhook(t,{name:r,schema:n}){let i=this.getOrCreateFile(t);i.webhooks==null&&(i.webhooks={}),i.webhooks[r]=n}addChannel(t,{channel:r}){let n=this.getOrCreateFile(t);n.channel=r;let i=this.basePath;i!=null&&(n.channel.path=H0(i,r.path))}addChannelExample(t,{example:r}){let n=this.getOrCreateFile(t);n.channel==null&&(n.channel={path:"",auth:!1}),n.channel.messages==null&&(n.channel.messages={}),n.channel.examples==null&&(n.channel.examples=[]),n.channel.examples.push(r)}addChannelMessage(t,{messageId:r,message:n}){let i=this.getOrCreateFile(t);i.channel==null&&(i.channel={path:"",auth:!1}),i.channel.messages==null&&(i.channel.messages={}),i.channel.messages[r]=n}optimizeServiceAuth(){let t=[this.packageMarkerFile,...Object.values(this.root.getAllFiles())];for(let r of t){if(r.service==null)continue;let n=Object.values(r.service.endpoints);if(n.length===0)continue;if(n.every(o=>o.auth===!0)){r.service.auth=!0;for(let o of Object.values(r.service.endpoints))delete o.auth}}}build(){let t=this.root.getAllFiles(),r=this.basePath;if(r!=null){this.packageMarkerFile.service!=null&&(this.packageMarkerFile.service={...this.packageMarkerFile.service,endpoints:Object.fromEntries(Object.entries(this.packageMarkerFile.service.endpoints).map(([i,o])=>[i,{...o,path:H0(r,o.path)}]))});for(let i of Object.values(t))i.service!=null&&(i.service={...i.service,endpoints:Object.fromEntries(Object.entries(i.service.endpoints).map(([o,s])=>[o,{...s,path:H0(r,s.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===tf?this.packageMarkerFile:this.root.getOrCreateFile(t)}getVersionHeader(){if(this.rootApiFile.version!=null)return typeof this.rootApiFile.version.header=="string"?this.rootApiFile.version.header:this.rootApiFile.version.header.value}};function BAs(e){return e?.header!=null}var Qar=class{logger;taskContext;ir;builder;environmentOverrides;authOverrides;globalHeaderOverrides;options;enableUniqueErrorsPerEndpoint;defaultServerName=void 0;unknownSchema=new Set;referencedSchemaIds;urlIdMap=new Map;endpointMethod;state=new Set;schemaNameMapping=new Map;variantPlan;reachability;constructor({taskContext:t,ir:r,options:n,environmentOverrides:i,globalHeaderOverrides:o,authOverrides:s}){this.logger=t.logger,this.taskContext=t,this.ir=r,this.environmentOverrides=i,this.authOverrides=s,this.globalHeaderOverrides=o,this.options=POe({options:n}),this.enableUniqueErrorsPerEndpoint=this.options.enableUniqueErrorsPerEndpoint,this.referencedSchemaIds=this.options.onlyIncludeReferencedSchemas?new Set:void 0,this.builder=new jOe(this.enableUniqueErrorsPerEndpoint),r.title!=null&&this.builder.setDisplayName({displayName:r.title});let a={};if(!this.enableUniqueErrorsPerEndpoint)for(let c of r.endpoints)for(let[u,l]of Object.entries(c.errors)){let p=parseInt(u),d=a[p];d==null&&l.schema!=null?a[p]=l.schema:d!=null&&l.schema!=null&&ik(d,l.schema)||this.unknownSchema.add(p)}}getReferencedSchemaIds(){if(this.referencedSchemaIds!=null)return Array.from(this.referencedSchemaIds)}getSchema(t,r){return r==null?this.ir.groupedSchemas.rootSchemas[t]:this.ir.groupedSchemas.namespacedSchemas[r]?.[t]}getDefaultServerName(){return this.defaultServerName}setDefaultServerName(t){this.defaultServerName=t}setUrlId(t,r){this.urlIdMap.set(t,r)}getUrlId(t){return this.urlIdMap.get(t)}isErrorUnknownSchema(t){return this.unknownSchema.has(t)}getEndpointMethod(){return this.endpointMethod}setEndpointMethod(t){this.endpointMethod=t}unsetEndpointMethod(){this.endpointMethod=void 0}isInState(t){return this.state.has(t)}setInState(t){this.state.add(t)}unsetInState(t){this.state.delete(t)}shouldMarkSchemaAsReferenced(){return this.options.onlyIncludeReferencedSchemas&&this.isInAnyState(ZS.Channel,ZS.Endpoint,ZS.Webhook)}markSchemaAsReferenced(t,r){switch(t.type){case"primitive":return;case"object":this.markObjectSchemaAsReferenced(t,r);return;case"array":this.markSchemaAsReferenced(t.value,r);return;case"map":this.markSchemaAsReferenced(t.value,r);return;case"optional":this.markSchemaAsReferenced(t.value,r);return;case"reference":this.markSchemaIdAsReferenced(t.schema,r);return;case"oneOf":this.markOneofSchemaAsReferenced(t.value,r);return;case"nullable":this.markSchemaAsReferenced(t.value,r);return;case"enum":return;case"literal":return;case"unknown":return;default:Be(t)}}markObjectSchemaAsReferenced(t,r){for(let n of t.allOf)this.markSchemaIdAsReferenced(n.schema,r);for(let n of t.properties)this.markSchemaAsReferenced(n.schema,r)}markOneofSchemaAsReferenced(t,r){switch(t.type){case"discriminated":for(let n of Object.values(t.schemas))this.markSchemaAsReferenced(n,r);return;case"undiscriminated":for(let n of t.schemas)this.markSchemaAsReferenced(n,r);return;default:Be(t)}}markSchemaIdAsReferenced(t,r){if(this.referencedSchemaIds!=null&&!this.referencedSchemaIds.has(t)){this.referencedSchemaIds.add(t);let n=this.getSchema(t,r);n!=null&&this.markSchemaAsReferenced(n,r)}}isInAnyState(...t){return t.some(r=>this.isInState(r))}setSchemaFinalName(t,r){this.schemaNameMapping.set(t,r)}hasReadVariant(t){return this.schemaNameMapping.has(t)}setVariantPlan(t,r){this.variantPlan=t,this.reachability=r;let n=[this.ir.groupedSchemas.rootSchemas,...Object.values(this.ir.groupedSchemas.namespacedSchemas)];for(let i of n)for(let[o,s]of Object.entries(i))if(t.needsBothVariants.has(o)&&s.type==="object"){let a=s.nameOverride??s.generatedName;this.schemaNameMapping.set(a,`${a}Read`)}}needsBothVariants(t){return this.variantPlan?.needsBothVariants.has(t)??!1}isRequestOnlyWithReadonly(t){return this.variantPlan?.requestOnlyWithReadonly.has(t)??!1}isResponseReachable(t){return this.reachability==null?this.ir.nonRequestReferencedSchemas.has(t):this.reachability.responseReachable.has(t)}isRequestOnly(t){return this.reachability==null?!this.ir.nonRequestReferencedSchemas.has(t):this.reachability.requestReachable.has(t)&&!this.reachability.responseReachable.has(t)}getSchemaFinalName(t,r){return!this.options.respectReadonlySchemas||r==="write"?t:this.schemaNameMapping.get(t)??t}};function Tli(e){let t=new Qar(e);return SAs(t)}sA();function qAs(e){return typeof e>"u"||e===null}function Wyl(e){return typeof e=="object"&&e!==null}function $yl(e){return Array.isArray(e)?e:qAs(e)?[]:[e]}function Hyl(e,t){var r,n,i,o;if(t)for(o=Object.keys(t),r=0,n=o.length;r<n;r+=1)i=o[r],e[i]=t[i];return e}function Kyl(e,t){var r="",n;for(n=0;n<t;n+=1)r+=e;return r}function Jyl(e){return e===0&&Number.NEGATIVE_INFINITY===1/e}var Yyl=qAs,Xyl=Wyl,Zyl=$yl,ebl=Kyl,tbl=Jyl,rbl=Hyl,Kw={isNothing:Yyl,isObject:Xyl,toArray:Zyl,repeat:ebl,isNegativeZero:tbl,extend:rbl};function GAs(e,t){var r="",n=e.reason||"(unknown reason)";return e.mark?(e.mark.name&&(r+='in "'+e.mark.name+'" '),r+="("+(e.mark.line+1)+":"+(e.mark.column+1)+")",!t&&e.mark.snippet&&(r+=`
1463
+ `)),{ok:!0,value:t}):n}}function lor(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}var r6e=class e extends Error{errors;constructor(t){super(t.map(lor).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};var n6e=class e extends Error{errors;constructor(t){super(t.map(lor).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};function Hd(e){return{nullable:()=>EAl(e),optional:()=>nli(e),optionalNullable:()=>vAl(e),transform:t=>ili(e,t),parseOrThrow:(t,r)=>{let n=e.parse(t,r);if(n.ok)return n.value;throw new n6e(n.errors)},jsonOrThrow:(t,r)=>{let n=e.json(t,r);if(n.ok)return n.value;throw new r6e(n.errors)}}}function EAl(e){let t={parse:(r,n)=>r==null?{ok:!0,value:null}:e.parse(r,n),json:(r,n)=>r==null?{ok:!0,value:null}:e.json(r,n),getType:()=>Cu.NULLABLE};return{...t,...Hd(t)}}function nli(e){let t={parse:(r,n)=>r==null?{ok:!0,value:void 0}:e.parse(r,n),json:(r,n)=>n?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:e.json(r,n),getType:()=>Cu.OPTIONAL};return{...t,...Hd(t)}}function vAl(e){let t={parse:(r,n)=>r===void 0?{ok:!0,value:void 0}:r===null?{ok:!0,value:null}:e.parse(r,n),json:(r,n)=>r===void 0?{ok:!0,value:void 0}:r===null?{ok:!0,value:null}:e.json(r,n),getType:()=>Cu.OPTIONAL_NULLABLE};return{...t,...Hd(t)}}function ili(e,t){let r={parse:(n,i)=>{let o=e.parse(n,i);return o.ok?{ok:!0,value:t.transform(o.value)}:o},json:(n,i)=>{let o=t.untransform(n);return e.json(o,i)},getType:()=>e.getType()};return{...r,...Hd(r)}}function sgs(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t=="bigint"?{ok:!0,value:t}:typeof t=="number"?{ok:!0,value:BigInt(t)}:{ok:!1,errors:[{path:r,message:gd(t,"bigint | number")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="bigint"?{ok:!1,errors:[{path:r,message:gd(t,"bigint")}]}:{ok:!0,value:t},getType:()=>Cu.BIGINT};return{..._x(e),...Hd(e)}}var IAl=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function ags(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:gd(t,"string")}]}:IAl.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:gd(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:gd(t,"Date object")}]},getType:()=>Cu.DATE};return{..._x(e),...Hd(e)}}function Sx(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return{..._x(r),...Hd(r)}}}function por(e){let t=new Set(e);return Sx(Cu.ENUM,(n,{allowUnrecognizedEnumValues:i,breadcrumbsPrefix:o=[]}={})=>typeof n!="string"?{ok:!1,errors:[{path:o,message:gd(n,"string")}]}:!t.has(n)&&!i?{ok:!1,errors:[{path:o,message:gd(n,"enum")}]}:{ok:!0,value:n})()}function cgs(e){let t=oli(e);return{...t,...Hd(t)}}function oli(e){return{parse:(t,r)=>i6e(e).parse(t,r),json:(t,r)=>i6e(e).json(t,r),getType:()=>i6e(e).getType()}}function i6e(e){let t=e;return t.__zurg_memoized==null&&(t.__zurg_memoized=e()),t.__zurg_memoized}function sli(e){return Object.entries(e)}function $vt(e,t){let r=new Set(t);return Object.entries(e).reduce((n,[i,o])=>(r.has(i)&&(n[i]=o),n),{})}function Use(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===null?!0:Object.getPrototypeOf(t)===null}function Hvt(e){return Object.keys(e)}function ugs(e,t){let r=[],n=[];for(let i of e)t(i)?r.push(i):n.push(i);return[r,n]}var wAl=Object.prototype.hasOwnProperty;function sq(e){return{withParsedProperties:t=>ali(e,t)}}function ali(e,t){let r={parse:(n,i)=>{let o=e.parse(n,i);if(!o.ok)return o;let s={};for(let a in t)if(wAl.call(t,a)){let c=t[a];s[a]=typeof c=="function"?c(o.value):c}return{ok:!0,value:{...o.value,...s}}},json:(n,i)=>{if(!Use(n))return{ok:!1,errors:[{path:i?.breadcrumbsPrefix??[],message:gd(n,"object")}]};let o=new Set(Object.keys(t)),s=$vt(n,Object.keys(n).filter(a=>!o.has(a)));return e.json(s,i)},getType:()=>e.getType()};return{...r,...Hd(r),...sq(r)}}function lgs(e,t){return{rawKey:e,valueSchema:t,isProperty:!0}}function zse(e){return e.isProperty}var CAl=Object.prototype.hasOwnProperty;function dor(e){let t;function r(){if(t==null){t={};for(let[d,f]of sli(e)){let m=zse(f)?f.rawKey:d,h=zse(f)?f.valueSchema:f;t[m]={rawKey:m,parsedKey:d,valueSchema:h}}}return t}let n,i,o,s;function a(){if(n==null){n=[],i=[];for(let[d,f]of sli(e)){let m=zse(f)?f.rawKey:d,h=zse(f)?f.valueSchema:f;xAl(h)&&(n.push(m),i.push(d))}o=new Set(n),s=new Set(i)}return n}function c(){return i==null&&a(),i}function u(){return o==null&&a(),o}function l(){return s==null&&a(),s}let p={_getRawProperties:()=>Object.entries(e).map(([d,f])=>zse(f)?f.rawKey:d),_getParsedProperties:()=>Hvt(e),parse:(d,f)=>{let m=f?.breadcrumbsPrefix??[];return pgs({value:d,requiredKeys:a(),requiredKeysSet:u(),getProperty:h=>{let g=r()[h];if(g!=null)return{transformedKey:g.parsedKey,transform:A=>{let b=[...m,h];return g.valueSchema.parse(A,{...f,breadcrumbsPrefix:b})}}},unrecognizedObjectKeys:f?.unrecognizedObjectKeys,skipValidation:f?.skipValidation,breadcrumbsPrefix:m,omitUndefined:f?.omitUndefined})},json:(d,f)=>{let m=f?.breadcrumbsPrefix??[];return pgs({value:d,requiredKeys:c(),requiredKeysSet:l(),getProperty:h=>{let g=e[h];if(g!=null)return zse(g)?{transformedKey:g.rawKey,transform:A=>{let b=[...m,h];return g.valueSchema.json(A,{...f,breadcrumbsPrefix:b})}}:{transformedKey:h,transform:A=>{let b=[...m,h];return g.json(A,{...f,breadcrumbsPrefix:b})}}},unrecognizedObjectKeys:f?.unrecognizedObjectKeys,skipValidation:f?.skipValidation,breadcrumbsPrefix:m,omitUndefined:f?.omitUndefined})},getType:()=>Cu.OBJECT};return{..._x(p),...Hd(p),...sq(p),...ROe(p)}}function pgs({value:e,requiredKeys:t,requiredKeysSet:r,getProperty:n,unrecognizedObjectKeys:i="fail",skipValidation:o=!1,breadcrumbsPrefix:s=[]}){if(!Use(e))return{ok:!1,errors:[{path:s,message:gd(e,"object")}]};let a=t.length,c=[],u={};for(let l in e){if(!CAl.call(e,l))continue;let p=e[l],d=n(l);if(d!=null){a>0&&r.has(l)&&a--;let f=d.transform(p);f.ok?u[d.transformedKey]=f.value:(u[l]=p,c.push(...f.errors))}else switch(i){case"fail":c.push({path:[...s,l],message:`Unexpected key "${l}"`});break;case"strip":break;case"passthrough":u[l]=p;break}}if(a>0)for(let l of t)l in e||c.push({path:s,message:`Missing required key "${l}"`});return c.length===0||o?{ok:!0,value:u}:{ok:!1,errors:c}}function ROe(e){return{extend:t=>{let r={_getParsedProperties:()=>[...e._getParsedProperties(),...t._getParsedProperties()],_getRawProperties:()=>[...e._getRawProperties(),...t._getRawProperties()],parse:(n,i)=>fgs({extensionKeys:t._getRawProperties(),value:n,transformBase:o=>e.parse(o,i),transformExtension:o=>t.parse(o,i),breadcrumbsPrefix:i?.breadcrumbsPrefix}),json:(n,i)=>fgs({extensionKeys:t._getParsedProperties(),value:n,transformBase:o=>e.json(o,i),transformExtension:o=>t.json(o,i),breadcrumbsPrefix:i?.breadcrumbsPrefix}),getType:()=>Cu.OBJECT};return{...r,...Hd(r),...sq(r),...ROe(r)}},passthrough:()=>{let t=new Set(e._getRawProperties()),r=new Set(e._getParsedProperties()),n={_getParsedProperties:()=>e._getParsedProperties(),_getRawProperties:()=>e._getRawProperties(),parse:(i,o)=>{let s=e.parse(i,{...o,unrecognizedObjectKeys:"passthrough"});if(!s.ok)return s;let a={};if(typeof i=="object"&&i!=null)for(let[c,u]of Object.entries(i))t.has(c)||(a[c]=u);return{ok:!0,value:{...a,...s.value}}},json:(i,o)=>{let s=e.json(i,{...o,unrecognizedObjectKeys:"passthrough"});if(!s.ok)return s;let a={};if(typeof i=="object"&&i!=null)for(let[c,u]of Object.entries(i))r.has(c)||(a[c]=u);return{ok:!0,value:{...a,...s.value}}},getType:()=>Cu.OBJECT};return{...n,...Hd(n),...sq(n),...ROe(n)}}}}function fgs({extensionKeys:e,value:t,transformBase:r,transformExtension:n,breadcrumbsPrefix:i=[]}){if(!Use(t))return{ok:!1,errors:[{path:i,message:gd(t,"object")}]};let o=new Set(e),[s,a]=ugs(Hvt(t),l=>o.has(l)),c=r($vt(t,a)),u=n($vt(t,s));return c.ok&&u.ok?{ok:!0,value:{...c.value,...u.value}}:{ok:!1,errors:[...c.ok?[]:c.errors,...u.ok?[]:u.errors]}}function xAl(e){return!_Al(e)}function _Al(e){switch(e.getType()){case Cu.ANY:case Cu.UNKNOWN:case Cu.OPTIONAL:case Cu.OPTIONAL_NULLABLE:return!0;default:return!1}}function dgs(e){return dor(e)}function mgs(e){let t={...oli(e),_getRawProperties:()=>i6e(e)._getRawProperties(),_getParsedProperties:()=>i6e(e)._getParsedProperties()};return{...t,...Hd(t),...sq(t),...ROe(t)}}function mor(e){let t={parse:(r,n)=>hgs(r,(i,o)=>e.parse(i,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`[${o}]`]})),json:(r,n)=>hgs(r,(i,o)=>e.json(i,{...n,breadcrumbsPrefix:[...n?.breadcrumbsPrefix??[],`[${o}]`]})),getType:()=>Cu.LIST};return{..._x(t),...Hd(t)}}function hgs(e,t){if(!Array.isArray(e))return{ok:!1,errors:[{message:gd(e,"list"),path:[]}]};let r=[],n=[];for(let i=0;i<e.length;i++){let o=t(e[i],i);o.ok?r.push(o.value):n.push(...o.errors)}return n.length===0?{ok:!0,value:r}:{ok:!1,errors:n}}function ggs(e){return Sx(Cu.BOOLEAN_LITERAL,(r,{breadcrumbsPrefix:n=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:n,message:gd(r,`${e.toString()}`)}]})()}function Ags(e){return Sx(Cu.STRING_LITERAL,(r,{breadcrumbsPrefix:n=[]}={})=>r===e?{ok:!0,value:e}:{ok:!1,errors:[{path:n,message:gd(r,`"${e}"`)}]})()}var ygs=Sx(Cu.ANY,e=>({ok:!0,value:e}));var bgs=Sx(Cu.BOOLEAN,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="boolean"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:gd(e,"boolean")}]});var Egs=Sx(Cu.NEVER,(e,{breadcrumbsPrefix:t=[]}={})=>({ok:!1,errors:[{path:t,message:"Expected never"}]}));var vgs=Sx(Cu.NUMBER,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="number"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:gd(e,"number")}]});var Igs=Sx(Cu.STRING,(e,{breadcrumbsPrefix:t=[]}={})=>typeof e=="string"?{ok:!0,value:e}:{ok:!1,errors:[{path:t,message:gd(e,"string")}]});var wgs=Sx(Cu.UNKNOWN,e=>({ok:!0,value:e}));var SAl=Object.prototype.hasOwnProperty;function xgs(e,t){let r={parse:(n,i)=>Cgs({value:n,isKeyNumeric:e.getType()===Cu.NUMBER,transformKey:o=>e.parse(o,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${o} (key)`]}),transformValue:(o,s)=>t.parse(o,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${s}`]}),breadcrumbsPrefix:i?.breadcrumbsPrefix}),json:(n,i)=>Cgs({value:n,isKeyNumeric:e.getType()===Cu.NUMBER,transformKey:o=>e.json(o,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${o} (key)`]}),transformValue:(o,s)=>t.json(o,{...i,breadcrumbsPrefix:[...i?.breadcrumbsPrefix??[],`${s}`]}),breadcrumbsPrefix:i?.breadcrumbsPrefix}),getType:()=>Cu.RECORD};return{..._x(r),...Hd(r)}}function Cgs({value:e,isKeyNumeric:t,transformKey:r,transformValue:n,breadcrumbsPrefix:i=[]}){if(!Use(e))return{ok:!1,errors:[{path:i,message:gd(e,"object")}]};let o={},s=[];for(let a in e){if(!SAl.call(e,a))continue;let c=e[a];if(c===void 0)continue;let u=a;if(t){let d=a.length>0?Number(a):NaN;Number.isNaN(d)||(u=d)}let l=r(u),p=n(c,u);l.ok&&p.ok?o[l.value]=p.value:(l.ok||s.push(...l.errors),p.ok||s.push(...p.errors))}return s.length===0?{ok:!0,value:o}:{ok:!1,errors:s}}function _gs(e){let t=mor(e),r={parse:(n,i)=>{let o=t.parse(n,i);return o.ok?{ok:!0,value:new Set(o.value)}:o},json:(n,i)=>n instanceof Set?t.json([...n],i):{ok:!1,errors:[{path:i?.breadcrumbsPrefix??[],message:gd(n,"Set")}]},getType:()=>Cu.SET};return{..._x(r),...Hd(r)}}function Bgs(e){let t={parse:(r,n)=>Sgs((i,o)=>i.parse(r,o),e,n),json:(r,n)=>Sgs((i,o)=>i.json(r,o),e,n),getType:()=>Cu.UNDISCRIMINATED_UNION};return{..._x(t),...Hd(t)}}function Sgs(e,t,r){let n=[];for(let[i,o]of t.entries()){let s=e(o,{...r,skipValidation:!1});if(s.ok)return s;for(let a of s.errors)n.push({path:a.path,message:`[Variant ${i}] ${a.message}`})}return{ok:!1,errors:n}}function Tgs(e,t){return{parsedDiscriminant:e,rawDiscriminant:t}}var BAl=Object.prototype.hasOwnProperty;function Pgs(e,t){let r=typeof e=="string"?e:e.rawDiscriminant,n=typeof e=="string"?e:e.parsedDiscriminant,i=por(Hvt(t)),o={parse:(s,a)=>Ogs({value:s,discriminant:r,transformedDiscriminant:n,transformDiscriminantValue:c=>i.parse(c,{allowUnrecognizedEnumValues:a?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...a?.breadcrumbsPrefix??[],r]}),getAdditionalPropertiesSchema:c=>t[c],allowUnrecognizedUnionMembers:a?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(c,u)=>u.parse(c,a),breadcrumbsPrefix:a?.breadcrumbsPrefix}),json:(s,a)=>Ogs({value:s,discriminant:n,transformedDiscriminant:r,transformDiscriminantValue:c=>i.json(c,{allowUnrecognizedEnumValues:a?.allowUnrecognizedUnionMembers,breadcrumbsPrefix:[...a?.breadcrumbsPrefix??[],n]}),getAdditionalPropertiesSchema:c=>t[c],allowUnrecognizedUnionMembers:a?.allowUnrecognizedUnionMembers,transformAdditionalProperties:(c,u)=>u.json(c,a),breadcrumbsPrefix:a?.breadcrumbsPrefix}),getType:()=>Cu.UNION};return{..._x(o),...Hd(o),...sq(o)}}function Ogs({value:e,discriminant:t,transformedDiscriminant:r,transformDiscriminantValue:n,getAdditionalPropertiesSchema:i,allowUnrecognizedUnionMembers:o=!1,transformAdditionalProperties:s,breadcrumbsPrefix:a=[]}){if(!Use(e))return{ok:!1,errors:[{path:a,message:gd(e,"object")}]};let c=e[t],u={};for(let f in e)BAl.call(e,f)&&f!==t&&(u[f]=e[f]);if(c==null)return{ok:!1,errors:[{path:a,message:`Missing discriminant ("${t}")`}]};let l=n(c);if(!l.ok)return{ok:!1,errors:l.errors};let p=i(l.value);if(p==null)return o?{ok:!0,value:{[r]:l.value,...u}}:{ok:!1,errors:[{path:[...a,t],message:"Unexpected discriminant value"}]};let d=s(u,p);return d.ok?{ok:!0,value:{[r]:c,...d.value}}:d}var hor=J.objectWithoutOptionalProperties({usernameVariableName:J.string().optional(),usernameEnvVar:J.string().optional(),passwordVariableName:J.string().optional(),passwordEnvVar:J.string().optional()});var gor=J.objectWithoutOptionalProperties({tokenVariableName:J.string().optional(),tokenEnvVar:J.string().optional()});var Aor=J.objectWithoutOptionalProperties({typeName:J.string()});var yor=J.union("type",{protobuf:Aor}).transform({transform:e=>e.type==="protobuf"?t6e.protobuf(e):e,untransform:({_visit:e,...t})=>t});var bor=J.objectWithoutOptionalProperties({headerName:J.string(),prefix:J.string().optional(),headerVariableName:J.string().optional(),headerEnvVar:J.string().optional()});var Eor=J.objectWithoutOptionalProperties({type:J.stringLiteral("namespace"),name:J.string()});var vor=J.string();var Ior=J.enum_(["GenerallyAvailable","Beta","Deprecated"]);var us=J.objectWithoutOptionalProperties({availability:Ior.optional()});var mn=J.objectWithoutOptionalProperties({description:J.string().optional()});var Uf=J.objectWithoutOptionalProperties({inline:J.boolean().optional()});var Nc=J.objectWithoutOptionalProperties({nameOverride:J.string().optional(),generatedName:J.string()});var oc=J.objectWithoutOptionalProperties({namespace:J.string().optional()});var wor=J.undiscriminatedUnion([J.string(),Eor]);var _he=J.list(wor);var xu=J.objectWithoutOptionalProperties({groupName:_he.optional()});var Cor=J.objectWithoutOptionalProperties({file:J.string()});var xor=J.objectWithoutOptionalProperties({file:J.string()});var _or=J.union("type",{openapi:Cor,protobuf:xor}).transform({transform:e=>{switch(e.type){case"openapi":return lT.openapi(e);case"protobuf":return lT.protobuf(e);default:return e}},untransform:({_visit:e,...t})=>t});var $o=J.objectWithoutOptionalProperties({source:_or.optional()});var _u=J.objectWithoutOptionalProperties({title:J.string().optional()});var Sor=J.objectWithoutOptionalProperties({snake:J.string().optional(),camel:J.string().optional(),screamingSnake:J.string().optional(),pascal:J.string().optional()});var She=J.objectWithoutOptionalProperties({nameOverride:J.string().optional(),generatedName:J.string(),value:J.string(),casing:Sor.optional()}).extend(mn).extend(us);var o6e=J.objectWithoutOptionalProperties({default:She.optional(),values:J.list(She)}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend($o).extend(_u).extend(Uf);var Bor=J.objectWithoutOptionalProperties({scopesEnum:o6e.optional()});var Tor=J.objectWithoutOptionalProperties({queryParameterName:J.string()});var KP=J.string();var Oor=J.union("type",{basic:hor,bearer:gor,header:bor,query:Tor,oauth:Bor}).transform({transform:e=>{switch(e.type){case"basic":return Ix.basic(e);case"bearer":return Ix.bearer(e);case"header":return Ix.header(e);case"query":return Ix.query(e);case"oauth":return Ix.oauth(e);default:return e}},untransform:({_visit:e,...t})=>t});var Bhe=J.string();var Por=J.objectWithoutOptionalProperties({id:J.string(),default:J.string().optional(),values:J.list(J.string()).optional()});var Kvt=J.objectWithoutOptionalProperties({name:J.string().optional(),url:J.string(),audiences:J.list(J.string()).optional(),defaultUrl:J.string().optional(),urlTemplate:J.string().optional(),variables:J.list(Por).optional()}).extend(mn);var w$=J.number();var JP=J.string();var Dor=J.objectWithoutOptionalProperties({id:JP}).extend(mn);var Bx=J.objectWithoutOptionalProperties({encoding:yor.optional()});var C$=J.objectWithoutOptionalProperties({sdkMethodName:J.string().optional()});var YU=J.objectWithoutOptionalProperties({statusCode:w$.optional()});var uli={};te(uli,{FullExample:()=>qm,FullObjectExample:()=>kor,FullOneOfExample:()=>Nor,KeyValuePair:()=>Qor,LiteralExample:()=>Ror,NullExample:()=>For,PrimitiveExample:()=>s6e,PropertyKey:()=>a6e});var Ror=J.union("type",{boolean:J.object({value:J.boolean()}),string:J.object({value:J.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return Che.boolean(e.value);case"string":return Che.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var For=J.objectWithoutOptionalProperties({});var s6e=J.union("type",{int:J.object({value:J.number()}),int64:J.object({value:J.number()}),uint:J.object({value:J.number()}),uint64:J.object({value:J.number()}),float:J.object({value:J.number()}),double:J.object({value:J.number()}),string:J.object({value:J.string()}),datetime:J.object({value:J.string()}),datetimeRfc2822:J.object({value:J.string()}),date:J.object({value:J.string()}),base64:J.object({value:J.string()}),boolean:J.object({value:J.boolean()})}).transform({transform:e=>{switch(e.type){case"int":return hs.int(e.value);case"int64":return hs.int64(e.value);case"uint":return hs.uint(e.value);case"uint64":return hs.uint64(e.value);case"float":return hs.float(e.value);case"double":return hs.double(e.value);case"string":return hs.string(e.value);case"datetime":return hs.datetime(e.value);case"datetimeRfc2822":return hs.datetimeRfc2822(e.value);case"date":return hs.date(e.value);case"base64":return hs.base64(e.value);case"boolean":return hs.boolean(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var qm=J.union("type",{primitive:J.object({value:s6e}),object:J.lazyObject(()=>kor),array:J.object({value:J.list(J.lazy(()=>qm))}),map:J.object({value:J.list(J.lazyObject(()=>Qor))}),enum:J.object({value:J.string()}),literal:J.object({value:Ror}),oneOf:J.object({value:J.lazy(()=>Nor)}),null:For,unknown:J.object({value:J.lazy(()=>qm)})}).transform({transform:e=>{switch(e.type){case"primitive":return lc.primitive(e.value);case"object":return lc.object(e);case"array":return lc.array(e.value);case"map":return lc.map(e.value);case"enum":return lc.enum(e.value);case"literal":return lc.literal(e.value);case"oneOf":return lc.oneOf(e.value);case"null":return lc.null(e);case"unknown":return lc.unknown(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var a6e=J.string();var kor=J.objectWithoutOptionalProperties({properties:J.record(a6e,J.lazy(()=>qm))});var Nor=J.union("type",{discriminated:J.object({value:J.record(a6e,J.lazy(()=>qm))}),undiscriminated:J.object({value:J.lazy(()=>qm)})}).transform({transform:e=>{switch(e.type){case"discriminated":return whe.discriminated(e.value);case"undiscriminated":return whe.undiscriminated(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Qor=J.objectWithoutOptionalProperties({key:s6e,value:J.lazy(()=>qm)});var lli={};te(lli,{AllOfPropertyConflict:()=>c6e,ArraySchema:()=>jor,AsymmetricAlgorithm:()=>Mor,AsymmetricWebhookSignatureVerification:()=>Uor,Availability:()=>Ior,BooleanSchema:()=>zor,BytesResponse:()=>p6e,CasingOverrides:()=>Sor,CommonProperty:()=>Vor,CursorPagination:()=>qor,CustomCodeSample:()=>Hor,CustomCodeSampleLanguage:()=>Gor,CustomCodeSampleSdk:()=>$or,CustomPagination:()=>Kor,DiscriminatedOneOfSchema:()=>Jor,DiscriminatorContext:()=>f6e,DoubleSchema:()=>Yor,Endpoint:()=>msr,EndpointExample:()=>h6e,EndpointResponseExample:()=>esr,EndpointSdkName:()=>x$,EndpointSecurity:()=>g6e,EnumSchema:()=>o6e,EnumValue:()=>She,ErrorExample:()=>nsr,FernExample:()=>Xor,FileResponse:()=>C6e,FileSchema:()=>psr,FormUrlEncodedRequest:()=>csr,FullEndpointExample:()=>rsr,GlobalHeader:()=>hsr,GlobalSecurity:()=>gsr,Header:()=>The,HeaderExample:()=>d6e,HmacWebhookSignatureVerification:()=>Esr,HttpEndpointServer:()=>A6e,HttpError:()=>isr,HttpMethod:()=>y6e,IdempotencyHeader:()=>vsr,IntSchema:()=>Isr,JsonRequest:()=>usr,JsonResponse:()=>x6e,LiteralSchema:()=>B6e,LiteralSchemaValue:()=>wsr,LongSchema:()=>Csr,MapSchema:()=>Ssr,MultipartFormDataWebhookPayload:()=>Bsr,MultipartRequest:()=>I6e,MultipartRequestProperty:()=>Ohe,MultipartRequestPropertyEncoding:()=>lsr,MultipartSchema:()=>fsr,NullableSchema:()=>Tsr,ObjectProperty:()=>Osr,ObjectPropertyConflictInfo:()=>T6e,ObjectSchema:()=>Psr,OctetStreamRequest:()=>w6e,OffsetPagination:()=>osr,OneOfSchema:()=>Dsr,OpenApiIntermediateRepresentation:()=>Dgs,OptionalSchema:()=>Gsr,Pagination:()=>b6e,PathPagination:()=>ssr,PathParameter:()=>E6e,PathParameterExample:()=>tsr,PrimitiveSchema:()=>Dhe,PrimitiveSchemaValue:()=>_sr,QueryParameter:()=>v6e,QueryParameterExample:()=>m6e,ReferencedSchema:()=>_$,Request:()=>dsr,Response:()=>_6e,RetriesConfiguration:()=>S6e,Schema:()=>$u,Schemas:()=>Fsr,SdkGroupInfo:()=>ksr,StreamingResponseExample:()=>Zor,StringSchema:()=>xsr,SupportedSdkLanguage:()=>Wor,Tags:()=>Nsr,TextResponse:()=>Phe,UnDiscriminatedOneOfSchema:()=>Rsr,UnknownSchema:()=>Wsr,UriPagination:()=>asr,Webhook:()=>Qsr,WebhookExampleCall:()=>O6e,WebhookHttpMethod:()=>P6e,WebhookPayloadComponent:()=>Asr,WebhookPayloadFormat:()=>ysr,WebhookSignatureAlgorithm:()=>bsr,WebhookSignatureEncoding:()=>u6e,WebhookSignatureVerification:()=>D6e,WebhookTimestamp:()=>l6e,WebhookTimestampFormat:()=>Lor,WebsocketChannel:()=>qsr,WebsocketHandshake:()=>jsr,WebsocketMessageExample:()=>zsr,WebsocketMessageOrigin:()=>Msr,WebsocketMessageSchema:()=>Lsr,WebsocketServer:()=>Usr,WebsocketSessionExample:()=>Vsr});var c6e=J.objectWithoutOptionalProperties({propertyKey:J.string(),allOfSchemaIds:J.list(KP),conflictingTypeSignatures:J.boolean()});var jor=J.objectWithoutOptionalProperties({value:J.lazy(()=>$u),minItems:J.number().optional(),maxItems:J.number().optional()}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(_u).extend(Uf);var Mor=J.enum_(["rsa-sha256","rsa-sha384","rsa-sha512","ecdsa-sha256","ecdsa-sha384","ecdsa-sha512","ed25519"]);var u6e=J.enum_(["base64","hex"]);var Lor=J.enum_(["unix-seconds","unix-millis","iso8601"]);var l6e=J.objectWithoutOptionalProperties({header:J.string(),format:Lor.optional(),tolerance:J.number().optional()});var Uor=J.objectWithoutOptionalProperties({header:J.string(),asymmetricAlgorithm:Mor,encoding:u6e.optional(),signaturePrefix:J.string().optional(),jwksUrl:J.string().optional(),keyIdHeader:J.string().optional(),timestamp:l6e.optional()});var zor=J.objectWithoutOptionalProperties({default:J.boolean().optional()});var p6e=J.objectWithoutOptionalProperties({}).extend(mn).extend($o).extend(YU);var Vor=J.objectWithoutOptionalProperties({key:J.string(),schema:J.lazy(()=>$u)});var qor=J.objectWithoutOptionalProperties({cursor:J.string(),nextCursor:J.property("next_cursor",J.string()),results:J.string()});var Gor=J.objectWithoutOptionalProperties({name:J.string().optional(),language:J.string(),code:J.string(),install:J.string().optional()}).extend(mn);var Wor=J.enum_(["curl","python","javascript","typescript","go","ruby","csharp","java","js","node","ts","nodets","golang","dotnet","jvm"]);var $or=J.objectWithoutOptionalProperties({name:J.string().optional(),sdk:Wor,code:J.string()}).extend(mn);var Hor=J.union("type",{language:Gor,sdk:$or}).transform({transform:e=>{switch(e.type){case"language":return E$.language(e);case"sdk":return E$.sdk(e);default:return e}},untransform:({_visit:e,...t})=>t});var Kor=J.objectWithoutOptionalProperties({results:J.string()});var f6e=J.enum_(["data","protocol"]);var Jor=J.objectWithoutOptionalProperties({discriminantProperty:J.string(),discriminantPropertyNameOverride:J.string().optional(),discriminatorContext:f6e.optional(),commonProperties:J.list(J.lazyObject(()=>Vor)),schemas:J.record(J.string(),J.lazy(()=>$u))}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(Bx).extend($o).extend(_u).extend(Uf);var Yor=J.objectWithoutOptionalProperties({default:J.number().optional(),minimum:J.number().optional(),maximum:J.number().optional(),exclusiveMinimum:J.boolean().optional(),exclusiveMaximum:J.boolean().optional(),multipleOf:J.number().optional()});var Xor=J.unknown();var Zor=J.objectWithoutOptionalProperties({sse:J.boolean(),events:J.list(J.lazy(()=>qm))});var esr=J.union("type",{withStreaming:Zor,withoutStreaming:J.object({value:J.lazy(()=>qm)})}).transform({transform:e=>{switch(e.type){case"withStreaming":return JU.withStreaming(e);case"withoutStreaming":return JU.withoutStreaming(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var d6e=J.objectWithoutOptionalProperties({name:J.string(),value:J.lazy(()=>qm)});var tsr=J.objectWithoutOptionalProperties({name:J.string(),parameterNameOverride:J.string().optional(),value:J.lazy(()=>qm)});var m6e=J.objectWithoutOptionalProperties({name:J.string(),value:J.lazy(()=>qm)});var rsr=J.objectWithoutOptionalProperties({name:J.string().optional(),pathParameters:J.list(tsr).optional(),queryParameters:J.list(m6e).optional(),headers:J.list(d6e).optional(),request:J.lazy(()=>qm).optional(),response:esr.optional(),codeSamples:J.list(Hor)}).extend(mn);var h6e=J.union("type",{unknown:J.object({value:Xor}),full:rsr}).transform({transform:e=>{switch(e.type){case"unknown":return KU.unknown(e.value);case"full":return KU.full(e);default:return e}},untransform:({_visit:e,...t})=>t});var x$=J.objectWithoutOptionalProperties({groupName:_he,methodName:J.string()});var g6e=J.list(J.record(Bhe,J.list(J.string())));var The=J.objectWithoutOptionalProperties({name:J.string(),schema:J.lazy(()=>$u),env:J.string().optional(),parameterNameOverride:J.string().optional()}).extend(mn).extend(us).extend($o);var A6e=J.objectWithoutOptionalProperties({name:J.string().optional(),url:J.string().optional(),audiences:J.list(J.string()).optional()});var nsr=J.objectWithoutOptionalProperties({name:J.string().optional(),description:J.string().optional(),example:J.lazy(()=>qm)});var isr=J.objectWithoutOptionalProperties({schema:J.lazy(()=>$u).optional(),examples:J.list(nsr).optional()}).extend(mn).extend(Nc).extend($o);var y6e=J.enum_(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS","TRACE"]);var osr=J.objectWithoutOptionalProperties({offset:J.string(),results:J.string(),step:J.string().optional(),hasNextPage:J.string().optional()});var ssr=J.objectWithoutOptionalProperties({nextPath:J.string(),results:J.string()});var asr=J.objectWithoutOptionalProperties({nextUri:J.string(),results:J.string()});var b6e=J.union("type",{cursor:qor,offset:osr,custom:Kor,uri:asr,path:ssr}).transform({transform:e=>{switch(e.type){case"cursor":return Hw.cursor(e);case"offset":return Hw.offset(e);case"custom":return Hw.custom(e);case"uri":return Hw.uri(e);case"path":return Hw.path(e);default:return e}},untransform:({_visit:e,...t})=>t});var E6e=J.objectWithoutOptionalProperties({name:J.string(),schema:J.lazy(()=>$u),variableReference:J.string().optional(),parameterNameOverride:J.string().optional()}).extend(mn).extend(us).extend($o);var v6e=J.objectWithoutOptionalProperties({name:J.string(),schema:J.lazy(()=>$u),parameterNameOverride:J.string().optional(),explode:J.boolean().optional()}).extend(mn).extend(us).extend($o);var csr=J.objectWithoutOptionalProperties({schema:J.lazy(()=>$u),contentType:J.string().optional(),additionalProperties:J.boolean()}).extend(mn).extend($o);var usr=J.objectWithoutOptionalProperties({schema:J.lazy(()=>$u),contentType:J.string().optional(),additionalProperties:J.boolean()}).extend(mn).extend($o);var lsr=J.enum_(["json","form"]);var psr=J.objectWithoutOptionalProperties({isOptional:J.boolean(),isArray:J.boolean()}).extend(mn);var fsr=J.union("type",{file:psr,json:J.object({value:J.lazy(()=>$u)})}).transform({transform:e=>{switch(e.type){case"file":return v$.file(e);case"json":return v$.json(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var Ohe=J.objectWithoutOptionalProperties({key:J.string(),schema:fsr,contentType:J.string().optional(),exploded:J.boolean().optional(),encoding:lsr.optional()}).extend(mn);var I6e=J.objectWithoutOptionalProperties({name:J.string().optional(),properties:J.list(Ohe)}).extend(mn).extend($o);var w6e=J.objectWithoutOptionalProperties({contentType:J.string().optional()}).extend(mn).extend($o);var dsr=J.union("type",{octetStream:w6e,multipart:I6e,json:usr,formUrlEncoded:csr}).transform({transform:e=>{switch(e.type){case"octetStream":return oq.octetStream(e);case"multipart":return oq.multipart(e);case"json":return oq.json(e);case"formUrlEncoded":return oq.formUrlEncoded(e);default:return e}},untransform:({_visit:e,...t})=>t});var C6e=J.objectWithoutOptionalProperties({}).extend(mn).extend($o).extend(YU);var x6e=J.objectWithoutOptionalProperties({schema:J.lazy(()=>$u),responseProperty:J.string().optional(),terminator:J.string().optional()}).extend(mn).extend($o).extend(YU);var Phe=J.objectWithoutOptionalProperties({}).extend(mn).extend($o).extend(YU);var _6e=J.union("type",{file:C6e,json:x6e,text:Phe,bytes:p6e,streamingSse:x6e,streamingText:Phe,streamingJson:x6e}).transform({transform:e=>{switch(e.type){case"file":return XS.file(e);case"json":return XS.json(e);case"text":return XS.text(e);case"bytes":return XS.bytes(e);case"streamingSse":return XS.streamingSse(e);case"streamingText":return XS.streamingText(e);case"streamingJson":return XS.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var S6e=J.union("type",{disabled:J.object({value:J.boolean().optional()})}).transform({transform:e=>e.type==="disabled"?qvt.disabled(e.value):e,untransform:({_visit:e,...t})=>t});var msr=J.objectWithoutOptionalProperties({authed:J.boolean(),security:g6e.optional(),internal:J.boolean().optional(),idempotent:J.boolean().optional(),method:y6e,audiences:J.list(J.string()),path:J.string(),summary:J.string().optional(),operationId:J.string().optional(),tags:J.list(JP),pathParameters:J.list(E6e),queryParameters:J.list(v6e),headers:J.list(The),sdkName:x$.optional(),generatedRequestName:J.string(),requestNameOverride:J.string().optional(),request:dsr.optional(),response:_6e.optional(),errors:J.record(w$,isr),servers:J.list(A6e),examples:J.list(h6e),pagination:b6e.optional(),retries:S6e.optional()}).extend(mn).extend(us).extend($o).extend(oc);var hsr=J.objectWithoutOptionalProperties({header:J.string(),name:J.string().optional(),optional:J.boolean().optional(),env:J.string().optional(),schema:J.lazy(()=>$u).optional()});var gsr=J.list(J.record(Bhe,J.list(J.string())));var Asr=J.enum_(["body","timestamp","notification-url","message-id"]);var ysr=J.objectWithoutOptionalProperties({components:J.list(Asr),delimiter:J.string().optional()});var bsr=J.enum_(["sha256","sha1","sha384","sha512"]);var Esr=J.objectWithoutOptionalProperties({header:J.string(),algorithm:bsr.optional(),encoding:u6e.optional(),signaturePrefix:J.string().optional(),payloadFormat:ysr.optional(),timestamp:l6e.optional()});var vsr=J.objectWithoutOptionalProperties({header:J.string(),name:J.string().optional(),env:J.string().optional(),schema:J.lazy(()=>$u).optional()});var Isr=J.objectWithoutOptionalProperties({default:J.number().optional(),minimum:J.number().optional(),maximum:J.number().optional(),exclusiveMinimum:J.boolean().optional(),exclusiveMaximum:J.boolean().optional(),multipleOf:J.number().optional()});var wsr=J.union("type",{boolean:J.object({value:J.boolean()}),string:J.object({value:J.string()})}).transform({transform:e=>{switch(e.type){case"boolean":return fA.boolean(e.value);case"string":return fA.string(e.value);default:return e}},untransform:({_visit:e,...t})=>t});var B6e=J.objectWithoutOptionalProperties({value:wsr}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(_u);var Csr=J.objectWithoutOptionalProperties({default:J.number().optional()});var xsr=J.objectWithoutOptionalProperties({default:J.string().optional(),pattern:J.string().optional(),format:J.string().optional(),minLength:J.number().optional(),maxLength:J.number().optional()});var _sr=J.union("type",{int:Isr,int64:Csr,uint:J.object({}),uint64:J.object({}),float:J.object({}),double:Yor,string:xsr,datetime:J.object({}),datetimeRfc2822:J.object({}),date:J.object({}),base64:J.object({}),boolean:zor}).transform({transform:e=>{switch(e.type){case"int":return ol.int(e);case"int64":return ol.int64(e);case"uint":return ol.uint();case"uint64":return ol.uint64();case"float":return ol.float();case"double":return ol.double(e);case"string":return ol.string(e);case"datetime":return ol.datetime();case"datetimeRfc2822":return ol.datetimeRfc2822();case"date":return ol.date();case"base64":return ol.base64();case"boolean":return ol.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var Dhe=J.objectWithoutOptionalProperties({schema:_sr}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(_u);var Ssr=J.objectWithoutOptionalProperties({key:Dhe,value:J.lazy(()=>$u),minProperties:J.number().optional(),maxProperties:J.number().optional()}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(Bx).extend(_u).extend(Uf);var Bsr=J.objectWithoutOptionalProperties({name:J.string().optional(),properties:J.list(Ohe)}).extend(mn).extend($o);var Tsr=J.objectWithoutOptionalProperties({value:J.lazy(()=>$u)}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(_u).extend(Uf);var T6e=J.objectWithoutOptionalProperties({differentSchema:J.boolean()});var Osr=J.objectWithoutOptionalProperties({key:J.string(),schema:J.lazy(()=>$u),readonly:J.boolean().optional(),writeonly:J.boolean().optional(),conflict:J.record(KP,T6e),generatedName:J.string(),nameOverride:J.string().optional(),audiences:J.list(J.string())}).extend(us);var _$=J.objectWithoutOptionalProperties({schema:KP}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend($o).extend(_u);var Psr=J.objectWithoutOptionalProperties({allOf:J.list(_$),properties:J.list(J.lazyObject(()=>Osr)),allOfPropertyConflicts:J.list(c6e),additionalProperties:J.boolean(),minProperties:J.number().optional(),maxProperties:J.number().optional()}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(Bx).extend($o).extend(_u).extend(Uf);var Dsr=J.union("type",{discriminated:J.lazyObject(()=>Jor),undiscriminated:J.lazyObject(()=>Rsr)}).transform({transform:e=>{switch(e.type){case"discriminated":return I$.discriminated(e);case"undiscriminated":return I$.undiscriminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var Fsr=J.objectWithoutOptionalProperties({rootSchemas:J.record(KP,J.lazy(()=>$u)),namespacedSchemas:J.record(vor,J.record(KP,J.lazy(()=>$u)))});var ksr=J.objectWithoutOptionalProperties({summary:J.string().optional(),description:J.string().optional()});var Nsr=J.objectWithoutOptionalProperties({tagsById:J.record(JP,Dor),orderedTagIds:J.list(JP).optional()});var O6e=J.objectWithoutOptionalProperties({name:J.string().optional(),payload:J.lazy(()=>qm)}).extend(mn);var P6e=J.enum_(["GET","POST"]);var D6e=J.union("type",{hmac:Esr,asymmetric:Uor}).transform({transform:e=>{switch(e.type){case"hmac":return DOe.hmac(e);case"asymmetric":return DOe.asymmetric(e);default:return e}},untransform:({_visit:e,...t})=>t});var Qsr=J.objectWithoutOptionalProperties({audiences:J.list(J.string()),sdkName:x$.optional(),method:P6e,summary:J.string().optional(),operationId:J.string(),tags:J.list(JP),headers:J.list(The),generatedPayloadName:J.string(),payload:J.lazy(()=>$u),multipartFormData:Bsr.optional(),response:_6e.optional(),signatureVerification:D6e.optional(),examples:J.list(O6e)}).extend(mn).extend($o).extend(oc);var jsr=J.objectWithoutOptionalProperties({queryParameters:J.list(v6e),headers:J.list(The),pathParameters:J.list(E6e)});var Msr=J.enum_(["client","server"]);var Lsr=J.objectWithoutOptionalProperties({name:J.string(),origin:Msr,body:J.lazy(()=>$u),methodName:J.string().optional()});var Usr=J.objectWithoutOptionalProperties({name:J.string(),url:J.string()});var zsr=J.objectWithoutOptionalProperties({messageType:J.string(),payload:J.lazy(()=>qm)}).extend(mn);var Vsr=J.objectWithoutOptionalProperties({name:J.string().optional(),queryParameters:J.list(m6e).optional(),headers:J.list(d6e).optional(),messages:J.list(zsr)}).extend(mn);var qsr=J.objectWithoutOptionalProperties({audiences:J.list(J.string()),path:J.string(),groupName:_he,summary:J.string().optional(),connectMethodName:J.string().optional(),handshake:jsr,messages:J.list(Lsr),servers:J.list(Usr),examples:J.list(Vsr)}).extend(mn).extend($o);var Dgs=J.objectWithoutOptionalProperties({apiVersion:J.unknown().optional(),title:J.string().optional(),description:J.string().optional(),basePath:J.string().optional(),servers:J.list(Kvt),websocketServers:J.list(Kvt),groups:J.record(J.string(),ksr),tags:Nsr,hasEndpointsMarkedInternal:J.boolean(),endpoints:J.list(msr),webhooks:J.list(Qsr),channels:J.record(J.string(),qsr),groupedSchemas:Fsr,variables:J.record(J.string(),Dhe),nonRequestReferencedSchemas:J.set(KP),securitySchemes:J.record(Bhe,Oor),security:gsr.optional(),globalHeaders:J.list(hsr).optional(),idempotencyHeaders:J.list(vsr).optional()});var Gsr=J.objectWithoutOptionalProperties({value:J.lazy(()=>$u)}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(_u).extend(Uf);var Wsr=J.objectWithoutOptionalProperties({}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(_u);var $u=J.union("type",{primitive:Dhe,object:J.lazyObject(()=>Psr),array:J.lazyObject(()=>jor),map:J.lazyObject(()=>Ssr),optional:J.lazyObject(()=>Gsr),enum:o6e,reference:_$,literal:B6e,oneOf:J.object({value:J.lazy(()=>Dsr)}),nullable:J.lazyObject(()=>Tsr),unknown:Wsr}).transform({transform:e=>{switch(e.type){case"primitive":return ba.primitive(e);case"object":return ba.object(e);case"array":return ba.array(e);case"map":return ba.map(e);case"optional":return ba.optional(e);case"enum":return ba.enum(e);case"reference":return ba.reference(e);case"literal":return ba.literal(e);case"oneOf":return ba.oneOf(e.value);case"nullable":return ba.nullable(e);case"unknown":return ba.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var Rsr=J.objectWithoutOptionalProperties({schemas:J.list(J.lazy(()=>$u))}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(Bx).extend($o).extend(_u).extend(Uf);var pli={};te(pli,{ArraySchemaWithExample:()=>$sr,Base64WithExample:()=>Hsr,BooleanWithExample:()=>Ksr,CommonPropertyWithExample:()=>Jsr,DateWithExample:()=>Ysr,DatetimeWithExample:()=>Jvt,DiscriminatedOneOfSchemaWithExample:()=>Xsr,DoubleWithExample:()=>Zsr,EndpointWithExample:()=>Rgs,EnumSchemaWithExample:()=>aar,FloatWithExample:()=>car,HeaderWithExample:()=>Rhe,HttpErrorWithExample:()=>ear,Int64WithExample:()=>uar,IntWithExample:()=>lar,JsonRequestWithExample:()=>rar,JsonResponseWithExample:()=>F6e,MapSchemaWithExample:()=>har,MultipartFormDataWebhookPayloadWithExample:()=>gar,NamedFullExample:()=>nk,NullableSchemaWithExample:()=>Aar,ObjectPropertyWithExample:()=>yar,ObjectSchemaWithExample:()=>bar,OneOfSchemaWithExample:()=>Ear,OptionalSchemaWithExample:()=>war,ParseFormUrlEncodedRequest:()=>nar,ParseMultipartRequest:()=>iar,ParseOctetStreamRequest:()=>oar,PathParameterWithExample:()=>tar,PrimitiveSchemaValueWithExample:()=>mar,PrimitiveSchemaWithExample:()=>N6e,QueryParameterWithExample:()=>R6e,RequestWithExample:()=>sar,ResponseWithExample:()=>k6e,SchemaWithExample:()=>zf,StringSchemaWithExample:()=>par,Uint64WithExample:()=>far,UintWithExample:()=>dar,UnDiscriminatedOneOfSchemaWithExample:()=>Iar,UnknownSchemaWithExample:()=>Car,WebhookWithExample:()=>Fgs,WebsocketHandshakeWithExample:()=>kgs});var $sr=J.objectWithoutOptionalProperties({value:J.lazy(()=>zf),minItems:J.number().optional(),maxItems:J.number().optional(),example:J.list(J.unknown()).optional()}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(_u).extend(Uf);var Hsr=J.objectWithoutOptionalProperties({example:J.string().optional()});var Ksr=J.objectWithoutOptionalProperties({default:J.boolean().optional(),example:J.boolean().optional()});var Jsr=J.objectWithoutOptionalProperties({key:J.string(),schema:J.lazy(()=>zf)});var Jvt=J.objectWithoutOptionalProperties({example:J.string().optional()});var Ysr=J.objectWithoutOptionalProperties({example:J.string().optional()});var Xsr=J.objectWithoutOptionalProperties({discriminantProperty:J.string(),discriminantPropertyNameOverride:J.string().optional(),discriminatorContext:f6e.optional(),commonProperties:J.list(J.lazyObject(()=>Jsr)),schemas:J.record(J.string(),J.lazy(()=>zf))}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(Bx).extend($o).extend(_u).extend(Uf);var Zsr=J.objectWithoutOptionalProperties({default:J.number().optional(),minimum:J.number().optional(),maximum:J.number().optional(),exclusiveMinimum:J.boolean().optional(),exclusiveMaximum:J.boolean().optional(),multipleOf:J.number().optional(),example:J.number().optional()});var Rhe=J.objectWithoutOptionalProperties({name:J.string(),schema:J.lazy(()=>zf),env:J.string().optional(),parameterNameOverride:J.string().optional()}).extend(mn).extend(us).extend($o);var nk=J.objectWithoutOptionalProperties({name:J.string().optional(),value:J.unknown()}).extend(mn);var ear=J.objectWithoutOptionalProperties({statusCode:w$,schema:J.lazy(()=>zf),fullExamples:J.list(nk).optional()}).extend(mn).extend(Nc).extend($o);var tar=J.objectWithoutOptionalProperties({name:J.string(),schema:J.lazy(()=>zf),variableReference:J.string().optional(),parameterNameOverride:J.string().optional(),explode:J.boolean().optional()}).extend(mn).extend(us).extend($o);var R6e=J.objectWithoutOptionalProperties({name:J.string(),schema:J.lazy(()=>zf),parameterNameOverride:J.string().optional(),explode:J.boolean().optional()}).extend(mn).extend(us).extend($o);var rar=J.objectWithoutOptionalProperties({schema:J.lazy(()=>zf),contentType:J.string().optional(),fullExamples:J.list(nk).optional(),additionalProperties:J.boolean()}).extend(mn).extend($o).extend(C$);var nar=J.objectWithoutOptionalProperties({schema:J.lazy(()=>zf),contentType:J.string().optional(),fullExamples:J.list(nk).optional(),additionalProperties:J.boolean()}).extend(mn).extend($o).extend(C$);var iar=J.objectWithoutOptionalProperties({fullExamples:J.list(nk).optional()}).extend(I6e).extend(C$);var oar=J.objectWithoutOptionalProperties({}).extend(w6e).extend(C$);var sar=J.union("type",{octetStream:oar,multipart:iar,json:rar,formUrlEncoded:nar}).transform({transform:e=>{switch(e.type){case"octetStream":return HP.octetStream(e);case"multipart":return HP.multipart(e);case"json":return HP.json(e);case"formUrlEncoded":return HP.formUrlEncoded(e);default:return e}},untransform:({_visit:e,...t})=>t});var F6e=J.objectWithoutOptionalProperties({schema:J.lazy(()=>zf),responseProperty:J.string().optional(),terminator:J.string().optional(),fullExamples:J.list(nk).optional()}).extend(mn).extend($o).extend(YU);var k6e=J.union("type",{file:C6e,json:F6e,text:Phe,bytes:p6e,streamingSse:F6e,streamingText:Phe,streamingJson:F6e}).transform({transform:e=>{switch(e.type){case"file":return Fh.file(e);case"json":return Fh.json(e);case"text":return Fh.text(e);case"bytes":return Fh.bytes(e);case"streamingSse":return Fh.streamingSse(e);case"streamingText":return Fh.streamingText(e);case"streamingJson":return Fh.streamingJson(e);default:return e}},untransform:({_visit:e,...t})=>t});var Rgs=J.objectWithoutOptionalProperties({authed:J.boolean(),security:g6e.optional(),internal:J.boolean().optional(),idempotent:J.boolean().optional(),method:y6e,audiences:J.list(J.string()),path:J.string(),summary:J.string().optional(),operationId:J.string().optional(),tags:J.list(JP),pathParameters:J.list(tar),queryParameters:J.list(R6e),headers:J.list(Rhe),sdkName:x$.optional(),generatedRequestName:J.string(),requestNameOverride:J.string().optional(),request:sar.optional(),response:k6e.optional(),errors:J.record(w$,ear),servers:J.list(A6e),examples:J.list(h6e),pagination:b6e.optional(),retries:S6e.optional()}).extend(mn).extend(us).extend($o).extend(oc);var aar=J.objectWithoutOptionalProperties({default:She.optional(),values:J.list(She),example:J.string().optional()}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend($o).extend(_u).extend(Uf);var car=J.objectWithoutOptionalProperties({example:J.number().optional()});var uar=J.objectWithoutOptionalProperties({default:J.number().optional(),example:J.number().optional()});var lar=J.objectWithoutOptionalProperties({default:J.number().optional(),minimum:J.number().optional(),maximum:J.number().optional(),exclusiveMinimum:J.boolean().optional(),exclusiveMaximum:J.boolean().optional(),multipleOf:J.number().optional(),example:J.number().optional()});var par=J.objectWithoutOptionalProperties({default:J.string().optional(),pattern:J.string().optional(),format:J.string().optional(),minLength:J.number().optional(),maxLength:J.number().optional(),example:J.string().optional()});var far=J.objectWithoutOptionalProperties({default:J.number().optional(),example:J.number().optional()});var dar=J.objectWithoutOptionalProperties({default:J.number().optional(),example:J.number().optional()});var mar=J.union("type",{int:lar,int64:uar,uint:dar,uint64:far,float:car,double:Zsr,string:par,datetime:Jvt,datetimeRfc2822:Jvt,date:Ysr,base64:Hsr,boolean:Ksr}).transform({transform:e=>{switch(e.type){case"int":return xi.int(e);case"int64":return xi.int64(e);case"uint":return xi.uint(e);case"uint64":return xi.uint64(e);case"float":return xi.float(e);case"double":return xi.double(e);case"string":return xi.string(e);case"datetime":return xi.datetime(e);case"datetimeRfc2822":return xi.datetimeRfc2822(e);case"date":return xi.date(e);case"base64":return xi.base64(e);case"boolean":return xi.boolean(e);default:return e}},untransform:({_visit:e,...t})=>t});var N6e=J.objectWithoutOptionalProperties({schema:mar}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(_u);var har=J.objectWithoutOptionalProperties({key:N6e,value:J.lazy(()=>zf),minProperties:J.number().optional(),maxProperties:J.number().optional(),example:J.unknown().optional()}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(Bx).extend(_u).extend(Uf);var gar=J.objectWithoutOptionalProperties({name:J.string().optional(),properties:J.list(Ohe)}).extend(mn).extend($o);var Aar=J.objectWithoutOptionalProperties({value:J.lazy(()=>zf)}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(_u).extend(Uf);var yar=J.objectWithoutOptionalProperties({key:J.string(),schema:J.lazy(()=>zf),readonly:J.boolean().optional(),writeonly:J.boolean().optional(),audiences:J.list(J.string()),conflict:J.record(KP,T6e),nameOverride:J.string().optional(),generatedName:J.string()}).extend(us);var bar=J.objectWithoutOptionalProperties({allOf:J.list(_$),properties:J.list(J.lazyObject(()=>yar)),allOfPropertyConflicts:J.list(c6e),fullExamples:J.list(nk).optional(),additionalProperties:J.boolean(),minProperties:J.number().optional(),maxProperties:J.number().optional()}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(Bx).extend($o).extend(_u).extend(Uf);var Ear=J.union("type",{discriminated:J.lazyObject(()=>Xsr),undiscriminated:J.lazyObject(()=>Iar)}).transform({transform:e=>{switch(e.type){case"discriminated":return vj.discriminated(e);case"undiscriminated":return vj.undiscriminated(e);default:return e}},untransform:({_visit:e,...t})=>t});var war=J.objectWithoutOptionalProperties({value:J.lazy(()=>zf)}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(_u).extend(Uf);var Car=J.objectWithoutOptionalProperties({example:J.unknown()}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(_u);var zf=J.union("type",{primitive:N6e,object:J.lazyObject(()=>bar),array:J.lazyObject(()=>$sr),map:J.lazyObject(()=>har),optional:J.lazyObject(()=>war),enum:aar,reference:_$,literal:B6e,oneOf:J.object({value:J.lazy(()=>Ear)}),nullable:J.lazyObject(()=>Aar),unknown:Car}).transform({transform:e=>{switch(e.type){case"primitive":return Fr.primitive(e);case"object":return Fr.object(e);case"array":return Fr.array(e);case"map":return Fr.map(e);case"optional":return Fr.optional(e);case"enum":return Fr.enum(e);case"reference":return Fr.reference(e);case"literal":return Fr.literal(e);case"oneOf":return Fr.oneOf(e.value);case"nullable":return Fr.nullable(e);case"unknown":return Fr.unknown(e);default:return e}},untransform:({_visit:e,...t})=>t});var Iar=J.objectWithoutOptionalProperties({schemas:J.list(J.lazy(()=>zf))}).extend(xu).extend(oc).extend(Nc).extend(mn).extend(us).extend(Bx).extend($o).extend(_u).extend(Uf);var Fgs=J.objectWithoutOptionalProperties({audiences:J.list(J.string()),sdkName:x$.optional(),method:P6e,summary:J.string().optional(),operationId:J.string(),tags:J.list(JP),headers:J.list(Rhe),generatedPayloadName:J.string(),payload:J.lazy(()=>zf),multipartFormData:gar.optional(),response:k6e.optional(),signatureVerification:D6e.optional(),examples:J.list(O6e)}).extend(mn).extend($o).extend(oc);var kgs=J.objectWithoutOptionalProperties({queryParameters:J.list(R6e),headers:J.list(Rhe)});var Ngs=/^(\d+)/,Q6e=/^[a-zA-Z][a-zA-Z0-9_]*$/,Qgs={"<":"LESS_THAN",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL_TO","<=":"LESS_THAN_OR_EQUAL_TO","!=":"NOT_EQUALS","=":"EQUAL_TO","==":"EQUAL_TO","*":"ALL","":"EMPTY",'""':"EMPTY_STRING","-":"HYPHEN","|":"PIPE",".":"DOT","/":"SLASH"};function FOe(e){let t=["zero","one","two","three","four","five","six","seven","eight","nine"],r=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],n=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"];if(e<0||e>9999)return;if(e<10)return t[e];if(e<20)return r[e-10];if(e<100){let s=Math.floor(e/10),a=e%10;return a===0?n[s]:`${n[s]}_${t[a]}`}if(e<1e3){let s=Math.floor(e/100),a=e%100;return a===0?`${t[s]}_hundred`:`${t[s]}_hundred_${FOe(a)}`}let i=Math.floor(e/1e3),o=e%1e3;return o===0?`${t[i]}_thousand`:`${t[i]}_thousand_${FOe(o)}`}Bi();function Yvt(e){let t=e.match(Ngs);if(t&&t[0]!=null){let r=t[0],n=e.substring(r.length),i=parseFloat(r);if(!isNaN(i)&&isFinite(i)){let o=FOe(i);return n.length>0?`${o}_${n}`:o}}}function j6e(e){let t=Yvt(e),r=Qgs[e];return t!=null?gu(Vn(t)):r??(e.toLowerCase()==="n/a"?"NOT_APPLICABLE":gu(Vn(e)))}Bi();function ik(e,t){return e.type==="primitive"&&t.type==="primitive"?jgs(e.schema,t.schema):e.type==="enum"&&t.type==="enum"?TAl(e.values,t.values):e.type==="array"&&t.type==="array"?ik(e.value,t.value):e.type==="unknown"&&t.type==="unknown"?!0:e.type==="reference"&&t.type==="reference"?e.schema===t.schema:e.type==="optional"&&t.type==="optional"?ik(e.value,t.value):e.type==="oneOf"&&t.type==="oneOf"?OAl(e.value,t.value):e.type==="object"&&t.type==="object"?PAl(e,t):e.type==="map"&&t.type==="map"?jgs(e.key.schema,t.key.schema)&&ik(e.value,t.value):e.type==="literal"&&t.type==="literal"?e.value===t.value:!1}function jgs(e,t){return e.type===t.type}function TAl(e,t){let r=new Set(e.map(i=>i.value)),n=new Set(t.map(i=>i.value));return $0(r,n)}function OAl(e,t){return e.type==="discriminated"&&t.type==="discriminated"?e.discriminantProperty===t.discriminantProperty&&Object.keys(e.schemas).length===Object.keys(t.schemas).length&&Object.entries(e.schemas).every(([r,n])=>{let i=t.schemas[r];return i==null?!1:ik(n,i)}):e.type==="undiscriminated"&&t.type==="undiscriminated"?e.schemas.length===t.schemas.length&&e.schemas.every((r,n)=>{let i=t.schemas[n];return i==null?!1:ik(r,i)}):!1}function PAl(e,t){if(Object.keys(e.properties).length!==Object.keys(t.properties).length)return!1;let r=Object.fromEntries(e.properties.map(n=>[n.key,n.schema]));return Object.entries(t.properties).every(([n,i])=>{let o=r[n];return o==null?!1:ik(o,i.schema)})}St();function ab(e){switch(e){case wx.Deprecated:return"deprecated";case wx.Beta:return"pre-release";case wx.GenerallyAvailable:return"generally-available";default:return}}St();function Xvt(e){if(e.type==="protobuf")return{proto:{type:e.typeName}};Be(e.type)}St();St();sA();Bi();function Mgs(e){let t=e.match(/^(_+)/),r=e.match(/(_+)$/),n=t?.[1]??"",i=r?.[1]??"";if(n===""&&i==="")return Vn(e);if(n.length+i.length>=e.length)return e;let o=e.slice(n.length,e.length-i.length||void 0);return`${n}${Vn(o)}${i}`}function DAl(e){let t=e.find(n=>typeof n=="object"&&n.type==="namespace"),r=e.filter(n=>typeof n=="string"||n.type!=="namespace");return t?[t,...r]:r}function Lgs(e){let t=e?DAl(e):void 0;if(t==null||t.length===0)return gOe;let r=[];for(let[n,i]of t.entries())typeof i=="string"?r.push(Mgs(i)):typeof i=="object"?i.type==="namespace"?n<t.length-1?r.push(Mgs(i.name)):r.push(i.name,gOe):Be(i.type):Be(i);return r.join("/")}function Vse(e){return Qs.of(`${Lgs(e)}.yml`)}function fli({sdkName:e,namespaceOverride:t}){let r;return e==null||e.groupName.length===0&&t==null?gOe:(t!=null?r=[{type:"namespace",name:t},...e.groupName.filter(n=>typeof n=="string"||n.type!=="namespace")]:r=e.groupName,Lgs(r))}function Ugs({sdkName:e,namespaceOverride:t}){return Qs.of(`${fli({sdkName:e,namespaceOverride:t})}.yml`)}function zgs({location:e,namespaceOverride:t}){return t!=null?H0(Qs.of(t),e):e}function Vgs(e){switch(e.type){case"object":case"primitive":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":case"unknown":return xar({namespace:e.namespace,groupName:e.groupName});case"oneOf":return xar({namespace:e.value.namespace,groupName:e.value.groupName});default:Be(e)}}function xar({namespace:e,groupName:t}){return e!=null&&t!=null?Vse([{type:"namespace",name:e},...t]):e!=null?Vse([{type:"namespace",name:e}]):Vse(t)}St();function qse(e){switch(e.type){case"object":case"enum":case"array":case"map":case"reference":case"literal":case"optional":case"nullable":case"primitive":case"unknown":return e.groupName??void 0;case"oneOf":return e.value.groupName??void 0;default:Be(e)}}function bp(e){return typeof e=="string"?e:e.type}function M6e(e){if(typeof e!="string")return e.docs}function Zvt(e){if(typeof e!="string")return e.default}function dli(e){if(typeof e!="string")return e.validation}function L6e(e){let t=e.match(/^optional<\s*nullable<\s*(.+)\s*>\s*>$/);if(t!=null&&t[1]!=null)return t[1].trim();let r=e.match(/^nullable<\s*(.+)\s*>$/);return r!=null&&r[1]!=null?r[1].trim():e}function Ggs(e){let t=bp(e);return t.startsWith("nullable<")||t.startsWith("optional<nullable<")?e:typeof e=="string"?qgs(e):{...e,type:qgs(e.type)}}function qgs(e){return e.startsWith("nullable<")||e.startsWith("optional<nullable<")?e:e.startsWith("optional<")?e.replace("optional<","optional<nullable<")+">":`nullable<${e}>`}function kOe(e){return bp(e).startsWith("optional<")?e:typeof e=="string"?Wgs(e):{...e,type:Wgs(e.type)}}function Wgs(e){return e.startsWith("optional<")?e:`optional<${e}>`}var RAl=-2147483648,FAl=2147483647,kAl=-17976931348623157e292,NAl=17976931348623157e292;function pc({schema:e,fileContainingReference:t,declarationFile:r=t,context:n,namespace:i,declarationDepth:o,variant:s}){switch(n.shouldMarkSchemaAsReferenced()&&n.markSchemaAsReferenced(e,i),e.type){case"primitive":return _ar(e);case"array":return gli({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:o,variant:s});case"map":return Ali({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:o,variant:s});case"reference":return hli({schema:e,fileContainingReference:t,context:n,namespace:i,variant:s});case"unknown":return bli();case"optional":return Sar({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:o,variant:s});case"nullable":return yli({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:o,variant:s});case"enum":return GAl({schema:e,fileContainingReference:t,context:n,declarationFile:r,declarationDepth:o});case"literal":return e.value,Eli(e);case"object":return WAl({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:o,variant:s});case"oneOf":return $Al({schema:e.value,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:o,variant:s});default:Be(e)}}function _ar(e){switch(e.schema.type){case"string":return MAl({description:e.description,schema:e.schema});case"int":return LAl({description:e.description,schema:e.schema});case"float":return UAl({description:e.description,schema:e.schema});case"double":return zAl({description:e.description,schema:e.schema});case"boolean":return QAl({description:e.description,schema:e.schema});case"int64":return jAl({description:e.description,schema:e.schema})}let t=e.schema._visit({int:()=>"integer",int64:()=>"long",uint:()=>"uint",uint64:()=>"uint64",float:()=>"double",double:()=>"double",string:()=>"string",datetime:()=>"datetime",datetimeRfc2822:()=>"datetime-rfc-2822",date:()=>"date",base64:()=>"base64",boolean:()=>"boolean",_other:()=>"unknown"});return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:ab(e.availability)}:{}}}function QAl({description:e,schema:t}){let r="boolean";if(e==null&&t.default==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),n}function jAl({description:e,schema:t}){let r="long";if(e==null&&t.default==null)return r;let n={type:r};return e!=null&&(n.docs=e),t.default!=null&&(n.default=t.default),n}function MAl({description:e,schema:t}){let r="string",n=VAl(t);if(e==null&&t.default==null&&n==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),n!=null&&(i.validation=n),i}function LAl({description:e,schema:t}){let r="integer",n=$gs(t,r);if(e==null&&t.default==null&&n==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),n!=null&&(i.validation=n),i}function UAl({description:e,schema:t}){let r="float";if(e==null)return r;let n={type:r};return e!=null&&(n.docs=e),n}function zAl({description:e,schema:t}){let r="double",n=$gs(t,r);if(e==null&&t.default==null&&n==null)return r;let i={type:r};return e!=null&&(i.docs=e),t.default!=null&&(i.default=t.default),n!=null&&(i.validation=n),i}function VAl(e){if(e==null)return;let{format:t,pattern:r,minLength:n,maxLength:i}=e,o=qAl(t);if(!(o==null&&r==null&&n==null&&i==null))return{format:o,pattern:r,minLength:n,maxLength:i}}function qAl(e){switch(e){case"date":case"date-time":case"password":case"byte":case"bytes":case"binary":case"email":case"uuid":case"uri":case"hostname":case"ipv4":case"ipv6":return e;default:return}}function $gs(e,t){if(e==null)return;let{minimum:r,maximum:n,multipleOf:i}=e,{exclusiveMinimum:o,exclusiveMaximum:s}=e;if(r=mli(r,t),n=mli(n,t),i=mli(i,t),!(r==null&&n==null&&o==null&&s==null&&i==null))return{min:r,max:n,exclusiveMin:o,exclusiveMax:s,multipleOf:i}}function mli(e,t){if(e===void 0)return;let[r,n]=t==="integer"?[RAl,FAl]:[kAl,NAl];return e<r||e>n?void 0:e}function hli({schema:e,fileContainingReference:t,context:r,variant:n}){let i=r.getSchema(e.schema,e.namespace);if(i==null)return"unknown";let o=HAl(i)??e.schema,s=r.options.respectReadonlySchemas&&n!=null?r.getSchemaFinalName(o,n):o,a=qse(i),c=KAl(i),l=Bar({context:r,fileContainingReference:t,declarationFile:xar({namespace:e.namespace,groupName:a}),type:s});return i.type==="nullable"&&(l=r.options.wrapReferencesToNullableInOptional?`optional<${l}>`:`nullable<${l}>`),i.type==="optional"&&!l.startsWith("optional<")&&(l=`optional<${l}>`),e.description==null&&c==null?l:{type:l,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:ab(e.availability)}:{}}}function gli({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}){let a=pc({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}),c=`list<${bp(a)}>`;return e.description==null&&e.title==null?c:{...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:ab(e.availability)}:{},type:c}}function Ali({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}){let a=_ar(e.key),c=pc({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}),u=e.encoding!=null?Xvt(e.encoding):void 0,l=`map<${bp(a)}, ${bp(c)}>`;if(e.description==null&&u==null&&e.title==null)return l;let p={type:l};return e.description!=null&&(p.docs=e.description),e.encoding!=null&&(p.encoding=u),e.availability!=null&&(p.availability=ab(e.availability)),p}function yli({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}){if(!n.options.respectNullableSchemas)return Sar({schema:e,fileContainingReference:t,context:n,declarationFile:r,namespace:i,declarationDepth:o,variant:s});let a=pc({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}),c=bp(a),u=M6e(a),l=Zvt(a),p=dli(a),d=Ggs(c);if(n.options.wrapReferencesToNullableInOptional&&(d=kOe(d)),e.availability==null&&e.description==null&&u==null&&l==null&&p==null&&e.title==null)return d;let f=typeof d=="string"?{type:d}:d;return(e.description!=null||u!=null)&&(f.docs=e.description??u),l!=null&&(f.default=l),p!=null&&(f.validation=p),e.availability!=null&&(f.availability=ab(e.availability)),f}function Sar({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}){let a=pc({schema:e.value,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}),c=bp(a),u=M6e(a),l=Zvt(a),p=dli(a),d=kOe(c);if(e.availability==null&&e.description==null&&u==null&&l==null&&p==null&&e.title==null)return d;let f=typeof d=="string"?{type:d}:d;return(e.description!=null||u!=null)&&(f.docs=e.description??u),l!=null&&(f.default=l),p!=null&&(f.validation=p),e.availability!=null&&(f.availability=ab(e.availability)),f}function bli(){return"unknown"}function Eli(e){let t;switch(e.value.type){case"boolean":{t=`literal<${e.value.value}>`;break}case"string":{t=`literal<"${e.value.value}">`;break}default:Be(e.value)}return e.description==null&&e.title==null?t:{type:t,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:ab(e.availability)}:{}}}function GAl({schema:e,fileContainingReference:t,declarationFile:r,context:n,declarationDepth:i}){let o=eIt(e,i),s=e.nameOverride??e.generatedName;n.builder.addType(r,{name:s,schema:o.schema});let a=Bar({type:s,fileContainingReference:t,declarationFile:r,context:n});if(e.description==null&&e.default==null&&e.title==null)return a;let c={type:a};return e.description!=null&&(c.docs=e.description),e.default!=null&&(c.default=e.default.value),e.availability!=null&&(c.availability=ab(e.availability)),c}function WAl({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}){let a=NOe({schema:e,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}),c=e.nameOverride??e.generatedName;n.builder.addType(r,{name:c,schema:a.schema});let u=Bar({type:c,fileContainingReference:t,declarationFile:r,context:n});return e.description==null&&e.title==null?u:{type:u,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:ab(e.availability)}:{}}}function $Al({schema:e,fileContainingReference:t,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}){let a=vli({schema:e,declarationFile:r,context:n,namespace:i,declarationDepth:o,variant:s}),c=e.nameOverride??e.generatedName;n.builder.addType(r,{name:c,schema:a.schema});let u=Bar({type:c,fileContainingReference:t,declarationFile:r,context:n});return e.description==null&&e.title==null?u:{...e.title!=null?{"display-name":e.title}:{},type:u,...e.description!=null?{docs:e.description}:{},...e.availability!=null?{availability:ab(e.availability)}:{}}}function Bar({type:e,fileContainingReference:t,declarationFile:r,context:n}){if(r===t)return e;let i=n.builder.addImport({file:t,fileToImport:r});return i!=null?`${i}.${e}`:e}function HAl(e){return ba._visit(e,{primitive:t=>t.nameOverride??t.generatedName,object:t=>t.nameOverride??t.generatedName,array:t=>t.nameOverride??t.generatedName,map:t=>t.nameOverride??t.generatedName,enum:t=>t.nameOverride??t.generatedName,reference:t=>t.nameOverride??t.generatedName,literal:t=>t.nameOverride??t.generatedName,oneOf:t=>t.nameOverride??t.generatedName,optional:t=>t.nameOverride??t.generatedName,nullable:t=>t.nameOverride??t.generatedName,unknown:t=>t.nameOverride??t.generatedName,_other:()=>{}})}function KAl(e){return ba._visit(e,{primitive:t=>t.title,object:t=>t.title,array:t=>t.title,map:t=>t.title,enum:t=>t.title,reference:t=>t.title,literal:t=>t.title,oneOf:t=>t.title,optional:t=>t.title,nullable:t=>t.title,unknown:t=>{},_other:()=>{}})}St();function Gse(e){switch(e.type){case"openapi":return{openapi:e.file};case"protobuf":return{proto:e.file};default:Be(e)}}function Kgs({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i,variant:o}){let s;switch(e.type){case"primitive":s=XAl(e);break;case"array":s=JAl({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;case"map":s=YAl({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;case"reference":s=ZAl({schema:e,context:t,declarationFile:r,namespace:n,variant:o});break;case"unknown":s=tyl(e.nameOverride,e.generatedName,e.description);break;case"optional":s=Ygs({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;case"nullable":s=eyl({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i});break;case"enum":s=eIt(e,i);break;case"literal":s=ryl(e,e.nameOverride,e.generatedName);break;case"object":s=NOe({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i,variant:o});break;case"oneOf":s=vli({schema:e.value,context:t,declarationFile:r,namespace:n,declarationDepth:i,variant:o});break;default:Be(e)}return s}function NOe({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i,skipReadonlyProperties:o,variant:s}){let a=o===!0||s==="write",c=!1,u={},l=new Set;for(let g of e.properties){if(g.readonly&&(c=!0),a&&g.readonly)continue;if(Object.keys(g.conflict).length>0){if(Object.entries(g.conflict).every(([x,C])=>!C.differentSchema))continue;Object.entries(g.conflict).forEach(([x])=>{Ili({property:g.key,schemaId:x,context:t,namespace:n}).forEach(_=>{l.add(_)})})}let A=pc({schema:g.schema,context:t,fileContainingReference:r,namespace:n,declarationDepth:i+1,variant:s}),b=g.audiences,v=g.nameOverride,E=ab(g.availability),I=syl(g);u[g.key]=oyl({typeReference:A,audiences:b,name:v,availability:E,propertyAccess:I})}let p=new Set;for(let g of e.allOfPropertyConflicts)g.allOfSchemaIds.forEach(A=>l.add(A)),g.conflictingTypeSignatures&&p.add(g.propertyKey);let d=[];for(let g of e.allOf){let A=Tar({schema:g.schema,context:t,namespace:n});if(A==null||l.has(g.schema)||l.has(A))continue;let b=pc({schema:ba.reference(g),context:t,fileContainingReference:r,namespace:n,declarationDepth:i+1,variant:s});d.push(L6e(bp(b)))}for(let g of l){let A=U6e(t,g,n);for(let b of A.properties)u[b.key]==null&&(p.has(b.key)&&(u[b.key]="unknown"),u[b.key]=pc({schema:b.schema,context:t,fileContainingReference:r,namespace:n,declarationDepth:i+1,variant:s}));for(let b of A.allOf){if(l.has(b.schema))continue;let v=pc({schema:ba.reference(b),context:t,fileContainingReference:r,namespace:n,declarationDepth:i+1,variant:s});d.push(L6e(bp(v)))}}let f={docs:e.description??void 0,properties:Object.fromEntries(Object.entries(u).map(([g,A])=>iyl(g)?[g,typeof A=="string"?{type:A,name:`_${g}`}:{...A,name:`_${g}`}]:[g,A]))};d.length>0&&(f.extends=d),e.additionalProperties&&(f["extra-properties"]=!0),e.availability!=null&&(f.availability=ab(e.availability)),e.source!=null&&(f.source=Gse(e.source)),e.encoding!=null&&(f.encoding=Xvt(e.encoding)),f.inline=wli(e,i);let m=e.nameOverride??e.generatedName;return{name:s==="read"&&c&&t.options.respectReadonlySchemas&&t.hasReadVariant(m)?`${m}Read`:m,schema:f}}function Ili({property:e,schemaId:t,context:r,namespace:n}){let i=r.getSchema(t,n);if(i==null)return[];if(i.type==="reference")return Ili({property:e,schemaId:i.schema,context:r,namespace:n});if(i.type==="object"){let{properties:o,allOf:s}=U6e(r,t,n),a=o.some(u=>u.key===e),c=[...s.flatMap(u=>Ili({property:e,context:r,schemaId:u.schema,namespace:n}))];if(a||c.length>0)return[t,...c]}return[]}function Jgs(e,t,r){return t.type==="object"?{properties:t.properties,allOf:t.allOf}:t.type==="reference"?U6e(e,t.schema,r):t.type==="nullable"?Jgs(e,t.value,r):{properties:[],allOf:[]}}function U6e(e,t,r){let n=e.getSchema(t,r);return n==null?{properties:[],allOf:[]}:Jgs(e,n,r)}function JAl({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){return{name:e.nameOverride??e.generatedName,schema:gli({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:n,declarationDepth:i})}}function YAl({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){return{name:e.nameOverride??e.generatedName,schema:Ali({schema:e,fileContainingReference:r,declarationFile:r,context:t,namespace:n,declarationDepth:i})}}function XAl(e){let t=_ar(e);if(typeof t=="string")return{name:e.nameOverride??e.generatedName,schema:t};let{default:r,...n}=t;return{name:e.nameOverride??e.generatedName,schema:{...n}}}function Hgs(e){return e.camel==null&&e.pascal==null&&e.screamingSnake==null&&e.snake==null}function eIt(e,t){let r={enum:e.values.map(o=>{let s=o.nameOverride??o.generatedName,a=o.value;if(s===a&&o.description==null&&(o.casing==null||Hgs(o.casing)))return s;let c={value:o.value};if(s!==a&&(c.name=s),o.description!=null&&(c.docs=o.description),o.casing!=null&&!Hgs(o.casing)){let u={},l=!1;o.casing.camel!=null&&(u.camel=o.casing.camel,l=!0),o.casing.screamingSnake!=null&&(u["screaming-snake"]=o.casing.screamingSnake,l=!0),o.casing.snake!=null&&(u.snake=o.casing.snake,l=!0),o.casing.pascal!=null&&(u.pascal=o.casing.pascal,l=!0),l&&(c.casing=u)}return c})};e.description!=null&&(r.docs=e.description),e.default!=null&&(r.default=e.default.value),r.inline=wli(e,t);let n=new Set,i={...r,enum:[],source:e.source!=null?Gse(e.source):void 0};for(let o of r.enum){let s=typeof o=="string"?o:o.name??o.value;n.has(s.toLowerCase())||(i.enum.push(o),n.add(s.toLowerCase()))}return{name:e.nameOverride??e.generatedName,schema:i}}function ZAl({schema:e,context:t,declarationFile:r,namespace:n,variant:i}){return{name:e.nameOverride??e.generatedName,schema:hli({schema:e,context:t,fileContainingReference:r,namespace:n,variant:i})}}function eyl({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){return t.options.respectNullableSchemas?{name:e.nameOverride??e.generatedName,schema:yli({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:n,declarationDepth:i})}:Ygs({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i})}function Ygs({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i}){return{name:e.nameOverride??e.generatedName,schema:Sar({schema:e,context:t,fileContainingReference:r,declarationFile:r,namespace:n,declarationDepth:i})}}function tyl(e,t,r){return r!=null?{name:e??t,schema:{type:"unknown",docs:r}}:{name:e??t,schema:bli()}}function ryl(e,t,r){return{name:t??r,schema:Eli(e)}}function vli({schema:e,context:t,declarationFile:r,namespace:n,declarationDepth:i,variant:o}){let s=e.encoding!=null?Xvt(e.encoding):void 0;if(e.type==="discriminated"){let c={};for(let l of e.commonProperties)c[l.key]=pc({schema:l.schema,fileContainingReference:r,context:t,namespace:n,declarationDepth:i+1,variant:o});let u={};for(let[l,p]of Object.entries(e.schemas))u[l]=pc({schema:p,context:t,fileContainingReference:r,namespace:n,declarationDepth:i+1,variant:o});return{name:e.nameOverride??e.generatedName,schema:{discriminant:e.discriminantPropertyNameOverride!=null||e.discriminatorContext!=null?{...e.discriminantPropertyNameOverride!=null&&{name:e.discriminantPropertyNameOverride},value:e.discriminantProperty,...e.discriminatorContext!=null&&{context:e.discriminatorContext}}:e.discriminantProperty,"base-properties":c,docs:e.description??void 0,availability:e.availability!=null?ab(e.availability):void 0,union:u,encoding:s,source:e.source!=null?Gse(e.source):void 0}}}let a=[];for(let c of e.schemas)a.push(pc({schema:c,fileContainingReference:r,context:t,namespace:n,declarationDepth:i+1,variant:o}));return{name:e.nameOverride??e.generatedName,schema:{discriminated:!1,docs:e.description??void 0,union:a,encoding:s,source:e.source!=null?Gse(e.source):void 0,inline:wli(e,i)}}}var nyl=/^[0-9]/;function iyl(e){return nyl.test(e)}function Tar({schema:e,context:t,namespace:r}){let n=t.getSchema(e,r);if(n!=null)return n.type==="reference"?Tar({context:t,schema:n.schema,namespace:r}):e}function oyl({typeReference:e,audiences:t,name:r,availability:n,propertyAccess:i}){return t.length===0&&r==null&&n==null&&i==null?e:{...typeof e=="string"?{type:e}:{...e},...t.length>0?{audiences:t}:{},...r!=null?{name:r}:{},...n!=null?{availability:n}:{},...i!=null?{access:i}:{}}}function wli(e,t){return e.inline===!0||t>0?!0:void 0}function syl(e){if(!(e.readonly&&e.writeonly)){if(e.readonly)return Sm.ObjectPropertyAccess.ReadOnly;if(e.writeonly)return Sm.ObjectPropertyAccess.WriteOnly}}Bi();function Xgs(e){let t=e.replace(/^x-|^X-/,"");return Vn(t)}function Zgs(e){if(e.authOverrides!=null){for(let[r,n]of Object.entries(e.authOverrides["auth-schemes"]??{}))e.builder.addAuthScheme({name:r,schema:n});e.authOverrides.auth!=null&&e.builder.setAuth(e.authOverrides.auth);return}let t=!1;for(let[r,n]of Object.entries(e.ir.securitySchemes))if(n.type==="basic"){let i={scheme:"basic"};n.usernameVariableName!=null&&(i.username===void 0?i.username={name:n.usernameVariableName}:i.username.name=n.usernameVariableName),n.usernameEnvVar!=null&&(i.username===void 0?i.username={env:n.usernameEnvVar}:i.username.env=n.usernameEnvVar),n.passwordVariableName!=null&&(i.password===void 0?i.password={name:n.passwordVariableName}:i.password.name=n.passwordVariableName),n.passwordEnvVar!=null&&(i.password===void 0?i.password={env:n.passwordEnvVar}:i.password.env=n.passwordEnvVar),e.builder.addAuthScheme({name:r,schema:i}),t||(e.builder.setAuth(r),t=!0)}else if(n.type==="bearer"){let i={scheme:"bearer"};n.tokenVariableName!=null&&(i.token===void 0?i.token={name:n.tokenVariableName}:i.token.name=n.tokenVariableName),n.tokenEnvVar!=null&&(i.token===void 0?i.token={env:n.tokenEnvVar}:i.token.env=n.tokenEnvVar),e.builder.addAuthScheme({name:r,schema:i}),t||(e.builder.setAuth(r),t=!0)}else if(n.type==="header")if(t)e.builder.addGlobalHeader({name:n.headerName,schema:{type:"string",name:n.headerVariableName??Xgs(n.headerName),env:n.headerEnvVar}});else{let i={header:n.headerName,name:n.headerVariableName??"apiKey",type:"string"};n.headerEnvVar!=null&&(i.env=n.headerEnvVar),n.prefix!=null&&(i.prefix=n.prefix),e.builder.addAuthScheme({name:r,schema:i}),e.builder.setAuth(r),t=!0}else if(n.type==="oauth"){let i={scheme:"bearer"};e.builder.addAuthScheme({name:r,schema:i}),t||(e.builder.setAuth(r),t=!0),n.scopesEnum!=null&&n.scopesEnum.values.length>0&&e.builder.addType(Qs.of("__package__.yml"),{name:"OauthScope",schema:eIt(n.scopesEnum,0).schema})}}Bi();function S$({header:e,context:t,fileContainingReference:r,namespace:n}){let i=pc({schema:e.schema,context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),o=bp(i),s=e.name.replace(/^x-|^X-/,""),a=e.parameterNameOverride!=null?e.parameterNameOverride:Vn(s);if(e.description==null&&e.name===a&&e.env==null&&e.availability==null)return o;let c={type:o};return a!==e.name&&(c.name=a),e.description!=null&&(c.docs=e.description),e.env!=null&&(c.env=e.env),e.availability!=null&&(c.availability=ab(e.availability)),c}function Oar({pathParameter:e,context:t,fileContainingReference:r,namespace:n}){let i=pc({schema:e.schema,context:t,fileContainingReference:r,namespace:n,declarationDepth:0});if(e.variableReference==null&&e.description==null&&e.availability==null)return bp(i);let o=e.variableReference!=null?{variable:`$${e.variableReference}`}:{type:bp(i)};return e.description!=null&&(o.docs=e.description),e.availability!=null&&(o.availability=ab(e.availability)),o}sA();function Dar({queryParameter:e,context:t,fileContainingReference:r,namespace:n}){let i=Cli({schema:e.schema,context:t,fileContainingReference:r,namespace:n});if(i==null)return;let o=bp(i.value),s=Zvt(i.value);o==="unknown"?o="string":o==="optional<unknown>"&&(o="optional<string>");let a={type:o};return s!=null&&(a.default=s),i.allowMultiple&&(a["allow-multiple"]=!0),e.explode!=null&&(a.explode=e.explode),e.description!=null&&(a.docs=e.description),e.parameterNameOverride!=null&&(a.name=e.parameterNameOverride),e.availability!=null&&(a.availability=ab(e.availability)),ayl(i.value)&&i.value.validation!==void 0&&(a.validation=i.value.validation),a.default==null&&a["allow-multiple"]==null&&a.docs==null&&a.name==null&&a.availability==null&&a.validation==null&&a.explode==null?o:a}function Cli({schema:e,context:t,fileContainingReference:r,namespace:n}){if(e.type==="reference"){let i=t.getSchema(e.schema,n);if(i==null)return;if(i.type==="array")return{value:pc({schema:ba.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:i.value,description:e.description??i.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,declarationFile:Qs.of(tf),fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0};if(i.type==="oneOf"&&i.value.type==="undiscriminated"){let o=[],s=!1;for(let[a,c]of Object.entries(i.value.schemas))c.type==="primitive"&&c.schema.type==="string"&&(s=!0),c.type==="literal"&&c.value.type==="string"&&(Q6e.test(c.value.value)?o.push(c.value.value):o.push({value:c.value.value,name:j6e(c.value.value)}));if(o.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:o}}),s&&t.options.respectForwardCompatibleEnums?(t.builder.addType(r,{name:`${e.generatedName}OrString`,schema:{discriminated:!1,union:[{type:"string"},{type:e.generatedName}]}}),{value:`${e.generatedName}OrString`,allowMultiple:!1}):{value:e.generatedName,allowMultiple:!1};if(i.value.schemas.length===2){let[a,c]=i.value.schemas;if(a!=null&&c!=null&&Par({array:a,primitive:c}))return{value:pc({schema:ba.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:c,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0};if(a!=null&&c!=null&&Par({array:c,primitive:a}))return{value:pc({schema:ba.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:a,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:void 0}),context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0}}for(let[a,c]of Object.entries(i.value.schemas))return Cli({schema:c,context:t,fileContainingReference:r,namespace:n})}else if(t.options.objectQueryParameters)return{value:pc({schema:e,context:t,fileContainingReference:r,declarationFile:Qs.of(tf),namespace:n,declarationDepth:0}),allowMultiple:!1}}if(e.type==="optional"||e.type==="nullable"){let i=e.type==="optional"?ba.optional:ba.nullable;if(e.value.type==="reference"){let o=t.getSchema(e.value.schema,n);if(o==null)return;if(o.type==="array")return{value:pc({schema:i({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:o.value,description:e.description??o.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,declarationFile:Qs.of(tf),namespace:n,declarationDepth:0}),allowMultiple:!0};if(t.options.objectQueryParameters)return{value:pc({schema:e,context:t,fileContainingReference:r,declarationFile:Qs.of(tf),namespace:n,declarationDepth:0}),allowMultiple:!1}}if(e.value.type==="array")return{value:pc({schema:i({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value.value,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0};if(e.value.type==="oneOf"&&e.value.value.type==="undiscriminated"){let o=[],s=!1;for(let[a,c]of Object.entries(e.value.value.schemas))c.type==="primitive"&&c.schema.type==="string"&&(s=!0),c.type==="literal"&&c.value.type==="string"&&(Q6e.test(c.value.value)?o.push(c.value.value):o.push({value:c.value.value,name:j6e(c.value.value)}));if(o.length>0)return t.builder.addType(r,{name:e.generatedName,schema:{enum:o}}),s&&t.options.respectForwardCompatibleEnums?(t.builder.addType(r,{name:`${e.generatedName}OrString`,schema:{discriminated:!1,union:[{type:"string"},{type:`optional<${e.value.value.generatedName}>`}]}}),{value:`optional<${e.value.value.generatedName}OrString>`,allowMultiple:!1}):{value:`optional<${e.value.value.generatedName}>`,allowMultiple:!1};if(e.value.value.schemas.length===2){let[a,c]=e.value.value.schemas;if(a!=null&&c!=null&&Par({array:a,primitive:c}))return{value:pc({schema:i({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:c,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0};if(a!=null&&c!=null&&Par({array:c,primitive:a}))return{value:pc({schema:i({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:a,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0}}if(t.options.objectQueryParameters)return{value:pc({schema:e,context:t,fileContainingReference:r,declarationFile:Qs.of(tf),namespace:n,declarationDepth:0}),allowMultiple:!1};for(let[a,c]of Object.entries(e.value.value.schemas))return Cli({schema:i({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:c,description:void 0,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:n})}else if(e.value.type==="object")return t.options.objectQueryParameters?{value:pc({schema:e,context:t,fileContainingReference:r,declarationFile:Qs.of(tf),namespace:n,declarationDepth:0}),allowMultiple:!1}:void 0;return{value:pc({schema:e,context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!1}}return e.type==="array"?{value:pc({schema:ba.optional({nameOverride:e.nameOverride,generatedName:e.generatedName,title:e.title,value:e.value,description:e.description,availability:e.availability,namespace:void 0,groupName:void 0,inline:e.inline}),context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!0}:{value:pc({schema:e,context:t,fileContainingReference:r,namespace:n,declarationDepth:0}),allowMultiple:!1}}function Par({array:e,primitive:t}){return e?.type==="array"&&e.value.type==="primitive"&&t?.type==="primitive"&&e.value.schema.type===t.schema.type}function ayl(e){return typeof e=="object"&&e!==null&&"type"in e}St();function eAs({websocketExample:e,context:t}){let r={messages:[]};e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=cyl(e.queryParameters)),e.headers!=null&&e.headers.length>0&&(r.headers=uyl({context:t,namedFullExamples:e.headers}));for(let n of e.messages){let i=Fhe(n.payload);i!=null&&r.messages.push({type:n.messageType,body:i})}return r}function cyl(e){let t={};return e.forEach(r=>{let n=Fhe(r.value);Array.isArray(n)?t[r.name]=n[0]:n!=null&&(t[r.name]=n)}),t}function uyl({context:e,namedFullExamples:t}){let r=e.builder.getGlobalHeaderNames(),n={};return t.forEach(i=>{let o=Fhe(i.value);r.has(i.name)||o!=null&&(n[i.name]=o)}),n}function Fhe(e){switch(e.type){case"primitive":return tAs(e.value);case"object":return rAs(e.properties);case"array":return lyl(e.value);case"map":return pyl(e.value);case"oneOf":return fyl(e.value);case"enum":return e.value;case"literal":return dyl(e.value);case"unknown":return Fhe(e.value);case"null":return null;default:Be(e)}}function tAs(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`${e.value.slice(1)}`:e.value;case"datetime":try{return new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"datetimeRfc2822":return e.value;case"date":return e.value;case"base64":case"boolean":return e.value;default:Be(e)}}function rAs(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Fhe(r)]))}function lyl(e){return e.map(t=>Fhe(t))}function pyl(e){return Object.fromEntries(e.map(t=>[tAs(t.key),Fhe(t.value)]))}function fyl(e){return e.type==="discriminated"?rAs(e.value):Fhe(e.value)}function dyl(e){switch(e.type){case"string":return e.value;case"boolean":return e.value;default:Be(e)}}function tIt(e){try{let r=new URL(e).pathname.split("/").filter(n=>n.length>0);if(r.length>0)return r[r.length-1]}catch{}}function Rar(e){try{return new URL(e).protocol.replace(":","")}catch{return}}function Far(e,t,r=!1){let n=tIt(t);return r&&n!=null?n:e!=null&&n!=null?`${e}_${n}`:n??e??"websocket"}function Wse(e){return e.find(t=>typeof t!="string"&&t.type==="namespace")?.name}function kar(e,t){return t??(e?.groupName!=null?Wse(e.groupName):void 0)}function nAs({channel:e,context:t,declarationFile:r}){let n=e.servers[0],i=t.ir.servers.length===0&&t.ir.websocketServers.length<=1,o=n!=null&&!i?t.options.groupEnvironmentsByHost?t.getUrlId(n.url)??Far(n.name,n.url,!0):n.name:void 0;t.logger.debug(`[buildChannel] Channel path="${e.path}", server name="${n?.name}", server url="${n?.url}", resolved urlId="${o}" (from collision map: ${t.getUrlId(n?.url??"")!=null})`);let s=e.path;for(let f of e.handshake.pathParameters)f.parameterNameOverride!=null&&(s=s.replace(`{${f.name}}`,`{${f.parameterNameOverride}}`));let a=t.authOverrides?.auth!=null,c={path:s,url:o,auth:a};e.audiences!=null&&e.audiences.length>0&&(c.audiences=e.audiences),e.summary!=null&&(c["display-name"]=e.summary),e.connectMethodName!=null&&(c["connect-method-name"]=e.connectMethodName),e.description!=null&&(c.docs=e.description);let u=Wse(e.groupName),l={};if(e.handshake.pathParameters.length>0)for(let f of e.handshake.pathParameters){let m=f.parameterNameOverride??f.name;l[m]=Oar({pathParameter:f,context:t,fileContainingReference:r,namespace:u})}Object.keys(l).length>0&&(c["path-parameters"]=l);let p={};if(e.handshake.queryParameters.length>0)for(let f of e.handshake.queryParameters){let m=Dar({queryParameter:f,context:t,fileContainingReference:r,namespace:u});m!=null&&(p[f.name]=m)}Object.keys(p).length>0&&(c["query-parameters"]=p);let d={};if(e.handshake.headers.length>0)for(let f of e.handshake.headers){let m=S$({header:f,context:t,fileContainingReference:r,namespace:u});d[f.name]=m}Object.keys(d).length>0&&(c.headers=d),t.builder.addChannel(r,{channel:c});for(let f of e.messages){let m={origin:f.origin,body:pc({schema:f.body,context:t,fileContainingReference:r,namespace:u,declarationDepth:0})};f.methodName!=null&&(m["method-name"]=f.methodName),t.builder.addChannelMessage(r,{messageId:f.name,message:m})}for(let f of e.examples){let m=eAs({context:t,websocketExample:f});t.builder.addChannelExample(r,{example:m})}}function xli(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="grouped"}var CI="Base",sAs="Default";function iAs(e){try{return new URL(e).hostname}catch{return}}function oAs(e){return e??sAs}function myl(e,t){let r=new Map;for(let n of e){if(xli(n)||!("url"in n)||!n.url)continue;let i=iAs(n.url)??n.url;r.has(i)||r.set(i,{environmentName:oAs(n.name),httpServers:[],websocketServers:[]}),r.get(i)?.httpServers.push({name:n.name,url:n.url,audiences:n.audiences})}for(let n of t){let i=iAs(n.url)??n.url;r.has(i)||r.set(i,{environmentName:oAs(n.name),httpServers:[],websocketServers:[]}),r.get(i)?.websocketServers.push(n)}return r}function QOe(e){return Object.entries(e).reduce((t,[r,n])=>(WF(n)?Object.entries(n.urls).forEach(([i,o])=>{t[i]=o}):t[r]=typeof n=="string"?n:n.url,t),{})}function aAs(e){if(e.environmentOverrides!=null){for(let[E,I]of Object.entries(e.environmentOverrides.environments??{}))e.builder.addEnvironment({name:E,schema:I});e.environmentOverrides["default-environment"]!=null&&e.builder.setDefaultEnvironment(e.environmentOverrides["default-environment"]),e.environmentOverrides["default-url"]!=null&&e.builder.setDefaultUrl(e.environmentOverrides["default-url"]);return}let t={},r=[],n=e.ir.servers.some(E=>xli(E)),i=e.ir.servers;for(let E of i)if(xli(E)){let I={urls:{}},w={},x={},C={};for(let[D,z]of Object.entries(E.urls))I.urls[D]=z.defaultUrl??z.url,z.urlTemplate&&(w[D]=z.urlTemplate),z.defaultUrl&&(x[D]=z.defaultUrl),z.variables&&z.variables.length>0&&(C[D]=z.variables);(Object.keys(w).length>0||Object.keys(C).length>0)&&(I["url-templates"]=w,I["default-urls"]=x,I.variables=C),E.name&&(t[E.name]=I)}else if("url"in E&&E.url){let w=E.urlTemplate!=null&&E.variables!=null&&E.variables.length>0?{url:E.url,audiences:E.audiences,"default-url":E.defaultUrl,"url-template":E.urlTemplate,variables:E.variables?.map(x=>({id:x.id,default:x.default,values:x.values}))}:E.audiences?{url:E.url,audiences:E.audiences}:E.url;if(E.name==null){r.push(w);continue}t[E.name]=w}let o={},s={},a=[],c={},u={},l={};for(let E of e.ir.endpoints)for(let I of E.servers){if(I.url==null&&I.name!=null){o[I.name]||(o[I.name]=[]);continue}if(I.url==null)continue;let w=I,x="defaultUrl"in I&&typeof w.defaultUrl=="string"?w.defaultUrl:void 0,C="urlTemplate"in I&&typeof w.urlTemplate=="string"?w.urlTemplate:void 0,_="variables"in I&&Array.isArray(w.variables)?w.variables:void 0,D=x??I.url,z=I.audiences?{url:D,audiences:I.audiences}:D;if(I.name==null){a.push(z);continue}o[I.name]||(o[I.name]=[]),o[I.name]?.push({url:D,audiences:I.audiences}),s[I.name]=z,C&&I.name&&(c[I.name]=C),x&&I.name&&(u[I.name]=x),_&&_.length>0&&I.name&&(l[I.name]=_)}let p={},d=[];for(let E of e.ir.websocketServers){e.logger.debug(`[buildEnvironments] Processing WebSocket server: name="${E.name}", url="${E.url}"`);let I=E.audiences?{url:E.url,audiences:E.audiences}:E.url;if(E.name==null){d.push(I);continue}p[E.name]=I}let f=Object.keys(t).length,m=f>0,h=Object.keys(s).length>0,g=Object.keys(o).some(E=>o[E]?.length===0),A=Object.keys(p).length>0;if(e.options.groupEnvironmentsByHost&&A&&(m||e.ir.servers.length>0)){let E=Object.entries(p).map(([w,x])=>({name:w,url:typeof x=="string"?x:x.url,audiences:typeof x=="string"?void 0:x.audiences})),I=myl(i,E);if(I.size>0){let w=!0;for(let[x,C]of I.entries()){let _={},D=[...C.httpServers.map(q=>({...q,isHttp:!0})),...C.websocketServers.map(q=>({...q,isHttp:!1}))],z=new Map;for(let q of D){let U=tIt(q.url),$=Rar(q.url);U&&$&&(z.has(U)||z.set(U,new Set),z.get(U)?.add($))}if(C.httpServers.length>0){let q=C.httpServers[0];q!=null&&(_[CI]=q.url,e.setUrlId(q.url,CI));for(let U=1;U<C.httpServers.length;U++){let $=C.httpServers[U];if($!=null){let re=tIt($.url),V=Rar($.url),W=re?z.get(re):void 0,ge=W&&W.size>1,K=ge&&V!=="https"?`${re}_${V}`:re||`Http${U+1}`;e.logger.debug(`[buildEnvironments] HTTP server: url="${$.url}", pathSegment="${re}", protocol="${V}", hasCollision=${ge}, urlId="${K}"`),_[K]=$.url,e.setUrlId($.url,K)}}}for(let q of C.websocketServers){let U=tIt(q.url),$=Rar(q.url),re=U?z.get(U):void 0,V=re&&re.size>1,W=V?`${U}_${$}`:Far(q.name,q.url,!0);e.logger.debug(`[buildEnvironments] WebSocket server: name="${q.name}", url="${q.url}", pathSegment="${U}", protocol="${$}", hasCollision=${V}, urlId="${W}"`),_[W]=q.url,e.setUrlId(q.url,W)}if(Object.keys(_).length>1)e.builder.addEnvironment({name:C.environmentName,schema:{urls:_}});else if(Object.keys(_).length===1){let q=Object.values(_)[0];q!=null&&e.builder.addEnvironment({name:C.environmentName,schema:q})}w&&(e.options.inferDefaultEnvironment!==!1&&e.builder.setDefaultEnvironment(C.environmentName),Object.keys(_).length>1&&e.builder.setDefaultUrl(CI),w=!1)}return}}if(!m&&!h&&A&&e.ir.servers.length===0){for(let[E,I]of Object.entries(p))e.builder.addEnvironment({name:E,schema:I});e.options.inferDefaultEnvironment!==!1&&e.builder.setDefaultEnvironment(Object.keys(p)[0]),e.builder.setDefaultUrl(CI);return}if(a.length>0&&e.logger.debug(`Skipping endpoint level servers ${a.map(E=>typeof E=="string"?E:E.url).join(", ")} because x-fern-server-name was not provided.`),!m){let E=e.ir.servers[0],I=E?.url,w=E?.audiences,x=E?.defaultUrl,C=E?.urlTemplate,_=E?.variables;if(I!=null){let z=C!=null&&_!=null&&_.length>0?{url:I,audiences:w,"default-url":x,"url-template":C,variables:_?.map(q=>({id:q.id,default:q.default,values:q.values}))}:w?{url:I,audiences:w}:I;t[sAs]=z}}let b=Object.values(t).map(E=>typeof E=="string"?E:WF(E)?Object.values(E.urls)[0]:E.url),v=r.filter(E=>{let I=typeof E=="string"?E:E.url;return!b.includes(I)});if(v.length>0&&e.logger.debug(`Skipping top level servers ${v.map(E=>typeof E=="string"?E:E.url).join(", ")} because x-fern-server-name was not provided.`),n){let E=!0;for(let[I,w]of Object.entries(t))if(e.builder.addEnvironment({name:I,schema:w}),E){if(e.options.inferDefaultEnvironment!==!1&&e.builder.setDefaultEnvironment(I),WF(w)){let x=Object.keys(w.urls)[0];x&&e.builder.setDefaultUrl(x)}E=!1}return}if(!h&&!g){let E=!0;for(let[I,w]of Object.entries(t))if(E){if(A){let x=typeof w=="string"?w:WF(w)?Object.values(w.urls)[0]:w["default-url"]??w.url;x!=null&&e.setUrlId(x,CI),e.builder.addEnvironment({name:I,schema:{urls:{[CI]:x??"",...QOe(p)}}})}else e.builder.addEnvironment({name:I,schema:w});e.options.inferDefaultEnvironment!==!1&&e.builder.setDefaultEnvironment(I),E=!1}else if(A){let x=typeof w=="string"?w:WF(w)?Object.values(w.urls)[0]:w["default-url"]??w.url;x!=null&&e.setUrlId(x,CI),e.builder.addEnvironment({name:I,schema:{urls:{[CI]:x??"",...QOe(p)}}})}else e.builder.addEnvironment({name:I,schema:w});A&&e.builder.setDefaultUrl(CI)}else if(f===1){let E=Object.keys(t)[0],I=Object.values(t)[0],w=typeof I=="string"?I:WF(I)?Object.values(I.urls)[0]:I["default-url"]??I.url,x={},C={},_={};typeof I!="string"&&!WF(I)&&(I["url-template"]&&(x[CI]=I["url-template"]),I["default-url"]&&(C[CI]=I["default-url"]),I.variables&&I.variables.length>0&&(_[CI]=I.variables)),Object.assign(x,c),Object.assign(C,u),Object.assign(_,l);let D=Object.keys(x).length>0||Object.keys(_).length>0;w!=null&&e.setUrlId(w,CI);let z={urls:{[CI]:w??"",...QOe(s),...QOe(p)},...D?{"url-templates":x,"default-urls":C,variables:_}:{}};e.builder.addEnvironment({name:E,schema:z}),e.options.inferDefaultEnvironment!==!1&&e.builder.setDefaultEnvironment(E),e.builder.setDefaultUrl(CI)}else{let E=new Map;for(let I of e.ir.endpoints)for(let w of I.servers)if(w.url!=null&&w.name!=null){E.has(w.name)||E.set(w.name,new Map);let x=w.url.match(/[-]([a-z0-9]+)\./i)?.[1]?.toLowerCase()||"production",C=E.get(w.name);C&&C.set(x,w.url)}if(E.size>0){let I=!0;for(let[w,x]of Object.entries(t)){let C=typeof x=="string"?x:WF(x)?Object.values(x.urls)[0]:x["default-url"]??x.url;if(!C)continue;e.setUrlId(C,CI);let _=C.match(/[-]([a-z0-9]+)\./i)?.[1]?.toLowerCase()||"production",D={[CI]:C};for(let[z,q]of E.entries()){let U=q.get(_)||q.get("production")||q.values().next().value;U&&(D[z]=U)}A&&Object.assign(D,QOe(p)),Object.keys(D).length>1?e.builder.addEnvironment({name:w,schema:{urls:D}}):e.builder.addEnvironment({name:w,schema:C}),I&&(e.options.inferDefaultEnvironment!==!1&&e.builder.setDefaultEnvironment(w),I=!1)}E.size>0&&e.builder.setDefaultUrl(CI)}else{let I=!0;for(let[w,x]of Object.entries(t)){if(A||Object.keys(s).length>0){let C=typeof x=="string"?x:WF(x)?Object.values(x.urls)[0]:x["default-url"]??x.url;C!=null&&e.setUrlId(C,CI),e.builder.addEnvironment({name:w,schema:{urls:{[CI]:C??"",...QOe(s),...QOe(p)}}})}else e.builder.addEnvironment({name:w,schema:x});I&&(e.options.inferDefaultEnvironment!==!1&&e.builder.setDefaultEnvironment(w),I=!1)}}}}sA();Bi();var _li=class{schema;count=0;constructor(t){this.schema=t}increment(){this.count+=1}},hyl=.75,gyl=new Set(["authorization"]);function cAs(e){if(e.globalHeaderOverrides!=null){for(let[r,n]of Object.entries(e.globalHeaderOverrides.headers??{}))e.builder.addGlobalHeader({name:r,schema:n});return}let t=Object.fromEntries((e.ir.globalHeaders??[]).map(r=>[r.header,r]));for(let[r,n]of Object.entries(t)){let o=n.optional===!0?"optional<string>":"string",s=o;if(n.name==null&&n.env==null&&typeof n.schema=="string")s=n.schema;else if(n!=null){let a=n.schema?qse(n.schema):void 0,c=a!=null?Wse(a):void 0,u=Qs.of("api.yml");s={name:n.name,env:n.env,type:n.schema!=null?bp(pc({schema:n.schema,context:e,fileContainingReference:c?H0(Qs.of(Vn(c)),u):u,namespace:c,declarationDepth:0}))??o:o}}e.builder.addGlobalHeader({name:r,schema:s})}if(e.options.detectGlobalHeaders){let r={};for(let i of e.ir.endpoints)for(let o of i.headers){if(gyl.has(o.name.toLowerCase()))continue;let s=r[o.name];if(s==null){let a=t[o.name],c=S$({header:{...o,schema:a?.schema??o.schema,name:a?.name??o.name},fileContainingReference:Qs.of(Y0),context:e,namespace:void 0});s=new _li(c),r[o.name]=s}s.increment()}let n=e.ir.endpoints.length*hyl;for(let[i,o]of Object.entries(r)){let s=t[i],a=o.count===e.ir.endpoints.length,c=o.count>=n;s==null&&(a?e.builder.addGlobalHeader({name:i,schema:o.schema}):c&&e.builder.addGlobalHeader({name:i,schema:kOe(o.schema)}))}}}sA();function uAs(e){for(let t of e.ir.idempotencyHeaders??[]){let r=t.schema?qse(t.schema):void 0,n=r!=null?Wse(r):void 0,i=S$({header:{...t,schema:t.schema??ba.primitive({description:void 0,availability:void 0,generatedName:"",title:void 0,namespace:void 0,groupName:void 0,nameOverride:void 0,schema:ol.string({default:void 0,pattern:void 0,format:void 0,minLength:void 0,maxLength:void 0})}),name:t.name??t.header,parameterNameOverride:void 0,description:void 0,availability:void 0,source:void 0},fileContainingReference:Qs.of(Y0),context:e,namespace:n});e.builder.addIdempotencyHeader({name:t.header,schema:kOe(i)})}}St();sA();St();St();function pT(e){switch(e.type){case"primitive":return pAs(e.value);case"object":return fAs(e.properties);case"array":return dAs(e.value);case"map":return yyl(e.value);case"oneOf":return byl(e.value);case"enum":return typeof e.value=="string"&&e.value.startsWith("$")?`\\${e.value}`:e.value;case"literal":return Eyl(e.value);case"unknown":return pT(e.value);case"null":return null;default:Be(e)}}function lAs(e){switch(e.type){case"withStreaming":return e.sse?{stream:Ayl(e.events)}:{stream:dAs(e.events)};case"withoutStreaming":return{body:pT(e.value)};default:Be(e)}}function pAs(e){switch(e.type){case"int":return e.value;case"int64":return e.value;case"uint":return e.value;case"uint64":return e.value;case"float":return e.value;case"double":return e.value;case"string":return e.value.startsWith("$")?`\\${e.value}`:e.value;case"datetime":try{return!e.value.endsWith("Z")&&!e.value.includes("+")&&(e.value+="Z"),new Date(e.value).toISOString().replace(/\.\d{3}Z$/,"Z")}catch{return"2024-01-15T09:30:00Z"}case"datetimeRfc2822":return e.value;case"date":return e.value;case"base64":case"boolean":return e.value;default:Be(e)}}function fAs(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,pT(r)]))}function Ayl(e){return e.map(t=>({event:"",data:pT(t)}))}function dAs(e){return e.map(t=>pT(t))}function yyl(e){return Object.fromEntries(e.map(t=>[pAs(t.key),pT(t.value)]))}function byl(e){return e.type==="discriminated"?fAs(e.value):pT(e.value)}function Eyl(e){switch(e.type){case"string":return e.value.startsWith("$")?`\\${e.value}`:e.value;case"boolean":return e.value;default:Be(e)}}function mAs({endpointExample:e,context:t}){let r={};if(e.type!=="full")return e.value;e.name!=null&&(r.name=e.name),e.description!=null&&(r.docs=e.description),e.pathParameters!=null&&e.pathParameters.length>0&&(r["path-parameters"]=vyl(e.pathParameters)),e.queryParameters!=null&&e.queryParameters.length>0&&(r["query-parameters"]=Iyl(e.queryParameters));let n=e.headers!=null&&e.headers.length>0,i=t.builder.getGlobalHeaders(),o=Object.keys(i).length>0,s=new Set(e.headers?.map(a=>a.name)??[]);if(n||o){let a=[];if(e.headers!=null)for(let c of e.headers)c.name!==t.builder.getAuthHeaderName()&&a.push(c);for(let[c,u]of Object.entries(i)){if(u!=null&&typeof u=="object"&&u.type!=null){let l=$E({type:u.type,_default:void 0,validation:void 0,visitor:{primitive:pt,map:pt,list:pt,optional:p=>p,nullable:p=>p,set:pt,named:pt,literal:p=>{if(p.type==="string")return p.string;if(p.type==="boolean")return p.boolean.toString()},unknown:pt}});if(l!=null){let p=a.findIndex(f=>f.name===c),d={name:c,value:lc.literal(Che.string(l))};p>=0?a[p]=d:a.push(d);continue}}s.has(c)||a.push({name:c,value:lc.primitive(hs.string(c))})}r.headers=wyl({context:t,namedFullExamples:a})}return e.request!=null&&(r.request=pT(e.request)),e.response!=null&&(r.response=lAs(e.response)),e.codeSamples!=null&&e.codeSamples.length>0&&(r["code-samples"]=e.codeSamples.map(a=>a.type==="language"?{name:a.name??void 0,docs:a.description??void 0,language:a.language,code:a.code,install:a.install??void 0}:{name:a.name??void 0,docs:a.description??void 0,sdk:a.sdk,code:a.code}).filter(ya)),r}function vyl(e){let t={};return e.forEach(r=>{let n=pT(r.value);n!=null&&(t[r.parameterNameOverride??r.name]=n)}),t}function Iyl(e){let t={};return e.forEach(r=>{let n=pT(r.value);Array.isArray(n)?t[r.name]=n[0]:n!=null&&(t[r.name]=n)}),t}function wyl({context:e,namedFullExamples:t}){let r={};return t.forEach(n=>{let i=pT(n.value);i!=null&&(r[n.name]=i)}),r}var ZS;(function(e){e[e.Channel=0]="Channel",e[e.Endpoint=1]="Endpoint",e[e.Request=2]="Request",e[e.Webhook=3]="Webhook"})(ZS||(ZS={}));function hAs(e){return Cx._visit(e,{get:()=>Sm.HttpMethodSchema.Get,post:()=>Sm.HttpMethodSchema.Post,put:()=>Sm.HttpMethodSchema.Put,patch:()=>Sm.HttpMethodSchema.Patch,delete:()=>Sm.HttpMethodSchema.Delete,head:()=>Sm.HttpMethodSchema.Head,options:()=>{throw new Error("OPTIONS is unsupported")},trace:()=>{throw new Error("TRACE is unsupported")},_other:()=>{throw new Error("Unknown http method is unsupported")}})}function Sli(e){return e==="POST"||e==="PUT"||e==="PATCH"}function gAs({endpoint:e,declarationFile:t,context:r}){let n=[],i=new Set,o=e.path,s=kar(e.sdkName,e.namespace),a={};for(let h of e.pathParameters)h.parameterNameOverride&&(o=o.replace(h.name,h.parameterNameOverride)),a[h.parameterNameOverride??h.name]=Oar({pathParameter:h,context:r,fileContainingReference:t,namespace:s}),i.add(h.name);let c={};for(let h of e.queryParameters){let g=Dar({queryParameter:h,context:r,fileContainingReference:t,namespace:s});g!=null&&(c[h.name]=g,i.add(h.name))}let u;if(e.pagination!=null)switch(e.pagination.type){case"cursor":u={cursor:e.pagination.cursor,next_cursor:e.pagination.nextCursor,results:e.pagination.results};break;case"offset":u={offset:e.pagination.offset,step:e.pagination.step,results:e.pagination.results,"has-next-page":e.pagination.hasNextPage};break;case"custom":u={type:"custom",results:e.pagination.results};break;case"uri":u={next_uri:e.pagination.nextUri,results:e.pagination.results};break;case"path":u={next_path:e.pagination.nextPath,results:e.pagination.results};break;default:Be(e.pagination)}let l={path:o,method:hAs(e.method),auth:Cyl({endpoint:e,context:r}),docs:e.description??void 0,pagination:u,source:e.source!=null?Gse(e.source):void 0};!Byl({context:r,request:e.request})&&Object.keys(a).length>0&&(l["path-parameters"]=a),e.summary!=null&&(l["display-name"]=e.summary);let p={},d=r.builder.getGlobalHeaderNames(),f=r.builder.getAuthHeaderName();f!=null&&d.add(f);let m=e.headers.filter(h=>!d.has(h.name));for(let h of m){let g=S$({header:h,context:r,fileContainingReference:t,namespace:s});p[h.name]=g,i.add(typeof g=="string"?h.name:g.name??h.name)}if(e.request!=null){r.setInState(ZS.Request);let h=Syl({endpoint:e,context:r,declarationFile:t,request:e.request,generatedRequestName:e.generatedRequestName,requestNameOverride:e.requestNameOverride??void 0,pathParameters:r.options.inlinePathParameters&&Object.keys(a).length>0?a:void 0,queryParameters:Object.keys(c).length>0?c:void 0,headers:Object.keys(p).length>0?p:void 0,usedNames:i,namespace:s});l.request=h.value,n=[...n,...h.schemaIdsToExclude??[]],r.unsetInState(ZS.Request)}else{let h=r.options.inlinePathParameters&&Object.keys(a).length>0,g=Object.keys(c).length>0,A=Object.keys(p).length>0,b={};(h||g||A)&&(b.name=e.requestNameOverride??e.generatedRequestName),h&&(b["path-parameters"]=a),g&&(b["query-parameters"]=c),A&&(b.headers=p),Object.keys(b).length>0&&(l.request=b)}if(e.response!=null&&e.response._visit({json:h=>{let g=pc({schema:h.schema,context:r,fileContainingReference:t,namespace:s,declarationDepth:0});l.response={docs:h.description??void 0,type:bp(g)},h.statusCode!=null&&(l.response["status-code"]=h.statusCode),h.responseProperty!=null&&(l.response.property=h.responseProperty)},streamingJson:h=>{let g=pc({schema:h.schema,context:r,fileContainingReference:t,namespace:s,declarationDepth:0});l["response-stream"]={docs:h.description??void 0,type:bp(g),format:"json",terminator:h.terminator??void 0}},streamingSse:h=>{let g=pc({schema:h.schema,context:r,fileContainingReference:t,namespace:s,declarationDepth:0});l["response-stream"]={docs:h.description??void 0,type:bp(g),format:"sse",terminator:h.terminator??void 0}},file:h=>{l.response={docs:h.description??void 0,type:"file","status-code":h.statusCode}},bytes:h=>{l.response={docs:h.description??void 0,type:"bytes","status-code":h.statusCode}},streamingText:h=>{l["response-stream"]={docs:h.description??void 0,type:"text"}},text:h=>{l.response={docs:h.description??void 0,type:"text","status-code":h.statusCode}},_other:()=>{throw new Error("Unrecognized Response type: "+e.response?.type)}}),r.builder.getEnvironmentType()==="multi"){let h=r.getDefaultServerName(),g=e.servers[0];if(g==null)h!=null&&(l.url=h);else{let A=g.url!=null?r.getUrlId(g.url):void 0;l.url=A??g.name??void 0}}return e.idempotent&&(l.idempotent=!0),e.availability!=null&&(l.availability=ab(e.availability)),Object.entries(e.errors).forEach(([h,g])=>{let A=g.generatedName,b=Qs.of(tf);r.builder.enableUniqueErrorsPerEndpoint&&(A=`${e.generatedRequestName}${g.generatedName}`,g.schema!=null&&(g.schema.type!=="reference"&&g.schema.type!=="oneOf"?g.schema.generatedName=`${e.generatedRequestName}${g.schema.generatedName}`:g.schema.type==="oneOf"&&(g.schema.value.generatedName=`${e.generatedRequestName}${g.schema.value.generatedName}`)));let v={"status-code":parseInt(h)},E=zgs({location:AAs,namespaceOverride:s});if(g.schema!=null){let x=pc({schema:g.schema,context:r,fileContainingReference:E,declarationFile:E,namespace:s,declarationDepth:0});v.type=bp(x),v.docs=g.description}r.builder.addError(E,{name:A,schema:r.isErrorUnknownSchema(parseInt(h))?{...v,type:"unknown"}:v}),l.errors==null&&(l.errors=[]);let I=r.builder.addImport({file:t,fileToImport:E});l.errors.push(I!=null?`${I}.${A}`:A),v.type!=null&&g.examples?.forEach(x=>{let C={value:pT(x.example),name:x.name,docs:x.description};r.builder.addErrorExample(E,{name:A,example:C})})}),e.examples.length>0&&(l.examples=xyl({endpointExamples:e.examples,context:r})),e.retries!=null&&(l.retries=_yl({retries:e.retries})),r.ir.hasEndpointsMarkedInternal&&(e.internal==null||!e.internal)?l.audiences=[Bli,...e.audiences]:e.audiences.length>0&&(l.audiences=e.audiences),{value:l,schemaIdsToExclude:n}}function Cyl({endpoint:e,context:t}){return e.security==null?t.authOverrides?.auth!=null?!0:t.ir.security==null?void 0:t.ir.security.length>0?!0:void 0:e.security.length===0?!1:JSON.stringify(e.security)===JSON.stringify(t.ir.security)?!0:e.security}function xyl({endpointExamples:e,context:t}){return e.map(r=>{try{return mAs({endpointExample:r,context:t})}catch(n){throw console.error(`Error building endpoint example: ${n}`),n}})}function _yl({retries:e}){if(e!=null){if(e.type==="disabled")return{disabled:e.value??void 0};Be(e)}}function Syl({endpoint:e,declarationFile:t,context:r,request:n,requestNameOverride:i,generatedRequestName:o,pathParameters:s,queryParameters:a,headers:c,usedNames:u,namespace:l}){if(n.type==="json"||n.type==="formUrlEncoded"){let p=n.schema.type==="reference"?n.schema.schema:void 0,d=n.schema.type==="reference"?r.getSchema(n.schema.schema,l):n.schema;if(d?.type!=="object"||p!=null&&r.isResponseReachable(p)){let I=r.options.respectReadonlySchemas&&Sli(e.method)?"write":void 0,w=pc({schema:n.schema,fileContainingReference:t,context:r,namespace:l,declarationDepth:0,variant:I}),x={schemaIdsToExclude:[],value:{body:w}},C=Object.keys(s??{}).length>0,_=Object.keys(a??{}).length>0,D=Object.keys(c??{}).length>0;return C&&(x.value["path-parameters"]=s),_&&(x.value["query-parameters"]=a),D&&(x.value.headers=c),(C||_||D)&&(x.value.name=i??o),n.contentType!=null&&(x.value["content-type"]=n.contentType),n.description!=null&&(x.value.docs=n.description),x}let f=new Map;for(let E of d.allOf){let I=r.getSchema(E.schema,l);if(I==null)continue;let w=qse(I),x=Vse(w),{properties:C}=U6e(r,E.schema,l);for(let _ of C)f.set(_.key,x)}let m=Object.fromEntries(d.properties.filter(E=>E.readonly==null?!0:!(Sli(e.method)&&E.readonly)).map(E=>{let I=f.get(E.key)??t,w=pc({schema:E.schema,fileContainingReference:t,declarationFile:I,context:r,namespace:l,declarationDepth:1}),x=E.nameOverride??E.key,C=ab(E.availability);if(!u.has(x)&&E.audiences.length<=0)return u.add(x),E.nameOverride!=null?[E.key,{type:bp(w),docs:M6e(w),name:E.nameOverride,availability:C}]:[E.key,C?{...typeof w=="string"?{type:w}:w,availability:C}:w];let _={type:bp(w),docs:M6e(w)};return u.has(x)&&(_.name=E.generatedName),E.audiences.length>0&&(_.audiences=E.audiences),C!=null&&(_.availability=C),u.add(x),[E.key,_]})),h=new Set,g=new Set;for(let E of d.allOfPropertyConflicts)E.allOfSchemaIds.forEach(I=>h.add(I)),E.conflictingTypeSignatures&&g.add(E.propertyKey);let A=[];for(let E of d.allOf){let I=Tar({schema:E.schema,context:r,namespace:l});if(I==null||h.has(E.schema)||h.has(I))continue;let w=pc({schema:ba.reference(E),fileContainingReference:t,context:r,namespace:l,declarationDepth:0}),x=L6e(bp(w));x!=="unknown"&&A.push(x)}for(let E of h){let I=U6e(r,E,l),w=r.getSchema(E,l),x=w!=null?Vse(qse(w)):t;for(let C of I.properties)m[C.key]==null&&(g.has(C.key)?m[C.key]="unknown":m[C.key]=pc({schema:C.schema,fileContainingReference:t,declarationFile:x,context:r,namespace:l,declarationDepth:1}));for(let C of I.allOf){if(h.has(C.schema))continue;let _=pc({schema:ba.reference(C),fileContainingReference:t,context:r,namespace:l,declarationDepth:0}),D=L6e(bp(_));D!=="unknown"&&!A.includes(D)&&A.push(D)}}let b={properties:m};A.length>0&&(b.extends=A),n.additionalProperties&&(b["extra-properties"]=!0);let v={name:i??d.nameOverride??d.generatedName,"path-parameters":s,"query-parameters":a,headers:c,body:b};return n.contentType!=null&&(v["content-type"]=n.contentType),n.description!=null&&(v.docs=n.description),{schemaIdsToExclude:p!=null?[p]:[],value:v}}else if(n.type==="octetStream"){let p={body:"bytes","content-type":n.contentType??vf.APPLICATION_OCTET_STREAM,"query-parameters":a};return a!=null&&(p.name=i??o),n.description!=null&&(p.docs=n.description),{schemaIdsToExclude:[],value:p}}else if(n.type==="multipart"){let p=Object.fromEntries(n.properties.map(d=>{if(d.schema.type==="file"){let f=d.schema.isArray?"list<file>":"file";if(f=d.schema.isOptional?`optional<${f}>`:f,d.description!=null||d.contentType!=null){let m={type:f};if(d.description!=null&&(m.docs=d.description),d.contentType!=null){let h=d.contentType.split(",")[0];m["content-type"]=h}return[d.key,m]}return[d.key,f]}else{let f=pc({schema:d.schema.value,fileContainingReference:t,context:r,namespace:l,declarationDepth:1});if(d.contentType||d.exploded||d.encoding){let m=typeof f=="string"?{type:f}:f;d.contentType!=null&&(m["content-type"]=d.contentType),d.encoding==="form"?m.style="form":d.encoding==="json"?m.style="json":d.exploded&&(m.style="exploded"),f=m}return[d.key,f]}}));return{schemaIdsToExclude:n.name==null?[]:[n.name],value:{name:i??n.name??o,"path-parameters":s,"query-parameters":a,headers:c,body:{properties:p},"content-type":vf.MULTIPART_FORM_DATA,...n.description?{docs:n.description}:{}}}}else Be(n)}function Byl({context:e,request:t}){if(!e.options.inlinePathParameters)return!1;if(t==null)return!0;switch(t.type){case"octetStream":return!1;case"multipart":return!0;case"json":return!0;case"formUrlEncoded":return!0;default:Be(t)}}sA();Bi();function Tyl({location:e,namespaceOverride:t}){return t!=null?{...e,file:H0(Qs.of(t),e.file)}:e}function Oyl(e){let t=e.namespace,r=e.tags.filter(c=>c!==t)[0],n=e.operationId;if(n==null)return r!=null?{file:Qs.of(`${Vn(r)}.yml`),endpointId:e.summary!=null?Vn(e.summary):Vn(`${e.method}_${e.path.split("/").join("_")}`)}:e.summary!=null?{file:Qs.of(tf),endpointId:Vn(e.summary)}:{file:Qs.of(tf),endpointId:Vn(`${e.method}_${e.path.split("/").join("_")}`)};if(r==null)return{file:Qs.of(tf),endpointId:n};let i=rIt(r),o=rIt(n);if($0(i,o))return{file:Qs.of("__package__.yml"),endpointId:r};let s=Ryl({operationId:n,tag:r,path:e.path,method:e.method});if(s!=null)return s;let a=[];for(let c=0;c<i.length;++c){let u=i[c];if(u!=null&&u===o[c])a.push(u);else{let l=Vn(r);return{file:Qs.of(`${l}.yml`),endpointId:n,tag:r}}}if(a.length>=o.length)throw new Error(`Cannot get file for endpoint ${JSON.stringify(e)}`);return{file:Qs.of(Vn(a.join("_"))+".yml"),endpointId:Vn(o.slice(a.length).join("_")),tag:r}}function nIt(e){let t=e.tags[0];if(e.sdkName!=null){let r=fli({sdkName:e.sdkName,namespaceOverride:e.namespace}),n=`${r}.yml`,i=r.toLowerCase()===t?.toLowerCase().replaceAll(" ","");return{file:Qs.of(n),endpointId:e.sdkName.methodName,tag:i?t:void 0}}return Tyl({namespaceOverride:e.namespace,location:Oyl(e)})}function rIt(e){let t;return/^[a-z]+(?:[A-Z][a-z]+)*$/.test(e)?t=e.split(/(?=[A-Z])/):t=e.split(/[^a-zA-Z0-9]+/),t=t.map(r=>r.toLowerCase()),t=sU(t),t}var Pyl=new RegExp("[^a-zA-Z0-9{}]+"),Dyl=new RegExp("[{}]","g");function Ryl({operationId:e,tag:t,path:r,method:n}){let o=`${r.split(Pyl).join("_").replaceAll(Dyl,"_")}_${n.toLowerCase()}`;if(e.endsWith(o))return{file:Qs.of(Vn(t)+".yml"),endpointId:Vn(e.slice(0,-1*o.length)),tag:t}}function yAs(e){let t=new Set,{endpoints:r,tags:n}=e.ir,i=[];for(let o of r){let{endpointId:s,file:a,tag:c}=nIt(o),u=a.split(".")[0];u!=null&&t.add(u);let l;if(o.sdkName!=null){let f=e.ir.groups;for(let m of o.sdkName.groupName){let h=typeof m=="string"?m:m.name,g=f[h];if(g==null)break;if(g.summary!=null||g.description!=null){l=f[h];break}}}let p=c==null?void 0:n.tagsById[c];e.setInState(ZS.Endpoint),e.setEndpointMethod(o.method);let d=gAs({context:e,endpoint:o,declarationFile:a});e.unsetEndpointMethod(),e.unsetInState(ZS.Endpoint),i=[...i,...d.schemaIdsToExclude],e.builder.addEndpoint(a,{name:s,schema:d.value,source:o.source!=null?Gse(o.source):void 0}),(p?.id!=null||p?.description!=null)&&e.builder.setServiceInfo(a,{"display-name":l?.summary??p?.id,docs:l?.description??p?.description??void 0})}return{schemaIdsToExclude:i,sdkGroups:t}}sA();function bAs(e){for(let[t,r]of Object.entries(e.ir.variables)){let n=r.groupName!=null?Wse(r.groupName):void 0,i=pc({schema:ba.primitive(r),context:e,fileContainingReference:Qs.of(tf),namespace:n,declarationDepth:0});e.builder.addVariable({name:t,schema:{type:bp(i),docs:r.description??void 0}})}}sA();Bi();function IAs(e){for(let t of e.ir.webhooks){let r=Nyl({webhook:t,context:e});if(r==null)continue;let n=kar(t.sdkName,t.namespace),i={};for(let s of t.headers)i[s.name]=S$({header:s,context:e,fileContainingReference:r.file,namespace:n});let o={audiences:t.audiences,method:t.method,"display-name":t.summary??void 0,headers:i,payload:pc({schema:t.payload,context:e,fileContainingReference:r.file,namespace:n,declarationDepth:0}),signature:Qyl(t.signatureVerification),examples:t.examples!=null?t.examples.map(s=>({docs:s.description,name:s.name,payload:pT(s.payload)})):void 0};t.response!=null&&t.response._visit({json:s=>{let a=pc({schema:s.schema,context:e,fileContainingReference:r.file,namespace:n,declarationDepth:0});o.response={docs:s.description??void 0,type:bp(a)},s.statusCode!=null&&(o.response["status-code"]=s.statusCode)},file:s=>{o.response={docs:s.description??void 0,type:"file","status-code":s.statusCode}},bytes:s=>{o.response={docs:s.description??void 0,type:"bytes","status-code":s.statusCode}},text:s=>{o.response={docs:s.description??void 0,type:"text","status-code":s.statusCode}},streamingJson:s=>{let a=pc({schema:s.schema,context:e,fileContainingReference:r.file,namespace:n,declarationDepth:0});o["response-stream"]={docs:s.description??void 0,type:bp(a),format:"json"}},streamingSse:s=>{let a=pc({schema:s.schema,context:e,fileContainingReference:r.file,namespace:n,declarationDepth:0});o["response-stream"]={docs:s.description??void 0,type:bp(a),format:"sse"}},streamingText:s=>{o["response-stream"]={docs:s.description??void 0,type:"text"}},_other:()=>{throw new Error("Unrecognized Response type: "+t.response?.type)}}),e.builder.addWebhook(r.file,{name:r.endpointId,schema:o}),t.description!=null&&(o.docs=t.description)}}function Fyl({location:e,namespaceOverride:t}){if(e!=null)return t!=null?{...e,file:H0(Qs.of(t),e.file)}:e}function kyl({webhook:e,context:t}){let r=e.tags[0],n=e.operationId;if(r==null)return{file:Qs.of(tf),endpointId:n};let i=rIt(r),o=rIt(n);if($0(i,o))return{file:Qs.of("__package__.yml"),endpointId:r};let s=[];for(let a=0;a<i.length;++a){let c=i[a];if(c!=null&&c===o[a])s.push(c);else{let u=Vn(r);return{file:Qs.of(`${u}.yml`),endpointId:n,tag:r}}}if(s.length>=o.length){t.logger.warn(`Skipping webhook ${e.operationId} because couldn't compute file location`);return}return{file:Qs.of(Vn(s.join("_"))+".yml"),endpointId:Vn(o.slice(s.length).join("_")),tag:r}}function Nyl({webhook:e,context:t}){return e.sdkName!=null?{file:Ugs({sdkName:e.sdkName,namespaceOverride:e.namespace}),endpointId:e.sdkName.methodName}:Fyl({namespaceOverride:e.namespace,location:kyl({webhook:e,context:t})})}function Qyl(e){if(e!=null)switch(e.type){case"hmac":return{type:"hmac",header:e.header,algorithm:jyl(e.algorithm),encoding:EAs(e.encoding),"signature-prefix":e.signaturePrefix,"payload-format":Lyl(e.payloadFormat),timestamp:vAs(e.timestamp)};case"asymmetric":return{type:"asymmetric",header:e.header,"asymmetric-algorithm":Myl(e.asymmetricAlgorithm),encoding:EAs(e.encoding),"signature-prefix":e.signaturePrefix,"jwks-url":e.jwksUrl,"key-id-header":e.keyIdHeader,timestamp:vAs(e.timestamp)};default:return}}function jyl(e){if(e!=null)switch(e){case"sha256":return"sha256";case"sha1":return"sha1";case"sha384":return"sha384";case"sha512":return"sha512";default:return}}function EAs(e){if(e!=null)switch(e){case"base64":return"base64";case"hex":return"hex";default:return}}function Myl(e){switch(e){case"rsa-sha256":return"rsa-sha256";case"rsa-sha384":return"rsa-sha384";case"rsa-sha512":return"rsa-sha512";case"ecdsa-sha256":return"ecdsa-sha256";case"ecdsa-sha384":return"ecdsa-sha384";case"ecdsa-sha512":return"ecdsa-sha512";case"ed25519":return"ed25519";default:return"rsa-sha256"}}function Lyl(e){if(e!=null)return{components:e.components.map(Uyl),delimiter:e.delimiter}}function Uyl(e){switch(e){case"body":return"body";case"timestamp":return"timestamp";case"notification-url":return"notification-url";case"message-id":return"message-id";default:return"body"}}function zyl(e){switch(e){case"unix-seconds":return"unix-seconds";case"unix-millis":return"unix-millis";case"iso8601":return"iso8601";default:return}}function vAs(e){if(e!=null)return{header:e.header,format:e.format!=null?zyl(e.format):void 0,tolerance:e.tolerance}}St();function khe(e,t,r){switch(e.type){case"primitive":case"enum":case"literal":case"unknown":return;case"reference":{let n=e.schema;if(r.has(n))return;r.add(n);let i=wAs(n,e.namespace,t);i!=null&&khe(i,t,r);return}case"object":for(let n of e.allOf)if(!r.has(n.schema)){r.add(n.schema);let i=wAs(n.schema,n.namespace,t);i!=null&&khe(i,t,r)}for(let n of e.properties)khe(n.schema,t,r);return;case"array":case"map":case"optional":case"nullable":khe(e.value,t,r);return;case"oneOf":Vyl(e.value,t,r);return;default:Be(e)}}function Vyl(e,t,r){switch(e.type){case"discriminated":for(let n of Object.values(e.schemas))khe(n,t,r);for(let n of e.commonProperties)khe(n.schema,t,r);return;case"undiscriminated":for(let n of e.schemas)khe(n,t,r);return;default:Be(e)}}function wAs(e,t,r){return t==null?r.rootSchemas[e]:r.namespacedSchemas[t]?.[e]}function XU(e,t,r){khe(e,t,r)}function CAs(e){let t=new Set,r=new Set,{groupedSchemas:n}=e;for(let i of e.endpoints){if(i.request!=null)switch(i.request.type){case"json":case"formUrlEncoded":XU(i.request.schema,n,t);break;case"multipart":for(let o of i.request.properties)o.schema.type==="json"&&XU(o.schema.value,n,t);break;case"octetStream":break;default:Be(i.request)}if(i.response!=null)switch(i.response.type){case"json":case"streamingJson":case"streamingSse":XU(i.response.schema,n,r);break;case"file":case"text":case"bytes":case"streamingText":break;default:Be(i.response)}for(let o of Object.values(i.errors))o.schema!=null&&XU(o.schema,n,r);for(let o of i.pathParameters)XU(o.schema,n,r);for(let o of i.queryParameters)XU(o.schema,n,r);for(let o of i.headers)XU(o.schema,n,r)}for(let i of e.webhooks)XU(i.payload,n,r);for(let i of Object.values(e.channels)){for(let o of i.messages)XU(o.body,n,r);for(let o of i.handshake.queryParameters)XU(o.schema,n,r);for(let o of i.handshake.headers)XU(o.schema,n,r);for(let o of i.handshake.pathParameters)XU(o.schema,n,r)}return{requestReachable:t,responseReachable:r}}function qyl(e){return e.type!=="object"?!1:e.properties.some(t=>t.readonly===!0)}function xAs(e,t){let r=new Set,n=new Set,i=new Set;function o(s){for(let[a,c]of Object.entries(s)){if(!qyl(c))continue;let u=t.requestReachable.has(a),l=t.responseReachable.has(a);u&&l?r.add(a):u&&!l?n.add(a):!u&&l&&i.add(a)}}o(e.groupedSchemas.rootSchemas);for(let s of Object.values(e.groupedSchemas.namespacedSchemas))o(s);return{needsBothVariants:r,requestOnlyWithReadonly:n,responseOnlyWithReadonly:i}}var Bli="external",AAs=Qs.of(tf);function _As({schemas:e,schemaIdsToExclude:t,namespace:r,context:n}){for(let[i,o]of Object.entries(e)){if(t.has(i))continue;let s=Vgs(o);if(n.options.respectReadonlySchemas&&n.needsBothVariants(i)&&o.type==="object"){let u=NOe({schema:o,context:n,declarationFile:s,namespace:r,declarationDepth:0,variant:"read"});n.builder.addType(s,{name:u.name??i,schema:u.schema});let l=NOe({schema:o,context:n,declarationFile:s,namespace:r,declarationDepth:0,skipReadonlyProperties:!0,variant:"write"});n.builder.addType(s,{name:l.name??i,schema:l.schema});continue}if(n.options.respectReadonlySchemas&&n.isRequestOnlyWithReadonly(i)&&o.type==="object"){let u=NOe({schema:o,context:n,declarationFile:s,namespace:r,declarationDepth:0,skipReadonlyProperties:!0,variant:"write"});n.builder.addType(s,{name:u.name??i,schema:u.schema});continue}let a;n.options.respectReadonlySchemas&&(a=n.isRequestOnly(i)?"write":"read");let c=Kgs({schema:o,context:n,declarationFile:s,namespace:r,declarationDepth:0,variant:a});if($me(c.schema)){let u=bp(c.schema);if(u===(c.name??i)||u===`optional<${c.name??i}>`||u===`nullable<${c.name??i}>`||u===`optional<nullable<${c.name??i}>>`)continue}n.builder.addType(s,{name:c.name??i,schema:c.schema})}}function SAs(e){e.ir.apiVersion!=null&&e.builder.setApiVersion(e.ir.apiVersion),aAs(e),cAs(e),uAs(e),Zgs(e),bAs(e),e.ir.basePath!=null&&e.builder.setBasePath(e.ir.basePath),e.ir.hasEndpointsMarkedInternal&&e.builder.addAudience(Bli);let t=yAs(e),r=t.sdkGroups;e.setInState(ZS.Webhook),IAs(e),e.unsetInState(ZS.Webhook),e.setInState(ZS.Channel);for(let i of Object.values(e.ir.channels)){let o=Vse(i.groupName);nAs({channel:i,context:e,declarationFile:o})}e.unsetInState(ZS.Channel);let n=Gyl({context:e,schemaIdsToExcludeFromServices:t.schemaIdsToExclude});if(e.options.respectReadonlySchemas){let i=CAs(e.ir),o=xAs(e.ir,i);e.setVariantPlan(o,i)}_As({schemas:e.ir.groupedSchemas.rootSchemas,schemaIdsToExclude:n,namespace:void 0,context:e});for(let[i,o]of Object.entries(e.ir.groupedSchemas.namespacedSchemas))_As({schemas:o,schemaIdsToExclude:n,namespace:i,context:e});return e.ir.tags.orderedTagIds!=null&&e.ir.tags.orderedTagIds.length>0&&e.ir.tags.orderedTagIds.every(o=>r.has(o))&&e.builder.addNavigation({navigation:e.ir.tags.orderedTagIds}),e.builder.optimizeServiceAuth(),e.builder.build()}function Gyl({context:e,schemaIdsToExcludeFromServices:t}){let r=e.getReferencedSchemaIds();if(r==null)return new Set(t);let n=new Set([...Object.keys(e.ir.groupedSchemas.rootSchemas),...Object.values(e.ir.groupedSchemas.namespacedSchemas).flatMap(o=>Object.keys(o))]),i=new Set(t);for(let o of n)r.includes(o)||i.add(o);return i}St();var iIt=class{context;constructor(t){this.context=t}};sA();Bi();sA();var Nar=class e{files={};directories={};getAllFiles(){let t={},r=(n,i)=>{for(let[s,a]of Object.entries(n.files)){let c=i!=null?Qs.of(`${i}${"/"}${s}`):Qs.of(s);t[c]=a}let o=Object.keys(n.directories).sort();for(let s of o){let a=i!=null?`${i}${"/"}${s}`:s,c=n.directories[s];r(c,a)}};return r(this),t}getOrCreateFile(t){return this.getOrCreateFileRecursive(t.split("/"))}getOrCreateFileRecursive(t){if(t.length===1)return this.files[Qs.of(t[0])]??={};let[r,...n]=t;if(r==null)throw new Error(`Internal error; cannot add file with path: ${t}`);return this.directories[r]||(this.directories[r]=new e),this.directories[r].getOrCreateFileRecursive(n)}};var jOe=class{enableUniqueErrorsPerEndpoint;root;rootApiFile;packageMarkerFile={};basePath=void 0;constructor(t){this.enableUniqueErrorsPerEndpoint=t,this.root=new Nar,this.rootApiFile={name:"api","error-discrimination":{strategy:"status-code"}}}setDisplayName({displayName:t}){this.rootApiFile["display-name"]=t}addNavigation({navigation:t}){this.packageMarkerFile.navigation=t}setServiceInfo(t,{auth:r,"base-path":n,"display-name":i,docs:o}){let s=this.getOrCreateFile(t);s.service==null&&(s.service={auth:!1,"base-path":"",endpoints:{}}),r!=null&&(s.service.auth=r),n!=null&&(s.service["base-path"]=n),i!=null&&(s.service["display-name"]=i),o!=null&&(s.docs=o)}addAudience(t){this.rootApiFile.audiences==null&&(this.rootApiFile.audiences=[]),this.rootApiFile.audiences.push(t)}setAuth(t){this.rootApiFile.auth=t}addAuthScheme({name:t,schema:r}){this.rootApiFile["auth-schemes"]==null&&(this.rootApiFile["auth-schemes"]={}),this.rootApiFile["auth-schemes"][t]==null&&(this.rootApiFile["auth-schemes"][t]=r)}setDefaultEnvironment(t){this.rootApiFile["default-environment"]=t}setDefaultUrl(t){this.rootApiFile["default-url"]=t}setBasePath(t){this.basePath=t}setApiVersion(t){this.rootApiFile.version=t}getEnvironmentType(){let t=Object.entries(this.rootApiFile.environments??{})[0];if(t!=null)return i$(t[1],{singleBaseUrl:()=>"single",multipleBaseUrls:()=>"multi"})}addEnvironment({name:t,schema:r}){this.rootApiFile.environments==null&&(this.rootApiFile.environments={}),this.rootApiFile.environments[t]=r}getGlobalHeaderNames(){let t=Object.keys(this.rootApiFile.headers??{});if(this.rootApiFile["auth-schemes"]!=null)for(let n of Object.values(this.rootApiFile["auth-schemes"]))BAs(n)&&t.push(n.header);let r=this.getVersionHeader();return r!=null&&t.push(r),new Set(t)}getAuthHeaderName(){if(this.rootApiFile["auth-schemes"]!=null){for(let t of Object.values(this.rootApiFile["auth-schemes"]))if(BAs(t))return t.header;return"Authorization"}}addGlobalHeader({name:t,schema:r}){let n=this.getVersionHeader();n!=null&&n===t||(this.rootApiFile.headers==null&&(this.rootApiFile.headers={}),this.rootApiFile.headers[t]=r)}getGlobalHeaders(){return this.rootApiFile.headers??{}}addIdempotencyHeader({name:t,schema:r}){this.rootApiFile["idempotency-headers"]==null&&(this.rootApiFile["idempotency-headers"]={}),this.rootApiFile["idempotency-headers"][t]=r}addVariable({name:t,schema:r}){this.rootApiFile.variables==null&&(this.rootApiFile.variables={}),this.rootApiFile.variables[t]=r}addImport({file:t,fileToImport:r,alias:n}){if(t===r)return;let i=n??Vn((gU(r)+"/"+qB(r,{stripExtension:!0})).replaceAll("__package__","root"));if(t===Qs.of(Y0))return this.rootApiFile.imports==null&&(this.rootApiFile.imports={}),this.rootApiFile.imports[i]=T3e(gU(B3e.of(`/${t}`)),B3e.of(`/${r}`)),i;let o=this.getOrCreateFile(t);return o.imports==null&&(o.imports={}),o.imports[i]=T3e(gU(B3e.of(`/${t}`)),B3e.of(`/${r}`)),i}addType(t,{name:r,schema:n}){if(t===Qs.of(Y0))return;let i=this.getOrCreateFile(t);i.types==null&&(i.types={}),i.types[r]=n}addTypeExample(t,r,n){let i=this.getOrCreateFile(t);i.types==null&&(i.types={});let o=i.types[r];o!=null&&(typeof o=="string"?i.types[r]={type:o,examples:[n]}:(o.examples==null&&(o.examples=[]),o.examples.push(n)))}addError(t,{name:r,schema:n}){let i=this.getOrCreateFile(t);i.errors==null&&(i.errors={}),i.errors[r]==null?i.errors[r]=n:i.errors[r]?.type!==n.type&&(i.errors[r]={"status-code":n["status-code"],type:"unknown"})}addErrorExample(t,{name:r,example:n}){let i=this.getOrCreateFile(t);if(i.errors==null)return;let o=i.errors[r];if(o==null)return;o.examples==null&&(o.examples=[]),(o.examples.some(a=>$0(a,n))??!1)||o.examples?.push(n)}addEndpoint(t,{name:r,schema:n,source:i}){let o=this.getOrCreateFile(t);o.service==null&&(o.service={auth:!1,"base-path":"",endpoints:{}}),i!=null&&(o.service.source=i),o.service.endpoints[r]=n}addWebhook(t,{name:r,schema:n}){let i=this.getOrCreateFile(t);i.webhooks==null&&(i.webhooks={}),i.webhooks[r]=n}addChannel(t,{channel:r}){let n=this.getOrCreateFile(t);n.channel=r;let i=this.basePath;i!=null&&(n.channel.path=H0(i,r.path))}addChannelExample(t,{example:r}){let n=this.getOrCreateFile(t);n.channel==null&&(n.channel={path:"",auth:!1}),n.channel.messages==null&&(n.channel.messages={}),n.channel.examples==null&&(n.channel.examples=[]),n.channel.examples.push(r)}addChannelMessage(t,{messageId:r,message:n}){let i=this.getOrCreateFile(t);i.channel==null&&(i.channel={path:"",auth:!1}),i.channel.messages==null&&(i.channel.messages={}),i.channel.messages[r]=n}optimizeServiceAuth(){let t=[this.packageMarkerFile,...Object.values(this.root.getAllFiles())];for(let r of t){if(r.service==null)continue;let n=Object.values(r.service.endpoints);if(n.length===0)continue;if(n.every(o=>o.auth===!0)){r.service.auth=!0;for(let o of Object.values(r.service.endpoints))delete o.auth}}}build(){let t=this.root.getAllFiles(),r=this.basePath;if(r!=null){this.packageMarkerFile.service!=null&&(this.packageMarkerFile.service={...this.packageMarkerFile.service,endpoints:Object.fromEntries(Object.entries(this.packageMarkerFile.service.endpoints).map(([i,o])=>[i,{...o,path:H0(r,o.path)}]))});for(let i of Object.values(t))i.service!=null&&(i.service={...i.service,endpoints:Object.fromEntries(Object.entries(i.service.endpoints).map(([o,s])=>[o,{...s,path:H0(r,s.path)}]))})}return{rootApiFile:this.rootApiFile,packageMarkerFile:this.packageMarkerFile,definitionFiles:t}}getOrCreateFile(t){return t===tf?this.packageMarkerFile:this.root.getOrCreateFile(t)}getVersionHeader(){if(this.rootApiFile.version!=null)return typeof this.rootApiFile.version.header=="string"?this.rootApiFile.version.header:this.rootApiFile.version.header.value}};function BAs(e){return e?.header!=null}var Qar=class{logger;taskContext;ir;builder;environmentOverrides;authOverrides;globalHeaderOverrides;options;enableUniqueErrorsPerEndpoint;defaultServerName=void 0;unknownSchema=new Set;referencedSchemaIds;urlIdMap=new Map;endpointMethod;state=new Set;schemaNameMapping=new Map;variantPlan;reachability;constructor({taskContext:t,ir:r,options:n,environmentOverrides:i,globalHeaderOverrides:o,authOverrides:s}){this.logger=t.logger,this.taskContext=t,this.ir=r,this.environmentOverrides=i,this.authOverrides=s,this.globalHeaderOverrides=o,this.options=POe({options:n}),this.enableUniqueErrorsPerEndpoint=this.options.enableUniqueErrorsPerEndpoint,this.referencedSchemaIds=this.options.onlyIncludeReferencedSchemas?new Set:void 0,this.builder=new jOe(this.enableUniqueErrorsPerEndpoint),r.title!=null&&this.builder.setDisplayName({displayName:r.title});let a={};if(!this.enableUniqueErrorsPerEndpoint)for(let c of r.endpoints)for(let[u,l]of Object.entries(c.errors)){let p=parseInt(u),d=a[p];d==null&&l.schema!=null?a[p]=l.schema:d!=null&&l.schema!=null&&ik(d,l.schema)||this.unknownSchema.add(p)}}getReferencedSchemaIds(){if(this.referencedSchemaIds!=null)return Array.from(this.referencedSchemaIds)}getSchema(t,r){return r==null?this.ir.groupedSchemas.rootSchemas[t]:this.ir.groupedSchemas.namespacedSchemas[r]?.[t]}getDefaultServerName(){return this.defaultServerName}setDefaultServerName(t){this.defaultServerName=t}setUrlId(t,r){this.urlIdMap.set(t,r)}getUrlId(t){return this.urlIdMap.get(t)}isErrorUnknownSchema(t){return this.unknownSchema.has(t)}getEndpointMethod(){return this.endpointMethod}setEndpointMethod(t){this.endpointMethod=t}unsetEndpointMethod(){this.endpointMethod=void 0}isInState(t){return this.state.has(t)}setInState(t){this.state.add(t)}unsetInState(t){this.state.delete(t)}shouldMarkSchemaAsReferenced(){return this.options.onlyIncludeReferencedSchemas&&this.isInAnyState(ZS.Channel,ZS.Endpoint,ZS.Webhook)}markSchemaAsReferenced(t,r){switch(t.type){case"primitive":return;case"object":this.markObjectSchemaAsReferenced(t,r);return;case"array":this.markSchemaAsReferenced(t.value,r);return;case"map":this.markSchemaAsReferenced(t.value,r);return;case"optional":this.markSchemaAsReferenced(t.value,r);return;case"reference":this.markSchemaIdAsReferenced(t.schema,r);return;case"oneOf":this.markOneofSchemaAsReferenced(t.value,r);return;case"nullable":this.markSchemaAsReferenced(t.value,r);return;case"enum":return;case"literal":return;case"unknown":return;default:Be(t)}}markObjectSchemaAsReferenced(t,r){for(let n of t.allOf)this.markSchemaIdAsReferenced(n.schema,r);for(let n of t.properties)this.markSchemaAsReferenced(n.schema,r)}markOneofSchemaAsReferenced(t,r){switch(t.type){case"discriminated":for(let n of Object.values(t.schemas))this.markSchemaAsReferenced(n,r);return;case"undiscriminated":for(let n of t.schemas)this.markSchemaAsReferenced(n,r);return;default:Be(t)}}markSchemaIdAsReferenced(t,r){if(this.referencedSchemaIds!=null&&!this.referencedSchemaIds.has(t)){this.referencedSchemaIds.add(t);let n=this.getSchema(t,r);n!=null&&this.markSchemaAsReferenced(n,r)}}isInAnyState(...t){return t.some(r=>this.isInState(r))}setSchemaFinalName(t,r){this.schemaNameMapping.set(t,r)}hasReadVariant(t){return this.schemaNameMapping.has(t)}setVariantPlan(t,r){this.variantPlan=t,this.reachability=r;let n=[this.ir.groupedSchemas.rootSchemas,...Object.values(this.ir.groupedSchemas.namespacedSchemas)];for(let i of n)for(let[o,s]of Object.entries(i))if(t.needsBothVariants.has(o)&&s.type==="object"){let a=s.nameOverride??s.generatedName;this.schemaNameMapping.set(a,`${a}Read`)}}needsBothVariants(t){return this.variantPlan?.needsBothVariants.has(t)??!1}isRequestOnlyWithReadonly(t){return this.variantPlan?.requestOnlyWithReadonly.has(t)??!1}isResponseReachable(t){return this.reachability==null?this.ir.nonRequestReferencedSchemas.has(t):this.reachability.responseReachable.has(t)}isRequestOnly(t){return this.reachability==null?!this.ir.nonRequestReferencedSchemas.has(t):this.reachability.requestReachable.has(t)&&!this.reachability.responseReachable.has(t)}getSchemaFinalName(t,r){return!this.options.respectReadonlySchemas||r==="write"?t:this.schemaNameMapping.get(t)??t}};function Tli(e){let t=new Qar(e);return SAs(t)}sA();function qAs(e){return typeof e>"u"||e===null}function Wyl(e){return typeof e=="object"&&e!==null}function $yl(e){return Array.isArray(e)?e:qAs(e)?[]:[e]}function Hyl(e,t){var r,n,i,o;if(t)for(o=Object.keys(t),r=0,n=o.length;r<n;r+=1)i=o[r],e[i]=t[i];return e}function Kyl(e,t){var r="",n;for(n=0;n<t;n+=1)r+=e;return r}function Jyl(e){return e===0&&Number.NEGATIVE_INFINITY===1/e}var Yyl=qAs,Xyl=Wyl,Zyl=$yl,ebl=Kyl,tbl=Jyl,rbl=Hyl,Kw={isNothing:Yyl,isObject:Xyl,toArray:Zyl,repeat:ebl,isNegativeZero:tbl,extend:rbl};function GAs(e,t){var r="",n=e.reason||"(unknown reason)";return e.mark?(e.mark.name&&(r+='in "'+e.mark.name+'" '),r+="("+(e.mark.line+1)+":"+(e.mark.column+1)+")",!t&&e.mark.snippet&&(r+=`
1464
1464
 
1465
1465
  `+e.mark.snippet),n+" "+r):n}function sIt(e,t){Error.call(this),this.name="YAMLException",this.reason=e,this.mark=t,this.message=GAs(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}sIt.prototype=Object.create(Error.prototype);sIt.prototype.constructor=sIt;sIt.prototype.toString=function(t){return this.name+": "+GAs(this,t)};var YP=sIt;function Oli(e,t,r,n,i){var o="",s="",a=Math.floor(i/2)-1;return n-t>a&&(o=" ... ",t=n-a+o.length),r-n>a&&(s=" ...",r=n+a-s.length),{str:o+e.slice(t,r).replace(/\t/g,"\u2192")+s,pos:n-t+o.length}}function Pli(e,t){return Kw.repeat(" ",t-e.length)+e}function nbl(e,t){if(t=Object.create(t||null),!e.buffer)return null;t.maxLength||(t.maxLength=79),typeof t.indent!="number"&&(t.indent=1),typeof t.linesBefore!="number"&&(t.linesBefore=3),typeof t.linesAfter!="number"&&(t.linesAfter=2);for(var r=/\r?\n|\r|\0/g,n=[0],i=[],o,s=-1;o=r.exec(e.buffer);)i.push(o.index),n.push(o.index+o[0].length),e.position<=o.index&&s<0&&(s=n.length-2);s<0&&(s=n.length-1);var a="",c,u,l=Math.min(e.line+t.linesAfter,i.length).toString().length,p=t.maxLength-(t.indent+l+3);for(c=1;c<=t.linesBefore&&!(s-c<0);c++)u=Oli(e.buffer,n[s-c],i[s-c],e.position-(n[s]-n[s-c]),p),a=Kw.repeat(" ",t.indent)+Pli((e.line-c+1).toString(),l)+" | "+u.str+`
1466
1466
  `+a;for(u=Oli(e.buffer,n[s],i[s],e.position,p),a+=Kw.repeat(" ",t.indent)+Pli((e.line+1).toString(),l)+" | "+u.str+`
@@ -1657,7 +1657,7 @@ ${x8a.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&V4i(th
1657
1657
  `+fNe.default.red(">> ")+t),this.screen.render(r,n)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?fNe.default.cyan(F8a(t,this.opt.mask)):fNe.default.italic(fNe.default.dim("[hidden]")):this.opt.mask?F8a(t,this.opt.mask):fNe.default.italic(fNe.default.dim("[input is hidden] "))}getSpinningValue(t){return this.getMaskedValue(t)}filterInput(t){return t||(this.opt.default==null?"":this.opt.default)}onEnd(t){this.status="answered",this.answer=t.value,this.render(),this.screen.done(),this.done(t.value)}onError(t){this.render(t.isValid)}onKeypress(){this.opt.default&&=void 0,this.render()}};var yPr=ye(hC(),1);var RVa=ye(Czi(),1),gPr=require("child_process"),ZKe=require("fs"),hPr=ye(require("path"),1),FVa=ye(require("os"),1),kVa=require("crypto"),c3i=ye(PVa(),1);var fPr=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var vDt=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var dPr=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var mPr=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function APr(e="",t,r){let n=new u3i(e,r);n.runAsync((i,o)=>{if(i)setImmediate(t,i,void 0);else try{n.cleanup(),setImmediate(t,void 0,o)}catch(s){setImmediate(t,s,void 0)}})}function DVa(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function nrd(e){let t=[],r="";for(let n=0;n<e.length;n++){let i=e.charAt(n);n>0&&i===" "&&e[n-1]!=="\\"&&r.length>0?(t.push(r),r=""):r=`${r}${i}`}return r.length>0&&t.push(r),t}var u3i=class{text="";tempFile;editor;lastExitStatus=0;fileOptions={};get temp_file(){return console.log("DEPRECATED: temp_file. Use tempFile moving forward."),this.tempFile}get last_exit_status(){return console.log("DEPRECATED: last_exit_status. Use lastExitStatus moving forward."),this.lastExitStatus}constructor(t="",r){this.text=t,r&&(this.fileOptions=r),this.determineEditor(),this.createTemporaryFile()}run(){return this.launchEditor(),this.readTemporaryFile(),this.text}runAsync(t){try{this.launchEditorAsync(()=>{try{this.readTemporaryFile(),setImmediate(t,void 0,this.text)}catch(r){setImmediate(t,r,void 0)}})}catch(r){setImmediate(t,r,void 0)}}cleanup(){this.removeTemporaryFile()}determineEditor(){let t=process.env.VISUAL?process.env.VISUAL:process.env.EDITOR?process.env.EDITOR:process.platform.startsWith("win")?"notepad":"vim",r=nrd(t).map(i=>i.replace("\\ "," ")),n=r.shift();this.editor={args:r,bin:n}}createTemporaryFile(){try{let t=this.fileOptions.dir??FVa.default.tmpdir(),r=(0,kVa.randomUUID)(),n=DVa(this.fileOptions.prefix),i=DVa(this.fileOptions.postfix),o=`${n}${r}${i}`,s=hPr.default.resolve(t,o),a=hPr.default.resolve(t)+hPr.default.sep;if(!s.startsWith(a))throw new Error("Resolved temporary file escaped the base directory");this.tempFile=s;let c={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(c.mode=this.fileOptions.mode),(0,ZKe.writeFileSync)(this.tempFile,this.text,c)}catch(t){throw new fPr(t)}}readTemporaryFile(){try{let t=(0,ZKe.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,RVa.detect)(t)??"utf8";c3i.default.encodingExists(r)||(r="utf8"),this.text=c3i.default.decode(t,r)}}catch(t){throw new dPr(t)}}removeTemporaryFile(){try{(0,ZKe.unlinkSync)(this.tempFile)}catch(t){throw new mPr(t)}}launchEditor(){try{let t=(0,gPr.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new vDt(t)}}launchEditorAsync(t){try{(0,gPr.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",n=>{this.lastExitStatus=n,setImmediate(t)})}catch(r){throw new vDt(r)}}};var NVa=ye(mM(),1);var IDt=class extends gC{_run(t){this.done=t,this.editorResult=new NVa.Subject;let r=W1(this.rl);this.lineSubscription=r.line.subscribe(this.startExternalEditor.bind(this));let n=this.opt.waitUserInput===void 0?!0:this.opt.waitUserInput,i=this.handleSubmitEvents(this.editorResult);return i.success.forEach(this.onEnd.bind(this)),i.error.forEach(this.onError.bind(this)),this.currentText=this.opt.default,this.opt.default=null,n?this.render():this.startExternalEditor(),this}render(t){let r="",n=this.getQuestion();n+=this.status==="answered"?yPr.default.dim("Received"):yPr.default.dim("Press <enter> to launch your preferred editor."),t&&(r=yPr.default.red(">> ")+t),this.screen.render(n,r)}startExternalEditor(){this.rl.pause(),APr(this.currentText,this.endExternalEditor.bind(this),{postfix:this.opt.postfix??".txt"})}endExternalEditor(t,r){this.rl.resume(),t?this.editorResult.error(t):this.editorResult.next(r)}onEnd(t){this.editorResult.unsubscribe(),this.lineSubscription.unsubscribe(),this.answer=t.value,this.status="answered",this.render(),this.screen.done(),this.done(this.answer)}onError(t){this.render(t.isValid)}};var UVa=require("stream");var MVa=ye(require("readline"),1),LVa=ye(jVa(),1),gNe=class{constructor(t){this.rl||=MVa.default.createInterface(ord(t)),this.rl.resume(),this.onForceClose=this.onForceClose.bind(this),process.on("exit",this.onForceClose),this.rl.on("SIGINT",this.onForceClose)}onForceClose(){this.close(),process.kill(process.pid,"SIGINT"),console.log("")}close(){this.rl.removeListener("SIGINT",this.onForceClose),process.removeListener("exit",this.onForceClose),this.rl.output.unmute(),this.activePrompt&&typeof this.activePrompt.close=="function"&&this.activePrompt.close(),this.rl.output.end(),this.rl.pause(),this.rl.close()}};function ord(e={}){e.skipTTYChecks=e.skipTTYChecks===void 0?!0:e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY){let i=new Error("Prompts can not be meaningfully rendered in non-TTY environments");throw i.isTtyError=!0,i}let r=new LVa.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var wDt=class extends gNe{constructor(t={}){super(t),this.log=new UVa.Writable({write:(r,n,i)=>{this.writeLog(r),i()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return sDt(this.rl,this.bottomBar.split(`
1658
1658
  `).length),this}updateBottomBar(t){return sDt(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+`
1659
1659
  `}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&&LOr(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var Yf=ye(mM(),1),qVa=ye(QPt(),1);var bPr=ye(mM(),1),zVa=ye(QPt(),1),EPr=function(e,t,r){return typeof e[t]!="function"?(0,bPr.of)(e):(0,bPr.from)((0,zVa.default)(e[t])(r).then(n=>(e[t]=n,e)))};var VVa={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}},eJe=class extends gNe{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,Yf.from)(t):(0,Yf.isObservable)(t)?n=t:Object.values(t).every(i=>typeof i=="object"&&!Array.isArray(i)&&i!=null)?n=(0,Yf.from)(Object.entries(t).map(([i,o])=>({name:i,...o}))):n=(0,Yf.from)([t]),this.process=n.pipe((0,Yf.concatMap)(this.processQuestion.bind(this)),(0,Yf.publish)()),this.process.connect(),this.process.pipe((0,Yf.reduce)((i,o)=>(VVa.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,Yf.defer)(()=>(0,Yf.of)(t).pipe((0,Yf.concatMap)(this.setDefaultType.bind(this)),(0,Yf.concatMap)(this.filterIfRunnable.bind(this)),(0,Yf.concatMap)(()=>EPr(t,"message",this.answers)),(0,Yf.concatMap)(()=>EPr(t,"default",this.answers)),(0,Yf.concatMap)(()=>EPr(t,"choices",this.answers)),(0,Yf.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,Yf.defer)(()=>(0,Yf.from)(this.activePrompt.run().then(n=>({name:t.name,answer:n}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,Yf.defer)(()=>(0,Yf.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&VVa.get(this.answers,t.name)!==void 0)return Yf.EMPTY;if(t.when===!1)return Yf.EMPTY;if(typeof t.when!="function")return(0,Yf.of)(t);let{answers:r}=this;return(0,Yf.defer)(()=>(0,Yf.from)((0,qVa.default)(t.when)(r).then(n=>{if(n)return t})).pipe((0,Yf.filter)(n=>n!=null)))}};function GVa(e){let t=function(r,n){let i;try{i=new eJe(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",cDt),this.registerPrompt("input",pNe),this.registerPrompt("number",uDt),this.registerPrompt("confirm",lDt),this.registerPrompt("rawlist",pDt),this.registerPrompt("expand",fDt),this.registerPrompt("checkbox",dDt),this.registerPrompt("password",mDt),this.registerPrompt("editor",IDt)},t.restoreDefaultPrompts(),t}var p3i=GVa();function ard(e,t){p3i.registerPrompt(e,t)}function crd(){p3i.restoreDefaultPrompts()}var urd={prompt:p3i,ui:{BottomBar:wDt,Prompt:eJe},createPromptModule:GVa,registerPrompt:ard,restoreDefaultPrompts:crd,Separator:BN},Rp=urd;var tJe=require("path");function $Va(){let e=lrd();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function lrd(e=process.argv[1]?(0,tJe.dirname)(process.argv[1]):process.cwd(),t=tJe.sep==="\\"){let r=t?WVa(e):e;return n=>{if(!n)return;let i=t?WVa(n):n,{dir:o,base:s,ext:a}=tJe.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 WVa(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var f3i=e=>{if("flags"in e){let t=HVa(e.flags),r=KVa(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,o])=>[i,d3i(o)])),n=Object.fromEntries(Object.entries(t).map(([i,o])=>[i,prd(i,o,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function prd(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 HVa=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,CDt(r)]).filter(([,t])=>t!==void 0)),KVa=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?d3i(n):void 0]}))};var CDt=e=>e===void 0?void 0:e.variant??e.enabled,d3i=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var vPr="0123456789abcdef",IPr=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+=vPr.charAt(this.bytes[r]>>>4),t+=vPr.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+=vPr.charAt(this.bytes[r]>>>4),t+=vPr.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}},m3i=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??frd()}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 IPr.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,IPr.ofInner(t)}},frd=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),JVa,zbe=()=>drd().toString(),drd=()=>(JVa||(JVa=new m3i)).generate();var ON=(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.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.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e})({});var mrd=["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","pinterest","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"],YVa=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return mrd.concat(t).some(n=>{let i=n.toLowerCase();return r.indexOf(i)!==-1})};var grd=Array.isArray,XVa=Object.prototype,$8b=XVa.hasOwnProperty,h3i=XVa.toString,g3i=grd||function(e){return h3i.call(e)==="[object Array]"};var A3i=e=>e===Object(e)&&!g3i(e);var rJe=e=>e===void 0,xDt=e=>h3i.call(e)=="[object String]",ZVa=e=>xDt(e)&&e.trim().length===0;var e6a=e=>h3i.call(e)=="[object Number]"&&e===e;var y3i=e=>e instanceof Error;function wPr(e){return e===null||typeof e!="object"}function ANe(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function t6a(e){return ANe(e,"ErrorEvent")}function nJe(e){return!rJe(Event)&&Ard(e,Event)}function r6a(e){return ANe(e,"Object")}function Ard(e,t){try{return e instanceof t}catch{return!1}}function _Dt(e,t,r,n,i){return t>r&&(n.warn("min cannot be greater than max."),t=r),e6a(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),_Dt(i||r,t,r,n))}var yrd=864e5,CPr=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=_Dt(t.bucketSize,0,100,t._logger),this._refillRate=_Dt(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=_Dt(t.refillInterval,0,yrd,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 xPr=class{add(t){let r=zbe();return this.promiseByIds[r]=t,t.catch(()=>{}).finally(()=>{delete this.promiseByIds[r]}),t}async join(){let t=Object.values(this.promiseByIds),r=t.length;for(;r>0;)await Promise.all(t),t=Object.values(this.promiseByIds),r=t.length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}};function brd(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var n6a=(e,t,r)=>{function n(o,...s){t(()=>{let a=r[o];a(e,...s)})}return{info:(...o)=>{n("log",...o)},warn:(...o)=>{n("warn",...o)},error:(...o)=>{n("error",...o)},critical:(...o)=>{r.error(e,...o)},createLogger:o=>n6a(`${e} ${o}`,t,r)}},Erd=e=>e();function i6a(e,t=Erd){return n6a(e,t,brd())}var oJe="Mobile",SPr="iOS",iJe="Android",o6a="Tablet",oVb=iJe+" "+o6a;var vrd="Apple",sVb=vrd+" Watch",s6a="Safari",BPr="BlackBerry",a6a="Samsung",Ird=a6a+"Browser",wrd=a6a+" Internet",TPr="Chrome",Crd=TPr+" OS",xrd=TPr+" "+SPr,c6a="Internet Explorer",_rd=c6a+" "+oJe,E3i="Opera",aVb=E3i+" Mini",u6a="Edge",Srd="Microsoft "+u6a,v3i="Firefox",Brd=v3i+" "+SPr,I3i="Nintendo",w3i="PlayStation",_Pr="Xbox",Trd=iJe+" "+oJe,Ord=oJe+" "+s6a,SDt="Windows",Prd=SDt+" Phone";var l6a="Generic",cVb=l6a+" "+oJe.toLowerCase(),uVb=l6a+" "+o6a.toLowerCase(),Drd="Konqueror",OD="(\\d+(\\.\\d+)?)",b3i=new RegExp("Version/"+OD),lVb=new RegExp(_Pr,"i"),pVb=new RegExp(w3i+" \\w+","i"),fVb=new RegExp(I3i+" \\w+","i"),Rrd=new RegExp(BPr+"|PlayBook|BB10","i"),Frd={"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 dVb={[_rd]:[new RegExp("rv:"+OD)],[Srd]:[new RegExp(u6a+"?\\/"+OD)],[TPr]:[new RegExp("("+TPr+"|CrMo)\\/"+OD)],[xrd]:[new RegExp("CriOS\\/"+OD)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+OD)],[s6a]:[b3i],[Ord]:[b3i],[E3i]:[new RegExp("("+E3i+"|OPR)\\/"+OD)],[v3i]:[new RegExp(v3i+"\\/"+OD)],[Brd]:[new RegExp("FxiOS\\/"+OD)],[Drd]:[new RegExp("Konqueror[:/]?"+OD,"i")],[BPr]:[new RegExp(BPr+" "+OD),b3i],[Trd]:[new RegExp("android\\s"+OD,"i")],[wrd]:[new RegExp(Ird+"\\/"+OD)],[c6a]:[new RegExp("(rv:|MSIE )"+OD)],Mozilla:[new RegExp("rv:"+OD)]};var mVb=[[new RegExp(_Pr+"; "+_Pr+" (.*?)[);]","i"),e=>[_Pr,e&&e[1]||""]],[new RegExp(I3i,"i"),[I3i,""]],[new RegExp(w3i,"i"),[w3i,""]],[Rrd,[BPr,""]],[new RegExp(SDt,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[Prd,""];if(new RegExp(oJe).test(t)&&!/IEMobile\b/.test(t))return[SDt+" "+oJe,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let n=r[1],i=Frd[n]||"";return/arm/i.test(t)&&(i="RT"),[SDt,i]}return[SDt,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[SPr,t.join(".")]}return[SPr,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=rJe(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+iJe+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+iJe+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[iJe,t.join(".")]}return[iJe,""]}],[/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/,[Crd,""]],[/Linux|debian/i,["Linux",""]]];var p6a="utf8";function f6a(e,t){if(!e||typeof e!="string"||krd(e))throw new Error(t)}function krd(e){return e.trim().length===0}function d6a(e){return e?.replace(/\/+$/,"")}async function m6a(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 OPr(){return new Date().toISOString()}function Zue(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var h6a=e=>e instanceof Error;function C3i(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var PPr=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 g6a(){return"CompressionStream"in globalThis}async function x3i(e,t=!0){try{let n=new Blob([e],{type:"text/plain"}).stream().pipeThrough(new CompressionStream("gzip"));return await new Response(n).blob()}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var yNe=class extends Error{constructor(t,r){super("HTTP error while fetching PostHog: status="+t.status+", reqByteLength="+r),this.response=t,this.reqByteLength=r,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}},sJe=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function A6a(e){if(e instanceof yNe){let t="";try{t=await e.text}catch{}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function _3i(e){return typeof e=="object"&&(e instanceof yNe||e instanceof sJe)}function y6a(e){return typeof e=="object"&&e instanceof yNe&&e.status===413}var BDt=class{constructor(t,r={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new xPr,this._events=new PPr,this._isInitialized=!1,f6a(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=d6a(r.host||"https://us.i.posthog.com"),this.flushAt=r.flushAt?Math.max(r.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r.maxQueueSize??1e3),this.flushInterval=r.flushInterval??1e4,this.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:_3i},this.requestTimeout=r.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r.featureFlagsRequestTimeoutMs??3e3,this.remoteConfigRequestTimeoutMs=r.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r.disableGeoip??!0,this.disabled=r.disabled??!1,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this._logger=i6a("[PostHog]",this.logMsgIfDebug.bind(this)),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=!g6a()||(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(ON.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(ON.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(ON.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){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}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 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,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(i=>i.json()).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};this.evaluationContexts&&this.evaluationContexts.length>0&&(u.evaluation_contexts=this.evaluationContexts);let l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(u)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,l,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(p=>p.json()).then(p=>({success:!0,response:f3i(p)})).catch(p=>(this._events.emit("error",p),{success:!1,error:this.categorizeRequestError(p)}))}categorizeRequestError(t){if(t instanceof yNe)return{type:"api_error",statusCode:t.status};if(t instanceof sJe){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=CDt(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={};(o??this.disableGeoip)&&(a.geoip_disable=!0),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.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).then(o=>{if(o.status!==200||!o.json){let s=`Surveys API could not be loaded: ${o.status}`,a=new Error(s);this._logger.error(a),this._events.emit("error",new Error(s));return}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(ON.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(ON.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(ON.Props,this.props)})}processBeforeEnqueue(t){return t}async flushStorage(){}enqueue(t,r,n){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,r,n);if(i=this.processBeforeEnqueue(i),i===null)return;let o=this.getPersistedProperty(ON.Queue)||[];o.length>=this.maxQueueSize&&(o.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),o.push({message:i}),this.setPersistedProperty(ON.Queue,o),this._events.emit(t,i),o.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=Zue(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,n){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 i=this.prepareMessage(t,r,n);if(i=this.processBeforeEnqueue(i),i===null)return;let o={api_key:this.apiKey,batch:[i],sent_at:OPr()};this.historicalMigration&&(o.historical_migration=!0);let s=JSON.stringify(o),a=`${this.host}/batch/`,c=this.disableCompression?null:await x3i(s,this.isDebug),u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...c!==null&&{"Content-Encoding":"gzip"}},body:c||s};try{await this.fetchWithRetry(a,u)}catch(l){this._events.emit("error",l)}}prepareMessage(t,r,n){let i={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:n?.timestamp?n?.timestamp:OPr(),uuid:n?.uuid?n.uuid:zbe()};return(n?.disableGeoip??this.disableGeoip)&&(i.properties||(i.properties={}),i.properties.$geoip_disable=!0),i.distinctId&&(i.distinct_id=i.distinctId,delete i.distinctId),i}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(async t=>{await A6a(t)})}async flush(){let t=C3i([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),C3i([t]).then(()=>{this.flushPromise===t&&(this.flushPromise=null)}),t}getCustomHeaders(){let t=this.getCustomUserAgent(),r={};return t&&t!==""&&(r["User-Agent"]=t),r}async _flush(){this.clearFlushTimer(),await this._initPromise;let t=this.getPersistedProperty(ON.Queue)||[];if(!t.length)return;let r=[],n=t.length;for(;t.length>0&&r.length<n;){let i=t.slice(0,this.maxBatchSize),o=i.map(f=>f.message),s=async()=>{let m=(this.getPersistedProperty(ON.Queue)||[]).slice(i.length);this.setPersistedProperty(ON.Queue,m),t=m,await this.flushStorage()},a={api_key:this.apiKey,batch:o,sent_at:OPr()};this.historicalMigration&&(a.historical_migration=!0);let c=JSON.stringify(a),u=`${this.host}/batch/`,l=this.disableCompression?null:await x3i(c,this.isDebug),p={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...l!==null&&{"Content-Encoding":"gzip"}},body:l||c},d={retryCheck:f=>y6a(f)?!1:_3i(f)};try{await this.fetchWithRetry(u,p,d)}catch(f){if(y6a(f)&&o.length>1){this.maxBatchSize=Math.max(1,Math.floor(o.length/2)),this._logger.warn(`Received 413 when sending batch of size ${o.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw f instanceof sJe||await s(),this._events.emit("error",f),f}await s(),r.push(...o)}this._events.emit("flush",r)}async fetchWithRetry(t,r,n,i){let o=r.body?r.body:"",s=-1;try{s=o instanceof Blob?o.size:Buffer.byteLength(o,p6a)}catch{o instanceof Blob?s=o.size:s=new TextEncoder().encode(o).length}return await m6a(async()=>{let a=new AbortController,c=i??this.requestTimeout,u=Zue(()=>a.abort(),c),l=null;try{l=await this.fetch(t,{signal:a.signal,...r})}catch(d){throw new sJe(d)}finally{clearTimeout(u)}if(!(r.mode==="no-cors")&&(l.status<200||l.status>=400))throw new yNe(l,s);return l},{...this._retryOptions,...n})}async _shutdown(t=3e4){await this._initPromise;let r=!1;this.clearFlushTimer();let n=async()=>{try{for(await this.promiseQueue.join();!((this.getPersistedProperty(ON.Queue)||[]).length===0||(await this.flush(),r)););}catch(o){if(!_3i(o))throw o;await A6a(o)}},i;try{return await Promise.race([new Promise((o,s)=>{i=Zue(()=>{this._logger.error("Timed out while shutting down PostHog"),r=!0,s("Timeout while shutting down PostHog. Some events may not have been sent.")},t)}),n()])}finally{clearTimeout(i)}}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 PN={};te(PN,{DOMExceptionCoercer:()=>O3i,ErrorCoercer:()=>P3i,ErrorEventCoercer:()=>D3i,ErrorPropertiesBuilder:()=>S3i,EventCoercer:()=>k3i,ObjectCoercer:()=>F3i,PrimitiveCoercer:()=>N3i,PromiseRejectionEventCoercer:()=>Q3i,ReduceableCache:()=>j3i,StringCoercer:()=>R3i,chromeStackLineParser:()=>B3i,createDefaultStackParser:()=>Jrd,createStackParser:()=>T6a,geckoStackLineParser:()=>T3i,nodeStackLineParser:()=>x6a,opera10StackLineParser:()=>I6a,opera11StackLineParser:()=>w6a,reverseAndStripFrames:()=>B6a,winjsStackLineParser:()=>v6a});var DPr,b6a,RPr;function E6a(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return RPr&&r.length===b6a||(b6a=r.length,RPr=r.reduce((n,i)=>{DPr||(DPr={});let o=DPr[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,DPr[i]=[u,l];break}}}return n},{})),RPr}var Qrd=4,S3i=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&&g3i(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;return t.stack!=""&&t.stack!=null&&(i=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?r.skipFirstLines:0),r.chunkIdMap)),{...t,cause:n,stack:i}}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={type:t.type,value:t.value,mechanism:{type:r.type??"generic",handled:r.handled??!0,synthetic:t.synthetic??!1}};t.stack&&(n.stacktrace={type:"raw",frames:t.stack});let i=[n];return t.cause!=null&&i.push(...this.convertToExceptionList(t.cause,{...r,handled:!0})),i}buildParsingContext(t){return{chunkIdMap:E6a(this.stackParser),skipFirstLines:t.skipFirstLines??1}}buildCoercingContext(t,r,n=0){let i=(s,a)=>{if(a<=Qrd){let c=this.buildCoercingContext(t,r,a);return this.applyCoercers(s,c)}};return{...r,syntheticException:n==0?r.syntheticException:void 0,mechanism:t,apply:s=>i(s,n),next:s=>i(s,n+1)}}};var H1="?";function DX(e,t,r,n,i){let o={platform:e,filename:t,function:r==="<anonymous>"?H1:r,in_app:!0};return rJe(n)||(o.lineno=n),rJe(i)||(o.colno=i),o}var FPr=(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]:H1,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var jrd=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Mrd=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Lrd=/\((\S*)(?::(\d+))(?::(\d+))\)/,B3i=(e,t)=>{let r=jrd.exec(e);if(r){let[,i,o,s]=r;return DX(t,i,H1,+o,+s)}let n=Mrd.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=Lrd.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[o,s]=FPr(n[1]||H1,n[2]);return DX(t,s,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var Urd=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,zrd=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,T3i=(e,t)=>{let r=Urd.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let s=zrd.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]||H1;return[o,i]=FPr(o,i),DX(t,i,o,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var Vrd=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,v6a=(e,t)=>{let r=Vrd.exec(e);return r?DX(t,r[2],r[1]||H1,+r[3],r[4]?+r[4]:void 0):void 0};var qrd=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,I6a=(e,t)=>{let r=qrd.exec(e);return r?DX(t,r[2],r[3]||H1,+r[1]):void 0},Grd=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,w6a=(e,t)=>{let r=Grd.exec(e);return r?DX(t,r[5],r[3]||r[4]||H1,+r[1],+r[2]):void 0};var Wrd=/^\s*[-]{4,}$/,$rd=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,x6a=(e,t)=>{let r=e.match($rd);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||H1,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]),{filename:c?decodeURI(c):void 0,module:void 0,function:o,lineno:C6a(r[3]),colno:C6a(r[4]),in_app:Hrd(c||"",u),platform:t}}if(e.match(Wrd))return{filename:e,platform:t}};function Hrd(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 C6a(e){return parseInt(e||"",10)||void 0}var _6a=/\(error: (.*)\)/,S6a=50;function B6a(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,S6a).map(r=>({...r,filename:r.filename||Krd(t).filename,function:r.function||H1}))}function Krd(e){return e[e.length-1]||{}}function Jrd(){return T6a("web:javascript",B3i,T3i)}function T6a(e,...t){return(r,n=0)=>{let i=[],o=r.split(`
1660
- `);for(let s=n;s<o.length;s++){let a=o[s];if(a.length>1024)continue;let c=_6a.test(a)?a.replace(_6a,"$1"):a;if(!c.match(/\S*Error: /)){for(let u of t){let l=u(c,e);if(l){i.push(l);break}}if(i.length>=S6a)break}}return B6a(i)}}var O3i=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=xDt(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 ANe(t,"DOMException")}isDOMError(t){return ANe(t,"DOMError")}};var P3i=class{match(t){return y3i(t)}coerce(t,r){return{type:this.getType(t),value:this.getMessage(t,r),stack:this.getStack(t),cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}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){return t.stacktrace||t.stack||void 0}};var D3i=class{constructor(){}match(t){return t6a(t)&&t.error!=null}coerce(t,r){let n=r.apply(t.error);return n||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var Yrd=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,R3i=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(Yrd);return i&&(r=i[1],n=i[2]),[r,n]}};var O6a=["fatal","error","warning","log","info","debug"];function kPr(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 F3i=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:r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return nJe(t)?t.constructor.name:"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=kPr(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return xDt(t)&&!ZVa(t)&&O6a.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(h6a(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var k3i=class{match(t){return nJe(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${kPr(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var N3i=class{match(t){return wPr(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Q3i=class{match(t){return ANe(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!nJe(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 wPr(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 j3i=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 R6a=require("fs"),F6a=require("readline"),NPr=new PN.ReduceableCache(25),k6a=new PN.ReduceableCache(20),M3i=7,Xrd=1e3,Zrd=1e4;async function N6a(e){let t={};for(let i=e.length-1;i>=0;i--){let o=e[i],s=o?.filename;if(!o||typeof s!="string"||typeof o.lineno!="number"||nnd(s)||ind(o))continue;t[s]||(t[s]=[]),t[s].push(o.lineno)}let r=Object.keys(t);if(r.length==0)return e;let n=[];for(let i of r){if(k6a.get(i))continue;let o=t[i];if(!o)continue;o.sort((c,u)=>c-u);let s=snd(o);if(s.every(c=>ond(i,c)))continue;let a=and(NPr,i,{});n.push(end(i,s,a))}return await Promise.all(n).catch(()=>{}),e&&e.length>0&&tnd(e,NPr),NPr.reduce(),e}function end(e,t,r){return new Promise(n=>{let i=(0,R6a.createReadStream)(e),o=(0,F6a.createInterface)({input:i});function s(){i.destroy(),n()}let a=0,c=0,u=t[c];if(u===void 0)return void s();let l=u[0],p=u[1];function d(){k6a.set(e,1),o.close(),o.removeAllListeners(),s()}i.on("error",d),o.on("error",d),o.on("close",s),o.on("line",f=>{if(a++,!(a<l)&&(r[a]=cnd(f,0),a>=p)){if(c===t.length-1){o.close(),o.removeAllListeners();return}c++;let m=t[c];if(m===void 0){o.close(),o.removeAllListeners();return}l=m[0],p=m[1]}})})}function tnd(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let n=t.get(r.filename);if(n===void 0)continue;rnd(r.lineno,r,n)}}function rnd(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=Q6a(e);i<e;i++){let o=r[i];if(o===void 0)return void P6a(t);t.pre_context.push(o)}if(r[e]===void 0)return void P6a(t);t.context_line=r[e];let n=j6a(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 P6a(e){delete e.pre_context,delete e.context_line,delete e.post_context}function nnd(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function ind(e){return e.lineno!==void 0&&e.lineno>Zrd||e.colno!==void 0&&e.colno>Xrd}function ond(e,t){let r=NPr.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 snd(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=D6a(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+M3i:(i.push(n),n=D6a(o)),t++}return i}function D6a(e){return[Q6a(e),j6a(e)]}function Q6a(e){return Math.max(1,e-M3i)}function j6a(e){return e+M3i}function and(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function cnd(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}function und(e,t){let r=!1;return Object.assign(n=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length===0;e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&o&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function M6a(e,t){globalThis.process?.on("uncaughtException",und(e,t))}function L6a(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var lnd=2e3,l9=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new CPr({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return A3i(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i){let o={...i},s=this.errorPropertiesBuilder.buildFromUnknown(t,r);return s.$exception_list=await this.errorPropertiesBuilder.modifyFrames(s.$exception_list),{event:"$exception",distinctId:n,properties:{...s,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(M6a(this.onException.bind(this),this.onFatalError.bind(this)),L6a(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(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.capture(n)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(lnd),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var U6a="5.28.6";var TDt={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function z6a(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(i=>i.toString(16).padStart(2,"0")).join("")}var pnd=6e4,fnd=1152921504606847e3,dnd=["is_not"],aJe=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},Xf=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},RX=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},QPr=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.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.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}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 RX||u instanceof Xf?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={...t,evaluationCache:t.evaluationCache??{}};return await Promise.all(s.map(async c=>{try{let{value:u,payload:l}=await this.computeFlagAndPayloadLocally(c,a);n[c.key]=u,l&&(i[c.key]=l)}catch(u){u instanceof RX||u instanceof Xf?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(o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:a}}async computeFlagValueLocally(t,r){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=r;if(t.ensure_experience_continuity)throw new Xf("Flag has experience continuity enabled");if(!t.active)return!1;let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let u=this.groupTypeMapping[String(c)];if(!u)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new Xf("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 Xf(`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}getFeatureFlagPayload(t,r){let n=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),n!=null)){if(typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!this.featureFlagsByKey)throw new Xf("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new Xf(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new Xf(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new Xf(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let l=this.featureFlagsByKey[c];if(l)if(l.active)try{let p=await this.computeFlagValueLocally(l,n);i[c]=p}catch(p){throw new Xf(`Error evaluating flag dependency '${c}' for flag '${o}': ${p}`)}else i[c]=!1;else throw new Xf(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new Xf(`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){let o=t.filters||{},s=o.groups||[],a=!1,c;for(let u of s)try{if(await this.isConditionMatch(t,r,u,n,i)){let l=u.variant,p=o.multivariate?.variants||[];c=l&&p.some(d=>d.key===l)?l:await this.getMatchingVariant(t,r)||!0;break}}catch(l){if(l instanceof RX)throw l;if(l instanceof Xf)a=!0;else throw l}if(c!==void 0)return c;if(a)throw new Xf("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){let s=n.rollout_percentage,a=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((n.properties||[]).length>0){for(let c of n.properties){let u=c.type,l=!1;if(l=u==="cohort"?$6a(c,i,this.cohorts,this.debugMode):u==="flag"?await this.evaluateFlagDependency(c,i,o):W6a(c,i,a),!l)return!1}if(s==null)return!0}return!(s!=null&&await V6a(t.key,r)>s/100)}async getMatchingVariant(t,r){let n=await V6a(t.key,r,"variant"),i=this.variantLookupTable(t).find(o=>n>=o.valueMin&&n<o.valueMax);if(i)return i.key}variantLookupTable(t){let r=[],n=0,i=0;return((t.filters||{}).multivariate?.variants||[]).forEach(a=>{i=n+a.rollout_percentage/100,r.push({valueMin:n,valueMax:i,key:a.key}),n=i}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,n)=>(r[n.key]=n,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!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(r.flags),!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(){return this.shouldBeginExponentialBackoff?Math.min(pnd,this.pollingInterval*2**this.backOffCount):this.pollingInterval}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),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());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 aJe(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.beginBackoff(),new aJe(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new aJe(`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={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{}};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(o){this.onError?.(new Error(`Failed to store in cache: ${o}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(t){t instanceof aJe&&this.onError?.(t)}}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}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;n=Zue(()=>{i.abort()},this.timeout),r.signal=i.signal}try{let i=this.fetch;return i(t,r)}finally{clearTimeout(n)}}async stopPoller(t=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Promise.race([r,new Promise((n,i)=>setTimeout(()=>i(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function V6a(e,t,r=""){let n=await z6a(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/fnd}function W6a(e,t,r){let n=e.key,i=e.value,o=e.operator||"exact";if(n in t){if(o==="is_not_set")throw new Xf("Operator is_not_set is not supported")}else throw new Xf(`Property ${n} not found in propertyValues`);let s=t[n];if(s==null&&!dnd.includes(o))return r&&r(`Property ${n} cannot have a value of null/undefined with the ${o} operator`),!1;function a(u,l){return Array.isArray(u)?u.map(p=>String(p).toLowerCase()).includes(String(l).toLowerCase()):String(u).toLowerCase()===String(l).toLowerCase()}function c(u,l,p){if(p==="gt")return u>l;if(p==="gte")return u>=l;if(p==="lt")return u<l;if(p==="lte")return u<=l;throw new Error(`Invalid operator: ${p}`)}switch(o){case"exact":return a(i,s);case"is_not":return!a(i,s);case"is_set":return n in t;case"icontains":return String(s).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(i).toLowerCase());case"regex":return q6a(String(i))&&String(s).match(String(i))!==null;case"not_regex":return q6a(String(i))&&String(s).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let u=typeof i=="number"?i:null;if(typeof i=="string")try{u=parseFloat(i)}catch{}return u==null||s==null?c(String(s),String(i),o):typeof s=="string"?c(s,String(i),o):c(s,u,o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new Xf("Date operations cannot be performed on boolean values");let u=ynd(String(i));if(u==null&&(u=G6a(i)),u==null)throw new Xf(`Invalid date: ${i}`);let l=G6a(s);return["is_date_before"].includes(o)?l<u:l>u}case"semver_eq":return Zz(K1(String(s)),K1(String(i)))===0;case"semver_neq":return Zz(K1(String(s)),K1(String(i)))!==0;case"semver_gt":return Zz(K1(String(s)),K1(String(i)))>0;case"semver_gte":return Zz(K1(String(s)),K1(String(i)))>=0;case"semver_lt":return Zz(K1(String(s)),K1(String(i)))<0;case"semver_lte":return Zz(K1(String(s)),K1(String(i)))<=0;case"semver_tilde":{let u=K1(String(s)),{lower:l,upper:p}=hnd(String(i));return Zz(u,l)>=0&&Zz(u,p)<0}case"semver_caret":{let u=K1(String(s)),{lower:l,upper:p}=gnd(String(i));return Zz(u,l)>=0&&Zz(u,p)<0}case"semver_wildcard":{let u=K1(String(s)),{lower:l,upper:p}=And(String(i));return Zz(u,l)>=0&&Zz(u,p)<0}default:throw new Xf(`Unknown operator: ${o}`)}}function mnd(e,t){if(!(e in t))throw new RX(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function $6a(e,t,r,n=!1){let i=String(e.value);mnd(i,r);let o=r[i];return H6a(o,t,r,n)}function H6a(e,t,r,n=!1){if(!e)return!0;let i=e.type,o=e.values;if(!o||o.length===0)return!0;let s=!1;if("values"in o[0]){for(let a of o)try{let c=H6a(a,t,r,n);if(i==="AND"){if(!c)return!1}else if(c)return!0}catch(c){if(c instanceof RX)throw c;if(c instanceof Xf)n&&console.debug(`Failed to compute property ${a} locally: ${c}`),s=!0;else throw c}if(s)throw new Xf("Can't match cohort without a given cohort property value");return i==="AND"}for(let a of o)try{let c;if(a.type==="cohort")c=$6a(a,t,r,n);else if(a.type==="flag"){n&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${a.key||"unknown"}'`);continue}else c=W6a(a,t);let u=a.negation||!1;if(i==="AND"){if(!c&&!u||c&&u)return!1}else if(c&&!u||!c&&u)return!0}catch(c){if(c instanceof RX)throw c;if(c instanceof Xf)n&&console.debug(`Failed to compute property ${a} locally: ${c}`),s=!0;else throw c}if(s)throw new Xf("can't match cohort without a given cohort property value");return i==="AND"}function q6a(e){try{return new RegExp(e),!0}catch{return!1}}function K1(e){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new Xf(`Invalid semver: ${e}`);let n=r.split("."),i=c=>{if(c===void 0||c==="")return 0;if(!/^\d+$/.test(c))throw new Xf(`Invalid semver: ${e}`);return parseInt(c,10)},o=i(n[0]),s=i(n[1]),a=i(n[2]);return[o,s,a]}function Zz(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 hnd(e){let t=K1(e),r=[t[0],t[1],t[2]],n=[t[0],t[1]+1,0];return{lower:r,upper:n}}function gnd(e){let t=K1(e),[r,n,i]=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 And(e){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new Xf(`Invalid wildcard semver: ${e}`);let n=r.split("."),i=parseInt(n[0],10);if(isNaN(i))throw new Xf(`Invalid wildcard semver: ${e}`);let o,s;if(n.length===1)o=[i,0,0],s=[i+1,0,0];else{let a=parseInt(n[1],10);if(isNaN(a))throw new Xf(`Invalid wildcard semver: ${e}`);o=[i,a,0],s=[i,a+1,0]}return{lower:o,upper:s}}function G6a(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 Xf(`${e} is in an invalid date format`)}throw new Xf(`The date provided ${e} must be a string, number, or date object`)}function ynd(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r)return null;{if(!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}}var jPr=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var bnd=100,K6a=3e4,End=5e4,vnd=50,Ind=500,MPr=class extends BDt{constructor(t,r={}){if(super(t,r),this._memoryStorage=new jPr,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,bnd):K6a,typeof r.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(r.waitUntilDebounceMs,0)),typeof r.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(r.waitUntilMaxWaitMs,0)),r.personalApiKey){if(r.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');r.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new QPr({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},onLoad:i=>{this._events.emit("localEvaluationFlagsLoaded",i)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider,strictLocalEvaluation:r.strictLocalEvaluation}))}this.errorTracking=new l9(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||End}enqueue(t,r,n){super.enqueue(t,r,n),this.scheduleDebouncedFlush()}async flush(){let t=super.flush(),r=this.options.waitUntil;if(r&&!this._waitUntilCycle)try{r(t.catch(()=>{}))}catch{}return t}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??Ind,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??vnd;this._waitUntilCycle.timer=Zue(()=>{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 super.flush()}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)}getLibraryVersion(){return U6a}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStateless(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}async captureImmediate(t){return typeof t=="string"&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("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.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStatelessImmediate(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}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};super.identifyStateless(t,l,{disableGeoip:n})}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};super.identifyStatelessImmediate(t,l,{disableGeoip:n})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=K6a){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){let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let w=this._flagOverrides[t];if(w===void 0)return;let x=this._payloadOverrides?.[t];return{key:t,enabled:w!==!1,variant:typeof w=="string"?w:void 0,payload:x}}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,u,l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,h,g,A,b,v,E;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let w=this.featureFlagsPoller?.featureFlagsByKey[t];if(w)try{let x=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(w,d,{matchValue:i});if(x){m=!0;let C=x.value;b=w.id,E="Evaluated locally",f={key:t,enabled:C!==!1,variant:typeof C=="string"?C:void 0,payload:x.payload??void 0}}}catch(x){if(x instanceof RX||x instanceof Xf)this._logger?.info(`${x.name} when computing flag locally: ${t}: ${x.message}`);else throw x}}if(!m&&!c){let w=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,a,[t]);if(w===void 0)A=TDt.UNKNOWN_ERROR;else{h=w.requestId,g=w.evaluatedAt;let x=[];w.errorsWhileComputingFlags&&x.push(TDt.ERRORS_WHILE_COMPUTING),w.quotaLimited?.includes("feature_flags")&&x.push(TDt.QUOTA_LIMITED);let C=w.flags[t];if(C===void 0)x.push(TDt.FLAG_MISSING);else{b=C.metadata?.id,v=C.metadata?.version,E=C.reason?.description??C.reason?.code;let _;if(C.metadata?.payload!==void 0)try{_=JSON.parse(C.metadata.payload)}catch{_=C.metadata.payload}f={key:t,enabled:C.enabled,variant:C.variant,payload:_}}x.length>0&&(A=x.join(","))}}if(o){let w=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,x=`${t}_${w}`;if(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(x)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(x):this.distinctIdHasSentFlagCalls[r]=[x];let C={$feature_flag:t,$feature_flag_response:w,$feature_flag_id:b,$feature_flag_version:v,$feature_flag_reason:E,locally_evaluated:m,[`$feature/${t}`]:w,$feature_flag_request_id:h,$feature_flag_evaluated_at:m?Date.now():g};if(m&&this.featureFlagsPoller){let _=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();_!==void 0&&(C.$feature_flag_definitions_loaded_at=_)}A&&(C.$feature_flag_error=A),this.capture({distinctId:r,event:"$feature_flag_called",properties:C,groups:s,disableGeoip:a})}}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){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(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.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){let i=await this.getFeatureFlag(t,r,n);if(i!==void 0)return!!i||!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:{}};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,u,l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),m={},h={},g=!0;if(f&&(m=f.response,h=f.payloads,g=f.fallbackToFlags),g&&!c){let A=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,s,a);m={...m,...A.flags||{}},h={...h,...A.payloads||{}}}return this._flagOverrides!==void 0&&(m={...m,...this._flagOverrides}),this._payloadOverrides!==void 0&&(h={...h,...this._payloadOverrides}),{featureFlags:m,featureFlagPayloads:h}}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){super.groupIdentifyStateless(t,r,n,{disableGeoip:o},i)}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=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown();try{return await super._shutdown(t)}finally{r?.()}}async _requestRemoteConfigPayload(t){if(!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=Zue(()=>{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(r6a(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){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={distinct_id:t,...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i){if(!l9.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");this.addPendingPromise(l9.buildEventMessage(t,{syntheticException:o},r,n).then(s=>this.capture({...s,uuid:i})))}}async captureExceptionImmediate(t,r,n){if(!l9.isPreviouslyCapturedError(t)){let i=new Error("PostHog syntheticException");return this.addPendingPromise(l9.buildEventMessage(t,{syntheticException:i},r,n).then(o=>this.captureImmediate(o)))}}async prepareEventMessage(t){let{distinctId:r,event:n,properties:i,groups:o,sendFeatureFlags:s,timestamp:a,disableGeoip:c,uuid:u}=t,l=this.context?.get(),p=r||l?.distinctId,d={...this.props,...l?.properties||{},...i||{}};p||(p=zbe(),d.$process_person_profile=!1),l?.sessionId&&!d.$session_id&&(d.$session_id=l.sessionId);let f=this._runBeforeSend({distinctId:p,event:n,properties:d,groups:o,sendFeatureFlags:s,timestamp:a,disableGeoip:c,uuid:u});if(!f)return Promise.reject(null);let m=await Promise.resolve().then(async()=>{if(s){let h=typeof s=="object"?s:void 0;return await this.getFeatureFlagsForEvent(f.distinctId,o,c,h)}return f.event,{}}).then(h=>{let g={};if(h)for(let[b,v]of Object.entries(h))g[`$feature/${b}`]=v;let A=Object.keys(h||{}).filter(b=>h?.[b]!==!1).sort();return A.length>0&&(g.$active_feature_flags=A),g}).catch(()=>({})).then(h=>({...h,...f.properties||{},$groups:f.groups||o}));return f.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof m.$raw_user_agent=="string"&&YVa(m.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(f.event="$bot_pageview",m.$browser_type="bot"),{distinctId:f.distinctId,event:f.event,properties:m,options:{timestamp:f.timestamp,disableGeoip:f.disableGeoip,uuid:f.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){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)}}return i}};var J6a=require("async_hooks"),LPr=class{constructor(){this.storage=new J6a.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 Y6a="posthog-node";function wnd(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[L3i.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(m=>({...m,stacktrace:m.stacktrace?{...m.stacktrace,type:"raw",frames:(m.stacktrace.frames||[]).map(h=>({...h,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};return 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 L3i=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,n,i,o){this.name=Y6a,this.name=Y6a,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(wnd(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};l9.errorPropertiesBuilder=new PN.ErrorPropertiesBuilder([new PN.EventCoercer,new PN.ErrorCoercer,new PN.ObjectCoercer,new PN.StringCoercer,new PN.PrimitiveCoercer],PN.createStackParser("node:javascript",PN.nodeStackLineParser),[$Va(),N6a]);var Vbe=class extends MPr{getLibraryId(){return"posthog-node"}initializeContext(){return new LPr}};var UPr=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Vbe(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"4.48.0",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var ODt=class{async sendEvent(){}async identify(){}async flush(){}};qt();var cJe=require("fs/promises"),X6a=require("os"),Z6a=require("path");var Cnd="id",xnd=".fern",PDt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new Vbe(r),this.userId=t==null?void 0:nji(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:"4.48.0",...t,...t.properties,usingAccessToken:!1,...r!=null?{userEmail:r}:{}}})}async flush(){await this.posthog.flush()}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 Iy({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=We(zt.of((0,X6a.homedir)()),Se.of(xnd),Se.of(Cnd));await er(t)||(await(0,cJe.mkdir)((0,Z6a.dirname)(t),{recursive:!0}),await(0,cJe.writeFile)(t,Zx())),this.persistedDistinctId=(await(0,cJe.readFile)(t)).toString()}return this.persistedDistinctId}};var U3i;async function uJe(){return U3i==null&&(U3i=await _nd()),U3i}async function _nd(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new ODt;let r=await e_r();return r!=null?new PDt({token:r,posthogApiKey:e}):await hX()!=null?new UPr({posthogApiKey:e}):new PDt({token:void 0,posthogApiKey:e})}catch{return new ODt}}St();var DDt=ye(require("process"),1);var rqa=ye(XOi(),1),nqa=ye(tqa(),1);function g_(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=sue(e),e.length===0))return 0;e=e.replace((0,nqa.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(rqa.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}function zPr(e){let t=0;for(let r of e.split(`
1660
+ `);for(let s=n;s<o.length;s++){let a=o[s];if(a.length>1024)continue;let c=_6a.test(a)?a.replace(_6a,"$1"):a;if(!c.match(/\S*Error: /)){for(let u of t){let l=u(c,e);if(l){i.push(l);break}}if(i.length>=S6a)break}}return B6a(i)}}var O3i=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let n=xDt(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 ANe(t,"DOMException")}isDOMError(t){return ANe(t,"DOMError")}};var P3i=class{match(t){return y3i(t)}coerce(t,r){return{type:this.getType(t),value:this.getMessage(t,r),stack:this.getStack(t),cause:t.cause?r.next(t.cause):void 0,synthetic:!1}}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){return t.stacktrace||t.stack||void 0}};var D3i=class{constructor(){}match(t){return t6a(t)&&t.error!=null}coerce(t,r){let n=r.apply(t.error);return n||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var Yrd=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,R3i=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(Yrd);return i&&(r=i[1],n=i[2]),[r,n]}};var O6a=["fatal","error","warning","log","info","debug"];function kPr(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 F3i=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:r.syntheticException?.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return nJe(t)?t.constructor.name:"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=kPr(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(t){return xDt(t)&&!ZVa(t)&&O6a.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(h6a(n))return n}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var k3i=class{match(t){return nJe(t)}coerce(t,r){let n=t.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${kPr(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var N3i=class{match(t){return wPr(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Q3i=class{match(t){return ANe(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!nJe(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 wPr(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 j3i=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 R6a=require("fs"),F6a=require("readline"),NPr=new PN.ReduceableCache(25),k6a=new PN.ReduceableCache(20),M3i=7,Xrd=1e3,Zrd=1e4;async function N6a(e){let t={};for(let i=e.length-1;i>=0;i--){let o=e[i],s=o?.filename;if(!o||typeof s!="string"||typeof o.lineno!="number"||nnd(s)||ind(o))continue;t[s]||(t[s]=[]),t[s].push(o.lineno)}let r=Object.keys(t);if(r.length==0)return e;let n=[];for(let i of r){if(k6a.get(i))continue;let o=t[i];if(!o)continue;o.sort((c,u)=>c-u);let s=snd(o);if(s.every(c=>ond(i,c)))continue;let a=and(NPr,i,{});n.push(end(i,s,a))}return await Promise.all(n).catch(()=>{}),e&&e.length>0&&tnd(e,NPr),NPr.reduce(),e}function end(e,t,r){return new Promise(n=>{let i=(0,R6a.createReadStream)(e),o=(0,F6a.createInterface)({input:i});function s(){i.destroy(),n()}let a=0,c=0,u=t[c];if(u===void 0)return void s();let l=u[0],p=u[1];function d(){k6a.set(e,1),o.close(),o.removeAllListeners(),s()}i.on("error",d),o.on("error",d),o.on("close",s),o.on("line",f=>{if(a++,!(a<l)&&(r[a]=cnd(f,0),a>=p)){if(c===t.length-1){o.close(),o.removeAllListeners();return}c++;let m=t[c];if(m===void 0){o.close(),o.removeAllListeners();return}l=m[0],p=m[1]}})})}function tnd(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let n=t.get(r.filename);if(n===void 0)continue;rnd(r.lineno,r,n)}}function rnd(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=Q6a(e);i<e;i++){let o=r[i];if(o===void 0)return void P6a(t);t.pre_context.push(o)}if(r[e]===void 0)return void P6a(t);t.context_line=r[e];let n=j6a(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 P6a(e){delete e.pre_context,delete e.context_line,delete e.post_context}function nnd(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function ind(e){return e.lineno!==void 0&&e.lineno>Zrd||e.colno!==void 0&&e.colno>Xrd}function ond(e,t){let r=NPr.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 snd(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=D6a(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+M3i:(i.push(n),n=D6a(o)),t++}return i}function D6a(e){return[Q6a(e),j6a(e)]}function Q6a(e){return Math.max(1,e-M3i)}function j6a(e){return e+M3i}function and(e,t,r){let n=e.get(t);return n===void 0?(e.set(t,r),r):n}function cnd(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}function und(e,t){let r=!1;return Object.assign(n=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length===0;e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&o&&(r=!0,t(n))},{_posthogErrorHandler:!0})}function M6a(e,t){globalThis.process?.on("uncaughtException",und(e,t))}function L6a(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var lnd=2e3,l9=class e{constructor(t,r,n){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new CPr({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return A3i(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,n,i){let o={...i},s=this.errorPropertiesBuilder.buildFromUnknown(t,r);return s.$exception_list=await this.errorPropertiesBuilder.modifyFrames(s.$exception_list),{event:"$exception",distinctId:n,properties:{...s,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(M6a(this.onException.bind(this),this.onFatalError.bind(this)),L6a(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let n=await e.buildEventMessage(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.capture(n)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(lnd),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var U6a="5.28.6";var TDt={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function z6a(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(i=>i.toString(16).padStart(2,"0")).join("")}var pnd=6e4,fnd=1152921504606847e3,dnd=["is_not"],aJe=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},Xf=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},RX=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},QPr=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.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.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}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 RX||u instanceof Xf?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={...t,evaluationCache:t.evaluationCache??{}};return await Promise.all(s.map(async c=>{try{let{value:u,payload:l}=await this.computeFlagAndPayloadLocally(c,a);n[c.key]=u,l&&(i[c.key]=l)}catch(u){u instanceof RX||u instanceof Xf?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(o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=i!==void 0?i:await this.computeFlagValueLocally(t,r);let a=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:a}}async computeFlagValueLocally(t,r){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=r;if(t.ensure_experience_continuity)throw new Xf("Flag has experience continuity enabled");if(!t.active)return!1;let c=(t.filters||{}).aggregation_group_type_index;if(c!=null){let u=this.groupTypeMapping[String(c)];if(!u)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${t.key}`)),new Xf("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 Xf(`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}getFeatureFlagPayload(t,r){let n=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(n=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),n!=null)){if(typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(t,r,n){let{evaluationCache:i}=n,o=t.key;if(!this.featureFlagsByKey)throw new Xf("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new Xf(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=t.dependency_chain;if(!Array.isArray(s))throw new Xf(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new Xf(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of s){if(!(c in i)){let l=this.featureFlagsByKey[c];if(l)if(l.active)try{let p=await this.computeFlagValueLocally(l,n);i[c]=p}catch(p){throw new Xf(`Error evaluating flag dependency '${c}' for flag '${o}': ${p}`)}else i[c]=!1;else throw new Xf(`Missing flag dependency '${c}' for flag '${o}'`)}if(i[c]==null)throw new Xf(`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){let o=t.filters||{},s=o.groups||[],a=!1,c;for(let u of s)try{if(await this.isConditionMatch(t,r,u,n,i)){let l=u.variant,p=o.multivariate?.variants||[];c=l&&p.some(d=>d.key===l)?l:await this.getMatchingVariant(t,r)||!0;break}}catch(l){if(l instanceof RX)throw l;if(l instanceof Xf)a=!0;else throw l}if(c!==void 0)return c;if(a)throw new Xf("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,n,i,o){let s=n.rollout_percentage,a=c=>{this.logMsgIfDebug(()=>console.warn(c))};if((n.properties||[]).length>0){for(let c of n.properties){let u=c.type,l=!1;if(l=u==="cohort"?$6a(c,i,this.cohorts,this.debugMode):u==="flag"?await this.evaluateFlagDependency(c,i,o):W6a(c,i,a),!l)return!1}if(s==null)return!0}return!(s!=null&&await V6a(t.key,r)>s/100)}async getMatchingVariant(t,r){let n=await V6a(t.key,r,"variant"),i=this.variantLookupTable(t).find(o=>n>=o.valueMin&&n<o.valueMax);if(i)return i.key}variantLookupTable(t){let r=[],n=0,i=0;return((t.filters||{}).multivariate?.variants||[]).forEach(a=>{i=n+a.rollout_percentage/100,r.push({valueMin:n,valueMax:i,key:a.key}),n=i}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,n)=>(r[n.key]=n,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!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(r.flags),!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(){return this.shouldBeginExponentialBackoff?Math.min(pnd,this.pollingInterval*2**this.backOffCount):this.pollingInterval}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),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());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 aJe(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.beginBackoff(),new aJe(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new aJe(`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={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{}};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(o){this.onError?.(new Error(`Failed to store in cache: ${o}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(t){t instanceof aJe&&this.onError?.(t)}}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}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;n=Zue(()=>{i.abort()},this.timeout),r.signal=i.signal}try{let i=this.fetch;return i(t,r)}finally{clearTimeout(n)}}async stopPoller(t=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Promise.race([r,new Promise((n,i)=>setTimeout(()=>i(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function V6a(e,t,r=""){let n=await z6a(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/fnd}function W6a(e,t,r){let n=e.key,i=e.value,o=e.operator||"exact";if(n in t){if(o==="is_not_set")throw new Xf("Operator is_not_set is not supported")}else throw new Xf(`Property ${n} not found in propertyValues`);let s=t[n];if(s==null&&!dnd.includes(o))return r&&r(`Property ${n} cannot have a value of null/undefined with the ${o} operator`),!1;function a(u,l){return Array.isArray(u)?u.map(p=>String(p).toLowerCase()).includes(String(l).toLowerCase()):String(u).toLowerCase()===String(l).toLowerCase()}function c(u,l,p){if(p==="gt")return u>l;if(p==="gte")return u>=l;if(p==="lt")return u<l;if(p==="lte")return u<=l;throw new Error(`Invalid operator: ${p}`)}switch(o){case"exact":return a(i,s);case"is_not":return!a(i,s);case"is_set":return n in t;case"icontains":return String(s).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(i).toLowerCase());case"regex":return q6a(String(i))&&String(s).match(String(i))!==null;case"not_regex":return q6a(String(i))&&String(s).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let u=typeof i=="number"?i:null;if(typeof i=="string")try{u=parseFloat(i)}catch{}return u==null||s==null?c(String(s),String(i),o):typeof s=="string"?c(s,String(i),o):c(s,u,o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new Xf("Date operations cannot be performed on boolean values");let u=ynd(String(i));if(u==null&&(u=G6a(i)),u==null)throw new Xf(`Invalid date: ${i}`);let l=G6a(s);return["is_date_before"].includes(o)?l<u:l>u}case"semver_eq":return Zz(K1(String(s)),K1(String(i)))===0;case"semver_neq":return Zz(K1(String(s)),K1(String(i)))!==0;case"semver_gt":return Zz(K1(String(s)),K1(String(i)))>0;case"semver_gte":return Zz(K1(String(s)),K1(String(i)))>=0;case"semver_lt":return Zz(K1(String(s)),K1(String(i)))<0;case"semver_lte":return Zz(K1(String(s)),K1(String(i)))<=0;case"semver_tilde":{let u=K1(String(s)),{lower:l,upper:p}=hnd(String(i));return Zz(u,l)>=0&&Zz(u,p)<0}case"semver_caret":{let u=K1(String(s)),{lower:l,upper:p}=gnd(String(i));return Zz(u,l)>=0&&Zz(u,p)<0}case"semver_wildcard":{let u=K1(String(s)),{lower:l,upper:p}=And(String(i));return Zz(u,l)>=0&&Zz(u,p)<0}default:throw new Xf(`Unknown operator: ${o}`)}}function mnd(e,t){if(!(e in t))throw new RX(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function $6a(e,t,r,n=!1){let i=String(e.value);mnd(i,r);let o=r[i];return H6a(o,t,r,n)}function H6a(e,t,r,n=!1){if(!e)return!0;let i=e.type,o=e.values;if(!o||o.length===0)return!0;let s=!1;if("values"in o[0]){for(let a of o)try{let c=H6a(a,t,r,n);if(i==="AND"){if(!c)return!1}else if(c)return!0}catch(c){if(c instanceof RX)throw c;if(c instanceof Xf)n&&console.debug(`Failed to compute property ${a} locally: ${c}`),s=!0;else throw c}if(s)throw new Xf("Can't match cohort without a given cohort property value");return i==="AND"}for(let a of o)try{let c;if(a.type==="cohort")c=$6a(a,t,r,n);else if(a.type==="flag"){n&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${a.key||"unknown"}'`);continue}else c=W6a(a,t);let u=a.negation||!1;if(i==="AND"){if(!c&&!u||c&&u)return!1}else if(c&&!u||!c&&u)return!0}catch(c){if(c instanceof RX)throw c;if(c instanceof Xf)n&&console.debug(`Failed to compute property ${a} locally: ${c}`),s=!0;else throw c}if(s)throw new Xf("can't match cohort without a given cohort property value");return i==="AND"}function q6a(e){try{return new RegExp(e),!0}catch{return!1}}function K1(e){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new Xf(`Invalid semver: ${e}`);let n=r.split("."),i=c=>{if(c===void 0||c==="")return 0;if(!/^\d+$/.test(c))throw new Xf(`Invalid semver: ${e}`);return parseInt(c,10)},o=i(n[0]),s=i(n[1]),a=i(n[2]);return[o,s,a]}function Zz(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 hnd(e){let t=K1(e),r=[t[0],t[1],t[2]],n=[t[0],t[1]+1,0];return{lower:r,upper:n}}function gnd(e){let t=K1(e),[r,n,i]=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 And(e){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new Xf(`Invalid wildcard semver: ${e}`);let n=r.split("."),i=parseInt(n[0],10);if(isNaN(i))throw new Xf(`Invalid wildcard semver: ${e}`);let o,s;if(n.length===1)o=[i,0,0],s=[i+1,0,0];else{let a=parseInt(n[1],10);if(isNaN(a))throw new Xf(`Invalid wildcard semver: ${e}`);o=[i,a,0],s=[i,a+1,0]}return{lower:o,upper:s}}function G6a(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 Xf(`${e} is in an invalid date format`)}throw new Xf(`The date provided ${e} must be a string, number, or date object`)}function ynd(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r)return null;{if(!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}}var jPr=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var bnd=100,K6a=3e4,End=5e4,vnd=50,Ind=500,MPr=class extends BDt{constructor(t,r={}){if(super(t,r),this._memoryStorage=new jPr,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,bnd):K6a,typeof r.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(r.waitUntilDebounceMs,0)),typeof r.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(r.waitUntilMaxWaitMs,0)),r.personalApiKey){if(r.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');r.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new QPr({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:i=>{this._events.emit("error",i)},onLoad:i=>{this._events.emit("localEvaluationFlagsLoaded",i)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider,strictLocalEvaluation:r.strictLocalEvaluation}))}this.errorTracking=new l9(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||End}enqueue(t,r,n){super.enqueue(t,r,n),this.scheduleDebouncedFlush()}async flush(){let t=super.flush(),r=this.options.waitUntil;if(r&&!this._waitUntilCycle)try{r(t.catch(()=>{}))}catch{}return t}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??Ind,i=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??vnd;this._waitUntilCycle.timer=Zue(()=>{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 super.flush()}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)}getLibraryVersion(){return U6a}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(t=!0){super.debug(t),this.featureFlagsPoller?.debug(t)}capture(t){typeof t=="string"&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStateless(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}async captureImmediate(t){return typeof t=="string"&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),t.event==="$exception"&&!t._originatedFromCaptureException&&this._logger.warn("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.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:n,properties:i,options:o})=>super.captureStatelessImmediate(r,n,i,{timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid})).catch(r=>{r&&console.error(r)}))}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};super.identifyStateless(t,l,{disableGeoip:n})}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};super.identifyStatelessImmediate(t,l,{disableGeoip:n})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=K6a){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){let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let w=this._flagOverrides[t];if(w===void 0)return;let x=this._payloadOverrides?.[t];return{key:t,enabled:w!==!1,variant:typeof w=="string"?w:void 0,payload:x}}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,u,l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f,m=!1,h,g,A,b,v,E;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let w=this.featureFlagsPoller?.featureFlagsByKey[t];if(w)try{let x=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(w,d,{matchValue:i});if(x){m=!0;let C=x.value;b=w.id,E="Evaluated locally",f={key:t,enabled:C!==!1,variant:typeof C=="string"?C:void 0,payload:x.payload??void 0}}}catch(x){if(x instanceof RX||x instanceof Xf)this._logger?.info(`${x.name} when computing flag locally: ${t}: ${x.message}`);else throw x}}if(!m&&!c){let w=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,a,[t]);if(w===void 0)A=TDt.UNKNOWN_ERROR;else{h=w.requestId,g=w.evaluatedAt;let x=[];w.errorsWhileComputingFlags&&x.push(TDt.ERRORS_WHILE_COMPUTING),w.quotaLimited?.includes("feature_flags")&&x.push(TDt.QUOTA_LIMITED);let C=w.flags[t];if(C===void 0)x.push(TDt.FLAG_MISSING);else{b=C.metadata?.id,v=C.metadata?.version,E=C.reason?.description??C.reason?.code;let _;if(C.metadata?.payload!==void 0)try{_=JSON.parse(C.metadata.payload)}catch{_=C.metadata.payload}f={key:t,enabled:C.enabled,variant:C.variant,payload:_}}x.length>0&&(A=x.join(","))}}if(o){let w=f===void 0?void 0:f.enabled===!1?!1:f.variant??!0,x=`${t}_${w}`;if(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(x)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(x):this.distinctIdHasSentFlagCalls[r]=[x];let C={$feature_flag:t,$feature_flag_response:w,$feature_flag_id:b,$feature_flag_version:v,$feature_flag_reason:E,locally_evaluated:m,[`$feature/${t}`]:w,$feature_flag_request_id:h,$feature_flag_evaluated_at:m?Date.now():g};if(m&&this.featureFlagsPoller){let _=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();_!==void 0&&(C.$feature_flag_definitions_loaded_at=_)}A&&(C.$feature_flag_error=A),this.capture({distinctId:r,event:"$feature_flag_called",properties:C,groups:s,disableGeoip:a})}}return f!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(f={...f,payload:this._payloadOverrides[t]}),f}async getFeatureFlag(t,r,n){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(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.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){let i=await this.getFeatureFlag(t,r,n);if(i!==void 0)return!!i||!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:{}};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,u,l);c==null&&(c=this.options.strictLocalEvaluation??!1);let f=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,a),m={},h={},g=!0;if(f&&(m=f.response,h=f.payloads,g=f.fallbackToFlags),g&&!c){let A=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,d.personProperties,d.groupProperties,s,a);m={...m,...A.flags||{}},h={...h,...A.payloads||{}}}return this._flagOverrides!==void 0&&(m={...m,...this._flagOverrides}),this._payloadOverrides!==void 0&&(h={...h,...this._payloadOverrides}),{featureFlags:m,featureFlagPayloads:h}}groupIdentify({groupType:t,groupKey:r,properties:n,distinctId:i,disableGeoip:o}){super.groupIdentifyStateless(t,r,n,{disableGeoip:o},i)}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=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown();try{return await super._shutdown(t)}finally{r?.()}}async _requestRemoteConfigPayload(t){if(!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=Zue(()=>{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(r6a(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){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={distinct_id:t,...n||{}},s={};if(r)for(let a of Object.keys(r))s[a]={$group_key:r[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}createFeatureFlagEvaluationContext(t,r,n,i){return{distinctId:t,groups:r||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(t,r,n,i){if(!l9.isPreviouslyCapturedError(t)){let o=new Error("PostHog syntheticException");this.addPendingPromise(l9.buildEventMessage(t,{syntheticException:o},r,n).then(s=>this.capture({...s,uuid:i})))}}async captureExceptionImmediate(t,r,n){if(!l9.isPreviouslyCapturedError(t)){let i=new Error("PostHog syntheticException");return this.addPendingPromise(l9.buildEventMessage(t,{syntheticException:i},r,n).then(o=>this.captureImmediate(o)))}}async prepareEventMessage(t){let{distinctId:r,event:n,properties:i,groups:o,sendFeatureFlags:s,timestamp:a,disableGeoip:c,uuid:u}=t,l=this.context?.get(),p=r||l?.distinctId,d={...this.props,...l?.properties||{},...i||{}};p||(p=zbe(),d.$process_person_profile=!1),l?.sessionId&&!d.$session_id&&(d.$session_id=l.sessionId);let f=this._runBeforeSend({distinctId:p,event:n,properties:d,groups:o,sendFeatureFlags:s,timestamp:a,disableGeoip:c,uuid:u});if(!f)return Promise.reject(null);let m=await Promise.resolve().then(async()=>{if(s){let h=typeof s=="object"?s:void 0;return await this.getFeatureFlagsForEvent(f.distinctId,o,c,h)}return f.event,{}}).then(h=>{let g={};if(h)for(let[b,v]of Object.entries(h))g[`$feature/${b}`]=v;let A=Object.keys(h||{}).filter(b=>h?.[b]!==!1).sort();return A.length>0&&(g.$active_feature_flags=A),g}).catch(()=>({})).then(h=>({...h,...f.properties||{},$groups:f.groups||o}));return f.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof m.$raw_user_agent=="string"&&YVa(m.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(f.event="$bot_pageview",m.$browser_type="bot"),{distinctId:f.distinctId,event:f.event,properties:m,options:{timestamp:f.timestamp,disableGeoip:f.disableGeoip,uuid:f.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){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)}}return i}};var J6a=require("async_hooks"),LPr=class{constructor(){this.storage=new J6a.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 Y6a="posthog-node";function wnd(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[L3i.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(m=>({...m,stacktrace:m.stacktrace?{...m.stacktrace,type:"raw",frames:(m.stacktrace.frames||[]).map(h=>({...h,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};return 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 L3i=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,n,i,o){this.name=Y6a,this.name=Y6a,this.setupOnce=function(s,a){let c=a()?.getClient()?.getDsn()?.projectId;s(wnd(t,{organization:r,projectId:c,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};l9.errorPropertiesBuilder=new PN.ErrorPropertiesBuilder([new PN.EventCoercer,new PN.ErrorCoercer,new PN.ObjectCoercer,new PN.StringCoercer,new PN.PrimitiveCoercer],PN.createStackParser("node:javascript",PN.nodeStackLineParser),[$Va(),N6a]);var Vbe=class extends MPr{getLibraryId(){return"posthog-node"}initializeContext(){return new LPr}};var UPr=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Vbe(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"4.48.1",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var ODt=class{async sendEvent(){}async identify(){}async flush(){}};qt();var cJe=require("fs/promises"),X6a=require("os"),Z6a=require("path");var Cnd="id",xnd=".fern",PDt=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new Vbe(r),this.userId=t==null?void 0:nji(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:"4.48.1",...t,...t.properties,usingAccessToken:!1,...r!=null?{userEmail:r}:{}}})}async flush(){await this.posthog.flush()}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 Iy({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=We(zt.of((0,X6a.homedir)()),Se.of(xnd),Se.of(Cnd));await er(t)||(await(0,cJe.mkdir)((0,Z6a.dirname)(t),{recursive:!0}),await(0,cJe.writeFile)(t,Zx())),this.persistedDistinctId=(await(0,cJe.readFile)(t)).toString()}return this.persistedDistinctId}};var U3i;async function uJe(){return U3i==null&&(U3i=await _nd()),U3i}async function _nd(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new ODt;let r=await e_r();return r!=null?new PDt({token:r,posthogApiKey:e}):await hX()!=null?new UPr({posthogApiKey:e}):new PDt({token:void 0,posthogApiKey:e})}catch{return new ODt}}St();var DDt=ye(require("process"),1);var rqa=ye(XOi(),1),nqa=ye(tqa(),1);function g_(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=sue(e),e.length===0))return 0;e=e.replace((0,nqa.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(rqa.default.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}function zPr(e){let t=0;for(let r of e.split(`
1661
1661
  `))t=Math.max(t,g_(r));return t}var wqa=ye(V3i(),1);var Bnd=/[\p{Lu}]/u,Tnd=/[\p{Ll}]/u,sqa=/^[\p{Lu}](?![\p{Lu}])/gu,uqa=/([\p{Alpha}\p{N}_]|$)/u,q3i=/[_.\- ]+/,Ond=new RegExp("^"+q3i.source),aqa=new RegExp(q3i.source+uqa.source,"gu"),cqa=new RegExp("\\d+"+uqa.source,"gu"),Pnd=(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&&Bnd.test(u)?(e=e.slice(0,c)+"-"+e.slice(c),i=!1,s=o,o=!0,c++):o&&s&&Tnd.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},Dnd=(e,t)=>(sqa.lastIndex=0,e.replace(sqa,r=>t(r))),Rnd=(e,t)=>(aqa.lastIndex=0,cqa.lastIndex=0,e.replace(aqa,(r,n)=>t(n)).replace(cqa,r=>t(r)));function G3i(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?q3i.test(e)?"":t.pascalCase?n(e):r(e):(e!==r(e)&&(e=Pnd(e,r,n,t.preserveConsecutiveUppercase)),e=e.replace(Ond,""),e=t.preserveConsecutiveUppercase?Dnd(e,r):r(e),t.pascalCase&&(e=n(e.charAt(0))+e.slice(1)),Rnd(e,n))}var K3i=ye(pqa(),1);var fqa=(e=0)=>t=>`\x1B[${t+e}m`,dqa=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,mqa=(e=0)=>(t,r,n)=>`\x1B[${38+e};2;${t};${r};${n}m`,Eb={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]}},IGb=Object.keys(Eb.modifier),Qnd=Object.keys(Eb.color),jnd=Object.keys(Eb.bgColor),wGb=[...Qnd,...jnd];function Mnd(){let e=new Map;for(let[t,r]of Object.entries(Eb)){for(let[n,i]of Object.entries(r))Eb[n]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},r[n]=Eb[n],e.set(i[0],i[1]);Object.defineProperty(Eb,t,{value:r,enumerable:!1})}return Object.defineProperty(Eb,"codes",{value:e,enumerable:!1}),Eb.color.close="\x1B[39m",Eb.bgColor.close="\x1B[49m",Eb.color.ansi=fqa(),Eb.color.ansi256=dqa(),Eb.color.ansi16m=mqa(),Eb.bgColor.ansi=fqa(10),Eb.bgColor.ansi256=dqa(10),Eb.bgColor.ansi16m=mqa(10),Object.defineProperties(Eb,{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=>Eb.rgbToAnsi256(...Eb.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)=>Eb.ansi256ToAnsi(Eb.rgbToAnsi256(t,r,n)),enumerable:!1},hexToAnsi:{value:t=>Eb.ansi256ToAnsi(Eb.hexToAnsi256(t)),enumerable:!1}}),Eb}var Lnd=Mnd(),hqa=Lnd;var VPr=new Set(["\x1B","\x9B"]),Und=39,$3i="\x07",yqa="[",znd="]",bqa="m",H3i=`${znd}8;;`,gqa=e=>`${VPr.values().next().value}${yqa}${e}${bqa}`,Aqa=e=>`${VPr.values().next().value}${H3i}${e}${$3i}`,Vnd=e=>e.split(" ").map(t=>g_(t)),W3i=(e,t,r)=>{let n=[...t],i=!1,o=!1,s=g_(sue(e[e.length-1]));for(let[a,c]of n.entries()){let u=g_(c);if(s+u<=r?e[e.length-1]+=c:(e.push(c),s=0),VPr.has(c)&&(i=!0,o=n.slice(a+1).join("").startsWith(H3i)),i){o?c===$3i&&(i=!1,o=!1):c===bqa&&(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())},qnd=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(g_(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},Gnd=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",i,o,s=Vnd(e),a=[""];for(let[u,l]of e.split(" ").entries()){r.trim!==!1&&(a[a.length-1]=a[a.length-1].trimStart());let p=g_(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(""),W3i(a,l,t);continue}if(p+s[u]>t&&p>0&&s[u]>0){if(r.wordWrap===!1&&p<t){W3i(a,l,t);continue}a.push("")}if(p+s[u]>t&&r.wordWrap===!1){W3i(a,l,t);continue}a[a.length-1]+=l}r.trim!==!1&&(a=a.map(u=>qnd(u)));let c=[...a.join(`
1662
1662
  `)];for(let[u,l]of c.entries()){if(n+=l,VPr.has(l)){let{groups:d}=new RegExp(`(?:\\${yqa}(?<code>\\d+)m|\\${H3i}(?<uri>.*)${$3i})`).exec(c.slice(u).join(""))||{groups:{}};if(d.code!==void 0){let f=Number.parseFloat(d.code);i=f===Und?void 0:f}else d.uri!==void 0&&(o=d.uri.length===0?void 0:d.uri)}let p=hqa.codes.get(Number(i));c[u+1]===`
1663
1663
  `?(o&&(n+=Aqa("")),i&&p&&(n+=gqa(p))):l===`
@@ -2196,7 +2196,7 @@ Hint: Values starting with "@" (such as scoped npm packages) must be wrapped in
2196
2196
  Example: package-name: "@scope/package"`)}return{success:!1,warnings:[{type:"conflict",message:`Failed to parse generators.yml: ${o}`}]}}}checkDeprecatedFields(t,r){t.openapi!=null&&r.push({type:"deprecated",message:"The 'openapi' field is deprecated",suggestion:"Use 'api.specs' instead"}),t["openapi-overrides"]!=null&&r.push({type:"deprecated",message:"The 'openapi-overrides' field is deprecated",suggestion:"Use 'api.specs.[].overrides' instead"}),t["spec-origin"]!=null&&r.push({type:"deprecated",message:"The 'spec-origin' field is deprecated",suggestion:"Use 'api.specs.[].origin' instead"}),t["async-api"]!=null&&r.push({type:"deprecated",message:"The 'async-api' field is deprecated",suggestion:"Use 'api.specs' with asyncapi instead"}),t["api-settings"]!=null&&r.push({type:"deprecated",message:"The 'api-settings' field is deprecated",suggestion:"Use 'api.specs.[].settings' instead"}),t.whitelabel!=null&&r.push({type:"unsupported",message:"Whitelabel configuration is not yet supported in fern.yml"}),t.metadata!=null&&r.push({type:"unsupported",message:"Metadata configuration is not yet supported in fern.yml"}),t.reviewers!=null&&r.push({type:"unsupported",message:"Reviewers configuration is not yet supported in fern.yml"}),t.aliases!=null&&r.push({type:"unsupported",message:"Group aliases are not yet supported in fern.yml",suggestion:"Use multiple group names in target.group array instead"}),t["auth-schemes"]!=null&&r.push({type:"info",message:"Auth schemes configuration detected but not yet migrated",suggestion:"Auth schemes will be supported in a future version"})}async getAbsoluteFilePath(){let t=We(this.cwd,Se.of(Vp)),r=We(this.cwd,Se.of(j8e));if(await er(t,"file"))return t;if(await er(r,"file"))return r}};var zQt=class{cwd;logger;deleteOriginals;constructor(t){this.cwd=t.cwd,this.logger=t.logger,this.deleteOriginals=t.deleteOriginals??!0}async migrate(){let t=[],r=[],n=await this.findFernDirectory();if(n==null)return{success:!1,warnings:[{type:"conflict",message:"Could not find fern directory",suggestion:"Run this command from a directory containing a 'fern' folder"}],migratedFiles:r};let o=await new UQt({cwd:n}).migrate();if(t.push(...o.warnings),!o.success||o.org==null)return{success:!1,warnings:[...t,{type:"conflict",message:"Failed to migrate fern.config.json - organization is required"}],migratedFiles:r};o.absoluteFilePath!=null&&r.push(o.absoluteFilePath);let s=We(n,Se.of(qP)),a=await er(s,"directory"),c;if(a){let p=await this.migrateMultiApi({fernDir:n,apisDir:s,org:o.org,warnings:t,migratedFiles:r});if(!p.success)return{success:!1,warnings:t,migratedFiles:r};c=p.fernYml}else{let p=await this.migrateSingleApi({fernDir:n,org:o.org,warnings:t,migratedFiles:r});if(!p.success)return{success:!1,warnings:t,migratedFiles:r};c=p.fernYml}let u=We(this.cwd,Se.of(Mv)),l=this.serializeFernYml(c);if(await(0,Dlt.writeFile)(u,l,"utf-8"),this.deleteOriginals)for(let p of r)try{await(0,Dlt.rm)(p),this.logger.debug(`Deleted ${p}`)}catch{t.push({type:"info",message:`Could not delete ${p}`})}return this.logger.info(`Created ${u}`),{success:!0,warnings:t,migratedFiles:r,outputPath:u}}async migrateSingleApi(t){let{fernDir:r,org:n,warnings:i,migratedFiles:o}=t,a=await new tje({cwd:r}).migrate();i.push(...a.warnings),a.absoluteFilePath!=null&&o.push(a.absoluteFilePath);let c=await bso({fernDir:r,generatorsYmlApi:a.rawApi});i.push(...c.warnings);let u={org:n};return c.api!=null&&(u.api=c.api),a.sdks!=null&&(u.sdks=a.sdks),{success:!0,fernYml:u}}async migrateMultiApi(t){let{fernDir:r,apisDir:n,org:i,warnings:o,migratedFiles:s}=t,c=(await(0,Dlt.readdir)(n,{withFileTypes:!0})).filter(A=>A.isDirectory()).map(A=>A.name);if(c.length===0)return o.push({type:"conflict",message:"No API directories found in fern/apis/"}),{success:!1,fernYml:{org:i}};let u={},l={targets:{}},p,d;for(let A of c){let b=We(n,Se.of(A)),E=await new tje({cwd:b,apiName:A}).migrate();if(o.push(...E.warnings),E.absoluteFilePath!=null&&s.push(E.absoluteFilePath),u[A]=E.rawApi,E.sdks!=null){for(let[I,w]of Object.entries(E.sdks.targets))l.targets[I]=w;E.sdks.defaultGroup!=null&&p==null&&(p=E.sdks.defaultGroup),E.sdks.autorelease!=null&&d==null&&(d=E.sdks.autorelease)}}let f=await Eso({fernDir:r,apisDir:n,generatorsYmlApis:u});o.push(...f.warnings);let m={org:i,apis:f.apis};Object.keys(l.targets).length>0&&(p!=null&&(l.defaultGroup=p),d!=null&&(l.autorelease=d),m.sdks=l);let g=await new tje({cwd:r}).detect();return g.found&&g.absoluteFilePath!=null&&(o.push({type:"info",message:"Found generators.yml in fern root alongside apis/ directory",suggestion:"Review the migrated configuration to ensure it's correct"}),s.push(g.absoluteFilePath)),{success:!0,fernYml:m}}async findFernDirectory(){if(this.cwd.split("/").pop()===Fg)return this.cwd;let r=We(this.cwd,Se.of(Fg));if(await er(r,"directory"))return r}serializeFernYml(t){let r={edition:t.edition,org:t.org};return t.api!=null&&(r.api=t.api),t.apis!=null&&(r.apis=t.apis),t.ai!=null&&(r.ai=t.ai),t.cli!=null&&(r.cli=t.cli),t.sdks!=null&&(r.sdks=this.simplifySdks(t.sdks)),_r.dump(r,{indent:2,lineWidth:120,noRefs:!0,sortKeys:!1,quotingType:'"',forceQuotes:!1})}simplifySdks(t){let r={...t},n={};for(let[i,o]of Object.entries(t.targets)){let s=o.output;if(typeof s=="string"){n[i]=o;continue}if(s.git==null&&s.path!=null){n[i]={...o,output:s.path};continue}n[i]=o}return r.targets=n,r}};var vso=class{async handle(t,r){let i=await new zQt({cwd:t.cwd,logger:t.stdout,deleteOriginals:r.delete}).migrate();for(let o of i.warnings){switch(o.type){case"deprecated":t.stdout.warn(`Deprecated: ${o.message}`);break;case"unsupported":t.stdout.warn(`Unsupported: ${o.message}`);break;case"conflict":t.stderr.error(`Error: ${o.message}`);break;case"info":t.stdout.info(o.message);break}o.suggestion!=null&&t.stdout.info(` Suggestion: ${o.suggestion}`)}if(i.success){i.outputPath!=null&&t.stdout.debug(`Created: ${i.outputPath}`);return}throw new Yr({message:"Migration failed"})}};function Iso(e){let t=new vso;Ra(e,"migrate","Migrate legacy configuration files to fern.yml",(r,n)=>t.handle(r,n),r=>r.option("delete",{type:"boolean",description:"Keep original files after migration",default:!0}))}function wso(e){QB(e,"config","Configure, edit, and inspect your settings",[Iso])}var Cso=class{async handle(t,r){let n=await t.loadWorkspaceOrThrow();if(n.docs==null)throw new Yr({message:`No docs configuration found in fern.yml.
2197
2197
 
2198
2198
  Add a 'docs:' section to your fern.yml to get started.`});let o=await new z_e({context:t}).check({workspace:n,strict:r.strict}),s=o.hasErrors||r.strict&&o.hasWarnings;if(r.json){let a=this.buildJsonResponse({result:o,hasErrors:s});if(t.stdout.info(JSON.stringify(a,null,2)),s)throw Yr.exit();return}if(o.violations.length>0)for(let a of o.violations){let c=a.severity==="warning"?ve.yellow:ve.red;process.stderr.write(`${c(`${a.displayRelativeFilepath}:${a.line}:${a.column}: ${a.message}`)}
2199
- `)}if(s)throw Yr.exit();if(o.warningCount>0){t.stderr.info(`${bo.warning} ${ve.yellow(`Found ${o.warningCount} warnings`)}`),t.stderr.info(ve.dim(" Run 'fern docs check --strict' to treat warnings as errors"));return}t.stderr.info(`${bo.success} ${ve.green("All checks passed")}`)}buildJsonResponse({result:t,hasErrors:r}){let n={};return t.violations.length>0&&(n.docs=t.violations.map(i=>tZ(i))),{success:!r,results:n}}};function xso(e){let t=new Cso;Ra(e,"check","Validate docs configuration",(r,n)=>t.handle(r,n),r=>r.option("strict",{type:"boolean",description:"Treat warnings as errors",default:!1}).option("json",{type:"boolean",description:"Output results as JSON to stdout",default:!1}))}var bNc=ye(require("net"),1),ENc=ye(require("os"),1),dFn=class extends Error{constructor(t){super(`${t} is locked`)}},Rlt={old:new Set,young:new Set},Znm=1e3*15;var VQt,eim=()=>{let e=ENc.default.networkInterfaces(),t=new Set([void 0,"0.0.0.0"]);for(let r of Object.values(e))for(let n of r)t.add(n.address);return t},ANc=e=>new Promise((t,r)=>{let n=bNc.default.createServer();n.unref(),n.on("error",r),n.listen(e,()=>{let{port:i}=n.address();n.close(()=>{t(i)})})}),yNc=async(e,t)=>{if(e.host||e.port===0)return ANc(e);for(let r of t)try{await ANc({port:e.port,host:r})}catch(n){if(!["EADDRNOTAVAIL","EINVAL"].includes(n.code))throw n}return e.port},tim=function*(e){e&&(yield*e),yield 0};async function V_e(e){let t,r=new Set;if(e&&(e.port&&(t=typeof e.port=="number"?[e.port]:e.port),e.exclude)){let i=e.exclude;if(typeof i[Symbol.iterator]!="function")throw new TypeError("The `exclude` option must be an iterable.");for(let o of i){if(typeof o!="number")throw new TypeError("Each item in the `exclude` option must be a number corresponding to the port you want excluded.");if(!Number.isSafeInteger(o))throw new TypeError(`Number ${o} in the exclude option is not a safe integer and can't be used`)}r=new Set(i)}VQt===void 0&&(VQt=setTimeout(()=>{VQt=void 0,Rlt.old=Rlt.young,Rlt.young=new Set},Znm),VQt.unref&&VQt.unref());let n=eim();for(let i of tim(t))try{if(r.has(i))continue;let o=await yNc({...e,port:i},n);for(;Rlt.old.has(o)||Rlt.young.has(o);){if(i!==0)throw new dFn(i);o=await yNc({...e,port:i},n)}return Rlt.young.add(o),o}catch(o){if(!["EADDRINUSE","EACCES"].includes(o.code)&&!(o instanceof dFn))throw o}throw new Error("No available ports found")}St();Vg();qt();var NVc=ye(Bso(),1),QVc=ye(ZFn(),1),jNn=require("fs/promises"),jVc=ye(require("http"),1),MVc=ye(require("path"),1);var yLc=require("events"),ikn=ye(require("fs"),1),pje=ye(require("path"),1);var eLc=ye(require("os"),1),tLc=300,J_e=20,mjt=1e7,rLc=eLc.default.platform();var gpm=rLc==="darwin",$ao=rLc==="win32",Y_e=gpm||$ao,nLc=3e3,iLc=2e4,Hao=1250;var _re;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(_re||(_re={}));var lje;(function(e){e.CHANGE="change",e.RENAME="rename"})(lje||(lje={}));var hjt;(function(e){e.CHANGE="change",e.ERROR="error"})(hjt||(hjt={}));var gc;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(gc||(gc={}));var HR;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(HR||(HR={}));var Apm=(e,t=1,r)=>{t=Math.max(1,t);let n=r?.leading??!1,i=r?.trailing??!0,o=Math.max(r?.maxWait??1/0,t),s,a,c=0,u=0,l=()=>{let E=Date.now(),I=E-c,w=E-u,x=I>=t||w>=o;return[E,x]},p=E=>{if(u=E,!s)return;let I=s;s=void 0,e.apply(void 0,I)},d=()=>{b(0)},f=()=>{a&&(d(),p(Date.now()))},m=E=>{if(u=E,n)return p(E)},h=E=>{if(i&&s)return p(E);s=void 0},g=()=>{a=void 0;let[E,I]=l();return I?h(E):A(E)},A=E=>{let I=E-c,w=E-u,x=t-I,C=o-w,_=Math.min(x,C);return b(_)},b=E=>{a&&clearTimeout(a),!(E<=0)&&(a=setTimeout(g,E))},v=(...E)=>{let[I,w]=l(),x=!!a;if(s=E,c=I,(w||!a)&&b(t),w)return x?p(I):m(I)};return v.cancel=d,v.flush=f,v},ekn=Apm;var Xao=ye(require("fs"),1),rkn=ye(require("path"),1);var ed=ye(require("fs"),1),gB=require("util");var Fpe=(e,t)=>function(...n){return e.apply(void 0,n).catch(t)},Sre=(e,t)=>function(...n){try{return e.apply(void 0,n)}catch(i){return t(i)}};var Kao=ye(require("process"),1),oLc=Kao.default.getuid?!Kao.default.getuid():!1,sLc=1e4,H2=()=>{};var gjt={isChangeErrorOk:e=>{if(!gjt.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!oLc&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!gjt.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!gjt.isNodeError(e))throw e;if(!gjt.isChangeErrorOk(e))throw e}},Wv=gjt;var Jao=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=sLc,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(n),n=()=>t(r);this.add(n)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},aLc=new Jao;var kpe=(e,t)=>function(n){return function i(...o){return aLc.schedule().then(s=>{let a=u=>(s(),u),c=u=>{if(s(),Date.now()>=n)throw u;if(t(u)){let l=Math.round(100*Math.random());return new Promise(d=>setTimeout(d,l)).then(()=>i.apply(void 0,o))}throw u};return e.apply(void 0,o).then(a,c)})}},Npe=(e,t)=>function(n){return function i(...o){try{return e.apply(void 0,o)}catch(s){if(Date.now()>n)throw s;if(t(s))return i.apply(void 0,o);throw s}}};var ypm={attempt:{chmod:Fpe((0,gB.promisify)(ed.default.chmod),Wv.onChangeError),chown:Fpe((0,gB.promisify)(ed.default.chown),Wv.onChangeError),close:Fpe((0,gB.promisify)(ed.default.close),H2),fsync:Fpe((0,gB.promisify)(ed.default.fsync),H2),mkdir:Fpe((0,gB.promisify)(ed.default.mkdir),H2),realpath:Fpe((0,gB.promisify)(ed.default.realpath),H2),stat:Fpe((0,gB.promisify)(ed.default.stat),H2),unlink:Fpe((0,gB.promisify)(ed.default.unlink),H2),chmodSync:Sre(ed.default.chmodSync,Wv.onChangeError),chownSync:Sre(ed.default.chownSync,Wv.onChangeError),closeSync:Sre(ed.default.closeSync,H2),existsSync:Sre(ed.default.existsSync,H2),fsyncSync:Sre(ed.default.fsync,H2),mkdirSync:Sre(ed.default.mkdirSync,H2),realpathSync:Sre(ed.default.realpathSync,H2),statSync:Sre(ed.default.statSync,H2),unlinkSync:Sre(ed.default.unlinkSync,H2)},retry:{close:kpe((0,gB.promisify)(ed.default.close),Wv.isRetriableError),fsync:kpe((0,gB.promisify)(ed.default.fsync),Wv.isRetriableError),open:kpe((0,gB.promisify)(ed.default.open),Wv.isRetriableError),readFile:kpe((0,gB.promisify)(ed.default.readFile),Wv.isRetriableError),rename:kpe((0,gB.promisify)(ed.default.rename),Wv.isRetriableError),stat:kpe((0,gB.promisify)(ed.default.stat),Wv.isRetriableError),write:kpe((0,gB.promisify)(ed.default.write),Wv.isRetriableError),writeFile:kpe((0,gB.promisify)(ed.default.writeFile),Wv.isRetriableError),closeSync:Npe(ed.default.closeSync,Wv.isRetriableError),fsyncSync:Npe(ed.default.fsyncSync,Wv.isRetriableError),openSync:Npe(ed.default.openSync,Wv.isRetriableError),readFileSync:Npe(ed.default.readFileSync,Wv.isRetriableError),renameSync:Npe(ed.default.renameSync,Wv.isRetriableError),statSync:Npe(ed.default.statSync,Wv.isRetriableError),writeSync:Npe(ed.default.writeSync,Wv.isRetriableError),writeFileSync:Npe(ed.default.writeFileSync,Wv.isRetriableError)}},cLc=ypm;var tkn=ye(require("fs"),1),Ajt=ye(require("path"),1);var Yao=()=>{};var bpm=()=>{let e=Yao,t=Yao,r=!1,n=!1;return{promise:new Promise((c,u)=>{e=l=>(r=!0,c(l)),t=l=>(n=!0,u(l))}),resolve:e,reject:t,isPending:()=>!r&&!n,isResolved:()=>r,isRejected:()=>n}},uLc=bpm;var Epm=()=>{let{promise:e,resolve:t,isPending:r}=uLc(),n=0,i=()=>{n+=1},o=()=>{n-=1,!n&&t()};return i(),queueMicrotask(o),{promise:e,isPending:r,increment:i,decrement:o}},lLc=Epm;var pLc={then:e=>{e()}};var fLc=e=>Array.isArray(e)?e:[e],dLc=e=>typeof e=="function";var vpm=(e,t)=>{let r=t?.followSymlinks??!1,n=t?.depth??1/0,i=t?.limit??1/0,o=t?.ignore??[],s=fLc(o).map(K=>dLc(K)?K:X=>K.test(X)),a=K=>s.some(X=>X(K)),c=t?.signal??{aborted:!1},u=t?.onDirents||(()=>{}),l=[],p=new Set,d={},f=[],m=new Set,h={},g=[],A=new Set,b={},v={},E=new Set,I={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},w={directories:l,directoriesNames:p,directoriesNamesToPaths:d,files:f,filesNames:m,filesNamesToPaths:h,symlinks:g,symlinksNames:A,symlinksNamesToPaths:b,map:v},{promise:x,increment:C,decrement:_}=lLc(),D=0,z=(K,X,Ae,he)=>{E.has(X)||D>=i||(D+=1,K.directories.push(X),K.directoriesNames.add(Ae),l.push(X),p.add(Ae),d.propertyIsEnumerable(Ae)||(d[Ae]=[]),d[Ae].push(X),E.add(X),!(he>=n)&&(D>=i||W(X,he+1)))},q=(K,X,Ae)=>{E.has(X)||D>=i||(D+=1,K.files.push(X),K.filesNames.add(Ae),f.push(X),m.add(Ae),h.propertyIsEnumerable(Ae)||(h[Ae]=[]),h[Ae].push(X),E.add(X))},U=(K,X,Ae,he)=>{E.has(X)||D>=i||(D+=1,K.symlinks.push(X),K.symlinksNames.add(Ae),g.push(X),A.add(Ae),b.propertyIsEnumerable(Ae)||(b[Ae]=[]),b[Ae].push(X),E.add(X),r&&(he>=n||D>=i||ge(X,he+1)))},$=(K,X,Ae,he,_e)=>{c.aborted||a(X)||(he.isDirectory()?z(K,X,Ae,_e):he.isFile()?q(K,X,Ae):he.isSymbolicLink()&&U(K,X,Ae,_e))},re=(K,X,Ae,he)=>{if(c.aborted)return;let _e=X===Ajt.default.sep?"":Ajt.default.sep,xe=Ae.name,ue=`${X}${_e}${xe}`;a(ue)||(Ae.isDirectory()?z(K,ue,xe,he):Ae.isFile()?q(K,ue,xe):Ae.isSymbolicLink()&&U(K,ue,xe,he))},V=(K,X,Ae,he)=>{for(let _e=0,xe=Ae.length;_e<xe;_e++)re(K,X,Ae[_e],he)},W=(K,X)=>{c.aborted||X>n||D>=i||(C(),tkn.default.readdir(K,{withFileTypes:!0},(Ae,he)=>{if(Ae||c.aborted||!he.length)return _();(u(he)||pLc).then(()=>{let xe=v[K]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};V(xe,K,he,X),_()})}))},ge=(K,X)=>{C(),tkn.default.realpath(K,(Ae,he)=>{if(Ae||c.aborted)return _();tkn.default.stat(he,(_e,xe)=>{if(_e||c.aborted)return _();let ue=Ajt.default.basename(he),ce=v[K]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};$(ce,he,ue,xe,X),_()})})};return(async(K,X=1)=>(K=Ajt.default.normalize(K),E.add(K),W(K,X),await x,c.aborted?I:w))(e)},mLc=vpm;var Bre={lang:{debounce:ekn,attempt:e=>{try{return e()}catch(t){return Bre.lang.castError(t)}},castArray:e=>Bre.lang.isArray(e)?e:[e],castError:e=>Bre.lang.isError(e)?e:Bre.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(Bre.lang.isNaN(e))return Bre.lang.isNaN(t);if(Bre.lang.isPrimitive(e)||Bre.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(rkn.default.sep).length-1),getRealPath:(e,t)=>{try{return t?Xao.default.realpathSync.native(e):Xao.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===rkn.default.sep&&t.length-e.length>rkn.default.sep.length,poll:(e,t=iLc)=>cLc.retry.stat(t)(e,{bigint:!0}).catch(Bre.lang.noop),readdir:async(e,t,r=1/0,n=1/0,i,o)=>{if(o&&r===1&&e in o){let s=o[e];return[s.directories,s.files]}else{let s=await mLc(e,{depth:r,limit:n,ignore:t,signal:i});return[s.directories,s.files]}}}},Pl=Bre;var nkn=ye(require("path"),1);var Zao=class{constructor(t,r,n){this.base=n,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||Pl.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=tLc){return(()=>{let r=this.watcher._readyWait,n=[],i=new Set,o=async(a,c)=>{let u=this.options.ignoreInitial?[]:a,l=await this.eventsPopulate([...c]),p=this.eventsDeduplicate([...u,...l]);this.onTargetEvents(p)},s=Pl.lang.debounce(()=>{this.watcher.isClosed()||(r=o(n,i),n=[],i=new Set)},t);return async(a,c="",u=!1)=>{u?await this.eventsPopulate([c],n,!0):i.add(c),r.then(s)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((n,i)=>{let[o,s]=i,a=r[s];return o===a||o===gc.CHANGE&&a===gc.ADD||(r[s]=o,n.push(i)),n},[])}async eventsPopulate(t,r=[],n=!1){return await Promise.all(t.map(async i=>{let o=await this.watcher._poller.update(i,this.options.pollingTimeout);await Promise.all(o.map(async s=>{r.push([s,i]),s===gc.ADD_DIR?await this.eventsPopulateAddDir(t,i,r,n):s===gc.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,i,r,n)}))})),r}async eventsPopulateAddDir(t,r,n=[],i=!1){if(i)return n;let o=this.options.recursive?this.options.depth??J_e:Math.min(1,this.options.depth??J_e),s=this.options.limit??mjt,[a,c]=await Pl.fs.readdir(r,this.options.ignore,o,s,this.watcher._closeSignal),u=[...a,...c];return await Promise.all(u.map(l=>{if(!this.watcher.isIgnored(l,this.options.ignore)&&!t.includes(l))return this.eventsPopulate([l],n,!0)})),n}async eventsPopulateUnlinkDir(t,r,n=[],i=!1){if(i)return n;for(let o of this.watcher._poller.stats.keys())Pl.fs.isSubPath(r,o)&&(t.includes(o)||await this.eventsPopulate([o],n,!0));return n}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(gc.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!Y_e&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(gc.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(gc.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(nkn.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(gc.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(nkn.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(gc.UNLINK_DIR,t))}onTargetEvent(t){let[r,n]=t;r===gc.ADD?this.onTargetAdd(n):r===gc.ADD_DIR?this.onTargetAddDir(n):r===gc.CHANGE?this.onTargetChange(n):r===gc.UNLINK?this.onTargetUnlink(n):r===gc.UNLINK_DIR&&this.onTargetUnlinkDir(n)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,n=!1){return this.handlerBatched(t,r,n)}onWatcherChange(t=lje.CHANGE,r){if(this.watcher.isClosed())return;let n=nkn.default.resolve(this.folderPath,r||"");this.filePath&&n!==this.folderPath&&n!==this.filePath||this.watcher.isIgnored(n,this.options.ignore)||this.onWatcherEvent(t,n)}onWatcherError(t){$ao&&t.code==="EPERM"?this.onWatcherChange(lje.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(hjt.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(hjt.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(lje.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&Y_e&&this.options.native!==!1?this.options.depth??J_e:Math.min(1,this.options.depth??J_e),n=this.options.limit??mjt,[i,o]=await Pl.fs.readdir(this.folderPath,this.options.ignore,r,n,this.watcher._closeSignal,this.options.readdirMap),s=[this.folderPath,...i,...o];await Promise.all(s.map(a=>{if(!this.watcher._poller.stats.has(a)&&!this.watcher.isIgnored(a,this.options.ignore))return this.onWatcherEvent(lje.CHANGE,a,t)}))}}},hLc=Zao;var KR={interval:100,intervalId:void 0,fns:new Map,init:()=>{KR.intervalId||(KR.intervalId=setInterval(KR.resolve,KR.interval))},reset:()=>{KR.intervalId&&(clearInterval(KR.intervalId),delete KR.intervalId)},add:(e,t)=>{KR.fns.set(e,Date.now()+t),KR.init()},remove:e=>{KR.fns.delete(e)},resolve:()=>{if(!KR.fns.size)return KR.reset();let e=Date.now();for(let[t,r]of KR.fns)r>=e||(KR.remove(t),t())}},yjt=KR;var bjt=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=Hao){let{ino:n,targetPath:i,events:o,locks:s}=t,a=()=>{let p=this._watcher._poller.paths.find(n||-1,d=>d!==i);if(p&&p!==i){if(Pl.fs.getRealPath(i,!0)===p)return;this._watcher.event(o.rename,p,i)}else this._watcher.event(o.add,i)};if(!n)return a();let c=()=>{s.add.delete(n),yjt.remove(u)},u=()=>{c(),a()};yjt.add(u,r);let l=()=>{let p=s.unlink.get(n);if(!p)return;c();let d=p();i===d?o.change&&this._watcher._poller.stats.has(i)&&this._watcher.event(o.change,i):this._watcher.event(o.rename,d,i)};s.add.set(n,l),l()}getLockUnlink(t,r=Hao){let{ino:n,targetPath:i,events:o,locks:s}=t,a=()=>{this._watcher.event(o.unlink,i)};if(!n)return a();let c=()=>{s.unlink.delete(n),yjt.remove(u)},u=()=>{c(),a()};yjt.add(u,r);let l=()=>(c(),i);s.unlink.set(n,l),s.add.get(n)?.()}getLockTargetAdd(t,r){let n=this._watcher._poller.getIno(t,gc.ADD,_re.FILE);return this.getLockAdd({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let n=this._watcher._poller.getIno(t,gc.ADD_DIR,_re.DIR);return this.getLockAdd({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let n=this._watcher._poller.getIno(t,gc.UNLINK,_re.FILE);return this.getLockUnlink({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let n=this._watcher._poller.getIno(t,gc.UNLINK_DIR,_re.DIR);return this.getLockUnlink({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};bjt.DIR_EVENTS={add:gc.ADD_DIR,rename:gc.RENAME_DIR,unlink:gc.UNLINK_DIR};bjt.FILE_EVENTS={add:gc.ADD,change:gc.CHANGE,rename:gc.RENAME,unlink:gc.UNLINK};var gLc=bjt;var eco=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Pl.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let n=this.map.get(t);if(Pl.lang.isSet(n)){let i=n.delete(r);return n.size||this.map.delete(t),i}else if(n===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let n=this.map.get(t);if(Pl.lang.isSet(n))return Array.from(n).find(r);if(r(n))return n}}get(t){return this.map.get(t)}has(t,r){if(Pl.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let n=this.map.get(t);return Pl.lang.isSet(n)?n.has(r):n===r}return!1}set(t,r){if(this.map.has(t)){let n=this.map.get(t);Pl.lang.isSet(n)?n.add(r):n!==r&&this.map.set(t,new Set([n,r]))}else this.map.set(t,r);return this}},tco=eco;var rco=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},ALc=rco;var nco=class{constructor(){this.inos={},this.paths=new tco,this.stats=new Map}getIno(t,r,n){let i=this.inos[r];if(!i)return;let o=i[t];if(o&&!(n&&o[1]!==n))return o[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let n=await Pl.fs.poll(t,r);if(!(!n||!(n.isFile()||n.isDirectory())))return new ALc(n)}reset(){this.inos={},this.paths=new tco,this.stats=new Map}async update(t,r){let n=this.getStats(t),i=await this.poll(t,r);if(this.updateStats(t,i),!n&&i){if(i.isFile())return this.updateIno(t,gc.ADD,i),[gc.ADD];if(i.isDirectory())return this.updateIno(t,gc.ADD_DIR,i),[gc.ADD_DIR]}else if(n&&!i){if(n.isFile())return this.updateIno(t,gc.UNLINK,n),[gc.UNLINK];if(n.isDirectory())return this.updateIno(t,gc.UNLINK_DIR,n),[gc.UNLINK_DIR]}else if(n&&i){if(n.isFile()){if(i.isFile())return n.ino===i.ino&&!n.size&&!i.size?[]:(this.updateIno(t,gc.CHANGE,i),[gc.CHANGE]);if(i.isDirectory())return this.updateIno(t,gc.UNLINK,n),this.updateIno(t,gc.ADD_DIR,i),[gc.UNLINK,gc.ADD_DIR]}else if(n.isDirectory()){if(i.isFile())return this.updateIno(t,gc.UNLINK_DIR,n),this.updateIno(t,gc.ADD,i),[gc.UNLINK_DIR,gc.ADD];if(i.isDirectory())return n.ino===i.ino?[]:(this.updateIno(t,gc.UNLINK_DIR,n),this.updateIno(t,gc.ADD_DIR,i),[gc.UNLINK_DIR,gc.ADD_DIR])}}return[]}updateIno(t,r,n){let i=this.inos[r]=this.inos[r]||(this.inos[r]={}),o=n.isFile()?_re.FILE:_re.DIR;i[t]=[n.ino,o]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let n=this.stats.get(t)?.ino||-1;this.paths.delete(n,t),this.stats.delete(t)}}},ico=nco;var oco=class e extends yLc.EventEmitter{constructor(t,r,n){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(HR.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(i=>this.on(HR.CLOSE,i)),this._readyWait=new Promise(i=>this.on(HR.READY,i)),this._locker=new gLc(this),this._roots=new Set,this._poller=new ico,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,n)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(Pl.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(HR.CLOSE))}error(t){if(this.isClosed())return!1;let r=Pl.lang.castError(t);return this.emit(HR.ERROR,r)}event(t,r,n){return this.isClosed()?!1:(this.emit(HR.ALL,t,r,n),this.emit(t,r,n))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(HR.READY))}pollerExists(t,r){for(let n of this._pollers)if(n.targetPath===t&&Pl.lang.isShallowEqual(n.options,r))return!0;return!1}subwatcherExists(t,r){for(let n of this._subwatchers)if(n.targetPath===t&&Pl.lang.isShallowEqual(n.options,r))return!0;return!1}watchersClose(t,r,n=!0){if(t){let i=this._watchers[t];if(i)for(let o of[...i])r&&o.filePath!==r||this.watcherClose(o);if(n)for(let o in this._watchers)Pl.fs.isSubPath(t,o)&&this.watchersClose(o,r,!1)}else for(let i in this._watchers)this.watchersClose(i,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,n]of t)this.watchPath(r,n.options,n.handler)}async watcherAdd(t,r){let{folderPath:n}=t;(this._watchers[n]=this._watchers[n]||[]).push(t);let o=new hLc(this,t,r);return await o.init(),o}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let o=r.indexOf(t);r.splice(o,1),r.length||delete this._watchers[t.folderPath]}let n=t.filePath||t.folderPath;this._roots.has(n)&&(this._watchersRestorable[n]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=Pl.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,n,i){if(this._watchers[t]?.find(a=>a.handler===n&&(!a.filePath||a.filePath===i)&&a.options.ignore===r.ignore&&!!a.options.native==!!r.native&&(!r.recursive||a.options.recursive)))return!0;let s=pje.default.dirname(t);for(let a=1;a<1/0;a++){if(this._watchers[s]?.find(l=>(a===1||l.options.recursive&&a<=(l.options.depth??J_e))&&l.handler===n&&(!l.filePath||l.filePath===i)&&l.options.ignore===r.ignore&&!!l.options.native==!!r.native&&(!r.recursive||l.options.recursive&&Y_e&&l.options.native!==!1)))return!0;if(!Y_e)break;let u=pje.default.dirname(t);if(s===u)break;s=u}return!1}async watchDirectories(t,r,n,i,o){if(this.isClosed())return;t=Pl.lang.uniq(t).sort();let s;for(let a of t)if(!this.isIgnored(a,r.ignore)&&!this.watcherExists(a,r,n,i))try{let c=!r.recursive||Y_e&&r.native!==!1?r:{...r,recursive:!1},l={watcher:ikn.default.watch(a,c),handler:n,options:r,folderPath:a,filePath:i},p=s=await this.watcherAdd(l,o);if(this._roots.has(i||a)){let f={...r,ignoreInitial:!0,recursive:!1},m=pje.default.dirname(a),h=a;await this.watchDirectories([m],f,n,h,p)}}catch(c){this.error(c)}return s}async watchDirectory(t,r,n,i,o){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||Y_e&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,n,i,o));{r={...r,recursive:!0};let s=r.depth??J_e,a=r.limit??mjt,[c]=await Pl.fs.readdir(t,r.ignore,s,a,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let u=await this.watchDirectories([t],r,n,i,o);if(c.length){let l=Pl.fs.getDepth(t);for(let p of c){let d=Pl.fs.getDepth(p),f=Math.max(0,s-(d-l)),m={...r,depth:f};await this.watchDirectories([p],m,n,i,o||u)}}})}}}async watchFileOnce(t,r,n){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let i={targetPath:t,options:r},o=(u,l)=>{l===t&&(c(),n())},s=new e(o),a=()=>{this._subwatchers.add(i),this.on(HR.CLOSE,c),s.watchFile(t,r,o)},c=()=>{this._subwatchers.delete(i),this.removeListener(HR.CLOSE,c),s.close()};return a()}async watchFile(t,r,n){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let i=pje.default.dirname(t);return this.watchDirectory(i,r,n,t)}async watchPollingOnce(t,r,n){if(this.isClosed())return;let i=!1,o=new ico,s=await this.watchPolling(t,r,async()=>{i||!(await o.update(t,r.pollingTimeout)).length||i||(i=!0,s(),n())})}async watchPolling(t,r,n){if(this.isClosed())return Pl.lang.noop;if(this.pollerExists(t,r))return Pl.lang.noop;let i={...r,interval:r.pollingInterval??nLc},o={targetPath:t,options:r},s=()=>{this._pollers.add(o),this.on(HR.CLOSE,a),ikn.default.watchFile(t,i,n)},a=()=>{this._pollers.delete(o),this.removeListener(HR.CLOSE,a),ikn.default.unwatchFile(t,n)};return Pl.lang.attempt(s),()=>Pl.lang.attempt(a)}async watchUnknownChild(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchFileOnce(t,r,i)}async watchUnknownTarget(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchPollingOnce(t,r,i)}async watchPaths(t,r,n){if(this.isClosed())return;if(t=Pl.lang.uniq(t).sort(),t.every((o,s)=>t.every((a,c)=>c===s||!Pl.fs.isSubPath(o,a))))await Promise.all(t.map(o=>this.watchPath(o,r,n)));else for(let o of t)await this.watchPath(o,r,n)}async watchPath(t,r,n){if(this.isClosed()||(t=pje.default.resolve(t),this.isIgnored(t,r.ignore)))return;let i=await Pl.fs.poll(t,r.pollingTimeout);if(i){if(i.isFile())return this.watchFile(t,r,n);if(i.isDirectory())return this.watchDirectory(t,r,n);this.error(`"${t}" is not supported`)}else{let o=pje.default.dirname(t);return(await Pl.fs.poll(o,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,n):this.watchUnknownTarget(t,r,n)}}async watch(t,r,n=Pl.lang.noop){if(Pl.lang.isFunction(t))return this.watch([],{},t);if(Pl.lang.isUndefined(t))return this.watch([],r,n);if(Pl.lang.isFunction(r))return this.watch(t,{},r);if(Pl.lang.isUndefined(r))return this.watch(t,{},n);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let i=Pl.lang.castArray(t);i.forEach(o=>this._roots.add(o)),await this.watchPaths(i,r,n),!this.isClosed()&&(n!==Pl.lang.noop&&this.on(HR.ALL,n),r.readdirMap=void 0,this.ready())}},okn=oco;Ekn();qt();var ipt=require("fs/promises"),wUc=require("os"),CUc=ye(require("path"),1),$fm=".fern",Hfm="logs";function Kfm(){return"cli@4.48.0"}var Aje=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=We(zt.of((0,wUc.homedir)()),Se.of($fm)),r=We(t,Se.of(Hfm));await er(r)||await(0,ipt.mkdir)(r,{recursive:!0});let i=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=We(r,Se.of(i));let o=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${CUc.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
2199
+ `)}if(s)throw Yr.exit();if(o.warningCount>0){t.stderr.info(`${bo.warning} ${ve.yellow(`Found ${o.warningCount} warnings`)}`),t.stderr.info(ve.dim(" Run 'fern docs check --strict' to treat warnings as errors"));return}t.stderr.info(`${bo.success} ${ve.green("All checks passed")}`)}buildJsonResponse({result:t,hasErrors:r}){let n={};return t.violations.length>0&&(n.docs=t.violations.map(i=>tZ(i))),{success:!r,results:n}}};function xso(e){let t=new Cso;Ra(e,"check","Validate docs configuration",(r,n)=>t.handle(r,n),r=>r.option("strict",{type:"boolean",description:"Treat warnings as errors",default:!1}).option("json",{type:"boolean",description:"Output results as JSON to stdout",default:!1}))}var bNc=ye(require("net"),1),ENc=ye(require("os"),1),dFn=class extends Error{constructor(t){super(`${t} is locked`)}},Rlt={old:new Set,young:new Set},Znm=1e3*15;var VQt,eim=()=>{let e=ENc.default.networkInterfaces(),t=new Set([void 0,"0.0.0.0"]);for(let r of Object.values(e))for(let n of r)t.add(n.address);return t},ANc=e=>new Promise((t,r)=>{let n=bNc.default.createServer();n.unref(),n.on("error",r),n.listen(e,()=>{let{port:i}=n.address();n.close(()=>{t(i)})})}),yNc=async(e,t)=>{if(e.host||e.port===0)return ANc(e);for(let r of t)try{await ANc({port:e.port,host:r})}catch(n){if(!["EADDRNOTAVAIL","EINVAL"].includes(n.code))throw n}return e.port},tim=function*(e){e&&(yield*e),yield 0};async function V_e(e){let t,r=new Set;if(e&&(e.port&&(t=typeof e.port=="number"?[e.port]:e.port),e.exclude)){let i=e.exclude;if(typeof i[Symbol.iterator]!="function")throw new TypeError("The `exclude` option must be an iterable.");for(let o of i){if(typeof o!="number")throw new TypeError("Each item in the `exclude` option must be a number corresponding to the port you want excluded.");if(!Number.isSafeInteger(o))throw new TypeError(`Number ${o} in the exclude option is not a safe integer and can't be used`)}r=new Set(i)}VQt===void 0&&(VQt=setTimeout(()=>{VQt=void 0,Rlt.old=Rlt.young,Rlt.young=new Set},Znm),VQt.unref&&VQt.unref());let n=eim();for(let i of tim(t))try{if(r.has(i))continue;let o=await yNc({...e,port:i},n);for(;Rlt.old.has(o)||Rlt.young.has(o);){if(i!==0)throw new dFn(i);o=await yNc({...e,port:i},n)}return Rlt.young.add(o),o}catch(o){if(!["EADDRINUSE","EACCES"].includes(o.code)&&!(o instanceof dFn))throw o}throw new Error("No available ports found")}St();Vg();qt();var NVc=ye(Bso(),1),QVc=ye(ZFn(),1),jNn=require("fs/promises"),jVc=ye(require("http"),1),MVc=ye(require("path"),1);var yLc=require("events"),ikn=ye(require("fs"),1),pje=ye(require("path"),1);var eLc=ye(require("os"),1),tLc=300,J_e=20,mjt=1e7,rLc=eLc.default.platform();var gpm=rLc==="darwin",$ao=rLc==="win32",Y_e=gpm||$ao,nLc=3e3,iLc=2e4,Hao=1250;var _re;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(_re||(_re={}));var lje;(function(e){e.CHANGE="change",e.RENAME="rename"})(lje||(lje={}));var hjt;(function(e){e.CHANGE="change",e.ERROR="error"})(hjt||(hjt={}));var gc;(function(e){e.ADD="add",e.ADD_DIR="addDir",e.CHANGE="change",e.RENAME="rename",e.RENAME_DIR="renameDir",e.UNLINK="unlink",e.UNLINK_DIR="unlinkDir"})(gc||(gc={}));var HR;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(HR||(HR={}));var Apm=(e,t=1,r)=>{t=Math.max(1,t);let n=r?.leading??!1,i=r?.trailing??!0,o=Math.max(r?.maxWait??1/0,t),s,a,c=0,u=0,l=()=>{let E=Date.now(),I=E-c,w=E-u,x=I>=t||w>=o;return[E,x]},p=E=>{if(u=E,!s)return;let I=s;s=void 0,e.apply(void 0,I)},d=()=>{b(0)},f=()=>{a&&(d(),p(Date.now()))},m=E=>{if(u=E,n)return p(E)},h=E=>{if(i&&s)return p(E);s=void 0},g=()=>{a=void 0;let[E,I]=l();return I?h(E):A(E)},A=E=>{let I=E-c,w=E-u,x=t-I,C=o-w,_=Math.min(x,C);return b(_)},b=E=>{a&&clearTimeout(a),!(E<=0)&&(a=setTimeout(g,E))},v=(...E)=>{let[I,w]=l(),x=!!a;if(s=E,c=I,(w||!a)&&b(t),w)return x?p(I):m(I)};return v.cancel=d,v.flush=f,v},ekn=Apm;var Xao=ye(require("fs"),1),rkn=ye(require("path"),1);var ed=ye(require("fs"),1),gB=require("util");var Fpe=(e,t)=>function(...n){return e.apply(void 0,n).catch(t)},Sre=(e,t)=>function(...n){try{return e.apply(void 0,n)}catch(i){return t(i)}};var Kao=ye(require("process"),1),oLc=Kao.default.getuid?!Kao.default.getuid():!1,sLc=1e4,H2=()=>{};var gjt={isChangeErrorOk:e=>{if(!gjt.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!oLc&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!gjt.isNodeError(e))return!1;let{code:t}=e;return t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM"},onChangeError:e=>{if(!gjt.isNodeError(e))throw e;if(!gjt.isChangeErrorOk(e))throw e}},Wv=gjt;var Jao=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=sLc,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(n),n=()=>t(r);this.add(n)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},aLc=new Jao;var kpe=(e,t)=>function(n){return function i(...o){return aLc.schedule().then(s=>{let a=u=>(s(),u),c=u=>{if(s(),Date.now()>=n)throw u;if(t(u)){let l=Math.round(100*Math.random());return new Promise(d=>setTimeout(d,l)).then(()=>i.apply(void 0,o))}throw u};return e.apply(void 0,o).then(a,c)})}},Npe=(e,t)=>function(n){return function i(...o){try{return e.apply(void 0,o)}catch(s){if(Date.now()>n)throw s;if(t(s))return i.apply(void 0,o);throw s}}};var ypm={attempt:{chmod:Fpe((0,gB.promisify)(ed.default.chmod),Wv.onChangeError),chown:Fpe((0,gB.promisify)(ed.default.chown),Wv.onChangeError),close:Fpe((0,gB.promisify)(ed.default.close),H2),fsync:Fpe((0,gB.promisify)(ed.default.fsync),H2),mkdir:Fpe((0,gB.promisify)(ed.default.mkdir),H2),realpath:Fpe((0,gB.promisify)(ed.default.realpath),H2),stat:Fpe((0,gB.promisify)(ed.default.stat),H2),unlink:Fpe((0,gB.promisify)(ed.default.unlink),H2),chmodSync:Sre(ed.default.chmodSync,Wv.onChangeError),chownSync:Sre(ed.default.chownSync,Wv.onChangeError),closeSync:Sre(ed.default.closeSync,H2),existsSync:Sre(ed.default.existsSync,H2),fsyncSync:Sre(ed.default.fsync,H2),mkdirSync:Sre(ed.default.mkdirSync,H2),realpathSync:Sre(ed.default.realpathSync,H2),statSync:Sre(ed.default.statSync,H2),unlinkSync:Sre(ed.default.unlinkSync,H2)},retry:{close:kpe((0,gB.promisify)(ed.default.close),Wv.isRetriableError),fsync:kpe((0,gB.promisify)(ed.default.fsync),Wv.isRetriableError),open:kpe((0,gB.promisify)(ed.default.open),Wv.isRetriableError),readFile:kpe((0,gB.promisify)(ed.default.readFile),Wv.isRetriableError),rename:kpe((0,gB.promisify)(ed.default.rename),Wv.isRetriableError),stat:kpe((0,gB.promisify)(ed.default.stat),Wv.isRetriableError),write:kpe((0,gB.promisify)(ed.default.write),Wv.isRetriableError),writeFile:kpe((0,gB.promisify)(ed.default.writeFile),Wv.isRetriableError),closeSync:Npe(ed.default.closeSync,Wv.isRetriableError),fsyncSync:Npe(ed.default.fsyncSync,Wv.isRetriableError),openSync:Npe(ed.default.openSync,Wv.isRetriableError),readFileSync:Npe(ed.default.readFileSync,Wv.isRetriableError),renameSync:Npe(ed.default.renameSync,Wv.isRetriableError),statSync:Npe(ed.default.statSync,Wv.isRetriableError),writeSync:Npe(ed.default.writeSync,Wv.isRetriableError),writeFileSync:Npe(ed.default.writeFileSync,Wv.isRetriableError)}},cLc=ypm;var tkn=ye(require("fs"),1),Ajt=ye(require("path"),1);var Yao=()=>{};var bpm=()=>{let e=Yao,t=Yao,r=!1,n=!1;return{promise:new Promise((c,u)=>{e=l=>(r=!0,c(l)),t=l=>(n=!0,u(l))}),resolve:e,reject:t,isPending:()=>!r&&!n,isResolved:()=>r,isRejected:()=>n}},uLc=bpm;var Epm=()=>{let{promise:e,resolve:t,isPending:r}=uLc(),n=0,i=()=>{n+=1},o=()=>{n-=1,!n&&t()};return i(),queueMicrotask(o),{promise:e,isPending:r,increment:i,decrement:o}},lLc=Epm;var pLc={then:e=>{e()}};var fLc=e=>Array.isArray(e)?e:[e],dLc=e=>typeof e=="function";var vpm=(e,t)=>{let r=t?.followSymlinks??!1,n=t?.depth??1/0,i=t?.limit??1/0,o=t?.ignore??[],s=fLc(o).map(K=>dLc(K)?K:X=>K.test(X)),a=K=>s.some(X=>X(K)),c=t?.signal??{aborted:!1},u=t?.onDirents||(()=>{}),l=[],p=new Set,d={},f=[],m=new Set,h={},g=[],A=new Set,b={},v={},E=new Set,I={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},w={directories:l,directoriesNames:p,directoriesNamesToPaths:d,files:f,filesNames:m,filesNamesToPaths:h,symlinks:g,symlinksNames:A,symlinksNamesToPaths:b,map:v},{promise:x,increment:C,decrement:_}=lLc(),D=0,z=(K,X,Ae,he)=>{E.has(X)||D>=i||(D+=1,K.directories.push(X),K.directoriesNames.add(Ae),l.push(X),p.add(Ae),d.propertyIsEnumerable(Ae)||(d[Ae]=[]),d[Ae].push(X),E.add(X),!(he>=n)&&(D>=i||W(X,he+1)))},q=(K,X,Ae)=>{E.has(X)||D>=i||(D+=1,K.files.push(X),K.filesNames.add(Ae),f.push(X),m.add(Ae),h.propertyIsEnumerable(Ae)||(h[Ae]=[]),h[Ae].push(X),E.add(X))},U=(K,X,Ae,he)=>{E.has(X)||D>=i||(D+=1,K.symlinks.push(X),K.symlinksNames.add(Ae),g.push(X),A.add(Ae),b.propertyIsEnumerable(Ae)||(b[Ae]=[]),b[Ae].push(X),E.add(X),r&&(he>=n||D>=i||ge(X,he+1)))},$=(K,X,Ae,he,_e)=>{c.aborted||a(X)||(he.isDirectory()?z(K,X,Ae,_e):he.isFile()?q(K,X,Ae):he.isSymbolicLink()&&U(K,X,Ae,_e))},re=(K,X,Ae,he)=>{if(c.aborted)return;let _e=X===Ajt.default.sep?"":Ajt.default.sep,xe=Ae.name,ue=`${X}${_e}${xe}`;a(ue)||(Ae.isDirectory()?z(K,ue,xe,he):Ae.isFile()?q(K,ue,xe):Ae.isSymbolicLink()&&U(K,ue,xe,he))},V=(K,X,Ae,he)=>{for(let _e=0,xe=Ae.length;_e<xe;_e++)re(K,X,Ae[_e],he)},W=(K,X)=>{c.aborted||X>n||D>=i||(C(),tkn.default.readdir(K,{withFileTypes:!0},(Ae,he)=>{if(Ae||c.aborted||!he.length)return _();(u(he)||pLc).then(()=>{let xe=v[K]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};V(xe,K,he,X),_()})}))},ge=(K,X)=>{C(),tkn.default.realpath(K,(Ae,he)=>{if(Ae||c.aborted)return _();tkn.default.stat(he,(_e,xe)=>{if(_e||c.aborted)return _();let ue=Ajt.default.basename(he),ce=v[K]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};$(ce,he,ue,xe,X),_()})})};return(async(K,X=1)=>(K=Ajt.default.normalize(K),E.add(K),W(K,X),await x,c.aborted?I:w))(e)},mLc=vpm;var Bre={lang:{debounce:ekn,attempt:e=>{try{return e()}catch(t){return Bre.lang.castError(t)}},castArray:e=>Bre.lang.isArray(e)?e:[e],castError:e=>Bre.lang.isError(e)?e:Bre.lang.isString(e)?new Error(e):new Error("Unknown error"),defer:e=>setTimeout(e,0),isArray:e=>Array.isArray(e),isError:e=>e instanceof Error,isFunction:e=>typeof e=="function",isNaN:e=>Number.isNaN(e),isNumber:e=>typeof e=="number",isPrimitive:e=>{if(e===null)return!0;let t=typeof e;return t!=="object"&&t!=="function"},isShallowEqual:(e,t)=>{if(e===t)return!0;if(Bre.lang.isNaN(e))return Bre.lang.isNaN(t);if(Bre.lang.isPrimitive(e)||Bre.lang.isPrimitive(t))return e===t;for(let r in e)if(!(r in t))return!1;for(let r in t)if(e[r]!==t[r])return!1;return!0},isSet:e=>e instanceof Set,isString:e=>typeof e=="string",isUndefined:e=>e===void 0,noop:()=>{},uniq:e=>e.length<2?e:Array.from(new Set(e))},fs:{getDepth:e=>Math.max(0,e.split(rkn.default.sep).length-1),getRealPath:(e,t)=>{try{return t?Xao.default.realpathSync.native(e):Xao.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===rkn.default.sep&&t.length-e.length>rkn.default.sep.length,poll:(e,t=iLc)=>cLc.retry.stat(t)(e,{bigint:!0}).catch(Bre.lang.noop),readdir:async(e,t,r=1/0,n=1/0,i,o)=>{if(o&&r===1&&e in o){let s=o[e];return[s.directories,s.files]}else{let s=await mLc(e,{depth:r,limit:n,ignore:t,signal:i});return[s.directories,s.files]}}}},Pl=Bre;var nkn=ye(require("path"),1);var Zao=class{constructor(t,r,n){this.base=n,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||Pl.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=tLc){return(()=>{let r=this.watcher._readyWait,n=[],i=new Set,o=async(a,c)=>{let u=this.options.ignoreInitial?[]:a,l=await this.eventsPopulate([...c]),p=this.eventsDeduplicate([...u,...l]);this.onTargetEvents(p)},s=Pl.lang.debounce(()=>{this.watcher.isClosed()||(r=o(n,i),n=[],i=new Set)},t);return async(a,c="",u=!1)=>{u?await this.eventsPopulate([c],n,!0):i.add(c),r.then(s)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((n,i)=>{let[o,s]=i,a=r[s];return o===a||o===gc.CHANGE&&a===gc.ADD||(r[s]=o,n.push(i)),n},[])}async eventsPopulate(t,r=[],n=!1){return await Promise.all(t.map(async i=>{let o=await this.watcher._poller.update(i,this.options.pollingTimeout);await Promise.all(o.map(async s=>{r.push([s,i]),s===gc.ADD_DIR?await this.eventsPopulateAddDir(t,i,r,n):s===gc.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,i,r,n)}))})),r}async eventsPopulateAddDir(t,r,n=[],i=!1){if(i)return n;let o=this.options.recursive?this.options.depth??J_e:Math.min(1,this.options.depth??J_e),s=this.options.limit??mjt,[a,c]=await Pl.fs.readdir(r,this.options.ignore,o,s,this.watcher._closeSignal),u=[...a,...c];return await Promise.all(u.map(l=>{if(!this.watcher.isIgnored(l,this.options.ignore)&&!t.includes(l))return this.eventsPopulate([l],n,!0)})),n}async eventsPopulateUnlinkDir(t,r,n=[],i=!1){if(i)return n;for(let o of this.watcher._poller.stats.keys())Pl.fs.isSubPath(r,o)&&(t.includes(o)||await this.eventsPopulate([o],n,!0));return n}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(gc.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!Y_e&&this.options.native!==!1&&this.watcher.watchDirectory(t,this.options,this.handler,void 0,this.base||this),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAddDir(t,this.options.renameTimeout):this.watcher.event(gc.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(gc.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(nkn.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(gc.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(nkn.default.dirname(t),t,!1),this.watcher.watchersClose(t),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlinkDir(t,this.options.renameTimeout):this.watcher.event(gc.UNLINK_DIR,t))}onTargetEvent(t){let[r,n]=t;r===gc.ADD?this.onTargetAdd(n):r===gc.ADD_DIR?this.onTargetAddDir(n):r===gc.CHANGE?this.onTargetChange(n):r===gc.UNLINK?this.onTargetUnlink(n):r===gc.UNLINK_DIR&&this.onTargetUnlinkDir(n)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,n=!1){return this.handlerBatched(t,r,n)}onWatcherChange(t=lje.CHANGE,r){if(this.watcher.isClosed())return;let n=nkn.default.resolve(this.folderPath,r||"");this.filePath&&n!==this.folderPath&&n!==this.filePath||this.watcher.isIgnored(n,this.options.ignore)||this.onWatcherEvent(t,n)}onWatcherError(t){$ao&&t.code==="EPERM"?this.onWatcherChange(lje.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(hjt.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(hjt.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(lje.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&Y_e&&this.options.native!==!1?this.options.depth??J_e:Math.min(1,this.options.depth??J_e),n=this.options.limit??mjt,[i,o]=await Pl.fs.readdir(this.folderPath,this.options.ignore,r,n,this.watcher._closeSignal,this.options.readdirMap),s=[this.folderPath,...i,...o];await Promise.all(s.map(a=>{if(!this.watcher._poller.stats.has(a)&&!this.watcher.isIgnored(a,this.options.ignore))return this.onWatcherEvent(lje.CHANGE,a,t)}))}}},hLc=Zao;var KR={interval:100,intervalId:void 0,fns:new Map,init:()=>{KR.intervalId||(KR.intervalId=setInterval(KR.resolve,KR.interval))},reset:()=>{KR.intervalId&&(clearInterval(KR.intervalId),delete KR.intervalId)},add:(e,t)=>{KR.fns.set(e,Date.now()+t),KR.init()},remove:e=>{KR.fns.delete(e)},resolve:()=>{if(!KR.fns.size)return KR.reset();let e=Date.now();for(let[t,r]of KR.fns)r>=e||(KR.remove(t),t())}},yjt=KR;var bjt=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=Hao){let{ino:n,targetPath:i,events:o,locks:s}=t,a=()=>{let p=this._watcher._poller.paths.find(n||-1,d=>d!==i);if(p&&p!==i){if(Pl.fs.getRealPath(i,!0)===p)return;this._watcher.event(o.rename,p,i)}else this._watcher.event(o.add,i)};if(!n)return a();let c=()=>{s.add.delete(n),yjt.remove(u)},u=()=>{c(),a()};yjt.add(u,r);let l=()=>{let p=s.unlink.get(n);if(!p)return;c();let d=p();i===d?o.change&&this._watcher._poller.stats.has(i)&&this._watcher.event(o.change,i):this._watcher.event(o.rename,d,i)};s.add.set(n,l),l()}getLockUnlink(t,r=Hao){let{ino:n,targetPath:i,events:o,locks:s}=t,a=()=>{this._watcher.event(o.unlink,i)};if(!n)return a();let c=()=>{s.unlink.delete(n),yjt.remove(u)},u=()=>{c(),a()};yjt.add(u,r);let l=()=>(c(),i);s.unlink.set(n,l),s.add.get(n)?.()}getLockTargetAdd(t,r){let n=this._watcher._poller.getIno(t,gc.ADD,_re.FILE);return this.getLockAdd({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let n=this._watcher._poller.getIno(t,gc.ADD_DIR,_re.DIR);return this.getLockAdd({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let n=this._watcher._poller.getIno(t,gc.UNLINK,_re.FILE);return this.getLockUnlink({ino:n,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let n=this._watcher._poller.getIno(t,gc.UNLINK_DIR,_re.DIR);return this.getLockUnlink({ino:n,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};bjt.DIR_EVENTS={add:gc.ADD_DIR,rename:gc.RENAME_DIR,unlink:gc.UNLINK_DIR};bjt.FILE_EVENTS={add:gc.ADD,change:gc.CHANGE,rename:gc.RENAME,unlink:gc.UNLINK};var gLc=bjt;var eco=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Pl.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let n=this.map.get(t);if(Pl.lang.isSet(n)){let i=n.delete(r);return n.size||this.map.delete(t),i}else if(n===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let n=this.map.get(t);if(Pl.lang.isSet(n))return Array.from(n).find(r);if(r(n))return n}}get(t){return this.map.get(t)}has(t,r){if(Pl.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let n=this.map.get(t);return Pl.lang.isSet(n)?n.has(r):n===r}return!1}set(t,r){if(this.map.has(t)){let n=this.map.get(t);Pl.lang.isSet(n)?n.add(r):n!==r&&this.map.set(t,new Set([n,r]))}else this.map.set(t,r);return this}},tco=eco;var rco=class{constructor(t){this.ino=t.ino<=Number.MAX_SAFE_INTEGER?Number(t.ino):t.ino,this.size=Number(t.size),this.atimeMs=Number(t.atimeMs),this.mtimeMs=Number(t.mtimeMs),this.ctimeMs=Number(t.ctimeMs),this.birthtimeMs=Number(t.birthtimeMs),this._isFile=t.isFile(),this._isDirectory=t.isDirectory(),this._isSymbolicLink=t.isSymbolicLink()}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isSymbolicLink(){return this._isSymbolicLink}},ALc=rco;var nco=class{constructor(){this.inos={},this.paths=new tco,this.stats=new Map}getIno(t,r,n){let i=this.inos[r];if(!i)return;let o=i[t];if(o&&!(n&&o[1]!==n))return o[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let n=await Pl.fs.poll(t,r);if(!(!n||!(n.isFile()||n.isDirectory())))return new ALc(n)}reset(){this.inos={},this.paths=new tco,this.stats=new Map}async update(t,r){let n=this.getStats(t),i=await this.poll(t,r);if(this.updateStats(t,i),!n&&i){if(i.isFile())return this.updateIno(t,gc.ADD,i),[gc.ADD];if(i.isDirectory())return this.updateIno(t,gc.ADD_DIR,i),[gc.ADD_DIR]}else if(n&&!i){if(n.isFile())return this.updateIno(t,gc.UNLINK,n),[gc.UNLINK];if(n.isDirectory())return this.updateIno(t,gc.UNLINK_DIR,n),[gc.UNLINK_DIR]}else if(n&&i){if(n.isFile()){if(i.isFile())return n.ino===i.ino&&!n.size&&!i.size?[]:(this.updateIno(t,gc.CHANGE,i),[gc.CHANGE]);if(i.isDirectory())return this.updateIno(t,gc.UNLINK,n),this.updateIno(t,gc.ADD_DIR,i),[gc.UNLINK,gc.ADD_DIR]}else if(n.isDirectory()){if(i.isFile())return this.updateIno(t,gc.UNLINK_DIR,n),this.updateIno(t,gc.ADD,i),[gc.UNLINK_DIR,gc.ADD];if(i.isDirectory())return n.ino===i.ino?[]:(this.updateIno(t,gc.UNLINK_DIR,n),this.updateIno(t,gc.ADD_DIR,i),[gc.UNLINK_DIR,gc.ADD_DIR])}}return[]}updateIno(t,r,n){let i=this.inos[r]=this.inos[r]||(this.inos[r]={}),o=n.isFile()?_re.FILE:_re.DIR;i[t]=[n.ino,o]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let n=this.stats.get(t)?.ino||-1;this.paths.delete(n,t),this.stats.delete(t)}}},ico=nco;var oco=class e extends yLc.EventEmitter{constructor(t,r,n){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(HR.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(i=>this.on(HR.CLOSE,i)),this._readyWait=new Promise(i=>this.on(HR.READY,i)),this._locker=new gLc(this),this._roots=new Set,this._poller=new ico,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,n)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(Pl.lang.isFunction(r)?!!r(t):r.test(t))}isReady(){return this._ready}close(){return this._locker.reset(),this._poller.reset(),this._roots.clear(),this.watchersClose(),this.isClosed()?!1:(this._closed=!0,this.emit(HR.CLOSE))}error(t){if(this.isClosed())return!1;let r=Pl.lang.castError(t);return this.emit(HR.ERROR,r)}event(t,r,n){return this.isClosed()?!1:(this.emit(HR.ALL,t,r,n),this.emit(t,r,n))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(HR.READY))}pollerExists(t,r){for(let n of this._pollers)if(n.targetPath===t&&Pl.lang.isShallowEqual(n.options,r))return!0;return!1}subwatcherExists(t,r){for(let n of this._subwatchers)if(n.targetPath===t&&Pl.lang.isShallowEqual(n.options,r))return!0;return!1}watchersClose(t,r,n=!0){if(t){let i=this._watchers[t];if(i)for(let o of[...i])r&&o.filePath!==r||this.watcherClose(o);if(n)for(let o in this._watchers)Pl.fs.isSubPath(t,o)&&this.watchersClose(o,r,!1)}else for(let i in this._watchers)this.watchersClose(i,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,n]of t)this.watchPath(r,n.options,n.handler)}async watcherAdd(t,r){let{folderPath:n}=t;(this._watchers[n]=this._watchers[n]||[]).push(t);let o=new hLc(this,t,r);return await o.init(),o}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let o=r.indexOf(t);r.splice(o,1),r.length||delete this._watchers[t.folderPath]}let n=t.filePath||t.folderPath;this._roots.has(n)&&(this._watchersRestorable[n]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=Pl.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,n,i){if(this._watchers[t]?.find(a=>a.handler===n&&(!a.filePath||a.filePath===i)&&a.options.ignore===r.ignore&&!!a.options.native==!!r.native&&(!r.recursive||a.options.recursive)))return!0;let s=pje.default.dirname(t);for(let a=1;a<1/0;a++){if(this._watchers[s]?.find(l=>(a===1||l.options.recursive&&a<=(l.options.depth??J_e))&&l.handler===n&&(!l.filePath||l.filePath===i)&&l.options.ignore===r.ignore&&!!l.options.native==!!r.native&&(!r.recursive||l.options.recursive&&Y_e&&l.options.native!==!1)))return!0;if(!Y_e)break;let u=pje.default.dirname(t);if(s===u)break;s=u}return!1}async watchDirectories(t,r,n,i,o){if(this.isClosed())return;t=Pl.lang.uniq(t).sort();let s;for(let a of t)if(!this.isIgnored(a,r.ignore)&&!this.watcherExists(a,r,n,i))try{let c=!r.recursive||Y_e&&r.native!==!1?r:{...r,recursive:!1},l={watcher:ikn.default.watch(a,c),handler:n,options:r,folderPath:a,filePath:i},p=s=await this.watcherAdd(l,o);if(this._roots.has(i||a)){let f={...r,ignoreInitial:!0,recursive:!1},m=pje.default.dirname(a),h=a;await this.watchDirectories([m],f,n,h,p)}}catch(c){this.error(c)}return s}async watchDirectory(t,r,n,i,o){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||Y_e&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,n,i,o));{r={...r,recursive:!0};let s=r.depth??J_e,a=r.limit??mjt,[c]=await Pl.fs.readdir(t,r.ignore,s,a,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let u=await this.watchDirectories([t],r,n,i,o);if(c.length){let l=Pl.fs.getDepth(t);for(let p of c){let d=Pl.fs.getDepth(p),f=Math.max(0,s-(d-l)),m={...r,depth:f};await this.watchDirectories([p],m,n,i,o||u)}}})}}}async watchFileOnce(t,r,n){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let i={targetPath:t,options:r},o=(u,l)=>{l===t&&(c(),n())},s=new e(o),a=()=>{this._subwatchers.add(i),this.on(HR.CLOSE,c),s.watchFile(t,r,o)},c=()=>{this._subwatchers.delete(i),this.removeListener(HR.CLOSE,c),s.close()};return a()}async watchFile(t,r,n){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let i=pje.default.dirname(t);return this.watchDirectory(i,r,n,t)}async watchPollingOnce(t,r,n){if(this.isClosed())return;let i=!1,o=new ico,s=await this.watchPolling(t,r,async()=>{i||!(await o.update(t,r.pollingTimeout)).length||i||(i=!0,s(),n())})}async watchPolling(t,r,n){if(this.isClosed())return Pl.lang.noop;if(this.pollerExists(t,r))return Pl.lang.noop;let i={...r,interval:r.pollingInterval??nLc},o={targetPath:t,options:r},s=()=>{this._pollers.add(o),this.on(HR.CLOSE,a),ikn.default.watchFile(t,i,n)},a=()=>{this._pollers.delete(o),this.removeListener(HR.CLOSE,a),ikn.default.unwatchFile(t,n)};return Pl.lang.attempt(s),()=>Pl.lang.attempt(a)}async watchUnknownChild(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchFileOnce(t,r,i)}async watchUnknownTarget(t,r,n){if(this.isClosed())return;let i=()=>this.watchPath(t,r,n);return this.watchPollingOnce(t,r,i)}async watchPaths(t,r,n){if(this.isClosed())return;if(t=Pl.lang.uniq(t).sort(),t.every((o,s)=>t.every((a,c)=>c===s||!Pl.fs.isSubPath(o,a))))await Promise.all(t.map(o=>this.watchPath(o,r,n)));else for(let o of t)await this.watchPath(o,r,n)}async watchPath(t,r,n){if(this.isClosed()||(t=pje.default.resolve(t),this.isIgnored(t,r.ignore)))return;let i=await Pl.fs.poll(t,r.pollingTimeout);if(i){if(i.isFile())return this.watchFile(t,r,n);if(i.isDirectory())return this.watchDirectory(t,r,n);this.error(`"${t}" is not supported`)}else{let o=pje.default.dirname(t);return(await Pl.fs.poll(o,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,n):this.watchUnknownTarget(t,r,n)}}async watch(t,r,n=Pl.lang.noop){if(Pl.lang.isFunction(t))return this.watch([],{},t);if(Pl.lang.isUndefined(t))return this.watch([],r,n);if(Pl.lang.isFunction(r))return this.watch(t,{},r);if(Pl.lang.isUndefined(r))return this.watch(t,{},n);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let i=Pl.lang.castArray(t);i.forEach(o=>this._roots.add(o)),await this.watchPaths(i,r,n),!this.isClosed()&&(n!==Pl.lang.noop&&this.on(HR.ALL,n),r.readdirMap=void 0,this.ready())}},okn=oco;Ekn();qt();var ipt=require("fs/promises"),wUc=require("os"),CUc=ye(require("path"),1),$fm=".fern",Hfm="logs";function Kfm(){return"cli@4.48.1"}var Aje=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=We(zt.of((0,wUc.homedir)()),Se.of($fm)),r=We(t,Se.of(Hfm));await er(r)||await(0,ipt.mkdir)(r,{recursive:!0});let i=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=We(r,Se.of(i));let o=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${CUc.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
2200
2200
  `);await(0,ipt.writeFile)(this.logFilePath,o,"utf-8"),this.initialized=!0}getLogFilePath(){return this.logFilePath}async writeEntry(t){if(!this.initialized||!this.logFilePath)return;let r=JSON.stringify(t)+`
2201
2201
  `;try{await(0,ipt.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:Kfm(),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)}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 Sco={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type"};function xUc(e){let t=Jfm();if(t==null)return;let{port:r,debugLogger:n,getDocsLoadResponse:i}=e,o=new Map;function s(c){let u=JSON.stringify(c),l=[];for(let[p]of o)try{p.send(u)}catch{l.push(p)}for(let p of l){let d=o.get(p);d&&(clearInterval(d.pingInterval),o.delete(p))}}let a=t.serve({port:r,fetch(c,u){if(c.method==="OPTIONS")return new Response(null,{status:204,headers:Sco});let l=new URL(c.url);if(c.headers.get("upgrade")?.toLowerCase()==="websocket"){u.upgrade(c,{data:{connectionId:`${Date.now()}`}});return}if(c.method==="POST"&&l.pathname==="/v2/registry/docs/load-with-url")return new Response(JSON.stringify(i()),{headers:{"Content-Type":"application/json",...Sco}});let p=/^\/_local\/(.*)/.exec(l.pathname);return c.method==="GET"&&p!=null?new Response(t.file(`/${p[1]}`),{headers:Sco}):new Response("Not Found",{status:404})},websocket:{open(c){let{connectionId:u}=c.data,l=setInterval(()=>{let p=o.get(c);if(!p)return;let d=Date.now();if(d-p.lastPong>9e4){c.close();return}try{c.send(JSON.stringify({type:"ping",timestamp:d}))}catch{c.close()}},3e4);o.set(c,{pingInterval:l,lastPong:Date.now()});try{c.send(JSON.stringify({type:"connected",connectionId:u}))}catch{}},message(c,u){try{let l=JSON.parse(u.toString());if(l.type==="pong"){let p=o.get(c);p&&(p.lastPong=Date.now())}else Aje.isMetricsMessage(l)&&n.logFrontendMetrics(l)}catch{}},close(c){let u=o.get(c);u&&(clearInterval(u.pingInterval),o.delete(c))}}});return{sendData:s,stop:c=>a.stop(c)}}function Jfm(){return globalThis.Bun}qt();var alo=ye(Nco(),1),BVc=ye(Kuo(),1),K2=require("fs/promises"),TVc=require("os"),OVc=ye(tx(),1),PVc=ye(_Vc(),1),DNn=process.platform==="win32",slo=ve.cyan("[docs]:"),_Am="etag",SAm=23,SVc=e=>e.padEnd(SAm," "),BAm="preview",TAm="app-preview",OAm="bundle",PAm=".next",DAm="standalone",RAm=".fern",FAm="packages/fern-docs/bundle/.next/server/instrumentation.js",kAm=".npmrc",NAm=".pnpmfile.cjs",QAm="pnpm-workspace.yaml",jAm='Cannot find matching keyid: {"signatures":';function MAm(){return We(zt.of((0,TVc.homedir)()),Se.of(RAm))}function Ipt({app:e=!1}){return We(MAm(),Se.of(e?TAm:BAm))}function cSe({app:e=!1}){return We(Ipt({app:e}),Se.of(e?PAm:OAm))}function Yjt({app:e=!1}){return We(cSe({app:e}),Se.of(DAm))}function LAm({app:e=!1}){return We(Yjt({app:e}),Se.of(FAm))}function UAm({app:e=!1}){return We(Yjt({app:e}),Se.of(QAm))}function zAm({app:e=!1}){return We(Yjt({app:e}),Se.of(NAm))}function VAm({app:e=!1}){return We(Yjt({app:e}),Se.of(kAm))}function _je(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function qAm({app:e=!1}){return We(Ipt({app:e}),Se.of(_Am))}var GAm=`module.exports = {
2202
2202
  hooks: {
@@ -2237,7 +2237,7 @@ Please ensure you have membership at https://dashboard.buildwithfern.com, and as
2237
2237
 
2238
2238
  Please ensure you have membership at https://dashboard.buildwithfern.com, and ask a team member for an invite if not.`);case"UnavailableError":return t.failAndThrow("Failed to publish docs. Please try again later or reach out to Fern support at support@buildwithfern.com.");default:return t.failAndThrow("Failed to publish docs.",e)}}function Q0m(e,t){let n=e?.content;if(n?.reason==="status-code"){let i=n.statusCode;if(i===401||i===403)return`${`You do not have permission to publish docs to organization '${t}'. Please run 'fern login' to ensure you are logged in with the correct account.`}
2239
2239
 
2240
- Please ensure you have membership at https://dashboard.buildwithfern.com, and ask a team member for an invite if not.`}}function j0m(e){try{return new URL(LR(e)).pathname}catch{return}}async function M0m({fdr:e,workspace:t,organization:r,context:n,snippetsConfig:i}){if(!t)return;let o=await L0m({fdr:e,workspace:t,snippetsConfig:i,context:n});if(Object.keys(o).length===0){n.logger.debug("[SDK Dynamic IR] No snippet configs found, skipping S3 check");return}try{let s=await e.api.v1.register.checkSdkDynamicIrExists({orgId:Sr.OrgId(r),snippetConfiguration:o});if(!s.ok||!s.body){n.logger.debug("[SDK Dynamic IR] API call failed or returned empty body");return}let a=s.body.existingDynamicIrs;if(Object.keys(a).length===0){n.logger.debug("[SDK Dynamic IR] No existing SDK dynamic IRs found in S3");return}let c={};for(let[u,l]of Object.entries(a))try{n.logger.debug(`Downloading existing SDK dynamic IR for ${u}...`);let p=await fetch(l.downloadUrl);if(p.ok){let d=await p.json();c[u]={dynamicIR:d},n.logger.debug(`Successfully downloaded SDK dynamic IR for ${u}`)}else n.logger.warn(`Failed to download SDK dynamic IR for ${u}: ${p.status}`)}catch(p){n.logger.warn(`Error downloading SDK dynamic IR for ${u}: ${p}`)}return Object.keys(c).length>0?c:void 0}catch(s){n.logger.debug(`Error checking for existing SDK dynamic IRs: ${s}`);return}}function yqc(e){return e.replace(/^https:\/\//,"")}async function L0m({fdr:e,workspace:t,snippetsConfig:r,context:n}){let i={},o=[{language:"typescript",snippetName:r.typescriptSdk?.package,explicitVersion:r.typescriptSdk?.version},{language:"python",snippetName:r.pythonSdk?.package,explicitVersion:r.pythonSdk?.version},{language:"java",snippetName:r.javaSdk?.coordinate,explicitVersion:r.javaSdk?.version},{language:"go",snippetName:r.goSdk?.githubRepo&&yqc(r.goSdk?.githubRepo),explicitVersion:r.goSdk?.version},{language:"csharp",snippetName:r.csharpSdk?.package,explicitVersion:r.csharpSdk?.version},{language:"ruby",snippetName:r.rubySdk?.gem,explicitVersion:r.rubySdk?.version},{language:"php",snippetName:r.phpSdk?.package,explicitVersion:r.phpSdk?.version},{language:"swift",snippetName:r.swiftSdk?.package,explicitVersion:r.swiftSdk?.version},{language:"rust",snippetName:r.rustSdk?.package,explicitVersion:r.rustSdk?.version}];for(let s of o){if(!s.snippetName)continue;let a=s.explicitVersion;a||(a=(await U0m({fdr:e,workspace:t,language:s.language,snippetName:s.snippetName,context:n}))?.version),i[s.language]={packageName:s.snippetName,version:a},a||n.logger.debug(`[SDK Dynamic IR] ${s.language}: no version specified, will use latest`)}return i}async function U0m({fdr:e,workspace:t,language:r,snippetName:n,context:i}){let o;switch(r){case"csharp":o="Csharp";break;case"go":o="Go";break;case"java":o="Java";break;case"python":o="Python";break;case"ruby":o="Ruby";break;case"typescript":o="TypeScript";break;case"php":o="Php";break;case"swift":o="Swift";break;default:return}let s,a,c;if(t.generatorsConfiguration?.groups){let u=[];for(let l of t.generatorsConfiguration.groups)for(let p of l.generators)if(p.language===r){let d=In.getPackageName({generatorInvocation:p});d&&u.push(d),!a&&d&&(a=d,c=p.name,p.outputMode.type==="githubV2"&&(s=`${p.outputMode.githubV2.owner}/${p.outputMode.githubV2.repo}`))}}if(!a){i.logger.debug(`[SDK Dynamic IR] ${r}: no generator found with a package name`);return}try{let u=await e.sdks.versions.computeSemanticVersion({githubRepository:s,language:o,package:a});if(!u.ok){i.logger.debug(`[SDK Dynamic IR] ${r}: version computation failed for package "${a}"`);return}return i.logger.debug(`[SDK Dynamic IR] ${r}: computed version ${u.body.version} for package "${a}"`),{version:u.body.version,generatorPackage:a}}catch(u){i.logger.debug(`[SDK Dynamic IR] ${r}: error computing version: ${u}`);return}}async function z0m({workspace:e,organization:t,context:r,snippetsConfig:n,skipLanguages:i=new Set}){let o={};if(!e)return;let s={typescript:n.typescriptSdk?.package,python:n.pythonSdk?.package,java:n.javaSdk?.coordinate,go:n.goSdk?.githubRepo&&yqc(n.goSdk?.githubRepo),csharp:n.csharpSdk?.package,ruby:n.rubySdk?.gem,php:n.phpSdk?.package,swift:n.swiftSdk?.package,rust:n.rustSdk?.package};if(e.generatorsConfiguration?.groups)for(let a of e.generatorsConfiguration.groups)for(let c of a.generators){let u=Sje({apiName:e.workspaceName??"",organization:t,generatorInvocation:c}),l="";if(u?.outputConfig.type==="publish")switch(u.outputConfig.value.type){case"npm":case"nuget":case"pypi":case"rubygems":l=u.outputConfig.value.packageName;break;case"maven":l=u.outputConfig.value.coordinate;break;case"go":l=u.outputConfig.value.repoUrl;break;case"swift":l=u.outputConfig.value.repoUrl;break;case"crates":l=u.outputConfig.value.packageName;break}if(c.language==="php"&&c.config&&typeof c.config=="object"&&"packageName"in c.config&&(l=c.config.packageName??""),!!c.language){if(i.has(c.language)){r.logger.debug(`Skipping dynamic IR generation for ${c.language} (using existing SDK dynamic IR)`);continue}if(c.language&&s[c.language]===l){let p=jh({workspace:e,generationLanguage:c.language,keywords:void 0,smartCasing:c.smartCasing,exampleGeneration:{disabled:!0,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},audiences:{type:"all"},readme:void 0,packageName:l,version:void 0,context:r,sourceResolver:new km(r,e),dynamicGeneratorConfig:u}),d=wFe({ir:p,disableExamples:!0,smartCasing:c.smartCasing,generationLanguage:c.language,generatorConfig:u});d?o[c.language]={dynamicIR:d}:r.logger.debug(`Failed to create dynamic IR for ${c.language}`)}}}for(let[a,c]of Object.entries(s))a&&c&&!Object.keys(o).includes(a)&&!i.has(a)&&(r.logger.warn(),r.logger.warn(`Failed to upload ${a} SDK snippets because of unknown package \`${c}\`.`),r.logger.warn(`Please make sure your ${e.workspaceName?`${e.workspaceName}/`:""}generators.yml has a generator that publishes a ${c} package.`),r.logger.warn());if(Object.keys(o).length>0)return o}async function V0m({dynamicIRs:e,dynamicIRUploadUrls:t,context:r,apiId:n}){if(Object.keys(t).length>0)for(let[i,o]of Object.entries(t)){let s=e[i]?.dynamicIR;if(s){let a=JSON.stringify(s);(await fetch(o.uploadUrl,{method:"PUT",body:a,headers:{"Content-Type":"application/octet-stream","Content-Length":Buffer.byteLength(a,"utf8").toString()}})).ok?r.logger.debug(`Uploaded dynamic IR for ${n}:${i}`):r.logger.warn(`Failed to upload dynamic IR for ${n}:${i}`)}else r.logger.warn(`Could not find matching dynamic IR to upload for ${n}:${i}`)}}async function q0m({docsDefinition:e,isPreview:t,context:r}){e.config.aiChatConfig==null||t||r.logger.warn(ve.yellow("Enabling Ask Fern from docs.yml is deprecated. Please enable it from the Fern dashboard instead."))}function G0m(e,t){if(e)return{enabled:!0,model:process.env.FERN_AI_MODEL||"gpt-4o-mini",maxRetries:parseInt(process.env.FERN_AI_MAX_RETRIES||"3"),requestTimeoutMs:parseInt(process.env.FERN_AI_TIMEOUT_MS||"25000"),styleInstructions:t}}function W0m(e){let t=e,r=t?.content;return{errorType:t?.error,statusCode:t?.statusCode??r?.statusCode,reason:r?.reason,errorMessage:r?.errorMessage??r?.message,body:r?.body,cause:r?.cause,rawError:e}}var oMt=[60*1e3,300*1e3,300*1e3];async function sMt({organization:e,apiWorkspaces:t,ossWorkspaces:r,docsWorkspace:n,context:i,token:o,instanceUrl:s,preview:a,previewId:c,disableTemplates:u,skipUpload:l,cliVersion:p,ciSource:d}){let f=a&&!n.config.settings?.substituteEnvVars;n.config=Zy(n.config,{onError:b=>i.failAndThrow(b)},{substituteAsEmpty:f});let m=n.config.instances;if(m.length===0){i.failAndThrow("No instances specified in docs.yml! Cannot register docs.");return}if(m.length>1&&s==null){i.failAndThrow(`More than one docs instances. Please specify one (e.g. --instance ${m[0]?.url})`);return}let h=m.find(b=>b.url===s)??m[0];if(h==null){i.failAndThrow(`No docs instance with url ${s}. Failed to register.`);return}let g=[];h.customDomain!=null&&(typeof h.customDomain=="string"?g.push(h.customDomain):Array.isArray(h.customDomain)&&g.push(...h.customDomain)),i.logger.info(`Starting docs publishing for ${a?"preview":"production"}: ${h.url}`),i.logger.debug(`Organization: ${e}, Preview: ${a}, APIs: ${t.length}, OSS: ${r.length}`);let A;return await i.runInteractiveTask({name:h.url},async()=>{let b=performance.now(),v=()=>Aqc({docsWorkspace:n,customDomains:g,domain:h.url,token:o,organization:e,context:i,apiWorkspaces:t,ossWorkspaces:r,preview:a,previewId:c,editThisPage:h.editThisPage,isPrivate:h.private,disableTemplates:u,skipUpload:l,withAiExamples:n.config.aiExamples?.enabled??n.config.experimental?.aiExamples??!0,excludeApis:n.config.experimental?.excludeApis??!1,targetAudiences:h.audiences?Array.isArray(h.audiences)?h.audiences:[h.audiences]:void 0,docsUrl:h.url,cliVersion:p,ciSource:d});for(let I=0;;I++)try{A=await v();break}catch(w){if(!(w instanceof _pt)||I>=oMt.length){if(w instanceof _pt)return i.failAndThrow("Another docs publish is currently in progress. Please try again once the other publish is complete.");throw w}let x=oMt[I]??oMt[oMt.length-1]??6e4,C=x/6e4;i.logger.warn(`Another docs publish is in progress. Retrying in ${C} minute${C===1?"":"s"} (attempt ${I+1}/${oMt.length})...`),await new Promise(_=>setTimeout(_,x))}let E=performance.now()-b;i.logger.debug(`Docs publishing completed in ${E.toFixed(0)}ms`)}),A}var B2n=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,skipUpload:n}){let i=new Vh({context:this.context,task:this.task});try{let o=await sMt({organization:this.project.config.organization,apiWorkspaces:this.project.apiWorkspaces,ossWorkspaces:this.ossWorkspaces,docsWorkspace:this.docsWorkspace,context:i,token:this.token,instanceUrl:t,preview:r,previewId:void 0,disableTemplates:void 0,skipUpload:n,cliVersion:"4.48.0"});return i.getResult()===rf.Failure?{success:!1}:{success:!0,url:o}}catch(o){return{success:!1,error:Ti(o)}}}};St();var Spt=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(`
2240
+ Please ensure you have membership at https://dashboard.buildwithfern.com, and ask a team member for an invite if not.`}}function j0m(e){try{return new URL(LR(e)).pathname}catch{return}}async function M0m({fdr:e,workspace:t,organization:r,context:n,snippetsConfig:i}){if(!t)return;let o=await L0m({fdr:e,workspace:t,snippetsConfig:i,context:n});if(Object.keys(o).length===0){n.logger.debug("[SDK Dynamic IR] No snippet configs found, skipping S3 check");return}try{let s=await e.api.v1.register.checkSdkDynamicIrExists({orgId:Sr.OrgId(r),snippetConfiguration:o});if(!s.ok||!s.body){n.logger.debug("[SDK Dynamic IR] API call failed or returned empty body");return}let a=s.body.existingDynamicIrs;if(Object.keys(a).length===0){n.logger.debug("[SDK Dynamic IR] No existing SDK dynamic IRs found in S3");return}let c={};for(let[u,l]of Object.entries(a))try{n.logger.debug(`Downloading existing SDK dynamic IR for ${u}...`);let p=await fetch(l.downloadUrl);if(p.ok){let d=await p.json();c[u]={dynamicIR:d},n.logger.debug(`Successfully downloaded SDK dynamic IR for ${u}`)}else n.logger.warn(`Failed to download SDK dynamic IR for ${u}: ${p.status}`)}catch(p){n.logger.warn(`Error downloading SDK dynamic IR for ${u}: ${p}`)}return Object.keys(c).length>0?c:void 0}catch(s){n.logger.debug(`Error checking for existing SDK dynamic IRs: ${s}`);return}}function yqc(e){return e.replace(/^https:\/\//,"")}async function L0m({fdr:e,workspace:t,snippetsConfig:r,context:n}){let i={},o=[{language:"typescript",snippetName:r.typescriptSdk?.package,explicitVersion:r.typescriptSdk?.version},{language:"python",snippetName:r.pythonSdk?.package,explicitVersion:r.pythonSdk?.version},{language:"java",snippetName:r.javaSdk?.coordinate,explicitVersion:r.javaSdk?.version},{language:"go",snippetName:r.goSdk?.githubRepo&&yqc(r.goSdk?.githubRepo),explicitVersion:r.goSdk?.version},{language:"csharp",snippetName:r.csharpSdk?.package,explicitVersion:r.csharpSdk?.version},{language:"ruby",snippetName:r.rubySdk?.gem,explicitVersion:r.rubySdk?.version},{language:"php",snippetName:r.phpSdk?.package,explicitVersion:r.phpSdk?.version},{language:"swift",snippetName:r.swiftSdk?.package,explicitVersion:r.swiftSdk?.version},{language:"rust",snippetName:r.rustSdk?.package,explicitVersion:r.rustSdk?.version}];for(let s of o){if(!s.snippetName)continue;let a=s.explicitVersion;a||(a=(await U0m({fdr:e,workspace:t,language:s.language,snippetName:s.snippetName,context:n}))?.version),i[s.language]={packageName:s.snippetName,version:a},a||n.logger.debug(`[SDK Dynamic IR] ${s.language}: no version specified, will use latest`)}return i}async function U0m({fdr:e,workspace:t,language:r,snippetName:n,context:i}){let o;switch(r){case"csharp":o="Csharp";break;case"go":o="Go";break;case"java":o="Java";break;case"python":o="Python";break;case"ruby":o="Ruby";break;case"typescript":o="TypeScript";break;case"php":o="Php";break;case"swift":o="Swift";break;default:return}let s,a,c;if(t.generatorsConfiguration?.groups){let u=[];for(let l of t.generatorsConfiguration.groups)for(let p of l.generators)if(p.language===r){let d=In.getPackageName({generatorInvocation:p});d&&u.push(d),!a&&d&&(a=d,c=p.name,p.outputMode.type==="githubV2"&&(s=`${p.outputMode.githubV2.owner}/${p.outputMode.githubV2.repo}`))}}if(!a){i.logger.debug(`[SDK Dynamic IR] ${r}: no generator found with a package name`);return}try{let u=await e.sdks.versions.computeSemanticVersion({githubRepository:s,language:o,package:a});if(!u.ok){i.logger.debug(`[SDK Dynamic IR] ${r}: version computation failed for package "${a}"`);return}return i.logger.debug(`[SDK Dynamic IR] ${r}: computed version ${u.body.version} for package "${a}"`),{version:u.body.version,generatorPackage:a}}catch(u){i.logger.debug(`[SDK Dynamic IR] ${r}: error computing version: ${u}`);return}}async function z0m({workspace:e,organization:t,context:r,snippetsConfig:n,skipLanguages:i=new Set}){let o={};if(!e)return;let s={typescript:n.typescriptSdk?.package,python:n.pythonSdk?.package,java:n.javaSdk?.coordinate,go:n.goSdk?.githubRepo&&yqc(n.goSdk?.githubRepo),csharp:n.csharpSdk?.package,ruby:n.rubySdk?.gem,php:n.phpSdk?.package,swift:n.swiftSdk?.package,rust:n.rustSdk?.package};if(e.generatorsConfiguration?.groups)for(let a of e.generatorsConfiguration.groups)for(let c of a.generators){let u=Sje({apiName:e.workspaceName??"",organization:t,generatorInvocation:c}),l="";if(u?.outputConfig.type==="publish")switch(u.outputConfig.value.type){case"npm":case"nuget":case"pypi":case"rubygems":l=u.outputConfig.value.packageName;break;case"maven":l=u.outputConfig.value.coordinate;break;case"go":l=u.outputConfig.value.repoUrl;break;case"swift":l=u.outputConfig.value.repoUrl;break;case"crates":l=u.outputConfig.value.packageName;break}if(c.language==="php"&&c.config&&typeof c.config=="object"&&"packageName"in c.config&&(l=c.config.packageName??""),!!c.language){if(i.has(c.language)){r.logger.debug(`Skipping dynamic IR generation for ${c.language} (using existing SDK dynamic IR)`);continue}if(c.language&&s[c.language]===l){let p=jh({workspace:e,generationLanguage:c.language,keywords:void 0,smartCasing:c.smartCasing,exampleGeneration:{disabled:!0,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},audiences:{type:"all"},readme:void 0,packageName:l,version:void 0,context:r,sourceResolver:new km(r,e),dynamicGeneratorConfig:u}),d=wFe({ir:p,disableExamples:!0,smartCasing:c.smartCasing,generationLanguage:c.language,generatorConfig:u});d?o[c.language]={dynamicIR:d}:r.logger.debug(`Failed to create dynamic IR for ${c.language}`)}}}for(let[a,c]of Object.entries(s))a&&c&&!Object.keys(o).includes(a)&&!i.has(a)&&(r.logger.warn(),r.logger.warn(`Failed to upload ${a} SDK snippets because of unknown package \`${c}\`.`),r.logger.warn(`Please make sure your ${e.workspaceName?`${e.workspaceName}/`:""}generators.yml has a generator that publishes a ${c} package.`),r.logger.warn());if(Object.keys(o).length>0)return o}async function V0m({dynamicIRs:e,dynamicIRUploadUrls:t,context:r,apiId:n}){if(Object.keys(t).length>0)for(let[i,o]of Object.entries(t)){let s=e[i]?.dynamicIR;if(s){let a=JSON.stringify(s);(await fetch(o.uploadUrl,{method:"PUT",body:a,headers:{"Content-Type":"application/octet-stream","Content-Length":Buffer.byteLength(a,"utf8").toString()}})).ok?r.logger.debug(`Uploaded dynamic IR for ${n}:${i}`):r.logger.warn(`Failed to upload dynamic IR for ${n}:${i}`)}else r.logger.warn(`Could not find matching dynamic IR to upload for ${n}:${i}`)}}async function q0m({docsDefinition:e,isPreview:t,context:r}){e.config.aiChatConfig==null||t||r.logger.warn(ve.yellow("Enabling Ask Fern from docs.yml is deprecated. Please enable it from the Fern dashboard instead."))}function G0m(e,t){if(e)return{enabled:!0,model:process.env.FERN_AI_MODEL||"gpt-4o-mini",maxRetries:parseInt(process.env.FERN_AI_MAX_RETRIES||"3"),requestTimeoutMs:parseInt(process.env.FERN_AI_TIMEOUT_MS||"25000"),styleInstructions:t}}function W0m(e){let t=e,r=t?.content;return{errorType:t?.error,statusCode:t?.statusCode??r?.statusCode,reason:r?.reason,errorMessage:r?.errorMessage??r?.message,body:r?.body,cause:r?.cause,rawError:e}}var oMt=[60*1e3,300*1e3,300*1e3];async function sMt({organization:e,apiWorkspaces:t,ossWorkspaces:r,docsWorkspace:n,context:i,token:o,instanceUrl:s,preview:a,previewId:c,disableTemplates:u,skipUpload:l,cliVersion:p,ciSource:d}){let f=a&&!n.config.settings?.substituteEnvVars;n.config=Zy(n.config,{onError:b=>i.failAndThrow(b)},{substituteAsEmpty:f});let m=n.config.instances;if(m.length===0){i.failAndThrow("No instances specified in docs.yml! Cannot register docs.");return}if(m.length>1&&s==null){i.failAndThrow(`More than one docs instances. Please specify one (e.g. --instance ${m[0]?.url})`);return}let h=m.find(b=>b.url===s)??m[0];if(h==null){i.failAndThrow(`No docs instance with url ${s}. Failed to register.`);return}let g=[];h.customDomain!=null&&(typeof h.customDomain=="string"?g.push(h.customDomain):Array.isArray(h.customDomain)&&g.push(...h.customDomain)),i.logger.info(`Starting docs publishing for ${a?"preview":"production"}: ${h.url}`),i.logger.debug(`Organization: ${e}, Preview: ${a}, APIs: ${t.length}, OSS: ${r.length}`);let A;return await i.runInteractiveTask({name:h.url},async()=>{let b=performance.now(),v=()=>Aqc({docsWorkspace:n,customDomains:g,domain:h.url,token:o,organization:e,context:i,apiWorkspaces:t,ossWorkspaces:r,preview:a,previewId:c,editThisPage:h.editThisPage,isPrivate:h.private,disableTemplates:u,skipUpload:l,withAiExamples:n.config.aiExamples?.enabled??n.config.experimental?.aiExamples??!0,excludeApis:n.config.experimental?.excludeApis??!1,targetAudiences:h.audiences?Array.isArray(h.audiences)?h.audiences:[h.audiences]:void 0,docsUrl:h.url,cliVersion:p,ciSource:d});for(let I=0;;I++)try{A=await v();break}catch(w){if(!(w instanceof _pt)||I>=oMt.length){if(w instanceof _pt)return i.failAndThrow("Another docs publish is currently in progress. Please try again once the other publish is complete.");throw w}let x=oMt[I]??oMt[oMt.length-1]??6e4,C=x/6e4;i.logger.warn(`Another docs publish is in progress. Retrying in ${C} minute${C===1?"":"s"} (attempt ${I+1}/${oMt.length})...`),await new Promise(_=>setTimeout(_,x))}let E=performance.now()-b;i.logger.debug(`Docs publishing completed in ${E.toFixed(0)}ms`)}),A}var B2n=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,skipUpload:n}){let i=new Vh({context:this.context,task:this.task});try{let o=await sMt({organization:this.project.config.organization,apiWorkspaces:this.project.apiWorkspaces,ossWorkspaces:this.ossWorkspaces,docsWorkspace:this.docsWorkspace,context:i,token:this.token,instanceUrl:t,preview:r,previewId:void 0,disableTemplates:void 0,skipUpload:n,cliVersion:"4.48.1"});return i.getResult()===rf.Failure?{success:!1}:{success:!0,url:o}}catch(o){return{success:!1,error:Ti(o)}}}};St();var Spt=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(`
2241
2241
  `),this.stream.write(`${ve.cyan("\u25C6")} ${ve.bold(t.title)}
2242
2242
  `),t.subtitle!=null&&this.stream.write(` ${ve.dim(t.subtitle)}
2243
2243
  `),this.stream.write(`
@@ -3638,7 +3638,7 @@ For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides
3638
3638
  Run ${ve.cyan("fern generator upgrade")} to upgrade your generators.`),i.length>2&&(r+=`
3639
3639
  Run ${ve.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),lJe(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function djo({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:n=!0}){if(!q_u(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+=`
3640
3640
  ${await UNh(a.generatorName)} (${a.apiName!=null?"API: "+a.apiName+", ":""}Group: ${a.generatorGroup}) `+ve.dim(a.currentVersion)+ve.reset(" \u2192 ")+ve.green(a.latestVersion);return i+=`
3641
- `,n?lJe(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function UNh(e){let r=await new V_u.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new Error(`Generator ${e} not found`);return r.body.displayName}async function zNh({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){if(t.length===1){let a={type:"singleApi",versions:{}};return await W_u({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,u,l,p)=>{a.versions[u]==null&&(a.versions[u]={});let d=QRe(l.name);if(d==null){p.logger.debug(`Skipping unknown generator: ${l.name}`);return}let f=await RT({generatorName:d,cliVersion:e.environment.packageVersion,currentGeneratorVersion:l.version,channel:i,includeMajor:o,context:p});f!=null&&(a.versions[u][l.name]={previousVersion:l.version,latestVersion:f})},generatorFilter:r,groupFilter:n}),a}let s={type:"multiApi",versions:{}};return await W_u({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(a,c,u,l)=>{if(a==null)return;s.versions[a]==null&&(s.versions[a]={}),s.versions[a][c]==null&&(s.versions[a][c]={});let p=QRe(u.name);if(p==null){l.logger.debug(`Skipping unknown generator: ${u.name}`);return}let d=await RT({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:i,includeMajor:o,context:l});d!=null&&(s.versions[a][c][u.name]={previousVersion:u.version,latestVersion:d})},generatorFilter:r,groupFilter:n}),s}async function W_u({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 Vj({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?qx(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 $_u(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=lN(a.latestVersion,a.previousVersion);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 PGn({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){let s=[];if(e!=null){let a=await zNh({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o});if(a.type==="multiApi")for(let[c,u]of Object.entries(a.versions))s.push(...$_u(u,c,t.logger));else s.push(...$_u(a.versions,void 0,t.logger))}return s}async function Ide({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:zEt(e.packageName,{version:t?"prerelease":"latest"})}var H_u=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],DGn=class{environment;sentryClient;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=$n.Info;isLocal;stdoutRedirector=new OGn;jsonMode=!1;constructor(t,r,{isLocal:n}){this.ttyAwareLogger=new jFe(t,r),this.isLocal=n??!1;let i=this.getPackageName(),o=this.getPackageVersion(),s=this.getCliName();(i==null||o==null||s==null)&&this.exitProgram(),this.environment={packageName:i,packageVersion:o,cliName:s},this.sentryClient=new TGn({release:`cli@${this.environment.packageVersion}`})}getPackageName(){return"fern-api"}getPackageVersion(){return"4.48.0"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${ve.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new Bm}failWithoutThrowing(t,r){this.didSucceed=!1,F1t({message:t,error:r,logger:this.logger})}enableJsonMode(){this.jsonMode||(this.jsonMode=!0,this.stdoutRedirector.redirect())}get isJsonMode(){return this.jsonMode}writeJsonToStdout(t){this.stdoutRedirector.restore(),process.stdout.write(JSON.stringify(t,null,2)+`
3641
+ `,n?lJe(i,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):i}async function UNh(e){let r=await new V_u.FernRegistryClient({environment:"https://registry.buildwithfern.com"}).generators.getGeneratorByImage({dockerImage:e});if(!r.ok||r.body==null)throw new Error(`Generator ${e} not found`);return r.body.displayName}async function zNh({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){if(t.length===1){let a={type:"singleApi",versions:{}};return await W_u({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,u,l,p)=>{a.versions[u]==null&&(a.versions[u]={});let d=QRe(l.name);if(d==null){p.logger.debug(`Skipping unknown generator: ${l.name}`);return}let f=await RT({generatorName:d,cliVersion:e.environment.packageVersion,currentGeneratorVersion:l.version,channel:i,includeMajor:o,context:p});f!=null&&(a.versions[u][l.name]={previousVersion:l.version,latestVersion:f})},generatorFilter:r,groupFilter:n}),a}let s={type:"multiApi",versions:{}};return await W_u({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(a,c,u,l)=>{if(a==null)return;s.versions[a]==null&&(s.versions[a]={}),s.versions[a][c]==null&&(s.versions[a][c]={});let p=QRe(u.name);if(p==null){l.logger.debug(`Skipping unknown generator: ${u.name}`);return}let d=await RT({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:i,includeMajor:o,context:l});d!=null&&(s.versions[a][c][u.name]={previousVersion:u.version,latestVersion:d})},generatorFilter:r,groupFilter:n}),s}async function W_u({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 Vj({absolutePathToWorkspace:o.absoluteFilePath,context:s});if(a==null||a.groups==null)return;let c=n!=null?qx(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 $_u(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=lN(a.latestVersion,a.previousVersion);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 PGn({project:e,cliContext:t,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o}){let s=[];if(e!=null){let a=await zNh({cliContext:t,project:e,generatorFilter:r,groupFilter:n,channel:i,includeMajor:o});if(a.type==="multiApi")for(let[c,u]of Object.entries(a.versions))s.push(...$_u(u,c,t.logger));else s.push(...$_u(a.versions,void 0,t.logger))}return s}async function Ide({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:zEt(e.packageName,{version:t?"prerelease":"latest"})}var H_u=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],DGn=class{environment;sentryClient;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=$n.Info;isLocal;stdoutRedirector=new OGn;jsonMode=!1;constructor(t,r,{isLocal:n}){this.ttyAwareLogger=new jFe(t,r),this.isLocal=n??!1;let i=this.getPackageName(),o=this.getPackageVersion(),s=this.getCliName();(i==null||o==null||s==null)&&this.exitProgram(),this.environment={packageName:i,packageVersion:o,cliName:s},this.sentryClient=new TGn({release:`cli@${this.environment.packageVersion}`})}getPackageName(){return"fern-api"}getPackageVersion(){return"4.48.1"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${ve.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new Bm}failWithoutThrowing(t,r){this.didSucceed=!1,F1t({message:t,error:r,logger:this.logger})}enableJsonMode(){this.jsonMode||(this.jsonMode=!0,this.stdoutRedirector.redirect())}get isJsonMode(){return this.jsonMode}writeJsonToStdout(t){this.stdoutRedirector.restore(),process.stdout.write(JSON.stringify(t,null,2)+`
3642
3642
  `),this.jsonMode&&this.stdoutRedirector.redirect()}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await uJe()).flush(),await this.sentryClient.flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((n,i)=>setTimeout(()=>i("Request timed out"),300))]),r=await G_u({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
3643
3643
  `)||(r+=`
3644
3644
  `),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=fJn(t.map(n=>n.type==="docs"?"docs":n.workspaceName??"api"),n=>n.length);r!=null&&(this.longestWorkspaceName=r)}project;registerProject(t){this.project=t}runTask(t){return this.runTaskWithInit(this.constructTaskInit(),t)}addTask(){return this.addTaskWithInit(this.constructTaskInit())}async runTaskForWorkspace(t,r){await this.runTaskWithInit(this.constructTaskInitForWorkspace(t),r)}addTaskWithInit(t){let r=new J3t(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){throw o.message.includes("globalThis")?(n.logger.error(this.USE_NODE_18_OR_ABOVE_MESSAGE),n.failWithoutThrowing()):n.failWithoutThrowing(void 0,o),new Bm}finally{n.finish()}return i}async instrumentPostHogEvent(t){this.isLocal||(await uJe()).sendEvent(t)}async captureException(t){await this.sentryClient.captureException(t)}logger=sD((t,...r)=>this.log(t,...r));stderr=sD((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=K_u(t.type==="docs"?"docs":t.workspaceName??"api"),n=1+(this.longestWorkspaceName!=null?K_u(this.longestWorkspaceName):r).length,i=r.padEnd(n),o=H_u[this.numTasks++%H_u.length],s=ve.hex(o)(i);return{...this.constructTaskInit(),logPrefix:s}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===rf.Failure&&(this.didSucceed=!1)},instrumentPostHogEvent:async t=>{await this.instrumentPostHogEvent(t)},shouldBufferLogs:!1}}log(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}])}logStderr(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}],{stderr:!0})}logImmediately(t,{stderr:r=!1}={}){let n=t.filter(i=>p1.indexOf(i.level)>=p1.indexOf(this.logLevel));this.ttyAwareLogger.log(n,{includeDebugInfo:this.logLevel===$n.Debug,stderr:r||this.jsonMode})}_suppressUpgradeMessage=!1;suppressUpgradeMessage(){this._suppressUpgradeMessage=!0}_isUpgradeAvailable;async isUpgradeAvailable({includePreReleases:t=!1}={}){if(this._isUpgradeAvailable==null){this.logger.debug(`Checking if ${this.environment.packageName} upgrade is available...`);let r=await Ide({cliEnvironment:this.environment,includePreReleases:t}),n=lN(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(n?"Upgrade available.":"No upgrade available."));let i={isUpgradeAvailable:n,latestVersion:r},o=await PGn({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:i,generatorUpgradeInfo:o}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await pjo({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:ve.yellow("?"),style:{answer:i=>ve.cyan(i),message:i=>ve.bold(i),highlight:i=>ve.cyan(i)}}})}catch(n){throw n?.name==="ExitPromptError"?(this.logger.info(`