fern-api 3.57.1 → 3.58.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.cjs +5 -5
- package/package.json +1 -1
package/cli.cjs
CHANGED
|
@@ -2147,7 +2147,7 @@ ${i.map(a=>` ${a}`).join(`,
|
|
|
2147
2147
|
`)}
|
|
2148
2148
|
]`;case 1:return`${n} Did you mean ${r[0]}?`;case 2:return`${n} Did you mean ${r[0]} or ${r[1]}?`;default:return`${n} Did you mean ${r[0]}, ${r[1]}, or ${r[2]}?`}}function wec(e){return`API section ${e} is specified multiple times, however will be only rendered once.`}function T5x(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}bE();function Eec({children:e,findEndpointById:t,stringifyEndpointPathParts:r,disableEndpointPairs:i,apiDefinitionId:n}){if(i)return e;let a=[],o=new Map;return e.forEach(c=>{if(c.type!=="endpoint"){a.push(c);return}let d=t(c.endpointId);if(d==null)throw new Error(`Endpoint ${c.endpointId} not found`);let s=`${d.method} ${r(d)}`,u=o.get(s);if(o.set(s,c),u==null||u.isResponseStream===c.isResponseStream){a.push(c);return}let f=a.indexOf(u),p=c.isResponseStream?c:u,_=c.isResponseStream?u:c,h={id:Ut.V1.NodeId(`${n}:${_.endpointId}+${p.endpointId}`),type:"endpointPair",stream:p,nonStream:_};a[f]=h}),a}function y1E({left:e,right:t,findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}){return Eec({children:[...e,...t],findEndpointById:r,stringifyEndpointPathParts:i,disableEndpointPairs:n,apiDefinitionId:a}).filter(o=>o.type==="apiPackage"?o.children.length>0||o.overviewPageId!=null:!0)}bE();function S8a(e,t){if(t!=null)return nd(e.absoluteFilePath,t)}function b1E({docsWorkspace:e,page:t,parentSlug:r,idgen:i,markdownFilesToFullSlugs:n,markdownFilesToNoIndex:a,hideChildren:o,resolveIconFileId:c}){let d=Ut.V1.PageId(S8a(e,t.absolutePath)),s=r.apply({fullSlug:n.get(t.absolutePath)?.split("/"),urlSlug:t.slug??q0(t.title)});return{id:i.get(d),type:"page",pageId:d,title:t.title,slug:s.get(),icon:c?c(t.icon):t.icon,hidden:o||t.hidden,noindex:t.noindex||a.get(t.absolutePath),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,availability:t.availability}}var Sec=class{apiSection;docsWorkspace;taskContext;markdownFilesToFullSlugs;markdownFilesToNoIndex;markdownFilesToTags;workspace;hideChildren;parentAvailability;openApiTags;apiDefinitionId;#e;#t=new Set;#r=new Set;#i=new Set;#n=new Set;#a=new Set;#o=new Set;#u=new Map;#s=[];#l;#p;#f;disableEndpointPairs;collectedFileIds=new Map;#d;#c;constructor(t,r,i,n,a,o,c,d,s,u,f,p,_,h,y){this.apiSection=t,this.docsWorkspace=n,this.taskContext=a,this.markdownFilesToFullSlugs=o,this.markdownFilesToNoIndex=c,this.markdownFilesToTags=d,this.workspace=f,this.hideChildren=p,this.parentAvailability=_,this.openApiTags=h,this.#d=new Map,this.#c=y??new Map,this.disableEndpointPairs=n.config.experimental?.disableStreamToggle??!1,this.apiDefinitionId=Ut.V1.ApiDefinitionId(r.id),this.#e=Lhn.create(r,a),this.collectedFileIds=u,this.#f=s,this.#l=this.apiSection.overviewAbsolutePath!=null?Ut.V1.PageId(S8a(this.docsWorkspace,this.apiSection.overviewAbsolutePath)):void 0;let b=this.apiSection.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(this.apiSection.overviewAbsolutePath):void 0;this.#p=i.apply({fullSlug:b?.split("/"),skipUrlSlug:this.apiSection.skipUrlSlug,urlSlug:this.apiSection.slug??q0(this.apiSection.title)});let v=this.apiSection.availability??this.parentAvailability;this.apiSection.navigation!=null&&(this.#s=this.#_(this.apiSection.navigation,this.#e.api.rootPackage,this.#p,v)),this.#s=this.#m(this.#s.map(O=>this.#v(O,v)),this.#P(this.#e.api.rootPackage,this.#p,v))}get(){let t=Ut.V1.followRedirects(this.#s),r=new lea(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.workspace?.changelog?.files.map(n=>n.absoluteFilepath),this.docsWorkspace,this.#f).orUndefined(),i=this.#l;if(i==null){let n=this.#s.find(a=>a.type==="apiPackage"&&a.overviewPageId!=null);n!=null&&(i=n.overviewPageId)}return{id:this.#f.get(this.apiDefinitionId),type:"apiReference",title:this.apiSection.title,apiDefinitionId:this.apiDefinitionId,overviewPageId:i,paginated:this.apiSection.paginated,slug:this.#p.get(),icon:this.resolveIconFileId(this.apiSection.icon),hidden:this.hideChildren||this.apiSection.hidden,hideTitle:this.apiSection.flattened,showErrors:this.apiSection.showErrors,changelog:r?.toChangelogNode({parentSlug:this.#p,viewers:void 0,hidden:this.hideChildren}),children:this.#s,availability:this.apiSection.availability??this.parentAvailability,pointsTo:t,noindex:void 0,playground:this.#h(this.apiSection.playground),postmanCollectionUrl:this.apiSection.postman,authed:void 0,viewers:this.apiSection.viewers,orphaned:this.apiSection.orphaned,featureFlags:this.apiSection.featureFlags}}getTagDescriptionContent(){return this.#d}createTagDescriptionPageId(t){if(!this.apiSection.tagDescriptionPages||!this.openApiTags)return;let r=e$t(t)?t.name:void 0;if(!r)return;let i=this.openApiTags[r];if(!i||!i.description)return;let n=`tag-${r}.md`,a=mr.of(`/${n}`),o=Ut.V1.PageId(n),c=i.description.replace(/\{/g,"\\{").replace(/\}/g,"\\}").replace(/</g,"<").replace(/>/g,">"),d=`# ${Bx(i.id.replace(/[_-]/g," "))}
|
|
2149
2149
|
|
|
2150
|
-
${c}`;return this.#d.set(a,d),this.markdownFilesToNoIndex.set(a,!1),this.markdownFilesToTags.set(a,[r]),o}#_(t,r,i,n){r=this.#e.resolveSubpackage(r);let a=r!=null?Lhn.getSubpackageId(r):void 0;return t.map(o=>Emp(o)._visit({link:c=>({id:this.#f.get(c.url),type:"link",title:c.text,icon:this.resolveIconFileId(c.icon),url:Ut.Url(c.url),target:c.target}),page:c=>this.#y(c,i,n),package:c=>this.#b(c,i,n),section:c=>this.#O(c,i,n),item:({value:c})=>this.#g(c,a,i,n),endpoint:c=>this.#A(c,a,i,n)})).filter(Cs)}#y(t,r,i){return b1E({page:{...t,availability:t.availability??i},parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#f,hideChildren:this.hideChildren,resolveIconFileId:this.resolveIconFileId.bind(this)})}#b(t,r,i){let n=t.overviewAbsolutePath!=null?Ut.V1.PageId(S8a(this.docsWorkspace,t.overviewAbsolutePath)):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,o=t.availability??i,c=this.#e.getSubpackageByIdOrLocator(t.package);if(c!=null){let d=Lhn.getSubpackageId(c),s=this.#f.get(n??`${this.apiDefinitionId}:${d}`);this.#o.has(d)&&this.taskContext.logger.warn(wec(t.package)),this.#o.add(d),this.#u.set(s,[d]);let u=t.slug??(e$t(c)?c.urlSlug:this.apiSection.slug??q0(this.apiSection.title)),f=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),p=this.#_(t.contents,c,f,o);return{id:s,type:"apiPackage",children:p,title:t.title??(e$t(c)?c.displayName??Bx(c.name):this.apiSection.title),slug:f.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:n,availability:o,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#h(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}else{this.taskContext.logger.warn(jec(t.package,this.#e.subpackageLocators));let d=t.slug??q0(t.package),s=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),u=this.#_(t.contents,void 0,s,o);return{id:this.#f.get(n??`${this.apiDefinitionId}:${q0(t.package)}`),type:"apiPackage",children:u,title:t.title??t.package,slug:s.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:n,availability:o,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#h(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#O(t,r,i){let n=t.overviewAbsolutePath!=null?Ut.V1.PageId(S8a(this.docsWorkspace,t.overviewAbsolutePath)):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,o=t.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(t.overviewAbsolutePath):void 0,c=this.#f.get(n??a??r.get()),d=t.referencedSubpackages.map(_=>{let h=this.#e.getSubpackageByIdOrLocator(_),y=h!=null?Lhn.getSubpackageId(h):void 0;if(y===void 0){this.taskContext.logger.error(jec(_,this.#e.subpackageLocators));return}return{subpackageId:y,locator:_}}).filter(_=>_!=null).filter(Cs);this.#u.set(c,d.map(_=>_.subpackageId)),d.forEach(_=>{this.#o.has(_.subpackageId)&&this.taskContext.logger.error(wec(_.locator)),this.#o.add(_.subpackageId)});let s=t.slug??q0(t.title),u=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:s}),f=t.availability??i,p=this.#_(t.contents,void 0,u,f);return{id:c,type:"apiPackage",children:p,title:t.title,slug:u.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:n,availability:f,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:o,playground:this.#h(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#g(t,r,i,n){t=t.trim();let a=this.#e.getSubpackageByIdOrLocator(t)??this.#e.getSubpackageByIdOrLocator(mn(t));if(a!=null){let o=Lhn.getSubpackageId(a),c=this.#f.get(`${this.apiDefinitionId}:${o}`);this.#o.has(o)&&this.taskContext.logger.error(wec(t)),this.#o.add(o),this.#u.set(c,[o]);let d=e$t(a)?a.urlSlug:"",s=i.apply({urlSlug:d});return{id:c,type:"apiPackage",children:[],title:e$t(a)?a.displayName??Bx(a.name):this.apiSection.title,slug:s.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:this.createTagDescriptionPageId(a),availability:n,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}return this.#A({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,availability:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i,n)}#A(t,r,i,n){let a=(r!=null?this.#e.subpackages.get(WB.SubpackageId(r))?.endpoints.get(WB.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(a!=null){let s=this.#e.getEndpointId(a);if(s==null)this.taskContext.logger.debug(`Expected Endpoint ID for ${a.id} at path: ${Pec(a.method,a.path.parts)}. Got undefined.`);else{this.#t.has(s)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${s}`),this.#t.add(s);let u=t.slug!=null?i.append(t.slug):i.apply(a);return{id:this.#f.get(`${this.apiDefinitionId}:${s}`),type:"endpoint",method:a.method,endpointId:s,apiDefinitionId:this.apiDefinitionId,availability:t.availability??Ut.V1.convertAvailability(a.availability)??n,isResponseStream:a.response?.type.type==="stream",title:t.title??a.name??MH(a.path.parts),slug:u.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,playground:this.#h(a.includeInApiExplorer===!1?{...t.playground,hidden:!0}:t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}let o=(r!=null?this.#e.subpackages.get(WB.SubpackageId(r))?.webSockets.get(WB.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(o!=null){let s=this.#e.getWebSocketId(o);if(s==null)this.taskContext.logger.error(`Expected WebSocket ID for ${o.id}. Got undefined.`);else return this.#r.has(s)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${s}`),this.#r.add(s),{id:this.#f.get(`${this.apiDefinitionId}:${s}`),type:"webSocket",webSocketId:s,title:t.title??o.name??MH(o.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(o)).get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:t.availability??Ut.V1.convertAvailability(o.availability)??n,playground:this.#h(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let c=(r!=null?this.#e.subpackages.get(WB.SubpackageId(r))?.webhooks.get(WB.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(Ut.V1.WebhookId(t.endpoint));if(c!=null){let s=this.#e.getWebhookId(c);if(s==null)this.taskContext.logger.error(`Expected Webhook ID for ${c.id}. Got undefined.`);else return this.#i.has(s)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${s}`),this.#i.add(s),{id:this.#f.get(`${this.apiDefinitionId}:${s}`),type:"webhook",webhookId:s,method:c.method,title:t.title??c.name??(0,v1E.default)("/",...c.path),slug:(t.slug!=null?i.append(t.slug):i.apply(c)).get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:t.availability??Ut.V1.convertAvailability(c.availability)??n,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let d=this.#e.api.rootPackage.graphqlOperations?.find(s=>s.id===t.endpoint||s.name===t.endpoint);if(d!=null){let s=WB.GraphQlOperationId(d.id);if(this.#a.has(s)){this.taskContext.logger.error(`Duplicate GraphQL operation found in the API Reference layout: ${s}`);return}this.#a.add(s);let u=t.slug!=null?i.append(t.slug):i.append(d.name??d.id);return{id:this.#f.get(`${this.apiDefinitionId}:${s}`),type:"graphql",operationType:d.operationType,graphqlOperationId:WB.GraphQlOperationId(d.id),apiDefinitionId:this.apiDefinitionId,availability:t.availability??n,title:t.title??d.displayName??d.name??d.id,slug:u.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,playground:this.#h(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#m(t,r){return y1E({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>MH(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#v(t,r){return Dmp({child:t,nodeIdToSubpackageId:this.#u,convertApiDefinitionPackageId:(i,n,a)=>this.#w(i,n,a),mergeAndFilterChildren:this.#m.bind(this)})}#P(t,r,i){let n=[];if(t.endpoints.forEach(a=>{if(a.protocol?.type==="grpc"){let o=this.#e.getGrpcId(a);if(o==null){this.taskContext.logger.error(`Expected Grpc ID for ${a.id} at path: ${Pec(a.method,a.path.parts)}. Got undefined.`);return}if(this.#n.has(o))return;let c=r.apply(a);n.push({id:Ut.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"grpc",grpcId:o,title:a.name??MH(a.path.parts),method:a.protocol?.methodType??"UNARY",apiDefinitionId:this.apiDefinitionId,availability:i,slug:c.get(),icon:void 0,hidden:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}else{let o=this.#e.getEndpointId(a);if(o==null){this.taskContext.logger.debug(`Expected Endpoint ID for ${a.id} at path: ${Pec(a.method,a.path.parts)}. Got undefined.`);return}if(this.#t.has(o))return;let c=r.apply(a);n.push({id:Ut.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"endpoint",method:a.method,endpointId:o,apiDefinitionId:this.apiDefinitionId,availability:Ut.V1.convertAvailability(a.availability)??i,isResponseStream:a.response?.type.type==="stream",title:a.name??MH(a.path.parts),slug:c.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}}),t.websockets.forEach(a=>{let o=this.#e.getWebSocketId(a);if(o==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}this.#r.has(o)||n.push({id:Ut.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"webSocket",webSocketId:o,title:a.name??MH(a.path.parts),slug:r.apply(a).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Ut.V1.convertAvailability(a.availability)??i,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.webhooks.forEach(a=>{let o=this.#e.getWebhookId(a);if(o==null){this.taskContext.logger.error(`Expected Webhook ID for ${a.id}. Got undefined.`);return}this.#i.has(o)||n.push({id:Ut.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"webhook",webhookId:o,method:a.method,title:a.name??Bx(a.id),slug:r.apply(a).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Ut.V1.convertAvailability(a.availability)??i,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(a=>{if(this.#o.has(a))return;let o=this.#e.getSubpackageByIdOrLocator(a);if(o==null){this.taskContext.logger.error(`Subpackage ${a} not found in ${this.apiDefinitionId}`);return}let c=e$t(o)?r.apply(o):r,d=this.#w(a,c,i),s=this.createTagDescriptionPageId(o),u=this.#e.subpackages.get(WB.SubpackageId(a)),f=u?Array.from(u.endpoints.values()).some(p=>{let _=this.#e.getEndpointId(p);return _!=null&&this.#t.has(_)}):!1;(d.length>0||s!=null&&f)&&n.push({id:Ut.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"apiPackage",children:d,title:e$t(o)?o.displayName??Bx(o.name):this.apiSection.title,slug:c.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:s,availability:i,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.graphqlOperations!=null&&t.graphqlOperations.length>0){let a=this.#j(t.graphqlOperations,r,i);n.push(...a)}return n=this.mergeEndpointPairs(n),this.apiSection.alphabetized&&(n=n.sort((a,o)=>{let c=a.type==="endpointPair"?a.nonStream.title:a.title,d=o.type==="endpointPair"?o.nonStream.title:o.title;return c.localeCompare(d)})),n}#j(t,r,i){let n={},a={};for(let s of t){let u=WB.GraphQlOperationId(s.id);if(this.#a.has(u))continue;this.#a.add(u);let f=this.#c.get(Jr.GraphQlOperationId(s.id)),p=s.operationType;f!=null?(n[f]==null&&(n[f]={}),n[f][p]==null&&(n[f][p]=[]),n[f][p].push(s)):(a[p]==null&&(a[p]=[]),a[p].push(s))}let o=[],c=["QUERY","MUTATION","SUBSCRIPTION"],d={QUERY:"Queries",MUTATION:"Mutations",SUBSCRIPTION:"Subscriptions"};for(let[s,u]of Object.entries(n)){let f=r.append(q0(s)),p=[];for(let h of c){let y=u[h];if(y==null||y.length===0)continue;let b=d[h],v=f.append(q0(b)),O=y.map(g=>{let A=v.append(g.name??g.id);return{id:Ut.V1.NodeId(`${this.apiDefinitionId}:${g.id}`),type:"graphql",operationType:g.operationType,graphqlOperationId:WB.GraphQlOperationId(g.id),apiDefinitionId:this.apiDefinitionId,availability:i,title:g.displayName??g.name??g.id,slug:A.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),m={id:this.#f.get(`${this.apiDefinitionId}:graphql:${s}:${h}`),type:"apiPackage",children:O,title:b,slug:v.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:i,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};p.push(m)}let _={id:this.#f.get(`${this.apiDefinitionId}:graphql:namespace:${s}`),type:"apiPackage",children:p,title:Bx(s),slug:f.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:i,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};o.push(_)}for(let s of c){let u=a[s];if(u==null||u.length===0)continue;let f=d[s],p=r.append(q0(f)),_=u.map(y=>{let b=p.append(y.name??y.id);return{id:Ut.V1.NodeId(`${this.apiDefinitionId}:${y.id}`),type:"graphql",operationType:y.operationType,graphqlOperationId:WB.GraphQlOperationId(y.id),apiDefinitionId:this.apiDefinitionId,availability:i,title:y.displayName??y.name??y.id,slug:b.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),h={id:this.#f.get(`${this.apiDefinitionId}:graphql:${s}`),type:"apiPackage",children:_,title:f,slug:p.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:i,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};o.push(h)}return o}#w(t,r,i){let n=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return n==null?(this.taskContext.logger.debug(jec(t||"unknown",[])),[]):this.#P(n,r,i)}#h(t){return u1E(t)}mergeEndpointPairs(t){return Eec({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>MH(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}getFileId(t){let r=this.collectedFileIds.get(t);return r??this.taskContext.failAndThrow("Failed to locate file after uploading: "+t)}resolveIconFileId(t){if(t!=null)return this.collectedFileIds.has(t)?`file:${this.getFileId(t)}`:t}};bE();var g1E=se(require("crypto"),1);function R5x(e){return g1E.default.createHash("sha256").update(e).digest("hex")}var Mec=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#r(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),R5x(r===0?t:`${t}-${r}`)}#i(t){let r=this.#r(t),i=0;for(;this.#t.has(r);)if(r=this.#r(t),i++,i>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return Ut.V1.NodeId(this.#i(t))}};function O1E(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0,csharpSdk:e.csharp!=null?{package:typeof e.csharp=="string"?e.csharp:e.csharp.package,version:typeof e.csharp=="string"?void 0:e.csharp.version}:void 0,phpSdk:e.php!=null?{package:typeof e.php=="string"?e.php:e.php.package,version:typeof e.php=="string"?void 0:e.php.version}:void 0,swiftSdk:e.swift!=null?{package:typeof e.swift=="string"?e.swift:e.swift.package,version:typeof e.swift=="string"?void 0:e.swift.version}:void 0,rustSdk:e.rust!=null?{package:typeof e.rust=="string"?e.rust:e.rust.package,version:typeof e.rust=="string"?void 0:e.rust.version}:void 0}}bE();var z5x=new s$o({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function SLo({ir:e,apiDefinitionId:t,playgroundConfig:r,context:i,graphqlOperations:n={},graphqlTypes:a={}}){return c$o(o$o(qY({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0,phpSdk:void 0,swiftSdk:void 0,rustSdk:void 0},playgroundConfig:r,graphqlOperations:n,graphqlTypes:a,context:i}),WB.ApiDefinitionId(t),z5x))}var m1E=se(require("path"),1);async function qEe({iconPath:e,filepaths:t}){e!=null&&typeof e=="string"&&m1E.default.isAbsolute(e)&&t.add(e)}async function A1E({parsedDocsConfig:e}){let t=new Set;return e.logo?.dark!=null&&t.add(e.logo.dark),e.logo?.light!=null&&t.add(e.logo.light),e.favicon!=null&&t.add(e.favicon),e.backgroundImage?.dark!=null&&t.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&t.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&t.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&t.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&t.add(e.metadata["twitter:image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(i=>{t.add(i.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(i=>{t.add(i.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(i=>{t.add(i.absolutePath)}),e.navigation.type==="productgroup"&&e.navigation.products.forEach(i=>{i.image!=null&&t.add(i.image)}),(await Imp({navigation:e.navigation})).forEach(i=>{t.add(i)}),e.navbarLinks&&await Promise.all(e.navbarLinks.map(async i=>{i.type==="dropdown"&&i.links.map(async n=>{n.icon&&await qEe({iconPath:n.icon,filepaths:t}),n.rightIcon&&await qEe({iconPath:n.rightIcon,filepaths:t})}),i.type!=="github"&&(i.icon&&await qEe({iconPath:i.icon,filepaths:t}),i.rightIcon&&await qEe({iconPath:i.rightIcon,filepaths:t}))})),e.js!=null&&e.js.files.forEach(i=>{t.add(i.absolutePath)}),e.pageActions?.options?.custom!=null&&await Promise.all(e.pageActions.options.custom.map(async i=>{i.icon!=null&&await qEe({iconPath:i.icon,filepaths:t})})),t}async function Imp({navigation:e}){let t=new Set;switch(e.type){case"untabbed":await Promise.all(e.items.map(r=>M8a({item:r,filepaths:t})));break;case"tabbed":await Promise.all(e.items.map(async r=>{r.icon!=null&&await qEe({iconPath:r.icon,filepaths:t}),r.child.type==="layout"&&r.child.layout!=null?await Promise.all(r.child.layout.map(i=>M8a({item:i,filepaths:t}))):r.child.type==="variants"&&r.child.variants!=null&&await Promise.all(r.child.variants.flatMap(i=>{let n=[];return i.icon!=null&&n.push(qEe({iconPath:i.icon,filepaths:t})),n.push(...i.layout.map(a=>M8a({item:a,filepaths:t}))),n}))}));break;case"versioned":await Promise.all(e.versions.map(async r=>{r.landingPage!=null&&await M8a({item:r.landingPage,filepaths:t}),(await Imp({navigation:r.navigation})).forEach(n=>t.add(n))}));break;case"productgroup":await Promise.all(e.products.map(async r=>{r.icon!=null&&await qEe({iconPath:r.icon,filepaths:t}),r.type==="internal"&&(r.landingPage!=null&&await M8a({item:r.landingPage,filepaths:t}),(await Imp({navigation:r.navigation})).forEach(n=>t.add(n)))}));break}return t}async function M8a({item:e,filepaths:t}){switch(e.type){case"page":e.icon!=null&&await qEe({iconPath:e.icon,filepaths:t});break;case"section":e.icon!=null&&await qEe({iconPath:e.icon,filepaths:t}),await Promise.all(e.contents.map(r=>M8a({item:r,filepaths:t})));break;case"apiSection":e.icon!=null&&await qEe({iconPath:e.icon,filepaths:t});break;case"link":e.icon!=null&&await qEe({iconPath:e.icon,filepaths:t});break;case"changelog":e.icon!=null&&await qEe({iconPath:e.icon,filepaths:t});break;case"pythonDocsSection":break}}async function P1E({navigation:e,apiWorkspaces:t,visitor:r,context:i}){F5x(e)?await Promise.all(e.map(async n=>{Q5x(n)?await Promise.all(n.layout.map(async a=>{await Dec({navigationItem:a,visitor:r,apiWorkspaces:t,context:i})})):U5x(n)&&await Promise.all(n.variants.flatMap(a=>a.layout.map(async o=>{await Dec({navigationItem:o,visitor:r,apiWorkspaces:t,context:i})})))})):await Promise.all(e.map(async n=>{await Dec({navigationItem:n,visitor:r,apiWorkspaces:t,context:i})}))}async function Dec({navigationItem:e,visitor:t,apiWorkspaces:r,context:i}){if(await x8t(e,{alphabetized:At,api:At,apiName:At,audiences:At,displayErrors:At,tagDescriptionPages:At,snippets:At,summary:At,title:At,layout:At,collapsed:At,icon:At,slug:At,hidden:At,skipSlug:At,paginated:At,playground:At,flattened:At,path:At,page:At,featureFlag:At,openrpc:At,postman:At,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await Dec({navigationItem:a,visitor:t,apiWorkspaces:r,context:i})}))},viewers:At,orphaned:At,availability:At}),N5x(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function N5x(e){return e.api!=null}function F5x(e){return e[0]?.tab!=null}function Q5x(e){return"layout"in e&&Array.isArray(e.layout)}function U5x(e){return"variants"in e&&Array.isArray(e.variants)}function LY(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}w1E.default.extend(E1E.default);var L5x=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),j1E=0,V5x=async({ir:e})=>(j1E++,`${e.apiName.snakeCase.unsafeName}-${j1E}`),t$t=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;targetAudiences;pythonDocsSectionHandler;constructor({domain:t,docsWorkspace:r,ossWorkspaces:i,apiWorkspaces:n,taskContext:a,editThisPage:o,uploadFiles:c=L5x,registerApi:d=V5x,targetAudiences:s,pythonDocsSectionHandler:u}){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.apiWorkspaces=n,this.taskContext=a,this.editThisPage=o,this.uploadFiles=c,this.registerApi=d,this.targetAudiences=s,this.pythonDocsSectionHandler=u}#e=Mec.init();shouldIncludeByAudience(t){return!t||t.length===0||!this.targetAudiences||this.targetAudiences.length===0?!0:t.some(r=>this.targetAudiences?.includes(r))}applyAudienceFiltering(t){let r=this.filterNavigationByAudience(t.navigation);return{...t,navigation:r}}filterNavigationByAudience(t){return t.type==="untabbed"||t.type==="tabbed"?t:t.type==="versioned"?{...t,versions:t.versions.filter(r=>this.shouldIncludeByAudience(this.getRawVersionAudiences(r.version)))}:t.type==="productgroup"?{...t,products:t.products.filter(r=>{let i=this.getRawProductAudiences(r.product);return this.shouldIncludeByAudience(i)})}:t}getRawProductAudiences(t){let i=this.docsWorkspace.config.products?.find(n=>n.displayName===t);return rro(i?.audiences)}getRawVersionAudiences(t){let i=this.docsWorkspace.config.versions?.find(n=>n.displayName===t);return rro(i?.audiences)}_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToSidebarTitle=new Map;markdownFilesToNoIndex=new Map;markdownFilesToTags=new Map;rawMarkdownFiles={};referencedMarkdownFiles=[];async resolve(){let t=performance.now(),r=process.memoryUsage();this.referencedMarkdownFiles=[],this.taskContext.logger.debug("Parsing docs configuration...");let i=performance.now();this._parsedDocsConfig=await kZc({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig});let n=performance.now()-i,a=Object.keys(this.parsedDocsConfig.pages).length;this.taskContext.logger.debug(`Parsed docs configuration in ${n.toFixed(0)}ms: ${a} pages`),this.targetAudiences&&this.targetAudiences.length>0&&(this._parsedDocsConfig=this.applyAudienceFiltering(this._parsedDocsConfig)),this.taskContext.logger.debug("Storing raw markdown content...");for(let[U,ce]of Object.entries(this.parsedDocsConfig.pages))this.rawMarkdownFiles[Pe.of(U)]=ce;let o=this.parsedDocsConfig.experimental?.openapiParserV3,c=o!=null&&!o;if(this.docsWorkspace.config.navigation!=null&&c){this.taskContext.logger.debug("Visiting navigation AST for changelog files...");let U=performance.now();await P1E({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:ae})=>{(await ae.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0,objectQueryParameters:!0,respectReadonlySchemas:!0})).changelog?.files.forEach(ve=>{let re=nd(this.docsWorkspace.absoluteFilePath,ve.absoluteFilepath);this.parsedDocsConfig.pages[re]=ve.contents,this.rawMarkdownFiles[Pe.of(re)]=ve.contents})}},apiWorkspaces:this.apiWorkspaces,context:this.taskContext});let ce=performance.now()-U;this.taskContext.logger.debug(`Visited navigation AST in ${ce.toFixed(0)}ms`)}this.taskContext.logger.debug("Building markdown file maps...");let d=performance.now();this.extractAllFrontmatterData(this.parsedDocsConfig.pages);let s=performance.now()-d;this.taskContext.logger.debug(`Built markdown file maps in ${s.toFixed(0)}ms`),this.taskContext.logger.debug("Replacing referenced markdown and code files...");let u=performance.now(),f=new Set;for(let[U,ce]of Object.entries(this.parsedDocsConfig.pages)){let ae=await Aec({markdown:ce,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(U),context:this.taskContext});for(let ve of ae.referencedFiles)f.has(ve.absoluteFilePath)||(f.add(ve.absoluteFilePath),this.referencedMarkdownFiles.push(ve));let de=await wmp({markdown:ae.markdown,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(U),context:this.taskContext});this.parsedDocsConfig.pages[Pe.of(U)]=de}let p=performance.now()-u;this.taskContext.logger.debug(`Replaced referenced content in ${p.toFixed(0)}ms, found ${this.referencedMarkdownFiles.length} referenced markdown files`),this.taskContext.logger.debug("Collecting files from docs config...");let _=performance.now(),h=await A1E({parsedDocsConfig:this.parsedDocsConfig}),y=performance.now()-_;this.taskContext.logger.debug(`Collected ${h.size} files in ${y.toFixed(0)}ms`),this.taskContext.logger.debug("Parsing image paths from markdown files...");let b=performance.now();for(let[U,ce]of Object.entries(this.parsedDocsConfig.pages))try{let{filepaths:ae,markdown:de}=sea(ce,{absolutePathToMarkdownFile:this.resolveFilepath(U),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);this.parsedDocsConfig.pages[Pe.of(U)]=de;for(let ve of ae)h.add(ve)}catch(ae){throw this.taskContext.logger.error(`Failed to parse ${U}: ${ae instanceof Error?ae.message:String(ae)}`),ae}let v=performance.now()-b;this.taskContext.logger.debug(`Parsed image paths in ${v.toFixed(0)}ms`);let O=Array.from(h).map(U=>({absoluteFilePath:U,relativeFilePath:this.toRelativeFilepath(U)}));this.taskContext.logger.info(`Uploading ${O.length} files...`);let m=performance.now(),g=await this.uploadFiles(O),A=performance.now()-m;this.taskContext.logger.info(`Uploaded ${g.length} files in ${A.toFixed(0)}ms`),g.forEach(U=>{this.collectedFileIds.set(U.absoluteFilePath,U.fileId)}),this.taskContext.logger.debug("Building navigation tree...");let j=performance.now(),M=await this.toRootNode(),w=performance.now()-j;this.taskContext.logger.debug(`Built navigation tree in ${w.toFixed(0)}ms`),this.taskContext.logger.debug("Getting fully qualified path names...");let E=performance.now(),B=await this.getMarkdownFilesToFullyQualifiedPathNames(M),q=performance.now()-E;this.taskContext.logger.debug(`Got path names in ${q.toFixed(0)}ms`),this.taskContext.logger.debug("Replacing image paths and URLs in markdown...");let R=performance.now();for(let[U,ce]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Pe.of(U)]=jmp(ce,this.collectedFileIds,B,{absolutePathToMarkdownFile:this.resolveFilepath(U),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let T=performance.now()-R;this.taskContext.logger.debug(`Replaced image paths in ${T.toFixed(0)}ms`),this.taskContext.logger.debug("Building page content...");let K={};Object.entries(this.parsedDocsConfig.pages).forEach(([U,ce])=>{let{url:ae,launch:de}=W5x(this.editThisPage,U),ve=this.rawMarkdownFiles[Pe.of(U)];K[l7.PageId(U)]={markdown:ce,editThisPageUrl:ae?l7.Url(ae):void 0,editThisPageLaunch:de,rawMarkdown:ve}}),this.taskContext.logger.debug("Converting docs configuration...");let H=performance.now(),z=await this.convertDocsConfiguration(M),W=performance.now()-H;this.taskContext.logger.debug(`Converted docs configuration in ${W.toFixed(0)}ms`);let Oe={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){this.taskContext.logger.debug("Processing MDX components...");let U=performance.now(),ce=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async de=>{let ve=xo(this.docsWorkspace.absoluteFilePath,de);(await(0,Bec.stat)(ve)).isDirectory()?(await h3(ve,"{js,ts,jsx,tsx,md,mdx}")).forEach(Ue=>{ce.add(Ue)}):ve.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&ce.add(ve)})),Oe=Object.fromEntries(await Promise.all([...ce].map(async de=>{let ve=this.toRelativeFilepath(de),re=(await(0,Bec.readFile)(de)).toString();return[ve,re]})));let ae=performance.now()-U;this.taskContext.logger.debug(`Processed ${ce.size} MDX component files in ${ae.toFixed(0)}ms`)}if(this.referencedMarkdownFiles.length>0){this.taskContext.logger.debug(`Adding ${this.referencedMarkdownFiles.length} referenced markdown files to jsFiles...`);for(let U of this.referencedMarkdownFiles)Oe[U.relativeFilePath]=U.content}let Ae=performance.now()-t,Q=process.memoryUsage();return this.taskContext.logger.debug(`Total resolve time: ${Ae.toFixed(0)}ms, Memory delta: RSS=${((Q.rss-r.rss)/1024/1024).toFixed(2)}MB`),{config:z,pages:K,jsFiles:Oe}}resolveFilepath(t){if(t!=null)return xo(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return nd(this.docsWorkspace.absoluteFilePath,t)}extractAllFrontmatterData(t){for(let[r,i]of Object.entries(t)){let n=(0,S1E.default)(i),a=this.resolveFilepath(r),o=n.data.slug;if(typeof o=="string"&&o.trim().length>0){let u=o.trim();Amp(u)?this.markdownFilesToFullSlugs.set(a,u):this.taskContext.logger.warn(`Ignoring absolute URL slug "${u}" in ${r}. Absolute URLs are not allowed for frontmatter slugs.`)}let c=n.data["sidebar-title"];typeof c=="string"&&c.trim().length>0&&this.markdownFilesToSidebarTitle.set(a,c.trim());let d=n.data.noindex;typeof d=="boolean"&&this.markdownFilesToNoIndex.set(a,d);let s=n.data.tags;typeof s=="string"?this.markdownFilesToTags.set(a,s.split(",").map(u=>u.trim()).filter(u=>u.length>0)):Array.isArray(s)&&this.markdownFilesToTags.set(a,s)}}async getMarkdownFilesToFullyQualifiedPathNames(t){let r={},i=Ut.migrate.FernNavigationV1ToLatest.create().root(t);return Ut.NodeCollector.collect(i).slugMap.forEach((a,o)=>{if(a==null||!Ut.isPage(a))return;let c=Ut.getPageId(a);if(c==null)return;let d=ot(this.docsWorkspace.absoluteFilePath,Pe.of(c));r[d]=o}),r}getDocsBasePath(){return new URL(LY(this.domain)).pathname}async convertDocsConfiguration(t){return{aiChatConfig:this.parsedDocsConfig.aiChatConfig!=null?{model:this.parsedDocsConfig.aiChatConfig.model,systemPrompt:this.parsedDocsConfig.aiChatConfig.systemPrompt,location:this.parsedDocsConfig.aiChatConfig.location,datasources:this.parsedDocsConfig.aiChatConfig.datasources?.map(i=>({url:i.url,title:i.title}))}:void 0,hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?l7.Url(this.parsedDocsConfig.logo?.href):void 0,logoRightText:this.parsedDocsConfig.logo?.rightText,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(i=>i.type==="dropdown"?{...i,links:i.links?.map(n=>({...n,url:l7.Url(n.url),icon:this.resolveIconFileId(n.icon),rightIcon:this.resolveIconFileId(n.rightIcon)})),icon:this.resolveIconFileId(i.icon),rightIcon:this.resolveIconFileId(i.rightIcon)}:i.type==="github"?{...i,url:l7.Url(i.url)}:{...i,url:l7.Url(i.url),icon:this.resolveIconFileId(i.icon),rightIcon:this.resolveIconFileId(i.rightIcon)}),typographyV2:this.convertDocsTypographyConfiguration(),layout:this.parsedDocsConfig.layout,settings:this.parsedDocsConfig.settings,css:this.parsedDocsConfig.css,js:this.convertJavascriptConfiguration(),metadata:this.convertMetadata(),redirects:this.parsedDocsConfig.redirects,integrations:this.parsedDocsConfig.integrations,footerLinks:this.parsedDocsConfig.footerLinks?.map(i=>({...i,value:l7.Url(i.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,languages:this.parsedDocsConfig.languages,analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}:void 0,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,editThisPageLaunch:this.editThisPage?.launch??"github",pageActions:this.convertPageActions(),theme:this.parsedDocsConfig.theme!=null?{sidebar:this.parsedDocsConfig.theme.sidebar,body:this.parsedDocsConfig.theme.body,tabs:this.parsedDocsConfig.theme.tabs,"page-actions":this.parsedDocsConfig.theme.pageActions,footerNav:this.parsedDocsConfig.theme.footerNav,"language-switcher":this.parsedDocsConfig.theme.languageSwitcher,"product-switcher":this.parsedDocsConfig.theme.productSwitcher}:void 0,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0,header:void 0,footer:void 0}}getFernWorkspaceForApiSection(t){if(t.apiName!=null){let i=this.apiWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}else if(this.apiWorkspaces.length===1&&this.apiWorkspaces[0]!=null)return this.apiWorkspaces[0];let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs.
|
|
2150
|
+
${c}`;return this.#d.set(a,d),this.markdownFilesToNoIndex.set(a,!1),this.markdownFilesToTags.set(a,[r]),o}#_(t,r,i,n){r=this.#e.resolveSubpackage(r);let a=r!=null?Lhn.getSubpackageId(r):void 0;return t.map(o=>Emp(o)._visit({link:c=>({id:this.#f.get(c.url),type:"link",title:c.text,icon:this.resolveIconFileId(c.icon),url:Ut.Url(c.url),target:c.target}),page:c=>this.#y(c,i,n),package:c=>this.#b(c,i,n),section:c=>this.#O(c,i,n),item:({value:c})=>this.#g(c,a,i,n),endpoint:c=>this.#A(c,a,i,n)})).filter(Cs)}#y(t,r,i){return b1E({page:{...t,availability:t.availability??i},parentSlug:r,docsWorkspace:this.docsWorkspace,markdownFilesToFullSlugs:this.markdownFilesToFullSlugs,markdownFilesToNoIndex:this.markdownFilesToNoIndex,idgen:this.#f,hideChildren:this.hideChildren,resolveIconFileId:this.resolveIconFileId.bind(this)})}#b(t,r,i){let n=t.overviewAbsolutePath!=null?Ut.V1.PageId(S8a(this.docsWorkspace,t.overviewAbsolutePath)):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,o=t.availability??i,c=this.#e.getSubpackageByIdOrLocator(t.package);if(c!=null){let d=Lhn.getSubpackageId(c),s=this.#f.get(n??`${this.apiDefinitionId}:${d}`);this.#o.has(d)&&this.taskContext.logger.warn(wec(t.package)),this.#o.add(d),this.#u.set(s,[d]);let u=t.slug??(e$t(c)?c.urlSlug:this.apiSection.slug??q0(this.apiSection.title)),f=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:u}),p=this.#_(t.contents,c,f,o);return{id:s,type:"apiPackage",children:p,title:t.title??(e$t(c)?c.displayName??Bx(c.name):this.apiSection.title),slug:f.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:n,availability:o,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#h(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}else{this.taskContext.logger.warn(jec(t.package,this.#e.subpackageLocators));let d=t.slug??q0(t.package),s=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:d}),u=this.#_(t.contents,void 0,s,o);return{id:this.#f.get(n??`${this.apiDefinitionId}:${q0(t.package)}`),type:"apiPackage",children:u,title:t.title??t.package,slug:s.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:n,availability:o,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:this.#h(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}#O(t,r,i){let n=t.overviewAbsolutePath!=null?Ut.V1.PageId(S8a(this.docsWorkspace,t.overviewAbsolutePath)):void 0,a=t.overviewAbsolutePath!=null?this.markdownFilesToFullSlugs.get(t.overviewAbsolutePath):void 0,o=t.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(t.overviewAbsolutePath):void 0,c=this.#f.get(n??a??r.get()),d=t.referencedSubpackages.map(_=>{let h=this.#e.getSubpackageByIdOrLocator(_),y=h!=null?Lhn.getSubpackageId(h):void 0;if(y===void 0){this.taskContext.logger.error(jec(_,this.#e.subpackageLocators));return}return{subpackageId:y,locator:_}}).filter(_=>_!=null).filter(Cs);this.#u.set(c,d.map(_=>_.subpackageId)),d.forEach(_=>{this.#o.has(_.subpackageId)&&this.taskContext.logger.error(wec(_.locator)),this.#o.add(_.subpackageId)});let s=t.slug??q0(t.title),u=r.apply({fullSlug:a?.split("/"),skipUrlSlug:t.skipUrlSlug,urlSlug:s}),f=t.availability??i,p=this.#_(t.contents,void 0,u,f);return{id:c,type:"apiPackage",children:p,title:t.title,slug:u.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,overviewPageId:n,availability:f,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:o,playground:this.#h(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}#g(t,r,i,n){t=t.trim();let a=this.#e.getSubpackageByIdOrLocator(t)??this.#e.getSubpackageByIdOrLocator(mn(t));if(a!=null){let o=Lhn.getSubpackageId(a),c=this.#f.get(`${this.apiDefinitionId}:${o}`);this.#o.has(o)&&this.taskContext.logger.error(wec(t)),this.#o.add(o),this.#u.set(c,[o]);let d=e$t(a)?a.urlSlug:"",s=i.apply({urlSlug:d});return{id:c,type:"apiPackage",children:[],title:e$t(a)?a.displayName??Bx(a.name):this.apiSection.title,slug:s.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:this.createTagDescriptionPageId(a),availability:n,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}return this.#A({type:"endpoint",endpoint:t,title:void 0,icon:void 0,slug:void 0,hidden:void 0,availability:void 0,playground:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0},r,i,n)}#A(t,r,i,n){let a=(r!=null?this.#e.subpackages.get(WB.SubpackageId(r))?.endpoints.get(WB.EndpointId(t.endpoint)):void 0)??this.#e.endpointsByLocator.get(t.endpoint);if(a!=null){let s=this.#e.getEndpointId(a);if(s==null)this.taskContext.logger.debug(`Expected Endpoint ID for ${a.id} at path: ${Pec(a.method,a.path.parts)}. Got undefined.`);else{this.#t.has(s)&&this.taskContext.logger.error(`Duplicate endpoint found in the API Reference layout: ${s}`),this.#t.add(s);let u=t.slug!=null?i.append(t.slug):i.apply(a);return{id:this.#f.get(`${this.apiDefinitionId}:${s}`),type:"endpoint",method:a.method,endpointId:s,apiDefinitionId:this.apiDefinitionId,availability:t.availability??Ut.V1.convertAvailability(a.availability)??n,isResponseStream:a.response?.type.type==="stream",title:t.title??a.name??MH(a.path.parts),slug:u.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,playground:this.#h(a.includeInApiExplorer===!1?{...t.playground,hidden:!0}:t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}}let o=(r!=null?this.#e.subpackages.get(WB.SubpackageId(r))?.webSockets.get(WB.WebSocketId(t.endpoint)):void 0)??this.#e.webSocketsByLocator.get(t.endpoint);if(o!=null){let s=this.#e.getWebSocketId(o);if(s==null)this.taskContext.logger.error(`Expected WebSocket ID for ${o.id}. Got undefined.`);else return this.#r.has(s)&&this.taskContext.logger.error(`Duplicate web socket found in the API Reference layout: ${s}`),this.#r.add(s),{id:this.#f.get(`${this.apiDefinitionId}:${s}`),type:"webSocket",webSocketId:s,title:t.title??o.name??MH(o.path.parts),slug:(t.slug!=null?i.append(t.slug):i.apply(o)).get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:t.availability??Ut.V1.convertAvailability(o.availability)??n,playground:this.#h(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let c=(r!=null?this.#e.subpackages.get(WB.SubpackageId(r))?.webhooks.get(WB.WebhookId(t.endpoint)):void 0)??this.#e.webhooks.get(Ut.V1.WebhookId(t.endpoint));if(c!=null){let s=this.#e.getWebhookId(c);if(s==null)this.taskContext.logger.error(`Expected Webhook ID for ${c.id}. Got undefined.`);else return this.#i.has(s)&&this.taskContext.logger.error(`Duplicate webhook found in the API Reference layout: ${s}`),this.#i.add(s),{id:this.#f.get(`${this.apiDefinitionId}:${s}`),type:"webhook",webhookId:s,method:c.method,title:t.title??c.name??(0,v1E.default)("/",...c.path),slug:(t.slug!=null?i.append(t.slug):i.apply(c)).get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,apiDefinitionId:this.apiDefinitionId,availability:t.availability??Ut.V1.convertAvailability(c.availability)??n,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}let d=this.#e.api.rootPackage.graphqlOperations?.find(s=>s.id===t.endpoint||s.name===t.endpoint);if(d!=null){let s=WB.GraphQlOperationId(d.id);if(this.#a.has(s)){this.taskContext.logger.error(`Duplicate GraphQL operation found in the API Reference layout: ${s}`);return}this.#a.add(s);let u=t.slug!=null?i.append(t.slug):i.append(d.name??d.id);return{id:this.#f.get(`${this.apiDefinitionId}:${s}`),type:"graphql",operationType:d.operationType,graphqlOperationId:WB.GraphQlOperationId(d.id),apiDefinitionId:this.apiDefinitionId,availability:t.availability??n,title:t.title??d.displayName??d.name??d.id,slug:u.get(),icon:this.resolveIconFileId(t.icon),hidden:this.hideChildren||t.hidden,playground:this.#h(t.playground),authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags}}this.taskContext.logger.error("Unknown identifier in the API Reference layout: ",t.endpoint)}#m(t,r){return y1E({left:t,right:r,findEndpointById:i=>this.#e.endpoints.get(i),stringifyEndpointPathParts:i=>MH(i.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}#v(t,r){return Dmp({child:t,nodeIdToSubpackageId:this.#u,convertApiDefinitionPackageId:(i,n,a)=>this.#w(i,n,a),mergeAndFilterChildren:this.#m.bind(this)})}#P(t,r,i){let n=[];if(t.endpoints.forEach(a=>{if(a.protocol?.type==="grpc"){let o=this.#e.getGrpcId(a);if(o==null){this.taskContext.logger.error(`Expected Grpc ID for ${a.id} at path: ${Pec(a.method,a.path.parts)}. Got undefined.`);return}if(this.#n.has(o))return;let c=r.apply(a);n.push({id:Ut.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"grpc",grpcId:o,title:a.name??MH(a.path.parts),method:a.protocol?.methodType??"UNARY",apiDefinitionId:this.apiDefinitionId,availability:i,slug:c.get(),icon:void 0,hidden:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}else{let o=this.#e.getEndpointId(a);if(o==null){this.taskContext.logger.debug(`Expected Endpoint ID for ${a.id} at path: ${Pec(a.method,a.path.parts)}. Got undefined.`);return}if(this.#t.has(o))return;let c=r.apply(a);n.push({id:Ut.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"endpoint",method:a.method,endpointId:o,apiDefinitionId:this.apiDefinitionId,availability:Ut.V1.convertAvailability(a.availability)??i,isResponseStream:a.response?.type.type==="stream",title:a.name??MH(a.path.parts),slug:c.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}}),t.websockets.forEach(a=>{let o=this.#e.getWebSocketId(a);if(o==null){this.taskContext.logger.error(`Expected WebSocket ID for ${a.id}. Got undefined.`);return}this.#r.has(o)||n.push({id:Ut.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"webSocket",webSocketId:o,title:a.name??MH(a.path.parts),slug:r.apply(a).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Ut.V1.convertAvailability(a.availability)??i,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.webhooks.forEach(a=>{let o=this.#e.getWebhookId(a);if(o==null){this.taskContext.logger.error(`Expected Webhook ID for ${a.id}. Got undefined.`);return}this.#i.has(o)||n.push({id:Ut.V1.NodeId(`${this.apiDefinitionId}:${o}`),type:"webhook",webhookId:o,method:a.method,title:a.name??Bx(a.id),slug:r.apply(a).get(),icon:void 0,hidden:this.hideChildren,apiDefinitionId:this.apiDefinitionId,availability:Ut.V1.convertAvailability(a.availability)??i,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.subpackages.forEach(a=>{if(this.#o.has(a))return;let o=this.#e.getSubpackageByIdOrLocator(a);if(o==null){this.taskContext.logger.error(`Subpackage ${a} not found in ${this.apiDefinitionId}`);return}let c=e$t(o)?r.apply(o):r,d=this.#w(a,c,i),s=this.createTagDescriptionPageId(o),u=this.#e.subpackages.get(WB.SubpackageId(a)),f=u?Array.from(u.endpoints.values()).some(p=>{let _=this.#e.getEndpointId(p);return _!=null&&this.#t.has(_)}):!1;(d.length>0||s!=null&&f)&&n.push({id:Ut.V1.NodeId(`${this.apiDefinitionId}:${a}`),type:"apiPackage",children:d,title:e$t(o)?o.displayName??Bx(o.name):this.apiSection.title,slug:c.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:s,availability:i,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0})}),t.graphqlOperations!=null&&t.graphqlOperations.length>0){let a=this.#j(t.graphqlOperations,r,i);n.push(...a)}return n=this.mergeEndpointPairs(n),this.apiSection.alphabetized&&(n=n.sort((a,o)=>{let c=a.type==="endpointPair"?a.nonStream.title:a.title,d=o.type==="endpointPair"?o.nonStream.title:o.title;return c.localeCompare(d)})),n}#j(t,r,i){let n={},a={};for(let s of t){let u=WB.GraphQlOperationId(s.id);if(this.#a.has(u))continue;this.#a.add(u);let f=this.#c.get(Jr.GraphQlOperationId(s.id)),p=s.operationType;f!=null?(n[f]==null&&(n[f]={}),n[f][p]==null&&(n[f][p]=[]),n[f][p].push(s)):(a[p]==null&&(a[p]=[]),a[p].push(s))}let o=[],c=["QUERY","MUTATION","SUBSCRIPTION"],d={QUERY:"Queries",MUTATION:"Mutations",SUBSCRIPTION:"Subscriptions"};for(let[s,u]of Object.entries(n)){let f=r.append(q0(s)),p=[];for(let h of c){let y=u[h];if(y==null||y.length===0)continue;let b=d[h],v=f.append(q0(b)),O=y.map(g=>{let A=v.append(g.name??g.id);return{id:Ut.V1.NodeId(`${this.apiDefinitionId}:${g.id}`),type:"graphql",operationType:g.operationType,graphqlOperationId:WB.GraphQlOperationId(g.id),apiDefinitionId:this.apiDefinitionId,availability:i,title:g.displayName??g.name??g.id,slug:A.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),m={id:this.#f.get(`${this.apiDefinitionId}:graphql:${s}:${h}`),type:"apiPackage",children:O,title:b,slug:v.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:i,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};p.push(m)}let _={id:this.#f.get(`${this.apiDefinitionId}:graphql:namespace:${s}`),type:"apiPackage",children:p,title:Bx(s),slug:f.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:i,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};o.push(_)}for(let s of c){let u=a[s];if(u==null||u.length===0)continue;let f=d[s],p=r.append(q0(f)),_=u.map(y=>{let b=p.append(y.name??y.id);return{id:Ut.V1.NodeId(`${this.apiDefinitionId}:${y.id}`),type:"graphql",operationType:y.operationType,graphqlOperationId:WB.GraphQlOperationId(y.id),apiDefinitionId:this.apiDefinitionId,availability:i,title:y.displayName??y.name??y.id,slug:b.get(),icon:void 0,hidden:this.hideChildren,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0}}),h={id:this.#f.get(`${this.apiDefinitionId}:graphql:${s}`),type:"apiPackage",children:_,title:f,slug:p.get(),icon:void 0,hidden:this.hideChildren,overviewPageId:void 0,availability:i,apiDefinitionId:this.apiDefinitionId,pointsTo:void 0,noindex:void 0,playground:void 0,authed:void 0,viewers:void 0,orphaned:void 0,featureFlags:void 0};o.push(h)}return o}#w(t,r,i){let n=t!=null?this.#e.resolveSubpackage(this.#e.getSubpackageByIdOrLocator(t)):void 0;return n==null?(this.taskContext.logger.debug(jec(t||"unknown",[])),[]):this.#P(n,r,i)}#h(t){return u1E(t)}mergeEndpointPairs(t){return Eec({children:t,findEndpointById:r=>this.#e.endpoints.get(r),stringifyEndpointPathParts:r=>MH(r.path.parts),disableEndpointPairs:this.disableEndpointPairs,apiDefinitionId:this.apiDefinitionId})}getFileId(t){let r=this.collectedFileIds.get(t);return r??this.taskContext.failAndThrow("Failed to locate file after uploading: "+t)}resolveIconFileId(t){if(t!=null)return this.collectedFileIds.has(t)?`file:${this.getFileId(t)}`:t}};bE();var g1E=se(require("crypto"),1);function R5x(e){return g1E.default.createHash("sha256").update(e).digest("hex")}var Mec=class e{static init(){return new e}constructor(){}#e=new Map;#t=new Set;#r(t){let r=this.#e.get(t)??0;return this.#e.set(t,r+1),R5x(r===0?t:`${t}-${r}`)}#i(t){let r=this.#r(t),i=0;for(;this.#t.has(r);)if(r=this.#r(t),i++,i>100)throw new Error(`Infinite loop detected for id: ${t}`);return r}get(t){return Ut.V1.NodeId(this.#i(t))}};function O1E(e){return e==null?{}:{pythonSdk:e.python!=null?{package:typeof e.python=="string"?e.python:e.python.package,version:typeof e.python=="string"?void 0:e.python.version}:void 0,typescriptSdk:e.typescript!=null?{package:typeof e.typescript=="string"?e.typescript:e.typescript.package,version:typeof e.typescript=="string"?void 0:e.typescript.version}:void 0,goSdk:e.go!=null?{githubRepo:typeof e.go=="string"?e.go:e.go.package,version:typeof e.go=="string"?void 0:e.go.version}:void 0,javaSdk:e.java!=null?{coordinate:typeof e.java=="string"?e.java:e.java.package,version:typeof e.java=="string"?void 0:e.java.version}:void 0,rubySdk:e.ruby!=null?{gem:typeof e.ruby=="string"?e.ruby:e.ruby.package,version:typeof e.ruby=="string"?void 0:e.ruby.version}:void 0,csharpSdk:e.csharp!=null?{package:typeof e.csharp=="string"?e.csharp:e.csharp.package,version:typeof e.csharp=="string"?void 0:e.csharp.version}:void 0,phpSdk:e.php!=null?{package:typeof e.php=="string"?e.php:e.php.package,version:typeof e.php=="string"?void 0:e.php.version}:void 0,swiftSdk:e.swift!=null?{package:typeof e.swift=="string"?e.swift:e.swift.package,version:typeof e.swift=="string"?void 0:e.swift.version}:void 0,rustSdk:e.rust!=null?{package:typeof e.rust=="string"?e.rust:e.rust.package,version:typeof e.rust=="string"?void 0:e.rust.version}:void 0}}bE();var z5x=new s$o({snippetsBySdkId:{},snippetsConfigWithSdkId:{},snippetTemplatesByEndpoint:{},snippetsBySdkIdAndEndpointId:{},snippetTemplatesByEndpointId:{}});function SLo({ir:e,apiDefinitionId:t,playgroundConfig:r,context:i,graphqlOperations:n={},graphqlTypes:a={}}){return c$o(o$o(qY({ir:e,snippetsConfig:{typescriptSdk:void 0,pythonSdk:void 0,javaSdk:void 0,rubySdk:void 0,goSdk:void 0,csharpSdk:void 0,phpSdk:void 0,swiftSdk:void 0,rustSdk:void 0},playgroundConfig:r,graphqlOperations:n,graphqlTypes:a,context:i}),WB.ApiDefinitionId(t),z5x))}var m1E=se(require("path"),1);async function qEe({iconPath:e,filepaths:t}){e!=null&&typeof e=="string"&&m1E.default.isAbsolute(e)&&t.add(e)}async function A1E({parsedDocsConfig:e}){let t=new Set;return e.logo?.dark!=null&&t.add(e.logo.dark),e.logo?.light!=null&&t.add(e.logo.light),e.favicon!=null&&t.add(e.favicon),e.backgroundImage?.dark!=null&&t.add(e.backgroundImage.dark),e.backgroundImage?.light!=null&&t.add(e.backgroundImage.light),e.metadata?.["og:image"]!=null&&e.metadata["og:image"].type==="filepath"&&t.add(e.metadata["og:image"].value),e.metadata?.["og:logo"]!=null&&e.metadata["og:logo"].type==="filepath"&&t.add(e.metadata["og:logo"].value),e.metadata?.["twitter:image"]!=null&&e.metadata["twitter:image"].type==="filepath"&&t.add(e.metadata["twitter:image"].value),e.typography?.bodyFont!=null&&e.typography.bodyFont.variants.forEach(i=>{t.add(i.absolutePath)}),e.typography?.headingsFont!=null&&e.typography.headingsFont.variants.forEach(i=>{t.add(i.absolutePath)}),e.typography?.codeFont!=null&&e.typography.codeFont.variants.forEach(i=>{t.add(i.absolutePath)}),e.navigation.type==="productgroup"&&e.navigation.products.forEach(i=>{i.image!=null&&t.add(i.image)}),(await Imp({navigation:e.navigation})).forEach(i=>{t.add(i)}),e.navbarLinks&&await Promise.all(e.navbarLinks.map(async i=>{i.type==="dropdown"&&i.links.map(async n=>{n.icon&&await qEe({iconPath:n.icon,filepaths:t}),n.rightIcon&&await qEe({iconPath:n.rightIcon,filepaths:t})}),i.type!=="github"&&(i.icon&&await qEe({iconPath:i.icon,filepaths:t}),i.rightIcon&&await qEe({iconPath:i.rightIcon,filepaths:t}))})),e.js!=null&&e.js.files.forEach(i=>{t.add(i.absolutePath)}),e.pageActions?.options?.custom!=null&&await Promise.all(e.pageActions.options.custom.map(async i=>{i.icon!=null&&await qEe({iconPath:i.icon,filepaths:t})})),t}async function Imp({navigation:e}){let t=new Set;switch(e.type){case"untabbed":await Promise.all(e.items.map(r=>M8a({item:r,filepaths:t})));break;case"tabbed":await Promise.all(e.items.map(async r=>{r.icon!=null&&await qEe({iconPath:r.icon,filepaths:t}),r.child.type==="layout"&&r.child.layout!=null?await Promise.all(r.child.layout.map(i=>M8a({item:i,filepaths:t}))):r.child.type==="variants"&&r.child.variants!=null&&await Promise.all(r.child.variants.flatMap(i=>{let n=[];return i.icon!=null&&n.push(qEe({iconPath:i.icon,filepaths:t})),n.push(...i.layout.map(a=>M8a({item:a,filepaths:t}))),n}))}));break;case"versioned":await Promise.all(e.versions.map(async r=>{r.landingPage!=null&&await M8a({item:r.landingPage,filepaths:t}),(await Imp({navigation:r.navigation})).forEach(n=>t.add(n))}));break;case"productgroup":await Promise.all(e.products.map(async r=>{r.icon!=null&&await qEe({iconPath:r.icon,filepaths:t}),r.type==="internal"&&(r.landingPage!=null&&await M8a({item:r.landingPage,filepaths:t}),(await Imp({navigation:r.navigation})).forEach(n=>t.add(n)))}));break}return t}async function M8a({item:e,filepaths:t}){switch(e.type){case"page":e.icon!=null&&await qEe({iconPath:e.icon,filepaths:t});break;case"section":e.icon!=null&&await qEe({iconPath:e.icon,filepaths:t}),await Promise.all(e.contents.map(r=>M8a({item:r,filepaths:t})));break;case"apiSection":e.icon!=null&&await qEe({iconPath:e.icon,filepaths:t});break;case"link":e.icon!=null&&await qEe({iconPath:e.icon,filepaths:t});break;case"changelog":e.icon!=null&&await qEe({iconPath:e.icon,filepaths:t});break;case"pythonDocsSection":break}}async function P1E({navigation:e,apiWorkspaces:t,visitor:r,context:i}){F5x(e)?await Promise.all(e.map(async n=>{Q5x(n)?await Promise.all(n.layout.map(async a=>{await Dec({navigationItem:a,visitor:r,apiWorkspaces:t,context:i})})):U5x(n)&&await Promise.all(n.variants.flatMap(a=>a.layout.map(async o=>{await Dec({navigationItem:o,visitor:r,apiWorkspaces:t,context:i})})))})):await Promise.all(e.map(async n=>{await Dec({navigationItem:n,visitor:r,apiWorkspaces:t,context:i})}))}async function Dec({navigationItem:e,visitor:t,apiWorkspaces:r,context:i}){if(await x8t(e,{alphabetized:At,api:At,apiName:At,audiences:At,displayErrors:At,tagDescriptionPages:At,snippets:At,summary:At,title:At,layout:At,collapsed:At,icon:At,slug:At,hidden:At,skipSlug:At,paginated:At,playground:At,flattened:At,path:At,page:At,featureFlag:At,openrpc:At,postman:At,contents:async n=>{n!=null&&await Promise.all(n.map(async a=>{await Dec({navigationItem:a,visitor:t,apiWorkspaces:r,context:i})}))},viewers:At,orphaned:At,availability:At}),N5x(e)){let n=r.find(a=>a.workspaceName===e.apiName);n!=null&&await t.apiSection?.({config:e,workspace:n,context:i})}}function N5x(e){return e.api!=null}function F5x(e){return e[0]?.tab!=null}function Q5x(e){return"layout"in e&&Array.isArray(e.layout)}function U5x(e){return"variants"in e&&Array.isArray(e.variants)}function LY(e){return e.startsWith("https://")||e.startsWith("http://")?e:`https://${e}`}w1E.default.extend(E1E.default);var L5x=e=>e.map(t=>({...t,fileId:String(t.relativeFilePath)})),j1E=0,V5x=async({ir:e})=>(j1E++,`${e.apiName.snakeCase.unsafeName}-${j1E}`),t$t=class{domain;docsWorkspace;ossWorkspaces;apiWorkspaces;taskContext;editThisPage;uploadFiles;registerApi;targetAudiences;pythonDocsSectionHandler;constructor({domain:t,docsWorkspace:r,ossWorkspaces:i,apiWorkspaces:n,taskContext:a,editThisPage:o,uploadFiles:c=L5x,registerApi:d=V5x,targetAudiences:s,pythonDocsSectionHandler:u}){this.domain=t,this.docsWorkspace=r,this.ossWorkspaces=i,this.apiWorkspaces=n,this.taskContext=a,this.editThisPage=o,this.uploadFiles=c,this.registerApi=d,this.targetAudiences=s,this.pythonDocsSectionHandler=u}#e=Mec.init();shouldIncludeByAudience(t){return!t||t.length===0||!this.targetAudiences||this.targetAudiences.length===0?!0:t.some(r=>this.targetAudiences?.includes(r))}applyAudienceFiltering(t){let r=this.filterNavigationByAudience(t.navigation);return{...t,navigation:r}}filterNavigationByAudience(t){return t.type==="untabbed"||t.type==="tabbed"?t:t.type==="versioned"?{...t,versions:t.versions.filter(r=>this.shouldIncludeByAudience(this.getRawVersionAudiences(r.version)))}:t.type==="productgroup"?{...t,products:t.products.filter(r=>{let i=this.getRawProductAudiences(r.product);return this.shouldIncludeByAudience(i)})}:t}getRawProductAudiences(t){let i=this.docsWorkspace.config.products?.find(n=>n.displayName===t);return rro(i?.audiences)}getRawVersionAudiences(t){let i=this.docsWorkspace.config.versions?.find(n=>n.displayName===t);return rro(i?.audiences)}_parsedDocsConfig;get parsedDocsConfig(){if(this._parsedDocsConfig==null)throw new Error("parsedDocsConfig is not set");return this._parsedDocsConfig}collectedFileIds=new Map;markdownFilesToFullSlugs=new Map;markdownFilesToSidebarTitle=new Map;markdownFilesToNoIndex=new Map;markdownFilesToTags=new Map;markdownFilesToAvailability=new Map;rawMarkdownFiles={};referencedMarkdownFiles=[];async resolve(){let t=performance.now(),r=process.memoryUsage();this.referencedMarkdownFiles=[],this.taskContext.logger.debug("Parsing docs configuration...");let i=performance.now();this._parsedDocsConfig=await kZc({rawDocsConfiguration:this.docsWorkspace.config,context:this.taskContext,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absoluteFilepathToDocsConfig:this.docsWorkspace.absoluteFilepathToDocsConfig});let n=performance.now()-i,a=Object.keys(this.parsedDocsConfig.pages).length;this.taskContext.logger.debug(`Parsed docs configuration in ${n.toFixed(0)}ms: ${a} pages`),this.targetAudiences&&this.targetAudiences.length>0&&(this._parsedDocsConfig=this.applyAudienceFiltering(this._parsedDocsConfig)),this.taskContext.logger.debug("Storing raw markdown content...");for(let[U,ce]of Object.entries(this.parsedDocsConfig.pages))this.rawMarkdownFiles[Pe.of(U)]=ce;let o=this.parsedDocsConfig.experimental?.openapiParserV3,c=o!=null&&!o;if(this.docsWorkspace.config.navigation!=null&&c){this.taskContext.logger.debug("Visiting navigation AST for changelog files...");let U=performance.now();await P1E({navigation:this.docsWorkspace.config.navigation,visitor:{apiSection:async({workspace:ae})=>{(await ae.toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,preserveSchemaIds:!0,objectQueryParameters:!0,respectReadonlySchemas:!0})).changelog?.files.forEach(ve=>{let re=nd(this.docsWorkspace.absoluteFilePath,ve.absoluteFilepath);this.parsedDocsConfig.pages[re]=ve.contents,this.rawMarkdownFiles[Pe.of(re)]=ve.contents})}},apiWorkspaces:this.apiWorkspaces,context:this.taskContext});let ce=performance.now()-U;this.taskContext.logger.debug(`Visited navigation AST in ${ce.toFixed(0)}ms`)}this.taskContext.logger.debug("Building markdown file maps...");let d=performance.now();this.extractAllFrontmatterData(this.parsedDocsConfig.pages);let s=performance.now()-d;this.taskContext.logger.debug(`Built markdown file maps in ${s.toFixed(0)}ms`),this.taskContext.logger.debug("Replacing referenced markdown and code files...");let u=performance.now(),f=new Set;for(let[U,ce]of Object.entries(this.parsedDocsConfig.pages)){let ae=await Aec({markdown:ce,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(U),context:this.taskContext});for(let ve of ae.referencedFiles)f.has(ve.absoluteFilePath)||(f.add(ve.absoluteFilePath),this.referencedMarkdownFiles.push(ve));let de=await wmp({markdown:ae.markdown,absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath,absolutePathToMarkdownFile:this.resolveFilepath(U),context:this.taskContext});this.parsedDocsConfig.pages[Pe.of(U)]=de}let p=performance.now()-u;this.taskContext.logger.debug(`Replaced referenced content in ${p.toFixed(0)}ms, found ${this.referencedMarkdownFiles.length} referenced markdown files`),this.taskContext.logger.debug("Collecting files from docs config...");let _=performance.now(),h=await A1E({parsedDocsConfig:this.parsedDocsConfig}),y=performance.now()-_;this.taskContext.logger.debug(`Collected ${h.size} files in ${y.toFixed(0)}ms`),this.taskContext.logger.debug("Parsing image paths from markdown files...");let b=performance.now();for(let[U,ce]of Object.entries(this.parsedDocsConfig.pages))try{let{filepaths:ae,markdown:de}=sea(ce,{absolutePathToMarkdownFile:this.resolveFilepath(U),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);this.parsedDocsConfig.pages[Pe.of(U)]=de;for(let ve of ae)h.add(ve)}catch(ae){throw this.taskContext.logger.error(`Failed to parse ${U}: ${ae instanceof Error?ae.message:String(ae)}`),ae}let v=performance.now()-b;this.taskContext.logger.debug(`Parsed image paths in ${v.toFixed(0)}ms`);let O=Array.from(h).map(U=>({absoluteFilePath:U,relativeFilePath:this.toRelativeFilepath(U)}));this.taskContext.logger.info(`Uploading ${O.length} files...`);let m=performance.now(),g=await this.uploadFiles(O),A=performance.now()-m;this.taskContext.logger.info(`Uploaded ${g.length} files in ${A.toFixed(0)}ms`),g.forEach(U=>{this.collectedFileIds.set(U.absoluteFilePath,U.fileId)}),this.taskContext.logger.debug("Building navigation tree...");let j=performance.now(),M=await this.toRootNode(),w=performance.now()-j;this.taskContext.logger.debug(`Built navigation tree in ${w.toFixed(0)}ms`),this.taskContext.logger.debug("Getting fully qualified path names...");let E=performance.now(),B=await this.getMarkdownFilesToFullyQualifiedPathNames(M),q=performance.now()-E;this.taskContext.logger.debug(`Got path names in ${q.toFixed(0)}ms`),this.taskContext.logger.debug("Replacing image paths and URLs in markdown...");let R=performance.now();for(let[U,ce]of Object.entries(this.parsedDocsConfig.pages))this.parsedDocsConfig.pages[Pe.of(U)]=jmp(ce,this.collectedFileIds,B,{absolutePathToMarkdownFile:this.resolveFilepath(U),absolutePathToFernFolder:this.docsWorkspace.absoluteFilePath},this.taskContext);let T=performance.now()-R;this.taskContext.logger.debug(`Replaced image paths in ${T.toFixed(0)}ms`),this.taskContext.logger.debug("Building page content...");let K={};Object.entries(this.parsedDocsConfig.pages).forEach(([U,ce])=>{let{url:ae,launch:de}=W5x(this.editThisPage,U),ve=this.rawMarkdownFiles[Pe.of(U)];K[l7.PageId(U)]={markdown:ce,editThisPageUrl:ae?l7.Url(ae):void 0,editThisPageLaunch:de,rawMarkdown:ve}}),this.taskContext.logger.debug("Converting docs configuration...");let H=performance.now(),z=await this.convertDocsConfiguration(M),W=performance.now()-H;this.taskContext.logger.debug(`Converted docs configuration in ${W.toFixed(0)}ms`);let Oe={};if(this._parsedDocsConfig.experimental?.mdxComponents!=null){this.taskContext.logger.debug("Processing MDX components...");let U=performance.now(),ce=new Set;await Promise.all(this._parsedDocsConfig.experimental.mdxComponents.map(async de=>{let ve=xo(this.docsWorkspace.absoluteFilePath,de);(await(0,Bec.stat)(ve)).isDirectory()?(await h3(ve,"{js,ts,jsx,tsx,md,mdx}")).forEach(Ue=>{ce.add(Ue)}):ve.match(/\.(js|ts|jsx|tsx|md|mdx)$/)!=null&&ce.add(ve)})),Oe=Object.fromEntries(await Promise.all([...ce].map(async de=>{let ve=this.toRelativeFilepath(de),re=(await(0,Bec.readFile)(de)).toString();return[ve,re]})));let ae=performance.now()-U;this.taskContext.logger.debug(`Processed ${ce.size} MDX component files in ${ae.toFixed(0)}ms`)}if(this.referencedMarkdownFiles.length>0){this.taskContext.logger.debug(`Adding ${this.referencedMarkdownFiles.length} referenced markdown files to jsFiles...`);for(let U of this.referencedMarkdownFiles)Oe[U.relativeFilePath]=U.content}let Ae=performance.now()-t,Q=process.memoryUsage();return this.taskContext.logger.debug(`Total resolve time: ${Ae.toFixed(0)}ms, Memory delta: RSS=${((Q.rss-r.rss)/1024/1024).toFixed(2)}MB`),{config:z,pages:K,jsFiles:Oe}}resolveFilepath(t){if(t!=null)return xo(this.docsWorkspace.absoluteFilePath,t)}toRelativeFilepath(t){if(t!=null)return nd(this.docsWorkspace.absoluteFilePath,t)}extractAllFrontmatterData(t){for(let[r,i]of Object.entries(t)){let n=(0,S1E.default)(i),a=this.resolveFilepath(r),o=n.data.slug;if(typeof o=="string"&&o.trim().length>0){let f=o.trim();Amp(f)?this.markdownFilesToFullSlugs.set(a,f):this.taskContext.logger.warn(`Ignoring absolute URL slug "${f}" in ${r}. Absolute URLs are not allowed for frontmatter slugs.`)}let c=n.data["sidebar-title"];typeof c=="string"&&c.trim().length>0&&this.markdownFilesToSidebarTitle.set(a,c.trim());let d=n.data.noindex;typeof d=="boolean"&&this.markdownFilesToNoIndex.set(a,d);let s=n.data.tags;typeof s=="string"?this.markdownFilesToTags.set(a,s.split(",").map(f=>f.trim()).filter(f=>f.length>0)):Array.isArray(s)&&this.markdownFilesToTags.set(a,s);let u=n.data.availability;if(typeof u=="string"){let f=this.parseAvailabilityFromFrontmatter(u);f!=null&&this.markdownFilesToAvailability.set(a,f)}}}parseAvailabilityFromFrontmatter(t){switch(t.toLowerCase().trim()){case"stable":return"stable";case"generally-available":return"generally-available";case"in-development":return"in-development";case"pre-release":return"pre-release";case"deprecated":return"deprecated";case"beta":return"beta";default:this.taskContext.logger.warn(`Invalid availability value "${t}" in frontmatter. Valid values are: stable, generally-available, in-development, pre-release, deprecated, beta`);return}}async getMarkdownFilesToFullyQualifiedPathNames(t){let r={},i=Ut.migrate.FernNavigationV1ToLatest.create().root(t);return Ut.NodeCollector.collect(i).slugMap.forEach((a,o)=>{if(a==null||!Ut.isPage(a))return;let c=Ut.getPageId(a);if(c==null)return;let d=ot(this.docsWorkspace.absoluteFilePath,Pe.of(c));r[d]=o}),r}getDocsBasePath(){return new URL(LY(this.domain)).pathname}async convertDocsConfiguration(t){return{aiChatConfig:this.parsedDocsConfig.aiChatConfig!=null?{model:this.parsedDocsConfig.aiChatConfig.model,systemPrompt:this.parsedDocsConfig.aiChatConfig.systemPrompt,location:this.parsedDocsConfig.aiChatConfig.location,datasources:this.parsedDocsConfig.aiChatConfig.datasources?.map(i=>({url:i.url,title:i.title}))}:void 0,hideNavLinks:void 0,title:this.parsedDocsConfig.title,logoHeight:this.parsedDocsConfig.logo?.height,logoHref:this.parsedDocsConfig.logo?.href?l7.Url(this.parsedDocsConfig.logo?.href):void 0,logoRightText:this.parsedDocsConfig.logo?.rightText,favicon:this.getFileId(this.parsedDocsConfig.favicon),navigation:void 0,root:t,colorsV3:this.convertColorConfigImageReferences(),navbarLinks:this.parsedDocsConfig.navbarLinks?.map(i=>i.type==="dropdown"?{...i,links:i.links?.map(n=>({...n,url:l7.Url(n.url),icon:this.resolveIconFileId(n.icon),rightIcon:this.resolveIconFileId(n.rightIcon)})),icon:this.resolveIconFileId(i.icon),rightIcon:this.resolveIconFileId(i.rightIcon)}:i.type==="github"?{...i,url:l7.Url(i.url)}:{...i,url:l7.Url(i.url),icon:this.resolveIconFileId(i.icon),rightIcon:this.resolveIconFileId(i.rightIcon)}),typographyV2:this.convertDocsTypographyConfiguration(),layout:this.parsedDocsConfig.layout,settings:this.parsedDocsConfig.settings,css:this.parsedDocsConfig.css,js:this.convertJavascriptConfiguration(),metadata:this.convertMetadata(),redirects:this.parsedDocsConfig.redirects,integrations:this.parsedDocsConfig.integrations,footerLinks:this.parsedDocsConfig.footerLinks?.map(i=>({...i,value:l7.Url(i.value)})),defaultLanguage:this.parsedDocsConfig.defaultLanguage,languages:this.parsedDocsConfig.languages,analyticsConfig:{...this.parsedDocsConfig.analyticsConfig,segment:this.parsedDocsConfig.analyticsConfig?.segment,fullstory:this.parsedDocsConfig.analyticsConfig?.fullstory,intercom:this.parsedDocsConfig.analyticsConfig?.intercom?{appId:this.parsedDocsConfig.analyticsConfig.intercom.appId,apiBase:this.parsedDocsConfig.analyticsConfig.intercom.apiBase}:void 0,posthog:this.parsedDocsConfig.analyticsConfig?.posthog?{apiKey:this.parsedDocsConfig.analyticsConfig.posthog.apiKey,endpoint:this.parsedDocsConfig.analyticsConfig.posthog.endpoint}:void 0,gtm:this.parsedDocsConfig.analyticsConfig?.gtm?{containerId:this.parsedDocsConfig.analyticsConfig.gtm.containerId}:void 0,ga4:this.parsedDocsConfig.analyticsConfig?.ga4?{measurementId:this.parsedDocsConfig.analyticsConfig.ga4.measurementId}:void 0,amplitude:void 0,mixpanel:void 0,hotjar:void 0,koala:void 0,logrocket:void 0,pirsch:void 0,plausible:void 0,fathom:void 0,clearbit:void 0,heap:void 0},announcement:this.parsedDocsConfig.announcement!=null?{text:this.parsedDocsConfig.announcement.message}:void 0,editThisPageLaunch:this.editThisPage?.launch??"github",pageActions:this.convertPageActions(),theme:this.parsedDocsConfig.theme!=null?{sidebar:this.parsedDocsConfig.theme.sidebar,body:this.parsedDocsConfig.theme.body,tabs:this.parsedDocsConfig.theme.tabs,"page-actions":this.parsedDocsConfig.theme.pageActions,footerNav:this.parsedDocsConfig.theme.footerNav,"language-switcher":this.parsedDocsConfig.theme.languageSwitcher,"product-switcher":this.parsedDocsConfig.theme.productSwitcher}:void 0,logo:void 0,logoV2:void 0,colors:void 0,colorsV2:void 0,typography:void 0,backgroundImage:void 0,header:void 0,footer:void 0}}getFernWorkspaceForApiSection(t){if(t.apiName!=null){let i=this.apiWorkspaces.find(n=>n.workspaceName===t.apiName);if(i!=null)return i}else if(this.apiWorkspaces.length===1&&this.apiWorkspaces[0]!=null)return this.apiWorkspaces[0];let r=t.apiName?`Failed to load API Definition '${t.apiName}' referenced in docs.
|
|
2151
2151
|
A valid API configuration was not found at the path: fern/apis/${t.apiName}.
|
|
2152
2152
|
Learn more about project structure:
|
|
2153
2153
|
https://buildwithfern.com/learn/docs/getting-started/project-structure#api-definitions`:`Failed to load API Definition referenced in docs.
|
|
@@ -2157,7 +2157,7 @@ A valid API configuration was not found at the path: fern/apis/${t.apiName}.
|
|
|
2157
2157
|
Learn more about project structure:
|
|
2158
2158
|
https://buildwithfern.com/learn/docs/getting-started/project-structure#api-definitions`:`Failed to load API Definition referenced in docs.
|
|
2159
2159
|
Learn more about project structure:
|
|
2160
|
-
https://buildwithfern.com/learn/docs/getting-started/project-structure#api-definitions`;throw new Error(r)}async toRootNode(){let t=Ut.V1.SlugGenerator.init(Ut.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),i=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:i,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0,roles:this.parsedDocsConfig.roles?.map(n=>Ut.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return LT(this.parsedDocsConfig.navigation)._visit({untabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),tabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),versioned:r=>this.toVersionedNode(r,t),productgroup:r=>this.toProductGroupNode({landingPageConfig:this.parsedDocsConfig.landingPage,productGroup:r,parentSlug:t})})}toLandingPageNode(t,r){let i=Ut.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??q0(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:this.resolveIconFileId(t.icon),hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,o=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:o}}async toVersionedNode(t,r){let i=this.#e.get("versioned"),n=t.versions[0];if(n?.hidden===!0)throw new Error(`The default version "${n.version}" cannot be hidden. Please set a non-hidden version as the first version in your versions list, or remove the hidden flag from the default version.`);let a=5,o=[];for(let c=0;c<t.versions.length;c+=a){let d=t.versions.slice(c,c+a),s=await Promise.all(d.map((u,f)=>this.toVersionNode(u,r,c+f===0)));o.push(...s)}return{id:i,type:"versioned",children:o}}async toProductGroupNode({productGroup:t,landingPageConfig:r,parentSlug:i}){let n=this.#e.get("productgroup"),a=r!=null?this.toLandingPageNode(r,i):void 0;return{id:n,type:"productgroup",landingPage:a,children:await Promise.all(t.products.map(o=>this.toProductNode(o,i)))}}async toProductNode(t,r){if(t.type==="internal"){let i=r.setProductSlug(t.slug??q0(t.product)),n;switch(t.navigation.type){case"tabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.convertTabbedNavigation(this.#e.get(t.product),t.navigation.items,i)};break;case"untabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.toSidebarRootNode(this.#e.get(t.product),t.navigation.items,i)};break;case"versioned":n=await this.toVersionedNode(t.navigation,i);break;default:fe(t.navigation)}return{type:"product",id:this.#e.get(t.product),productId:Ut.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",slug:i.get(),child:n,default:!1,hidden:void 0,authed:void 0,icon:this.resolveIconFileId(t.icon),image:t.image!=null?this.getFileId(t.image):void 0,pointsTo:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,announcement:t.announcement!=null?{text:t.announcement.message}:void 0}}else return{type:"productLink",id:this.#e.get(t.product),productId:Ut.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",href:l7.Url(t.href??""),target:t.target,default:!1,hidden:void 0,authed:void 0,icon:this.resolveIconFileId(t.icon),image:t.image!=null?this.getFileId(t.image):void 0,viewers:t.viewers,orphaned:t.orphaned}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??q0(t.version)),o=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(n,t.navigation.items,a):await this.toSidebarRootNode(n,t.navigation.items,a);return{type:"version",id:n,versionId:Ut.VersionId(t.version),title:t.version,slug:a.get(),child:o,default:i,availability:t.availability!=null?x5x(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:t.hidden,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags,announcement:t.announcement!=null?{text:t.announcement.message}:void 0}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),o=(await Promise.all(r.map(d=>this.toNavigationChild({prefix:n,item:d,parentSlug:i})))).filter(d=>d!=null),c=[];return o.forEach(d=>{if(d.type==="apiReference"){c.push(d);return}if(d.type==="section"&&!d.collapsed){c.push(d);return}let s=c.length>0?c[c.length-1]:void 0,u;s?.type==="sidebarGroup"?u=s:(u={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},c.push(u)),u.children.push(d)}),{type:"sidebarRoot",id:n,children:c}}async toSidebarRootNodeWithVariants(t,r,i){let n=this.#e.get(`${t}/root`);return{type:"sidebarRoot",id:n,children:[{type:"varianted",id:n,children:await Promise.all(r.map(a=>this.toVariantNode(a,n,i)))}]}}async toVariantNode(t,r,i){let n=this.#e.get(`${r}/variant/${t.slug??q0(t.title)}`),a=i.apply({urlSlug:t.slug??q0(t.title),skipUrlSlug:t.skipUrlSlug}),c=(await Promise.all(t.layout.map(d=>this.toVariantChild(d,n,a)))).filter(d=>d!=null);return{type:"variant",id:n,variantId:Ut.V1.VariantId(t.title),subtitle:t.subtitle??"",default:t.default??!1,image:void 0,children:c,title:t.title,slug:a.get(),icon:this.resolveIconFileId(t.icon),hidden:t.hidden,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,pointsTo:void 0}}async toVariantChild(t,r,i){return LT(t)._visit({page:async n=>this.toPageNode({item:n,parentSlug:i}),apiSection:async n=>this.toApiSectionNode({item:n,parentSlug:i}),section:async n=>this.toSectionNode({prefix:r,item:n,parentSlug:i}),link:async n=>this.toLinkNode(n),changelog:async n=>this.toChangelogNode(n,i),pythonDocsSection:async n=>this.handlePythonDocsSection(n,i)})}async toNavigationChild({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){return LT(r)._visit({page:async o=>this.toPageNode({item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),apiSection:async o=>this.toApiSectionNode({item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),section:async o=>this.toSectionNode({prefix:t,item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),link:async o=>this.toLinkNode(o),changelog:async o=>this.toChangelogNode(o,i,n),pythonDocsSection:async o=>this.handlePythonDocsSection(o,i)})}async toApiSectionNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=O1E(t.snippetsConfiguration),o,c,d,s,u=this.parsedDocsConfig.experimental?.openapiParserV3,f=u==null||u;if(f)try{d=this.getOpenApiWorkspaceForApiSection(t),o=await d.getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1})}catch(m){s=m}let p;if(t.tagDescriptionPages&&f)try{let g=await(d??this.getOpenApiWorkspaceForApiSection(t)).getOpenAPIIr({context:this.taskContext,loadAiExamples:!0});g.tags.tagsById&&(p=Object.fromEntries(Object.entries(g.tags.tagsById).filter(([A,j])=>j.description&&j.description.trim().length>0).map(([A,j])=>[mn(A),{id:String(j.id),description:j.description}])))}catch(m){this.taskContext.logger.warn("Failed to extract OpenAPI tags for tag description pages",String(m))}if(o==null){if(this.apiWorkspaces.length===0&&s!=null)throw s;c=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,preserveSchemaIds:!0}),o=ME({workspace:c,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new IE(this.taskContext,c)})}else if(Object.keys(a).length>0)try{c=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,preserveSchemaIds:!0})}catch(m){this.taskContext.logger.debug(`Could not load workspace for dynamic snippets: ${m}. Dynamic snippets may not be available.`)}this.docsWorkspace.config.settings?.substituteEnvVars&&(o=eN(o,{onError:m=>this.taskContext.failAndThrow(`Error substituting environment variables in API spec: ${m}`)},{substituteAsEmpty:!1}));let _=await this.extractGraphQLData(),h=t.apiName??c?.workspaceName??d?.workspaceName,y=await this.registerApi({ir:o,snippetsConfig:a,playgroundConfig:{oauth:t.playground?.oauth},apiName:h,workspace:c,graphqlOperations:_.operations,graphqlTypes:_.types}),b=SLo({ir:o,apiDefinitionId:y,playgroundConfig:{oauth:t.playground?.oauth},context:this.taskContext,graphqlOperations:_.operations,graphqlTypes:_.types}),v=new Sec(t,b,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.#e,this.collectedFileIds,c,i,n??t.availability,p,_.namespacesByOperationId),O=v.getTagDescriptionContent();for(let[m,g]of O.entries()){let A=m.split("/").pop()||m,j=Pe.of(A),M=g;this.docsWorkspace.config.settings?.substituteEnvVars&&(M=eN(g,{onError:w=>this.taskContext.logger.error(`Error in tag description environment variable substitution: ${w}`)},{substituteAsEmpty:!1})),this.rawMarkdownFiles[j]=M,this.parsedDocsConfig.pages[j]=M}return v.get()}async toChangelogNode(t,r,i){return new lea(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:i||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:Ut.V1.Url(t.url),icon:this.resolveIconFileId(t.icon),target:t.target}}async extractGraphQLData(){let t={},r={},i=new Map;for(let n of this.ossWorkspaces){Object.assign(t,n.getGraphqlOperations()),Object.assign(r,n.getGraphqlTypes());let a=n.allSpecs.filter(o=>o.type==="graphql");for(let o of a)if(o.namespace!=null)try{let d=await new Lha({context:this.taskContext,filePath:o.absoluteFilepath}).convert();for(let s of Object.keys(d.graphqlOperations))i.set(Jr.GraphQlOperationId(s),o.namespace)}catch(c){this.taskContext.logger.error(`Failed to process GraphQL spec for namespace mapping ${o.absoluteFilepath}:`,String(c))}}return{operations:t,types:r,namespacesByOperationId:i}}handlePythonDocsSection(t,r){return this.pythonDocsSectionHandler==null?null:this.pythonDocsSectionHandler(t,r,{addPage:(i,n)=>{this.parsedDocsConfig.pages[Pe.of(i)]=n},generateId:i=>this.#e.get(i)})}async toPageNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=Ut.PageId(this.toRelativeFilepath(t.absolutePath)),o=r.apply({urlSlug:t.slug??q0(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{id:this.#e.get(a),type:"page",slug:o.get(),title:this.markdownFilesToSidebarTitle.get(t.absolutePath)??t.title,icon:this.resolveIconFileId(t.icon),hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:a,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags,availability:t.availability??n}}async toSectionNode({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){let o=this.toRelativeFilepath(r.overviewAbsolutePath),c=o?Ut.PageId(o):void 0,d=this.#e.get(c??`${t}/section`),s=i.apply({urlSlug:r.slug??q0(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),u=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,f=n||r.hidden,_=(await Promise.all(r.contents.map(h=>this.toNavigationChild({prefix:d,item:h,parentSlug:s,hideChildren:f,parentAvailability:r.availability??a})))).filter(h=>h!=null);if(c==null){let h=_.find(y=>y.type==="apiReference"&&y.hideTitle===!0&&y.overviewPageId!=null);h!=null&&(c=h.overviewPageId)}return{id:d,type:"section",overviewPageId:c,slug:s.get(),title:r.overviewAbsolutePath!=null?this.markdownFilesToSidebarTitle.get(r.overviewAbsolutePath)??r.title:r.title,icon:this.resolveIconFileId(r.icon),collapsed:r.collapsed,hidden:f,viewers:r.viewers,orphaned:r.orphaned,children:_,authed:void 0,pointsTo:void 0,noindex:u,featureFlags:r.featureFlags,availability:r.availability??a}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return LT(r.child)._visit({link:({href:n,target:a})=>this.toTabLinkNode(r,n,a),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i),variants:({variants:n})=>this.toTabNodeWithVariants(t,r,n,i)})}async toTabChangelogNode(t,r,i){return new lea(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r,i){return{type:"link",id:this.#e.get(r),title:t.title,url:Ut.V1.Url(r),target:i,icon:this.resolveIconFileId(t.icon)}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??q0(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,o),featureFlags:r.featureFlags}}async toTabNodeWithVariants(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??q0(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNodeWithVariants(a,i,o),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):l7.FileId(r)}resolveIconFileId(t){if(t!=null)return this.collectedFileIds.has(t)?`file:${this.getFileId(t)}`:t}convertPageActions(){if(this.parsedDocsConfig.pageActions!=null)return{default:this.parsedDocsConfig.pageActions.default,options:{askAi:this.parsedDocsConfig.pageActions.options.askAi,copyPage:this.parsedDocsConfig.pageActions.options.copyPage,viewAsMarkdown:this.parsedDocsConfig.pageActions.options.viewAsMarkdown,openAi:this.parsedDocsConfig.pageActions.options.openAi,claude:this.parsedDocsConfig.pageActions.options.claude,cursor:this.parsedDocsConfig.pageActions.options.cursor,vscode:this.parsedDocsConfig.pageActions.options.vscode,custom:this.parsedDocsConfig.pageActions.options.custom.map(t=>({title:t.title,subtitle:t.subtitle,url:t.url,icon:this.resolveIconFileId(t.icon),default:t.default}))}}}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(Cs),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:l7.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return LT(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:l7.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function W5x(e,t){let r=e?.launch??"github";if(e?.github==null)return{url:void 0,launch:r};let{owner:i,repo:n,branch:a="main",host:o="https://github.com"}=e.github;return{url:`${LY(o)}/${i}/${n}/blob/${a}/fern/${t}?plain=1`,launch:r}}function x5x(e){switch(e){case"beta":return Ut.V1.NavigationV1Availability.Beta;case"deprecated":return Ut.V1.NavigationV1Availability.Deprecated;case"ga":return Ut.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Ut.V1.NavigationV1Availability.Stable;default:fe(e)}}function Cmp(e,t,r){let i=e.title??"Python Reference",n=e.slug??"python-docs",a=t.apply({urlSlug:n}),o=`__python-docs-placeholder-${n}__.mdx`,c=Ut.PageId(o),d=`---
|
|
2160
|
+
https://buildwithfern.com/learn/docs/getting-started/project-structure#api-definitions`;throw new Error(r)}async toRootNode(){let t=Ut.V1.SlugGenerator.init(Ut.slugjoin(this.getDocsBasePath())),r=this.#e.get("root"),i=await this.toRootChild(t);return{type:"root",version:"v1",id:r,child:i,slug:t.get(),title:this.parsedDocsConfig.title??"Documentation",hidden:!1,icon:void 0,pointsTo:void 0,authed:void 0,viewers:void 0,orphaned:void 0,roles:this.parsedDocsConfig.roles?.map(n=>Ut.RoleId(n)),featureFlags:void 0}}async toRootChild(t){return LT(this.parsedDocsConfig.navigation)._visit({untabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),tabbed:r=>this.toUnversionedNode({landingPage:this.parsedDocsConfig.landingPage,navigationConfig:r,parentSlug:t}),versioned:r=>this.toVersionedNode(r,t),productgroup:r=>this.toProductGroupNode({landingPageConfig:this.parsedDocsConfig.landingPage,productGroup:r,parentSlug:t})})}toLandingPageNode(t,r){let i=Ut.PageId(this.toRelativeFilepath(t.absolutePath)),n=r.apply({urlSlug:t.slug??q0(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")});return{type:"landingPage",id:this.#e.get(i),title:t.title,slug:n.get(),icon:this.resolveIconFileId(t.icon),hidden:t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:i,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags}}async toUnversionedNode({landingPage:t,navigationConfig:r,parentSlug:i}){let n=this.#e.get("unversioned"),a=t!=null?this.toLandingPageNode(t,i):void 0,o=r.type==="tabbed"?await this.convertTabbedNavigation(n,r.items,i):await this.toSidebarRootNode(n,r.items,i);return{type:"unversioned",id:n,landingPage:a,child:o}}async toVersionedNode(t,r){let i=this.#e.get("versioned"),n=t.versions[0];if(n?.hidden===!0)throw new Error(`The default version "${n.version}" cannot be hidden. Please set a non-hidden version as the first version in your versions list, or remove the hidden flag from the default version.`);let a=5,o=[];for(let c=0;c<t.versions.length;c+=a){let d=t.versions.slice(c,c+a),s=await Promise.all(d.map((u,f)=>this.toVersionNode(u,r,c+f===0)));o.push(...s)}return{id:i,type:"versioned",children:o}}async toProductGroupNode({productGroup:t,landingPageConfig:r,parentSlug:i}){let n=this.#e.get("productgroup"),a=r!=null?this.toLandingPageNode(r,i):void 0;return{id:n,type:"productgroup",landingPage:a,children:await Promise.all(t.products.map(o=>this.toProductNode(o,i)))}}async toProductNode(t,r){if(t.type==="internal"){let i=r.setProductSlug(t.slug??q0(t.product)),n;switch(t.navigation.type){case"tabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.convertTabbedNavigation(this.#e.get(t.product),t.navigation.items,i)};break;case"untabbed":n={type:"unversioned",id:this.#e.get(t.product),landingPage:void 0,child:await this.toSidebarRootNode(this.#e.get(t.product),t.navigation.items,i)};break;case"versioned":n=await this.toVersionedNode(t.navigation,i);break;default:fe(t.navigation)}return{type:"product",id:this.#e.get(t.product),productId:Ut.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",slug:i.get(),child:n,default:!1,hidden:void 0,authed:void 0,icon:this.resolveIconFileId(t.icon),image:t.image!=null?this.getFileId(t.image):void 0,pointsTo:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,announcement:t.announcement!=null?{text:t.announcement.message}:void 0}}else return{type:"productLink",id:this.#e.get(t.product),productId:Ut.V1.ProductId(t.product),title:t.product,subtitle:t.subtitle??"",href:l7.Url(t.href??""),target:t.target,default:!1,hidden:void 0,authed:void 0,icon:this.resolveIconFileId(t.icon),image:t.image!=null?this.getFileId(t.image):void 0,viewers:t.viewers,orphaned:t.orphaned}}async toVersionNode(t,r,i){let n=this.#e.get(t.version),a=r.setVersionSlug(t.slug??q0(t.version)),o=t.navigation.type==="tabbed"?await this.convertTabbedNavigation(n,t.navigation.items,a):await this.toSidebarRootNode(n,t.navigation.items,a);return{type:"version",id:n,versionId:Ut.VersionId(t.version),title:t.version,slug:a.get(),child:o,default:i,availability:t.availability!=null?x5x(t.availability):void 0,landingPage:t.landingPage?this.toLandingPageNode(t.landingPage,a):void 0,hidden:t.hidden,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,icon:void 0,pointsTo:void 0,featureFlags:t.featureFlags,announcement:t.announcement!=null?{text:t.announcement.message}:void 0}}async toSidebarRootNode(t,r,i){let n=this.#e.get(`${t}/root`),o=(await Promise.all(r.map(d=>this.toNavigationChild({prefix:n,item:d,parentSlug:i})))).filter(d=>d!=null),c=[];return o.forEach(d=>{if(d.type==="apiReference"){c.push(d);return}if(d.type==="section"&&!d.collapsed){c.push(d);return}let s=c.length>0?c[c.length-1]:void 0,u;s?.type==="sidebarGroup"?u=s:(u={id:this.#e.get(`${n}/group`),type:"sidebarGroup",children:[]},c.push(u)),u.children.push(d)}),{type:"sidebarRoot",id:n,children:c}}async toSidebarRootNodeWithVariants(t,r,i){let n=this.#e.get(`${t}/root`);return{type:"sidebarRoot",id:n,children:[{type:"varianted",id:n,children:await Promise.all(r.map(a=>this.toVariantNode(a,n,i)))}]}}async toVariantNode(t,r,i){let n=this.#e.get(`${r}/variant/${t.slug??q0(t.title)}`),a=i.apply({urlSlug:t.slug??q0(t.title),skipUrlSlug:t.skipUrlSlug}),c=(await Promise.all(t.layout.map(d=>this.toVariantChild(d,n,a)))).filter(d=>d!=null);return{type:"variant",id:n,variantId:Ut.V1.VariantId(t.title),subtitle:t.subtitle??"",default:t.default??!1,image:void 0,children:c,title:t.title,slug:a.get(),icon:this.resolveIconFileId(t.icon),hidden:t.hidden,authed:void 0,viewers:t.viewers,orphaned:t.orphaned,featureFlags:t.featureFlags,pointsTo:void 0}}async toVariantChild(t,r,i){return LT(t)._visit({page:async n=>this.toPageNode({item:n,parentSlug:i}),apiSection:async n=>this.toApiSectionNode({item:n,parentSlug:i}),section:async n=>this.toSectionNode({prefix:r,item:n,parentSlug:i}),link:async n=>this.toLinkNode(n),changelog:async n=>this.toChangelogNode(n,i),pythonDocsSection:async n=>this.handlePythonDocsSection(n,i)})}async toNavigationChild({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){return LT(r)._visit({page:async o=>this.toPageNode({item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),apiSection:async o=>this.toApiSectionNode({item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),section:async o=>this.toSectionNode({prefix:t,item:o,parentSlug:i,hideChildren:n,parentAvailability:a}),link:async o=>this.toLinkNode(o),changelog:async o=>this.toChangelogNode(o,i,n),pythonDocsSection:async o=>this.handlePythonDocsSection(o,i)})}async toApiSectionNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=O1E(t.snippetsConfiguration),o,c,d,s,u=this.parsedDocsConfig.experimental?.openapiParserV3,f=u==null||u;if(f)try{d=this.getOpenApiWorkspaceForApiSection(t),o=await d.getIntermediateRepresentation({context:this.taskContext,audiences:t.audiences,enableUniqueErrorsPerEndpoint:!0,generateV1Examples:!1,logWarnings:!1})}catch(m){s=m}let p;if(t.tagDescriptionPages&&f)try{let g=await(d??this.getOpenApiWorkspaceForApiSection(t)).getOpenAPIIr({context:this.taskContext,loadAiExamples:!0});g.tags.tagsById&&(p=Object.fromEntries(Object.entries(g.tags.tagsById).filter(([A,j])=>j.description&&j.description.trim().length>0).map(([A,j])=>[mn(A),{id:String(j.id),description:j.description}])))}catch(m){this.taskContext.logger.warn("Failed to extract OpenAPI tags for tag description pages",String(m))}if(o==null){if(this.apiWorkspaces.length===0&&s!=null)throw s;c=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,preserveSchemaIds:!0}),o=ME({workspace:c,audiences:t.audiences,generationLanguage:void 0,keywords:void 0,smartCasing:!1,exampleGeneration:{disabled:!1,skipAutogenerationIfManualExamplesExist:!0,skipErrorAutogenerationIfManualErrorExamplesExist:!0},readme:void 0,version:void 0,packageName:void 0,context:this.taskContext,sourceResolver:new IE(this.taskContext,c)})}else if(Object.keys(a).length>0)try{c=await this.getFernWorkspaceForApiSection(t).toFernWorkspace({context:this.taskContext},{enableUniqueErrorsPerEndpoint:!0,detectGlobalHeaders:!1,objectQueryParameters:!0,preserveSchemaIds:!0})}catch(m){this.taskContext.logger.debug(`Could not load workspace for dynamic snippets: ${m}. Dynamic snippets may not be available.`)}this.docsWorkspace.config.settings?.substituteEnvVars&&(o=eN(o,{onError:m=>this.taskContext.failAndThrow(`Error substituting environment variables in API spec: ${m}`)},{substituteAsEmpty:!1}));let _=await this.extractGraphQLData(),h=t.apiName??c?.workspaceName??d?.workspaceName,y=await this.registerApi({ir:o,snippetsConfig:a,playgroundConfig:{oauth:t.playground?.oauth},apiName:h,workspace:c,graphqlOperations:_.operations,graphqlTypes:_.types}),b=SLo({ir:o,apiDefinitionId:y,playgroundConfig:{oauth:t.playground?.oauth},context:this.taskContext,graphqlOperations:_.operations,graphqlTypes:_.types}),v=new Sec(t,b,r,this.docsWorkspace,this.taskContext,this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,this.#e,this.collectedFileIds,c,i,n??t.availability,p,_.namespacesByOperationId),O=v.getTagDescriptionContent();for(let[m,g]of O.entries()){let A=m.split("/").pop()||m,j=Pe.of(A),M=g;this.docsWorkspace.config.settings?.substituteEnvVars&&(M=eN(g,{onError:w=>this.taskContext.logger.error(`Error in tag description environment variable substitution: ${w}`)},{substituteAsEmpty:!1})),this.rawMarkdownFiles[j]=M,this.parsedDocsConfig.pages[j]=M}return v.get()}async toChangelogNode(t,r,i){return new lea(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,t.changelog,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:r,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:i||t.hidden,slug:t.slug})}async toLinkNode(t){return{type:"link",id:this.#e.get(t.url),title:t.text,url:Ut.V1.Url(t.url),icon:this.resolveIconFileId(t.icon),target:t.target}}async extractGraphQLData(){let t={},r={},i=new Map;for(let n of this.ossWorkspaces){Object.assign(t,n.getGraphqlOperations()),Object.assign(r,n.getGraphqlTypes());let a=n.allSpecs.filter(o=>o.type==="graphql");for(let o of a)if(o.namespace!=null)try{let d=await new Lha({context:this.taskContext,filePath:o.absoluteFilepath}).convert();for(let s of Object.keys(d.graphqlOperations))i.set(Jr.GraphQlOperationId(s),o.namespace)}catch(c){this.taskContext.logger.error(`Failed to process GraphQL spec for namespace mapping ${o.absoluteFilepath}:`,String(c))}}return{operations:t,types:r,namespacesByOperationId:i}}handlePythonDocsSection(t,r){return this.pythonDocsSectionHandler==null?null:this.pythonDocsSectionHandler(t,r,{addPage:(i,n)=>{this.parsedDocsConfig.pages[Pe.of(i)]=n},generateId:i=>this.#e.get(i)})}async toPageNode({item:t,parentSlug:r,hideChildren:i,parentAvailability:n}){let a=Ut.PageId(this.toRelativeFilepath(t.absolutePath)),o=r.apply({urlSlug:t.slug??q0(t.title),fullSlug:this.markdownFilesToFullSlugs.get(t.absolutePath)?.split("/")}),c=this.#e.get(a),d=this.markdownFilesToAvailability.get(t.absolutePath);return{id:c,type:"page",slug:o.get(),title:this.markdownFilesToSidebarTitle.get(t.absolutePath)??t.title,icon:this.resolveIconFileId(t.icon),hidden:i||t.hidden,viewers:t.viewers,orphaned:t.orphaned,pageId:a,authed:void 0,noindex:t.noindex||this.markdownFilesToNoIndex.get(t.absolutePath),featureFlags:t.featureFlags,availability:d??t.availability??n}}async toSectionNode({prefix:t,item:r,parentSlug:i,hideChildren:n,parentAvailability:a}){let o=this.toRelativeFilepath(r.overviewAbsolutePath),c=o?Ut.PageId(o):void 0,d=this.#e.get(c??`${t}/section`),s=i.apply({urlSlug:r.slug??q0(r.title),fullSlug:r.overviewAbsolutePath?this.markdownFilesToFullSlugs.get(r.overviewAbsolutePath)?.split("/"):void 0,skipUrlSlug:r.skipUrlSlug}),u=r.overviewAbsolutePath!=null?this.markdownFilesToNoIndex.get(r.overviewAbsolutePath):void 0,f=r.overviewAbsolutePath!=null?this.markdownFilesToAvailability.get(r.overviewAbsolutePath):void 0,p=n||r.hidden,h=(await Promise.all(r.contents.map(y=>this.toNavigationChild({prefix:d,item:y,parentSlug:s,hideChildren:p,parentAvailability:r.availability??a})))).filter(y=>y!=null);if(c==null){let y=h.find(b=>b.type==="apiReference"&&b.hideTitle===!0&&b.overviewPageId!=null);y!=null&&(c=y.overviewPageId)}return{id:d,type:"section",overviewPageId:c,slug:s.get(),title:r.overviewAbsolutePath!=null?this.markdownFilesToSidebarTitle.get(r.overviewAbsolutePath)??r.title:r.title,icon:this.resolveIconFileId(r.icon),collapsed:r.collapsed,hidden:p,viewers:r.viewers,orphaned:r.orphaned,children:h,authed:void 0,pointsTo:void 0,noindex:u,featureFlags:r.featureFlags,availability:f??r.availability??a}}async convertTabbedNavigation(t,r,i){let n=this.#e.get(`${t}/tabbed`);return{type:"tabbed",id:n,children:await Promise.all(r.map(a=>this.toTabChild(n,a,i)))}}async toTabChild(t,r,i){return LT(r.child)._visit({link:({href:n,target:a})=>this.toTabLinkNode(r,n,a),layout:({layout:n})=>this.toTabNode(t,r,n,i),changelog:({changelog:n})=>this.toTabChangelogNode(r,n,i),variants:({variants:n})=>this.toTabNodeWithVariants(t,r,n,i)})}async toTabChangelogNode(t,r,i){return new lea(this.markdownFilesToFullSlugs,this.markdownFilesToNoIndex,this.markdownFilesToTags,r,this.docsWorkspace,this.#e).toChangelogNode({parentSlug:i,title:t.title,icon:this.resolveIconFileId(t.icon),viewers:t.viewers,hidden:t.hidden,slug:t.slug})}async toTabLinkNode(t,r,i){return{type:"link",id:this.#e.get(r),title:t.title,url:Ut.V1.Url(r),target:i,icon:this.resolveIconFileId(t.icon)}}async toTabNode(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??q0(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNode(a,i,o),featureFlags:r.featureFlags}}async toTabNodeWithVariants(t,r,i,n){let a=this.#e.get(`${t}/tab`),o=n.apply({urlSlug:r.slug??q0(r.title),skipUrlSlug:r.skipUrlSlug});return{type:"tab",id:a,title:r.title,slug:o.get(),icon:this.resolveIconFileId(r.icon),hidden:r.hidden,authed:void 0,viewers:r.viewers,orphaned:r.orphaned,pointsTo:void 0,child:await this.toSidebarRootNodeWithVariants(a,i,o),featureFlags:r.featureFlags}}getFileId(t){if(t==null)return;let r=this.collectedFileIds.get(t);return r==null?this.taskContext.failAndThrow("Failed to locate file after uploading: "+t):l7.FileId(r)}resolveIconFileId(t){if(t!=null)return this.collectedFileIds.has(t)?`file:${this.getFileId(t)}`:t}convertPageActions(){if(this.parsedDocsConfig.pageActions!=null)return{default:this.parsedDocsConfig.pageActions.default,options:{askAi:this.parsedDocsConfig.pageActions.options.askAi,copyPage:this.parsedDocsConfig.pageActions.options.copyPage,viewAsMarkdown:this.parsedDocsConfig.pageActions.options.viewAsMarkdown,openAi:this.parsedDocsConfig.pageActions.options.openAi,claude:this.parsedDocsConfig.pageActions.options.claude,cursor:this.parsedDocsConfig.pageActions.options.cursor,vscode:this.parsedDocsConfig.pageActions.options.vscode,custom:this.parsedDocsConfig.pageActions.options.custom.map(t=>({title:t.title,subtitle:t.subtitle,url:t.url,icon:this.resolveIconFileId(t.icon),default:t.default}))}}}convertColorConfigImageReferences(){let{colors:t}=this.parsedDocsConfig;if(t!=null)return t.type==="dark"?{...t,...this.convertLogoAndBackgroundImage({theme:"dark"})}:t.type==="light"?{...t,...this.convertLogoAndBackgroundImage({theme:"light"}),type:"light"}:{...t,dark:{...t.dark,...this.convertLogoAndBackgroundImage({theme:"dark"})},light:{...t.light,...this.convertLogoAndBackgroundImage({theme:"light"})}}}convertLogoAndBackgroundImage({theme:t}){let{logo:r,backgroundImage:i}=this.parsedDocsConfig,n=r?.[t],a=i?.[t];return{logo:this.getFileId(n),backgroundImage:this.getFileId(a)}}convertDocsTypographyConfiguration(){if(this.parsedDocsConfig.typography!=null)return{headingsFont:this.convertFont(this.parsedDocsConfig.typography.headingsFont,"headings"),bodyFont:this.convertFont(this.parsedDocsConfig.typography.bodyFont,"body"),codeFont:this.convertFont(this.parsedDocsConfig.typography.codeFont,"code")}}convertFont(t,r){if(t==null||t.variants[0]==null)return;let i=this.getFileId(t.variants[0].absolutePath);return{type:"custom",name:t.name??`font:${r}:${i}`,variants:t.variants.map(n=>({fontFile:this.getFileId(n.absolutePath),weight:n.weight,style:n.style!=null?[n.style]:void 0})),display:t.display,fallback:t.fallback,fontVariationSettings:t.fontVariationSettings}}convertJavascriptConfiguration(){if(this.parsedDocsConfig.js!=null)return{files:this.parsedDocsConfig.js.files.map(({absolutePath:t,strategy:r})=>({fileId:this.getFileId(t),strategy:r})).filter(Cs),remote:this.parsedDocsConfig.js.remote?.map(t=>({...t,url:l7.Url(t.url)})),inline:void 0}}convertMetadata(){if(this.parsedDocsConfig.metadata==null)return;let{"og:image":t,"og:logo":r,"twitter:image":i,...n}=this.parsedDocsConfig.metadata;return{...n,"og:image":this.convertFileIdOrUrl(t),"og:logo":this.convertFileIdOrUrl(r),"twitter:image":this.convertFileIdOrUrl(i)}}convertFileIdOrUrl(t){if(t!=null)return LT(t,"type")._visit({filepath:({value:r})=>({type:"fileId",value:this.getFileId(r)}),url:({value:r})=>({type:"url",value:l7.Url(r)}),_other:()=>this.taskContext.failAndThrow("Invalid metadata configuration")})}};function W5x(e,t){let r=e?.launch??"github";if(e?.github==null)return{url:void 0,launch:r};let{owner:i,repo:n,branch:a="main",host:o="https://github.com"}=e.github;return{url:`${LY(o)}/${i}/${n}/blob/${a}/fern/${t}?plain=1`,launch:r}}function x5x(e){switch(e){case"beta":return Ut.V1.NavigationV1Availability.Beta;case"deprecated":return Ut.V1.NavigationV1Availability.Deprecated;case"ga":return Ut.V1.NavigationV1Availability.GenerallyAvailable;case"stable":return Ut.V1.NavigationV1Availability.Stable;default:fe(e)}}function Cmp(e,t,r){let i=e.title??"Python Reference",n=e.slug??"python-docs",a=t.apply({urlSlug:n}),o=`__python-docs-placeholder-${n}__.mdx`,c=Ut.PageId(o),d=`---
|
|
2161
2161
|
title: ${i}
|
|
2162
2162
|
---
|
|
2163
2163
|
|
|
@@ -2263,7 +2263,7 @@ ${MWE.default.cursorShow}`)}releaseCursor(){this.extraLinesUnderPrompt>0&&uwp(th
|
|
|
2263
2263
|
`+Bea.default.red(">> ")+t),this.screen.render(r,i)}getMaskedValue(t){return this.status==="answered"?this.opt.mask?Bea.default.cyan(NWE(t,this.opt.mask)):Bea.default.italic(Bea.default.dim("[hidden]")):this.opt.mask?NWE(t,this.opt.mask):Bea.default.italic(Bea.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 moc=se(uQ(),1);var z8E=se(Vwp(),1),goc=require("child_process"),Wxa=require("fs"),voc=se(require("path"),1),N8E=se(require("os"),1),F8E=require("crypto"),E0p=se(T8E(),1);var hoc=class extends Error{originalError;constructor(t){super(`Failed to create temporary file. ${t.message}`),this.originalError=t}};var R4o=class extends Error{originalError;constructor(t){super(`Failed to launch editor. ${t.message}`),this.originalError=t}};var yoc=class extends Error{originalError;constructor(t){super(`Failed to read temporary file. ${t.message}`),this.originalError=t}};var boc=class extends Error{originalError;constructor(t){super(`Failed to remove temporary file. ${t.message}`),this.originalError=t}};function Ooc(e="",t,r){let i=new S0p(e,r);i.runAsync((n,a)=>{if(n)setImmediate(t,n,void 0);else try{i.cleanup(),setImmediate(t,void 0,a)}catch(o){setImmediate(t,o,void 0)}})}function R8E(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}function pf5(e){let t=[],r="";for(let i=0;i<e.length;i++){let n=e.charAt(i);i>0&&n===" "&&e[i-1]!=="\\"&&r.length>0?(t.push(r),r=""):r=`${r}${n}`}return r.length>0&&t.push(r),t}var S0p=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=pf5(t).map(n=>n.replace("\\ "," ")),i=r.shift();this.editor={args:r,bin:i}}createTemporaryFile(){try{let t=this.fileOptions.dir??N8E.default.tmpdir(),r=(0,F8E.randomUUID)(),i=R8E(this.fileOptions.prefix),n=R8E(this.fileOptions.postfix),a=`${i}${r}${n}`,o=voc.default.resolve(t,a),c=voc.default.resolve(t)+voc.default.sep;if(!o.startsWith(c))throw new Error("Resolved temporary file escaped the base directory");this.tempFile=o;let d={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(d.mode=this.fileOptions.mode),(0,Wxa.writeFileSync)(this.tempFile,this.text,d)}catch(t){throw new hoc(t)}}readTemporaryFile(){try{let t=(0,Wxa.readFileSync)(this.tempFile);if(t.length===0)this.text="";else{let r=(0,z8E.detect)(t)??"utf8";E0p.default.encodingExists(r)||(r="utf8"),this.text=E0p.default.decode(t,r)}}catch(t){throw new yoc(t)}}removeTemporaryFile(){try{(0,Wxa.unlinkSync)(this.tempFile)}catch(t){throw new boc(t)}}launchEditor(){try{let t=(0,goc.spawnSync)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"});this.lastExitStatus=t.status??0}catch(t){throw new R4o(t)}}launchEditorAsync(t){try{(0,goc.spawn)(this.editor.bin,this.editor.args.concat([this.tempFile]),{stdio:"inherit"}).on("exit",i=>{this.lastExitStatus=i,setImmediate(t)})}catch(r){throw new R4o(r)}}};var Q8E=se(zEe(),1);var z4o=class extends sQ{_run(t){this.done=t,this.editorResult=new Q8E.Subject;let r=zx(this.rl);this.lineSubscription=r.line.subscribe(this.startExternalEditor.bind(this));let i=this.opt.waitUserInput===void 0?!0:this.opt.waitUserInput,n=this.handleSubmitEvents(this.editorResult);return n.success.forEach(this.onEnd.bind(this)),n.error.forEach(this.onError.bind(this)),this.currentText=this.opt.default,this.opt.default=null,i?this.render():this.startExternalEditor(),this}render(t){let r="",i=this.getQuestion();i+=this.status==="answered"?moc.default.dim("Received"):moc.default.dim("Press <enter> to launch your preferred editor."),t&&(r=moc.default.red(">> ")+t),this.screen.render(i,r)}startExternalEditor(){this.rl.pause(),Ooc(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 x8E=require("stream");var V8E=se(require("readline"),1),W8E=se(L8E(),1),Tea=class{constructor(t){this.rl||=V8E.default.createInterface(hf5(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 hf5(e={}){e.skipTTYChecks=e.skipTTYChecks===void 0?!0:e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY){let n=new Error("Prompts can not be meaningfully rendered in non-TTY environments");throw n.isTtyError=!0,n}let r=new W8E.default;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}var N4o=class extends Tea{constructor(t={}){super(t),this.log=new x8E.Writable({write:(r,i,n)=>{this.writeLog(r),n()}}),this.bottomBar=t.bottomBar||"",this.render()}render(){return this.write(this.bottomBar),this}clean(){return O4o(this.rl,this.bottomBar.split(`
|
|
2264
2264
|
`).length),this}updateBottomBar(t){return O4o(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+`
|
|
2265
2265
|
`}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&&Wac(this.rl,t.length+this.rl.line.length),this.rl.output.write(t)}};var AA=se(zEe(),1),K8E=se(XLo(),1);var Aoc=se(zEe(),1),G8E=se(XLo(),1),Poc=function(e,t,r){return typeof e[t]!="function"?(0,Aoc.of)(e):(0,Aoc.from)((0,G8E.default)(e[t])(r).then(i=>(e[t]=i,e)))};var H8E={set:(e,t="",r)=>{let i=e;t.split(".").forEach((n,a,o)=>{n==="__proto__"||n==="constructor"||(a===o.length-1?i[n]=r:(!(n in i)||typeof i[n]!="object")&&(i[n]={}),i=i[n])})},get:(e,t="",r)=>{let i=a=>String.prototype.split.call(t,a).filter(Boolean).reduce((o,c)=>o!=null?o[c]:o,e),n=i(/[,[\]]+?/)||i(/[,.[\]]+?/);return n===void 0||n===e?r:n}},xxa=class extends Tea{constructor(t,r){super(r),this.prompts=t}run(t,r){this.answers=typeof r=="object"?{...r}:{};let i;return Array.isArray(t)?i=(0,AA.from)(t):(0,AA.isObservable)(t)?i=t:Object.values(t).every(n=>typeof n=="object"&&!Array.isArray(n)&&n!=null)?i=(0,AA.from)(Object.entries(t).map(([n,a])=>({name:n,...a}))):i=(0,AA.from)([t]),this.process=i.pipe((0,AA.concatMap)(this.processQuestion.bind(this)),(0,AA.publish)()),this.process.connect(),this.process.pipe((0,AA.reduce)((n,a)=>(H8E.set(n,a.name,a.answer),n),this.answers)).toPromise(Promise).then(this.onCompletion.bind(this),this.onError.bind(this))}onCompletion(){return this.close(),this.answers}onError(t){return this.close(),Promise.reject(t)}processQuestion(t){return t={...t},(0,AA.defer)(()=>(0,AA.of)(t).pipe((0,AA.concatMap)(this.setDefaultType.bind(this)),(0,AA.concatMap)(this.filterIfRunnable.bind(this)),(0,AA.concatMap)(()=>Poc(t,"message",this.answers)),(0,AA.concatMap)(()=>Poc(t,"default",this.answers)),(0,AA.concatMap)(()=>Poc(t,"choices",this.answers)),(0,AA.concatMap)(this.fetchAnswer.bind(this))))}fetchAnswer(t){let r=this.prompts[t.type];return this.activePrompt=new r(t,this.rl,this.answers),(0,AA.defer)(()=>(0,AA.from)(this.activePrompt.run().then(i=>({name:t.name,answer:i}))))}setDefaultType(t){return this.prompts[t.type]||(t.type="input"),(0,AA.defer)(()=>(0,AA.of)(t))}filterIfRunnable(t){if(t.askAnswered!==!0&&H8E.get(this.answers,t.name)!==void 0)return AA.EMPTY;if(t.when===!1)return AA.EMPTY;if(typeof t.when!="function")return(0,AA.of)(t);let{answers:r}=this;return(0,AA.defer)(()=>(0,AA.from)((0,K8E.default)(t.when)(r).then(i=>{if(i)return t})).pipe((0,AA.filter)(i=>i!=null)))}};function $8E(e){let t=function(r,i){let n;try{n=new xxa(t.prompts,e)}catch(o){return Promise.reject(o)}let a=n.run(r,i);return a.ui=n,a};return t.prompts={},t.registerPrompt=function(r,i){return t.prompts[r]=i,this},t.restoreDefaultPrompts=function(){this.registerPrompt("list",A4o),this.registerPrompt("input",Dea),this.registerPrompt("number",P4o),this.registerPrompt("confirm",j4o),this.registerPrompt("rawlist",w4o),this.registerPrompt("expand",E4o),this.registerPrompt("checkbox",S4o),this.registerPrompt("password",M4o),this.registerPrompt("editor",z4o)},t.restoreDefaultPrompts(),t}var D0p=$8E();function bf5(e,t){D0p.registerPrompt(e,t)}function vf5(){D0p.restoreDefaultPrompts()}var gf5={prompt:D0p,ui:{BottomBar:N4o,Prompt:xxa},createPromptModule:$8E,registerPrompt:bf5,restoreDefaultPrompts:vf5,Separator:EOe},joc=gf5;var Gxa=require("path");function Y8E(){let e=Of5();return async t=>{for(let r of t)r.module=e(r.filename);return t}}function Of5(e=process.argv[1]?(0,Gxa.dirname)(process.argv[1]):process.cwd(),t=Gxa.sep==="\\"){let r=t?J8E(e):e;return i=>{if(!i)return;let n=t?J8E(i):i,{dir:a,base:o,ext:c}=Gxa.posix.parse(n);(c===".js"||c===".mjs"||c===".cjs")&&(o=o.slice(0,-1*c.length));let d=decodeURIComponent(o);a||(a=".");let s=a.lastIndexOf("/node_modules");if(s>-1)return`${a.slice(s+14).replace(/\//g,".")}:${d}`;if(a.startsWith(r)){let u=a.slice(r.length+1).replace(/\//g,".");return u?`${u}:${d}`:d}return d}}function J8E(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var B0p=e=>{if("flags"in e){let t=X8E(e.flags),r=Z8E(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,a])=>[n,k8E(a)])),i=Object.fromEntries(Object.entries(t).map(([n,a])=>[n,mf5(n,a,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function mf5(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 X8E=e=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,F4o(r)]).filter(([,t])=>t!==void 0)),Z8E=e=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter(r=>{let i=t[r];return i.enabled&&i.metadata&&i.metadata.payload!==void 0}).map(r=>{let i=t[r].metadata?.payload;return[r,i?k8E(i):void 0]}))};var F4o=e=>e===void 0?void 0:e.variant??e.enabled,k8E=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var woc="0123456789abcdef",Eoc=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,i,n){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||!Number.isInteger(n)||t<0||r<0||i<0||n<0||t>0xffffffffffff||r>4095||i>1073741823||n>4294967295)throw new RangeError("invalid field value");let a=new Uint8Array(16);return a[0]=t/2**40,a[1]=t/2**32,a[2]=t/2**24,a[3]=t/2**16,a[4]=t/256,a[5]=t,a[6]=112|r>>>8,a[7]=r,a[8]=128|i>>>24,a[9]=i>>>16,a[10]=i>>>8,a[11]=i,a[12]=n>>>24,a[13]=n>>>16,a[14]=n>>>8,a[15]=n,new e(a)}static parse(t){let r;switch(t.length){case 32:r=/^[0-9a-f]{32}$/i.exec(t)?.[0];break;case 36:r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;case 38:r=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(t)?.slice(1,6).join("");break;case 45:r=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(t)?.slice(1,6).join("");break;default:break}if(r){let i=new Uint8Array(16);for(let n=0;n<16;n+=4){let a=parseInt(r.substring(2*n,2*n+8),16);i[n+0]=a>>>24,i[n+1]=a>>>16,i[n+2]=a>>>8,i[n+3]=a}return new e(i)}throw new SyntaxError("could not parse UUID string")}toString(){let t="";for(let r=0;r<this.bytes.length;r++)t+=woc.charAt(this.bytes[r]>>>4),t+=woc.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+=woc.charAt(this.bytes[r]>>>4),t+=woc.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 i=this.bytes[r]-t.bytes[r];if(i!==0)return Math.sign(i)}return 0}},I0p=class{constructor(t){this.timestamp=0,this.counter=0,this.random=t??Af5()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(t,r){let i=this.generateOrAbortCore(t,r);return i===void 0&&(this.timestamp=0,i=this.generateOrAbortCore(t,r)),i}generateOrAbortCore(t,r){if(!Number.isInteger(t)||t<1||t>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(t>this.timestamp)this.timestamp=t,this.resetCounter();else{if(!(t+r>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return Eoc.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,Eoc.ofInner(t)}},Af5=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),exE,yLi=()=>Pf5().toString(),Pf5=()=>(exE||(exE=new I0p)).generate();var jf5=["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"],txE=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return jf5.concat(t).some(i=>{let n=i.toLowerCase();return r.indexOf(n)!==-1})};var MOe=(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 Ef5=Array.isArray,rxE=Object.prototype,Dyk=rxE.hasOwnProperty,C0p=rxE.toString,q0p=Ef5||function(e){return C0p.call(e)==="[object Array]"};var ixE=e=>e===Object(e)&&!q0p(e);var Hxa=e=>e===void 0,Q4o=e=>C0p.call(e)=="[object String]",nxE=e=>Q4o(e)&&e.trim().length===0;var axE=e=>C0p.call(e)=="[object Number]"&&e===e;var T0p=e=>e instanceof Error;function U4o(e){return e===null||typeof e!="object"}function Rea(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function oxE(e){return Rea(e,"ErrorEvent")}function Soc(e){return!Hxa(Event)&&Sf5(e,Event)}function uxE(e){return Rea(e,"Object")}function Sf5(e,t){try{return e instanceof t}catch{return!1}}function L4o(e,t,r,i,n){return t>r&&(i.warn("min cannot be greater than max."),t=r),axE(e)?e>r?(i.warn(" cannot be greater than max: "+r+". Using max value instead."),r):e<t?(i.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(i.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+n),L4o(n||r,t,r,i))}var Mf5=864e5,Moc=class{constructor(t){this._buckets={},this._onBucketRateLimited=t._onBucketRateLimited,this._bucketSize=L4o(t.bucketSize,0,100,t._logger),this._refillRate=L4o(t.refillRate,0,this._bucketSize,t._logger),this._refillInterval=L4o(t.refillInterval,0,Mf5,t._logger)}_applyRefill(t,r){let i=r-t.lastAccess,n=Math.floor(i/this._refillInterval);if(n>0){let a=n*this._refillRate;t.tokens=Math.min(t.tokens+a,this._bucketSize),t.lastAccess=t.lastAccess+n*this._refillInterval}}consumeRateLimit(t){let r=Date.now(),i=String(t),n=this._buckets[i];return n?this._applyRefill(n,r):(n={tokens:this._bucketSize,lastAccess:r},this._buckets[i]=n),n.tokens===0?!0:(n.tokens--,n.tokens===0&&this._onBucketRateLimited?.(t),n.tokens===0)}stop(){this._buckets={}}};var Doc=class{add(t){let r=yLi();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 Df5(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var sxE=(e,t,r)=>{function i(a,...o){t(()=>{let c=r[a];c(e,...o)})}return{info:(...a)=>{i("log",...a)},warn:(...a)=>{i("warn",...a)},error:(...a)=>{i("error",...a)},critical:(...a)=>{r.error(e,...a)},createLogger:a=>sxE(`${e} ${a}`,t,r)}},Bf5=e=>e();function cxE(e,t=Bf5){return sxE(e,t,Df5())}var $xa="Mobile",Ioc="iOS",Kxa="Android",lxE="Tablet",Lyk=Kxa+" "+lxE;var If5="Apple",Vyk=If5+" Watch",fxE="Safari",Coc="BlackBerry",dxE="Samsung",Cf5=dxE+"Browser",qf5=dxE+" Internet",qoc="Chrome",Tf5=qoc+" OS",Rf5=qoc+" "+Ioc,pxE="Internet Explorer",zf5=pxE+" "+$xa,z0p="Opera",Wyk=z0p+" Mini",_xE="Edge",Nf5="Microsoft "+_xE,N0p="Firefox",Ff5=N0p+" "+Ioc,F0p="Nintendo",Q0p="PlayStation",Boc="Xbox",Qf5=Kxa+" "+$xa,Uf5=$xa+" "+fxE,V4o="Windows",Lf5=V4o+" Phone";var hxE="Generic",xyk=hxE+" "+$xa.toLowerCase(),Gyk=hxE+" "+lxE.toLowerCase(),Vf5="Konqueror",$Y="(\\d+(\\.\\d+)?)",R0p=new RegExp("Version/"+$Y),Hyk=new RegExp(Boc,"i"),Kyk=new RegExp(Q0p+" \\w+","i"),$yk=new RegExp(F0p+" \\w+","i"),Wf5=new RegExp(Coc+"|PlayBook|BB10","i"),xf5={"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 Jyk={[zf5]:[new RegExp("rv:"+$Y)],[Nf5]:[new RegExp(_xE+"?\\/"+$Y)],[qoc]:[new RegExp("("+qoc+"|CrMo)\\/"+$Y)],[Rf5]:[new RegExp("CriOS\\/"+$Y)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+$Y)],[fxE]:[R0p],[Uf5]:[R0p],[z0p]:[new RegExp("("+z0p+"|OPR)\\/"+$Y)],[N0p]:[new RegExp(N0p+"\\/"+$Y)],[Ff5]:[new RegExp("FxiOS\\/"+$Y)],[Vf5]:[new RegExp("Konqueror[:/]?"+$Y,"i")],[Coc]:[new RegExp(Coc+" "+$Y),R0p],[Qf5]:[new RegExp("android\\s"+$Y,"i")],[qf5]:[new RegExp(Cf5+"\\/"+$Y)],[pxE]:[new RegExp("(rv:|MSIE )"+$Y)],Mozilla:[new RegExp("rv:"+$Y)]};var Yyk=[[new RegExp(Boc+"; "+Boc+" (.*?)[);]","i"),e=>[Boc,e&&e[1]||""]],[new RegExp(F0p,"i"),[F0p,""]],[new RegExp(Q0p,"i"),[Q0p,""]],[Wf5,[Coc,""]],[new RegExp(V4o,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[Lf5,""];if(new RegExp($xa).test(t)&&!/IEMobile\b/.test(t))return[V4o+" "+$xa,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let i=r[1],n=xf5[i]||"";return/arm/i.test(t)&&(n="RT"),[V4o,n]}return[V4o,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[Ioc,t.join(".")]}return[Ioc,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=Hxa(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+Kxa+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Kxa+")","i"),e=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[Kxa,t.join(".")]}return[Kxa,""]}],[/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/,[Tf5,""]],[/Linux|debian/i,["Linux",""]]];var yxE="utf8";function bxE(e,t){if(!e||typeof e!="string"||Gf5(e))throw new Error(t)}function Gf5(e){return e.trim().length===0}function vxE(e){return e?.replace(/\/+$/,"")}async function gxE(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(n=>setTimeout(n,t.retryDelay));try{return await e()}catch(n){if(r=n,!t.retryCheck(n))throw n}}throw r}function Toc(){return new Date().toISOString()}function zea(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var OxE=e=>e instanceof Error;function U0p(e){return Promise.all(e.map(t=>(t??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var Roc=class{constructor(){this.events={},this.events={}}on(t,r){return this.events[t]||(this.events[t]=[]),this.events[t].push(r),()=>{this.events[t]=this.events[t].filter(i=>i!==r)}}emit(t,r){for(let i of this.events[t]||[])i(r);for(let i of this.events["*"]||[])i(t,r)}};function mxE(){return"CompressionStream"in globalThis}async function L0p(e,t=!0){try{let i=new Blob([e],{type:"text/plain"}).stream().pipeThrough(new CompressionStream("gzip"));return await new Response(i).blob()}catch(r){return t&&console.error("Failed to gzip compress data",r),null}}var Nea=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()}},Jxa=class extends Error{constructor(t){super("Network error while fetching PostHog",t instanceof Error?{cause:t}:{}),this.error=t,this.name="PostHogFetchNetworkError"}};async function AxE(e){if(e instanceof Nea){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 V0p(e){return typeof e=="object"&&(e instanceof Nea||e instanceof Jxa)}function PxE(e){return typeof e=="object"&&e instanceof Nea&&e.status===413}var W4o=class{constructor(t,r={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new Doc,this._events=new Roc,this._isInitialized=!1,bxE(t,"You must pass your PostHog project's api key."),this.apiKey=t,this.host=vxE(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:V0p},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=cxE("[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=!mxE()||(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(MOe.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(MOe.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(MOe.OptedOut,!0)})}on(t,r){return this._events.on(t,r)}debug(t=!0){if(this.removeDebugCallback?.(),t){let r=this.on("*",(i,n)=>this._logger.info(i,n));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(t){return{distinct_id:t.distinct_id,event:t.event,properties:{...t.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(t){return this.promiseQueue.add(t)}identifyStateless(t,r,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};this.enqueue("identify",n,i)})}async identifyStatelessImmediate(t,r,i){let n={...this.buildPayload({distinct_id:t,event:"$identify",properties:r})};await this.sendImmediate("identify",n,i)}captureStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({distinct_id:t,event:r,properties:i});this.enqueue("capture",a,n)})}async captureStatelessImmediate(t,r,i,n){let a=this.buildPayload({distinct_id:t,event:r,properties:i});await this.sendImmediate("capture",a,n)}aliasStateless(t,r,i,n){this.wrap(()=>{let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});this.enqueue("alias",a,n)})}async aliasStatelessImmediate(t,r,i,n){let a=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...i||{},distinct_id:r,alias:t}});await this.sendImmediate("alias",a,n)}groupIdentifyStateless(t,r,i,n,a,o){this.wrap(()=>{let c=this.buildPayload({distinct_id:a||`$${t}_${r}`,event:"$groupidentify",properties:{$group_type:t,$group_key:r,$group_set:i||{},...o||{}}});this.enqueue("capture",c,n)})}async getRemoteConfig(){await this._initPromise;let t=this.host;t==="https://us.i.posthog.com"?t="https://us-assets.i.posthog.com":t==="https://eu.i.posthog.com"&&(t="https://eu-assets.i.posthog.com");let r=`${t}/array/${this.apiKey}/config`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,i,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(n=>n.json()).catch(n=>{this._logger.error("Remote config could not be loaded",n),this._events.emit("error",n)})}async getFlags(t,r={},i={},n={},a={},o=!0){await this._initPromise;let c=o?"&config=true":"",d=`${this.host}/flags/?v=2${c}`,s={token:this.apiKey,distinct_id:t,groups:r,person_properties:i,group_properties:n,...a};this.evaluationContexts&&this.evaluationContexts.length>0&&(s.evaluation_contexts=this.evaluationContexts);let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(s)};return this._logger.info("Flags URL",d),this.fetchWithRetry(d,u,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(f=>f.json()).then(f=>({success:!0,response:B0p(f)})).catch(f=>(this._events.emit("error",f),{success:!1,error:this.categorizeRequestError(f)}))}categorizeRequestError(t){if(t instanceof Nea)return{type:"api_error",statusCode:t.status};if(t instanceof Jxa){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,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagDetailStateless(t,r,i,n,a,o);if(c===void 0)return{response:void 0,requestId:void 0};let d=F4o(c.response);return d===void 0&&(d=!1),{response:d,requestId:c.requestId}}async getFeatureFlagDetailStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(r,i,n,a,o,[t]);return c===void 0?void 0:{response:c.flags[t],requestId:c.requestId,evaluatedAt:c.evaluatedAt}}async getFeatureFlagPayloadStateless(t,r,i={},n={},a={},o){await this._initPromise;let c=await this.getFeatureFlagPayloadsStateless(r,i,n,a,o,[t]);if(!c)return;let d=c[t];return d===void 0?null:d}async getFeatureFlagPayloadsStateless(t,r={},i={},n={},a,o){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,o)).payloads}async getFeatureFlagsStateless(t,r={},i={},n={},a,o){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(t,r,i,n,a,o)}async getFeatureFlagsAndPayloadsStateless(t,r={},i={},n={},a,o){await this._initPromise;let c=await this.getFeatureFlagDetailsStateless(t,r,i,n,a,o);return c?{flags:c.featureFlags,payloads:c.featureFlagPayloads,requestId:c.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(t,r={},i={},n={},a,o){await this._initPromise;let c={};(a??this.disableGeoip)&&(c.geoip_disable=!0),o&&(c.flag_keys_to_evaluate=o);let d=await this.getFlags(t,r,i,n,c);if(!d.success)return;let s=d.response;return s.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"),s.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:s?.requestId,quotaLimited:s.quotaLimited}):s}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"}},n=(await this.fetchWithRetry(t,r).then(a=>{if(a.status!==200||!a.json){let o=`Surveys API could not be loaded: ${a.status}`,c=new Error(o);this._logger.error(c),this._events.emit("error",new Error(o));return}return a.json()}).catch(a=>{this._logger.error("Surveys API could not be loaded",a),this._events.emit("error",a)}))?.surveys;return n&&this._logger.info("Surveys fetched from API: ",JSON.stringify(n)),n??[]}get props(){return this._props||(this._props=this.getPersistedProperty(MOe.Props)),this._props||{}}set props(t){this._props=t}async register(t){this.wrap(()=>{this.props={...this.props,...t},this.setPersistedProperty(MOe.Props,this.props)})}async unregister(t){this.wrap(()=>{delete this.props[t],this.setPersistedProperty(MOe.Props,this.props)})}processBeforeEnqueue(t){return t}enqueue(t,r,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let n=this.prepareMessage(t,r,i);if(n=this.processBeforeEnqueue(n),n===null)return;let a=this.getPersistedProperty(MOe.Queue)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),a.push({message:n}),this.setPersistedProperty(MOe.Queue,a),this._events.emit(t,n),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=zea(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(t,r,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(t,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let n=this.prepareMessage(t,r,i);if(n=this.processBeforeEnqueue(n),n===null)return;let a={api_key:this.apiKey,batch:[n],sent_at:Toc()};this.historicalMigration&&(a.historical_migration=!0);let o=JSON.stringify(a),c=`${this.host}/batch/`,d=this.disableCompression?null:await L0p(o,this.isDebug),s={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...d!==null&&{"Content-Encoding":"gzip"}},body:d||o};try{await this.fetchWithRetry(c,s)}catch(u){this._events.emit("error",u)}}prepareMessage(t,r,i){let n={...r,type:t,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:i?.timestamp?i?.timestamp:Toc(),uuid:i?.uuid?i.uuid:yLi()};return(i?.disableGeoip??this.disableGeoip)&&(n.properties||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(async t=>{await AxE(t)})}async flush(){let t=U0p([this.flushPromise]).then(()=>this._flush());return this.flushPromise=t,this.addPendingPromise(t),U0p([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(MOe.Queue)||[];if(!t.length)return;let r=[],i=t.length;for(;t.length>0&&r.length<i;){let n=t.slice(0,this.maxBatchSize),a=n.map(_=>_.message),o=()=>{let h=(this.getPersistedProperty(MOe.Queue)||[]).slice(n.length);this.setPersistedProperty(MOe.Queue,h),t=h},c={api_key:this.apiKey,batch:a,sent_at:Toc()};this.historicalMigration&&(c.historical_migration=!0);let d=JSON.stringify(c),s=`${this.host}/batch/`,u=this.disableCompression?null:await L0p(d,this.isDebug),f={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...u!==null&&{"Content-Encoding":"gzip"}},body:u||d},p={retryCheck:_=>PxE(_)?!1:V0p(_)};try{await this.fetchWithRetry(s,f,p)}catch(_){if(PxE(_)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this._logger.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw _ instanceof Jxa||o(),this._events.emit("error",_),_}o(),r.push(...a)}this._events.emit("flush",r)}async fetchWithRetry(t,r,i,n){AbortSignal.timeout??=function(c){let d=new AbortController;return setTimeout(()=>d.abort(),c),d.signal};let a=r.body?r.body:"",o=-1;try{o=a instanceof Blob?a.size:Buffer.byteLength(a,yxE)}catch{a instanceof Blob?o=a.size:o=new TextEncoder().encode(a).length}return await gxE(async()=>{let c=null;try{c=await this.fetch(t,{signal:AbortSignal.timeout(n??this.requestTimeout),...r})}catch(s){throw new Jxa(s)}if(!(r.mode==="no-cors")&&(c.status<200||c.status>=400))throw new Nea(c,o);return c},{...this._retryOptions,...i})}async _shutdown(t=3e4){await this._initPromise;let r=!1;this.clearFlushTimer();let i=async()=>{try{for(await this.promiseQueue.join();!((this.getPersistedProperty(MOe.Queue)||[]).length===0||(await this.flush(),r)););}catch(n){if(!V0p(n))throw n;await AxE(n)}};return Promise.race([new Promise((n,a)=>{zea(()=>{this._logger.error("Timed out while shutting down PostHog"),r=!0,a("Timeout while shutting down PostHog. Some events may not have been sent.")},t)}),i()])}async shutdown(t=3e4){return this.shutdownPromise?this._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 DOe={};$t(DOe,{DOMExceptionCoercer:()=>H0p,ErrorCoercer:()=>K0p,ErrorEventCoercer:()=>$0p,ErrorPropertiesBuilder:()=>W0p,EventCoercer:()=>X0p,ObjectCoercer:()=>Y0p,PrimitiveCoercer:()=>Z0p,PromiseRejectionEventCoercer:()=>k0p,ReduceableCache:()=>eEp,StringCoercer:()=>J0p,chromeStackLineParser:()=>x0p,createDefaultStackParser:()=>od5,createStackParser:()=>TxE,geckoStackLineParser:()=>G0p,nodeStackLineParser:()=>BxE,opera10StackLineParser:()=>SxE,opera11StackLineParser:()=>MxE,reverseAndStripFrames:()=>qxE,winjsStackLineParser:()=>ExE});var zoc,jxE,Noc;function wxE(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return Noc&&r.length===jxE||(jxE=r.length,Noc=r.reduce((i,n)=>{zoc||(zoc={});let a=zoc[n];if(a)i[a[0]]=a[1];else{let o=e(n);for(let c=o.length-1;c>=0;c--){let s=o[c]?.filename,u=t[n];if(s&&u){i[s]=u,zoc[n]=[s,u];break}}}return i},{})),Noc}var Kf5=4,W0p=class{constructor(t,r,i=[]){this.coercers=t,this.stackParser=r,this.modifiers=i}buildFromUnknown(t,r={}){let n=r&&r.mechanism||{handled:!0,type:"generic"},o=this.buildCoercingContext(n,r,0).apply(t),c=this.buildParsingContext(),d=this.parseStacktrace(o,c);return{$exception_list:this.convertToExceptionList(d,n),$exception_level:"error"}}async modifyFrames(t){for(let r of t)r.stacktrace&&r.stacktrace.frames&&q0p(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 i;t.cause!=null&&(i=this.parseStacktrace(t.cause,r));let n;return t.stack!=""&&t.stack!=null&&(n=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?1:0),r.chunkIdMap)),{...t,cause:i,stack:n}}applyChunkIds(t,r){return t.map(i=>(i.filename&&r&&(i.chunk_id=r[i.filename]),i))}applyCoercers(t,r){for(let i of this.coercers)if(i.match(t))return i.coerce(t,r);return this.coerceFallback(r)}async applyModifiers(t){let r=t;for(let i of this.modifiers)r=await i(r);return r}convertToExceptionList(t,r){let i={type:t.type,value:t.value,mechanism:{type:r.type??"generic",handled:r.handled??!0,synthetic:t.synthetic??!1}};t.stack&&(i.stacktrace={type:"raw",frames:t.stack});let n=[i];return t.cause!=null&&n.push(...this.convertToExceptionList(t.cause,{...r,handled:!0})),n}buildParsingContext(){return{chunkIdMap:wxE(this.stackParser)}}buildCoercingContext(t,r,i=0){let n=(o,c)=>{if(c<=Kf5){let d=this.buildCoercingContext(t,r,c);return this.applyCoercers(o,d)}};return{...r,syntheticException:i==0?r.syntheticException:void 0,mechanism:t,apply:o=>n(o,i),next:o=>n(o,i+1)}}};var Fx="?";function bLi(e,t,r,i,n){let a={platform:e,filename:t,function:r==="<anonymous>"?Fx:r,in_app:!0};return Hxa(i)||(a.lineno=i),Hxa(n)||(a.colno=n),a}var Foc=(e,t)=>{let r=e.indexOf("safari-extension")!==-1,i=e.indexOf("safari-web-extension")!==-1;return r||i?[e.indexOf("@")!==-1?e.split("@")[0]:Fx,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var $f5=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Jf5=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Yf5=/\((\S*)(?::(\d+))(?::(\d+))\)/,x0p=(e,t)=>{let r=$f5.exec(e);if(r){let[,n,a,o]=r;return bLi(t,n,Fx,+a,+o)}let i=Jf5.exec(e);if(i){if(i[2]&&i[2].indexOf("eval")===0){let c=Yf5.exec(i[2]);c&&(i[2]=c[1],i[3]=c[2],i[4]=c[3])}let[a,o]=Foc(i[1]||Fx,i[2]);return bLi(t,o,a,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}};var Xf5=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Zf5=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,G0p=(e,t)=>{let r=Xf5.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let o=Zf5.exec(r[3]);o&&(r[1]=r[1]||"eval",r[3]=o[1],r[4]=o[2],r[5]="")}let n=r[3],a=r[1]||Fx;return[a,n]=Foc(a,n),bLi(t,n,a,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var kf5=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,ExE=(e,t)=>{let r=kf5.exec(e);return r?bLi(t,r[2],r[1]||Fx,+r[3],r[4]?+r[4]:void 0):void 0};var ed5=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,SxE=(e,t)=>{let r=ed5.exec(e);return r?bLi(t,r[2],r[3]||Fx,+r[1]):void 0},td5=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,MxE=(e,t)=>{let r=td5.exec(e);return r?bLi(t,r[5],r[3]||r[4]||Fx,+r[1],+r[2]):void 0};var rd5=/^\s*[-]{4,}$/,id5=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,BxE=(e,t)=>{let r=e.match(id5);if(r){let i,n,a,o,c;if(r[1]){a=r[1];let u=a.lastIndexOf(".");if(a[u-1]==="."&&u--,u>0){i=a.slice(0,u),n=a.slice(u+1);let f=i.indexOf(".Module");f>0&&(a=a.slice(f+1),i=i.slice(0,f))}o=void 0}n&&(o=i,c=n),n==="<anonymous>"&&(c=void 0,a=void 0),a===void 0&&(c=c||Fx,a=o?`${o}.${c}`:c);let d=r[2]?.startsWith("file://")?r[2].slice(7):r[2],s=r[5]==="native";return d?.match(/\/[A-Z]:/)&&(d=d.slice(1)),!d&&r[5]&&!s&&(d=r[5]),{filename:d?decodeURI(d):void 0,module:void 0,function:a,lineno:DxE(r[3]),colno:DxE(r[4]),in_app:nd5(d||"",s),platform:t}}if(e.match(rd5))return{filename:e,platform:t}};function nd5(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 DxE(e){return parseInt(e||"",10)||void 0}var IxE=/\(error: (.*)\)/,CxE=50;function qxE(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,CxE).map(r=>({...r,filename:r.filename||ad5(t).filename,function:r.function||Fx}))}function ad5(e){return e[e.length-1]||{}}function od5(){return TxE("web:javascript",x0p,G0p)}function TxE(e,...t){return(r,i=0)=>{let n=[],a=r.split(`
|
|
2266
|
-
`);for(let o=i;o<a.length;o++){let c=a[o];if(c.length>1024)continue;let d=IxE.test(c)?c.replace(IxE,"$1"):c;if(!d.match(/\S*Error: /)){for(let s of t){let u=s(d,e);if(u){n.push(u);break}}if(n.length>=CxE)break}}return qxE(n)}}var H0p=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let i=Q4o(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:i?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 Rea(t,"DOMException")}isDOMError(t){return Rea(t,"DOMError")}};var K0p=class{match(t){return T0p(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 i=t.message;return i.error&&typeof i.error.message=="string"?String(i.error.message):String(i)}getStack(t){return t.stacktrace||t.stack||void 0}};var $0p=class{constructor(){}match(t){return oxE(t)&&t.error!=null}coerce(t,r){let i=r.apply(t.error);return i||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var ud5=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,J0p=class{match(t){return typeof t=="string"}coerce(t,r){let[i,n]=this.getInfos(t);return{type:i??"Error",value:n??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",i=t,n=t.match(ud5);return n&&(r=n[1],i=n[2]),[r,i]}};var RxE=["fatal","error","warning","log","info","debug"];function Qoc(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let i=r.length;i>0;i--){let n=r.slice(0,i).join(", ");if(!(n.length>t))return i===r.length||n.length<=t?n:`${n.slice(0,t)}...`}return""}var Y0p=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let i=this.getErrorPropertyFromObject(t);return i?r.apply(i):{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 Soc(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let n=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(n+=` with message: '${t.message}'`),n}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),i=Qoc(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(t){return Q4o(t)&&!nxE(t)&&RxE.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(OxE(i))return i}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var X0p=class{match(t){return Soc(t)}coerce(t,r){let i=t.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${Qoc(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Z0p=class{match(t){return U4o(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var k0p=class{match(t){return Rea(t,"PromiseRejectionEvent")}coerce(t,r){let i=this.getUnhandledRejectionReason(t);return U4o(i)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(i)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(i)}getUnhandledRejectionReason(t){if(U4o(t))return t;try{if("reason"in t)return t.reason;if("detail"in t&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var eEp=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 FxE=require("fs"),QxE=require("readline"),Uoc=new DOe.ReduceableCache(25),UxE=new DOe.ReduceableCache(20),tEp=7,sd5=1e3,cd5=1e4;async function LxE(e){let t={};for(let n=e.length-1;n>=0;n--){let a=e[n],o=a?.filename;if(!a||typeof o!="string"||typeof a.lineno!="number"||pd5(o)||_d5(a))continue;t[o]||(t[o]=[]),t[o].push(a.lineno)}let r=Object.keys(t);if(r.length==0)return e;let i=[];for(let n of r){if(UxE.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let o=yd5(a);if(o.every(d=>hd5(n,d)))continue;let c=bd5(Uoc,n,{});i.push(ld5(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&fd5(e,Uoc),Uoc.reduce(),e}function ld5(e,t,r){return new Promise(i=>{let n=(0,FxE.createReadStream)(e),a=(0,QxE.createInterface)({input:n});function o(){n.destroy(),i()}let c=0,d=0,s=t[d];if(s===void 0)return void o();let u=s[0],f=s[1];function p(){UxE.set(e,1),a.close(),a.removeAllListeners(),o()}n.on("error",p),a.on("error",p),a.on("close",o),a.on("line",_=>{if(c++,!(c<u)&&(r[c]=vd5(_,0),c>=f)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let h=t[d];if(h===void 0){a.close(),a.removeAllListeners();return}u=h[0],f=h[1]}})})}function fd5(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let i=t.get(r.filename);if(i===void 0)continue;dd5(r.lineno,r,i)}}function dd5(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=VxE(e);n<e;n++){let a=r[n];if(a===void 0)return void zxE(t);t.pre_context.push(a)}if(r[e]===void 0)return void zxE(t);t.context_line=r[e];let i=WxE(e);t.post_context=[];for(let n=e+1;n<=i;n++){let a=r[n];if(a===void 0)break;t.post_context.push(a)}}function zxE(e){delete e.pre_context,delete e.context_line,delete e.post_context}function pd5(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function _d5(e){return e.lineno!==void 0&&e.lineno>cd5||e.colno!==void 0&&e.colno>sd5}function hd5(e,t){let r=Uoc.get(e);if(r===void 0)return!1;for(let i=t[0];i<=t[1];i++)if(r[i]===void 0)return!1;return!0}function yd5(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=NxE(r),n=[];for(;;){if(t===e.length-1){n.push(i);break}let a=e[t+1];if(typeof a!="number")break;a<=i[1]?i[1]=a+tEp:(n.push(i),i=NxE(a)),t++}return n}function NxE(e){return[VxE(e),WxE(e)]}function VxE(e){return Math.max(1,e-tEp)}function WxE(e){return e+tEp}function bd5(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function vd5(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let n=Math.max(t-60,0);n<5&&(n=0);let a=Math.min(n+140,i);return a>i-5&&(a=i),a===i&&(n=Math.max(a-140,0)),r=r.slice(n,a),n>0&&(r=`...${r}`),a<i&&(r+="..."),r}function gd5(e,t){let r=!1;return Object.assign(i=>{let a=global.process.listeners("uncaughtException").filter(o=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length===0;e(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&a&&(r=!0,t(i))},{_posthogErrorHandler:!0})}function xxE(e,t){globalThis.process?.on("uncaughtException",gd5(e,t))}function GxE(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var Od5=2e3,d$t=class e{constructor(t,r,i){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new Moc({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return ixE(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,i,n){let a={...n};i||(a.$process_person_profile=!1);let o=this.errorPropertiesBuilder.buildFromUnknown(t,r);return o.$exception_list=await this.errorPropertiesBuilder.modifyFrames(o.$exception_list),{event:"$exception",distinctId:i||yLi(),properties:{...o,...a}}}startAutocaptureIfEnabled(){this.isEnabled()&&(xxE(this.onException.bind(this),this.onFatalError.bind(this)),GxE(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let i=await e.buildEventMessage(t,r),a=i.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(a)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:a}):this.client.capture(i)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(Od5),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var HxE="5.24.7";var x4o={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function KxE(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}var md5=6e4,Ad5=1152921504606847e3,Pd5=["is_not"],Yxa=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},uE=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},vLi=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},Loc=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:o,...c}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=c.fetch||fetch,this.onError=c.onError,this.customHeaders=o,this.onLoad=c.onLoad,this.cacheProvider=c.cacheProvider,this.strictLocalEvaluation=c.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let o,c;if(!this.loadedSuccessfullyOnce)return o;if(c=this.featureFlagsByKey[t],c!==void 0)try{o=(await this.computeFlagAndPayloadLocally(c,r,i,n,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${o}`))}catch(d){d instanceof vLi||d instanceof uE?this.logMsgIfDebug(()=>console.debug(`${d.name} when computing flag locally: ${t}: ${d.message}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return o}async getAllFlagsAndPayloads(t,r={},i={},n={},a){await this.loadFeatureFlags();let o={},c={},d=this.featureFlags.length==0,s=a?a.map(f=>this.featureFlagsByKey[f]).filter(Boolean):this.featureFlags,u={};return await Promise.all(s.map(async f=>{try{let{value:p,payload:_}=await this.computeFlagAndPayloadLocally(f,t,r,i,n,void 0,u);o[f.key]=p,_&&(c[f.key]=_)}catch(p){p instanceof vLi||p instanceof uE?this.logMsgIfDebug(()=>console.debug(`${p.name} when computing flag locally: ${f.key}: ${p.message}`)):p instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${f.key}: ${p}`)),d=!0}})),{response:o,payloads:c,fallbackToFlags:d}}async computeFlagAndPayloadLocally(t,r,i={},n={},a={},o,c,d=!1){if(d||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=o!==void 0?o:await this.computeFlagValueLocally(t,r,i,n,a,c);let u=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:u}}async computeFlagValueLocally(t,r,i={},n={},a={},o={}){if(t.ensure_experience_continuity)throw new uE("Flag has experience continuity enabled");if(!t.active)return!1;let d=(t.filters||{}).aggregation_group_type_index;if(d==null)return await this.matchFeatureFlagProperties(t,r,n,o);{let s=this.groupTypeMapping[String(d)];if(!s)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${d} for feature flag ${t.key}`)),new uE("Flag has unknown group type index");if(!(s in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let u=a[s];return await this.matchFeatureFlagProperties(t,i[s],u,o)}}getFeatureFlagPayload(t,r){let i=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),i!=null)){if(typeof i=="object")return i;if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}return null}async evaluateFlagDependency(t,r,i,n){let a=t.key;if(!this.featureFlagsByKey)throw new uE("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new uE(`Flag dependency property for '${a}' is missing required 'dependency_chain' field`);let o=t.dependency_chain;if(!Array.isArray(o))throw new uE(`Flag dependency property for '${a}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new uE(`Circular dependency detected for flag '${a}' (empty dependency chain)`);for(let d of o){if(!(d in n)){let u=this.featureFlagsByKey[d];if(u)if(u.active)try{let f=await this.matchFeatureFlagProperties(u,r,i,n);n[d]=f}catch(f){throw new uE(`Error evaluating flag dependency '${d}' for flag '${a}': ${f}`)}else n[d]=!1;else throw new uE(`Missing flag dependency '${d}' for flag '${a}'`)}if(n[d]==null)throw new uE(`Dependency '${d}' could not be evaluated`)}let c=n[a];return this.flagEvaluatesToExpectedValue(t.value,c)}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,i,n={}){let a=t.filters||{},o=a.groups||[],c=!1,d;for(let s of o)try{if(await this.isConditionMatch(t,r,s,i,n)){let u=s.variant,f=a.multivariate?.variants||[];d=u&&f.some(p=>p.key===u)?u:await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof vLi)throw u;if(u instanceof uE)c=!0;else throw u}if(d!==void 0)return d;if(c)throw new uE("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,i,n,a={}){let o=i.rollout_percentage,c=d=>{this.logMsgIfDebug(()=>console.warn(d))};if((i.properties||[]).length>0){for(let d of i.properties){let s=d.type,u=!1;if(u=s==="cohort"?ZxE(d,n,this.cohorts,this.debugMode):s==="flag"?await this.evaluateFlagDependency(d,r,n,a):XxE(d,n,c),!u)return!1}if(o==null)return!0}return!(o!=null&&await $xE(t.key,r)>o/100)}async getMatchingVariant(t,r){let i=await $xE(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(c=>{n=i+c.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:c.key}),i=n}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,i)=>(r[i.key]=i,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(i=>i.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(i=>i.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}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(md5,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(i){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${i}`))}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 Yxa(`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 Yxa(`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 Yxa(`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 i=await r.json()??{};if(!("flags"in i))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(i)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let n={flags:i.flags??[],groupTypeMapping:i.group_type_mapping||{},cohorts:i.cohorts||{}};if(this.updateFlagState(n),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(n.flags);break}default:return}}catch(t){t instanceof Yxa&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let i={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(i["If-None-Match"]=r),{method:t,headers:i}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=zea(()=>{n.abort()},this.timeout),r.signal=n.signal}try{let n=this.fetch;return n(t,r)}finally{clearTimeout(i)}}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((i,n)=>setTimeout(()=>n(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function $xE(e,t,r=""){let i=await KxE(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/Ad5}function XxE(e,t,r){let i=e.key,n=e.value,a=e.operator||"exact";if(i in t){if(a==="is_not_set")throw new uE("Operator is_not_set is not supported")}else throw new uE(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!Pd5.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function c(s,u){return Array.isArray(s)?s.map(f=>String(f).toLowerCase()).includes(String(u).toLowerCase()):String(s).toLowerCase()===String(u).toLowerCase()}function d(s,u,f){if(f==="gt")return s>u;if(f==="gte")return s>=u;if(f==="lt")return s<u;if(f==="lte")return s<=u;throw new Error(`Invalid operator: ${f}`)}switch(a){case"exact":return c(n,o);case"is_not":return!c(n,o);case"is_set":return i in t;case"icontains":return String(o).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(n).toLowerCase());case"regex":return JxE(String(n))&&String(o).match(String(n))!==null;case"not_regex":return JxE(String(n))&&String(o).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof n=="number"?n:null;if(typeof n=="string")try{s=parseFloat(n)}catch{}return s==null||o==null?d(String(o),String(n),a):typeof o=="string"?d(o,String(n),a):d(o,s,a)}case"is_date_after":case"is_date_before":{if(typeof n=="boolean")throw new uE("Date operations cannot be performed on boolean values");let s=wd5(String(n));if(s==null&&(s=YxE(n)),s==null)throw new uE(`Invalid date: ${n}`);let u=YxE(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new uE(`Unknown operator: ${a}`)}}function jd5(e,t){if(!(e in t))throw new vLi(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function ZxE(e,t,r,i=!1){let n=String(e.value);jd5(n,r);let a=r[n];return kxE(a,t,r,i)}function kxE(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let o=!1;if("values"in a[0]){for(let c of a)try{let d=kxE(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof vLi)throw d;if(d instanceof uE)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new uE("Can't match cohort without a given cohort property value");return n==="AND"}for(let c of a)try{let d;if(c.type==="cohort")d=ZxE(c,t,r,i);else if(c.type==="flag"){i&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${c.key||"unknown"}'`);continue}else d=XxE(c,t);let s=c.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof vLi)throw d;if(d instanceof uE)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new uE("can't match cohort without a given cohort property value");return n==="AND"}function JxE(e){try{return new RegExp(e),!0}catch{return!1}}function YxE(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 uE(`${e} is in an invalid date format`)}throw new uE(`The date provided ${e} must be a string, number, or date object`)}function wd5(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let a=r.groups.interval;if(a=="h")i.setUTCHours(i.getUTCHours()-n);else if(a=="d")i.setUTCDate(i.getUTCDate()-n);else if(a=="w")i.setUTCDate(i.getUTCDate()-7*n);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else{if(a!="y")return null;i.setUTCFullYear(i.getUTCFullYear()-n)}return i}}var Voc=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var Ed5=100,e5E=3e4,Sd5=5e4,Woc=class extends W4o{constructor(t,r={}){if(super(t,r),this._memoryStorage=new Voc,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,Ed5):e5E,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 Loc({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:n=>{this._events.emit("error",n)},onLoad:n=>{this._events.emit("localEvaluationFlagsLoaded",n)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider,strictLocalEvaluation:r.strictLocalEvaluation}))}this.errorTracking=new d$t(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||Sd5}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 HxE}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."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStateless(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.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."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStatelessImmediate(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStateless(t,u,{disableGeoip:i})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStatelessImmediate(t,u,{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=e5E){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let i=setTimeout(()=>{n(),r(!1)},t),n=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(i),n(),r(a>0)})})}async _getFeatureFlagResult(t,r,i={},n){let a=i.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let A=this._flagOverrides[t];if(A===void 0)return;let j=this._payloadOverrides?.[t];return{key:t,enabled:A!==!1,variant:typeof A=="string"?A:void 0,payload:j}}let{groups:o,disableGeoip:c}=i,{onlyEvaluateLocally:d,personProperties:s,groupProperties:u}=i,f=this.addLocalPersonAndGroupProperties(r,o,s,u);s=f.allPersonProperties,u=f.allGroupProperties,d==null&&(d=this.options.strictLocalEvaluation??!1);let p,_=!1,h,y,b,v,O,m;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let A=this.featureFlagsPoller?.featureFlagsByKey[t];if(A)try{let j=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(A,r,o,s,u,n);if(j){_=!0;let M=j.value;v=A.id,m="Evaluated locally",p={key:t,enabled:M!==!1,variant:typeof M=="string"?M:void 0,payload:j.payload??void 0}}}catch(j){if(j instanceof vLi||j instanceof uE)this._logger?.info(`${j.name} when computing flag locally: ${t}: ${j.message}`);else throw j}}if(!_&&!d){let A=await super.getFeatureFlagDetailsStateless(r,o,s,u,c,[t]);if(A===void 0)b=x4o.UNKNOWN_ERROR;else{h=A.requestId,y=A.evaluatedAt;let j=[];A.errorsWhileComputingFlags&&j.push(x4o.ERRORS_WHILE_COMPUTING),A.quotaLimited?.includes("feature_flags")&&j.push(x4o.QUOTA_LIMITED);let M=A.flags[t];if(M===void 0)j.push(x4o.FLAG_MISSING);else{v=M.metadata?.id,O=M.metadata?.version,m=M.reason?.description??M.reason?.code;let w;if(M.metadata?.payload!==void 0)try{w=JSON.parse(M.metadata.payload)}catch{w=M.metadata.payload}p={key:t,enabled:M.enabled,variant:M.variant,payload:w}}j.length>0&&(b=j.join(","))}}if(a){let A=p===void 0?void 0:p.enabled===!1?!1:p.variant??!0,j=`${t}_${A}`;if(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(j)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(j):this.distinctIdHasSentFlagCalls[r]=[j];let M={$feature_flag:t,$feature_flag_response:A,$feature_flag_id:v,$feature_flag_version:O,$feature_flag_reason:m,locally_evaluated:_,[`$feature/${t}`]:A,$feature_flag_request_id:h,$feature_flag_evaluated_at:y};b&&(M.$feature_flag_error=b),this.capture({distinctId:r,event:"$feature_flag_called",properties:M,groups:o,disableGeoip:c})}}return p!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(p={...p,payload:this._payloadOverrides[t]}),p}async getFeatureFlag(t,r,i){let n=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(n!==void 0)return n.enabled===!1?!1:n.variant??!0}async getFeatureFlagPayload(t,r,i,n){if(this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let a=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:!1},i);if(a!==void 0)return a.payload??null}async getFeatureFlagResult(t,r,i){return this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}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 i=await r.json();if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}async isFeatureEnabled(t,r,i){let n=await this.getFeatureFlag(t,r,i);if(n!==void 0)return!!n||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags||{}}async getAllFlagsAndPayloads(t,r){let{groups:i,disableGeoip:n,flagKeys:a}=r||{},{onlyEvaluateLocally:o,personProperties:c,groupProperties:d}=r||{},s=this.addLocalPersonAndGroupProperties(t,i,c,d);c=s.allPersonProperties,d=s.allGroupProperties,o==null&&(o=this.options.strictLocalEvaluation??!1);let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,c,d,a),f={},p={},_=!0;if(u&&(f=u.response,p=u.payloads,_=u.fallbackToFlags),_&&!o){let h=await super.getFeatureFlagsAndPayloadsStateless(t,i,c,d,n,a);f={...f,...h.flags||{}},p={...p,...h.payloads||{}}}return this._flagOverrides!==void 0&&(f={...f,...this._flagOverrides}),this._payloadOverrides!==void 0&&(p={...p,...this._payloadOverrides}),{featureFlags:f,featureFlagPayloads:p}}groupIdentify({groupType:t,groupKey:r,properties:i,distinctId:n,disableGeoip:a}){super.groupIdentifyStateless(t,r,i,{disableGeoip:a},n)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(t){let r=i=>Object.fromEntries(i.map(n=>[n,!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 i=r.flags;if(i===!1||Array.isArray(i)||typeof i=="object"&&i!==null)return!0}if("payloads"in r){let i=r.payloads;if(i===!1||typeof i=="object"&&i!==null)return!0}return!1}withContext(t,r,i){return this.context?this.context.run(t,r,i):r()}getContext(){return this.context?.get()}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),super._shutdown(t)}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},n=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let a=new AbortController;n=zea(()=>{a.abort()},this.options.requestTimeout),i.signal=a.signal}try{return await this.fetch(r,i)}catch(a){this._events.emit("error",a);return}finally{n&&clearTimeout(n)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let i={},n={};for(let[a,o]of Object.entries(t))if(uxE(o)&&r&&a in r){let c={};for(let[d,s]of Object.entries(o))c[String(d)]=String(s);n[String(a)]=c}else i[String(a)]=String(o);return{personProperties:i,groupProperties:n}}async getFeatureFlagsForEvent(t,r,i,n){let a=n?.personProperties||{},o=n?.groupProperties||{},c=n?.flagKeys;if(n?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,f]of Object.entries(r||{}))s[u]=String(f);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,f]of Object.entries(r||{}))s[u]=String(f);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}return(await super.getFeatureFlagsStateless(t,r,a,o,i)).flags}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},o={};if(r)for(let c of Object.keys(r))o[c]={$group_key:r[c],...n?.[c]||{}};return{allPersonProperties:a,allGroupProperties:o}}captureException(t,r,i,n){if(!d$t.isPreviouslyCapturedError(t)){let a=new Error("PostHog syntheticException");this.addPendingPromise(d$t.buildEventMessage(t,{syntheticException:a},r,i).then(o=>this.capture({...o,uuid:n})))}}async captureExceptionImmediate(t,r,i){if(!d$t.isPreviouslyCapturedError(t)){let n=new Error("PostHog syntheticException");this.addPendingPromise(d$t.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.captureImmediate(a)))}}async prepareEventMessage(t){let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s}=t,u=this.context?.get(),f=r||u?.distinctId,p={...u?.properties||{},...n||{}};f||(f=yLi(),p.$process_person_profile=!1),u?.sessionId&&!p.$session_id&&(p.$session_id=u.sessionId);let _=this._runBeforeSend({distinctId:f,event:i,properties:p,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s});if(!_)return Promise.reject(null);let h=await Promise.resolve().then(async()=>{if(o){let y=typeof o=="object"?o:void 0;return await this.getFeatureFlagsForEvent(_.distinctId,a,d,y)}return _.event,{}}).then(y=>{let b={};if(y)for(let[O,m]of Object.entries(y))b[`$feature/${O}`]=m;let v=Object.keys(y||{}).filter(O=>y?.[O]!==!1).sort();return v.length>0&&(b.$active_feature_flags=v),b}).catch(()=>({})).then(y=>({...y,..._.properties||{},$groups:_.groups||a}));return _.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof h.$raw_user_agent=="string"&&txE(h.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(_.event="$bot_pageview",h.$browser_type="bot"),{distinctId:_.distinctId,event:_.event,properties:h,options:{timestamp:_.timestamp,disableGeoip:_.disableGeoip,uuid:_.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let i=Array.isArray(r)?r:[r],n=t;for(let a of i){if(n=a(n),!n)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!n.properties||Object.keys(n.properties).length===0){let o=`Event '${n.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(o)}}return n}};var t5E=require("async_hooks"),xoc=class{constructor(){this.storage=new t5E.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,i){if(i?.fresh===!0)return this.storage.run(t,r);{let a=this.get()||{},o={distinctId:t.distinctId??a.distinctId,sessionId:t.sessionId??a.sessionId,properties:{...a.properties||{},...t.properties||{}}};return this.storage.run(o,r)}}};var r5E="posthog-node";function Md5(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"],sendExceptionsToPostHog:a=!0}={}){return o=>{if(!(n==="*"||n.includes(o.level)))return o;o.tags||(o.tags={});let d=o.tags[rEp.POSTHOG_ID_TAG];if(d===void 0)return o;let s=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${d}`,s).toString();o.tags["PostHog Person URL"]=u;let f=o.exception?.values||[],p=f.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),_={$exception_message:f[0]?.value||o.message,$exception_type:f[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:f[0]?.value||o.message,$sentry_exception_type:f[0]?.type,$sentry_tags:o.tags};return t&&r&&(_.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id),a&&e.capture({event:"$exception",distinctId:d,properties:_}),o}}var rEp=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,i,n,a){this.name=r5E,this.name=r5E,this.setupOnce=function(o,c){let d=c()?.getClient()?.getDsn()?.projectId;o(Md5(t,{organization:r,projectId:d,prefix:i,severityAllowList:n,sendExceptionsToPostHog:a??!0}))}}};d$t.errorPropertiesBuilder=new DOe.ErrorPropertiesBuilder([new DOe.EventCoercer,new DOe.ErrorCoercer,new DOe.ObjectCoercer,new DOe.StringCoercer,new DOe.PrimitiveCoercer],DOe.createStackParser("node:javascript",DOe.nodeStackLineParser),[Y8E(),LxE]);var Xxa=class extends Woc{getLibraryId(){return"posthog-node"}initializeContext(){return new xoc}};var Goc=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Xxa(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.57.1",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var G4o=class{async sendEvent(){}async identify(){}async flush(){}};var Zxa=require("fs/promises"),i5E=require("os"),n5E=require("path");var Dd5="id",Bd5=".fern",H4o=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new Xxa(r),this.userId=t==null?void 0:dFc(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:"3.57.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 p3({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=ot(mr.of((0,i5E.homedir)()),Pe.of(Bd5),Pe.of(Dd5));await ni(t)||(await(0,Zxa.mkdir)((0,n5E.dirname)(t),{recursive:!0}),await(0,Zxa.writeFile)(t,iAe())),this.persistedDistinctId=(await(0,Zxa.readFile)(t)).toString()}return this.persistedDistinctId}};var iEp;async function kxa(){return iEp==null&&(iEp=await Id5()),iEp}async function Id5(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new G4o;let r=await OZo();return r!=null?new H4o({token:r,posthogApiKey:e}):await rsa()!=null?new Goc({posthogApiKey:e}):new H4o({token:void 0,posthogApiKey:e})}catch{return new G4o}}var K4o=se(require("process"),1);var u5E=se(yLc(),1),s5E=se(o5E(),1);function gV(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=L8t(e),e.length===0))return 0;e=e.replace((0,s5E.default)()," ");let r=t.ambiguousIsNarrow?1:2,i=0;for(let n of e){let a=n.codePointAt(0);if(a<=31||a>=127&&a<=159||a>=768&&a<=879)continue;switch(u5E.default.eastAsianWidth(n)){case"F":case"W":i+=2;break;case"A":i+=r;break;default:i+=1}}return i}function Hoc(e){let t=0;for(let r of e.split(`
|
|
2266
|
+
`);for(let o=i;o<a.length;o++){let c=a[o];if(c.length>1024)continue;let d=IxE.test(c)?c.replace(IxE,"$1"):c;if(!d.match(/\S*Error: /)){for(let s of t){let u=s(d,e);if(u){n.push(u);break}}if(n.length>=CxE)break}}return qxE(n)}}var H0p=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,r){let i=Q4o(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:i?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 Rea(t,"DOMException")}isDOMError(t){return Rea(t,"DOMError")}};var K0p=class{match(t){return T0p(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 i=t.message;return i.error&&typeof i.error.message=="string"?String(i.error.message):String(i)}getStack(t){return t.stacktrace||t.stack||void 0}};var $0p=class{constructor(){}match(t){return oxE(t)&&t.error!=null}coerce(t,r){let i=r.apply(t.error);return i||{type:"ErrorEvent",value:t.message,stack:r.syntheticException?.stack,synthetic:!0}}};var ud5=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,J0p=class{match(t){return typeof t=="string"}coerce(t,r){let[i,n]=this.getInfos(t);return{type:i??"Error",value:n??t,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(t){let r="Error",i=t,n=t.match(ud5);return n&&(r=n[1],i=n[2]),[r,i]}};var RxE=["fatal","error","warning","log","info","debug"];function Qoc(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let i=r.length;i>0;i--){let n=r.slice(0,i).join(", ");if(!(n.length>t))return i===r.length||n.length<=t?n:`${n.slice(0,t)}...`}return""}var Y0p=class{match(t){return typeof t=="object"&&t!==null}coerce(t,r){let i=this.getErrorPropertyFromObject(t);return i?r.apply(i):{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 Soc(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){let n=`'${t.name}' captured as exception`;return"message"in t&&typeof t.message=="string"&&(n+=` with message: '${t.message}'`),n}if("message"in t&&typeof t.message=="string")return t.message;let r=this.getObjectClassName(t),i=Qoc(t);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(t){return Q4o(t)&&!nxE(t)&&RxE.indexOf(t)>=0}getErrorPropertyFromObject(t){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(OxE(i))return i}}getObjectClassName(t){try{let r=Object.getPrototypeOf(t);return r?r.constructor.name:void 0}catch{return}}};var X0p=class{match(t){return Soc(t)}coerce(t,r){let i=t.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${Qoc(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Z0p=class{match(t){return U4o(t)}coerce(t,r){return{type:"Error",value:`Primitive value captured as exception: ${String(t)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var k0p=class{match(t){return Rea(t,"PromiseRejectionEvent")}coerce(t,r){let i=this.getUnhandledRejectionReason(t);return U4o(i)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(i)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(i)}getUnhandledRejectionReason(t){if(U4o(t))return t;try{if("reason"in t)return t.reason;if("detail"in t&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var eEp=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 FxE=require("fs"),QxE=require("readline"),Uoc=new DOe.ReduceableCache(25),UxE=new DOe.ReduceableCache(20),tEp=7,sd5=1e3,cd5=1e4;async function LxE(e){let t={};for(let n=e.length-1;n>=0;n--){let a=e[n],o=a?.filename;if(!a||typeof o!="string"||typeof a.lineno!="number"||pd5(o)||_d5(a))continue;t[o]||(t[o]=[]),t[o].push(a.lineno)}let r=Object.keys(t);if(r.length==0)return e;let i=[];for(let n of r){if(UxE.get(n))continue;let a=t[n];if(!a)continue;a.sort((d,s)=>d-s);let o=yd5(a);if(o.every(d=>hd5(n,d)))continue;let c=bd5(Uoc,n,{});i.push(ld5(n,o,c))}return await Promise.all(i).catch(()=>{}),e&&e.length>0&&fd5(e,Uoc),Uoc.reduce(),e}function ld5(e,t,r){return new Promise(i=>{let n=(0,FxE.createReadStream)(e),a=(0,QxE.createInterface)({input:n});function o(){n.destroy(),i()}let c=0,d=0,s=t[d];if(s===void 0)return void o();let u=s[0],f=s[1];function p(){UxE.set(e,1),a.close(),a.removeAllListeners(),o()}n.on("error",p),a.on("error",p),a.on("close",o),a.on("line",_=>{if(c++,!(c<u)&&(r[c]=vd5(_,0),c>=f)){if(d===t.length-1){a.close(),a.removeAllListeners();return}d++;let h=t[d];if(h===void 0){a.close(),a.removeAllListeners();return}u=h[0],f=h[1]}})})}function fd5(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let i=t.get(r.filename);if(i===void 0)continue;dd5(r.lineno,r,i)}}function dd5(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=VxE(e);n<e;n++){let a=r[n];if(a===void 0)return void zxE(t);t.pre_context.push(a)}if(r[e]===void 0)return void zxE(t);t.context_line=r[e];let i=WxE(e);t.post_context=[];for(let n=e+1;n<=i;n++){let a=r[n];if(a===void 0)break;t.post_context.push(a)}}function zxE(e){delete e.pre_context,delete e.context_line,delete e.post_context}function pd5(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function _d5(e){return e.lineno!==void 0&&e.lineno>cd5||e.colno!==void 0&&e.colno>sd5}function hd5(e,t){let r=Uoc.get(e);if(r===void 0)return!1;for(let i=t[0];i<=t[1];i++)if(r[i]===void 0)return!1;return!0}function yd5(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=NxE(r),n=[];for(;;){if(t===e.length-1){n.push(i);break}let a=e[t+1];if(typeof a!="number")break;a<=i[1]?i[1]=a+tEp:(n.push(i),i=NxE(a)),t++}return n}function NxE(e){return[VxE(e),WxE(e)]}function VxE(e){return Math.max(1,e-tEp)}function WxE(e){return e+tEp}function bd5(e,t,r){let i=e.get(t);return i===void 0?(e.set(t,r),r):i}function vd5(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let n=Math.max(t-60,0);n<5&&(n=0);let a=Math.min(n+140,i);return a>i-5&&(a=i),a===i&&(n=Math.max(a-140,0)),r=r.slice(n,a),n>0&&(r=`...${r}`),a<i&&(r+="..."),r}function gd5(e,t){let r=!1;return Object.assign(i=>{let a=global.process.listeners("uncaughtException").filter(o=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length===0;e(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&a&&(r=!0,t(i))},{_posthogErrorHandler:!0})}function xxE(e,t){globalThis.process?.on("uncaughtException",gd5(e,t))}function GxE(e){globalThis.process?.on("unhandledRejection",t=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var Od5=2e3,d$t=class e{constructor(t,r,i){this.client=t,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new Moc({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(t){return ixE(t)&&"__posthog_previously_captured_error"in t&&t.__posthog_previously_captured_error===!0}static async buildEventMessage(t,r,i,n){let a={...n};i||(a.$process_person_profile=!1);let o=this.errorPropertiesBuilder.buildFromUnknown(t,r);return o.$exception_list=await this.errorPropertiesBuilder.modifyFrames(o.$exception_list),{event:"$exception",distinctId:i||yLi(),properties:{...o,...a}}}startAutocaptureIfEnabled(){this.isEnabled()&&(xxE(this.onException.bind(this),this.onFatalError.bind(this)),GxE(this.onException.bind(this)))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let i=await e.buildEventMessage(t,r),a=i.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(a)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:a}):this.client.capture(i)}})())}async onFatalError(t){console.error(t),await this.client.shutdown(Od5),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var HxE="5.24.7";var x4o={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function KxE(e){let t=globalThis.crypto?.subtle;if(!t)throw new Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}var md5=6e4,Ad5=1152921504606847e3,Pd5=["is_not"],Yxa=class e extends Error{constructor(t){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=t,Object.setPrototypeOf(this,e.prototype)}},uE=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},vLi=class e extends Error{constructor(t){super(t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e.prototype)}},Loc=class{constructor({pollingInterval:t,personalApiKey:r,projectApiKey:i,timeout:n,host:a,customHeaders:o,...c}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=t,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=n,this.projectApiKey=i,this.host=a,this.poller=void 0,this.fetch=c.fetch||fetch,this.onError=c.onError,this.customHeaders=o,this.onLoad=c.onLoad,this.cacheProvider=c.cacheProvider,this.strictLocalEvaluation=c.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(t=!0){this.debugMode=t}logMsgIfDebug(t){this.debugMode&&t()}async getFeatureFlag(t,r,i={},n={},a={}){await this.loadFeatureFlags();let o,c;if(!this.loadedSuccessfullyOnce)return o;if(c=this.featureFlagsByKey[t],c!==void 0)try{o=(await this.computeFlagAndPayloadLocally(c,r,i,n,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${t} -> ${o}`))}catch(d){d instanceof vLi||d instanceof uE?this.logMsgIfDebug(()=>console.debug(`${d.name} when computing flag locally: ${t}: ${d.message}`)):d instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${t}: ${d}`))}return o}async getAllFlagsAndPayloads(t,r={},i={},n={},a){await this.loadFeatureFlags();let o={},c={},d=this.featureFlags.length==0,s=a?a.map(f=>this.featureFlagsByKey[f]).filter(Boolean):this.featureFlags,u={};return await Promise.all(s.map(async f=>{try{let{value:p,payload:_}=await this.computeFlagAndPayloadLocally(f,t,r,i,n,void 0,u);o[f.key]=p,_&&(c[f.key]=_)}catch(p){p instanceof vLi||p instanceof uE?this.logMsgIfDebug(()=>console.debug(`${p.name} when computing flag locally: ${f.key}: ${p.message}`)):p instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${f.key}: ${p}`)),d=!0}})),{response:o,payloads:c,fallbackToFlags:d}}async computeFlagAndPayloadLocally(t,r,i={},n={},a={},o,c,d=!1){if(d||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=o!==void 0?o:await this.computeFlagValueLocally(t,r,i,n,a,c);let u=this.getFeatureFlagPayload(t.key,s);return{value:s,payload:u}}async computeFlagValueLocally(t,r,i={},n={},a={},o={}){if(t.ensure_experience_continuity)throw new uE("Flag has experience continuity enabled");if(!t.active)return!1;let d=(t.filters||{}).aggregation_group_type_index;if(d==null)return await this.matchFeatureFlagProperties(t,r,n,o);{let s=this.groupTypeMapping[String(d)];if(!s)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${d} for feature flag ${t.key}`)),new uE("Flag has unknown group type index");if(!(s in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${t.key} without group names passed in`)),!1;let u=a[s];return await this.matchFeatureFlagProperties(t,i[s],u,o)}}getFeatureFlagPayload(t,r){let i=null;if(r!==!1&&r!=null&&(typeof r=="boolean"?i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r.toString()]||null:typeof r=="string"&&(i=this.featureFlagsByKey?.[t]?.filters?.payloads?.[r]||null),i!=null)){if(typeof i=="object")return i;if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}return null}async evaluateFlagDependency(t,r,i,n){let a=t.key;if(!this.featureFlagsByKey)throw new uE("Feature flags not available for dependency evaluation");if(!("dependency_chain"in t))throw new uE(`Flag dependency property for '${a}' is missing required 'dependency_chain' field`);let o=t.dependency_chain;if(!Array.isArray(o))throw new uE(`Flag dependency property for '${a}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new uE(`Circular dependency detected for flag '${a}' (empty dependency chain)`);for(let d of o){if(!(d in n)){let u=this.featureFlagsByKey[d];if(u)if(u.active)try{let f=await this.matchFeatureFlagProperties(u,r,i,n);n[d]=f}catch(f){throw new uE(`Error evaluating flag dependency '${d}' for flag '${a}': ${f}`)}else n[d]=!1;else throw new uE(`Missing flag dependency '${d}' for flag '${a}'`)}if(n[d]==null)throw new uE(`Dependency '${d}' could not be evaluated`)}let c=n[a];return this.flagEvaluatesToExpectedValue(t.value,c)}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,i,n={}){let a=t.filters||{},o=a.groups||[],c=!1,d;for(let s of o)try{if(await this.isConditionMatch(t,r,s,i,n)){let u=s.variant,f=a.multivariate?.variants||[];d=u&&f.some(p=>p.key===u)?u:await this.getMatchingVariant(t,r)||!0;break}}catch(u){if(u instanceof vLi)throw u;if(u instanceof uE)c=!0;else throw u}if(d!==void 0)return d;if(c)throw new uE("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(t,r,i,n,a={}){let o=i.rollout_percentage,c=d=>{this.logMsgIfDebug(()=>console.warn(d))};if((i.properties||[]).length>0){for(let d of i.properties){let s=d.type,u=!1;if(u=s==="cohort"?ZxE(d,n,this.cohorts,this.debugMode):s==="flag"?await this.evaluateFlagDependency(d,r,n,a):XxE(d,n,c),!u)return!1}if(o==null)return!0}return!(o!=null&&await $xE(t.key,r)>o/100)}async getMatchingVariant(t,r){let i=await $xE(t.key,r,"variant"),n=this.variantLookupTable(t).find(a=>i>=a.valueMin&&i<a.valueMax);if(n)return n.key}variantLookupTable(t){let r=[],i=0,n=0;return((t.filters||{}).multivariate?.variants||[]).forEach(c=>{n=i+c.rollout_percentage/100,r.push({valueMin:i,valueMax:n,key:c.key}),i=n}),r}updateFlagState(t){this.featureFlags=t.flags,this.featureFlagsByKey=t.flags.reduce((r,i)=>(r[i.key]=i,r),{}),this.groupTypeMapping=t.groupTypeMapping,this.cohorts=t.cohorts,this.loadedSuccessfullyOnce=!0}warnAboutExperienceContinuityFlags(t){if(this.strictLocalEvaluation)return;let r=t.filter(i=>i.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(i=>i.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}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(md5,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(i){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${i}`))}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 Yxa(`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 Yxa(`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 Yxa(`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 i=await r.json()??{};if(!("flags"in i))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(i)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let n={flags:i.flags??[],groupTypeMapping:i.group_type_mapping||{},cohorts:i.cohorts||{}};if(this.updateFlagState(n),this.clearBackoff(),this.cacheProvider&&t)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(n.flags);break}default:return}}catch(t){t instanceof Yxa&&this.onError?.(t)}}getPersonalApiKeyRequestOptions(t="GET",r){let i={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(i["If-None-Match"]=r),{method:t,headers:i}}_requestFeatureFlagDefinitions(){let t=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=zea(()=>{n.abort()},this.timeout),r.signal=n.signal}try{let n=this.fetch;return n(t,r)}finally{clearTimeout(i)}}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((i,n)=>setTimeout(()=>n(new Error(`Cache shutdown timeout after ${t}ms`)),t))])}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};async function $xE(e,t,r=""){let i=await KxE(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/Ad5}function XxE(e,t,r){let i=e.key,n=e.value,a=e.operator||"exact";if(i in t){if(a==="is_not_set")throw new uE("Operator is_not_set is not supported")}else throw new uE(`Property ${i} not found in propertyValues`);let o=t[i];if(o==null&&!Pd5.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function c(s,u){return Array.isArray(s)?s.map(f=>String(f).toLowerCase()).includes(String(u).toLowerCase()):String(s).toLowerCase()===String(u).toLowerCase()}function d(s,u,f){if(f==="gt")return s>u;if(f==="gte")return s>=u;if(f==="lt")return s<u;if(f==="lte")return s<=u;throw new Error(`Invalid operator: ${f}`)}switch(a){case"exact":return c(n,o);case"is_not":return!c(n,o);case"is_set":return i in t;case"icontains":return String(o).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(n).toLowerCase());case"regex":return JxE(String(n))&&String(o).match(String(n))!==null;case"not_regex":return JxE(String(n))&&String(o).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let s=typeof n=="number"?n:null;if(typeof n=="string")try{s=parseFloat(n)}catch{}return s==null||o==null?d(String(o),String(n),a):typeof o=="string"?d(o,String(n),a):d(o,s,a)}case"is_date_after":case"is_date_before":{if(typeof n=="boolean")throw new uE("Date operations cannot be performed on boolean values");let s=wd5(String(n));if(s==null&&(s=YxE(n)),s==null)throw new uE(`Invalid date: ${n}`);let u=YxE(o);return["is_date_before"].includes(a)?u<s:u>s}default:throw new uE(`Unknown operator: ${a}`)}}function jd5(e,t){if(!(e in t))throw new vLi(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}function ZxE(e,t,r,i=!1){let n=String(e.value);jd5(n,r);let a=r[n];return kxE(a,t,r,i)}function kxE(e,t,r,i=!1){if(!e)return!0;let n=e.type,a=e.values;if(!a||a.length===0)return!0;let o=!1;if("values"in a[0]){for(let c of a)try{let d=kxE(c,t,r,i);if(n==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof vLi)throw d;if(d instanceof uE)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new uE("Can't match cohort without a given cohort property value");return n==="AND"}for(let c of a)try{let d;if(c.type==="cohort")d=ZxE(c,t,r,i);else if(c.type==="flag"){i&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${c.key||"unknown"}'`);continue}else d=XxE(c,t);let s=c.negation||!1;if(n==="AND"){if(!d&&!s||d&&s)return!1}else if(d&&!s||!d&&s)return!0}catch(d){if(d instanceof vLi)throw d;if(d instanceof uE)i&&console.debug(`Failed to compute property ${c} locally: ${d}`),o=!0;else throw d}if(o)throw new uE("can't match cohort without a given cohort property value");return n==="AND"}function JxE(e){try{return new RegExp(e),!0}catch{return!1}}function YxE(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 uE(`${e} is in an invalid date format`)}throw new uE(`The date provided ${e} must be a string, number, or date object`)}function wd5(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let a=r.groups.interval;if(a=="h")i.setUTCHours(i.getUTCHours()-n);else if(a=="d")i.setUTCDate(i.getUTCDate()-n);else if(a=="w")i.setUTCDate(i.getUTCDate()-7*n);else if(a=="m")i.setUTCMonth(i.getUTCMonth()-n);else{if(a!="y")return null;i.setUTCFullYear(i.getUTCFullYear()-n)}return i}}var Voc=class{getProperty(t){return this._memoryStorage[t]}setProperty(t,r){this._memoryStorage[t]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};var Ed5=100,e5E=3e4,Sd5=5e4,Woc=class extends W4o{constructor(t,r={}){if(super(t,r),this._memoryStorage=new Voc,this.options=r,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof r.featureFlagsPollingInterval=="number"?Math.max(r.featureFlagsPollingInterval,Ed5):e5E,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 Loc({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:t,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:n=>{this._events.emit("error",n)},onLoad:n=>{this._events.emit("localEvaluationFlagsLoaded",n)},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider,strictLocalEvaluation:r.strictLocalEvaluation}))}this.errorTracking=new d$t(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||Sd5}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 HxE}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."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStateless(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.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."),this.addPendingPromise(this.prepareEventMessage(t).then(({distinctId:r,event:i,properties:n,options:a})=>super.captureStatelessImmediate(r,i,n,{timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid})).catch(r=>{r&&console.error(r)}))}identify({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStateless(t,u,{disableGeoip:i})}async identifyImmediate({distinctId:t,properties:r={},disableGeoip:i}){let{$set:n,$set_once:a,$anon_distinct_id:o,...c}=r,u={$set:n||c,$set_once:a||{},$anon_distinct_id:o??void 0};super.identifyStatelessImmediate(t,u,{disableGeoip:i})}alias(t){super.aliasStateless(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}async aliasImmediate(t){await super.aliasStatelessImmediate(t.alias,t.distinctId,void 0,{disableGeoip:t.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(t=e5E){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let i=setTimeout(()=>{n(),r(!1)},t),n=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(i),n(),r(a>0)})})}async _getFeatureFlagResult(t,r,i={},n){let a=i.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&t in this._flagOverrides){let A=this._flagOverrides[t];if(A===void 0)return;let j=this._payloadOverrides?.[t];return{key:t,enabled:A!==!1,variant:typeof A=="string"?A:void 0,payload:j}}let{groups:o,disableGeoip:c}=i,{onlyEvaluateLocally:d,personProperties:s,groupProperties:u}=i,f=this.addLocalPersonAndGroupProperties(r,o,s,u);s=f.allPersonProperties,u=f.allGroupProperties,d==null&&(d=this.options.strictLocalEvaluation??!1);let p,_=!1,h,y,b,v,O,m;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let A=this.featureFlagsPoller?.featureFlagsByKey[t];if(A)try{let j=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(A,r,o,s,u,n);if(j){_=!0;let M=j.value;v=A.id,m="Evaluated locally",p={key:t,enabled:M!==!1,variant:typeof M=="string"?M:void 0,payload:j.payload??void 0}}}catch(j){if(j instanceof vLi||j instanceof uE)this._logger?.info(`${j.name} when computing flag locally: ${t}: ${j.message}`);else throw j}}if(!_&&!d){let A=await super.getFeatureFlagDetailsStateless(r,o,s,u,c,[t]);if(A===void 0)b=x4o.UNKNOWN_ERROR;else{h=A.requestId,y=A.evaluatedAt;let j=[];A.errorsWhileComputingFlags&&j.push(x4o.ERRORS_WHILE_COMPUTING),A.quotaLimited?.includes("feature_flags")&&j.push(x4o.QUOTA_LIMITED);let M=A.flags[t];if(M===void 0)j.push(x4o.FLAG_MISSING);else{v=M.metadata?.id,O=M.metadata?.version,m=M.reason?.description??M.reason?.code;let w;if(M.metadata?.payload!==void 0)try{w=JSON.parse(M.metadata.payload)}catch{w=M.metadata.payload}p={key:t,enabled:M.enabled,variant:M.variant,payload:w}}j.length>0&&(b=j.join(","))}}if(a){let A=p===void 0?void 0:p.enabled===!1?!1:p.variant??!0,j=`${t}_${A}`;if(!(r in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[r].includes(j)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[r])?this.distinctIdHasSentFlagCalls[r].push(j):this.distinctIdHasSentFlagCalls[r]=[j];let M={$feature_flag:t,$feature_flag_response:A,$feature_flag_id:v,$feature_flag_version:O,$feature_flag_reason:m,locally_evaluated:_,[`$feature/${t}`]:A,$feature_flag_request_id:h,$feature_flag_evaluated_at:y};b&&(M.$feature_flag_error=b),this.capture({distinctId:r,event:"$feature_flag_called",properties:M,groups:o,disableGeoip:c})}}return p!==void 0&&this._payloadOverrides!==void 0&&t in this._payloadOverrides&&(p={...p,payload:this._payloadOverrides[t]}),p}async getFeatureFlag(t,r,i){let n=await this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(n!==void 0)return n.enabled===!1?!1:n.variant??!0}async getFeatureFlagPayload(t,r,i,n){if(this._payloadOverrides!==void 0&&t in this._payloadOverrides)return this._payloadOverrides[t];let a=await this._getFeatureFlagResult(t,r,{...n,sendFeatureFlagEvents:!1},i);if(a!==void 0)return a.payload??null}async getFeatureFlagResult(t,r,i){return this._getFeatureFlagResult(t,r,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}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 i=await r.json();if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}async isFeatureEnabled(t,r,i){let n=await this.getFeatureFlag(t,r,i);if(n!==void 0)return!!n||!1}async getAllFlags(t,r){return(await this.getAllFlagsAndPayloads(t,r)).featureFlags||{}}async getAllFlagsAndPayloads(t,r){let{groups:i,disableGeoip:n,flagKeys:a}=r||{},{onlyEvaluateLocally:o,personProperties:c,groupProperties:d}=r||{},s=this.addLocalPersonAndGroupProperties(t,i,c,d);c=s.allPersonProperties,d=s.allGroupProperties,o==null&&(o=this.options.strictLocalEvaluation??!1);let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(t,i,c,d,a),f={},p={},_=!0;if(u&&(f=u.response,p=u.payloads,_=u.fallbackToFlags),_&&!o){let h=await super.getFeatureFlagsAndPayloadsStateless(t,i,c,d,n,a);f={...f,...h.flags||{}},p={...p,...h.payloads||{}}}return this._flagOverrides!==void 0&&(f={...f,...this._flagOverrides}),this._payloadOverrides!==void 0&&(p={...p,...this._payloadOverrides}),{featureFlags:f,featureFlagPayloads:p}}groupIdentify({groupType:t,groupKey:r,properties:i,distinctId:n,disableGeoip:a}){super.groupIdentifyStateless(t,r,i,{disableGeoip:a},n)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(t){let r=i=>Object.fromEntries(i.map(n=>[n,!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 i=r.flags;if(i===!1||Array.isArray(i)||typeof i=="object"&&i!==null)return!0}if("payloads"in r){let i=r.payloads;if(i===!1||typeof i=="object"&&i!==null)return!0}return!1}withContext(t,r,i){return this.context?this.context.run(t,r,i):r()}getContext(){return this.context?.get()}async _shutdown(t){return this.featureFlagsPoller?.stopPoller(t),this.errorTracking.shutdown(),super._shutdown(t)}async _requestRemoteConfigPayload(t){if(!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${t}/remote_config?token=${encodeURIComponent(this.apiKey)}`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},n=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let a=new AbortController;n=zea(()=>{a.abort()},this.options.requestTimeout),i.signal=a.signal}try{return await this.fetch(r,i)}catch(a){this._events.emit("error",a);return}finally{n&&clearTimeout(n)}}extractPropertiesFromEvent(t,r){if(!t)return{personProperties:{},groupProperties:{}};let i={},n={};for(let[a,o]of Object.entries(t))if(uxE(o)&&r&&a in r){let c={};for(let[d,s]of Object.entries(o))c[String(d)]=String(s);n[String(a)]=c}else i[String(a)]=String(o);return{personProperties:i,groupProperties:n}}async getFeatureFlagsForEvent(t,r,i,n){let a=n?.personProperties||{},o=n?.groupProperties||{},c=n?.flagKeys;if(n?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,f]of Object.entries(r||{}))s[u]=String(f);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let s={};for(let[u,f]of Object.entries(r||{}))s[u]=String(f);return await this.getAllFlags(t,{groups:s,personProperties:a,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:c})}return(await super.getFeatureFlagsStateless(t,r,a,o,i)).flags}addLocalPersonAndGroupProperties(t,r,i,n){let a={distinct_id:t,...i||{}},o={};if(r)for(let c of Object.keys(r))o[c]={$group_key:r[c],...n?.[c]||{}};return{allPersonProperties:a,allGroupProperties:o}}captureException(t,r,i,n){if(!d$t.isPreviouslyCapturedError(t)){let a=new Error("PostHog syntheticException");this.addPendingPromise(d$t.buildEventMessage(t,{syntheticException:a},r,i).then(o=>this.capture({...o,uuid:n})))}}async captureExceptionImmediate(t,r,i){if(!d$t.isPreviouslyCapturedError(t)){let n=new Error("PostHog syntheticException");this.addPendingPromise(d$t.buildEventMessage(t,{syntheticException:n},r,i).then(a=>this.captureImmediate(a)))}}async prepareEventMessage(t){let{distinctId:r,event:i,properties:n,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s}=t,u=this.context?.get(),f=r||u?.distinctId,p={...u?.properties||{},...n||{}};f||(f=yLi(),p.$process_person_profile=!1),u?.sessionId&&!p.$session_id&&(p.$session_id=u.sessionId);let _=this._runBeforeSend({distinctId:f,event:i,properties:p,groups:a,sendFeatureFlags:o,timestamp:c,disableGeoip:d,uuid:s});if(!_)return Promise.reject(null);let h=await Promise.resolve().then(async()=>{if(o){let y=typeof o=="object"?o:void 0;return await this.getFeatureFlagsForEvent(_.distinctId,a,d,y)}return _.event,{}}).then(y=>{let b={};if(y)for(let[O,m]of Object.entries(y))b[`$feature/${O}`]=m;let v=Object.keys(y||{}).filter(O=>y?.[O]!==!1).sort();return v.length>0&&(b.$active_feature_flags=v),b}).catch(()=>({})).then(y=>({...y,..._.properties||{},$groups:_.groups||a}));return _.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof h.$raw_user_agent=="string"&&txE(h.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(_.event="$bot_pageview",h.$browser_type="bot"),{distinctId:_.distinctId,event:_.event,properties:h,options:{timestamp:_.timestamp,disableGeoip:_.disableGeoip,uuid:_.uuid}}}_runBeforeSend(t){let r=this.options.before_send;if(!r)return t;let i=Array.isArray(r)?r:[r],n=t;for(let a of i){if(n=a(n),!n)return this._logger.info(`Event '${t.event}' was rejected in beforeSend function`),null;if(!n.properties||Object.keys(n.properties).length===0){let o=`Event '${n.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(o)}}return n}};var t5E=require("async_hooks"),xoc=class{constructor(){this.storage=new t5E.AsyncLocalStorage}get(){return this.storage.getStore()}run(t,r,i){if(i?.fresh===!0)return this.storage.run(t,r);{let a=this.get()||{},o={distinctId:t.distinctId??a.distinctId,sessionId:t.sessionId??a.sessionId,properties:{...a.properties||{},...t.properties||{}}};return this.storage.run(o,r)}}};var r5E="posthog-node";function Md5(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"],sendExceptionsToPostHog:a=!0}={}){return o=>{if(!(n==="*"||n.includes(o.level)))return o;o.tags||(o.tags={});let d=o.tags[rEp.POSTHOG_ID_TAG];if(d===void 0)return o;let s=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${d}`,s).toString();o.tags["PostHog Person URL"]=u;let f=o.exception?.values||[],p=f.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),_={$exception_message:f[0]?.value||o.message,$exception_type:f[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:f[0]?.value||o.message,$sentry_exception_type:f[0]?.type,$sentry_tags:o.tags};return t&&r&&(_.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id),a&&e.capture({event:"$exception",distinctId:d,properties:_}),o}}var rEp=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(t,r,i,n,a){this.name=r5E,this.name=r5E,this.setupOnce=function(o,c){let d=c()?.getClient()?.getDsn()?.projectId;o(Md5(t,{organization:r,projectId:d,prefix:i,severityAllowList:n,sendExceptionsToPostHog:a??!0}))}}};d$t.errorPropertiesBuilder=new DOe.ErrorPropertiesBuilder([new DOe.EventCoercer,new DOe.ErrorCoercer,new DOe.ObjectCoercer,new DOe.StringCoercer,new DOe.PrimitiveCoercer],DOe.createStackParser("node:javascript",DOe.nodeStackLineParser),[Y8E(),LxE]);var Xxa=class extends Woc{getLibraryId(){return"posthog-node"}initializeContext(){return new xoc}};var Goc=class{posthog;constructor({posthogApiKey:t}){this.posthog=new Xxa(t)}async identify(){}async sendEvent(t){t.orgId!=null&&this.posthog.capture({distinctId:t.orgId,event:"CLI",properties:{...t,...t.properties,version:"3.58.0",usingAccessToken:!0}})}async flush(){await this.posthog.flush()}};var G4o=class{async sendEvent(){}async identify(){}async flush(){}};var Zxa=require("fs/promises"),i5E=require("os"),n5E=require("path");var Dd5="id",Bd5=".fern",H4o=class{posthog;userId;token;constructor({token:t,posthogApiKey:r}){this.posthog=new Xxa(r),this.userId=t==null?void 0:dFc(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:"3.58.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 p3({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=ot(mr.of((0,i5E.homedir)()),Pe.of(Bd5),Pe.of(Dd5));await ni(t)||(await(0,Zxa.mkdir)((0,n5E.dirname)(t),{recursive:!0}),await(0,Zxa.writeFile)(t,iAe())),this.persistedDistinctId=(await(0,Zxa.readFile)(t)).toString()}return this.persistedDistinctId}};var iEp;async function kxa(){return iEp==null&&(iEp=await Id5()),iEp}async function Id5(){try{let e="phc_yQgAEdJJkVpI24NdSRID2mor1x1leRpDoC9yZ9mfXal",t=process.env.FERN_DISABLE_TELEMETRY==="true";if(e==null||t)return new G4o;let r=await OZo();return r!=null?new H4o({token:r,posthogApiKey:e}):await rsa()!=null?new Goc({posthogApiKey:e}):new H4o({token:void 0,posthogApiKey:e})}catch{return new G4o}}var K4o=se(require("process"),1);var u5E=se(yLc(),1),s5E=se(o5E(),1);function gV(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=L8t(e),e.length===0))return 0;e=e.replace((0,s5E.default)()," ");let r=t.ambiguousIsNarrow?1:2,i=0;for(let n of e){let a=n.codePointAt(0);if(a<=31||a>=127&&a<=159||a>=768&&a<=879)continue;switch(u5E.default.eastAsianWidth(n)){case"F":case"W":i+=2;break;case"A":i+=r;break;default:i+=1}}return i}function Hoc(e){let t=0;for(let r of e.split(`
|
|
2267
2267
|
`))t=Math.max(t,gV(r));return t}var M5E=se(aEp(),1);var qd5=/[\p{Lu}]/u,Td5=/[\p{Ll}]/u,f5E=/^[\p{Lu}](?![\p{Lu}])/gu,_5E=/([\p{Alpha}\p{N}_]|$)/u,oEp=/[_.\- ]+/,Rd5=new RegExp("^"+oEp.source),d5E=new RegExp(oEp.source+_5E.source,"gu"),p5E=new RegExp("\\d+"+_5E.source,"gu"),zd5=(e,t,r,i)=>{let n=!1,a=!1,o=!1,c=!1;for(let d=0;d<e.length;d++){let s=e[d];c=d>2?e[d-3]==="-":!0,n&&qd5.test(s)?(e=e.slice(0,d)+"-"+e.slice(d),n=!1,o=a,a=!0,d++):a&&o&&Td5.test(s)&&(!c||i)?(e=e.slice(0,d-1)+"-"+e.slice(d-1),o=a,a=!1,n=!0):(n=t(s)===s&&r(s)!==s,o=a,a=r(s)===s&&t(s)!==s)}return e},Nd5=(e,t)=>(f5E.lastIndex=0,e.replace(f5E,r=>t(r))),Fd5=(e,t)=>(d5E.lastIndex=0,p5E.lastIndex=0,e.replace(d5E,(r,i)=>t(i)).replace(p5E,r=>t(r)));function uEp(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(a=>a.trim()).filter(a=>a.length).join("-"):e=e.trim(),e.length===0)return"";let r=t.locale===!1?a=>a.toLowerCase():a=>a.toLocaleLowerCase(t.locale),i=t.locale===!1?a=>a.toUpperCase():a=>a.toLocaleUpperCase(t.locale);return e.length===1?oEp.test(e)?"":t.pascalCase?i(e):r(e):(e!==r(e)&&(e=zd5(e,r,i,t.preserveConsecutiveUppercase)),e=e.replace(Rd5,""),e=t.preserveConsecutiveUppercase?Nd5(e,r):r(e),t.pascalCase&&(e=i(e.charAt(0))+e.slice(1)),Fd5(e,i))}var fEp=se(y5E(),1);var b5E=(e=0)=>t=>`\x1B[${t+e}m`,v5E=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,g5E=(e=0)=>(t,r,i)=>`\x1B[${38+e};2;${t};${r};${i}m`,qB={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]}},Jgk=Object.keys(qB.modifier),Vd5=Object.keys(qB.color),Wd5=Object.keys(qB.bgColor),Ygk=[...Vd5,...Wd5];function xd5(){let e=new Map;for(let[t,r]of Object.entries(qB)){for(let[i,n]of Object.entries(r))qB[i]={open:`\x1B[${n[0]}m`,close:`\x1B[${n[1]}m`},r[i]=qB[i],e.set(n[0],n[1]);Object.defineProperty(qB,t,{value:r,enumerable:!1})}return Object.defineProperty(qB,"codes",{value:e,enumerable:!1}),qB.color.close="\x1B[39m",qB.bgColor.close="\x1B[49m",qB.color.ansi=b5E(),qB.color.ansi256=v5E(),qB.color.ansi16m=g5E(),qB.bgColor.ansi=b5E(10),qB.bgColor.ansi256=v5E(10),qB.bgColor.ansi16m=g5E(10),Object.defineProperties(qB,{rgbToAnsi256:{value(t,r,i){return t===r&&r===i?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(i/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[i]=r;i.length===3&&(i=[...i].map(a=>a+a).join(""));let n=Number.parseInt(i,16);return[n>>16&255,n>>8&255,n&255]},enumerable:!1},hexToAnsi256:{value:t=>qB.rgbToAnsi256(...qB.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let r,i,n;if(t>=232)r=((t-232)*10+8)/255,i=r,n=r;else{t-=16;let c=t%36;r=Math.floor(t/36)/5,i=Math.floor(c/6)/5,n=c%6/5}let a=Math.max(r,i,n)*2;if(a===0)return 30;let o=30+(Math.round(n)<<2|Math.round(i)<<1|Math.round(r));return a===2&&(o+=60),o},enumerable:!1},rgbToAnsi:{value:(t,r,i)=>qB.ansi256ToAnsi(qB.rgbToAnsi256(t,r,i)),enumerable:!1},hexToAnsi:{value:t=>qB.ansi256ToAnsi(qB.hexToAnsi256(t)),enumerable:!1}}),qB}var Gd5=xd5(),O5E=Gd5;var Koc=new Set(["\x1B","\x9B"]),Hd5=39,cEp="\x07",P5E="[",Kd5="]",j5E="m",lEp=`${Kd5}8;;`,m5E=e=>`${Koc.values().next().value}${P5E}${e}${j5E}`,A5E=e=>`${Koc.values().next().value}${lEp}${e}${cEp}`,$d5=e=>e.split(" ").map(t=>gV(t)),sEp=(e,t,r)=>{let i=[...t],n=!1,a=!1,o=gV(L8t(e[e.length-1]));for(let[c,d]of i.entries()){let s=gV(d);if(o+s<=r?e[e.length-1]+=d:(e.push(d),o=0),Koc.has(d)&&(n=!0,a=i.slice(c+1).join("").startsWith(lEp)),n){a?d===cEp&&(n=!1,a=!1):d===j5E&&(n=!1);continue}o+=s,o===r&&c<i.length-1&&(e.push(""),o=0)}!o&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},Jd5=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(gV(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},Yd5=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let i="",n,a,o=$d5(e),c=[""];for(let[s,u]of e.split(" ").entries()){r.trim!==!1&&(c[c.length-1]=c[c.length-1].trimStart());let f=gV(c[c.length-1]);if(s!==0&&(f>=t&&(r.wordWrap===!1||r.trim===!1)&&(c.push(""),f=0),(f>0||r.trim===!1)&&(c[c.length-1]+=" ",f++)),r.hard&&o[s]>t){let p=t-f,_=1+Math.floor((o[s]-p-1)/t);Math.floor((o[s]-1)/t)<_&&c.push(""),sEp(c,u,t);continue}if(f+o[s]>t&&f>0&&o[s]>0){if(r.wordWrap===!1&&f<t){sEp(c,u,t);continue}c.push("")}if(f+o[s]>t&&r.wordWrap===!1){sEp(c,u,t);continue}c[c.length-1]+=u}r.trim!==!1&&(c=c.map(s=>Jd5(s)));let d=[...c.join(`
|
|
2268
2268
|
`)];for(let[s,u]of d.entries()){if(i+=u,Koc.has(u)){let{groups:p}=new RegExp(`(?:\\${P5E}(?<code>\\d+)m|\\${lEp}(?<uri>.*)${cEp})`).exec(d.slice(s).join(""))||{groups:{}};if(p.code!==void 0){let _=Number.parseFloat(p.code);n=_===Hd5?void 0:_}else p.uri!==void 0&&(a=p.uri.length===0?void 0:p.uri)}let f=O5E.codes.get(Number(n));d[s+1]===`
|
|
2269
2269
|
`?(a&&(i+=A5E("")),n&&f&&(i+=m5E(f))):u===`
|
|
@@ -2426,7 +2426,7 @@ For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides
|
|
|
2426
2426
|
Run ${ct.cyan("fern generator upgrade")} to upgrade your generators.`),n.length>2&&(r+=`
|
|
2427
2427
|
Run ${ct.cyan("fern generator upgrade --list")} to see the full list of generator upgrades available.`),e5a(r,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"})}async function fzp({generatorUpgradeInfo:e,header:t,limit:r,includeBoxen:i=!0}){if(!aoS(e))return;let n=t??"",a=e.filter(c=>c.isUpgradeAvailable);r!=null&&(a=a.slice(0,r+1));let o=a.sort((c,d)=>c.generatorName.localeCompare(d.generatorName)||c.currentVersion.localeCompare(d.currentVersion));for(let c of o)n+=`
|
|
2428
2428
|
${await kz5(c.generatorName)} (${c.apiName!=null?"API: "+c.apiName+", ":""}Group: ${c.generatorGroup}) `+ct.dim(c.currentVersion)+ct.reset(" \u2192 ")+ct.green(c.latestVersion);return n+=`
|
|
2429
|
-
`,i?e5a(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function kz5(e){let r=await new noS.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 eN5({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await uoS({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,f)=>{c.versions[s]==null&&(c.versions[s]={});let p=lki(u.name,f),_=await K5t({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:f});_!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:_})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await uoS({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,d,s,u)=>{if(c==null)return;o.versions[c]==null&&(o.versions[c]={}),o.versions[c][d]==null&&(o.versions[c][d]={});let f=lki(s.name,u),p=await K5t({generatorName:f,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:u});p!=null&&(o.versions[c][d][s.name]={previousVersion:s.version,latestVersion:p})},generatorFilter:r,groupFilter:i}),o}async function uoS({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async o=>{let c=await Zme({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let d=i!=null?OU(i):void 0;for(let s of c.groups)if(!(n!=null&&s.groupName!==n))for(let u of s.generators)d!=null&&u.name!==d||await r(a.workspaceName,s.groupName,u,o)})}))}function soS(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[o,c]of Object.entries(a)){r.debug(`Checking if ${o} in group ${n} has an upgrade available...`);let d=kZ(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:o,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function C_c({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await eN5({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[d,s]of Object.entries(c.versions))o.push(...soS(s,d,t.logger));else o.push(...soS(c.versions,void 0,t.logger))}return o}async function zbn({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:Eka(e.packageName,{version:t?"prerelease":"latest"})}var coS=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],q_c=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=la.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new Wmn(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),o=this.getCliName();(n==null||a==null||o==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:o}}getPackageName(){return"fern-api"}getPackageVersion(){return"3.
|
|
2429
|
+
`,i?e5a(n,{padding:1,float:"center",textAlignment:"center",borderColor:"yellow",borderStyle:"round"}):n}async function kz5(e){let r=await new noS.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 eN5({cliContext:e,project:{apiWorkspaces:t},generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){if(t.length===1){let c={type:"singleApi",versions:{}};return await uoS({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(d,s,u,f)=>{c.versions[s]==null&&(c.versions[s]={});let p=lki(u.name,f),_=await K5t({generatorName:p,cliVersion:e.environment.packageVersion,currentGeneratorVersion:u.version,channel:n,includeMajor:a,context:f});_!=null&&(c.versions[s][u.name]={previousVersion:u.version,latestVersion:_})},generatorFilter:r,groupFilter:i}),c}let o={type:"multiApi",versions:{}};return await uoS({cliContext:e,apiWorkspaces:t,perGeneratorAction:async(c,d,s,u)=>{if(c==null)return;o.versions[c]==null&&(o.versions[c]={}),o.versions[c][d]==null&&(o.versions[c][d]={});let f=lki(s.name,u),p=await K5t({generatorName:f,cliVersion:e.environment.packageVersion,currentGeneratorVersion:s.version,channel:n,includeMajor:a,context:u});p!=null&&(o.versions[c][d][s.name]={previousVersion:s.version,latestVersion:p})},generatorFilter:r,groupFilter:i}),o}async function uoS({cliContext:e,apiWorkspaces:t,perGeneratorAction:r,generatorFilter:i,groupFilter:n}){await Promise.all(t.map(async a=>{await e.runTaskForWorkspace(a,async o=>{let c=await Zme({absolutePathToWorkspace:a.absoluteFilePath,context:o});if(c==null||c.groups==null)return;let d=i!=null?OU(i):void 0;for(let s of c.groups)if(!(n!=null&&s.groupName!==n))for(let u of s.generators)d!=null&&u.name!==d||await r(a.workspaceName,s.groupName,u,o)})}))}function soS(e,t,r){let i=[];for(let[n,a]of Object.entries(e))for(let[o,c]of Object.entries(a)){r.debug(`Checking if ${o} in group ${n} has an upgrade available...`);let d=kZ(c.latestVersion,c.previousVersion);r.debug(`Latest version: ${c.latestVersion}. `+(d?"Upgrade available.":"No upgrade available.")),i.push({generatorName:o,generatorGroup:n,apiName:t,isUpgradeAvailable:d,currentVersion:c.previousVersion,latestVersion:c.latestVersion})}return i}async function C_c({project:e,cliContext:t,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a}){let o=[];if(e!=null){let c=await eN5({cliContext:t,project:e,generatorFilter:r,groupFilter:i,channel:n,includeMajor:a});if(c.type==="multiApi")for(let[d,s]of Object.entries(c.versions))o.push(...soS(s,d,t.logger));else o.push(...soS(c.versions,void 0,t.logger))}return o}async function zbn({cliEnvironment:e,includePreReleases:t=!1}){return e.packageName!=="fern-api"?e.packageVersion:Eka(e.packageName,{version:t?"prerelease":"latest"})}var coS=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],q_c=class{environment;didSucceed=!0;numTasks=0;ttyAwareLogger;logLevel=la.Info;isLocal;constructor(t,r,{isLocal:i}){this.ttyAwareLogger=new Wmn(t,r),this.isLocal=i??!1;let n=this.getPackageName(),a=this.getPackageVersion(),o=this.getCliName();(n==null||a==null||o==null)&&this.exitProgram(),this.environment={packageName:n,packageVersion:a,cliName:o}}getPackageName(){return"fern-api"}getPackageVersion(){return"3.58.0"}getCliName(){return"fern"}setLogLevel(t){this.logLevel=t}logFernVersionDebug(){this.logger.debug(`Running ${ct.bold(`${this.environment.cliName}`)} (${this.environment.packageName}@${this.environment.packageVersion})`)}failAndThrow(t,r){throw this.failWithoutThrowing(t,r),new yS}failWithoutThrowing(t,r){this.didSucceed=!1,wZa({message:t,error:r,logger:this.logger})}async exit({code:t}={}){!this._suppressUpgradeMessage&&!this.isLocal&&await this.nudgeUpgradeIfAvailable(),this.ttyAwareLogger.finish(),await(await kxa()).flush(),this.exitProgram({code:t})}async nudgeUpgradeIfAvailable(){try{let t=await Promise.race([this.isUpgradeAvailable(),new Promise((i,n)=>setTimeout(()=>n("Request timed out"),300))]),r=await ooS({cliEnvironment:this.environment,upgradeInfo:t});r!=null&&(r.endsWith(`
|
|
2430
2430
|
`)||(r+=`
|
|
2431
2431
|
`),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=_Ac(t.map(i=>i.type==="docs"?"docs":i.workspaceName??"api"),i=>i.length);r!=null&&(this.longestWorkspaceName=r)}project;registerProject(t){this.project=t}runTask(t){return this.runTaskWithInit(this.constructTaskInit(),t)}addTask(){return this.addTaskWithInit(this.constructTaskInit())}async runTaskForWorkspace(t,r){await this.runTaskWithInit(this.constructTaskInitForWorkspace(t),r)}addTaskWithInit(t){let r=new YWo(t);return this.ttyAwareLogger.registerTask(r),r}USE_NODE_18_OR_ABOVE_MESSAGE="The Fern CLI requires Node 18+ or above.";async runTaskWithInit(t,r){let i=this.addTaskWithInit(t).start(),n;try{n=await r(i)}catch(a){throw a.message.includes("globalThis")?(i.logger.error(this.USE_NODE_18_OR_ABOVE_MESSAGE),i.failWithoutThrowing()):i.failWithoutThrowing(void 0,a),new yS}finally{i.finish()}return n}async instrumentPostHogEvent(t){this.isLocal||(await kxa()).sendEvent(t)}logger=ZH((t,...r)=>this.log(t,...r));stderr=ZH((t,...r)=>this.logStderr(t,...r));constructTaskInitForWorkspace(t){let r=loS(t.type==="docs"?"docs":t.workspaceName??"api"),i=1+(this.longestWorkspaceName!=null?loS(this.longestWorkspaceName):r).length,n=r.padEnd(i),a=coS[this.numTasks++%coS.length],o=ct.hex(a)(n);return{...this.constructTaskInit(),logPrefix:o}}constructTaskInit(){return{logImmediately:t=>this.logImmediately(t),takeOverTerminal:t=>this.ttyAwareLogger.takeOverTerminal(t),onResult:t=>{t===qA.Failure&&(this.didSucceed=!1)},instrumentPostHogEvent:async t=>{await this.instrumentPostHogEvent(t)},shouldBufferLogs:!1}}log(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}])}logStderr(t,...r){this.logImmediately([{parts:r,level:t,time:new Date}],{stderr:!0})}logImmediately(t,{stderr:r=!1}={}){let i=t.filter(n=>U8t.indexOf(n.level)>=U8t.indexOf(this.logLevel));this.ttyAwareLogger.log(i,{includeDebugInfo:this.logLevel===la.Debug,stderr:r})}_suppressUpgradeMessage=!1;suppressUpgradeMessage(){this._suppressUpgradeMessage=!0}_isUpgradeAvailable;async isUpgradeAvailable({includePreReleases:t=!1}={}){if(this._isUpgradeAvailable==null){this.logger.debug(`Checking if ${this.environment.packageName} upgrade is available...`);let r=await zbn({cliEnvironment:this.environment,includePreReleases:t}),i=kZ(r,this.environment.packageVersion);this.logger.debug(`Latest version: ${r}. `+(i?"Upgrade available.":"No upgrade available."));let n={isUpgradeAvailable:i,latestVersion:r},a=await C_c({project:this.project,cliContext:this});this._isUpgradeAvailable={cliUpgradeInfo:n,generatorUpgradeInfo:a}}return this._isUpgradeAvailable}async confirmPrompt(t,r=!1){try{return await czp({message:t,choices:[{name:"No",value:!1},{name:"Yes",value:!0}],default:r,theme:{prefix:ct.yellow("?"),style:{answer:n=>ct.cyan(n),message:n=>ct.bold(n),highlight:n=>ct.cyan(n)}}})}catch(i){throw i?.name==="ExitPromptError"?(this.logger.info(`
|
|
2432
2432
|
Cancelled by user.`),new yS):i}}async getInput(t){return await ozp({message:t.message,default:t.default})}};function loS(e){return`[${e}]:`}var foS=require("fs/promises");async function dzp({context:e,nameOverride:t,...r}){let i=await KM(t);return i==null?e.failAndThrow(`Directory "${t??wE}" not found.`):await doS({absolutePathToFernDirectory:i,context:e,nameOverride:t,...r})}async function doS({absolutePathToFernDirectory:e,cliName:t,cliVersion:r,commandLineApiWorkspace:i,defaultToAllApiWorkspaces:n,context:a}){let o=[];(await ni(ot(e,Pe.of(S7)))||await ni(ot(e,Pe.of(WM)))||await ni(ot(e,Pe.of(xM)))||await ni(ot(e,Pe.of(dfa)))||await ni(ot(e,Pe.of(Rka)))||await ni(ot(e,Pe.of(E9c))))&&(o=await poS({cliName:t,fernDirectory:e,cliVersion:r,context:a,commandLineApiWorkspace:i,defaultToAllApiWorkspaces:n}));let c=await Dvp({fernDirectory:e,context:a});return o.length===0&&c==null?a.failAndThrow(`No SDK specifications or docs specifications found. Please ensure one of the following .yml (not .yaml) files is present:
|
|
@@ -2462,7 +2462,7 @@ The generator configuration must be an object with a 'name' property, but the cu
|
|
|
2462
2462
|
|
|
2463
2463
|
Please check your generators.yml file and ensure the generator is properly configured.`);let o=n,c=await moS({generatorName:t,logger:a});if(c==null)return;let d=rN5({migrations:c.migrations,from:r,to:i,logger:a});if(d.length!==0)return AoS({migrations:d,config:o,logger:a})}function PoS(e){return{"fernapi/fern-typescript-sdk":"https://buildwithfern.com/learn/sdks/generators/typescript/changelog","fernapi/fern-typescript-node-sdk":"https://buildwithfern.com/learn/sdks/generators/typescript/changelog","fernapi/fern-python-sdk":"https://buildwithfern.com/learn/sdks/generators/python/changelog","fernapi/fern-go-sdk":"https://buildwithfern.com/learn/sdks/generators/go/changelog","fernapi/fern-java-sdk":"https://buildwithfern.com/learn/sdks/generators/java/changelog","fernapi/fern-csharp-sdk":"https://buildwithfern.com/learn/sdks/generators/csharp/changelog","fernapi/fern-php-sdk":"https://buildwithfern.com/learn/sdks/generators/php/changelog","fernapi/fern-ruby-sdk":"https://buildwithfern.com/learn/sdks/generators/ruby/changelog","fernapi/fern-swift-sdk":"https://buildwithfern.com/learn/sdks/generators/swift/changelog"}[e]}async function nN5({absolutePathToWorkspace:e,context:t,generatorFilter:r,groupFilter:i,includeMajor:n,channel:a,cliVersion:o}){let c=await _ki({absolutePathToWorkspace:e});if(c==null||!await ni(c))return t.logger.debug("Generators configuration file was not found, no generators to upgrade."),{updatedConfiguration:void 0,skippedMajorUpgrades:[],appliedUpgrades:[],alreadyUpToDate:[]};let d=await(0,z_c.readFile)(c);t.logger.debug(`Found generators: ${d.toString()}`);let s=o9a.default.parseDocument(d.toString()),u=s.get("groups");if(u==null)return t.logger.debug("No groups were found within the generators configuration, no generators to upgrade."),{updatedConfiguration:void 0,skippedMajorUpgrades:[],appliedUpgrades:[],alreadyUpToDate:[]};if(!o9a.default.isMap(u))return t.failAndThrow(`Expected 'groups' to be a map in ${ZWo.default.relative(process.cwd(),c)}`),{updatedConfiguration:void 0,skippedMajorUpgrades:[],appliedUpgrades:[],alreadyUpToDate:[]};t.logger.debug(`Groups found: ${u.toString()}`);let f=[],p=[],_=[];for(let h of u.items){let y=h.key.value,b=h.value;if(!o9a.default.isMap(b)){t.failAndThrow(`Expected group ${y} to be a map in ${ZWo.default.relative(process.cwd(),c)}`);continue}if(i!=null&&i!==y){t.logger.debug(`Skipping group ${y} as it does not match the filter: ${i}`);continue}let v=b.get("generators");if(!o9a.default.isSeq(v)){t.failAndThrow(`Expected group ${y} to have a 'generators' key in ${ZWo.default.relative(process.cwd(),c)}`);continue}t.logger.debug(`Generators found: ${v.toString()}`);for(let O of v.items){o9a.default.isMap(O)||t.failAndThrow(`Expected generator in group ${y} to be a map in ${ZWo.default.relative(process.cwd(),c)}`);let m=O.get("name"),g=lki(m,t),A=r!=null?OU(r):void 0;if(A!=null&&g!==A){t.logger.debug(`Skipping generator ${m} as it does not match the filter: ${r}`);continue}let j=O.get("version"),M=await K5t({generatorName:g,cliVersion:o,currentGeneratorVersion:j,channel:a,includeMajor:n,context:t}),w=M??j;if(M!=null)if(M!==j){t.logger.debug(ct.green(`Upgrading ${m} from ${j} to ${M}`)),O.set("version",M);let E=0,B=[],q=O.toJSON(),R=await pzp({generatorName:g,from:j,to:M,config:q,logger:t.logger});if(R!=null){E=R.migrationsApplied,B=R.appliedVersions;let T=new Set(Object.keys(q)),K=new Set(Object.keys(R.config));for(let H of T)K.has(H)||O.delete(H);for(let[H,z]of Object.entries(R.config))O.set(H,z);t.logger.debug(ct.dim(`Applied ${E} migration(s): ${B.join(", ")}`))}p.push({generatorName:m,groupName:y,previousVersion:j,newVersion:M,migrationsApplied:E>0?E:void 0,migrationVersions:B.length>0?B:void 0})}else t.logger.debug(ct.gray(`${m} is already on the latest version: ${j}`)),_.push({generatorName:m,groupName:y,version:j});if(!n){let E=await K5t({generatorName:g,cliVersion:o,currentGeneratorVersion:w,channel:a,includeMajor:!0,context:t});if(E!=null){let B=_zp.default.parse(w),q=_zp.default.parse(E);B!=null&&q!=null&&q.major>B.major&&f.push({generatorName:m,currentVersion:w,latestMajorVersion:E})}}}}return{updatedConfiguration:s.toString(),skippedMajorUpgrades:f,appliedUpgrades:p,alreadyUpToDate:_}}async function joS({cliContext:e,generator:t,group:r,project:{apiWorkspaces:i},includeMajor:n,channel:a}){let o=[],c=[],d=[];if(await Promise.all(i.map(async s=>{await e.runTaskForWorkspace(s,async u=>{let f=await h_a({absolutePathToWorkspace:s.absoluteFilePath,context:u})??{};if(f==null||f.groups==null){u.logger.debug("No groups were found within the generators configuration, no generators to upgrade.");return}s.workspaceName==null?u.logger.info("Upgrading generators."):u.logger.info(`Upgrading generators in workspace: ${s.workspaceName}.`);let p=await nN5({absolutePathToWorkspace:s.absoluteFilePath,context:u,generatorFilter:t,groupFilter:r,includeMajor:n,channel:a,cliVersion:e.environment.packageVersion}),_=await _ki({absolutePathToWorkspace:s.absoluteFilePath});_!=null&&p.updatedConfiguration!=null&&await(0,z_c.writeFile)(_,p.updatedConfiguration),o.push(...p.skippedMajorUpgrades),p.appliedUpgrades.length>0&&c.push({workspace:s.workspaceName,upgrades:p.appliedUpgrades}),p.alreadyUpToDate.length>0&&d.push({workspace:s.workspaceName,upToDate:p.alreadyUpToDate})})})),c.length>0){e.logger.info(""),e.logger.info(ct.green("Successfully upgraded generators:"));for(let{workspace:s,upgrades:u}of c){let f=new Map;for(let p of u){let _=f.get(p.groupName)??[];_.push(p),f.set(p.groupName,_)}for(let[p,_]of f){let h=s!=null?`[${s}] `:"";e.logger.info(ct.green(`${h}Group ${p}:`));for(let y of _){e.logger.info(ct.green(` - ${y.generatorName}: ${ct.dim(y.previousVersion)} \u2192 ${y.newVersion}`)),y.migrationsApplied!=null&&y.migrationsApplied>0&&e.logger.info(ct.dim(` Applied ${y.migrationsApplied} migration(s): ${y.migrationVersions?.join(", ")??""}`));let b=PoS(OU(y.generatorName));b!=null&&e.logger.info(ct.dim(` Changelog: ${b}`))}}}}if(d.length>0){e.logger.info(""),e.logger.info(ct.dim("Generators already on latest version:"));for(let{workspace:s,upToDate:u}of d){let f=new Map;for(let p of u){let _=f.get(p.groupName)??[];_.push(p),f.set(p.groupName,_)}for(let[p,_]of f){let h=s!=null?`[${s}] `:"";e.logger.info(ct.dim(`${h}Group ${p}:`));for(let y of _)e.logger.info(ct.dim(` - ${y.generatorName}: ${y.version} (latest)`))}}}if(c.length===0&&d.length===0){let s=r!=null?` for group ${r}`:t!=null?` for generator ${t}`:"";e.logger.info(""),e.logger.info(ct.gray(`No generators found${s}.`))}if(o.length>0){e.logger.info(""),e.logger.info(ct.yellow("Major version upgrades available:"));for(let s of o){e.logger.info(ct.yellow(` - ${s.generatorName}: ${s.currentVersion} \u2192 ${s.latestMajorVersion}`));let u=t!=null?`fern generator upgrade --generator ${s.generatorName} --include-major`:"fern generator upgrade --include-major";e.logger.info(ct.yellow(` Run: ${u}`));let f=PoS(OU(s.generatorName));f!=null&&e.logger.info(ct.yellow(` Changelog: ${f}`))}}}function SoS(e,t){e.command("organization",!1,r=>r.option("output",{string:!0,alias:"o",description:"The location to output the organization name as a text file, defaults to standard out."}),async r=>{await t.instrumentPostHogEvent({command:"fern organization",properties:{outputLocation:r.output}}),await goS({project:await jm(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),context:t,outputLocation:r.output})})}function MoS(e,t){e.command("generator","Operate on the generators within your Fern configuration",r=>{r.command("list",!1,i=>i.option("output",{string:!0,alias:"o",description:"The location to output the list as a text file, defaults to standard out."}).option("generators",{string:!0,type:"array",description:"The type of generator to include in the list, ex: `fern-typescript-node-sdk`. If omitted, all generators will be listed."}).option("groups",{type:"array",string:!0,description:"The groups to include generators from, if group is not specified, the all generators of the specified type will be listed."}).option("apis",{type:"array",string:!0,description:"The APIs to list the generators for. If not specified, the generator will be upgraded for all APIs."}).option("api-fallback",{string:!0,description:"The APIs to list the generators for. If not specified, the generator will be upgraded for all APIs."}).option("include-mode",{choices:Object.values(a9a),type:"array",description:"The generator output modes to include within the outputted list."}).option("exclude-mode",{choices:Object.values(a9a),type:"array",description:"The generator output modes to exclude within the outputted list."}),async i=>{await t.instrumentPostHogEvent({command:"fern generator list",properties:{outputLocation:i.output}}),await yoS({project:await jm(t,{commandLineApiWorkspace:void 0,defaultToAllApiWorkspaces:!0}),generatorFilter:i.generators?new Set(i.generators):void 0,groupFilter:i.groups?new Set(i.groups):void 0,apiFilter:i.apis?new Set(i.apis):void 0,apiKeyFallback:i.apiFallback,cliContext:t,outputLocation:i.output,includedModes:i["include-mode"]?new Set(i["include-mode"]):void 0,excludedModes:i["exclude-mode"]?new Set(i["exclude-mode"]):void 0})}).command("upgrade",`Upgrades the specified generator in ${xM} to the latest stable version.`,i=>i.option("generator",{string:!0,description:"The type of generator to upgrade, ex: `fern-typescript-node-sdk`."}).option("group",{string:!0,description:"The group in which the generator is located, if group is not specified, the all generators of the specified type will be upgraded."}).option("api",{string:!0,description:"The API to upgrade the generator for. If not specified, the generator will be upgraded for all APIs."}).option("yes",{alias:"y",boolean:!0,default:!1,description:"Automatically answer yes to any prompts that may appear during the upgrade process."}).option("include-major",{boolean:!0,default:!1,description:"Whether or not to include major versions within the upgrade. Defaults to false, meaning major versions will be skipped."}).option("channel",{demandOption:!1,choices:Object.values(woS.FernRegistry.generators.ReleaseType)}).option("list",{demandOption:!1,boolean:!0,default:!1,description:"When specified, a list of available upgrades will be displayed, but no upgrade will be taken."}),async i=>{await t.instrumentPostHogEvent({command:"fern generator upgrade",properties:{generator:i.generator,version:i.version,api:i.api,group:i.group,includeMajor:i.includeMajor,rc:i.rc}});let n=await jm(t,{commandLineApiWorkspace:i.api,defaultToAllApiWorkspaces:!0});if(i.list){t.suppressUpgradeMessage();let a=await C_c({cliContext:t,project:n,generatorFilter:i.generator,groupFilter:i.group,includeMajor:i.includeMajor,channel:i.channel}),o=await fzp({generatorUpgradeInfo:a,header:`Generator Upgrades
|
|
2464
2464
|
`,includeBoxen:!0});o!=null&&t.logger.info(o)}else await joS({cliContext:t,generator:i.generator,group:i.group,project:await jm(t,{commandLineApiWorkspace:i.api,defaultToAllApiWorkspaces:!0}),includeMajor:i.includeMajor,channel:i.channel})}).command("get",!1,i=>i.option("output",{string:!0,alias:"o",description:"The location to output the list as a text file, defaults to standard out."}).option("generator",{string:!0,demandOption:!0,description:"The name of the generator to get, ex: `fern-typescript-node-sdk`."}).option("group",{string:!0,demandOption:!0,description:"The group in which the generator is located."}).option("api",{string:!0,description:"The API in which the generator is located."}).option("version",{boolean:!0,default:!1,description:"Get the version of the specified generator."}).option("language",{boolean:!0,default:!1,description:"Get the language of the specified generator."}).option("repository",{boolean:!0,default:!1,description:"Get repository for the generator invocation, if one is specified."}),async i=>{await t.instrumentPostHogEvent({command:"fern generator get",properties:{generator:i.generator,version:i.version,api:i.api,group:i.group,includeMajor:i.includeMajor}});let n=await boS({cliContext:t,generatorFilter:i.generator,groupFilter:i.group,apiFilter:i.api,project:await jm(t,{commandLineApiWorkspace:i.api,defaultToAllApiWorkspaces:!0})});if(n==null){let o=i.api?` for API ${i.api}`:"";t.failAndThrow(`Generator ${i.generator}, in group ${i.group}${o} was not found.`)}let a={};if(i.version&&(a.version=n.version,i.output==null)){process.stdout.write(n.version);return}if(i.language)if(n.language!=null){if(a.language=n.language,i.output==null){process.stdout.write(n.language);return}}else t.logger.warn(`Language information is not available for generator ${n.name} in group ${i.group}`);if(i.repository){let o=n.outputMode.type==="github"?n.outputMode.repo:n.outputMode.type==="githubV2"?n.outputMode.githubV2.repo:void 0;if(o!=null){if(a.repository=o,i.output==null){process.stdout.write(a.repository);return}}else t.logger.warn(`Repository information is not available for generator ${n.name} in group ${i.group}`)}if(i.output)try{await(0,EoS.writeFile)(i.output,JSON.stringify(a,null,2))}catch(o){t.failAndThrow(`Could not write file to the specified location: ${i.output}`,o)}})})}var DoS=require("fs/promises");async function BoS({project:{apiWorkspaces:e},generatorName:t,groupName:r,cliContext:i}){await Promise.all(e.map(async n=>{await i.runTaskForWorkspace(n,async a=>{let o=await h_a({absolutePathToWorkspace:n.absoluteFilePath,context:a})??{},c=await t2c({generatorName:t,generatorsConfiguration:o,groupName:r,context:a,cliVersion:i.environment.packageVersion}),d=n.generatorsConfiguration?.absolutePathToConfiguration??await _ki({absolutePathToWorkspace:n.absoluteFilePath});d!=null&&(await(0,DoS.writeFile)(d,`# yaml-language-server: $schema=https://schema.buildwithfern.dev/generators-yml.json
|
|
2465
|
-
`+qi.dump(c)),a.logger.info(ct.green(`Added ${t} generator`)))})}))}var CoS=require("fs/promises"),qoS=se(PX(),1);async function ToS({context:e,from:t,to:r,fromVersion:i,generatorVersions:n}){let a=new vro,o=aN5(await a.check({from:await IoS({context:e,filepath:t,flagName:"from"}),to:await IoS({context:e,filepath:r,flagName:"to"})})),c=sN5(e,n),{bump:d,errors:s}=oN5(o,c);if(i==null)return{bump:d??"patch",errors:s};if(d==="no_change")return{bump:"no_change",nextVersion:i,errors:s};let u=d??"patch",f=qoS.default.inc(i,u);if(!f)throw e.failWithoutThrowing(`Invalid current version: ${i}`),new yS;return{bump:u,nextVersion:f,errors:s}}async function IoS({context:e,filepath:t,flagName:r}){let i=mr.of(xo(OO(),t));if(!await ni(i,"file"))throw e.failWithoutThrowing(`File not found: ${i}`),new yS;let n=await(0,CoS.readFile)(i,"utf-8"),a=sa.IntermediateRepresentation.parse(JSON.parse(n));if(!a.ok)throw e.failWithoutThrowing(`Invalid --${r}; expected a filepath containing a valid IR`),new yS;return a.value}function aN5(e){return{bump:e.bump,errors:e.errors.map(t=>t.message)}}function oN5(e,t){return{bump:uN5(e.bump,t.bump),errors:[...e.errors,...t.errors]}}function uN5(e,t){if(!(e===void 0&&t===void 0))return e==="no_change"&&(t===void 0||t==="no_change")||t==="no_change"&&(e===void 0||e==="no_change")?"no_change":e===void 0?t:t===void 0?e:e==="no_change"?t:t==="no_change"?e:e==="major"||t==="major"?"major":e==="minor"||t==="minor"?"minor":"patch"}function sN5(e,t){if(t===void 0)return{bump:void 0,errors:[]};let{from:r,to:i}=t;try{let n=cN5(ZAc(r,i)),a=[];return n==="major"&&a.push("Generator version changed by major version."),{bump:n,errors:a}}catch(n){throw e.failWithoutThrowing(`Error diffing generator versions ${r} and ${i}: ${n}`),new yS}}function cN5(e){if(e!==null)switch(e){case"major":case"minor":case"patch":return e;default:return}}bE();var JpS=se(bzp(),1),YpS=se(mhc(),1),tyc=require("fs/promises"),XpS=se(require("http"),1),ZpS=se(require("path"),1);var BfS=require("events"),Ehc=se(require("fs"),1),Bra=se(require("path"),1);var dfS=se(require("os"),1),pfS=300,Wbn=20,P8o=1e7,_fS=dfS.default.platform();var O35=_fS==="darwin",zNp=_fS==="win32",xbn=O35||zNp,hfS=3e3,yfS=2e4,NNp=1250;var XLi;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(XLi||(XLi={}));var Dra;(function(e){e.CHANGE="change",e.RENAME="rename"})(Dra||(Dra={}));var j8o;(function(e){e.CHANGE="change",e.ERROR="error"})(j8o||(j8o={}));var Rf;(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"})(Rf||(Rf={}));var cX;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(cX||(cX={}));var m35=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),o,c,d=0,s=0,u=()=>{let g=Date.now(),A=g-d,j=g-s,M=A>=t||j>=a;return[g,M]},f=g=>{if(s=g,!o)return;let A=o;o=void 0,e.apply(void 0,A)},p=()=>{O(0)},_=()=>{c&&(p(),f(Date.now()))},h=g=>{if(s=g,i)return f(g)},y=g=>{if(n&&o)return f(g);o=void 0},b=()=>{c=void 0;let[g,A]=u();return A?y(g):v(g)},v=g=>{let A=g-d,j=g-s,M=t-A,w=a-j,E=Math.min(M,w);return O(E)},O=g=>{c&&clearTimeout(c),!(g<=0)&&(c=setTimeout(b,g))},m=(...g)=>{let[A,j]=u(),M=!!c;if(o=g,d=A,(j||!c)&&O(t),j)return M?f(A):h(A)};return m.cancel=p,m.flush=_,m},Ahc=m35;var LNp=se(require("fs"),1),jhc=se(require("path"),1);var jA=se(require("fs"),1),xx=require("util");var sJi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},ZLi=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var FNp=se(require("process"),1),bfS=FNp.default.getuid?!FNp.default.getuid():!1,vfS=1e4,xOe=()=>{};var w8o={isChangeErrorOk:e=>{if(!w8o.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!bfS&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!w8o.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(!w8o.isNodeError(e))throw e;if(!w8o.isChangeErrorOk(e))throw e}},TT=w8o;var QNp=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=vfS,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(i),i=()=>t(r);this.add(i)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},gfS=new QNp;var cJi=(e,t)=>function(i){return function n(...a){return gfS.schedule().then(o=>{let c=s=>(o(),s),d=s=>{if(o(),Date.now()>=i)throw s;if(t(s)){let u=Math.round(100*Math.random());return new Promise(p=>setTimeout(p,u)).then(()=>n.apply(void 0,a))}throw s};return e.apply(void 0,a).then(c,d)})}},lJi=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(o){if(Date.now()>i)throw o;if(t(o))return n.apply(void 0,a);throw o}}};var A35={attempt:{chmod:sJi((0,xx.promisify)(jA.default.chmod),TT.onChangeError),chown:sJi((0,xx.promisify)(jA.default.chown),TT.onChangeError),close:sJi((0,xx.promisify)(jA.default.close),xOe),fsync:sJi((0,xx.promisify)(jA.default.fsync),xOe),mkdir:sJi((0,xx.promisify)(jA.default.mkdir),xOe),realpath:sJi((0,xx.promisify)(jA.default.realpath),xOe),stat:sJi((0,xx.promisify)(jA.default.stat),xOe),unlink:sJi((0,xx.promisify)(jA.default.unlink),xOe),chmodSync:ZLi(jA.default.chmodSync,TT.onChangeError),chownSync:ZLi(jA.default.chownSync,TT.onChangeError),closeSync:ZLi(jA.default.closeSync,xOe),existsSync:ZLi(jA.default.existsSync,xOe),fsyncSync:ZLi(jA.default.fsync,xOe),mkdirSync:ZLi(jA.default.mkdirSync,xOe),realpathSync:ZLi(jA.default.realpathSync,xOe),statSync:ZLi(jA.default.statSync,xOe),unlinkSync:ZLi(jA.default.unlinkSync,xOe)},retry:{close:cJi((0,xx.promisify)(jA.default.close),TT.isRetriableError),fsync:cJi((0,xx.promisify)(jA.default.fsync),TT.isRetriableError),open:cJi((0,xx.promisify)(jA.default.open),TT.isRetriableError),readFile:cJi((0,xx.promisify)(jA.default.readFile),TT.isRetriableError),rename:cJi((0,xx.promisify)(jA.default.rename),TT.isRetriableError),stat:cJi((0,xx.promisify)(jA.default.stat),TT.isRetriableError),write:cJi((0,xx.promisify)(jA.default.write),TT.isRetriableError),writeFile:cJi((0,xx.promisify)(jA.default.writeFile),TT.isRetriableError),closeSync:lJi(jA.default.closeSync,TT.isRetriableError),fsyncSync:lJi(jA.default.fsyncSync,TT.isRetriableError),openSync:lJi(jA.default.openSync,TT.isRetriableError),readFileSync:lJi(jA.default.readFileSync,TT.isRetriableError),renameSync:lJi(jA.default.renameSync,TT.isRetriableError),statSync:lJi(jA.default.statSync,TT.isRetriableError),writeSync:lJi(jA.default.writeSync,TT.isRetriableError),writeFileSync:lJi(jA.default.writeFileSync,TT.isRetriableError)}},OfS=A35;var Phc=se(require("fs"),1),E8o=se(require("path"),1);var UNp=()=>{};var P35=()=>{let e=UNp,t=UNp,r=!1,i=!1;return{promise:new Promise((d,s)=>{e=u=>(r=!0,d(u)),t=u=>(i=!0,s(u))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}},mfS=P35;var j35=()=>{let{promise:e,resolve:t,isPending:r}=mfS(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return n(),queueMicrotask(a),{promise:e,isPending:r,increment:n,decrement:a}},AfS=j35;var PfS={then:e=>{e()}};var jfS=e=>Array.isArray(e)?e:[e],wfS=e=>typeof e=="function";var w35=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=jfS(a).map(Q=>wfS(Q)?Q:U=>Q.test(U)),c=Q=>o.some(U=>U(Q)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),u=[],f=new Set,p={},_=[],h=new Set,y={},b=[],v=new Set,O={},m={},g=new Set,A={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},j={directories:u,directoriesNames:f,directoriesNamesToPaths:p,files:_,filesNames:h,filesNamesToPaths:y,symlinks:b,symlinksNames:v,symlinksNamesToPaths:O,map:m},{promise:M,increment:w,decrement:E}=AfS(),B=0,q=(Q,U,ce,ae)=>{g.has(U)||B>=n||(B+=1,Q.directories.push(U),Q.directoriesNames.add(ce),u.push(U),f.add(ce),p.propertyIsEnumerable(ce)||(p[ce]=[]),p[ce].push(U),g.add(U),!(ae>=i)&&(B>=n||W(U,ae+1)))},R=(Q,U,ce)=>{g.has(U)||B>=n||(B+=1,Q.files.push(U),Q.filesNames.add(ce),_.push(U),h.add(ce),y.propertyIsEnumerable(ce)||(y[ce]=[]),y[ce].push(U),g.add(U))},T=(Q,U,ce,ae)=>{g.has(U)||B>=n||(B+=1,Q.symlinks.push(U),Q.symlinksNames.add(ce),b.push(U),v.add(ce),O.propertyIsEnumerable(ce)||(O[ce]=[]),O[ce].push(U),g.add(U),r&&(ae>=i||B>=n||Oe(U,ae+1)))},K=(Q,U,ce,ae,de)=>{d.aborted||c(U)||(ae.isDirectory()?q(Q,U,ce,de):ae.isFile()?R(Q,U,ce):ae.isSymbolicLink()&&T(Q,U,ce,de))},H=(Q,U,ce,ae)=>{if(d.aborted)return;let de=U===E8o.default.sep?"":E8o.default.sep,ve=ce.name,re=`${U}${de}${ve}`;c(re)||(ce.isDirectory()?q(Q,re,ve,ae):ce.isFile()?R(Q,re,ve):ce.isSymbolicLink()&&T(Q,re,ve,ae))},z=(Q,U,ce,ae)=>{for(let de=0,ve=ce.length;de<ve;de++)H(Q,U,ce[de],ae)},W=(Q,U)=>{d.aborted||U>i||B>=n||(w(),Phc.default.readdir(Q,{withFileTypes:!0},(ce,ae)=>{if(ce||d.aborted||!ae.length)return E();(s(ae)||PfS).then(()=>{let ve=m[Q]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};z(ve,Q,ae,U),E()})}))},Oe=(Q,U)=>{w(),Phc.default.realpath(Q,(ce,ae)=>{if(ce||d.aborted)return E();Phc.default.stat(ae,(de,ve)=>{if(de||d.aborted)return E();let re=E8o.default.basename(ae),X=m[Q]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};K(X,ae,re,ve,U),E()})})};return(async(Q,U=1)=>(Q=E8o.default.normalize(Q),g.add(Q),W(Q,U),await M,d.aborted?A:j))(e)},EfS=w35;var kLi={lang:{debounce:Ahc,attempt:e=>{try{return e()}catch(t){return kLi.lang.castError(t)}},castArray:e=>kLi.lang.isArray(e)?e:[e],castError:e=>kLi.lang.isError(e)?e:kLi.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(kLi.lang.isNaN(e))return kLi.lang.isNaN(t);if(kLi.lang.isPrimitive(e)||kLi.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(jhc.default.sep).length-1),getRealPath:(e,t)=>{try{return t?LNp.default.realpathSync.native(e):LNp.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===jhc.default.sep&&t.length-e.length>jhc.default.sep.length,poll:(e,t=yfS)=>OfS.retry.stat(t)(e,{bigint:!0}).catch(kLi.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let o=a[e];return[o.directories,o.files]}else{let o=await EfS(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},Mh=kLi;var whc=se(require("path"),1);var VNp=class{constructor(t,r,i){this.base=i,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||Mh.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=pfS){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(c,d)=>{let s=this.options.ignoreInitial?[]:c,u=await this.eventsPopulate([...d]),f=this.eventsDeduplicate([...s,...u]);this.onTargetEvents(f)},o=Mh.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(c,d="",s=!1)=>{s?await this.eventsPopulate([d],i,!0):n.add(d),r.then(o)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,o]=n,c=r[o];return a===c||a===Rf.CHANGE&&c===Rf.ADD||(r[o]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async o=>{r.push([o,n]),o===Rf.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===Rf.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??Wbn:Math.min(1,this.options.depth??Wbn),o=this.options.limit??P8o,[c,d]=await Mh.fs.readdir(r,this.options.ignore,a,o,this.watcher._closeSignal),s=[...c,...d];return await Promise.all(s.map(u=>{if(!this.watcher.isIgnored(u,this.options.ignore)&&!t.includes(u))return this.eventsPopulate([u],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())Mh.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Rf.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!xbn&&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(Rf.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Rf.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(whc.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Rf.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(whc.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(Rf.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===Rf.ADD?this.onTargetAdd(i):r===Rf.ADD_DIR?this.onTargetAddDir(i):r===Rf.CHANGE?this.onTargetChange(i):r===Rf.UNLINK?this.onTargetUnlink(i):r===Rf.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=Dra.CHANGE,r){if(this.watcher.isClosed())return;let i=whc.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){zNp&&t.code==="EPERM"?this.onWatcherChange(Dra.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(j8o.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(j8o.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(Dra.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&xbn&&this.options.native!==!1?this.options.depth??Wbn:Math.min(1,this.options.depth??Wbn),i=this.options.limit??P8o,[n,a]=await Mh.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),o=[this.folderPath,...n,...a];await Promise.all(o.map(c=>{if(!this.watcher._poller.stats.has(c)&&!this.watcher.isIgnored(c,this.options.ignore))return this.onWatcherEvent(Dra.CHANGE,c,t)}))}}},SfS=VNp;var lX={interval:100,intervalId:void 0,fns:new Map,init:()=>{lX.intervalId||(lX.intervalId=setInterval(lX.resolve,lX.interval))},reset:()=>{lX.intervalId&&(clearInterval(lX.intervalId),delete lX.intervalId)},add:(e,t)=>{lX.fns.set(e,Date.now()+t),lX.init()},remove:e=>{lX.fns.delete(e)},resolve:()=>{if(!lX.fns.size)return lX.reset();let e=Date.now();for(let[t,r]of lX.fns)r>=e||(lX.remove(t),t())}},S8o=lX;var M8o=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=NNp){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{let f=this._watcher._poller.paths.find(i||-1,p=>p!==n);if(f&&f!==n){if(Mh.fs.getRealPath(n,!0)===f)return;this._watcher.event(a.rename,f,n)}else this._watcher.event(a.add,n)};if(!i)return c();let d=()=>{o.add.delete(i),S8o.remove(s)},s=()=>{d(),c()};S8o.add(s,r);let u=()=>{let f=o.unlink.get(i);if(!f)return;d();let p=f();n===p?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,p,n)};o.add.set(i,u),u()}getLockUnlink(t,r=NNp){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{this._watcher.event(a.unlink,n)};if(!i)return c();let d=()=>{o.unlink.delete(i),S8o.remove(s)},s=()=>{d(),c()};S8o.add(s,r);let u=()=>(d(),n);o.unlink.set(i,u),o.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,Rf.ADD,XLi.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,Rf.ADD_DIR,XLi.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,Rf.UNLINK,XLi.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,Rf.UNLINK_DIR,XLi.DIR);return this.getLockUnlink({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};M8o.DIR_EVENTS={add:Rf.ADD_DIR,rename:Rf.RENAME_DIR,unlink:Rf.UNLINK_DIR};M8o.FILE_EVENTS={add:Rf.ADD,change:Rf.CHANGE,rename:Rf.RENAME,unlink:Rf.UNLINK};var MfS=M8o;var WNp=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Mh.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(Mh.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(Mh.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(Mh.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return Mh.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);Mh.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},xNp=WNp;var GNp=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}},DfS=GNp;var HNp=class{constructor(){this.inos={},this.paths=new xNp,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await Mh.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new DfS(i)}reset(){this.inos={},this.paths=new xNp,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,Rf.ADD,n),[Rf.ADD];if(n.isDirectory())return this.updateIno(t,Rf.ADD_DIR,n),[Rf.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,Rf.UNLINK,i),[Rf.UNLINK];if(i.isDirectory())return this.updateIno(t,Rf.UNLINK_DIR,i),[Rf.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,Rf.CHANGE,n),[Rf.CHANGE]);if(n.isDirectory())return this.updateIno(t,Rf.UNLINK,i),this.updateIno(t,Rf.ADD_DIR,n),[Rf.UNLINK,Rf.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,Rf.UNLINK_DIR,i),this.updateIno(t,Rf.ADD,n),[Rf.UNLINK_DIR,Rf.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,Rf.UNLINK_DIR,i),this.updateIno(t,Rf.ADD_DIR,n),[Rf.UNLINK_DIR,Rf.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?XLi.FILE:XLi.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},KNp=HNp;var $Np=class e extends BfS.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(cX.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(cX.CLOSE,n)),this._readyWait=new Promise(n=>this.on(cX.READY,n)),this._locker=new MfS(this),this._roots=new Set,this._poller=new KNp,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(Mh.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(cX.CLOSE))}error(t){if(this.isClosed())return!1;let r=Mh.lang.castError(t);return this.emit(cX.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(cX.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(cX.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&Mh.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&Mh.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)Mh.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new SfS(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=Mh.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(c=>c.handler===i&&(!c.filePath||c.filePath===n)&&c.options.ignore===r.ignore&&!!c.options.native==!!r.native&&(!r.recursive||c.options.recursive)))return!0;let o=Bra.default.dirname(t);for(let c=1;c<1/0;c++){if(this._watchers[o]?.find(u=>(c===1||u.options.recursive&&c<=(u.options.depth??Wbn))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&xbn&&u.options.native!==!1)))return!0;if(!xbn)break;let s=Bra.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=Mh.lang.uniq(t).sort();let o;for(let c of t)if(!this.isIgnored(c,r.ignore)&&!this.watcherExists(c,r,i,n))try{let d=!r.recursive||xbn&&r.native!==!1?r:{...r,recursive:!1},u={watcher:Ehc.default.watch(c,d),handler:i,options:r,folderPath:c,filePath:n},f=o=await this.watcherAdd(u,a);if(this._roots.has(n||c)){let _={...r,ignoreInitial:!0,recursive:!1},h=Bra.default.dirname(c),y=c;await this.watchDirectories([h],_,i,y,f)}}catch(d){this.error(d)}return o}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||xbn&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??Wbn,c=r.limit??P8o,[d]=await Mh.fs.readdir(t,r.ignore,o,c,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,i,n,a);if(d.length){let u=Mh.fs.getDepth(t);for(let f of d){let p=Mh.fs.getDepth(f),_=Math.max(0,o-(p-u)),h={...r,depth:_};await this.watchDirectories([f],h,i,n,a||s)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(s,u)=>{u===t&&(d(),i())},o=new e(a),c=()=>{this._subwatchers.add(n),this.on(cX.CLOSE,d),o.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(cX.CLOSE,d),o.close()};return c()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=Bra.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new KNp,o=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,o(),i())})}async watchPolling(t,r,i){if(this.isClosed())return Mh.lang.noop;if(this.pollerExists(t,r))return Mh.lang.noop;let n={...r,interval:r.pollingInterval??hfS},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(cX.CLOSE,c),Ehc.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(cX.CLOSE,c),Ehc.default.unwatchFile(t,i)};return Mh.lang.attempt(o),()=>Mh.lang.attempt(c)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=Mh.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,d)=>d===o||!Mh.fs.isSubPath(a,c))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=Bra.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await Mh.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=Bra.default.dirname(t);return(await Mh.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=Mh.lang.noop){if(Mh.lang.isFunction(t))return this.watch([],{},t);if(Mh.lang.isUndefined(t))return this.watch([],r,i);if(Mh.lang.isFunction(r))return this.watch(t,{},r);if(Mh.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=Mh.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==Mh.lang.noop&&this.on(cX.ALL,i),r.readdirMap=void 0,this.ready())}},Shc=$Np;ufc();var A9a=require("fs/promises"),IfS=require("os"),CfS=se(require("path"),1),E35=".fern",S35="logs";function M35(){return"cli@3.57.1"}var D8o=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=ot(mr.of((0,IfS.homedir)()),Pe.of(E35)),r=ot(t,Pe.of(S35));await ni(r)||await(0,A9a.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=ot(r,Pe.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${CfS.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
|
|
2465
|
+
`+qi.dump(c)),a.logger.info(ct.green(`Added ${t} generator`)))})}))}var CoS=require("fs/promises"),qoS=se(PX(),1);async function ToS({context:e,from:t,to:r,fromVersion:i,generatorVersions:n}){let a=new vro,o=aN5(await a.check({from:await IoS({context:e,filepath:t,flagName:"from"}),to:await IoS({context:e,filepath:r,flagName:"to"})})),c=sN5(e,n),{bump:d,errors:s}=oN5(o,c);if(i==null)return{bump:d??"patch",errors:s};if(d==="no_change")return{bump:"no_change",nextVersion:i,errors:s};let u=d??"patch",f=qoS.default.inc(i,u);if(!f)throw e.failWithoutThrowing(`Invalid current version: ${i}`),new yS;return{bump:u,nextVersion:f,errors:s}}async function IoS({context:e,filepath:t,flagName:r}){let i=mr.of(xo(OO(),t));if(!await ni(i,"file"))throw e.failWithoutThrowing(`File not found: ${i}`),new yS;let n=await(0,CoS.readFile)(i,"utf-8"),a=sa.IntermediateRepresentation.parse(JSON.parse(n));if(!a.ok)throw e.failWithoutThrowing(`Invalid --${r}; expected a filepath containing a valid IR`),new yS;return a.value}function aN5(e){return{bump:e.bump,errors:e.errors.map(t=>t.message)}}function oN5(e,t){return{bump:uN5(e.bump,t.bump),errors:[...e.errors,...t.errors]}}function uN5(e,t){if(!(e===void 0&&t===void 0))return e==="no_change"&&(t===void 0||t==="no_change")||t==="no_change"&&(e===void 0||e==="no_change")?"no_change":e===void 0?t:t===void 0?e:e==="no_change"?t:t==="no_change"?e:e==="major"||t==="major"?"major":e==="minor"||t==="minor"?"minor":"patch"}function sN5(e,t){if(t===void 0)return{bump:void 0,errors:[]};let{from:r,to:i}=t;try{let n=cN5(ZAc(r,i)),a=[];return n==="major"&&a.push("Generator version changed by major version."),{bump:n,errors:a}}catch(n){throw e.failWithoutThrowing(`Error diffing generator versions ${r} and ${i}: ${n}`),new yS}}function cN5(e){if(e!==null)switch(e){case"major":case"minor":case"patch":return e;default:return}}bE();var JpS=se(bzp(),1),YpS=se(mhc(),1),tyc=require("fs/promises"),XpS=se(require("http"),1),ZpS=se(require("path"),1);var BfS=require("events"),Ehc=se(require("fs"),1),Bra=se(require("path"),1);var dfS=se(require("os"),1),pfS=300,Wbn=20,P8o=1e7,_fS=dfS.default.platform();var O35=_fS==="darwin",zNp=_fS==="win32",xbn=O35||zNp,hfS=3e3,yfS=2e4,NNp=1250;var XLi;(function(e){e[e.DIR=1]="DIR",e[e.FILE=2]="FILE"})(XLi||(XLi={}));var Dra;(function(e){e.CHANGE="change",e.RENAME="rename"})(Dra||(Dra={}));var j8o;(function(e){e.CHANGE="change",e.ERROR="error"})(j8o||(j8o={}));var Rf;(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"})(Rf||(Rf={}));var cX;(function(e){e.ALL="all",e.CLOSE="close",e.ERROR="error",e.READY="ready"})(cX||(cX={}));var m35=(e,t=1,r)=>{t=Math.max(1,t);let i=r?.leading??!1,n=r?.trailing??!0,a=Math.max(r?.maxWait??1/0,t),o,c,d=0,s=0,u=()=>{let g=Date.now(),A=g-d,j=g-s,M=A>=t||j>=a;return[g,M]},f=g=>{if(s=g,!o)return;let A=o;o=void 0,e.apply(void 0,A)},p=()=>{O(0)},_=()=>{c&&(p(),f(Date.now()))},h=g=>{if(s=g,i)return f(g)},y=g=>{if(n&&o)return f(g);o=void 0},b=()=>{c=void 0;let[g,A]=u();return A?y(g):v(g)},v=g=>{let A=g-d,j=g-s,M=t-A,w=a-j,E=Math.min(M,w);return O(E)},O=g=>{c&&clearTimeout(c),!(g<=0)&&(c=setTimeout(b,g))},m=(...g)=>{let[A,j]=u(),M=!!c;if(o=g,d=A,(j||!c)&&O(t),j)return M?f(A):h(A)};return m.cancel=p,m.flush=_,m},Ahc=m35;var LNp=se(require("fs"),1),jhc=se(require("path"),1);var jA=se(require("fs"),1),xx=require("util");var sJi=(e,t)=>function(...i){return e.apply(void 0,i).catch(t)},ZLi=(e,t)=>function(...i){try{return e.apply(void 0,i)}catch(n){return t(n)}};var FNp=se(require("process"),1),bfS=FNp.default.getuid?!FNp.default.getuid():!1,vfS=1e4,xOe=()=>{};var w8o={isChangeErrorOk:e=>{if(!w8o.isNodeError(e))return!1;let{code:t}=e;return t==="ENOSYS"||!bfS&&(t==="EINVAL"||t==="EPERM")},isNodeError:e=>e instanceof Error,isRetriableError:e=>{if(!w8o.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(!w8o.isNodeError(e))throw e;if(!w8o.isChangeErrorOk(e))throw e}},TT=w8o;var QNp=class{constructor(){this.interval=25,this.intervalId=void 0,this.limit=vfS,this.queueActive=new Set,this.queueWaiting=new Set,this.init=()=>{this.intervalId||(this.intervalId=setInterval(this.tick,this.interval))},this.reset=()=>{this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId)},this.add=t=>{this.queueWaiting.add(t),this.queueActive.size<this.limit/2?this.tick():this.init()},this.remove=t=>{this.queueWaiting.delete(t),this.queueActive.delete(t)},this.schedule=()=>new Promise(t=>{let r=()=>this.remove(i),i=()=>t(r);this.add(i)}),this.tick=()=>{if(!(this.queueActive.size>=this.limit)){if(!this.queueWaiting.size)return this.reset();for(let t of this.queueWaiting){if(this.queueActive.size>=this.limit)break;this.queueWaiting.delete(t),this.queueActive.add(t),t()}}}}},gfS=new QNp;var cJi=(e,t)=>function(i){return function n(...a){return gfS.schedule().then(o=>{let c=s=>(o(),s),d=s=>{if(o(),Date.now()>=i)throw s;if(t(s)){let u=Math.round(100*Math.random());return new Promise(p=>setTimeout(p,u)).then(()=>n.apply(void 0,a))}throw s};return e.apply(void 0,a).then(c,d)})}},lJi=(e,t)=>function(i){return function n(...a){try{return e.apply(void 0,a)}catch(o){if(Date.now()>i)throw o;if(t(o))return n.apply(void 0,a);throw o}}};var A35={attempt:{chmod:sJi((0,xx.promisify)(jA.default.chmod),TT.onChangeError),chown:sJi((0,xx.promisify)(jA.default.chown),TT.onChangeError),close:sJi((0,xx.promisify)(jA.default.close),xOe),fsync:sJi((0,xx.promisify)(jA.default.fsync),xOe),mkdir:sJi((0,xx.promisify)(jA.default.mkdir),xOe),realpath:sJi((0,xx.promisify)(jA.default.realpath),xOe),stat:sJi((0,xx.promisify)(jA.default.stat),xOe),unlink:sJi((0,xx.promisify)(jA.default.unlink),xOe),chmodSync:ZLi(jA.default.chmodSync,TT.onChangeError),chownSync:ZLi(jA.default.chownSync,TT.onChangeError),closeSync:ZLi(jA.default.closeSync,xOe),existsSync:ZLi(jA.default.existsSync,xOe),fsyncSync:ZLi(jA.default.fsync,xOe),mkdirSync:ZLi(jA.default.mkdirSync,xOe),realpathSync:ZLi(jA.default.realpathSync,xOe),statSync:ZLi(jA.default.statSync,xOe),unlinkSync:ZLi(jA.default.unlinkSync,xOe)},retry:{close:cJi((0,xx.promisify)(jA.default.close),TT.isRetriableError),fsync:cJi((0,xx.promisify)(jA.default.fsync),TT.isRetriableError),open:cJi((0,xx.promisify)(jA.default.open),TT.isRetriableError),readFile:cJi((0,xx.promisify)(jA.default.readFile),TT.isRetriableError),rename:cJi((0,xx.promisify)(jA.default.rename),TT.isRetriableError),stat:cJi((0,xx.promisify)(jA.default.stat),TT.isRetriableError),write:cJi((0,xx.promisify)(jA.default.write),TT.isRetriableError),writeFile:cJi((0,xx.promisify)(jA.default.writeFile),TT.isRetriableError),closeSync:lJi(jA.default.closeSync,TT.isRetriableError),fsyncSync:lJi(jA.default.fsyncSync,TT.isRetriableError),openSync:lJi(jA.default.openSync,TT.isRetriableError),readFileSync:lJi(jA.default.readFileSync,TT.isRetriableError),renameSync:lJi(jA.default.renameSync,TT.isRetriableError),statSync:lJi(jA.default.statSync,TT.isRetriableError),writeSync:lJi(jA.default.writeSync,TT.isRetriableError),writeFileSync:lJi(jA.default.writeFileSync,TT.isRetriableError)}},OfS=A35;var Phc=se(require("fs"),1),E8o=se(require("path"),1);var UNp=()=>{};var P35=()=>{let e=UNp,t=UNp,r=!1,i=!1;return{promise:new Promise((d,s)=>{e=u=>(r=!0,d(u)),t=u=>(i=!0,s(u))}),resolve:e,reject:t,isPending:()=>!r&&!i,isResolved:()=>r,isRejected:()=>i}},mfS=P35;var j35=()=>{let{promise:e,resolve:t,isPending:r}=mfS(),i=0,n=()=>{i+=1},a=()=>{i-=1,!i&&t()};return n(),queueMicrotask(a),{promise:e,isPending:r,increment:n,decrement:a}},AfS=j35;var PfS={then:e=>{e()}};var jfS=e=>Array.isArray(e)?e:[e],wfS=e=>typeof e=="function";var w35=(e,t)=>{let r=t?.followSymlinks??!1,i=t?.depth??1/0,n=t?.limit??1/0,a=t?.ignore??[],o=jfS(a).map(Q=>wfS(Q)?Q:U=>Q.test(U)),c=Q=>o.some(U=>U(Q)),d=t?.signal??{aborted:!1},s=t?.onDirents||(()=>{}),u=[],f=new Set,p={},_=[],h=new Set,y={},b=[],v=new Set,O={},m={},g=new Set,A={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{},map:{}},j={directories:u,directoriesNames:f,directoriesNamesToPaths:p,files:_,filesNames:h,filesNamesToPaths:y,symlinks:b,symlinksNames:v,symlinksNamesToPaths:O,map:m},{promise:M,increment:w,decrement:E}=AfS(),B=0,q=(Q,U,ce,ae)=>{g.has(U)||B>=n||(B+=1,Q.directories.push(U),Q.directoriesNames.add(ce),u.push(U),f.add(ce),p.propertyIsEnumerable(ce)||(p[ce]=[]),p[ce].push(U),g.add(U),!(ae>=i)&&(B>=n||W(U,ae+1)))},R=(Q,U,ce)=>{g.has(U)||B>=n||(B+=1,Q.files.push(U),Q.filesNames.add(ce),_.push(U),h.add(ce),y.propertyIsEnumerable(ce)||(y[ce]=[]),y[ce].push(U),g.add(U))},T=(Q,U,ce,ae)=>{g.has(U)||B>=n||(B+=1,Q.symlinks.push(U),Q.symlinksNames.add(ce),b.push(U),v.add(ce),O.propertyIsEnumerable(ce)||(O[ce]=[]),O[ce].push(U),g.add(U),r&&(ae>=i||B>=n||Oe(U,ae+1)))},K=(Q,U,ce,ae,de)=>{d.aborted||c(U)||(ae.isDirectory()?q(Q,U,ce,de):ae.isFile()?R(Q,U,ce):ae.isSymbolicLink()&&T(Q,U,ce,de))},H=(Q,U,ce,ae)=>{if(d.aborted)return;let de=U===E8o.default.sep?"":E8o.default.sep,ve=ce.name,re=`${U}${de}${ve}`;c(re)||(ce.isDirectory()?q(Q,re,ve,ae):ce.isFile()?R(Q,re,ve):ce.isSymbolicLink()&&T(Q,re,ve,ae))},z=(Q,U,ce,ae)=>{for(let de=0,ve=ce.length;de<ve;de++)H(Q,U,ce[de],ae)},W=(Q,U)=>{d.aborted||U>i||B>=n||(w(),Phc.default.readdir(Q,{withFileTypes:!0},(ce,ae)=>{if(ce||d.aborted||!ae.length)return E();(s(ae)||PfS).then(()=>{let ve=m[Q]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};z(ve,Q,ae,U),E()})}))},Oe=(Q,U)=>{w(),Phc.default.realpath(Q,(ce,ae)=>{if(ce||d.aborted)return E();Phc.default.stat(ae,(de,ve)=>{if(de||d.aborted)return E();let re=E8o.default.basename(ae),X=m[Q]={directories:[],directoriesNames:new Set,directoriesNamesToPaths:{},files:[],filesNames:new Set,filesNamesToPaths:{},symlinks:[],symlinksNames:new Set,symlinksNamesToPaths:{}};K(X,ae,re,ve,U),E()})})};return(async(Q,U=1)=>(Q=E8o.default.normalize(Q),g.add(Q),W(Q,U),await M,d.aborted?A:j))(e)},EfS=w35;var kLi={lang:{debounce:Ahc,attempt:e=>{try{return e()}catch(t){return kLi.lang.castError(t)}},castArray:e=>kLi.lang.isArray(e)?e:[e],castError:e=>kLi.lang.isError(e)?e:kLi.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(kLi.lang.isNaN(e))return kLi.lang.isNaN(t);if(kLi.lang.isPrimitive(e)||kLi.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(jhc.default.sep).length-1),getRealPath:(e,t)=>{try{return t?LNp.default.realpathSync.native(e):LNp.default.realpathSync(e)}catch{return}},isSubPath:(e,t)=>t.startsWith(e)&&t[e.length]===jhc.default.sep&&t.length-e.length>jhc.default.sep.length,poll:(e,t=yfS)=>OfS.retry.stat(t)(e,{bigint:!0}).catch(kLi.lang.noop),readdir:async(e,t,r=1/0,i=1/0,n,a)=>{if(a&&r===1&&e in a){let o=a[e];return[o.directories,o.files]}else{let o=await EfS(e,{depth:r,limit:i,ignore:t,signal:n});return[o.directories,o.files]}}}},Mh=kLi;var whc=se(require("path"),1);var VNp=class{constructor(t,r,i){this.base=i,this.watcher=t,this.handler=r.handler,this.fswatcher=r.watcher,this.options=r.options,this.folderPath=r.folderPath,this.filePath=r.filePath,this.handlerBatched=this.base?this.base.onWatcherEvent.bind(this.base):this._makeHandlerBatched(this.options.debounce)}_isSubRoot(t){return this.filePath?t===this.filePath:t===this.folderPath||Mh.fs.isSubPath(this.folderPath,t)}_makeHandlerBatched(t=pfS){return(()=>{let r=this.watcher._readyWait,i=[],n=new Set,a=async(c,d)=>{let s=this.options.ignoreInitial?[]:c,u=await this.eventsPopulate([...d]),f=this.eventsDeduplicate([...s,...u]);this.onTargetEvents(f)},o=Mh.lang.debounce(()=>{this.watcher.isClosed()||(r=a(i,n),i=[],n=new Set)},t);return async(c,d="",s=!1)=>{s?await this.eventsPopulate([d],i,!0):n.add(d),r.then(o)}})()}eventsDeduplicate(t){if(t.length<2)return t;let r={};return t.reduce((i,n)=>{let[a,o]=n,c=r[o];return a===c||a===Rf.CHANGE&&c===Rf.ADD||(r[o]=a,i.push(n)),i},[])}async eventsPopulate(t,r=[],i=!1){return await Promise.all(t.map(async n=>{let a=await this.watcher._poller.update(n,this.options.pollingTimeout);await Promise.all(a.map(async o=>{r.push([o,n]),o===Rf.ADD_DIR?await this.eventsPopulateAddDir(t,n,r,i):o===Rf.UNLINK_DIR&&await this.eventsPopulateUnlinkDir(t,n,r,i)}))})),r}async eventsPopulateAddDir(t,r,i=[],n=!1){if(n)return i;let a=this.options.recursive?this.options.depth??Wbn:Math.min(1,this.options.depth??Wbn),o=this.options.limit??P8o,[c,d]=await Mh.fs.readdir(r,this.options.ignore,a,o,this.watcher._closeSignal),s=[...c,...d];return await Promise.all(s.map(u=>{if(!this.watcher.isIgnored(u,this.options.ignore)&&!t.includes(u))return this.eventsPopulate([u],i,!0)})),i}async eventsPopulateUnlinkDir(t,r,i=[],n=!1){if(n)return i;for(let a of this.watcher._poller.stats.keys())Mh.fs.isSubPath(r,a)&&(t.includes(a)||await this.eventsPopulate([a],i,!0));return i}onTargetAdd(t){this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetAdd(t,this.options.renameTimeout):this.watcher.event(Rf.ADD,t))}onTargetAddDir(t){t!==this.folderPath&&this.options.recursive&&!xbn&&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(Rf.ADD_DIR,t))}onTargetChange(t){this._isSubRoot(t)&&this.watcher.event(Rf.CHANGE,t)}onTargetUnlink(t){this.watcher.watchersClose(whc.default.dirname(t),t,!1),this._isSubRoot(t)&&(this.options.renameDetection?this.watcher._locker.getLockTargetUnlink(t,this.options.renameTimeout):this.watcher.event(Rf.UNLINK,t))}onTargetUnlinkDir(t){this.watcher.watchersClose(whc.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(Rf.UNLINK_DIR,t))}onTargetEvent(t){let[r,i]=t;r===Rf.ADD?this.onTargetAdd(i):r===Rf.ADD_DIR?this.onTargetAddDir(i):r===Rf.CHANGE?this.onTargetChange(i):r===Rf.UNLINK?this.onTargetUnlink(i):r===Rf.UNLINK_DIR&&this.onTargetUnlinkDir(i)}onTargetEvents(t){for(let r of t)this.onTargetEvent(r)}onWatcherEvent(t,r,i=!1){return this.handlerBatched(t,r,i)}onWatcherChange(t=Dra.CHANGE,r){if(this.watcher.isClosed())return;let i=whc.default.resolve(this.folderPath,r||"");this.filePath&&i!==this.folderPath&&i!==this.filePath||this.watcher.isIgnored(i,this.options.ignore)||this.onWatcherEvent(t,i)}onWatcherError(t){zNp&&t.code==="EPERM"?this.onWatcherChange(Dra.CHANGE,""):this.watcher.error(t)}async init(){await this.initWatcherEvents(),await this.initInitialEvents()}async initWatcherEvents(){let t=this.onWatcherChange.bind(this);this.fswatcher.on(j8o.CHANGE,t);let r=this.onWatcherError.bind(this);this.fswatcher.on(j8o.ERROR,r)}async initInitialEvents(){let t=!this.watcher.isReady();if(this.filePath){if(this.watcher._poller.stats.has(this.filePath))return;await this.onWatcherEvent(Dra.CHANGE,this.filePath,t)}else{let r=this.options.recursive&&xbn&&this.options.native!==!1?this.options.depth??Wbn:Math.min(1,this.options.depth??Wbn),i=this.options.limit??P8o,[n,a]=await Mh.fs.readdir(this.folderPath,this.options.ignore,r,i,this.watcher._closeSignal,this.options.readdirMap),o=[this.folderPath,...n,...a];await Promise.all(o.map(c=>{if(!this.watcher._poller.stats.has(c)&&!this.watcher.isIgnored(c,this.options.ignore))return this.onWatcherEvent(Dra.CHANGE,c,t)}))}}},SfS=VNp;var lX={interval:100,intervalId:void 0,fns:new Map,init:()=>{lX.intervalId||(lX.intervalId=setInterval(lX.resolve,lX.interval))},reset:()=>{lX.intervalId&&(clearInterval(lX.intervalId),delete lX.intervalId)},add:(e,t)=>{lX.fns.set(e,Date.now()+t),lX.init()},remove:e=>{lX.fns.delete(e)},resolve:()=>{if(!lX.fns.size)return lX.reset();let e=Date.now();for(let[t,r]of lX.fns)r>=e||(lX.remove(t),t())}},S8o=lX;var M8o=class e{constructor(t){this._watcher=t,this.reset()}getLockAdd(t,r=NNp){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{let f=this._watcher._poller.paths.find(i||-1,p=>p!==n);if(f&&f!==n){if(Mh.fs.getRealPath(n,!0)===f)return;this._watcher.event(a.rename,f,n)}else this._watcher.event(a.add,n)};if(!i)return c();let d=()=>{o.add.delete(i),S8o.remove(s)},s=()=>{d(),c()};S8o.add(s,r);let u=()=>{let f=o.unlink.get(i);if(!f)return;d();let p=f();n===p?a.change&&this._watcher._poller.stats.has(n)&&this._watcher.event(a.change,n):this._watcher.event(a.rename,p,n)};o.add.set(i,u),u()}getLockUnlink(t,r=NNp){let{ino:i,targetPath:n,events:a,locks:o}=t,c=()=>{this._watcher.event(a.unlink,n)};if(!i)return c();let d=()=>{o.unlink.delete(i),S8o.remove(s)},s=()=>{d(),c()};S8o.add(s,r);let u=()=>(d(),n);o.unlink.set(i,u),o.add.get(i)?.()}getLockTargetAdd(t,r){let i=this._watcher._poller.getIno(t,Rf.ADD,XLi.FILE);return this.getLockAdd({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetAddDir(t,r){let i=this._watcher._poller.getIno(t,Rf.ADD_DIR,XLi.DIR);return this.getLockAdd({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}getLockTargetUnlink(t,r){let i=this._watcher._poller.getIno(t,Rf.UNLINK,XLi.FILE);return this.getLockUnlink({ino:i,targetPath:t,events:e.FILE_EVENTS,locks:this._locksFile},r)}getLockTargetUnlinkDir(t,r){let i=this._watcher._poller.getIno(t,Rf.UNLINK_DIR,XLi.DIR);return this.getLockUnlink({ino:i,targetPath:t,events:e.DIR_EVENTS,locks:this._locksDir},r)}reset(){this._locksAdd=new Map,this._locksAddDir=new Map,this._locksUnlink=new Map,this._locksUnlinkDir=new Map,this._locksDir={add:this._locksAddDir,unlink:this._locksUnlinkDir},this._locksFile={add:this._locksAdd,unlink:this._locksUnlink}}};M8o.DIR_EVENTS={add:Rf.ADD_DIR,rename:Rf.RENAME_DIR,unlink:Rf.UNLINK_DIR};M8o.FILE_EVENTS={add:Rf.ADD,change:Rf.CHANGE,rename:Rf.RENAME,unlink:Rf.UNLINK};var MfS=M8o;var WNp=class{constructor(){this.map=new Map}clear(){this.map.clear()}delete(t,r){if(Mh.lang.isUndefined(r))return this.map.delete(t);if(this.map.has(t)){let i=this.map.get(t);if(Mh.lang.isSet(i)){let n=i.delete(r);return i.size||this.map.delete(t),n}else if(i===r)return this.map.delete(t),!0}return!1}find(t,r){if(this.map.has(t)){let i=this.map.get(t);if(Mh.lang.isSet(i))return Array.from(i).find(r);if(r(i))return i}}get(t){return this.map.get(t)}has(t,r){if(Mh.lang.isUndefined(r))return this.map.has(t);if(this.map.has(t)){let i=this.map.get(t);return Mh.lang.isSet(i)?i.has(r):i===r}return!1}set(t,r){if(this.map.has(t)){let i=this.map.get(t);Mh.lang.isSet(i)?i.add(r):i!==r&&this.map.set(t,new Set([i,r]))}else this.map.set(t,r);return this}},xNp=WNp;var GNp=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}},DfS=GNp;var HNp=class{constructor(){this.inos={},this.paths=new xNp,this.stats=new Map}getIno(t,r,i){let n=this.inos[r];if(!n)return;let a=n[t];if(a&&!(i&&a[1]!==i))return a[0]}getStats(t){return this.stats.get(t)}async poll(t,r){let i=await Mh.fs.poll(t,r);if(!(!i||!(i.isFile()||i.isDirectory())))return new DfS(i)}reset(){this.inos={},this.paths=new xNp,this.stats=new Map}async update(t,r){let i=this.getStats(t),n=await this.poll(t,r);if(this.updateStats(t,n),!i&&n){if(n.isFile())return this.updateIno(t,Rf.ADD,n),[Rf.ADD];if(n.isDirectory())return this.updateIno(t,Rf.ADD_DIR,n),[Rf.ADD_DIR]}else if(i&&!n){if(i.isFile())return this.updateIno(t,Rf.UNLINK,i),[Rf.UNLINK];if(i.isDirectory())return this.updateIno(t,Rf.UNLINK_DIR,i),[Rf.UNLINK_DIR]}else if(i&&n){if(i.isFile()){if(n.isFile())return i.ino===n.ino&&!i.size&&!n.size?[]:(this.updateIno(t,Rf.CHANGE,n),[Rf.CHANGE]);if(n.isDirectory())return this.updateIno(t,Rf.UNLINK,i),this.updateIno(t,Rf.ADD_DIR,n),[Rf.UNLINK,Rf.ADD_DIR]}else if(i.isDirectory()){if(n.isFile())return this.updateIno(t,Rf.UNLINK_DIR,i),this.updateIno(t,Rf.ADD,n),[Rf.UNLINK_DIR,Rf.ADD];if(n.isDirectory())return i.ino===n.ino?[]:(this.updateIno(t,Rf.UNLINK_DIR,i),this.updateIno(t,Rf.ADD_DIR,n),[Rf.UNLINK_DIR,Rf.ADD_DIR])}}return[]}updateIno(t,r,i){let n=this.inos[r]=this.inos[r]||(this.inos[r]={}),a=i.isFile()?XLi.FILE:XLi.DIR;n[t]=[i.ino,a]}updateStats(t,r){if(r)this.paths.set(r.ino,t),this.stats.set(t,r);else{let i=this.stats.get(t)?.ino||-1;this.paths.delete(i,t),this.stats.delete(t)}}},KNp=HNp;var $Np=class e extends BfS.EventEmitter{constructor(t,r,i){super(),this._closed=!1,this._ready=!1,this._closeAborter=new AbortController,this._closeSignal=this._closeAborter.signal,this.on(cX.CLOSE,()=>this._closeAborter.abort()),this._closeWait=new Promise(n=>this.on(cX.CLOSE,n)),this._readyWait=new Promise(n=>this.on(cX.READY,n)),this._locker=new MfS(this),this._roots=new Set,this._poller=new KNp,this._pollers=new Set,this._subwatchers=new Set,this._watchers={},this._watchersLock=Promise.resolve(),this._watchersRestorable={},this.watch(t,r,i)}isClosed(){return this._closed}isIgnored(t,r){return!!r&&(Mh.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(cX.CLOSE))}error(t){if(this.isClosed())return!1;let r=Mh.lang.castError(t);return this.emit(cX.ERROR,r)}event(t,r,i){return this.isClosed()?!1:(this.emit(cX.ALL,t,r,i),this.emit(t,r,i))}ready(){return this.isClosed()||this.isReady()?!1:(this._ready=!0,this.emit(cX.READY))}pollerExists(t,r){for(let i of this._pollers)if(i.targetPath===t&&Mh.lang.isShallowEqual(i.options,r))return!0;return!1}subwatcherExists(t,r){for(let i of this._subwatchers)if(i.targetPath===t&&Mh.lang.isShallowEqual(i.options,r))return!0;return!1}watchersClose(t,r,i=!0){if(t){let n=this._watchers[t];if(n)for(let a of[...n])r&&a.filePath!==r||this.watcherClose(a);if(i)for(let a in this._watchers)Mh.fs.isSubPath(t,a)&&this.watchersClose(a,r,!1)}else for(let n in this._watchers)this.watchersClose(n,r,!1)}watchersLock(t){return this._watchersLock.then(()=>this._watchersLock=new Promise(async r=>{await t(),r()}))}watchersRestore(){delete this._watchersRestoreTimeout;let t=Object.entries(this._watchersRestorable);this._watchersRestorable={};for(let[r,i]of t)this.watchPath(r,i.options,i.handler)}async watcherAdd(t,r){let{folderPath:i}=t;(this._watchers[i]=this._watchers[i]||[]).push(t);let a=new SfS(this,t,r);return await a.init(),a}watcherClose(t){t.watcher.close();let r=this._watchers[t.folderPath];if(r){let a=r.indexOf(t);r.splice(a,1),r.length||delete this._watchers[t.folderPath]}let i=t.filePath||t.folderPath;this._roots.has(i)&&(this._watchersRestorable[i]=t,this._watchersRestoreTimeout||(this._watchersRestoreTimeout=Mh.lang.defer(()=>this.watchersRestore())))}watcherExists(t,r,i,n){if(this._watchers[t]?.find(c=>c.handler===i&&(!c.filePath||c.filePath===n)&&c.options.ignore===r.ignore&&!!c.options.native==!!r.native&&(!r.recursive||c.options.recursive)))return!0;let o=Bra.default.dirname(t);for(let c=1;c<1/0;c++){if(this._watchers[o]?.find(u=>(c===1||u.options.recursive&&c<=(u.options.depth??Wbn))&&u.handler===i&&(!u.filePath||u.filePath===n)&&u.options.ignore===r.ignore&&!!u.options.native==!!r.native&&(!r.recursive||u.options.recursive&&xbn&&u.options.native!==!1)))return!0;if(!xbn)break;let s=Bra.default.dirname(t);if(o===s)break;o=s}return!1}async watchDirectories(t,r,i,n,a){if(this.isClosed())return;t=Mh.lang.uniq(t).sort();let o;for(let c of t)if(!this.isIgnored(c,r.ignore)&&!this.watcherExists(c,r,i,n))try{let d=!r.recursive||xbn&&r.native!==!1?r:{...r,recursive:!1},u={watcher:Ehc.default.watch(c,d),handler:i,options:r,folderPath:c,filePath:n},f=o=await this.watcherAdd(u,a);if(this._roots.has(n||c)){let _={...r,ignoreInitial:!0,recursive:!1},h=Bra.default.dirname(c),y=c;await this.watchDirectories([h],_,i,y,f)}}catch(d){this.error(d)}return o}async watchDirectory(t,r,i,n,a){if(!this.isClosed()&&!this.isIgnored(t,r.ignore)){if(!r.recursive||xbn&&r.native!==!1)return this.watchersLock(()=>this.watchDirectories([t],r,i,n,a));{r={...r,recursive:!0};let o=r.depth??Wbn,c=r.limit??P8o,[d]=await Mh.fs.readdir(t,r.ignore,o,c,this._closeSignal,r.readdirMap);return this.watchersLock(async()=>{let s=await this.watchDirectories([t],r,i,n,a);if(d.length){let u=Mh.fs.getDepth(t);for(let f of d){let p=Mh.fs.getDepth(f),_=Math.max(0,o-(p-u)),h={...r,depth:_};await this.watchDirectories([f],h,i,n,a||s)}}})}}}async watchFileOnce(t,r,i){if(this.isClosed()||(r={...r,ignoreInitial:!1},this.subwatcherExists(t,r)))return;let n={targetPath:t,options:r},a=(s,u)=>{u===t&&(d(),i())},o=new e(a),c=()=>{this._subwatchers.add(n),this.on(cX.CLOSE,d),o.watchFile(t,r,a)},d=()=>{this._subwatchers.delete(n),this.removeListener(cX.CLOSE,d),o.close()};return c()}async watchFile(t,r,i){if(this.isClosed()||this.isIgnored(t,r.ignore))return;r={...r,recursive:!1};let n=Bra.default.dirname(t);return this.watchDirectory(n,r,i,t)}async watchPollingOnce(t,r,i){if(this.isClosed())return;let n=!1,a=new KNp,o=await this.watchPolling(t,r,async()=>{n||!(await a.update(t,r.pollingTimeout)).length||n||(n=!0,o(),i())})}async watchPolling(t,r,i){if(this.isClosed())return Mh.lang.noop;if(this.pollerExists(t,r))return Mh.lang.noop;let n={...r,interval:r.pollingInterval??hfS},a={targetPath:t,options:r},o=()=>{this._pollers.add(a),this.on(cX.CLOSE,c),Ehc.default.watchFile(t,n,i)},c=()=>{this._pollers.delete(a),this.removeListener(cX.CLOSE,c),Ehc.default.unwatchFile(t,i)};return Mh.lang.attempt(o),()=>Mh.lang.attempt(c)}async watchUnknownChild(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchFileOnce(t,r,n)}async watchUnknownTarget(t,r,i){if(this.isClosed())return;let n=()=>this.watchPath(t,r,i);return this.watchPollingOnce(t,r,n)}async watchPaths(t,r,i){if(this.isClosed())return;if(t=Mh.lang.uniq(t).sort(),t.every((a,o)=>t.every((c,d)=>d===o||!Mh.fs.isSubPath(a,c))))await Promise.all(t.map(a=>this.watchPath(a,r,i)));else for(let a of t)await this.watchPath(a,r,i)}async watchPath(t,r,i){if(this.isClosed()||(t=Bra.default.resolve(t),this.isIgnored(t,r.ignore)))return;let n=await Mh.fs.poll(t,r.pollingTimeout);if(n){if(n.isFile())return this.watchFile(t,r,i);if(n.isDirectory())return this.watchDirectory(t,r,i);this.error(`"${t}" is not supported`)}else{let a=Bra.default.dirname(t);return(await Mh.fs.poll(a,r.pollingTimeout))?.isDirectory()?this.watchUnknownChild(t,r,i):this.watchUnknownTarget(t,r,i)}}async watch(t,r,i=Mh.lang.noop){if(Mh.lang.isFunction(t))return this.watch([],{},t);if(Mh.lang.isUndefined(t))return this.watch([],r,i);if(Mh.lang.isFunction(r))return this.watch(t,{},r);if(Mh.lang.isUndefined(r))return this.watch(t,{},i);if(this.isClosed())return;this.isReady()&&(r.readdirMap=void 0);let n=Mh.lang.castArray(t);n.forEach(a=>this._roots.add(a)),await this.watchPaths(n,r,i),!this.isClosed()&&(i!==Mh.lang.noop&&this.on(cX.ALL,i),r.readdirMap=void 0,this.ready())}},Shc=$Np;ufc();var A9a=require("fs/promises"),IfS=require("os"),CfS=se(require("path"),1),E35=".fern",S35="logs";function M35(){return"cli@3.58.0"}var D8o=class{logFilePath=null;initialized=!1;sessionStartTime;constructor(){this.sessionStartTime=Date.now()}async initialize(){if(this.initialized)return;let t=ot(mr.of((0,IfS.homedir)()),Pe.of(E35)),r=ot(t,Pe.of(S35));await ni(r)||await(0,A9a.mkdir)(r,{recursive:!0});let n=`${new Date().toISOString().replace(/[:.]/g,"-")}.debug.log`;this.logFilePath=ot(r,Pe.of(n));let a=["================================================================================","Fern Docs Dev Debug Log",`Session started: ${new Date().toISOString()}`,`Log file: ${CfS.default.basename(this.logFilePath)}`,"================================================================================",""].join(`
|
|
2466
2466
|
`);await(0,A9a.writeFile)(this.logFilePath,a,"utf-8"),this.initialized=!0}getLogFilePath(){return this.logFilePath}async writeEntry(t){if(!this.initialized||!this.logFilePath)return;let r=JSON.stringify(t)+`
|
|
2467
2467
|
`;try{await(0,A9a.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 i={timestamp:t.timestamp,source:M35(),level:r,eventType:t.type,data:{durationMs:t.durationMs,metadata:t.metadata}};await this.writeEntry(i)}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 i={type:"cli_reload_finish",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(i)}async logCliDocsGeneration(t,r){let i={type:"cli_docs_generation",timestamp:new Date().toISOString(),durationMs:t,metadata:r};await this.logCliMetric(i)}async logCliValidation(t,r){let i={type:"cli_validation",timestamp:new Date().toISOString(),durationMs:t,metadata:{success:r}};await this.logCliMetric(i)}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 hFp=se(iFp(),1),DpS=se(W2s(),1),GOe=require("fs/promises"),BpS=require("os"),IpS=se(VQ(),1),CpS=se(SpS(),1),Ghc=process.platform==="win32",_Fp=ct.cyan("[docs]:"),k35="etag",eW5=23,MpS=e=>e.padEnd(eW5," "),tW5="preview",rW5="app-preview",iW5="bundle",nW5=".next",aW5="standalone",oW5=".fern",uW5="packages/fern-docs/bundle/.next/server/instrumentation.js",sW5=".npmrc",cW5=".pnpmfile.cjs",lW5="pnpm-workspace.yaml",fW5='Cannot find matching keyid: {"signatures":';function dW5(){return ot(mr.of((0,BpS.homedir)()),Pe.of(oW5))}function P9a({app:e=!1}){return ot(dW5(),Pe.of(e?rW5:tW5))}function Kbn({app:e=!1}){return ot(P9a({app:e}),Pe.of(e?nW5:iW5))}function C8o({app:e=!1}){return ot(Kbn({app:e}),Pe.of(aW5))}function pW5({app:e=!1}){return ot(C8o({app:e}),Pe.of(uW5))}function _W5({app:e=!1}){return ot(C8o({app:e}),Pe.of(lW5))}function hW5({app:e=!1}){return ot(C8o({app:e}),Pe.of(cW5))}function yW5({app:e=!1}){return ot(C8o({app:e}),Pe.of(sW5))}function qra(e){return new Error(`${e}. Please reach out to support@buildwithfern.com.`)}function bW5({app:e=!1}){return ot(P9a({app:e}),Pe.of(k35))}var vW5=`module.exports = {
|
|
2468
2468
|
hooks: {
|
package/package.json
CHANGED