@cline/core 0.0.95 → 0.2.0-nightly.1793312794

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/dist/ClineCore.d.ts +6 -1
  2. package/dist/account/rpc.d.ts +3 -1
  3. package/dist/account/types.d.ts +2 -0
  4. package/dist/artifacts/cloud/fetch.d.ts +8 -0
  5. package/dist/artifacts/cloud/publish.d.ts +6 -0
  6. package/dist/artifacts/publish.d.ts +30 -0
  7. package/dist/cline-core/runtime-services.d.ts +4 -2
  8. package/dist/cloud/computer-use-prompt.d.ts +9 -0
  9. package/dist/cloud/controller.d.ts +26 -4
  10. package/dist/cloud/hub-client.d.ts +53 -0
  11. package/dist/cloud/hub-protocol.d.ts +32 -0
  12. package/dist/cloud/index.d.ts +5 -0
  13. package/dist/cloud/index.js +34 -17
  14. package/dist/cloud/types.d.ts +4 -1
  15. package/dist/extensions/context/compaction-shared.d.ts +1 -0
  16. package/dist/extensions/context/compaction.d.ts +7 -0
  17. package/dist/extensions/context/summarize-conversation.d.ts +7 -0
  18. package/dist/extensions/context/summary-generation.d.ts +14 -0
  19. package/dist/extensions/mcp/apps.d.ts +16 -0
  20. package/dist/extensions/mcp/client.d.ts +1 -0
  21. package/dist/extensions/mcp/index.d.ts +5 -1
  22. package/dist/extensions/mcp/manager.d.ts +2 -1
  23. package/dist/extensions/mcp/session-apps.d.ts +28 -0
  24. package/dist/extensions/mcp/types.d.ts +22 -0
  25. package/dist/extensions/plugin/plugin-command-origin.d.ts +8 -0
  26. package/dist/extensions/plugin/plugin-registry.d.ts +1 -0
  27. package/dist/extensions/plugin/plugin-runtime.d.ts +7 -0
  28. package/dist/hub/client/index.d.ts +6 -0
  29. package/dist/hub/client/managed-hub-build-watcher.d.ts +2 -0
  30. package/dist/hub/client/plugin-commands.d.ts +4 -0
  31. package/dist/hub/client/session-client.d.ts +2 -0
  32. package/dist/hub/daemon/entry.js +248 -229
  33. package/dist/hub/daemon/index.d.ts +2 -0
  34. package/dist/hub/index.d.ts +1 -0
  35. package/dist/hub/index.js +238 -219
  36. package/dist/hub/runtime-host/hub-runtime-host.d.ts +6 -0
  37. package/dist/hub/server/cloud-session-service.d.ts +52 -0
  38. package/dist/hub/server/handlers/capability-handlers.d.ts +18 -1
  39. package/dist/hub/server/handlers/context.d.ts +13 -2
  40. package/dist/hub/server/handlers/mcp-apps-handlers.d.ts +5 -0
  41. package/dist/hub/server/handlers/session-handlers.d.ts +4 -0
  42. package/dist/hub/server/hub-server-options.d.ts +3 -0
  43. package/dist/hub/server/hub-server-transport.d.ts +2 -0
  44. package/dist/index.d.ts +10 -5
  45. package/dist/index.js +284 -258
  46. package/dist/plugin-runtime/node_modules/@cline/agents/dist/index.js +76 -0
  47. package/dist/plugin-runtime/node_modules/@cline/agents/package.json +1 -0
  48. package/dist/plugin-runtime/node_modules/@cline/core/dist/ai-sdk-bdvd54cj.js +1 -0
  49. package/dist/plugin-runtime/node_modules/@cline/core/dist/anthropic-d88t4w67.js +1 -0
  50. package/dist/plugin-runtime/node_modules/@cline/core/dist/bedrock-4rh6dw0e.js +1 -0
  51. package/dist/plugin-runtime/node_modules/@cline/core/dist/cline-dex049wz.js +1 -0
  52. package/dist/plugin-runtime/node_modules/@cline/core/dist/cloud/index.js +38 -0
  53. package/dist/plugin-runtime/node_modules/@cline/core/dist/community-adrseffv.js +1 -0
  54. package/dist/plugin-runtime/node_modules/@cline/core/dist/foundation-models-embedding-model-strategy-SAVQFBF4-vf44v1q1.js +1 -0
  55. package/dist/plugin-runtime/node_modules/@cline/core/dist/foundation-models-language-model-strategy-BPQO66W7-np6pavev.js +1 -0
  56. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-bsd-1xg0n8py.js +1 -0
  57. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-bsd-2h2811k3.js +1 -0
  58. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-darwin-918h9zb6.js +2 -0
  59. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-darwin-9g9qz8kw.js +2 -0
  60. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-linux-8p52y0t4.js +1 -0
  61. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-linux-cr4wnstr.js +1 -0
  62. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-unsupported-aa72jh2v.js +1 -0
  63. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-unsupported-k2y10eep.js +1 -0
  64. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-win-1hvm2h6v.js +1 -0
  65. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-win-7nqbajdc.js +1 -0
  66. package/dist/plugin-runtime/node_modules/@cline/core/dist/google-nqn5r579.js +1 -0
  67. package/dist/plugin-runtime/node_modules/@cline/core/dist/hub/daemon/entry.js +1166 -0
  68. package/dist/plugin-runtime/node_modules/@cline/core/dist/hub/index.js +1153 -0
  69. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-0ahmqye5.js +2 -0
  70. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-1jwj53tz.js +2 -0
  71. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-3qy7846d.js +14 -0
  72. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-418gvd4a.js +2 -0
  73. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-4etvmc8g.js +2 -0
  74. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-4pm9q9we.js +1 -0
  75. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-4tgv599k.js +2 -0
  76. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-5hwscy9s.js +15 -0
  77. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-6dpcn5cw.js +9 -0
  78. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-7ycwqbm0.js +1 -0
  79. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-8qjtgvqw.js +9 -0
  80. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-8zb5grad.js +1210 -0
  81. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-94jdgxt6.js +2 -0
  82. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-9g67p34k.js +2 -0
  83. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-a9d2sjh0.js +85 -0
  84. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-agemt17a.js +3 -0
  85. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bhf7enwn.js +1 -0
  86. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bnwxdgvg.js +1 -0
  87. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-brjxtvsh.js +4 -0
  88. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bvb7f701.js +1 -0
  89. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bwet95hr.js +2 -0
  90. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-cadyf2yp.js +14 -0
  91. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-cxfnnrmh.js +9 -0
  92. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-cyyvppz9.js +6 -0
  93. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-d4pbedxj.js +137 -0
  94. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ddwn220p.js +12 -0
  95. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-edf1hmcw.js +62 -0
  96. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ejyd73x5.js +1 -0
  97. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-f25bf131.js +4 -0
  98. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-f4rfmj6q.js +3 -0
  99. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-fet3kwk6.js +1 -0
  100. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ffna8yzn.js +121 -0
  101. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-g2y6ptdc.js +213 -0
  102. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ge184xvn.js +6 -0
  103. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-gevnedsc.js +13 -0
  104. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-hkmarmve.js +190 -0
  105. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-kqacxn3s.js +39 -0
  106. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-m3gtj35r.js +14 -0
  107. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-neczvge6.js +21 -0
  108. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-p5k5hnam.js +75 -0
  109. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-sdvqs19c.js +20 -0
  110. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-t75m2pgm.js +146 -0
  111. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v4-qqb2kabr.js +1 -0
  112. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v6mehmme.js +12 -0
  113. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v80fh3x3.js +16 -0
  114. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-vd605jwp.js +2 -0
  115. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-vryppqt1.js +1 -0
  116. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-w55v4n1n.js +2 -0
  117. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-w9n2kgjk.js +140 -0
  118. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-yjbp9r76.js +142 -0
  119. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ztb3cjfh.js +3 -0
  120. package/dist/plugin-runtime/node_modules/@cline/core/dist/index.js +1 -0
  121. package/dist/plugin-runtime/node_modules/@cline/core/dist/jiti-static-kj4rdeey.js +473 -0
  122. package/dist/plugin-runtime/node_modules/@cline/core/dist/jiti-y9tt7gmq.js +1 -0
  123. package/dist/plugin-runtime/node_modules/@cline/core/dist/langfuse-stream-telemetry-bg81k3qh.js +1 -0
  124. package/dist/plugin-runtime/node_modules/@cline/core/dist/langfuse-telemetry-tkbfbx5w.js +1 -0
  125. package/dist/plugin-runtime/node_modules/@cline/core/dist/mistral-mkw95amh.js +1 -0
  126. package/dist/plugin-runtime/node_modules/@cline/core/dist/multipart-parser-9z19cm6q.js +2 -0
  127. package/dist/plugin-runtime/node_modules/@cline/core/dist/ollama-sjp09b7p.js +1 -0
  128. package/dist/plugin-runtime/node_modules/@cline/core/dist/openai-1eyn4hw0.js +1 -0
  129. package/dist/plugin-runtime/node_modules/@cline/core/dist/openai-compatible-f99c7syq.js +1 -0
  130. package/dist/plugin-runtime/node_modules/@cline/core/dist/orchestration-embedding-model-strategy-GT27AFII-19936r1a.js +1 -0
  131. package/dist/plugin-runtime/node_modules/@cline/core/dist/orchestration-language-model-strategy-YEQPUCOT-eavx3zc3.js +1 -0
  132. package/dist/plugin-runtime/node_modules/@cline/core/dist/services/feature-flags/posthog.js +2 -0
  133. package/dist/plugin-runtime/node_modules/@cline/core/dist/services/telemetry/index.js +1 -0
  134. package/dist/plugin-runtime/node_modules/@cline/core/dist/token-04d0mwe8.js +1 -0
  135. package/dist/plugin-runtime/node_modules/@cline/core/dist/token-util-mt7pvm61.js +1 -0
  136. package/dist/plugin-runtime/node_modules/@cline/core/dist/vertex-6armtc3s.js +1 -0
  137. package/dist/plugin-runtime/node_modules/@cline/core/package.json +1 -0
  138. package/dist/plugin-runtime/node_modules/@cline/llms/dist/index.browser.js +16 -0
  139. package/dist/plugin-runtime/node_modules/@cline/llms/dist/index.js +1 -0
  140. package/dist/plugin-runtime/node_modules/@cline/llms/package.json +1 -0
  141. package/dist/plugin-runtime/node_modules/@cline/sdk/dist/index.js +1 -0
  142. package/dist/plugin-runtime/node_modules/@cline/sdk/package.json +1 -0
  143. package/dist/plugin-runtime/node_modules/@cline/shared/dist/automation/index.js +57 -0
  144. package/dist/plugin-runtime/node_modules/@cline/shared/dist/db/index.js +127 -0
  145. package/dist/plugin-runtime/node_modules/@cline/shared/dist/index.browser.js +110 -0
  146. package/dist/plugin-runtime/node_modules/@cline/shared/dist/index.js +1 -0
  147. package/dist/plugin-runtime/node_modules/@cline/shared/dist/node.js +1 -0
  148. package/dist/plugin-runtime/node_modules/@cline/shared/dist/remote-config/index.js +68 -0
  149. package/dist/plugin-runtime/node_modules/@cline/shared/dist/storage/index.js +1 -0
  150. package/dist/plugin-runtime/node_modules/@cline/shared/dist/types/index.js +1 -0
  151. package/dist/plugin-runtime/node_modules/@cline/shared/package.json +1 -0
  152. package/dist/plugin-runtime/package.json +1 -0
  153. package/dist/{extensions → plugin-runtime}/plugin-sandbox-bootstrap.js +129 -129
  154. package/dist/remote/remote-environments.d.ts +1 -0
  155. package/dist/runtime/config/agent-runtime-config-builder.d.ts +2 -0
  156. package/dist/runtime/host/local-runtime-host.d.ts +10 -0
  157. package/dist/runtime/host/runtime-host.d.ts +6 -0
  158. package/dist/runtime/orchestration/runtime-oauth-token-manager.d.ts +3 -0
  159. package/dist/runtime/orchestration/session-runtime-orchestrator.d.ts +10 -1
  160. package/dist/runtime/orchestration/session-runtime.d.ts +2 -0
  161. package/dist/runtime/tools/subprocess-sandbox.d.ts +22 -0
  162. package/dist/services/cloud-handoff/git-preparation.d.ts +22 -0
  163. package/dist/services/global-settings.d.ts +6 -0
  164. package/dist/services/llms/cline-recommended-models.d.ts +2 -0
  165. package/dist/services/local-runtime-bootstrap.d.ts +1 -0
  166. package/dist/services/plugin-command-api.d.ts +47 -0
  167. package/dist/services/plugin-commands.d.ts +25 -27
  168. package/dist/services/skills-cli.d.ts +2 -0
  169. package/dist/services/telemetry/core-events.d.ts +26 -0
  170. package/dist/services/telemetry/index.js +1 -1
  171. package/dist/services/telemetry/run-health.d.ts +40 -0
  172. package/dist/services/telemetry/stall-signals.d.ts +12 -0
  173. package/dist/types/config.d.ts +1 -0
  174. package/dist/types/session.d.ts +7 -0
  175. package/package.json +6 -5
@@ -0,0 +1 @@
1
+ import{Zp}from"./index-neczvge6.js";import{v}from"./index-edf1hmcw.js";var i=v(Zp(),1);import{createRequire as o}from"node:module";function n(r){throw r}var a=(r)=>import(r),e;function f(...r){if(!e)e=o(import.meta.url)("../dist/babel.cjs");return e(...r)}function m(r,t={}){if(!t.transform)t={...t,transform:f};return i.default(r,t,{onError:n,nativeImport:a,createRequire:o})}var l=m;export{m as createJiti,l as default};
@@ -0,0 +1 @@
1
+ import{hp}from"./index-ddwn220p.js";import{We,wc}from"./index-w9n2kgjk.js";import{Or}from"./index-ffna8yzn.js";class o extends hp{attempts=new Map;completedAttempts=new Map;startingCallId;constructor(t){super({tracer:{startSpan:(e,a,n)=>{let l=t.startSpan(e,a,n);if(this.startingCallId)this.attempts.set(this.startingCallId,l);return l},startActiveSpan:t.startActiveSpan.bind(t)}})}onLanguageModelCallStart(t){this.endAttempt(t.callId),this.startingCallId=t.callId;try{super.onLanguageModelCallStart(t)}finally{this.startingCallId=void 0}}async executeLanguageModelCall(t){try{return await super.executeLanguageModelCall(t)}catch(e){throw this.onLanguageModelCallError({callId:t.callId,error:e}),this.endAttempt(t.callId),e}}onLanguageModelCallEnd(t){if(this.completedAttempts.set(t.callId,t),t.finishReason!=="error")this.endAttempt(t.callId)}endAttempt(t){let e=this.completedAttempts.get(t);if(e)super.onLanguageModelCallEnd(e);else this.attempts.get(t)?.end();this.completedAttempts.delete(t),this.attempts.delete(t)}onStepEnd(t){this.endAttempt(t.callId),super.onStepEnd(t)}onLanguageModelCallError({callId:t,error:e}){if(We(e)&&!Or(e))return;let a=this.attempts.get(t);if(!a)return;let n=e instanceof Error?e.message:typeof e==="object"&&e!==null&&("message"in e)&&typeof e.message==="string"?e.message:"Provider stream failed";a.recordException(e instanceof Error?e:{message:n}),a.setStatus({code:wc.ERROR,message:n})}onError(t){if(typeof t==="object"&&t!==null&&"callId"in t&&typeof t.callId==="string"){let e="error"in t?t.error:t;if(We(e)&&!Or(e)){this.endAttempt(t.callId);return}this.onLanguageModelCallError({callId:t.callId,error:e}),this.endAttempt(t.callId)}super.onError(t)}onEnd(t){this.endAttempt(t.callId),super.onEnd(t)}onAbort(t){this.endAttempt(t.callId),super.onAbort(t)}}export{o as LangfuseStreamTelemetry};
@@ -0,0 +1 @@
1
+ import{Zv,LE,Mf}from"./index-ffna8yzn.js";export{Mf as disposeLangfuseTelemetry,LE as resolveAiSdkTelemetry,Zv as withLangfuseTraceAttributes};
@@ -0,0 +1 @@
1
+ import{Ne}from"./index-w9n2kgjk.js";import"./index-hkmarmve.js";import{lt,Cr}from"./index-ffna8yzn.js";import{yl}from"./index-f25bf131.js";async function s(e){let r=yl({apiKey:await lt(e),baseURL:e.baseUrl,headers:e.headers,fetch:e.fetch});return{operations:{language:(o)=>Ne({model:r(o),middleware:Cr})}}}export{s as createMistralProviderModule};
@@ -0,0 +1,2 @@
1
+ import{ou,Hr,ru,gd}from"./index-v6mehmme.js";import{bt}from"./index-edf1hmcw.js";class k{constructor(i){this.index=0,this.flags=0,this.onHeaderEnd=_,this.onHeaderField=_,this.onHeadersEnd=_,this.onHeaderValue=_,this.onPartBegin=_,this.onPartData=_,this.onPartEnd=_,this.boundaryChars={},i=`\r
2
+ --`+i;let r=new Uint8Array(i.length);for(let E=0;E<i.length;E++)r[E]=i.charCodeAt(E),this.boundaryChars[r[E]]=!0;this.boundary=r,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=t.START_BOUNDARY}write(i){let r=0,E=i.length,o=this.index,{lookbehind:d,boundary:A,boundaryChars:L,index:e,state:s,flags:l}=this,R=this.boundary.length,u=R-1,g=i.length,a,S,H=(c)=>{this[c+"Mark"]=r},T=(c)=>{delete this[c+"Mark"]},n=(c,P,f,N)=>{if(P===void 0||P!==f)this[c](N&&N.subarray(P,f))},b=(c,P)=>{let f=c+"Mark";if(!(f in this))return;if(P)n(c,this[f],r,i),delete this[f];else n(c,this[f],i.length,i),this[f]=0};for(r=0;r<E;r++)switch(a=i[r],s){case t.START_BOUNDARY:if(e===A.length-2){if(a===m)l|=D.LAST_BOUNDARY;else if(a!==O)return;e++;break}else if(e-1===A.length-2){if(l&D.LAST_BOUNDARY&&a===m)s=t.END,l=0;else if(!(l&D.LAST_BOUNDARY)&&a===p)e=0,n("onPartBegin"),s=t.HEADER_FIELD_START;else return;break}if(a!==A[e+2])e=-2;if(a===A[e+2])e++;break;case t.HEADER_FIELD_START:s=t.HEADER_FIELD,H("onHeaderField"),e=0;case t.HEADER_FIELD:if(a===O){T("onHeaderField"),s=t.HEADERS_ALMOST_DONE;break}if(e++,a===m)break;if(a===U){if(e===1)return;b("onHeaderField",!0),s=t.HEADER_VALUE_START;break}if(S=V(a),S<w||S>B)return;break;case t.HEADER_VALUE_START:if(a===F)break;H("onHeaderValue"),s=t.HEADER_VALUE;case t.HEADER_VALUE:if(a===O)b("onHeaderValue",!0),n("onHeaderEnd"),s=t.HEADER_VALUE_ALMOST_DONE;break;case t.HEADER_VALUE_ALMOST_DONE:if(a!==p)return;s=t.HEADER_FIELD_START;break;case t.HEADERS_ALMOST_DONE:if(a!==p)return;n("onHeadersEnd"),s=t.PART_DATA_START;break;case t.PART_DATA_START:s=t.PART_DATA,H("onPartData");case t.PART_DATA:if(o=e,e===0){r+=u;while(r<g&&!(i[r]in L))r+=R;r-=u,a=i[r]}if(e<A.length)if(A[e]===a){if(e===0)b("onPartData",!0);e++}else e=0;else if(e===A.length)if(e++,a===O)l|=D.PART_BOUNDARY;else if(a===m)l|=D.LAST_BOUNDARY;else e=0;else if(e-1===A.length)if(l&D.PART_BOUNDARY){if(e=0,a===p){l&=~D.PART_BOUNDARY,n("onPartEnd"),n("onPartBegin"),s=t.HEADER_FIELD_START;break}}else if(l&D.LAST_BOUNDARY)if(a===m)n("onPartEnd"),s=t.END,l=0;else e=0;else e=0;if(e>0)d[e-1]=a;else if(o>0){let c=new Uint8Array(d.buffer,d.byteOffset,d.byteLength);n("onPartData",0,o,c),o=0,H("onPartData"),r--}break;case t.END:break;default:throw Error(`Unexpected state entered: ${s}`)}b("onHeaderField"),b("onHeaderValue"),b("onPartData"),this.index=e,this.state=s,this.flags=l}end(){if(this.state===t.HEADER_FIELD_START&&this.index===0||this.state===t.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==t.END)throw Error("MultipartParser.end(): stream ended unexpectedly")}}function Y(i){let r=i.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!r)return;let E=r[2]||r[3]||"",o=E.slice(E.lastIndexOf("\\")+1);return o=o.replace(/%22/g,'"'),o=o.replace(/&#(\d{4});/g,(d,A)=>String.fromCharCode(A)),o}async function M(i,r){if(!/multipart/i.test(r))throw TypeError("Failed to fetch");let E=r.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!E)throw TypeError("no or bad content-type header, no multipart boundary");let o=new k(E[1]||E[2]),d,A,L,e,s,l,R=[],u=new Hr,g=(n)=>{L+=T.decode(n,{stream:!0})},a=(n)=>{R.push(n)},S=()=>{let n=new ou(R,l,{type:s});u.append(e,n)},H=()=>{u.append(e,L)},T=new TextDecoder("utf-8");T.decode(),o.onPartBegin=function(){o.onPartData=g,o.onPartEnd=H,d="",A="",L="",e="",s="",l=null,R.length=0},o.onHeaderField=function(n){d+=T.decode(n,{stream:!0})},o.onHeaderValue=function(n){A+=T.decode(n,{stream:!0})},o.onHeaderEnd=function(){if(A+=T.decode(),d=d.toLowerCase(),d==="content-disposition"){let n=A.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);if(n)e=n[2]||n[3]||"";if(l=Y(A),l)o.onPartData=a,o.onPartEnd=S}else if(d==="content-type")s=A;A="",d=""};for await(let n of i)o.write(n);return o.end(),u}var h=0,t,y=1,D,p=10,O=13,F=32,m=45,U=58,w=97,B=122,V=(i)=>i|32,_=()=>{};var x=bt(()=>{gd();ru();t={START_BOUNDARY:h++,HEADER_FIELD_START:h++,HEADER_FIELD:h++,HEADER_VALUE_START:h++,HEADER_VALUE:h++,HEADER_VALUE_ALMOST_DONE:h++,HEADERS_ALMOST_DONE:h++,PART_DATA_START:h++,PART_DATA:h++,END:h++},D={PART_BOUNDARY:y,LAST_BOUNDARY:y*=2}});x();export{M as toFormData};
@@ -0,0 +1 @@
1
+ import{Ne}from"./index-w9n2kgjk.js";import"./index-hkmarmve.js";import{Oo,lt,Cr}from"./index-ffna8yzn.js";import{fl}from"./index-gevnedsc.js";function l(e){let t=e?.trim().replace(/\/+$/,"");if(!t)return;return`${t.replace(/\/(?:v1|api)$/,"")}/api`}var m=300000;function u(e){let t=e.timeoutMs;if(typeof t==="number"&&Number.isFinite(t)&&t>0)return Math.floor(t);return m}function c(e,t){return async(a,o)=>{let r=new AbortController,n=setTimeout(()=>r.abort(Error(`Ollama request timed out after ${t/1000} seconds`)),t),i=o?.signal,s=i?AbortSignal.any([i,r.signal]):r.signal;try{return await e(a,{...o,signal:s})}finally{clearTimeout(n)}}}async function h(e,t){let a=await lt(e),o=l(e.baseUrl),r={...a?{Authorization:`Bearer ${a}`}:{},...e.headers},n=fl({...o?{baseURL:o}:{},...Object.keys(r).length>0?{headers:r}:{},compatibility:"strict",fetch:c(Oo(e.fetch),u(e))});return{operations:{language:(i)=>Ne({model:n.chat(i),middleware:Cr})}}}export{h as createOllamaProviderModule};
@@ -0,0 +1 @@
1
+ import{lt}from"./index-ffna8yzn.js";import{uo}from"./index-w9n2kgjk.js";function u(t){if(!t)return!1;try{let{hostname:r}=new URL(t);return r==="chatgpt.com"||r.endsWith(".chatgpt.com")}catch{return!1}}async function c(t,r){let d=await lt(t),o=uo({apiKey:d,baseURL:t.baseUrl,headers:t.headers,fetch:t.fetch,name:r.provider.id}),l=u(t.baseUrl);return{buildModelTools:(e)=>{let n={};for(let i of e)switch(i.name){case"web_search":n.web_search={tool:o.tools.webSearch()};break;case"image_generation":n.image_generation={tool:o.tools.imageGeneration({outputFormat:i.outputFormat??"png"}),projectResult:(a)=>{let s=a&&typeof a==="object"&&!Array.isArray(a)?a:void 0;if(typeof s?.result!=="string"||s.result.length===0)throw Error("OpenAI image generation tool returned no supported image output");return{media:[{modality:"image",mediaType:`image/${i.outputFormat??"png"}`,source:{type:"base64",data:s.result}}]}}};break}return n},operations:{language:(e)=>o.responses(e),imageGeneration:(e)=>o.image(e)},buildStreamConfig:(e)=>({...!l&&e.maxTokens!==void 0&&e.defaultedMaxTokens!==!0?{maxOutputTokens:e.maxTokens}:{},temperature:e.temperature})}}export{c as createOpenAIProviderModule};
@@ -0,0 +1 @@
1
+ import{Wf,Nf,UE}from"./index-ffna8yzn.js";import"./index-hkmarmve.js";import"./index-w9n2kgjk.js";export{UE as createOpenAICompatibleProviderModule,Nf as createSuccessDataResponseFetch,Wf as withMaxCompletionTokensForReasoningModels};
@@ -0,0 +1 @@
1
+ import{iu}from"./index-g2y6ptdc.js";import{Vr,On,eu}from"./index-w55v4n1n.js";import{Yl}from"./index-1jwj53tz.js";import{createRequire as s}from"module";var i=s(import.meta.url),p=class extends Yl{ClientClass;constructor(e){super();this.ClientClass=e}createClient(e,r,n){let t=this.mergeModelParams(r,n),o={embeddings:{model:{name:e.modelId,...On(t)?{params:t}:{},...r.modelVersion?{version:r.modelVersion}:{}}},...r.masking&&On(r.masking)?{masking:r.masking}:{}};return new this.ClientClass(o,e.deploymentConfig,e.destination)}async executeCall(e,r,n,t){return e.embed({input:r,type:n},t)}extractEmbeddings(e){return[...e.getEmbeddings()].sort((t,a)=>t.index-a.index).map((t)=>eu(t.embedding))}extractResponseMetadata(e){return Vr(e,"response")}extractTokenCount(e){return e.getTokenUsage().total_tokens}getUrl(){return"sap-ai:orchestration/embeddings"}resolveWarnings(e,r){iu(e,r)}};export{p as OrchestrationEmbeddingModelStrategy};
@@ -0,0 +1 @@
1
+ import{Fh,jh,ho,iu}from"./index-g2y6ptdc.js";import{Xl,Zl,On}from"./index-w55v4n1n.js";import{Ks}from"./index-4tgv599k.js";import{createRequire as g}from"module";var S=g(import.meta.url);function h(e){return C(e)?{id:e.id,...e.scope&&{scope:e.scope}}:{name:e.name,scenario:e.scenario,version:e.version,...e.scope&&{scope:e.scope}}}function C(e){return"id"in e}function u(e,t){let o=ho(e.placeholderValues,t?.placeholderValues);return On(o)?o:void 0}var f=["masking","filtering","grounding","translation"],R=[...f,"fallbackModuleConfigs","promptTemplateRef","responseFormat","tools","modelParams","modelVersion"],v=["promptTemplateRef","modelParams"];function T(e,t){for(let o of f){let r=t[o];if(r&&On(r))e[o]=r}}function d(e){return jh.safeParse(e).success}var O=[...Ks.COMMON_PARAM_MAPPINGS,{camelCaseKey:"topK",optionKey:"topK",outputKey:"top_k"}],I=class extends Ks{ClientClass;constructor(e){super();this.ClientClass=e}buildRequest(e,t,o,r){let s=[],{configRef:n}=r.resolvedState;if(n)return this.buildConfigRefRequest(t,o,r,s);return this.buildStandardRequest(t,r,s)}collectStreamWarnings(e,t){let o=[],r=t?.orchestrationConfigRef??e.orchestrationConfigRef;if(r&&d(r)){if(e.streamOptions&&On(e.streamOptions))o.push({message:"orchestrationConfigRef is set; local streamOptions are ignored. Configure streaming in the referenced configuration or its overrideConfig.",type:"other"});return o}if(e.translation&&On(e.translation)){if(!e.streamOptions?.delimiters||e.streamOptions.delimiters.length===0)o.push({message:"Translation module is configured but streamOptions.delimiters is not set. For proper sentence boundary detection during streaming with translation, consider setting delimiters (e.g., ['.', '!', '?', '\\n']).",type:"other"})}return o}createClient(e,t,o){let{configRef:r,promptTemplateRef:s,responseFormat:n,tools:i}=o.resolvedState;if(r)return new this.ClientClass(r,e.deploymentConfig,e.destination);let a=this.buildOrchestrationModuleConfig(e,t,{modelParams:o.modelParams,promptTemplateRef:s,responseFormat:n,toolChoice:o.toolChoice,tools:i});if(t.fallbackModuleConfigs&&t.fallbackModuleConfigs.length>0){let l=[a,...t.fallbackModuleConfigs];return new this.ClientClass(l,e.deploymentConfig,e.destination)}return new this.ClientClass(a,e.deploymentConfig,e.destination)}async executeApiCall(e,t,o){let r=await e.chatCompletion(t,o),{requestId:s,responseMetadata:n}=this.extractMetadata(r);return{getCitations:()=>r.getCitations(),getContent:()=>r.getContent(),getFinishReason:()=>r.getFinishReason(),getIntermediateFailures:()=>r.getIntermediateFailures(),getTokenUsage:()=>r.getTokenUsage(),getToolCalls:()=>r.getToolCalls(),rawResponse:{headers:r.rawResponse.headers},requestId:s,responseMetadata:n}}async executeStreamCall(e,t,o,r,s,n){let{configRef:i}=n.resolvedState,a=i?void 0:this.buildSdkStreamOptions(r.streamOptions),l=await e.stream(t,o,a,s),{requestId:p,responseHeaders:c,responseMetadata:m}=this.extractMetadata(l);return{cancel:()=>{l.stream.controller.abort()},getCitations:()=>l.getCitations(),getFinishReason:()=>l.getFinishReason(),getIntermediateFailures:()=>l.getIntermediateFailures(),requestId:p,responseHeaders:c,responseMetadata:m,stream:l.stream}}getCompletionDataPath(){return["final_result"]}getEscapeTemplatePlaceholders(e,t){return e?.escapeTemplatePlaceholders??t.escapeTemplatePlaceholders??!0}getParamMappings(){return O}getPartProviderOptionsParser(){return Fh}getUrl(){return"sap-ai:orchestration"}resolveAdditionalState(e,t,o,r,s){let n=this.resolveConfigRef(o,t,s),i=this.resolvePromptTemplateRef(o,t),a;if(n===void 0){iu(t,s);let p=Xl(r.responseFormat,t.responseFormat);if(a=p.responseFormat,p.warning)s.push(p.warning)}let l=this.resolveTools(t,r,s);return{configRef:n,promptTemplateRef:i,responseFormat:a,tools:l}}buildConfigRefRequest(e,t,o,r){r.push(...this.collectConfigRefIgnoredWarnings(e,t,o.sapOptions));let s=u(e,o.sapOptions);return{request:{messagesHistory:o.messages,...s?{placeholderValues:s}:{}},warnings:r}}buildInlineTemplateConfig(e,t){return{template:[],...e&&e.length>0?{tools:e}:{},...t?{response_format:t}:{}}}buildOrchestrationModuleConfig(e,t,o){let{modelParams:r,promptTemplateRef:s,responseFormat:n,toolChoice:i,tools:a}=o,l=s?this.buildTemplateRefPromptConfig(s,a,n):this.buildInlineTemplateConfig(a,n),p=i?{...r,tool_choice:i}:r,c={promptTemplating:{model:{name:e.modelId,params:p,...t.modelVersion?{version:t.modelVersion}:{}},prompt:l}};return T(c,t),c}buildSdkStreamOptions(e){let t=e?.delimiters,o=Array.isArray(t)&&t.length>0,r=e?.chunkSize!==void 0||o;return{promptTemplating:{include_usage:!0},...r&&{global:{...e?.chunkSize!==void 0&&{chunk_size:e.chunkSize},...o&&{delimiters:Array.from(t)}}},...e?.outputFilteringOverlap!==void 0&&{outputFiltering:{overlap:e.outputFilteringOverlap}}}}buildStandardRequest(e,t,o){let{promptTemplateRef:r}=t.resolvedState,s=u(e,t.sapOptions);return{request:{...r?{messagesHistory:t.messages}:{messages:t.messages},...s?{placeholderValues:s}:{}},warnings:o}}buildTemplateRefPromptConfig(e,t,o){return{template_ref:h(e),...t&&t.length>0?{tools:t}:{},...o?{response_format:o}:{}}}collectConfigRefIgnoredWarnings(e,t,o){let r=[],s=[];for(let i of R){let a=e[i];if(a!==void 0){if(typeof a==="object"&&Object.keys(a).length===0)continue;s.push(i)}}for(let i of v)if(o?.[i]&&!e[i])s.push(`providerOptions.${i}`);let n=t;for(let{optionKey:i}of this.getParamMappings())if(i&&n[i]!==void 0)s.push(`options.${i}`);if(t.stopSequences&&t.stopSequences.length>0)s.push("options.stopSequences");if(t.tools&&t.tools.length>0)s.push("options.tools");if(t.responseFormat)s.push("options.responseFormat");if(t.toolChoice)s.push("options.toolChoice");if(s.length>0)r.push({message:`orchestrationConfigRef is set; the following local settings are ignored: ${s.join(", ")}. The full configuration is managed by the referenced config.`,type:"other"});return r}resolveConfigRef(e,t,o){let r=e?.orchestrationConfigRef??t.orchestrationConfigRef;if(!r)return;if(d(r))return r;o.push({message:"orchestrationConfigRef is invalid and was ignored; falling back to local module settings.",type:"other"});return}resolvePromptTemplateRef(e,t){let o=e?.promptTemplateRef??t.promptTemplateRef;if(o&&typeof o==="object"&&(("id"in o)||("name"in o)))return o;return}resolveTools(e,t,o){let r=e.tools,s=t.tools;if(r&&r.length>0&&s&&s.length>0)o.push({message:"Both settings.tools and call options.tools were provided; preferring call options.tools.",type:"other"});if(r&&r.length>0&&(!s||s.length===0))return r;if(s&&s.length>0){let n=Zl(s,{parser:Fh,warnings:o});return o.push(...n.warnings),n.tools}return}};export{I as OrchestrationLanguageModelStrategy};
@@ -0,0 +1,2 @@
1
+ import{dirname as gn,posix as mn,sep as _n}from"path";function Wr(){let e=yn();return async(t)=>{for(let r of t)r.module=e(r.filename);return t}}function yn(e=process.argv[1]?gn(process.argv[1]):process.cwd(),t=_n==="\\"){let r=t?Hr(e):e;return(s)=>{if(!s)return;let i=t?Hr(s):s,{dir:n,base:o,ext:l}=mn.parse(i);if(l===".js"||l===".mjs"||l===".cjs")o=o.slice(0,-1*l.length);let a=decodeURIComponent(o);if(!n)n=".";let c=n.lastIndexOf("/node_modules");if(c>-1)return`${n.slice(c+14).replace(/\//g,".")}:${a}`;if(n.startsWith(r)){let u=n.slice(r.length+1).replace(/\//g,".");return u?`${u}:${a}`:a}return a}}function Hr(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var R=function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.AiQueue="ai_queue",e.AiCaptureQueue="ai_capture_queue",e.LogsQueue="logs_queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.PushRegistered="push_registered",e.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysInProgress="surveys_in_progress",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e}({});function Z(e){let t=[];return JSON.stringify(e,function(r,s){if(typeof s=="bigint")return s.toString();if(typeof s=="function"||typeof s=="symbol")return;if(s instanceof Error)return{name:s.name,message:s.message,stack:s.stack};if(s&&typeof s=="object"){while(t.length>0&&t[t.length-1]!==this)t.pop();if(t.includes(s))return"[Circular]";t.push(s)}return s})??"null"}var bn=Array.isArray,Qr=Object.prototype,{hasOwnProperty:mc,toString:Xe}=Qr,L=bn||function(e){return Xe.call(e)==="[object Array]"};var Qe=(e)=>e===Object(e)&&!L(e);var q=(e)=>e===void 0,D=(e)=>Xe.call(e)=="[object String]",zt=(e)=>D(e)&&e.trim().length===0,qt=(e)=>e===null,k=(e)=>q(e)||qt(e),Je=(e)=>Xe.call(e)=="[object Number]"&&e===e;var Jr=(e)=>Xe.call(e)==="[object Boolean]";function Gt(e){return e===null||typeof e!="object"}function Kt(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function H(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Zr(e,Error)}}function Fe(e){return"u">typeof Event&&Zr(e,Event)}function Yr(e){return Kt(e,"Object")}function Zr(e,t){try{return e instanceof t}catch{return!1}}var En=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],Ye=new Map;function vn(e,t){let r="";for(let s=0;s<t.length;s++){let i=t[s];r+=i.length+":"+i}return e.length+":"+e+"|"+t.length+":"+r}var es=function(e,t=[]){if(!e)return!1;let r=vn(e,t),s=Ye.get(r);if(s!==void 0)return s;let i=e.toLowerCase(),n=En.concat(t).some((o)=>i.indexOf(o.toLowerCase())!==-1);if(Ye.size>=256)Ye.clear();return Ye.set(r,n),n};function Ae(e,t,r,s,i){if(t>r)s.warn("min cannot be greater than max."),t=r;if(Je(e))if(e>r)return s.warn(" cannot be greater than max: "+r+". Using max value instead."),r;else{if(!(e<t))return e;return s.warn(" cannot be less than min: "+t+". Using min value instead."),t}return s.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+i),Ae(i??r,t,r,s)}var Sn=86400000,Fn=1,An=10;function ts(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??Fn,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??An}}class Ht{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=Ae(e.bucketSize,0,100,e._logger),this._refillRate=Ae(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=Ae(e.refillInterval,0,Sn,e._logger)}_applyRefill(e,t){let r=t-e.lastAccess,s=Math.floor(r/this._refillInterval);if(s>0){let i=s*this._refillRate;e.tokens=Math.min(e.tokens+i,this._bucketSize),e.lastAccess=e.lastAccess+s*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),r=String(e),s=this._buckets[r];if(s)this._applyRefill(s,t);else s={tokens:this._bucketSize,lastAccess:t},this._buckets[r]=s;if(s.tokens===0)return!0;if(s.tokens--,s.tokens===0)this._onBucketRateLimited?.(e);return s.tokens===0}stop(){this._buckets={}}}/*! LICENSE: uuidv7.mjs.LICENSE.txt */class ee{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new ee(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,r,s){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(s)||e<0||t<0||r<0||s<0||e>281474976710655||t>4095||r>1073741823||s>4294967295)throw RangeError("invalid field value");let i=new Uint8Array(16);return i[0]=e/1099511627776,i[1]=e/4294967296,i[2]=e/16777216,i[3]=e/65536,i[4]=e/256,i[5]=e,i[6]=112|t>>>8,i[7]=t,i[8]=128|r>>>24,i[9]=r>>>16,i[10]=r>>>8,i[11]=r,i[12]=s>>>24,i[13]=s>>>16,i[14]=s>>>8,i[15]=s,new ee(i)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;default:break}if(t){let r=new Uint8Array(16);for(let s=0;s<16;s+=4){let i=parseInt(t.substring(2*s,2*s+8),16);r[s+0]=i>>>24,r[s+1]=i>>>16,r[s+2]=i>>>8,r[s+3]=i}return new ee(r)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)if(e+="0123456789abcdef".charAt(this.bytes[t]>>>4),e+="0123456789abcdef".charAt(15&this.bytes[t]),t===3||t===5||t===7||t===9)e+="-";return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+="0123456789abcdef".charAt(this.bytes[t]>>>4),e+="0123456789abcdef".charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw Error("unreachable");if(e<=7)return this.bytes.every((t)=>t===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every((t)=>t===255)?"MAX":"VAR_RESERVED";else throw Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new ee(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let r=this.bytes[t]-e.bytes[t];if(r!==0)return Math.sign(r)}return 0}}class ss{constructor(e){this.timestamp=0,this.counter=0,this.random=e??wn()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let r=this.generateOrAbortCore(e,t);if(r===void 0)this.timestamp=0,r=this.generateOrAbortCore(e,t);return r}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>281474976710655)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>281474976710655)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;if(this.counter++,this.counter>4398046511103)this.timestamp++,this.resetCounter()}return ee.fromFieldsV7(this.timestamp,Math.trunc(this.counter/1073741824),this.counter&1073741823,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,ee.ofInner(e)}}var wn=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),rs,I=()=>Pn().toString(),Pn=()=>(rs||(rs=new ss)).generate();class Wt{add(e){let t=I(),r=++this.nextId;return this.promiseByIds[t]={id:r,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map((r)=>r.promise),t=e.length;while(t>0)await Promise.all(e),e=Object.values(this.promiseByIds).map((r)=>r.promise),t=e.length}getPromises(e=[],t=this.nextId){let r=new Set(e);return Object.values(this.promiseByIds).filter((s)=>s.id<=t&&!r.has(s.promise)).map((s)=>s.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}function xn(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var is=(e,t,r)=>{function s(n,...o){t(()=>{let l=r[n];l(e,...o)})}return{debug:(...n)=>{s("debug",...n)},info:(...n)=>{s("log",...n)},warn:(...n)=>{s("warn",...n)},error:(...n)=>{s("error",...n)},critical:(...n)=>{r.error(e,...n)},createLogger:(n)=>is(`${e} ${n}`,t,r)}},In=(e)=>e();function ns(e,t=In){return is(e,t,xn())}var ue="Mobile",et="iOS",ce="Android",us="Tablet",Cc=ce+" "+us;var Rn="Apple",Oc=Rn+" Watch",ds="Safari",tt="BlackBerry",fs="Samsung",Cn=fs+"Browser",On=fs+" Internet",rt="Chrome",Ln=rt+" OS",Nn=rt+" "+et,hs="Internet Explorer",Mn=hs+" "+ue,Jt="Opera",Lc=Jt+" Mini",ps="Edge",Dn="Microsoft "+ps,Yt="Firefox",$n=Yt+" "+et,Zt="Nintendo",er="PlayStation",Ze="Xbox",kn=ce+" "+ue,Un=ue+" "+ds,we="Windows",Bn=we+" Phone";var gs="Generic",Nc=gs+" "+ue.toLowerCase(),Mc=gs+" "+us.toLowerCase(),jn="Konqueror",Vn="Oculus Browser",os="Vivaldi",zn="Yandex",as="Whale",qn="DuckDuckGo",Gn="Pale Moon",ls="Waterfox",cs="Brave",ms="Claude",_s="Codex",ys="ChatGPT",Kn="Google Search App",P="(\\d+(\\.\\d+)?)",Xt=new RegExp("Version/"+P),Qt=new RegExp("("+ms+"|"+_s+"|"+ys+")\\/"+P);var Dc=new RegExp(Ze,"i"),$c=new RegExp(er+" \\w+","i"),kc=new RegExp(Zt+" \\w+","i"),Hn=new RegExp(tt+"|PlayBook|BB10","i"),Wn={"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 Uc={[Mn]:[new RegExp("rv:"+P)],[Dn]:[new RegExp(ps+"?\\/"+P)],[rt]:[new RegExp("("+rt+"|CrMo)\\/"+P)],[Nn]:[new RegExp("CriOS\\/"+P)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+P)],[ds]:[Xt],[Un]:[Xt],[Jt]:[new RegExp("("+Jt+"|OPR)\\/"+P)],[Yt]:[new RegExp(Yt+"\\/"+P)],[$n]:[new RegExp("FxiOS\\/"+P)],[jn]:[new RegExp("Konqueror[:/]?"+P,"i")],[tt]:[new RegExp(tt+" "+P),Xt],[kn]:[new RegExp("android\\s"+P,"i")],[On]:[new RegExp(Cn+"\\/"+P)],[Vn]:[new RegExp("OculusBrowser\\/"+P)],[os]:[new RegExp(os+"\\/"+P)],[zn]:[new RegExp("YaBrowser\\/"+P)],[as]:[new RegExp(as+"\\/"+P)],[cs]:[new RegExp(cs+"\\/"+P)],[ms]:[Qt],[_s]:[Qt],[ys]:[Qt],[qn]:[new RegExp("(DuckDuckGo|Ddg)\\/"+P)],[Gn]:[new RegExp("PaleMoon\\/"+P)],[ls]:[new RegExp(ls+"\\/"+P)],[Kn]:[new RegExp("GSA\\/"+P)],[hs]:[new RegExp("(rv:|MSIE )"+P)],Mozilla:[new RegExp("rv:"+P)]};var Bc=[[new RegExp(Ze+"; "+Ze+" (.*?)[);]","i"),(e)=>[Ze,e&&e[1]||""]],[new RegExp(Zt,"i"),[Zt,""]],[new RegExp(er,"i"),[er,""]],[Hn,[tt,""]],[new RegExp(we,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[Bn,""];if(new RegExp(ue).test(t)&&!/IEMobile\b/.test(t))return[we+" "+ue,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let s=r[1],i=Wn[s]||"";if(/arm/i.test(t))i="RT";return[we,i]}return[we,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(e)=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[et,t.join(".")]}return[et,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(e)=>{let t="";if(e&&e.length>=3)t=q(e[2])?e[3]:e[2];return["watchOS",t]}],[new RegExp("("+ce+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+ce+")","i"),(e)=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[ce,t.join(".")]}return[ce,""]}],[/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/,[Ln,""]],[/Linux|debian/i,["Linux",""]]];var st=20,de=1000,it=1e4,nt="[Circular]",ot="[Truncated]",U="[Unserializable]",bs="[Function]",zc=Date.prototype.getTime,qc=Date.prototype.toISOString;function j(e){let t="";for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);if(s>=55296&&s<=56319){let i=e.charCodeAt(r+1);if(i>=56320&&i<=57343)t+=e[r]+e[r+1],r++;else t+="�"}else t+=s>=56320&&s<=57343?"�":e[r]}return t}function G(e,t){if(!t)return e;let r=[];try{r=Object.keys(t)}catch{r=[]}for(let s of r){let i;try{i=t[s]}catch{i="[Unserializable]"}Object.defineProperty(e,s,{value:i,enumerable:!0,writable:!0,configurable:!0})}return e}function tr(e,t=Date.now()){if(typeof e!="string"||!e)return;let r=e.trim(),s=/^\d+\s*,/.test(r)?r.slice(0,r.indexOf(",")).trim():r;if(/^\d+$/.test(s)){let o=1000*Math.min(Number(s),300);return o>0?o:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(s))return;let i=/^\w{3} \w{3} /.test(s)?s+" GMT":s,n=Date.parse(i)-t;if(!Number.isFinite(n)||n<=0)return;return Math.min(n,300000)}class fe{record(e){if(e.kind==="too-large")return;if(e.kind!=="retry-later")return void this.reset();if(!e.retryAfterMs)return;let t=this.isOpen(),r=Date.now(),s=Math.min(e.retryAfterMs,300000);if(!t){this._installedAt=r,this._until=r+s;return}this._until=Math.max(this._until,Math.min(r+s,this._installedAt+300000))}remainingMs(){let e=Date.now();if(e<this._installedAt-5000)return this.reset(),0;let t=Math.min(300000,Math.max(0,this._until-e));if(t===0)this.reset();return t}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}}var Es="utf8",Xn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Qn(e){return typeof e=="string"&&Xn.test(e)}function te(e,t){return Qn(e)?e:t()}function he(e,t){let r=Error(t);try{Object.defineProperty(r,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function vs(e){return e?.replace(/\/+$/,"")}async function Ss(e,t){let r=null;for(let s=0;s<t.retryCount+1;s++){if(s>0)await new Promise((i)=>setTimeout(i,t.retryDelay));try{return await e()}catch(i){if(r=i,!t.retryCheck(i))throw i}}throw r}function rr(){return new Date().toISOString()}function T(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}async function W(e,t,r){let s;try{return await Promise.race([e,new Promise((i,n)=>{s=T(()=>{try{r?.(),i()}catch(o){n(o)}},t)})])}finally{clearTimeout(s)}}var Fs=(e)=>e&&typeof e.then=="function";function Pe(e){return Promise.all(e.map((t)=>(t??Promise.resolve()).then((r)=>({status:"fulfilled",value:r}),(r)=>({status:"rejected",reason:r}))))}var sr,As,ws,pe;function xs(e){let{_posthogChunkIds:t,_debugIds:r}=globalThis;if(!t&&!r)return;let s=t?Object.keys(t):[],i=r?Object.keys(r):[];if(pe&&Ps(t,s,As)&&Ps(r,i,ws))return pe;As=t?{...t}:void 0,ws=r?{...r}:void 0,pe={},sr??={};let n=(o,l)=>{for(let a of o){let c=l[a];if(!c)continue;let u=sr?.[a];if(u){pe[u]=c;continue}let d=e(a);for(let h=d.length-1;h>=0;h--){let p=d[h]?.filename;if(p){pe[p]=c,sr[a]=p;break}}}};if(r)n(i,r);if(t)n(s,t);return pe}function Ps(e,t,r){if(!e||!r)return e===r;return t.length===Object.keys(r).length&&t.every((s)=>e[s]===r[s])}var ir=50,Jn=1000,Yn=100,Zn=4;class at{constructor(e,t,r=[]){this.coercers=e,this.stackParser=t,this.modifiers=r}buildFromUnknown(e,t={}){let s=t&&t.mechanism||{handled:!0,type:"generic"},n=this.buildCoercingContext(s,t,0).apply(e),o=this.buildParsingContext(t),l=this.parseStacktrace(n,o);return{$exception_list:this.convertToExceptionList(l,s),$exception_level:"error"}}async modifyFrames(e){for(let t of e)if(t.stacktrace&&t.stacktrace.frames&&L(t.stacktrace.frames))t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames);return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let r;if(e.cause!=null)r=this.parseStacktrace(e.cause,t);let s;if(e.stack!=""&&e.stack!=null)try{s=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)}catch{}return{...e,cause:r,stack:s,errors:e.errors?.map((i)=>this.parseStacktrace(i,t))}}applyChunkIds(e,t){return e.map((r)=>{if(r.filename&&t)r.chunk_id=t[r.filename];return r})}applyCoercers(e,t){for(let r of this.coercers)if(r.match(e))return r.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let r of this.modifiers)t=await r(t);return t}convertToExceptionList(e,t){let r=[],s=(i,n,o)=>{let l=r.length,a=n===void 0?{type:typeof t.type=="string"&&t.type.length>0?t.type:"generic",...typeof t.handled=="boolean"?{handled:t.handled}:t.handled===void 0?{handled:!0}:{},synthetic:typeof t.synthetic=="boolean"?t.synthetic:i.synthetic,exception_id:l}:{type:"chained",source:o,synthetic:i.synthetic,exception_id:l,parent_id:n},c={type:i.type,value:i.value,mechanism:a};if(i.stack)c.stacktrace={type:"raw",frames:i.stack};if(r.push(c),i.cause)s(i.cause,l,"cause");for(let u of i.errors??[])s(u,l,"member")};return s(e),r}buildParsingContext(e){return{chunkIdMap:xs(this.stackParser),skipFirstLines:e.skipFirstLines??1}}getAggregateErrors(e){try{if(H(e)){let t=Object.getPrototypeOf(e);for(let r=0;t&&r<Yn;r++){let s=Object.getOwnPropertyDescriptor(t,"constructor")?.value;if(typeof s=="function"&&s.name==="AggregateError"){let i=e.errors;return L(i)?i:void 0}t=Object.getPrototypeOf(t)}}}catch{}}buildCoercingContext(e,t,r=0){let s=0,i=0,n=!1,o=new Set,l=[],a={},c=(h,p,f=0)=>{let g=u(p,f),m=g.apply;if(g.apply=(S)=>{l.push(h);try{return m(S)}finally{l.pop()}},f>Zn||f>0&&l.indexOf(h)!==-1)return this.coerceFallback(g);let b=typeof h=="object"&&h!==null||typeof h=="function";if(f===0&&s>=ir||b&&o.has(h))return;if(b)o.add(h);if(f===0)s++;let v=this.getAggregateErrors(h);n||=!!v;let E;try{if(E=this.applyCoercers(h,g),!E)throw a}catch(S){if(S===a){if(f===0)s--;return}if(!n)throw S;E=this.coerceFallback(g)}if(!v||s>=ir)return E;let A;try{A=v.length}catch{return E}if(!Number.isInteger(A)||A<0||A>4294967295)return E;let x=[];for(let S=0;s<ir&&i<Jn&&S<A;S++){i++;let _;try{_=g.next(v[S])}catch{s++,_=this.coerceFallback(u(p+1))}if(_)x.push(_)}return{...E,errors:x}},u=(h,p=0)=>({...t,syntheticException:h==0?t.syntheticException:void 0,mechanism:h==0?e:{},apply:(f)=>{let g=c(f,h,p+1);if(!g)throw a;return g},next:(f)=>c(f,h+1)}),d=u(r);return{...d,apply:(h)=>c(h,r)??this.coerceFallback(d)}}}var C="?",eo="<anonymous>",to=/^([a-z][a-z0-9.+-]+):/i,ro=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function so(e){if(!e||e===eo)return!1;let t=to.exec(e);return!t||ro.includes(t[1].toLowerCase())}function re(e,t,r,s,i){let n={platform:e,filename:t,function:r==="<anonymous>"?C:r,in_app:so(t)};if(!q(s))n.lineno=s;if(!q(i))n.colno=i;return n}var lt=(e,t)=>{let r=e.indexOf("safari-extension")!==-1,s=e.indexOf("safari-web-extension")!==-1;return r||s?[e.indexOf("@")!==-1?e.split("@")[0]:C,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var io=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,no=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,oo=/\((\S*)(?::(\d+))(?::(\d+))\)/,Is=(e,t)=>{let r=io.exec(e);if(r){let[,i,n,o]=r;return re(t,i,C,+n,+o)}let s=no.exec(e);if(s){if(s[2]&&s[2].indexOf("eval")===0){let l=oo.exec(s[2]);if(l)s[2]=l[1],s[3]=l[2],s[4]=l[3]}let[n,o]=lt(s[1]||C,s[2]);return re(t,o,n,s[3]?+s[3]:void 0,s[4]?+s[4]:void 0)}};var ao=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,lo=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Ts=(e,t)=>{let r=ao.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let o=lo.exec(r[3]);if(o)r[1]=r[1]||"eval",r[3]=o[1],r[4]=o[2],r[5]=""}let i=r[3],n=r[1]||C;return[n,i]=lt(n,i),re(t,i,n,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var co=/^\s*[-]{4,}$/,uo=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,fo=/^Promise\.(?:all|any)$/,ho=/^index \d+$/,po="node:internal/promise",Cs=(e,t)=>{let r=e.match(uo);if(r){let s,i,n,o,l;if(r[1]){n=r[1];let u=n.lastIndexOf(".");if(n[u-1]===".")u--;if(u>0){s=n.slice(0,u),i=n.slice(u+1);let d=s.indexOf(".Module");if(d>0)n=n.slice(d+1),s=s.slice(0,d)}o=void 0}if(i)o=s,l=i;if(i==="<anonymous>")l=void 0,n=void 0;if(n===void 0)l=l||C,n=o?`${o}.${l}`:l;let a=r[2]?.startsWith("file://")?r[2].slice(7):r[2],c=r[5]==="native";if(a?.match(/\/[A-Z]:/))a=a.slice(1);if(!a&&r[5]&&!c)a=r[5];if(fo.test(n)&&ho.test(a||""))a=po;return{filename:a?decodeURI(a):void 0,module:void 0,function:n,lineno:Rs(r[3]),colno:Rs(r[4]),in_app:go(a||"",c),platform:t}}if(e.match(co))return{filename:e,platform:t}};function go(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 Rs(e){return parseInt(e||"",10)||void 0}var Os=/\(error: (.*)\)/,Ls=50,mo=10,_o=1000;function nr(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function yo(e){for(let t=1;t<=mo;t++){let r=e.length-2*t;if(r<0)break;let s=!0;for(let i=0;i<t;i++){let n=e[r+i];if(!nr(n,e[r+t+i])){s=!1;break}}if(s){for(let i=0;i<t;i++)e[r+i]=e[r+t+i];return e.length=r+t,{start:r,length:t}}}}function bo(e,t){let r=t.start+t.length,s=Ms(e,t);if(s)e.splice(r+s===e.length?r:t.start,s)}function Ns(e,t){let r=t.start;while(r>0&&nr(e[r-1],e[r-1+t.length]))r--;return t.start-r}function Ms(e,t){let r=t.start+t.length,s=r;while(s<e.length&&nr(e[s],e[s-t.length]))s++;return s-r}function Eo(e,t){let r=t[0],s=e.length-(r?Ns(e,r):0);for(let i of t)s-=Ms(e,i);return s}function vo(e){let t=e.map((s)=>`${s.function}|${s.filename}|${s.lineno}|${s.colno}|${s.module}`),r=0;for(let s=1;s<t.length;s++)if(So(t,s,r))r=s;e.push(...e.splice(0,r))}function So(e,t,r){for(let s=0;s<e.length;s++){let i=e[(t+s)%e.length],n=e[(r+s)%e.length];if(i!==n)return i<n}return!1}function Fo(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,Ls).map((r)=>({...r,filename:r.filename||Ao(t).filename,function:r.function||C}))}function Ao(e){return e[e.length-1]||{}}function Ds(){return $s("web:javascript",Is,Ts)}function $s(e,...t){return(r,s=0)=>{let i=[],n=r.split(`
2
+ `),o=Math.min(n.length,s+_o),l=[];for(let u=s;u<o;u++){let d=n[u];if(d.length>1024)continue;let h=Os.test(d)?d.replace(Os,"$1"):d;if(!h.match(/\S*Error: /)){for(let p of t){let f=p(h,e);if(f){i.push(f);let g=yo(i);if(g){for(let m=l.length-1;m>=0;m--){let b=l[m];if(b.start+b.length<=g.start)break;l.pop()}l.push(g)}break}}if(Eo(i,l)>=Ls)break}}let a=[...l].sort((u,d)=>d.start-u.start),c=a[a.length-1];if(c){let u=Ns(i,c);i.splice(c.start-u,u);for(let d of a)d.start-=u}for(let u of a)bo(i,u);if(l.some((u)=>u.start===0&&i.length===u.length))vo(i);return Fo(i)}}class ct{match(e){return H(e)}coerce(e,t){let r=this.getStack(e),s=r===void 0?t.syntheticException?.stack:void 0,i=!!s;return{type:this.getType(e),value:this.getMessage(e,t),stack:r??s,cause:e.cause?t.next(e.cause):void 0,synthetic:i}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let r=e.message;if(r.error&&typeof r.error.message=="string")return String(r.error.message);return String(r)}getStack(e){try{let t=e.stacktrace;if(typeof t=="string"&&t.length>0)return t;let r=e.stack;return typeof r=="string"&&r.length>0?r:void 0}catch{return}}}var wo=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class ut{match(e){return typeof e=="string"}coerce(e,t){let[r,s]=this.getInfos(e);return{type:r??"Error",value:s??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",r=e,s=e.match(wo);if(s)t=s[1],r=s[2];return[t,r]}}var ks=["fatal","error","warning","log","info","debug"];function dt(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let s=r.length;s>0;s--){let i=r.slice(0,s).join(", ");if(!(i.length>t)){if(s===r.length)return i;return i.length<=t?i:`${i.slice(0,t)}...`}}return""}class ft{match(e){return typeof e=="object"&&e!==null}coerce(e,t){let r=this.getErrorPropertyFromObject(e);if(r)return t.apply(r);return{type:this.getType(e),value:this.getValue(e),stack:this.getStack(e)??t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(Fe(e))return e.constructor.name;let t="name"in e?e.name:void 0;return D(t)&&!zt(t)?t:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let s=`'${e.name}' captured as exception`;if("message"in e&&typeof e.message=="string")s+=` with message: '${e.message}'`;return s}if("message"in e&&typeof e.message=="string")return e.message;let t=this.getObjectClassName(e),r=dt(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${r}`}isSeverityLevel(e){return D(e)&&!zt(e)&&ks.indexOf(e)>=0}getStack(e){try{if(D(e.stacktrace)&&e.stacktrace.length>0)return e.stacktrace;return D(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(H(r))return r}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(t){return}}}class Us{match(e){return Fe(e)}coerce(e,t){let r=e.constructor.name;return{type:r,value:`${r} captured as exception with keys: ${dt(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class ht{match(e){return Gt(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class or{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(t===void 0)return;return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){while(this._cache.size>=this._maxSize){let e=this._cache.keys().next().value;if(e)this._cache.delete(e)}}}var Bs={MESSAGE:"$message",TIMESTAMP:"$timestamp"},md=new Set([Bs.MESSAGE,Bs.TIMESTAMP]);function js(){if("u">typeof process){let t=process.env.POSTHOG_RELEASE_ID?.trim();if(t)return t}let e=globalThis._posthogReleaseId;return typeof e=="string"&&e.length>0?e:void 0}var ar=(e)=>{if("flags"in e){let t=Vs(e.flags),r=zs(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,n])=>[i,ge(n)])),s=Object.fromEntries(Object.entries(t).map(([i,n])=>[i,xo(i,n,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:s}}};function xo(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 Vs=(e)=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,Ie(r)]).filter(([,t])=>t!==void 0)),zs=(e)=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter((r)=>{let s=t[r];return s.enabled&&s.metadata&&s.metadata.payload!==void 0}).map((r)=>{let s=t[r].metadata?.payload;return[r,s?ge(s):void 0]}))},Ie=(e)=>e===void 0?void 0:e.variant??e.enabled,ge=(e)=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var qs=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","bfcid","irclid","_kx"],Io=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain",...qs,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Te=(e,t=[])=>{let r={},s=(i)=>{if(e[i]!==void 0)r[i]=e[i]};return Io.forEach(s),t.forEach(s),r};class lr{constructor(){this.events={},this.events={}}on(e,t){if(!this.events[e])this.events[e]=[];return this.events[e].push(t),()=>{this.events[e]=this.events[e].filter((r)=>r!==t)}}emit(e,t){for(let r of this.events[e]||[])r(t);for(let r of this.events["*"]||[])r(e,t)}}function cr(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var Ro="NativeGzipValidationError",Co=31,Oo=139,Lo=8,No=(e)=>e.length>=2&&e[0]===Co&&e[1]===Oo;var Re,Mo=()=>{if(Re)return Re;Re=[];for(let e=0;e<256;e++){let t=e;for(let r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;Re[e]=t>>>0}return Re},Do=(e)=>{let t=Mo(),r=4294967295;for(let s=0;s<e.length;s++)r=t[(r^e[s])&255]^r>>>8;return(4294967295^r)>>>0},pt=(e)=>{throw he(Ro,`Native gzip produced invalid output: ${e}`)},$o=async(e,t)=>{if(e.size<18)pt("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());if(!No(r)||r[2]!==Lo)pt("invalid-header");let s=new DataView(await e.slice(e.size-8).arrayBuffer());if(s.getUint32(0,!0)!==Do(t))pt("invalid-crc");let i=t.length>>>0;if(s.getUint32(4,!0)!==i)pt("invalid-size")};async function Ce(e,t=!0,r){try{let s=new TextEncoder().encode(e),i=new globalThis.CompressionStream("gzip"),n=i.writable.getWriter(),o=n.write(s).then(()=>n.close()).catch(async(c)=>{try{await n.abort(c)}catch{}throw c}),l=new Response(i.readable).blob(),[a]=await Promise.all([l,o]);return await $o(a,s),a}catch(s){if(r?.rethrow)throw s;if(t)console.error("Failed to gzip compress data",s);return null}}class B extends Error{constructor(e,t,r,s){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.responseBodyDeadline=r,this.abortController=s,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return tr(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let e=he("AbortError","Response body read timed out");this.cancelResponseBody(e),this.responseBodyTextPromise=Promise.reject(e)}else{let e=new Promise((r,s)=>{this.responseBodyTimer=T(()=>{this._bodyReadTimedOut=!0;let i=he("AbortError","Response body read timed out");s(i),this.cancelResponseBody(i)},this.responseBodyDeadline-Date.now())}),t;try{t=Promise.resolve(this.response.text())}catch(r){t=Promise.reject(r)}this.responseBodyTextPromise=Promise.race([t,e]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then((e)=>JSON.parse(e))}cancelResponseBody(e){if(clearTimeout(this.responseBodyTimer),!this.abortController.signal.aborted)this.abortController.abort(e);(async()=>{try{await this.response.body?.cancel()}catch{}})()}}class X extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}var ko=(e,t)=>{for(let r of Object.keys(t))if(r.startsWith("$feature/")||r==="$active_feature_flags")e[r]=t[r]};async function Gs(e){if(e instanceof B){let t="";try{t=await e.text}catch{if(e.bodyReadTimedOut)t="<response body read timed out>"}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function Uo(e){return typeof e=="object"&&(e instanceof B||Xs(e))}function Xs(e){return e instanceof X}function Bo(e){if(e instanceof B)return e.status===502||e.status===504;if(!(e instanceof X))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}var Ks=10485760;function Hs(e){try{if(typeof e!="string")return e instanceof Uint8Array?e.byteLength:e.size;if("u">typeof Buffer)return Buffer.byteLength(e,Es);return new TextEncoder().encode(e).length}catch{return 0}}function me(e){return typeof e=="object"&&e instanceof B&&e.status===413}function gt(e){if(e instanceof B)return e.status===408||e.status===429||e.status>=500;return Xs(e)}function Ws(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var ur="default";class mt{getErrorPropertiesBuilder(){if(!this._errorPropertiesBuilder)this._errorPropertiesBuilder=this.createErrorPropertiesBuilder();return this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new at([new ct,new ft,new ut,new ht],Ds())}getEvaluationRuntime(){}get apiKey(){return this.projectToken}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new Wt,this._events=new lr,this._isInitialized=!1;let r=typeof e=="string"?e.trim():"",s=typeof t.host=="string"?t.host.trim():"",i=!r;if(this._logger=ns("[PostHog]",this.logMsgIfDebug.bind(this)),i)this._logger.error("You must pass your PostHog project token. The client will be disabled.");if(this.projectToken=r,this.host=vs(s||"https://us.i.posthog.com"),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1000),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3000,retryCheck:gt},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3000,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3000,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||i,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts)this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.");this.disableCompression=!cr()||(t?.disableCompression??!1)}logMsgIfDebug(e){if(this.isDebug)e()}wrap(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return e();this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(R.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(R.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(R.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let t=this.on("*",(r,s)=>this._logger.info(r,s));this.removeDebugCallback=()=>{t(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},r=this.mergeCommonEventProperties(t);if(ko(r,t),e.event==="$feature_flag_called"&&r.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled())r=Te(r);return{distinct_id:e.distinct_id,event:e.event,properties:r}}mergeCommonEventProperties(e){return{...e,...this.getCommonEventProperties()}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,r){this.wrap(()=>{let s={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",s,r)})}async identifyStatelessImmediate(e,t,r){let s={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",s,r)}captureStateless(e,t,r,s){this.wrap(()=>{let i=this.buildPayload({distinct_id:e,event:t,properties:r});this.enqueue("capture",i,s)})}async captureStatelessImmediate(e,t,r,s){let i=this.buildPayload({distinct_id:e,event:t,properties:r});await this.sendImmediate("capture",i,s)}aliasStateless(e,t,r,s){this.wrap(()=>{let i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});this.enqueue("alias",i,s)})}async aliasStatelessImmediate(e,t,r,s){let i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",i,s)}groupIdentifyStateless(e,t,r,s,i,n){this.wrap(()=>{let o=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...n||{}}});this.enqueue("capture",o,s)})}async groupIdentifyStatelessImmediate(e,t,r,s,i,n){let o=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...n||{}}});await this.sendImmediate("capture",o,s)}async getRemoteConfig(){await this._initPromise;let e=this.host;if(e==="https://us.i.posthog.com")e="https://us-assets.i.posthog.com";else if(e==="https://eu.i.posthog.com")e="https://eu-assets.i.posthog.com";let t=`${e}/array/${this.projectToken}/config`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,r,{type:"required",consume:(s)=>s.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch((s)=>{this._logger.error("Remote config could not be loaded",s),this._events.emit("error",s)})}async getFlags(e,t={},r={},s={},i={},n=!1){await this._initPromise;let o=n?"&config=true":"",l=`${this.host}/flags/?v=2${o}`,a={token:this.projectToken,distinct_id:e,groups:t,person_properties:r,group_properties:s,...i};if(r.$device_id)a.$device_id=r.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)a.evaluation_contexts=this.evaluationContexts;let c=this.getEvaluationRuntime();if(c)a.evaluation_runtime=c;let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(a)};return this._logger.info("Flags URL",l),this.fetchWithRetry(l,u,{type:"required",consume:(d)=>d.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:Bo},this.featureFlagsRequestTimeoutMs).then((d)=>({success:!0,response:ar(d)})).catch((d)=>(this._events.emit("error",d),{success:!1,error:this.categorizeRequestError(d)}))}categorizeRequestError(e){if(e instanceof B)return{type:"api_error",statusCode:e.status};if(e instanceof X){let t=e.error;if(t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError"))return{type:"timeout"};return{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,r={},s={},i={},n){await this._initPromise;let o=await this.getFeatureFlagDetailStateless(e,t,r,s,i,n);if(o===void 0)return{response:void 0,requestId:void 0};let l=Ie(o.response);if(l===void 0)l=!1;return{response:l,requestId:o.requestId}}async getFeatureFlagDetailStateless(e,t,r={},s={},i={},n){await this._initPromise;let o=await this.getFeatureFlagDetailsStateless(t,r,s,i,n,[e]);if(o===void 0)return;return{response:o.flags[e],requestId:o.requestId,evaluatedAt:o.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,r={},s={},i={},n){await this._initPromise;let o=await this.getFeatureFlagPayloadsStateless(t,r,s,i,n,[e]);if(!o)return;let l=o[e];if(l===void 0)return null;return l}async getFeatureFlagPayloadsStateless(e,t={},r={},s={},i,n){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,r,s,i,n)).payloads}async getFeatureFlagsStateless(e,t={},r={},s={},i,n){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,r,s,i,n)}async getFeatureFlagsAndPayloadsStateless(e,t={},r={},s={},i,n){await this._initPromise;let o=await this.getFeatureFlagDetailsStateless(e,t,r,s,i,n);if(!o)return{flags:void 0,payloads:void 0,requestId:void 0};return{flags:o.featureFlags,payloads:o.featureFlagPayloads,requestId:o.requestId}}async getFeatureFlagDetailsStateless(e,t={},r={},s={},i,n){await this._initPromise;let o={geoip_disable:i??this.disableGeoip};if(n)o.flag_keys_to_evaluate=n;let l=await this.getFlags(e,t,r,s,o);if(!l.success)return;let a=l.response;if(a.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");if(a.quotaLimited?.includes("feature_flags"))return 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:a?.requestId,quotaLimited:a.quotaLimited};return a}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.projectToken}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},s=(await this.fetchWithRetry(e,t,{type:"required",consume:(i)=>{if(i.status!==200||!i.json){let n=`Surveys API could not be loaded: ${i.status}`,o=Error(n);return this._logger.error(o),this._events.emit("error",Error(n)),Promise.resolve(void 0)}return i.json()}}).catch((i)=>{this._logger.error("Surveys API could not be loaded",i),this._events.emit("error",i)}))?.surveys;if(s)this._logger.info("Surveys fetched from API: ",JSON.stringify(s));return s??[]}get props(){if(!this._props)this._props=this.getPersistedProperty(R.Props);return this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(R.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(R.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return ur}persistedQueueKeyForRoute(e){return R.Queue}getActiveQueueRoutes(){return[ur]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,r,s){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,r);if(i=this.processBeforeEnqueue(i),i===null)return;i=this.normalizeMessage(i);let n=this.persistedQueueKeyForRoute(s??this.getQueueRouteKey(i)),o=this.getPersistedProperty(n)||[];if(o.length>=this.maxQueueSize)o.shift(),this._logger.warn("Queue is full, the oldest event is dropped.");if(o.push({message:i}),this.setPersistedProperty(n,o),this._events.emit(e,i),o.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=T(()=>this.flushBackground(),this.flushInterval)})}async sendImmediate(e,t,r,s){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this._isInitialized)await this._initPromise;if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,r);if(i=this.processBeforeEnqueue(i),i===null)return;i=this.normalizeMessage(i);try{await this.sendBatch([i],void 0,s??this.getQueueRouteKey(i))}catch(n){this._events.emit("error",n)}}normalizeMessage(e){let{type:t,library:r,library_version:s,...i}=e,n=Ws(i.properties)?i.properties:void 0;if(r!==void 0&&n?.$lib===void 0)n={...n||{},$lib:r};if(s!==void 0&&n?.$lib_version===void 0)n={...n||{},$lib_version:s};if(n)i.properties=n;return i.uuid=te(i.uuid,I),i}normalizeTimestampForWire(e){let t=e instanceof Date?e:typeof e=="string"?new Date(e):null;if(!t||Number.isNaN(t.getTime()))return e;let r=t.toISOString(),s=typeof e=="string"?e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return s&&s.length>3?r.replace(/\.\d{3}Z$/,`.${s}Z`):r}prepareMessage(e,t){let r={...e,timestamp:t?.timestamp?t?.timestamp:rr(),uuid:te(t?.uuid,I)};if(t?.disableGeoip??this.disableGeoip){if(!Ws(r.properties))r.properties={};r.properties.$geoip_disable=!0}if(r.distinctId)r.distinct_id=r.distinctId,delete r.distinctId;return r}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){if(this.pendingFlushPromise)return;this.flushAutomatic().catch(async(e)=>{await Gs(e)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(e,t=[]){let r=t.filter((i)=>!!i),s=0;while(!0){let i=this.promiseQueue.getPromises([...r,...this.flushPromises],e);if(i.length===0)return;if(s>0)this._logger.debug(`flush() re-checking ${i.length} pending promise(s) before flushing`);await Promise.all(i.map((n)=>n.catch(()=>{}))),s++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,r=this.promiseQueue.maxId,s=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(r,[t,s])}).then(()=>Pe([t])).then(()=>{if(this.pendingFlushPromise===s)this.pendingFlushPromise=null;return this._flush()});return this.pendingFlushPromise=s,this.flushPromise=s,this.flushPromises.add(s),this.addPendingPromise(s),Pe([s]).then(()=>{if(this.flushPromises.delete(s),this.pendingFlushPromise===s)this.pendingFlushPromise=null;if(this.flushPromise===s)this.flushPromise=null}),s}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};if(e&&e!=="")t["User-Agent"]=e;return t}compressPayload(e){return Ce(e,this.isDebug)}getBatchEndpointPath(e){return"/batch/"}async sendBatch(e,t,r=ur){let s={api_key:this.projectToken,batch:e.map((a)=>{if(!a)return a;let c=this.normalizeTimestampForWire(a.timestamp);return c===a.timestamp?a:{...a,timestamp:c}}),sent_at:rr()};if(this.historicalMigration)s.historical_migration=!0;let i=Z(s),n=`${this.host}${this.getBatchEndpointPath(r)}`,o=this.disableCompression?null:await this.compressPayload(i),l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...o!==null&&{"Content-Encoding":"gzip"}},body:o||i};await this.fetchWithRetry(n,l,{type:"successful-write"},t)}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getActiveQueueRoutes();if(!e.some((s)=>this.getRouteQueue(s).length>0))return;let t=[],r;for(let s of e)try{await this._flushRoute(s,t)}catch(i){if(r===void 0)r=i}if(r!==void 0)throw r;this._events.emit("flush",t)}async _flushRoute(e,t){let r=this.persistedQueueKeyForRoute(e),s=this.getPersistedProperty(r)||[];if(!s.length)return;let i=s.length,n=0;while(s.length>0&&n<i){let o=s.slice(0,this.maxBatchSize),l=o.map((u)=>u.message===void 0?u.message:this.normalizeMessage(u.message)),a=async()=>{let u=this.getPersistedProperty(r)||[],d=[...o],h=u.filter((p)=>{let f=p.message?.uuid,g=d.findIndex((m)=>m===p||typeof f=="string"&&f.length>0&&m.message?.uuid===f);if(g===-1)return!0;return d.splice(g,1),!1});this.setPersistedProperty(r,h),s=h,this._dequeuedMessagesCount+=o.length,await this.flushStorage()},c={retryCheck:(u)=>{if(me(u))return!1;return gt(u)}};try{await this.sendBatch(l,c,e)}catch(u){if(me(u)&&l.length>1){this.maxBatchSize=Math.max(1,Math.floor(l.length/2)),this._logger.warn(`Received 413 when sending batch of size ${l.length}, reducing batch size to ${this.maxBatchSize}`);continue}if(!(u instanceof X))await a();throw this._events.emit("error",u),u}await a(),t.push(...l),n+=l.length}}async _sendOtlpBatch({path:e,auth:t,payload:r}){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let s;try{s=JSON.stringify(r)}catch(c){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${e} batch; reporting it as too large`,c)),{kind:"too-large",measuredLocally:!0}}let i=Hs(s);if(i>Ks)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${e} batch of ${i} bytes: the endpoint accepts at most ${Ks}`)),{kind:"too-large",measuredLocally:!0};let n=t==="bearer"?`${this.host}/i/v1/${e}`:`${this.host}/i/v1/${e}?token=${encodeURIComponent(this.projectToken)}`,o=this.disableCompression?null:await this.compressPayload(s),l=o||s,a={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...t==="bearer"&&{Authorization:`Bearer ${this.projectToken}`},...o!==null&&{"Content-Encoding":"gzip"}},body:l};try{return await this.fetchWithRetry(n,a,{type:"successful-write"},{retryCheck:(c)=>{if(me(c))return!1;if(c instanceof B&&c.retryAfterMs!==void 0)return!1;return gt(c)}}),{kind:"ok"}}catch(c){if(me(c))return{kind:"too-large"};if(gt(c)){let u=c instanceof B?c.retryAfterMs:void 0;return{kind:"retry-later",error:c,...u!==void 0&&{retryAfterMs:u}}}return{kind:"fatal",error:c}}}async _sendLogsBatch(e){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:e})}async _sendMetricsBatch(e){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:e})}async _sendTracesBatch(e){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:e})}async fetchWithRetry(e,t,r,s,i){let n=t.body?t.body:"",o=Hs(n),l={...this._retryOptions,...s},a=0;return await Ss(async()=>{a++;let c=new AbortController,u=i??this.requestTimeout,d=Date.now()+u,h,p=new Promise((v,E)=>{h=T(()=>{let A=he("AbortError",`Request timed out after ${u}ms`);E(A),c.abort(A)},u)}),f,g=!1,m,b=()=>m??=(async()=>{try{await f?.body?.cancel()}catch{}})();try{let v;try{v=this.fetch(e,{signal:c.signal,...t})}catch(x){throw new X(x)}v.then((x)=>{if(c.signal.aborted&&!g)Promise.resolve(x.body?.cancel()).catch(()=>{})}).catch(()=>{});try{f=await Promise.race([v,p]),g=!0}catch(x){throw new X(x)}let E=t.mode==="no-cors",A=r.type==="successful-write"?300:400;if(!E&&(f.status<200||f.status>=A))throw new B(f,o,d,c);if(r.type==="successful-write"){try{await Promise.race([b(),p])}catch{}return}try{return await Promise.race([r.consume(f),p])}catch(x){if(c.signal.aborted)throw new X(x);throw x}}finally{if(clearTimeout(h),c.signal.aborted&&f)b()}},{...l,retryCheck:(c)=>{let u=l.retryCheck(c);if(u&&a<=l.retryCount&&c instanceof B)c.cancelResponseBody();return u}})}async _shutdown(e=30000){await this._initPromise;let t=!1;if(this.clearFlushTimer(),this.disabled)return;return W((async()=>{try{await this.promiseQueue.join();while(!0){if(!this.getActiveQueueRoutes().some((n)=>this.getRouteQueue(n).length>0))break;let i=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===i){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(s){if(!Uo(s))throw s;await Gs(s)}})(),e,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:e}),t=!0})}async shutdown(e=30000){if(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");else this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null});return this.shutdownPromise}}var Go=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var ef=new RegExp(Go.source,"i"),Qs=/[a-z][a-z0-9+.-]{0,63}:\/\//i,tf=new RegExp(`^${Qs.source}`,"i"),rf=new RegExp(Qs.source,"gi");var Ko=["exact","is_not","icontains","not_icontains","starts_with","not_starts_with","ends_with","not_ends_with","regex","not_regex"],Ho=1152921504606847000;class y extends Error{constructor(e,t="unsupported_definition"){super(e);this.name=this.constructor.name,this.reason=t,Object.setPrototypeOf(this,y.prototype)}}function _e(e){try{return e()}catch(t){if(t instanceof y)throw new y(t.message,"missing_context");throw t}}function fr(e){if(typeof e=="boolean")return!0;if(typeof e=="string"){let t=e.toLowerCase();return t==="true"||t==="false"}if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!fr(t in e?e[t]:null))return!1;return!0}function hr(e){if(typeof e=="boolean")return e;if(typeof e=="string")return e.toLowerCase()==="true";if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!hr(t in e?e[t]:null))return!1;return!0}function Ne(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let s=e.charCodeAt(t+1);if(t+1>=e.length||s<56320||s>57343)throw new y("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new y("Cannot stringify an unpaired surrogate like the flags service")}}function _t(e,t=new Set){if(e===null||typeof e=="boolean")return;if(typeof e=="string")return void Ne(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new y(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new y("Cannot represent a circular array during local evaluation");t.add(e);try{for(let r=0;r<e.length;r++)if(r in e)_t(e[r],t)}finally{t.delete(e)}return}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new y("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new y("Cannot represent a circular object during local evaluation");t.add(e);try{for(let s of Object.keys(e))Ne(s),_t(e[s],t)}finally{t.delete(e)}return}throw new y(`Cannot represent ${typeof e} like the flags service`)}function Wo(e,t){let r=0,s=0;while(r<e.length&&s<t.length){let i=e.charCodeAt(r),n=t.charCodeAt(s),o=i>=55296&&i<=56319,l=n>=55296&&n<=56319,a=o?e.charCodeAt(r+1):0,c=l?t.charCodeAt(s+1):0,u=o?(i-55296)*1024+a-56320+65536:i,d=l?(n-55296)*1024+c-56320+65536:n;if(u!==d)return u-d;r+=o?2:1,s+=l?2:1}return e.length-t.length}function pr(e,t=new Set){if(e===null)return"null";if(typeof e=="string")return Ne(e),JSON.stringify(e);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(!Number.isFinite(e))throw new y(`Cannot stringify non-finite number ${e} like the flags service`);if(Number.isInteger(e))throw new y(`Cannot distinguish integer ${e} from an integral JSON float during local evaluation`);return String(e)}if(Array.isArray(e)){if(t.has(e))throw new y("Cannot stringify a circular array during local evaluation");t.add(e);try{let r=[];for(let s=0;s<e.length;s++)r.push(s in e?pr(e[s],t):"null");return`[${r.join(",")}]`}finally{t.delete(e)}}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new y("Cannot stringify a non-JSON object like the flags service");if(t.has(e))throw new y("Cannot stringify a circular object during local evaluation");t.add(e);try{let s=Object.keys(e);return s.forEach(Ne),`{${s.sort(Wo).map((i)=>`${JSON.stringify(i)}:${pr(e[i],t)}`).join(",")}}`}finally{t.delete(e)}}throw new y(`Cannot stringify ${typeof e} like the flags service`)}function Le(e){if(typeof e=="string")return Ne(e),e;return pr(e)}var Xo=/[\x20-\x2f:;=?@\x5b-\x60\x7b-\x7e]/;function Qo(e){let t=[],r=-1,s="";for(let i=0;i<e.length;i++){let n=e[i];if(n.charCodeAt(0)>127)return null;if(n==="\\"){let o=e[++i];if(o===void 0)break;if(o==="x"){if(!/^[\da-f]{2}$/i.test(e.slice(i+1,i+3)))return null;i+=2}else if(!"dDsSwWbBfnrtv".includes(o)&&!Xo.test(o))return null;if(r===-1&&"bB".includes(o))return null;s="literal";continue}if(n==="["){if(r!==-1)return null;r=i}else if(n==="]"&&r!==-1){let o=r+(e[r+1]==="^"?2:1);if(i===o)return null;t.push(e.slice(r,i+1)),r=-1,s="literal";continue}else if(r!==-1){if(["&&","--","~~"].includes(e.slice(i,i+2)))return null;continue}else if(n==="("&&e[i+1]==="?"){if(e[i+2]!==":")return null;i+=2}else if(n==="{"){let o=/^\{(\d+)(?:,(\d*))?\}/.exec(e.slice(i));if(!o||["","|","("].includes(s)||o.slice(1).some((l)=>Number(l)>4294967295))return null}else if("*+?}".includes(n)&&(e[i+1]==="+"||e[i+1]==="{"))return null;if("*+?{".includes(n)&&["^","$","empty group"].includes(s))return null;s=n===")"&&["(","empty group"].includes(s)?"empty group":n}return t}function Oe(e){let t=new y(e);return Object.defineProperty(t,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),t}function Jo(e,t){if(e==="")return!0;let r=Qo(e);if(r===null)throw Oe("Regex syntax requires server evaluation");let s;try{s=new RegExp(e)}catch(i){if(i instanceof SyntaxError)return null;throw Oe("Regex compilation requires server evaluation")}for(let i of r)try{new RegExp(i,"u")}catch{throw Oe("Regex character class syntax requires server evaluation")}for(let i=0;i<t.length;i++){let n=t[i];if(n.charCodeAt(0)>127||n==="\r")throw Oe("Regex matching for Unicode or carriage returns requires server evaluation")}try{return s.test(t)}catch{throw Oe("Regex execution requires server evaluation")}}function N(e){return String(e).replace(/[A-Z]/g,(t)=>t.toLowerCase())}function Js(e,t,r){if(!/^\d+$/.test(e)||r==="strict"&&e.length>1&&e[0]==="0")throw new y(`Invalid semver: ${t}`);return parseInt(e,10)}function se(e,t="strict"){let s=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!s||s.startsWith("."))throw new y(`Invalid semver: ${e}`);let i=s.split("."),n=(o)=>{if(o===void 0||o==="")return 0;return Js(o,e,t)};return[n(i[0]),n(i[1]),n(i[2])]}function dr(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}function Ys(e,t){let r=se(e,t);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function Zs(e,t){let[r,s,i]=se(e,t),n=[r,s,i],o;return o=r>0?[r+1,0,0]:s>0?[0,s+1,0]:[0,0,i+1],{lower:n,upper:o}}function ei(e,t){let s=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!s)throw new y(`Invalid wildcard semver: ${e}`);let i=s.split("."),n=(a)=>{if(t==="legacy-permissive"){let c=parseInt(a,10);if(!isNaN(c))return c}else try{return Js(a,e,t)}catch{}throw new y(`Invalid wildcard semver: ${e}`)},o=n(i[0]);if(i.length===1)return{lower:[o,0,0],upper:[o+1,0,0]};let l=n(i[1]);return{lower:[o,l,0],upper:[o,l+1,0]}}function ti(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 y(`${e} is in an invalid date format`)}throw new y(`The date provided ${e} must be a string, number, or date object`)}function gr(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),s=new Date(new Date().toISOString());if(!r||!r.groups)return null;let i=parseInt(r.groups.number);if(i>=1e4)return null;let n=r.groups.interval;if(n==="h")s.setUTCHours(s.getUTCHours()-i);else if(n==="d")s.setUTCDate(s.getUTCDate()-i);else if(n==="w")s.setUTCDate(s.getUTCDate()-7*i);else if(n==="m")s.setUTCMonth(s.getUTCMonth()-i);else{if(n!=="y")return null;s.setUTCFullYear(s.getUTCFullYear()-i)}return s}function ri(e){if(typeof e=="boolean")throw new y("Date operations cannot be performed on boolean values");return gr(String(e))??ti(e)}function Me(e,t={}){let r=e.value,s=t.semverParsingPolicy??"strict";switch(e.operator||"exact"){case"exact":case"is_not":for(let i of Array.isArray(r)?r:[r])Le(i);return;case"is_set":case"is_not_set":case"icontains":case"not_icontains":case"starts_with":case"not_starts_with":case"ends_with":case"not_ends_with":case"regex":case"not_regex":case"gt":case"gte":case"lt":case"lte":return;case"is_date_after":case"is_date_before":ri(r);return;case"semver_eq":case"semver_neq":case"semver_gt":case"semver_gte":case"semver_lt":case"semver_lte":se(String(r),s);return;case"semver_tilde":Ys(String(r),s);return;case"semver_caret":Zs(String(r),s);return;case"semver_wildcard":ei(String(r),s);return;default:throw new y(`Unknown operator: ${e.operator}`)}}function mr(e,t,r={}){try{return Yo(e,t,r)}catch(s){if(s instanceof y&&s.reason==="missing_context")Me(e,r);throw s}}function Yo(e,t,r){let{key:s,value:i}=e,n=e.operator||"exact",o=r.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(t,s)){if(n==="is_not_set")return!1;else if(n==="is_set")return!0}else throw new y(`Property ${s} not found in propertyValues`,"missing_context");let a=t[s];if(a===void 0)throw r.warnFunction?.(`Property ${s} cannot have a value of undefined with the ${n} operator`),new y(`Property ${s} is undefined in propertyValues`);if(a===null&&!Ko.includes(n))return r.warnFunction?.(`Property ${s} cannot have a value of null with the ${n} operator`),!1;let c=(f,g)=>{if(r.propertyMatchingVersion!==2&&fr(f)||Array.isArray(f)&&f.length===0)return _e(()=>_t(g)),hr(f)===hr(g);if(r.propertyMatchingVersion===2&&typeof g=="number"&&fr(f))return _e(()=>_t(g)),!1;if(Array.isArray(f)){let b=_e(()=>Le(g)).toLowerCase();return f.some((v)=>Le(v).toLowerCase()===b)}return Le(f).toLowerCase()===_e(()=>Le(g)).toLowerCase()},u=(f,g,m)=>{if(m==="gt")return f>g;if(m==="gte")return f>=g;if(m==="lt")return f<g;if(m==="lte")return f<=g;throw Error(`Invalid operator: ${m}`)},d=()=>_e(()=>se(String(a),o)),h=()=>{let f=se(String(i),o);return dr(d(),f)},p=({lower:f,upper:g})=>{let m=d();return dr(m,f)>=0&&dr(m,g)<0};switch(n){case"exact":return c(i,a);case"is_not":return!c(i,a);case"is_set":return!0;case"icontains":return N(a).includes(N(i));case"not_icontains":return!N(a).includes(N(i));case"starts_with":return N(a).startsWith(N(i));case"not_starts_with":return!N(a).startsWith(N(i));case"ends_with":return N(a).endsWith(N(i));case"not_ends_with":return!N(a).endsWith(N(i));case"regex":case"not_regex":{let f=Jo(String(i),String(a));if(f===null)return!1;return n==="regex"?f:!f}case"gt":case"gte":case"lt":case"lte":{let f=typeof i=="number"?i:parseFloat(String(i)),g=typeof a=="number"?a:a!=null?parseFloat(String(a)):NaN;if(Number.isFinite(f)&&Number.isFinite(g))return u(g,f,n);return u(String(a),String(i),n)}case"is_date_after":case"is_date_before":{let f=ri(i),g=_e(()=>ti(a));return n==="is_date_before"?g<f:g>f}case"semver_eq":return h()===0;case"semver_neq":return h()!==0;case"semver_gt":return h()>0;case"semver_gte":return h()>=0;case"semver_lt":return h()<0;case"semver_lte":return h()<=0;case"semver_tilde":return p(Ys(String(i),o));case"semver_caret":return p(Zs(String(i),o));case"semver_wildcard":return p(ei(String(i),o));default:throw new y(`Unknown operator: ${n}`)}}async function si(e){let t=globalThis.crypto?.subtle;if(!t)throw Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map((s)=>s.toString(16).padStart(2,"0")).join("")}async function ye(e,t,r="",s="."){let i=await si(`${e}${s}${t}${r}`);return parseInt(i.slice(0,15),16)/Ho}async function _r(e,t){if(e==null||e.id==null||e.exclusion_percentage==null)return;let r=Number(e.exclusion_percentage);if(!Number.isFinite(r))return;let s=Math.min(Math.max(r,0),100);if(s!==100){if(await ye("holdout",t,"","-")>s/100)return}return`holdout-${e.id}`}function yt(e){let t=[],r=0;for(let s of e){let i=r+s.rollout_percentage/100;t.push({valueMin:r,valueMax:i,key:s.key}),r=i}return t}async function yr(e,t,r){let s=await ye(e,t,"variant");return yt(r).find((i)=>s>=i.valueMin&&s<i.valueMax)?.key}function br(e,t){if(t===!1||t==null||!e)return null;let r=typeof t=="boolean"?t.toString():t,s=e[r]||null;return s==null?null:ge(s)}var ii=9223372036854776000,Zo="9223372036854775808",ea=Object.prototype.propertyIsEnumerable;function ta(){return{ancestors:new WeakSet,remainingNodes:it}}function V(e,t){try{return ni(e,t,ta(),0)}catch{return[]}}function ra(e,t){let r=e.toString(),s=BigInt(Zo);if(e>=s||e<-s)return t?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r};return{intValue:r}}function Er(e,t,r,s){if(r.remainingNodes<=0)return{stringValue:ot};if(r.remainingNodes--,Jr(e))return{boolValue:e};if(typeof e=="bigint")return ra(e,t);if(typeof e=="number"){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e)){if(Number.isSafeInteger(e))return{intValue:String(e)};if("u"<typeof BigInt)return{stringValue:String(e)};let i=BigInt(e).toString();if(e>=ii||e<-ii)return t?.debug(`Attribute ${i} is outside the int64 range; encoding it as a string`),{stringValue:i};return{intValue:i}}return{doubleValue:e}}if(typeof e=="string")return{stringValue:j(e)};if(typeof e=="function")return{stringValue:bs};if(typeof e=="symbol")return{stringValue:String(e)};if(typeof e=="object"&&e!==null){if(r.ancestors.has(e))return{stringValue:nt};if(s>=st)return{stringValue:ot};if(e instanceof Date){let i=e.getTime(),n=Number.isFinite(i)?e.toISOString():String(e);return{stringValue:typeof n=="string"?j(n):String(n)}}r.ancestors.add(e);try{try{let i=e.toJSON;if(typeof i=="function")return Er(i.call(e),t,r,s+1)}catch{}if(L(e))return{arrayValue:{values:sa(e,t,r,s+1)}};return{kvlistValue:{values:ni(e,t,r,s+1)}}}finally{r.ancestors.delete(e)}}return{stringValue:j(String(e))}}function sa(e,t,r,s){let i=[],n=Math.min(e.length,de),o=0;for(;o<n&&r.remainingNodes>0;o++)try{let l=o in e?e[o]:void 0;if(k(l))continue;i.push(Er(l,t,r,s))}catch{i.push({stringValue:U})}if(e.length>o)i.push({stringValue:ot});return i}function ni(e,t,r,s){let i=[];for(let n in e)if(ea.call(e,n)){if(!n){t?.debug("Dropping an attribute with an empty key");continue}if(i.length>=de||r.remainingNodes<=0){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let o=e[n];if(qt(o)||q(o))continue;i.push({key:j(n),value:Er(o,t,r,s)})}catch{i.push({key:j(n),value:{stringValue:U}})}}return i}function De(e,t,r){return{...G({},e.resourceAttributes),"service.name":e.serviceName||"unknown_service",...e.environment&&{"deployment.environment":e.environment},...e.serviceVersion&&{"service.version":e.serviceVersion},"telemetry.sdk.name":t,"telemetry.sdk.version":r}}var ia=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function $e(e,t){let r=G({},e),s={};for(let i of ia)if(Object.prototype.hasOwnProperty.call(r,i))s[i]=r[i],delete r[i];return[...V(r,t),...V(s,t)]}var oi={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"};function na(e){if(!e)return;return Object.prototype.hasOwnProperty.call(oi,e)?oi[e]:e}function vr(e,t){let r=na(e);return{...r?{"os.name":r}:{},...t?{"os.version":t}:{}}}var oa={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},bf=oa.info;class be{constructor(e){this._onFire=e,this._firesAt=0}get pending(){return!!this._timer}arm(e){this.clear(),this._firesAt=Date.now()+e,this._timer=T(()=>{this._timer=void 0,this._onFire()},e)}armNoEarlierThan(e){if(this._timer&&Date.now()+e<=this._firesAt)return;this.arm(e)}clear(){if(this._timer)clearTimeout(this._timer),this._timer=void 0}}var ke=30000;function Ue(){return 0.75+Math.random()*0.25*2}var M=1;function Be(e,t,r,s){let i=Math.min(Math.max(0,t-1),6),n=e*2**i,o=s===void 0?n:Math.min(n,Math.max(s,e));return Math.round(o*r)}var ua="00000000000000000000000000000000",da=/^[0-9a-f]+$/;function fa(e){let t=new Uint8Array(e),r=globalThis.crypto;if(r&&typeof r.getRandomValues=="function")try{return r.getRandomValues(t),t}catch{}for(let s=0;s<e;s++)t[s]=Math.floor(256*Math.random());return t}function ha(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}function ai(e){let t=ha(fa(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function li(){return ai(16)}function ci(){return ai(8)}function ui(e,t,r){return typeof e=="string"&&e.length===t&&e!==r&&da.test(e)}function di(e){return ui(e,32,ua)}function fi(e){return ui(e,16,"0000000000000000")}var pa=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function bt(e){let t=hi(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:ga(t.flags)}}function ga(e){return 1&parseInt(e,16)?Ee:ma}function hi(e){if(typeof e!="string")return;let t=pa.exec(e.trim());if(!t)return;let[,r,s,i,n,o]=t;if(r==="ff")return;if(r==="00"&&o)return;if(!di(s)||!fi(i))return;return{version:r,traceId:s,spanId:i,flags:n}}function pi(e){return hi(e)&&e.trim()}function Et(e){return Array.isArray(e)&&e.length===1?e[0]:e}var Ee="01",ma="00";function gi(e,t,r=Ee){return`00-${e}-${t}-${r}`}var _a=32,Sr=512;function vt(e){if(typeof e!="string")return;let t=e.trim();if(!t)return;if(/[^\x20-\x7e\t]/.test(t))return;let r=t.split(",");if(r.length>_a)return;for(let s of r)if(s.trim()&&!s.includes("="))return;if(t.length<=Sr)return t;return ba(r)}var ya=128;function ba(e){let t=[...e],r=()=>t.reduce((s,i)=>s+i.length,0)+t.length-1;for(let s=t.length-1;s>=0&&r()>Sr;s--)if(t[s].length>ya)t.splice(s,1);while(t.length&&r()>Sr)t.pop();return t.length?t.join(","):void 0}var je=[0,5,10,25,50,75,100,250,500,750,1000,2500,5000,7500,1e4];function St(e){return String(e)+"000000"}function Fr(e,t,r,s){let i="";if(s)i=Object.keys(s).sort().map((o)=>`${JSON.stringify(o)}:${JSON.stringify(s[o])}`).join(",");return`${e}\x00${t}\x00${r??""}\x00${i}`}function mi(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function Ar(e,t,r){return De(e,t,r)}function wr(e,t,r,s){return{resourceMetrics:[{resource:{attributes:$e(t)},scopeMetrics:[{scope:{name:r,version:s},metrics:e}]}]}}function Ft(e){let t=e?.resourceAttributes;return{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1000}}var _i=1;class At{constructor(e,t,r){this._instance=e,this._config=t,this._logger=r,this._series=new Map,this._flushTimer=new be(()=>this.flush().catch((s)=>{this._logger.error("Metrics flush failed:",s)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new fe,this._consecutiveFlushFailures=0,this._flushJitter=M,this._generation=0}count(e,t=1,r){this._capture({name:e,type:"count",value:t,unit:r?.unit,attributes:r?.attributes})}gauge(e,t,r){this._capture({name:e,type:"gauge",value:t,unit:r?.unit,attributes:r?.attributes})}histogram(e,t,r){this._capture({name:e,type:"histogram",value:t,unit:r?.unit,attributes:r?.attributes})}flush(){let e=this._flushPromise,r=(async()=>{if(e)await e.catch(()=>{});await this._doFlush()})().finally(()=>{if(this._flushPromise===r)this._flushPromise=null});return this._flushPromise=r,r}drainWindow(){if(this._series.size===0)return null;let e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=M,this._flushTimer.clear(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){if(this._instance.isDisabled||this._instance.optedOut)return;let t=this._runBeforeSend(e);if(t===null)return;if(!t.name||typeof t.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof t.value!="number"||!Number.isFinite(t.value))return void this._logger.warn(`Dropping metric '${t.name}': value must be a finite number`);if(t.type==="count"&&t.value<0)return void this._logger.warn(`Dropping count '${t.name}': counters are monotonic, value must be >= 0`);let r,s;try{r=t.attributes?{...t.attributes}:void 0,s=Fr(t.type,t.name,t.unit,r)}catch(l){this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,l);return}let i=this._series.get(s);if(!i){if(!this._admitNewSeries())return;i={name:t.name,type:t.type,unit:t.unit,attributes:r,windowStartMs:Date.now()},this._series.set(s,i)}let n=this._typeByName.get(t.name);if(n===void 0)this._typeByName.set(t.name,t.type);else if(n!==t.type&&!this._typeCollisionWarned.has(t.name))this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${n}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`);this._fold(i,t.value);let o=this._activeTraceContext();if(o)i.exemplar={...o,value:t.value,timeMs:Date.now()};this._armFlushTimer()}_activeTraceContext(){try{let e=bt(this._instance.getActiveSpan?.()?.traceparent());if(e&&e.flags===Ee)return{traceId:e.traceId,spanId:e.spanId}}catch{}}_admitNewSeries(){if(this._series.size<this._config.maxSeriesPerFlush)return!0;if(!this._seriesCapWarned)this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);return!1}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{if(!e.hist)e.hist={count:0,sum:0,min:t,max:t,bucketCounts:Array(je.length+1).fill(0)};let r=e.hist;r.count+=1,r.sum+=t,r.min=Math.min(r.min,t),r.max=Math.max(r.max,t),r.bucketCounts[mi(t,je)]+=1;break}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let r=L(t)?t:[t],s=e;for(let i of r)try{let n=i(s);if(!n)return this._logger.info("Metric was rejected in beforeSend function"),null;s=n}catch(n){return this._logger.error("Error in beforeSend function for metric:",n),null}return s}_armFlushTimer(){if(this._flushTimer.pending)return;this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(Be(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,ke),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),this._series.size===0)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,r=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t!==this._generation)return;if(this._retryAfter.record(r),r.kind==="retry-later")this._consecutiveFlushFailures++,this._flushJitter=Ue();else this._consecutiveFlushFailures=0,this._flushJitter=M;if(this._flushTimer.pending)this._flushTimer.arm(this._nextFlushDelay());switch(r.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",r.error);return}}_buildPayload(e){return wr(this._buildMetrics(e),Ar(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let t=St(Date.now()),r=new Map;for(let s of e.values()){let i=Fr(s.type,s.name,s.unit,void 0),n=r.get(i);if(!n){if(n={name:s.name,...s.unit&&{unit:s.unit}},s.type==="count")n.sum={aggregationTemporality:_i,isMonotonic:!0,dataPoints:[]};else if(s.type==="gauge")n.gauge={dataPoints:[]};else n.histogram={aggregationTemporality:_i,dataPoints:[]};r.set(i,n)}let o=V(s.attributes??{},this._logger),l=St(s.windowStartMs),a=Ea(s.exemplar);if(s.type==="count"){let c={attributes:o,startTimeUnixNano:l,timeUnixNano:t,asDouble:s.total??0,...a};n.sum.dataPoints.push(c)}else if(s.type==="gauge"){let c={attributes:o,timeUnixNano:t,asDouble:s.last??0,...a};n.gauge.dataPoints.push(c)}else if(s.hist){let c={attributes:o,startTimeUnixNano:l,timeUnixNano:t,count:s.hist.count,sum:s.hist.sum,min:s.hist.min,max:s.hist.max,bucketCounts:s.hist.bucketCounts,explicitBounds:je,...a};n.histogram.dataPoints.push(c)}}return Array.from(r.values())}_mergeWindowBack(e){for(let[t,r]of e){let s=this._series.get(t);if(!s){if(this._admitNewSeries())this._series.set(t,r);continue}switch(s.windowStartMs=Math.min(s.windowStartMs,r.windowStartMs),s.exemplar=s.exemplar??r.exemplar,s.type){case"count":s.total=(s.total??0)+(r.total??0);break;case"gauge":break;case"histogram":if(r.hist)if(s.hist){s.hist.count+=r.hist.count,s.hist.sum+=r.hist.sum,s.hist.min=Math.min(s.hist.min,r.hist.min),s.hist.max=Math.max(s.hist.max,r.hist.max);for(let i=0;i<s.hist.bucketCounts.length;i++)s.hist.bucketCounts[i]+=r.hist.bucketCounts[i]}else s.hist=r.hist;break}}}}function Ea(e){if(!e)return{};return{exemplars:[{filteredAttributes:[],timeUnixNano:St(e.timeMs),asDouble:e.value,traceId:e.traceId,spanId:e.spanId}]}}function ie(e,t,r,s){if(typeof e=="string"&&e.trim())return e.length>r?e.slice(0,r):e;return s?.debug(`${t} must be a non-empty string; using "unknown"`),"unknown"}function ve(e){if(e==null)return;let t=e;if(e instanceof Date)try{t=e.getTime()}catch{return}if(typeof t!="number"||!Number.isFinite(t))return;if(t<0||t>9223372036854)return;return t}function yi(e,t,r){let s=ve(e);if(s===void 0){if(e!==void 0)r?.debug("Span startTime is out of range or not a valid time; using the current time");return t}if(t-s>86400000)r?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp");else if(s>t)r?.debug("Span startTime is in the future; the span may export with a zero duration");return s}function wt(e,t){return e<t?t:e}function Ve(e,t,r,s){let i=ve(e);if(i===void 0){if(e!==void 0)s?.debug(`Span ${r} is out of range or not a valid time; using the derived time`);return t}return i}function xt(){let e=globalThis.performance;return typeof e?.now=="function"?e.now():void 0}class ze{constructor(e,t,r){this._onEnd=t,this._logger=r,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=e.traceId,this._spanId=e.spanId,this._parentSpanId=e.parentSpanId,this._traceState=e.traceState,this._traceFlags=e.traceFlags??Ee,this._parentIsRemote=e.parentIsRemote??!1,this._name=e.name,this._kind=e.kind,this._autoKeys=new Set(e.autoAttributeKeys),this._maxAttributes=e.maxAttributes,this._maxEvents=e.maxEvents,this._maxAttributesPerEvent=e.maxAttributesPerEvent,this._maxAttributeValueLength=e.maxAttributeValueLength,this._attributes=Object.create(null);for(let s of Object.keys(e.attributes))this._writeAttribute(s,e.attributes[s]);if(this._startMono=e.backdated?void 0:xt(),this._startTime=e.clockAnchor&&this._startMono!==void 0?e.clockAnchor.wall+(this._startMono-e.clockAnchor.mono):e.startTime,this._startMono!==void 0)this._clockAnchor=e.clockAnchor??{wall:this._startTime,mono:this._startMono}}_now(){if(this._startMono!==void 0){let e=xt();if(e!==void 0)return this._startTime+Math.max(0,e-this._startMono)}return Date.now()}_mutable(e){if(this._ended)return this._logger?.debug(`Ignoring ${e} on a span that has already ended`),!1;return!0}_writeAttribute(e,t){if(k(t)){if(e in this._attributes&&!this._autoKeys.has(e))this._userAttributeCount--;delete this._attributes[e];return}if(!this._autoKeys.has(e)&&!(e in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[e]=Tt(t,this._maxAttributeValueLength)}setAttribute(e,t){if(this._mutable("setAttribute"))this._writeAttribute(e,t);return this}setAttributes(e){if(this._mutable("setAttributes")){let t=G({},e);for(let r of Object.keys(t))this._writeAttribute(r,t[r])}return this}addEvent(e,t,r){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let s=t&&Si(t,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:ie(e,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:Ve(r,this._now(),"event timestamp",this._logger),...s&&{attributes:s.attributes,...s.dropped&&{droppedAttributesCount:s.dropped}}})}return this}setStatus(e,t){if(this._mutable("setStatus")){if(e!=="ok"&&e!=="error")return this._logger?.debug(`Ignoring unknown span status "${String(e)}"; expected "ok" or "error"`),this;this._status={code:e,...t&&{message:xr(t,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(e){if(!this._mutable("recordException"))return this;let{type:t,message:r,stack:s}=Ir(e);return this.addEvent(va,{"exception.type":t,"exception.message":r,...s&&{"exception.stacktrace":s}}),this.setStatus("error",r)}updateName(e){if(this._mutable("updateName"))this._name=ie(e,"Span name",this._maxAttributeValueLength,this._logger);return this}traceparent(){return gi(this._traceId,this._spanId,this._traceFlags)}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(e){if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let t=this._now(),r=Ve(e,t,"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:wt(r,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}}var va="exception",Sa=4294967295;function Fa(e){try{return typeof e=="string"?e:String(e)}catch{return U}}function ne(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return 0;return Math.min(Math.floor(e),Sa)}function Aa(e,t){if(!t.length)return Object.keys(e);let r=t.filter((i)=>Object.prototype.propertyIsEnumerable.call(e,i)),s=new Set(r);return[...r,...Object.keys(e).filter((i)=>!s.has(i))]}function Ei(e,t,r,s,i,n,o=[]){let l=0,a=0,c={};for(let p of Aa(e.attributes,o)){let f=e.attributes[p];if(!k(f)){if(!t.has(p)){if(l>=r){a++;continue}l++}Object.defineProperty(c,p,{value:Tt(f,n),enumerable:!0,writable:!0,configurable:!0})}}if(e.attributes=c,a)e.droppedAttributesCount=ne(e.droppedAttributesCount)+a;let u=0,d=0,h=[];for(let p of e.events){if(u>=s){d++;continue}if(u++,p.attributes){let f=Si(p.attributes,i,n);if(p.attributes=f.attributes,f.dropped)p.droppedAttributesCount=ne(p.droppedAttributesCount)+f.dropped}h.push(p)}if(e.events=h,d)e.droppedEventsCount=ne(e.droppedEventsCount)+d;if(e.status?.message)e.status={...e.status,message:xr(Fa(e.status.message),n)}}class Pr{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}tracestate(){return null}end(){}}var vi=new Pr;class It extends Pr{constructor(e,t){super(),this._traceparent=e,this._tracestate=t}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}}function wa(e){try{let t=e.stack;return typeof t=="string"&&t?{stack:t}:{}}catch{return{}}}function Q(e,t){let r=Et(e?.parent)??t,s=typeof r=="string"||r==null?r:bi(r,"traceparent"),i=pi(s);if(!i)return vi;let n=typeof r=="string"||r==null?e?.tracestate:bi(r,"tracestate");return new It(i,vt(n))}function bi(e,t){try{let r=e[t];return typeof r=="function"?r.call(e):void 0}catch{return}}function xr(e,t){return e.length>t?e.slice(0,t):e}function Tt(e,t){return Pt(e,t,{ancestors:new WeakSet,remainingNodes:it},0)}function Pt(e,t,r,s){if(e===null||typeof e!="object"){if(k(e))return e;if(r.remainingNodes<=0)return e;return r.remainingNodes--,typeof e=="string"?xr(e,t):e}if(r.ancestors.has(e))return nt;if(r.remainingNodes<=0||s>=st)return e;r.remainingNodes--,r.ancestors.add(e);try{if(e instanceof Date)return e;let i=Pa(e);if(i.selfDescribed)return k(i.value)?String(i.value):Pt(i.value,t,r,s+1);if(L(e)){let l=Math.min(e.length,de),a=[];for(let c=0;c<l;c++)try{a.push(Pt(e[c],t,r,s+1))}catch{a.push(U)}if(e.length>l)a.length=e.length;return a}let n={},o=0;for(let l of Object.keys(e)){if(o>=de)break;let a;try{a=Pt(e[l],t,r,s+1)}catch{a=U}if(l&&!k(a))o++;Object.defineProperty(n,l,{value:a,enumerable:!0,writable:!0,configurable:!0})}return n}catch{return e}finally{r.ancestors.delete(e)}}function Pa(e){try{let t=e.toJSON;if(typeof t=="function")return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}function Si(e,t,r){let s;try{s=Object.keys(e)}catch{return{attributes:{},dropped:0}}let i={},n=0,o=0;for(let l of s){if(n>=t){o++;continue}let a;try{a=Tt(e[l],r)}catch{a=U}if(!k(a))n++,Object.defineProperty(i,l,{value:a,enumerable:!0,writable:!0,configurable:!0})}return{attributes:i,dropped:o}}function Fi(e,t){for(let r of Object.keys(e))e[r]=Tt(e[r],t);return e}function qe(e,t,r){return t===vi?r(t):e.with(t,()=>r(t))}function Ir(e){try{let t=wa(e);if(H(e))return{type:e.name||"Error",message:e.message||"",...t};if(typeof e=="string")return{type:"string",message:e};if(e&&typeof e=="object"){let r=e;if(typeof r.message=="string")return{type:typeof r.name=="string"?r.name:"Object",message:r.message,...t}}return{type:typeof e,message:String(e)}}catch{return{type:typeof e,message:""}}}var Tr={internal:1,server:2,client:3,producer:4,consumer:5},xa={ok:1,error:2},Ia=1,Ta=256,Ra=512;function Ca(e){let t=parseInt(e.traceFlags,16);return(Number.isFinite(t)?255&t:Ia)|Ta|(e.parentIsRemote?Ra:0)}function Rt(e){if(typeof e=="string")return j(e);try{return j(String(e))}catch{return U}}function Oa(e){if(e&&Object.prototype.hasOwnProperty.call(Tr,e))return Tr[e];return Tr.internal}function Rr(e){let t=Math.floor(e),r=Math.round((e-t)*1e6);if(r>=1e6)t+=1,r=0;return String(t)+String(r).padStart(6,"0")}function La(e,t){let r={name:Rt(e.name),timeUnixNano:Rr(e.timestamp)};if(e.attributes){let i=V(e.attributes,t);if(i.length)r.attributes=i}let s=ne(e.droppedAttributesCount);if(s)r.droppedAttributesCount=s;return r}function Ai(e,t){let r={traceId:e.traceId,spanId:e.spanId,name:Rt(e.name),kind:Oa(e.kind),startTimeUnixNano:Rr(e.startTime),endTimeUnixNano:Rr(e.endTime),flags:Ca(e)};if(e.parentSpanId)r.parentSpanId=e.parentSpanId;if(e.traceState)r.traceState=Rt(e.traceState);let s=V(e.attributes,t);if(s.length)r.attributes=s;if(e.events.length)r.events=e.events.map((o)=>La(o,t));let i=ne(e.droppedAttributesCount);if(i)r.droppedAttributesCount=i;let n=ne(e.droppedEventsCount);if(n)r.droppedEventsCount=n;if(e.status)r.status={code:xa[e.status.code],...e.status.message&&{message:Rt(e.status.message)}};return r}function wi(e,t,r){return De(e,t,r)}function Pi(e,t,r,s,i){return{resourceSpans:[{resource:{attributes:$e(t,i)},scopeSpans:[{scope:{name:r,version:s},spans:e}]}]}}var xi=8;function Ct(){return xt()??Date.now()}function Cr(e){try{return e instanceof ze}catch{return!1}}function Ii(e,t){let r=bt(e);if(!r)return;return{traceId:r.traceId,parentSpanId:r.spanId,traceState:vt(t),traceFlags:r.flags,isRemote:!0}}function Na(e){try{return typeof e.traceparent=="function"}catch{return!1}}function Ma(e){return!!e.attributes&&typeof e.attributes=="object"&&!Array.isArray(e.attributes)&&Array.isArray(e.events)&&e.name!==void 0&&e.kind!==void 0&&e.startTime!==void 0&&e.endTime!==void 0}function Ot(e,t,r){if(e[t]!==r)e[t]=r}function Da(e,t){try{let r=Object.getOwnPropertyDescriptors(e);for(let s of["traceId","spanId","parentSpanId","traceState"])r[s]={value:t[s],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(e),r)}catch{return e}}class Lt{constructor(e,t,r,s,i,n){this._instance=e,this._config=t,this._logger=r,this._getContext=s,this._contextManager=i,this._onSpanQueued=n,this._queue=[],this._flushTimer=new be(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=M,this._retryAfter=new fe,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=t.maxExportBatchSize}startSpan(e,t){if(this._instance.isDisabled||this._instance.optedOut)return Q(t,this._contextManager.active());let r=Et(t?.parent);if(r&&typeof r!="string"&&!Cr(r)){if(Na(r))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),Q(t,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let s=this._resolveParent(r,t);if(this._liveSpans.size>=this._config.maxLiveSpans)this._evictAgedSpans();if(this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached — spans are being started and never ended`),Q(t,this._contextManager.active());let i=Date.now(),n=yi(t?.startTime,i,this._logger),o=ci();this._liveSpans.set(o,Ct());let l=this._autoContextAttributes();return new ze({traceId:s?.traceId??li(),spanId:o,parentSpanId:s?.parentSpanId,traceState:s?.traceState,traceFlags:s?.traceFlags,parentIsRemote:s?.isRemote,name:ie(e,"Span name",this._config.maxAttributeValueLength,this._logger),kind:t?.kind??"internal",attributes:G({...l},t?.attributes),autoAttributeKeys:Object.keys(l),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:n,backdated:n!==i,clockAnchor:ve(t?.startTime)===void 0?s?.clockAnchor:void 0},(a,c)=>this._onSpanEnd(a,c),this._logger)}withSpan(e,t,r){let s=typeof t=="function"?void 0:t,i=typeof t=="function"?t:r,n=this.startSpan(e,s);try{let o=qe(this._contextManager,n,i);if(Fs(o))return o.then((l)=>(n.end(),l),(l)=>{throw this._recordCallbackError(n,l),n.end(),l});return n.end(),o}catch(o){throw this._recordCallbackError(n,o),n.end(),o}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;){if(!this._queue.length)return;if(!await(this._flushPromise??this._startFlush()))return}}_startFlush(){this._flushTimer.clear();let e=this._generation,t=Promise.resolve().then(()=>e===this._generation?this._flushInner():0).finally(()=>{if(this._flushPromise===t)this._flushPromise=null;this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=t,t}reset(){if(this._flushTimer.clear(),this._queue.length)this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`);this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=M,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(e,t){if(typeof e=="string"){let s=Ii(e,t?.tracestate);if(!s)this._logger.debug("Ignoring malformed traceparent; starting a new trace");return s}if(Cr(e))return e.childContext();let r=this._contextManager.active();if(Cr(r))return r.childContext();if(r instanceof It)return Ii(r.traceparent(),r.tracestate()??void 0)}_autoContextAttributes(){let e;try{e=this._getContext()}catch(r){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",r),{}}let t={};if(e.distinctId)t.posthogDistinctId=e.distinctId;if(e.sessionId)t.sessionId=e.sessionId;if(e.currentUrl)t["url.full"]=e.currentUrl;if(e.screenName)t["screen.name"]=e.screenName;if(e.appState)t["app.state"]=e.appState;return t}_recordCallbackError(e,t){if(!(e instanceof ze))return;let{type:r,message:s,stack:i}=Ir(t);if(e.addEvent("exception",{"exception.type":r,"exception.message":s,...i&&{"exception.stacktrace":i}}),!e.statusIsExplicitlyOk)e.setStatus("error",s)}_evictAgedSpans(){let e=Ct()-this._config.maxSpanAgeMs,t=0;for(let[r,s]of this._liveSpans){if(s>e)break;this._liveSpans.delete(r),t++}if(t)this._recordDrop(t,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(e,t){if(!this._liveSpans.delete(e.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let r=this._runBeforeSpanSend(e,t);if(!r)return;if(this._reportLimitDrops(r),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) — raise the flush frequency or reduce span volume`);this._queue.push(r);try{this._onSpanQueued?.()}catch(s){this._logger.debug("Span queue notification failed",s)}if(!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen())this._armFlushTimerIfQueued();else this._flushInBackground()}_reportLimitDrops(e){let t=e.droppedAttributesCount??0,r=e.droppedEventsCount??0,s=0;for(let i of e.events)s+=i.droppedAttributesCount??0;if(t||r||s)this._logger.debug(`Span limits discarded data from "${e.name}": ${t} attributes, ${r} events, ${s} event attributes`)}_runBeforeSpanSend(e,t){if(!this._config.beforeSpanSend.length)return e;let r={traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,traceState:e.traceState},s={startTime:e.startTime,endTime:e.endTime},i={attributes:e.droppedAttributesCount,events:e.droppedEventsCount},n=Object.keys(e.attributes),o={traceFlags:e.traceFlags,parentIsRemote:e.parentIsRemote},l=e.status&&{...e.status},a=e,c=e;try{for(let h of this._config.beforeSpanSend){let p=h(a);if(!p)return this._recordDrop(1,"beforeSpanSend dropped it"),null;a=this._keepSpanIdentity(p,r)}if(c={traceId:r.traceId,spanId:r.spanId,parentSpanId:r.parentSpanId,traceState:r.traceState,name:a.name,kind:a.kind,status:a.status,attributes:a.attributes,events:a.events,startTime:a.startTime,endTime:a.endTime,traceFlags:o.traceFlags,parentIsRemote:o.parentIsRemote,droppedAttributesCount:i.attributes,droppedEventsCount:i.events},!Ma(c))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;if(c.name=ie(c.name,"Span name",this._config.maxAttributeValueLength,this._logger),c.status&&c.status.code!=="ok"&&c.status.code!=="error")this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),c.status=l;c.startTime=ve(c.startTime)??s.startTime,c.endTime=wt(ve(c.endTime)??s.endTime,c.startTime);let d=[];for(let h of c.events)try{d.push({...h,name:ie(h.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:Ve(h.timestamp,c.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return c.events=d,Ei(c,t,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,n),c}catch(u){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",u),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(e,t){if(e.traceId!==t.traceId||e.spanId!==t.spanId||e.parentSpanId!==t.parentSpanId)this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{Ot(e,"traceId",t.traceId),Ot(e,"spanId",t.spanId),Ot(e,"parentSpanId",t.parentSpanId),Ot(e,"traceState",t.traceState)}catch{return Da(e,t)}return e}_recordDrop(e,t){if(this._droppedSinceWarning+=e,this._dropReasons.add(t),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs)this._warnAboutDrops()}_warnAboutDrops(){if(!this._droppedSinceWarning)return;this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear()}_encodeBatch(e){let t=[];for(let r of e)try{t.push(Ai(r,this._logger))}catch(s){this._logger.debug("Failed to encode a span; dropping it",s),this._recordDrop(1,"its attributes could not be encoded")}return t}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let e=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(e,"the user has opted out"),this._warnAboutDrops(),e}async _flushInner(){if(!this._queue.length)return 0;let e=this._discardQueueIfConsentWithdrawn();if(e)return e;let t=Fi(wi(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._config.maxAttributeValueLength),r=this._instance.getLibraryId(),s=this._instance.getLibraryVersion(),i=this._queue.length,n=0,o=1/0,l=this._generation;try{while(i>0&&this._queue.length>0){let a=this._discardQueueIfConsentWithdrawn();if(a)return n+a;let c=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,u=Math.max(1,Math.min(c,o,i,this._queue.length)),d=this._queue.slice(0,u),h=this._encodeBatch(d);if(!h.length){this._queue.splice(0,u),i-=u,n+=u,this._resetHeadBatchBudget();continue}let p=Ct()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),f=await this._instance._sendTracesBatch(Pi(h,t,r,s,this._logger));if(l!==this._generation)break;if(this._retryAfter.record(f),f.kind==="ok"){if(this._consecutiveFlushFailures=0,this._flushJitter=M,this._resetHeadBatchBudget(),this._queue.splice(0,u),i-=u,n+=u,this._maxExportBatchSize<this._config.maxExportBatchSize)this._maxExportBatchSize++;continue}if(f.kind==="too-large"){if(u===1){this._queue.splice(0,1),i-=1,n+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=M,this._resetHeadBatchBudget();continue}let g=Math.max(1,Math.floor(u/2));if(f.measuredLocally)o=g;else this._maxExportBatchSize=g;this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${g}`);continue}if(f.kind==="retry-later"){if(this._consecutiveFlushFailures++,this._flushJitter=Ue(),this._headBatchSize=u,p)this._headBatchFailures++,this._headBatchChargeableAt=Ct()+this._nextFlushDelay();if(this._headBatchFailures<xi)return this._logger.debug("Span export failed; retrying on the next flush",f.error),n;if(this._queue.splice(0,u),i-=u,n+=u,this._consecutiveFlushFailures=0,this._flushJitter=M,this._resetHeadBatchBudget(),this._recordDrop(u,`the ingestion endpoint failed ${xi} times in a row`),this._retryAfter.isOpen())return n;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",f.error),this._queue.splice(0,u),i-=u,n+=u,this._consecutiveFlushFailures=0,this._flushJitter=M,this._resetHeadBatchBudget(),this._recordDrop(u,"the ingestion endpoint rejected the batch")}return n}finally{this._warnAboutDrops()}}_flushInBackground(){if(this._backgroundFlush)return;this._backgroundFlush=this.flush().catch((e)=>{this._logger.debug("Background span flush failed",e)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()})}_armFlushTimerIfQueued(){if(this._flushTimer.pending||!this._queue.length)return;this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){if(!this._queue.length)return;this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(Be(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,ke),this._retryAfter.remainingMs())}}class Nt{active(){return this._active}with(e,t){let r=this._active;this._active=e;try{return t()}finally{this._active=r}}}var $a=5000,ka=512,Ua=2048,Ba=128,ja=128,Va=128,za=8192,qa=1e4,Ga=3600000;function J(e,t){return typeof e=="number"&&Number.isInteger(e)&&e>=1?e:t}var Ti=["service.name","service.version","deployment.environment"];function Ka(e){if(!e||typeof e!="object"||Array.isArray(e))return;try{if(Ti.every((r)=>!(r in e)||typeof e[r]=="string"))return e;let t={...e};for(let r of Ti)if(r in t&&typeof t[r]!="string")delete t[r];return t}catch{return}}function Ha(e,t){if(!e)return[];let r=[e].flat().filter((i)=>Boolean(i)),s=r.filter((i)=>typeof i=="function");if(s.length!==r.length)t?.critical(`beforeSpanSend: ignoring ${r.length-s.length} of ${r.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`);return s}function Or(e,t,r){let s=G({...t},Ka(e?.resourceAttributes)),i=J(e?.maxExportBatchSize,ka);return{serviceName:s?.["service.name"]??e?.serviceName,serviceVersion:s?.["service.version"]??e?.serviceVersion,environment:s?.["deployment.environment"]??e?.environment,resourceAttributes:s,beforeSpanSend:Ha(e?.beforeSpanSend,r),maxAttributesPerSpan:J(e?.maxAttributesPerSpan,Ba),maxEventsPerSpan:J(e?.maxEventsPerSpan,ja),maxAttributesPerEvent:Va,maxAttributeValueLength:J(e?.maxAttributeValueLength,za),flushIntervalMs:J(e?.flushIntervalMs,$a),maxExportBatchSize:i,maxQueueSize:Math.max(J(e?.maxQueueSize,Ua),i),maxLiveSpans:J(e?.maxLiveSpans,qa),maxSpanAgeMs:J(e?.maxSpanAgeMs,Ga)}}import{constants as Ri}from"node:fs";import{open as Wa}from"node:fs/promises";import{isAbsolute as Li}from"node:path";import{createInterface as Xa}from"node:readline";var Mt=new or(25),Ge=new or(20),Nr=7,Qa=1000,Ja=1e4,Lr=10485760;async function Ni(e,t=Wa,r){let s={},i;try{i=process.cwd()}catch{}for(let l=e.length-1;l>=0;l--){let a=e[l],c=a?.filename;if(!a||typeof c!="string"||typeof a.lineno!="number"||rl(c)||sl(a))continue;if(!Li(c)&&i===void 0)continue;if(!s[c])s[c]=[];s[c].push(a.lineno)}let n=Object.keys(s);if(n.length==0)return e;let o=[];for(let l of n){let a=Mi(l,i);if(a===void 0)continue;if(Ge.get(a))continue;let c=s[l];if(!c)continue;c.sort((h,p)=>h-p);let u=nl(c);if(u.every((h)=>il(a,h)))continue;let d=ol(Mt,a,{});o.push(Za(l,u,d,a,t,r))}if(await Promise.all(o).catch(()=>{}),e&&e.length>0)el(e,Mt,i);return Mt.reduce(),e}async function Ya(e,t,r){let s,i=!1;try{s=await t(e,Ri.O_RDONLY|Ri.O_NONBLOCK);let n=await s.stat();if(!n.isFile())return;if(n.size>Lr)return void r?.debug(`Skipping source context for oversized file ${e}: ${n.size} bytes exceeds ${Lr}`);return i=!0,s}catch{return}finally{if(s&&!i)await s.close().catch(()=>{})}}async function Za(e,t,r,s,i,n){let o=await Ya(e,i,n);if(o===void 0)return void Ge.set(s,1);let l=o;return new Promise((a)=>{let c=!1;function u(E){if(c)return;c=!0,E?.destroy(),l.close().then(a,a)}let d;try{d=l.createReadStream({autoClose:!1,start:0,end:Lr-1})}catch{Ge.set(s,1),u();return}let h;try{h=Xa({input:d})}catch{Ge.set(s,1),u(d);return}let p=0,f=0,g=t[f];if(g===void 0)return void u(d);let m=g[0],b=g[1];function v(){Ge.set(s,1),h.close(),h.removeAllListeners(),u(d)}d.on("error",v),h.on("error",v),h.on("close",()=>u(d)),h.on("line",(E)=>{if(p++,p<m)return;if(r[p]=al(E,0),p>=b){if(f===t.length-1){h.close(),h.removeAllListeners();return}f++;let A=t[f];if(A===void 0){h.close(),h.removeAllListeners();return}m=A[0],b=A[1]}})})}function el(e,t,r){for(let s of e)if(s.filename&&s.context_line===void 0&&typeof s.lineno=="number"){let i=Mi(s.filename,r),n=i===void 0?void 0:t.get(i);if(n===void 0)continue;tl(s.lineno,s,n)}}function tl(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=Di(e);i<e;i++){let n=r[i];if(n===void 0)return void Ci(t);t.pre_context.push(n)}if(r[e]===void 0)return void Ci(t);t.context_line=r[e];let s=$i(e);t.post_context=[];for(let i=e+1;i<=s;i++){let n=r[i];if(n===void 0)break;t.post_context.push(n)}}function Ci(e){delete e.pre_context,delete e.context_line,delete e.post_context}function rl(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function sl(e){if(e.lineno!==void 0&&e.lineno>Ja)return!0;if(e.colno!==void 0&&e.colno>Qa)return!0;return!1}function Mi(e,t){if(Li(e))return JSON.stringify([null,e]);return t===void 0?void 0:JSON.stringify([t,e])}function il(e,t){let r=Mt.get(e);if(r===void 0)return!1;for(let s=t[0];s<=t[1];s++)if(r[s]===void 0)return!1;return!0}function nl(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let s=Oi(r),i=[];while(!0){if(t===e.length-1){i.push(s);break}let n=e[t+1];if(typeof n!="number")break;if(n<=s[1])s[1]=n+Nr;else i.push(s),s=Oi(n);t++}return i}function Oi(e){return[Di(e),$i(e)]}function Di(e){return Math.max(1,e-Nr)}function $i(e){return e+Nr}function ol(e,t,r){let s=e.get(t);if(s===void 0)return e.set(t,r),r;return s}function al(e,t){let r=e,s=r.length;if(s<=150)return r;if(t>s)t=s;let i=Math.max(t-60,0);if(i<5)i=0;let n=Math.min(i+140,s);if(n>s-5)n=s;if(n===s)i=Math.max(n-140,0);if(r=r.slice(i,n),i>0)r=`...${r}`;if(n<s)r+="...";return r}import{isAbsolute as ll,relative as cl,sep as ul}from"path";function ki(e=process.cwd()){let t=ul==="\\",r=(i)=>t?i.replace(/\\/g,"/"):i,s=r(e);return async(i)=>{for(let n of i)if(!(!n.filename||n.filename.startsWith("node:")||n.filename.startsWith("data:"))){if(ll(n.filename))n.filename=r(cl(s,r(n.filename)))}return i}}var Ui="5.60.1";var z={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",LOCAL_EVALUATION_INCONCLUSIVE:"local_evaluation_inconclusive",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};class Y{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._unresolvedFlags=Object.freeze({...e.unresolvedFlags}),this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e,t={}){let r=this._flags[e];return this._recordAccess(e,t.sendFeatureFlagEvents),r?.enabled??t.defaultValue??!1}getFlag(e,t={}){let r=this._flags[e];if(this._recordAccess(e,t.sendFeatureFlagEvents),!r)return;if(!r.enabled)return!1;return r.variant??!0}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let r=this._flags[t];if(r)e[t]=r}return this._cloneWith(e)}only(e){let t={},r=[];for(let s of e){let i=this._flags[s];if(i)t[s]=i;else r.push(s)}if(r.length>0)this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${r.join(", ")}`);return this._cloneWith(t)}get keys(){return Object.keys(this._flags)}get unresolvedFlags(){return this._unresolvedFlags}_getEventProperties(){let e={},t=[];for(let[r,s]of Object.entries(this._flags)){let i=s.enabled===!1?!1:s.variant??!0;if(e[`$feature/${r}`]=i,s.enabled)t.push(r)}if(t.length>0)t.sort(),e.$active_feature_flags=t;return e}_cloneWith(e){return new Y({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e,t){if(this._accessed.add(e),!this._host.resolveSendFeatureFlagEvents(t))return;if(this._distinctId==="")return;if(this._isSlice&&!(e in this._flags))return;let r=this._flags[e],s=r===void 0?void 0:r.enabled===!1?!1:r.variant??!0,i={$feature_flag:e,$feature_flag_response:s,$feature_flag_id:r?.id,$feature_flag_version:r?.version,$feature_flag_reason:r?.reason,locally_evaluated:r?.locallyEvaluated??!1,[`$feature/${e}`]:s,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:r?.locallyEvaluated?Date.now():this._evaluatedAt};if(r?.hasExperiment!==void 0)i.$feature_flag_has_experiment=r.hasExperiment;if(r?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0)i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt;let n=[];if(this._errorsWhileComputing)n.push(z.ERRORS_WHILE_COMPUTING);if(this._quotaLimited)n.push(z.QUOTA_LIMITED);if(r===void 0)n.push(Object.prototype.hasOwnProperty.call(this._unresolvedFlags,e)?z.LOCAL_EVALUATION_INCONCLUSIVE:z.FLAG_MISSING);if(n.length>0)i.$feature_flag_error=n.join(",");this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:s,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}}var dl=60000;function Bi(e){return e==="client"||e==="server"?e:"all"}function fl(e,t){return e===t||e==="all"||t==="all"}class oe extends Error{constructor(e){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,oe.prototype)}}function hl(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}class O extends Error{constructor(e,t="unsupported_definition"){super(e),this.reason=t,hl(this,O)}}var ji=["experience_continuity","unsupported_definition","unresolved_dependency","missing_context"];function K(e,t){if(e===void 0)return t;return ji.indexOf(t)<ji.indexOf(e)?t:e}function Ke(e,t){if(t instanceof y&&Symbol.for("posthog.requiresServerRegexEvaluation")in t)Object.defineProperty(e,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0});return e}class Dr{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:r,timeout:s,host:i,customHeaders:n,...o}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.warnedUnresolvableFlags=new Map,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=s,this.projectApiKey=r,this.host=i,this.poller=void 0,this.fetch=o.fetch||fetch,this.onError=o.onError,this.customHeaders=n,this.onLoad=o.onLoad,this.onMinimalFlagCalledEvents=o.onMinimalFlagCalledEvents,this.cacheProvider=o.cacheProvider,this.strictLocalEvaluation=o.strictLocalEvaluation??!1,this.evaluationContexts=o.evaluationContexts,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){if(this.debugMode)e()}currentDefinitions(){return{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}withEvaluationSnapshot(e){if(e.definitions)return e;return{...e,evaluationCache:{},definitions:this.currentDefinitions()}}createEvaluationContext(e,t={},r={},s={},i={}){return{distinctId:e,groups:t,personProperties:r,groupProperties:s,evaluationCache:i}}async getFeatureFlag(e,t,r={},s={},i={}){await this.loadFeatureFlags();let n,o;if(!this.loadedSuccessfullyOnce)return n;if(o=this.featureFlagsByKey[e],o!==void 0){let l=this.createEvaluationContext(t,r,s,i);try{n=(await this.computeFlagAndPayloadLocally(o,l)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${n}`))}catch(a){if(a instanceof O||a instanceof y)this.logMsgIfDebug(()=>console.debug(`${a.name} when computing flag locally: ${e}: ${a.message}`));else if(a instanceof Error)this.onError?.(Error(`Error computing flag locally: ${e}: ${a}`))}}return n}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let r={},s={},i={},n=this.featureFlags.length==0,o=t?t.map((a)=>this.featureFlagsByKey[a]).filter(Boolean):this.featureFlags,l=this.withEvaluationSnapshot({...e,definitions:void 0});return await Promise.all(o.map(async(a)=>{try{let{value:c,payload:u}=await this.computeFlagAndPayloadLocally(a,l,{skipLoadCheck:!0});if(r[a.key]=c,u)s[a.key]=u}catch(c){if(c instanceof O||c instanceof y)this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${a.key}: ${c.message}`)),i[a.key]=c.reason;else if(c instanceof Error)this.onError?.(Error(`Error computing flag locally: ${a.key}: ${c}`));n=!0}})),{response:r,payloads:s,unresolved:i,fallbackToFlags:n}}async computeFlagAndPayloadLocally(e,t,r={}){let{matchValue:s,skipLoadCheck:i=!1}=r;if(this.loadedSuccessfullyOnce)t=this.withEvaluationSnapshot(t);if(!i)await this.loadFeatureFlags();if(!this.loadedSuccessfullyOnce)return{value:!1,payload:null};t=this.withEvaluationSnapshot(t),e=t.definitions.featureFlagsByKey[e.key]??e;let n;n=s!==void 0?s:await this.computeFlagValueLocally(e,t);let o=br(e.filters?.payloads,n);return{value:n,payload:o}}async computeFlagValueLocally(e,t){let{distinctId:r,groups:s,personProperties:i,groupProperties:n}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new y("Flag has experience continuity enabled","experience_continuity");let l=(e.filters||{}).aggregation_group_type_index;if(l!=null){let a=t.definitions.groupTypeMapping[String(l)];if(!a)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${l} for feature flag ${e.key}`)),new y("Flag has unknown group type index");if(!(a in s))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;if(e.bucketing_identifier==="device_id"&&(i?.$device_id===void 0||i?.$device_id===null||i?.$device_id===""))this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let c=n[a];return await this.matchFeatureFlagProperties(e,s[a],c,t)}{let a=this.getBucketingValueForFlag(e,r,i);if(a===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new y(`Can't compute feature flag: ${e.key} without $device_id`,Mr(e,t.definitions)??"missing_context");return await this.matchFeatureFlagProperties(e,a,i,t)}}getBucketingValueForFlag(e,t,r){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier==="device_id"){let s=r?.$device_id;if(s==null||s==="")return;return s}return t}async evaluateFlagDependency(e,t,r){let{evaluationCache:s}=r,i=e.key;if(!r.definitions.featureFlagsByKey)throw new y("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new y(`Flag dependency property for '${i}' is missing required 'dependency_chain' field`);let n=e.dependency_chain;if(!Array.isArray(n))throw new y(`Flag dependency property for '${i}' has an invalid 'dependency_chain' (expected array, got ${typeof n})`);if(n.length===0)throw new y(`Circular dependency detected for flag '${i}' (empty dependency chain)`);let o=n.find((a)=>!(a in s)&&!r.definitions.featureFlagsByKey[a]&&!r.definitions.filteredOutFlagKeys.has(a));if(o!==void 0)throw new y(`Missing flag dependency '${o}' for flag '${i}'`);for(let a of n){if(!(a in s)){let u=r.definitions.featureFlagsByKey[a];if(u)if(u.active)try{let d=await this.computeFlagValueLocally(u,r);s[a]=d}catch(d){if(d instanceof O)throw new O(`Flag dependency '${a}' for flag '${i}' requires server evaluation: ${d.message}`,"unresolved_dependency");throw Ke(new y(`Error evaluating flag dependency '${a}' for flag '${i}': ${d}`,"unresolved_dependency"),d)}else s[a]=!1;else s[a]=!1}if(s[a]==null)throw new y(`Dependency '${a}' could not be evaluated`,"unresolved_dependency")}let l=s[i];return this.flagEvaluatesToExpectedValue(e.value,l)}flagEvaluatesToExpectedValue(e,t){if(typeof e=="boolean")return e===t||typeof t=="string"&&t!==""&&e===!0;if(typeof e=="string")return t===e;return!1}async matchFeatureFlagProperties(e,t,r,s){s=this.withEvaluationSnapshot(s);let i=e.filters||{},n=await _r(i.holdout,t);if(n!==void 0)return n;let o=i.groups||[],l=i.aggregation_group_type_index,a=i.early_exit??!1,{groups:c,groupProperties:u}=s,d,h,p=new Set,f;for(let g of o){let m=t;try{let b=g.aggregation_group_type_index!==void 0?g.aggregation_group_type_index:l,v=r;if(b!==l){if(b!=null){let A=s.definitions.groupTypeMapping[String(b)];if(!A||!(A in c)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${b} not available`));continue}if(!(A in u)){d=K(d,"missing_context");continue}v=u[A],m=c[A]}}let E=await this.isConditionMatch(e,m,g,v,s);if(E==="match"){let A=g.variant,x=i.multivariate?.variants||[];f=A&&x.some((S)=>S.key===A)?A:await this.getMatchingVariant(e,m)||!0;break}if(a&&E==="out_of_rollout_bound"){if(d)break;return!1}}catch(b){if(b instanceof O){let v;try{v=Mr(e,s.definitions)}catch{}let E=K(K(d,b.reason),v??b.reason);throw E===b.reason?b:new O(b.message,E)}if(b instanceof y){if(d=K(d,b.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in b)if(h=b,a&&g.rollout_percentage!=null&&await ye(e.key,m)>g.rollout_percentage/100)p.add(!1);else{let v=i.multivariate?.variants||[],E=g.variant;p.add(E&&v.some((A)=>A.key===E)?E:await this.getMatchingVariant(e,m)||!0)}}else throw b}}if(f!==void 0&&!(h&&[...p].some((g)=>g!==f)))return f;if(d)throw Ke(new y("Can't determine if feature flag is enabled or not with given properties",d),h);return!1}async isConditionMatch(e,t,r,s,i){i=this.withEvaluationSnapshot(i);let n=i.definitions,o=r.rollout_percentage,l=(a)=>{this.logMsgIfDebug(()=>console.warn(a))};if((r.properties||[]).length>0){let a,c,u;for(let d of r.properties){let h=d.type,p=!1;try{if(h==="cohort"){let f=await Gi(d,s,n.cohorts,this.debugMode,(g)=>this.evaluateFlagDependency(g,s,i),n.propertyMatchingVersion);p=d.operator==="not_in"?!f:f}else if(h==="flag")p=await this.evaluateFlagDependency(d,s,i);else if(Object.prototype.hasOwnProperty.call(s,d.key))p=qi(d,s,l,n.propertyMatchingVersion);else{Me(d),a=K(a,"missing_context");continue}}catch(f){if(f instanceof O){if(a===void 0)u??=f;a=K(a,f.reason);continue}if(f instanceof y){if(Symbol.for("posthog.requiresServerRegexEvaluation")in f)c=f;a=K(a,f.reason);continue}if(a!==void 0)break;throw f}if(!p)return"no_match"}if(u)throw u;if(a)throw Ke(new y(`Can't determine if a condition of flag ${e.key} matches`,a),c);if(o==null)return"match"}if(o!=null&&await ye(e.key,t)>o/100)return"out_of_rollout_bound";return"match"}async getMatchingVariant(e,t){return yr(e.key,t,e.filters?.multivariate?.variants||[])}variantLookupTable(e){return yt(e.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(e){if(!this.evaluationContexts||this.evaluationContexts.length===0)return e;let t=new Set(this.evaluationContexts);return e.filter((r)=>{let s=r.evaluation_contexts??r.evaluation_tags;if(!s||s.length===0)return!0;return s.some((i)=>t.has(i))})}getEvaluationRuntimeForFlag(e){let t=this.featureFlagsByKey[e];return t?Bi(t.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(e){return this.featureFlags.filter((t)=>fl(Bi(t.evaluation_runtime),e)).map((t)=>t.key)}updateFlagState(e){let t=this.filterFlagsByEvaluationContexts(e.flags),r=t.reduce((n,o)=>(n[o.key]=o,n),{}),s=new Set(t.map((n)=>n.key)),i=new Set(e.flags.filter((n)=>!s.has(n.key)).map((n)=>n.key));this.featureFlags=t,this.featureFlagsByKey=r,this.filteredOutFlagKeys=i,this.groupTypeMapping=e.group_type_mapping??e.groupTypeMapping??{},this.cohorts=e.cohorts,this.propertyMatchingVersion=e.property_matching_version??e.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((e.minimal_flag_called_events??e.minimalFlagCalledEvents)===!0)}warnAboutUnresolvableFlags(e){let t=[],r=[],s=new Map,i=this.currentDefinitions();for(let n of e){let o=Mr(n,i);if(!o)continue;let l=JSON.stringify(n);if(s.set(n.key,l),this.warnedUnresolvableFlags.get(n.key)!==l)if(o==="experience_continuity")t.push(n.key);else r.push(n.key)}if(this.warnedUnresolvableFlags=s,t.length>0){let n=this.strictLocalEvaluation?"With strictLocalEvaluation enabled these flags are left unresolved. To evaluate them locally, disable experience continuity on these flags in PostHog.":"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).";console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled and cannot be resolved locally (reason: experience_continuity): ${t.join(", ")}. `+n)}if(r.length>0){let n=this.strictLocalEvaluation?"With strictLocalEvaluation enabled these flags are left unresolved when evaluation reaches that part.":"Evaluating these flags falls back to a server request when evaluation reaches that part.";console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) use something local evaluation does not support, such as a static cohort, an unknown operator, or a missing or circular flag dependency (reason: unsupported_definition): ${r.join(", ")}. ${n} To evaluate them locally, change these flags in PostHog or upgrade posthog-node.`)}}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();if(t)return this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags),!0;return!1}catch(t){return this.onError?.(Error(`Failed to load from cache: ${t}`)),!1}}async loadFeatureFlags(e=!1){if(this.loadedSuccessfullyOnce&&!e)return;if(!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt)return void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period"));if(!this.loadingPromise)this.loadingPromise=this._loadFeatureFlags().catch((t)=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${t}`))).finally(()=>{this.loadingPromise=void 0});return this.loadingPromise}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){let e=this.pollingInterval??30000;if(!this.shouldBeginExponentialBackoff)return e;return Math.min(dl,e*2**this.backOffCount)}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(){if(this.poller)clearTimeout(this.poller),this.poller=void 0;try{if(this.cacheProvider&&!this.personalApiKey)return void await this.loadFromCache("Loaded flags from cache (cache-only reader)");let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(r){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${r}`))}if(!e){if(await this.loadFromCache("Loaded flags from cache (skipped fetch)"))return;if(this.loadedSuccessfullyOnce)return}let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=t.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new oe(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.propertyMatchingVersion=void 0,this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new oe(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new oe(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let r=await t.json()??{};if(!("flags"in r))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let s=r.group_type_mapping||{},i=r.minimal_flag_called_events===!0,n={flags:r.flags??[],group_type_mapping:s,cohorts:r.cohorts||{},minimal_flag_called_events:i,property_matching_version:r.property_matching_version,propertyMatchingVersion:r.property_matching_version,groupTypeMapping:s,minimalFlagCalledEvents:i};if(this.updateFlagState(n),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(o){this.onError?.(Error(`Failed to store in cache: ${o}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags);break}default:return}}catch(e){if(e instanceof oe)this.onError?.(e)}finally{if(!this.pollerStopped&&this.pollingInterval!==null)this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval())}}getPersonalApiKeyRequestOptions(e="GET",t){let r={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};if(t)r["If-None-Match"]=t;return{method:e,headers:r}}async _requestFeatureFlagDefinitions(){if(!this.personalApiKey)throw new oe("A secretKey or personalApiKey is required to fetch feature flag definitions from PostHog.");let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),r=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;r=T(()=>{i.abort()},this.timeout),t.signal=i.signal}let s=()=>clearTimeout(r);try{let i=this.fetch,n=await i(e,t);if(n.status!==200)return s(),n;return{status:n.status,headers:n.headers,body:n.body,text:async()=>{try{return await n.text()}finally{s()}},json:async()=>{try{return await n.json()}finally{s()}}}}catch(i){throw s(),i}}async stopPoller(e=30000){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let t=this.cacheProvider.shutdown();if(t instanceof Promise)await W(t,e,()=>{throw Error(`Cache shutdown timeout after ${e}ms`)})}catch(t){this.onError?.(Error(`Error during cache shutdown: ${t}`))}}}function Mr(e,t){if(!e.active)return;if(e.ensure_experience_continuity)return"experience_continuity";let r=e.filters||{},s=r.aggregation_group_type_index;if(s!=null&&!t.groupTypeMapping[String(s)])return"unsupported_definition";return(r.groups||[]).some((n)=>(n.properties||[]).some((o)=>Vi(o,t,new Set)))?"unsupported_definition":void 0}function Vi(e,t,r){if(e.type==="flag"){let i=e.dependency_chain;if(!Array.isArray(i)||i.length===0)return!0;return i.some((n)=>!t.featureFlagsByKey[n]&&!t.filteredOutFlagKeys.has(n))}if(e.type!=="cohort")try{return Me(e),!1}catch(i){if(i instanceof y)return!0;throw i}let s=String(e.value);if(!(s in t.cohorts))return!0;if(r.has(s))return!1;return r.add(s),zi(t.cohorts[s],t,r)}function zi(e,t,r){return(e?.values??[]).some((s)=>("values"in s)?zi(s,t,r):Vi(s,t,r))}function qi(e,t,r,s){return mr(e,t,{warnFunction:r,propertyMatchingVersion:s})}function pl(e,t){if(!(e in t))throw new O(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Gi(e,t,r,s=!1,i,n){let o=String(e.value);pl(o,r);let l=r[o];return Ki(l,t,r,s,i,n)}async function Ki(e,t,r,s=!1,i,n){if(!e)return!0;let{type:o,values:l}=e;if(!l||l.length===0)return!0;let a,c;if("values"in l[0]){for(let u of l)try{let d=await Ki(u,t,r,s,i,n);if(o==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof O)throw d;if(d instanceof y){if(s)console.debug(`Failed to compute property ${u} locally: ${d}`);if(a=K(a,d.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in d)c=d}else throw d}if(a)throw Ke(new y("Can't match cohort without a given cohort property value",a),c);return o==="AND"}for(let u of l)try{let d;if(u.type==="cohort")d=await Gi(u,t,r,s,i,n);else if(u.type==="flag"){if(!i)throw new y(`Flag dependency '${u.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);d=await i(u)}else d=qi(u,t,void 0,n);let h=u.negation||!1;if(o==="AND"){if(!d&&!h)return!1;if(d&&h)return!1}else{if(d&&!h)return!0;if(!d&&h)return!0}}catch(d){if(d instanceof O)throw d;if(d instanceof y){if(s)console.debug(`Failed to compute property ${u} locally: ${d}`);if(a=K(a,d.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in d)c=d}else throw d}if(a)throw Ke(new y("can't match cohort without a given cohort property value",a),c);return o==="AND"}var gl=["--unhandled-rejections","--unhandled_rejections"],ml=new Set(["throw","strict","warn","warn-with-error-code","none"]),_l=[...globalThis.process?.execArgv??[]],yl=globalThis.process?.env?.NODE_OPTIONS;function bl(e){let t=[],r="",s=!1;for(let i=0;i<e.length;i++){let n=e[i];if(n==="\\"&&s&&i+1<e.length)r+=e[++i];else if(n!==" "||s)if(n==='"')s=!s;else r+=n;else if(r)t.push(r),r=""}if(r)t.push(r);return t}function Hi(e){let t;for(let r=0;r<e.length;r++){let s=e[r],i=gl.find((o)=>s===o||s.startsWith(`${o}=`));if(!i)continue;let n=s===i?e[++r]:s.slice(i.length+1);if(ml.has(n))t=n}return t}function El(e=_l,t=yl){return Hi(e)??Hi(bl(t??""))??"throw"}var Wi=El();function Xi(e,t,r){e(t,{mechanism:{type:r==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function vl(e,t){let r=!1;return Object.assign((s,i)=>{let n=global.process.listeners("uncaughtException").filter((o)=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length;if(Xi(e,s,i),!r&&n===0)r=!0,t(s)},{_posthogErrorHandler:!0})}function Qi(e,t,r=Wi){let s=globalThis.process;if(!s)return;if(r==="strict")return void s.on("uncaughtExceptionMonitor",(i,n)=>Xi(e,i,n));s.on("uncaughtException",vl(e,t))}function Ji(e,t=Wi){let r=globalThis.process;if(!r||t==="throw"||t==="strict"||t==="warn-with-error-code")return;r.on("unhandledRejection",(s)=>{e(s,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var $r=Symbol("capturedContext");function Yi(e){let t=e?{...e,properties:{...e.properties}}:null;return(r)=>Object.assign(r,{[$r]:t})}function Zi(e,t){return $r in e?e[$r]??void 0:t}var Sl=2000;class Dt{constructor(e,t,r){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=r,this._rateLimiter=new Ht({...ts(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return Qe(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,t,r,s,i,n){let o=Yi(n),l={...i},a=e.buildFromUnknown(t,r);a.$exception_list=await e.modifyFrames(a.$exception_list);let c=js();if(c)l.$release_id=c;return o({event:"$exception",distinctId:s,properties:{...a,...l},_originatedFromCaptureException:!0})}startAutocaptureIfEnabled(){if(this.isEnabled())Qi(this.onException.bind(this),this.onFatalError.bind(this)),Ji(this.onException.bind(this))}onException(e,t){this.client.addPendingPromise((async()=>{if(!Dt.isPreviouslyCapturedError(e)){let r=await Dt.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t,void 0,void 0,this.client.getContext()),i=r.properties?.$exception_list[0]?.type??"Exception";if(this._rateLimiter.consumeRateLimit(i))return void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:i});return this.client._capturePreparedEvent(r,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(Sl),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}var ae=Dt;var Fl=/^[0-9a-f]{32}$/i,Al=/^[0-9a-f]{16}$/i,wl=Symbol.for("opentelemetry.js.api.1"),Pl=Symbol.for("OpenTelemetry Context Key SPAN");async function en(){try{let r=globalThis[wl]?.context?.active().getValue(Pl)?.spanContext(),s=r?.traceId,i=r?.spanId;if(typeof s=="string"&&typeof i=="string"&&Fl.test(s)&&Al.test(i)&&!/^0+$/.test(s)&&!/^0+$/.test(i))return{$trace_id:s.toLowerCase(),$span_id:i.toLowerCase()}}catch{}return{}}class kr{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}}var xl=Symbol.for("posthog-node.context-listeners"),Il=globalThis,Tl=Il[xl]??=new WeakMap;function $t(e,t=!1){for(let r of Tl.get(e)??[])try{r(t)}catch{}}function Rl(e){return e==="v0"||e==="v1"}function tn(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return Rl(e)?e:"v0"}var He="analytics",We="ai";function rn(e){return typeof e.event=="string"&&e.event.startsWith("$ai_")}class Se extends Error{constructor({requestId:e,drops:t,retryExhausted:r,cause:s}){super(Se.buildMessage(e,t,r,s)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=r,this.cause=s}static buildMessage(e,t,r,s){let i=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${r.length} undelivered`;if(s instanceof Error)i+=` (${s.message})`;return i}}function Ur(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function Cl(e){return typeof e=="string"?e:void 0}var Ol=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:Ur},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:Ur},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:Ur},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:Cl}],Ll=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function Nl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ml(e){if(typeof e=="string"){let r=new Date(e);if(Number.isNaN(r.getTime()))return new Date().toISOString();let s=r.toISOString(),i=e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return i&&i.length>3?s.replace(/\.\d{3}Z$/,`.${i}Z`):s}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=e==null?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function sn(e,t,r){if(r!==void 0&&!(t in e))e[t]=r}function Dl(e){let r={...Nl(e.properties)?e.properties:{}},s={};for(let{property:n,optionKey:o,coerce:l}of Ol)if(n in r){let a=l(r[n]);if(a!==void 0)s[o]=a;delete r[n]}let i={};for(let{property:n,field:o}of Ll)if(n in r){let l=r[n];if(typeof l=="string")i[o]=l;delete r[n]}return delete r.$lib,delete r.$lib_version,sn(r,"$set",e.$set),sn(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:Ml(e.timestamp),...i,options:s,properties:r}}function nn(e,{createdAt:t,historicalMigration:r}){let s={created_at:t,batch:e.map(Dl)};if(r)s.historical_migration=!0;return s}var $l="/i/v1/analytics/events",kl=30000,Ul=new Set([408,500,502,503,504]);class Br{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??kl,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??((r)=>new Promise((s)=>T(s,r))),this.generateRequestId=t.generateRequestId??I,this.compress=t.compress??Ce}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),r=new Date(this.now()).toISOString(),{batch:s}=nn(e,{createdAt:r,historicalMigration:this.config.historicalMigration}),i=`${this.config.host}${$l}`,n=[],o=s,l=Math.max(1,this.config.maxAttempts);for(let a=1;a<=l;a++){let c=a===l,u=Z({created_at:r,...this.config.historicalMigration?{historical_migration:!0}:{},batch:o}),d,h;try{d=await this.sendOnce(i,u,a,t);let{response:p,signal:f}=d,{status:g}=p;if(g<200||g>=300)if(!c&&Ul.has(g)){let m=this.parseRetryAfter(p);await d.waitFor(d.cancelBody()).catch(()=>{}),h=this.backoffDelay(a,m)}else{let m=await this.buildHttpError(p,g,d.waitFor);return this.surfaceBatchFailure(t,n,o,m)}else{let m;try{m=await d.waitFor(this.parseResponse(p))}catch(E){if(f.aborted)throw E;return this.surfaceBatchFailure(t,n,o,Error(`Capture V1 returned an unparseable ${g} response body`))}let b=this.classify(o,m,n);if(b.length===0)return this.surfacePartialDrops(t,n);if(c)return void this.onError(new Se({requestId:t,drops:n,retryExhausted:b.map((E)=>E.uuid)}));o=b;let v=this.parseRetryAfter(p);h=this.backoffDelay(a,v)}}catch(p){if(d&&!d.signal.aborted)throw p;if(c)return this.surfaceBatchFailure(t,n,o,p);h=this.backoffDelay(a)}finally{d?.cleanup()}if(h!==void 0)await this.sleep(h)}}async sendOnce(e,t,r,s){let i=this.buildHeaders(r,s),n=t;if(this.config.compressionEnabled){let u=await this.compress(t,this.config.isDebug);if(u!==null)n=u,i["Content-Encoding"]="gzip"}let o=new AbortController,l="waiting for response headers",a,c=new Promise((u,d)=>{a=T(()=>{let h=Error(`Capture V1 request timed out ${l} after ${this.config.requestTimeoutMs}ms`);h.name="AbortError",d(h),o.abort(h)},this.config.requestTimeoutMs)});try{let u=this.fetchFn(e,{method:"POST",headers:i,body:n,signal:o.signal}),d=!1;u.then((m)=>{if(o.signal.aborted&&!d)this.cancelBody(m)}).catch(()=>{});let h=await Promise.race([u,c]);d=!0,l="while reading the response body";let p=!1,f,g=()=>f??=this.cancelBody(h);return{response:h,signal:o.signal,waitFor:(m)=>Promise.race([m,c]),cancelBody:g,cleanup:()=>{if(p)return;if(p=!0,clearTimeout(a),o.signal.aborted)g()}}}catch(u){throw clearTimeout(a),u}}buildHeaders(e,t){let r=`${this.config.libraryId}/${this.config.libraryVersion}`,s={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":r,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};if(this.config.userAgent)s["User-Agent"]=this.config.userAgent;return s}classify(e,t,r){let s=t.results??{},i=[];for(let n of e){let o=s[n.uuid];if(o){if(o.result==="drop")r.push({uuid:n.uuid,details:o.details??void 0});else if(o.result==="retry")i.push(n)}}return i}backoffDelay(e,t){let r=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);if(t===void 0)return r;return Math.max(r,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let r=t.trim();if(/^\d+$/.test(r)){let n=parseInt(r,10);return Number.isFinite(n)&&n>0?1000*n:void 0}let s=Date.parse(r);if(Number.isNaN(s))return;let i=s-this.now();return i>0?i:void 0}async parseResponse(e){let t=await e.text(),r=JSON.parse(t);if(typeof r!="object"||r===null||Array.isArray(r))throw Error("unexpected response shape");let s=r.results;if(s!==void 0&&(typeof s!="object"||s===null||Array.isArray(s)))throw Error("unexpected results shape");return{results:s??{}}}async buildHttpError(e,t,r){let s="";try{s=(await r(e.text())).slice(0,512)}catch{}let i=s?`: ${s}`:"";return Error(`Capture V1 request failed with HTTP ${t}${i}`)}surfaceBatchFailure(e,t,r,s){this.onError(new Se({requestId:e,drops:t,retryExhausted:r.map((i)=>i.uuid),cause:s}))}surfacePartialDrops(e,t){if(t.length>0)this.onError(new Se({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}}var le="ai-capture",kt="/i/v0/ai/batch/",Ut=8388608,on=5242880;var Bl=new TextEncoder;function jr(e){return Bl.encode(Z(e)).length}function an(e,t=Ut,r=on){let s=[],i=[],n=[],o=0;for(let l of e){if(l===void 0)continue;let a=jr(l);if(a>t){i.push({event:typeof l.event=="string"?l.event:"unknown",bytes:a});continue}if(n.length>0&&o+a>r)s.push(n),n=[],o=0;n.push(l),o+=a}if(n.length>0)s.push(n);return{batches:s,dropped:i}}var jl=100,ln=30000,Vl=50000,zl=50,ql=500,Gl="https://us.i.posthog.com",cn=new Set;function Bt(e,t){if(cn.has(e))return;cn.add(e),console.warn(`[PostHog] ${t}`)}function Kl(e){return typeof e=="string"?e.trim():""}function Hl(e){return(typeof e=="string"?e.trim():"")||void 0}function Wl(e){return(typeof e=="string"?e.trim():"")||Gl}function Xl(e){return(Array.isArray(e)?e:[e]).filter((r)=>typeof r=="string"&&r.trim().length>0)}function Ql(e){if(!e)return{};let t={};for(let[s,i]of Object.entries(e))t[`$feature/${s}`]=i;let r=Object.keys(e).filter((s)=>e[s]!==!1).sort();if(r.length>0)t.$active_feature_flags=r;return t}class Vr extends mt{get distinctIdHasSentFlagCalls(){return Object.fromEntries(this._distinctIdHasSentFlagCalls)}set distinctIdHasSentFlagCalls(e){this._distinctIdHasSentFlagCalls=new Map(Object.entries(e??{}))}constructor(e,t={}){let r=Kl(e),s={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5000,host:Wl(t.host),personalApiKey:Hl(t.secretKey??t.personalApiKey)};if(super(r,s),this._memoryStorage=new kr,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=s,this.captureMode=tn(),this.enableFullAiCapture=s.enableFullAiCapture===!0,this.privacyMode=s.privacyMode===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof s.featureFlagsPollingInterval=="number"?Math.max(s.featureFlagsPollingInterval,jl):s.featureFlagsPollingInterval===null?null:ln,typeof s.waitUntilDebounceMs=="number")this.options.waitUntilDebounceMs=Math.max(s.waitUntilDebounceMs,0);if(typeof s.waitUntilMaxWaitMs=="number")this.options.waitUntilMaxWaitMs=Math.max(s.waitUntilMaxWaitMs,0);if(!this.disabled&&(s.personalApiKey||s.flagDefinitionCacheProvider)){if(s.personalApiKey?.includes("phc_"))throw Error('A project API key ("phc_...") was provided as secretKey or personalApiKey. Pass the project API key as the first constructor argument. For local evaluation, set secretKey (or the deprecated personalApiKey alias) to a server-only Project Secret API Key ("phs_...") or Personal API Key ("phx_...") with feature flag read access.');if(s.enableLocalEvaluation!==!1)this.featureFlagsPoller=new Dr({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:s.personalApiKey,projectApiKey:r,timeout:s.requestTimeout??1e4,host:this.host,fetch:s.fetch,onError:(n)=>{this._events.emit("error",n)},onLoad:(n)=>{this._events.emit("localEvaluationFlagsLoaded",n)},onMinimalFlagCalledEvents:(n)=>{this._minimalFlagCalledEvents=n},customHeaders:this.getCustomHeaders(),cacheProvider:s.flagDefinitionCacheProvider,strictLocalEvaluation:s.strictLocalEvaluation,evaluationContexts:s.evaluationContexts??s.evaluationEnvironments})}this.errorTracking=new ae(this,s,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=s.maxCacheSize||Vl}enqueue(e,t,r,s){super.enqueue(e,t,r,s),this.scheduleDebouncedFlush()}_flushEventsAndSpans(e=!1){let t=this.flushWithPendingPromises();if(!this._traces||e&&this._traces.throttled)return t;return Pe([t,this._traces.flush().catch(()=>{})]).then(([r])=>{if(r.status==="rejected")throw r.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(e){let t=this._flushEventsAndSpans(e),r=this.options.waitUntil;if(r&&!this._waitUntilCycle)try{r(t.catch(()=>{}))}catch{}return t}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e)return;if(this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let n,o=new Promise((l)=>{n=l});try{e(o)}catch{return}this._waitUntilCycle={resolve:n,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,r=this.options.waitUntilMaxWaitMs??ql,s=t>=r;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(s)return void this.resolveWaitUntilFlush();let i=this.options.waitUntilDebounceMs??zl;this._waitUntilCycle.timer=T(()=>{this.resolveWaitUntilFlush()},i)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;if(e)clearTimeout(e.timer),this._waitUntilCycle=void 0;return e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getQueueRouteKey(e){return this.captureMode==="v1"&&rn(e)?We:He}persistedQueueKeyForRoute(e){if(e===le)return R.AiCaptureQueue;return e===We?R.AiQueue:R.Queue}getActiveQueueRoutes(){let e=this.captureMode==="v1"?[He,We]:[He];if(this._aiCaptureRouteActive)e.push(le);return e}getBatchEndpointPath(e){return e===le?kt:super.getBatchEndpointPath(e)}async sendBatch(e,t,r=He){if(r===le)return this.sendAiCaptureBatch(e,t);if(this.captureMode!=="v1"||r===We)return super.sendBatch(e,t,r);let s=e.filter((i)=>i!==void 0);await this.getV1Sender().sendV1Batch(s)}async sendAiCaptureBatch(e,t){let{batches:r,dropped:s}=an(e);for(let{event:i,bytes:n}of s){let o=`Event ${i} (${n} bytes) exceeds the ${Ut/1048576}MiB limit for ${kt}, dropping.`;this._logger.error(o),this._events.emit("error",Error(o))}for(let i of r)await this.sendAiSubBatch(i,t)}async sendAiSubBatch(e,t){try{await super.sendBatch(e,t,le)}catch(r){if(!me(r))throw r;if(e.length===1){let[i]=e,o=`Event ${typeof i.event=="string"?i.event:"unknown"} (${jr(i)} bytes) was rejected with 413 by ${kt} on its own, dropping.`;this._logger.error(o),this._events.emit("error",Error(o));return}let s=Math.ceil(e.length/2);await this.sendAiSubBatch(e.slice(0,s),t),await this.sendAiSubBatch(e.slice(s),t)}}getV1Sender(){if(!this._v1Sender)this._v1Sender=new Br({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3000,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:(e)=>this._events.emit("error",e),compress:(e)=>this.compressPayload(e)});return this._v1Sender}getLibraryVersion(){return Ui}get metrics(){if(!this._metrics)this._metrics=new At(this,Ft(this.options.metrics),this._logger);return this._metrics}initializeSpanContextManager(){return new Nt}hostResourceAttributes(){return{}}get _spanContextManager(){if(!this._spanContext)this._spanContext=this.initializeSpanContextManager();return this._spanContext}get _tracesPipeline(){if(!this.options.traces)return;if(!this._traces)this._traces=new Lt(this,Or(this.options.traces,this.hostResourceAttributes(),this._logger),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush());return this._traces}_tracingContext(){let e=this.context?.get();return{distinctId:e?.distinctId,sessionId:e?.sessionId}}startSpan(e,t){return this._tracesPipeline?.startSpan(e,t)??Q(t,this._spanContextManager.active())}withSpan(e,t,r){let s=typeof t=="function"?void 0:t,i=typeof t=="function"?t:r,n=this._tracesPipeline;if(!n)return qe(this._spanContextManager,Q(s,this._spanContextManager.active()),i);return s?n.withSpan(e,s,i):n.withSpan(e,i)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let e=super.getCommonEventProperties();if(this.options.isServer??!0)e.$is_server=!0;return e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,r){if(typeof e=="string")this._logger.warn(t);if(e.event==="$exception"&&!e._originatedFromCaptureException)this._logger.warn(r)}_sendPreparedEvent(e,t,r,s,i){return this.addPendingPromise(this._prepareEventMessage(t,s).then(({distinctId:n,event:o,properties:l,options:a})=>{let c={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},u={distinctId:n,event:o,properties:{...l,...this.getCommonEventProperties()}};return r?this.sendImmediate(e,u,c,i):this.enqueue(e,u,c,i)}).catch((n)=>{if(n)console.error(n)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}captureAi(e){if(this.disabled)return;let t=te(e.uuid,I);return this._sendPreparedAiEvent({...e,uuid:t},!1),t}async captureAiImmediate(e){if(this.disabled)return;let t=te(e.uuid,I);return await this._sendPreparedAiEvent({...e,uuid:t},!0),t}_sendPreparedAiEvent(e,t){if(typeof e?.event=="string"&&!e.event.startsWith("$ai_"))this._logger.debug(`captureAi called with non-AI event ${e.event}; routing it to the AI endpoint anyway.`);return this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",e,t,void 0,le)}identify({distinctId:e,properties:t={},disableGeoip:r}){let{$set:s,$set_once:i,$anon_distinct_id:n,...o}=t,c={$set:s||o,$set_once:i||{},$anon_distinct_id:n??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:c,disableGeoip:r},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:r}){let{$set:s,$set_once:i,$anon_distinct_id:n,...o}=t,c={$set:s||o,$set_once:i||{},$anon_distinct_id:n??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:c,disableGeoip:r},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:r={}}){if(Object.keys(t).length===0&&Object.keys(r).length===0)return;let s={};if(Object.keys(t).length>0)s.$set=t;if(Object.keys(r).length>0)s.$set_once=r;this.capture({distinctId:e,event:"$set",properties:s})}unsetPersonProperties({distinctId:e,properties:t}){let r=Xl(t);if(r.length===0)return;this.capture({distinctId:e,event:"$set",properties:{$unset:r}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(e){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(e)}getFeatureFlagKeysByEvaluationRuntime(e){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(e)??[]}async waitForLocalEvaluationReady(e=ln){if(this.isLocalEvaluationReady())return!0;if(this.featureFlagsPoller===void 0)return!1;return new Promise((t)=>{let r=setTimeout(()=>{s(),t(!1)},e),s=this._events.on("localEvaluationFlagsLoaded",(i)=>{clearTimeout(r),s(),t(i>0)})})}_resolveDistinctId(e,t){if(typeof e=="string")return{distinctId:e,options:t};return{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,r={},s){if(this.disabled)return void this._logger.warn("The client is disabled");let i=r.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let S=this._flagOverrides[e];if(S===void 0)return;let _=this._payloadOverrides?.[e];return{key:e,enabled:S!==!1,variant:typeof S=="string"?S:void 0,payload:_}}let{groups:n,disableGeoip:o}=r,{onlyEvaluateLocally:l,personProperties:a,groupProperties:c}=r,u=this.addLocalPersonAndGroupProperties(t,n,a,c);a=u.allPersonProperties,c=u.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(t,n,this.personPropertiesForLocalEvaluation(t,a),c);if(l==null)l=this.options.strictLocalEvaluation??!1;let h,p=!1,f,g,m,b,v,E,A;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let S=this.featureFlagsPoller?.featureFlagsByKey[e];if(S)try{let _=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(S,d,{matchValue:s});if(_){p=!0;let F=_.value;b=S.id,E="Evaluated locally",A=S.has_experiment,h={key:e,enabled:F!==!1,variant:typeof F=="string"?F:void 0,payload:_.payload??void 0,reason:E,reasonCode:S.active===!1?"flag_disabled":void 0}}}catch(_){if(_ instanceof O||_ instanceof y)this._logger?.info(`${_.name} when computing flag locally: ${e}: ${_.message}`);else throw _}}if(!p&&!l){let S=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,a,c,o,[e]);if(S===void 0)m=z.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=S.minimalFlagCalledEvents===!0,f=S.requestId,g=S.evaluatedAt;let _=[];if(S.errorsWhileComputingFlags)_.push(z.ERRORS_WHILE_COMPUTING);if(S.quotaLimited?.includes("feature_flags"))_.push(z.QUOTA_LIMITED);let F=S.flags[e];if(F===void 0)_.push(z.FLAG_MISSING);else{b=F.metadata?.id,v=F.metadata?.version,E=F.reason?.description??F.reason?.code,A=F.metadata?.has_experiment;let w;if(F.metadata?.payload!==void 0)try{w=JSON.parse(F.metadata.payload)}catch{w=F.metadata.payload}h={key:e,enabled:F.enabled,variant:F.variant??void 0,payload:w,reason:E,reasonCode:F.reason?.code}}if(_.length>0)m=_.join(",")}}if(i){let S=h===void 0?void 0:h.enabled===!1?!1:h.variant??!0,_={$feature_flag:e,$feature_flag_response:S,$feature_flag_id:b,$feature_flag_version:v,$feature_flag_reason:E,locally_evaluated:p,[`$feature/${e}`]:S,$feature_flag_request_id:f,$feature_flag_evaluated_at:p?Date.now():g};if(A!==void 0)_.$feature_flag_has_experiment=A;if(p&&this.featureFlagsPoller){let F=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();if(F!==void 0)_.$feature_flag_definitions_loaded_at=F}if(m)_.$feature_flag_error=m;this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:S,groups:n,disableGeoip:o,properties:_})}if(h!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides)h={...h,payload:this._payloadOverrides[e]};return h}async getFeatureFlag(e,t,r){Bt("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let s=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(r?.sendFeatureFlagEvents)});if(s===void 0)return;if(s.enabled===!1)return!1;return s.variant??!0}async getFeatureFlagPayload(e,t,r,s){if(Bt("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&e in this._payloadOverrides)return this._payloadOverrides[e];let i=await this._getFeatureFlagResult(e,t,{...s,sendFeatureFlagEvents:!1},r);if(i===void 0)return;return i.payload??null}async getFeatureFlagResult(e,t,r){let{distinctId:s,options:i}=this._resolveDistinctId(t,r);if(!s)return void this._logger.warn("[PostHog] distinctId is required — pass it explicitly or use withContext()");return this._getFeatureFlagResult(e,s,{...i,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(i?.sendFeatureFlagEvents)})}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let r=await t.json();if(typeof r=="string")try{return JSON.parse(r)}catch(s){}return r}async isFeatureEnabled(e,t,r){Bt("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let s=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(r?.sendFeatureFlagEvents)});if(s===void 0)return;if(s.enabled===!1)return!1;return!!(s.variant??!0)||!1}async getAllFlags(e,t){let{distinctId:r,options:s}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()"),{};return(await this.getAllFlagsAndPayloads(r,s)).featureFlags||{}}async getAllFlagsAndPayloads(e,t){let{distinctId:r,options:s}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads — pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:i,disableGeoip:n,flagKeys:o}=s||{},{onlyEvaluateLocally:l,personProperties:a,groupProperties:c}=s||{},u=this.addLocalPersonAndGroupProperties(r,i,a,c);a=u.allPersonProperties,c=u.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,i,this.personPropertiesForLocalEvaluation(r,a),c);if(l==null)l=this.options.strictLocalEvaluation??!1;let h=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,o),p={},f={},g=!0;if(h)p=h.response,f=h.payloads,g=h.fallbackToFlags;if(g&&!l){let m=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,a,c,n,o);p={...p,...m.flags||{}},f={...f,...m.payloads||{}}}if(this._flagOverrides!==void 0)p={...p,...this._flagOverrides};if(this._payloadOverrides!==void 0)f={...f,...this._payloadOverrides};return{featureFlags:p,featureFlagPayloads:f}}async evaluateFlags(e,t){let{distinctId:r,options:s}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags — pass it explicitly or use withContext()"),new Y({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new Y({host:this._getFeatureFlagEvaluationsHost(),distinctId:r,flags:{}});let{groups:i,disableGeoip:n}=s||{},o=s?.flagKeys??void 0;if(o?.length===0)return new Y({host:this._getFeatureFlagEvaluationsHost(),distinctId:r,groups:i,disableGeoip:n,flags:{}});let{onlyEvaluateLocally:l,personProperties:a,groupProperties:c}=s||{},u=this.addLocalPersonAndGroupProperties(r,i,a,c);a=u.allPersonProperties,c=u.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,i,this.personPropertiesForLocalEvaluation(r,a),c);if(l==null)l=this.options.strictLocalEvaluation??!1;let h=o?new Set(o):void 0,p={},f,g,m=!1,b=!1,v=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,o),E=new Set;if(v)for(let[_,F]of Object.entries(v.response)){let w=this.featureFlagsPoller?.featureFlagsByKey[_];p[_]={key:_,enabled:F!==!1,variant:typeof F=="string"?F:void 0,payload:v.payloads[_],id:w?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:w?.has_experiment},E.add(_)}let A=h!==void 0&&Array.from(h).some((_)=>this.featureFlagsPoller?.featureFlagsByKey[_]===void 0);if((v?v.fallbackToFlags||A:!0)&&!l){let _=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,a,c,n,o);if(_){this._minimalFlagCalledEvents=_.minimalFlagCalledEvents===!0,f=_.requestId,g=_.evaluatedAt,m=Boolean(_.errorsWhileComputingFlags),b=Array.isArray(_.quotaLimited)&&_.quotaLimited.includes("feature_flags");for(let[F,w]of Object.entries(_.flags)){if(E.has(F))continue;let Vt;if(w.metadata?.payload!==void 0)try{Vt=JSON.parse(w.metadata.payload)}catch{Vt=w.metadata.payload}p[F]={key:F,enabled:w.enabled,variant:w.variant,payload:Vt,id:w.metadata?.id,version:w.metadata?.version,reason:w.reason?.description??w.reason?.code,locallyEvaluated:!1,hasExperiment:w.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[_,F]of Object.entries(this._flagOverrides)){if(F===void 0){delete p[_];continue}let w=p[_];p[_]={key:_,enabled:F!==!1,variant:typeof F=="string"?F:void 0,payload:w?.payload,id:w?.id,version:w?.version,reason:w?.reason,locallyEvaluated:w?.locallyEvaluated??!1,hasExperiment:w?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[_,F]of Object.entries(this._payloadOverrides)){let w=p[_];if(w)p[_]={...w,payload:F}}if(h!==void 0){for(let _ of Object.keys(p))if(!h.has(_))delete p[_]}let S={};for(let[_,F]of Object.entries(v?.unresolved??{}))if(!Object.prototype.hasOwnProperty.call(p,_))S[_]=F;return new Y({host:this._getFeatureFlagEvaluationsHost(),distinctId:r,groups:i,disableGeoip:n,flags:p,unresolvedFlags:S,requestId:f,evaluatedAt:g,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:m,quotaLimited:b})}_shouldSendMinimalFlagCalledEvent(e,t){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&t.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:r,response:s,groups:i,disableGeoip:n,properties:o}=e,l=i&&Object.keys(i).length>0?`_${JSON.stringify(Object.entries(i).sort(([u],[d])=>u<d?-1:u>d?1:0))}`:"",a=`${r}_${s}${l}`,c=this._distinctIdHasSentFlagCalls.get(t)??new Set;if(this._distinctIdHasSentFlagCalls.delete(t),this._distinctIdHasSentFlagCalls.set(t,c),c.has(a))return;c.add(a);while(this._distinctIdHasSentFlagCalls.size>Math.max(this.maxCacheSize,1)){let u=this._distinctIdHasSentFlagCalls.keys().next().value;if(u===void 0)break;this._distinctIdHasSentFlagCalls.delete(u)}this.capture({distinctId:t,event:"$feature_flag_called",properties:o,groups:i,disableGeoip:n})}_resolveSendFeatureFlagEvents(e){return e??this.options.sendFeatureFlagEvent??!0}_getFeatureFlagEvaluationsHost(){if(!this._featureFlagEvaluationsHost)this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:(e)=>this._captureFlagCalledEventIfNeeded(e),resolveSendFeatureFlagEvents:(e)=>this._resolveSendFeatureFlagEvents(e),logWarning:(e)=>{if(this.options.featureFlagsLogWarnings!==!1)console.warn(`[PostHog] ${e}`)}};return this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:r,distinctId:s,disableGeoip:i}){this._sendPreparedEvent("capture",{distinctId:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:i},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:r,distinctId:s,disableGeoip:i}){await this._sendPreparedEvent("capture",{distinctId:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:i},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=(r)=>Object.fromEntries(r.map((s)=>[s,!0]));if(e===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){if("flags"in e){if(e.flags===!1)this._flagOverrides=void 0;else if(Array.isArray(e.flags))this._flagOverrides=t(e.flags);else if(e.flags!==void 0)this._flagOverrides={...e.flags}}if("payloads"in e){if(e.payloads===!1)this._payloadOverrides=void 0;else if(e.payloads!==void 0)this._payloadOverrides={...e.payloads}}return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if("flags"in t){let r=t.flags;if(r===!1||Array.isArray(r)||typeof r=="object"&&r!==null)return!0}if("payloads"in t){let r=t.payloads;if(r===!1||typeof r=="object"&&r!==null)return!0}return!1}withContext(e,t,r){if(!this.context)return t();return this.context.run(e,()=>($t(this),t()),r)}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t),$t(this)}async _shutdown(e){let t=Date.now()+(e??30000),r=this._consumeWaitUntilCycle();if(await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics)await W(this._metrics.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._metrics.reset();if(this._traces)await W(this._traces.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._traces.reset();try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this._distinctIdHasSentFlagCalls.clear(),r?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},s=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let i=new AbortController;s=T(()=>{i.abort()},this.options.requestTimeout),r.signal=i.signal}try{return await this.fetch(t,r)}catch(i){this._events.emit("error",i);return}finally{if(s)clearTimeout(s)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let r={},s={};for(let[i,n]of Object.entries(e))if(Yr(n)&&t&&i in t){let o={};for(let[l,a]of Object.entries(n))o[String(l)]=String(a);s[String(i)]=o}else r[String(i)]=String(n);return{personProperties:r,groupProperties:s}}async getFeatureFlagsForEvent(e,t,r,s){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let i=s?.personProperties||{},n=s?.groupProperties||{},o=s?.flagKeys;if(s?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let a={};for(let[c,u]of Object.entries(t||{}))a[c]=String(u);return await this.getAllFlags(e,{groups:a,personProperties:i,groupProperties:n,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:o})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let a={};for(let[c,u]of Object.entries(t||{}))a[c]=String(u);return await this.getAllFlags(e,{groups:a,personProperties:i,groupProperties:n,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:o})}return(await super.getFeatureFlagsStateless(e,t,i,n,r)).flags}addLocalPersonAndGroupProperties(e,t,r,s){let i={...r||{}},n={};if(t)for(let o of Object.keys(t))n[o]={$group_key:t[o],...s?.[o]||{}};return{allPersonProperties:i,allGroupProperties:n}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,r,s){return{distinctId:e,groups:t||{},personProperties:r||{},groupProperties:s||{},evaluationCache:{}}}captureException(e,t,r,s,i){if(!ae.isPreviouslyCapturedError(e)){let n=Error("PostHog syntheticException");this.addPendingPromise(ae.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:n},t,r,this.getContext()).then((o)=>this._capturePreparedEvent({...o,uuid:s,flags:i},!1)))}}async captureExceptionImmediate(e,t,r,s){if(!ae.isPreviouslyCapturedError(e)){let i=Error("PostHog syntheticException");return this.addPendingPromise(ae.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:i},t,r,this.getContext()).then((n)=>this.captureImmediate({...n,flags:s})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:r,event:s,properties:i,groups:n,flags:o,sendFeatureFlags:l,timestamp:a,disableGeoip:c,uuid:u}=e,d=Zi(e,this.context?.get()),h=t.includeContextProperties??!0,p=r||d?.distinctId,f=h?{...this.props,...d?.properties||{},...i||{}}:{...i||{}};if(s==="$exception"&&!(("$trace_id"in f)||("$span_id"in f)))Object.assign(f,await en());if(!p)p=I(),f.$process_person_profile=!1;if(h&&d?.sessionId&&!f.$session_id)f.$session_id=d.sessionId;let g=this._shouldSendMinimalFlagCalledEvent(s,f)?Te(f):f,m=this._runBeforeSend({distinctId:p,event:s,properties:g,groups:n,flags:o,sendFeatureFlags:l,timestamp:a,disableGeoip:c,uuid:u});if(!m)return Promise.reject(null);let b=await Promise.resolve().then(async()=>{if(o){if(l)console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.");return o._getEventProperties()}if(l){Bt("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let v=typeof l=="object"?l:void 0,E=await this.getFeatureFlagsForEvent(m.distinctId,n,c,v);return Ql(E)}return{}}).catch(()=>({})).then((v)=>{let E=m.groups||n;return{...v,...m.properties||{},...E!==void 0&&Object.keys(E).length>0?{$groups:E}:{}}});if(m.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof b.$raw_user_agent=="string"){if(es(b.$raw_user_agent,this.options.custom_blocked_useragents||[]))m.event="$bot_pageview",b.$browser_type="bot"}return{distinctId:m.distinctId,event:m.event,properties:b,options:{timestamp:m.timestamp,disableGeoip:m.disableGeoip,uuid:m.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let r=Array.isArray(t)?t:[t],s=e;for(let i of r)try{if(s=i(s),!s)return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!s.properties||Object.keys(s.properties).length===0){let n=`Event '${s.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(n)}}catch(n){return this._logger.error(`Error in before_send function for event '${e.event}':`,n),null}return s}}import{AsyncLocalStorage as Jl}from"node:async_hooks";var jt=new WeakMap;function zr(e,t,r){let s=e&&jt.get(e);if(r)jt.set(t,{signal:r,parent:s});else if(s)jt.set(t,s);return t}function un(e){let t=jt.get(e);while(t){if(t.signal.aborted)return!1;t=t.parent}return!0}class qr{constructor(){this.storage=new Jl}get(){let e=this.storage.getStore();return e&&un(e)?e:void 0}run(e,t,r){return this.storage.run(this.resolve(e,r),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){let r=this.get();if(t?.fresh===!0)return zr(void 0,{...e},t.signal);return zr(r,{distinctId:e.distinctId??r?.distinctId,sessionId:e.sessionId??r?.sessionId,properties:{...r?.properties||{},...e.properties||{}}},t?.signal)}}import{AsyncLocalStorage as Yl}from"node:async_hooks";class Gr{active(){return this._storage.getStore()}with(e,t){return this._storage.run(e,t)}constructor(){this._storage=new Yl}}import{gzip as Zl}from"node:zlib";import{promisify as ec}from"node:util";var tc=ec(Zl);async function dn(e,t=!0){try{let r=await tc(e);return new Uint8Array(r)}catch(r){if(t)console.error("Failed to gzip compress data",r);return null}}import{platform as rc,release as sc}from"node:os";function fn(){let e,t;try{e=rc(),t=sc()}catch{}return vr(e,t)}var hn="posthog-node";function ic(e,{organization:t,projectId:r,prefix:s,severityAllowList:i=["error"],sendExceptionsToPostHog:n=!0}={}){return(o)=>{if(!(i==="*"||i.includes(o.level)))return o;if(!o.tags)o.tags={};let a=o.tags[pn.POSTHOG_ID_TAG];if(a===void 0)return o;let c=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${a}`,c).toString();o.tags["PostHog Person URL"]=u;let d=o.exception?.values||[],h=d.map((g)=>({...g,stacktrace:g.stacktrace?{...g.stacktrace,type:"raw",frames:(g.stacktrace.frames||[]).map((m)=>({...m,platform:"node:javascript"}))}:void 0})),p={$exception_message:d[0]?.value||o.message,$exception_type:d[0]?.type,$exception_level:o.level,$exception_list:h,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:d[0]?.value||o.message,$sentry_exception_type:d[0]?.type,$sentry_tags:o.tags},f=js();if(f)p.$release_id=f;if(t&&r)p.$sentry_url=(s||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id;if(n)e.capture({event:"$exception",distinctId:a,properties:p});return o}}class pn{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(e,t,r,s,i){this.name=hn,this.name=hn,this.setupOnce=function(n,o){let l=o()?.getClient()?.getDsn()?.projectId;n(ic(e,{organization:t,projectId:l,prefix:r,severityAllowList:s,sendExceptionsToPostHog:i??!0}))}}}class Kr extends Vr{getLibraryId(){return"posthog-node"}compressPayload(e){return dn(e,this.isDebug)}initializeContext(){return new qr}initializeSpanContextManager(){return new Gr}hostResourceAttributes(){return fn()}createErrorPropertiesBuilder(){return new at([new Us,new ct,new ft,new ut,new ht],$s("node:javascript",Cs),[Wr(),(e)=>Ni(e,void 0,this._logger),ki()])}}function Yg(e,t){return new Kr(e,{host:"https://data.cline.bot",...t})}class ac{client;settings;logger;constructor(e){if(!e.client)throw Error("PostHog client is required for feature flags");this.logger=e.config.logger,this.settings={enabled:!0},this.client=e.client}async getAllFlagsAndPayloads(e){if(!this.enabled)return;let t=this.resolveDistinctId(e.context);if(!t)return this.logger?.log?.("PostHog feature flags requested without a distinct ID"),{};try{return await this.client.getAllFlagsAndPayloads(t,{flagKeys:e.flagKeys?[...e.flagKeys]:void 0})}catch(r){return this.logger?.error?.("Error getting PostHog feature flags",{error:r}),{}}}get enabled(){return this.settings.enabled}getSettings(){return{...this.settings}}async dispose(){try{await this.client.shutdown()}catch(e){this.logger?.error?.("Error shutting down PostHog feature flags client",{error:e})}}resolveDistinctId(e){return e?.distinctId?.trim()||e?.userId?.trim()||void 0}}export{ac as PostHogFeatureFlagsProvider,Yg as buildClinePostHogClient};
@@ -0,0 +1 @@
1
+ import{$i,Vn,He,ei,Zi}from"../../index-ffna8yzn.js";import"../../index-hkmarmve.js";import{R,kn,Wi}from"../../index-w9n2kgjk.js";import{Yo}from"../../index-9g67p34k.js";import{Xr,ui,Zr,es,ts,is,Pn,Dn}from"../../index-cadyf2yp.js";import{fo}from"../../index-m3gtj35r.js";import{ya,pn}from"../../index-bwet95hr.js";import"../../index-418gvd4a.js";import{v,e,r,o,t,sn,s,je}from"../../index-edf1hmcw.js";import{existsSync as W,mkdirSync as J,readFileSync as Q,writeFileSync as X}from"node:fs";import{resolve as Y}from"node:path";var Z=v(Xr(),1),E=v(ui(),1);var j=v(ui(),1),F=v(Zr(),1),k=v(es(),1),z=v(fo(),1),B=v(ya(),1),y=v(ts(),1),P=v(is(),1),A=v(pn(),1),G=v(Yo(),1);import{mkdirSync as qe,readFileSync as se,statSync as ne,writeFileSync as We}from"node:fs";var ee="machine-id",M,x=!1;function te(){if(!x)M=L(),x=!0;return M??V()}function N(i){let n=i?.trim();if(n)return n;let a=L();if(a)return a;return V()}function re(){let i=Z;return i.machineIdSync??i.default?.machineIdSync}function L(){try{let i=re();if(!i)return;return i().trim()||void 0}catch{return}}function V(){let i=He(),n=Y(i,ee);try{if(W(n)){let l=Q(n,"utf8").trim();if(l.length>0)return l}}catch{}let a=`cl-${R()}`;try{J(i,{recursive:!0}),X(n,a,"utf8")}catch{}return a}class D{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor(i){this.name=i.name??"OpenTelemetryAdapter",this.metadata={...i.metadata},this.meterProvider=i.meterProvider,this.loggerProvider=i.loggerProvider,this.meter=i.meterProvider?.getMeter("cline")??null,this.logger=i.loggerProvider?.getLogger("cline")??null,this.enabled=i.enabled??!0,this.distinctId=i.distinctId,this.commonProperties=i.commonProperties?{...i.commonProperties}:{}}emit(i,n){if(!this.isEnabled())return;this.emitLog(i,n,!1)}emitRequired(i,n){this.emitLog(i,n,!0)}recordCounter(i,n,a,l,d=!1){if(!this.meter||!d&&!this.isEnabled())return;let c=this.counters.get(i);if(!c)c=this.meter.createCounter(i,l?{description:l}:void 0),this.counters.set(i,c);c.add(n,this.flattenProperties(this.buildAttributes(a)))}recordHistogram(i,n,a,l,d=!1){if(!this.meter||!d&&!this.isEnabled())return;let c=this.histograms.get(i);if(!c)c=this.meter.createHistogram(i,l?{description:l}:void 0),this.histograms.set(i,c);c.record(n,this.flattenProperties(this.buildAttributes(a)))}recordGauge(i,n,a,l,d=!1){if(!this.meter||!d&&!this.isEnabled())return;let c=this.buildAttributes(a),u=JSON.stringify(c),p=this.gaugeValues.get(i);if(n===null){if(p){if(p.delete(u),p.size===0)this.gaugeValues.delete(i),this.gauges.delete(i)}return}let m=p;if(!m)m=new Map,this.gaugeValues.set(i,m);if(!this.gauges.has(i)){let h=this.meter.createObservableGauge(i,l?{description:l}:void 0);h.addCallback((g)=>{for(let C of this.snapshotGaugeSeries(i))g.observe(C.value,this.flattenProperties(C.attributes))}),this.gauges.set(i,h)}m.set(u,{value:n,attributes:c})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId(i){this.distinctId=i}setCommonProperties(i){this.commonProperties={...i}}updateCommonProperties(i){this.commonProperties={...this.commonProperties,...i}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog(i,n,a){if(!this.logger)return;let l=this.flattenProperties(this.buildAttributes(n,a)),d=ie(l.severity);this.logger.emit({severityText:d.text,severityNumber:d.number,body:i,attributes:l})}buildAttributes(i,n=!1){return{...this.commonProperties,...this.metadata,...i,...this.distinctId?{distinct_id:this.distinctId}:{},...n?{_required:!0}:{}}}snapshotGaugeSeries(i){let n=this.gaugeValues.get(i);if(!n)return[];return Array.from(n.values(),(a)=>({value:a.value,attributes:a.attributes?{...a.attributes}:void 0}))}flattenProperties(i,n="",a=new WeakSet,l=0){if(!i)return{};let d={},c=100,u=10;for(let[p,m]of Object.entries(i)){if(p==="__proto__"||p==="constructor"||p==="prototype")continue;let h=n?`${n}.${p}`:p;if(m===null||m===void 0){d[h]=String(m);continue}if(Array.isArray(m)){let g=m.length>c?m.slice(0,c):m;try{d[h]=JSON.stringify(g)}catch{d[h]="[UnserializableArray]"}if(m.length>c)d[`${h}_truncated`]=!0,d[`${h}_original_length`]=m.length;continue}if(typeof m==="object"){if(m instanceof Date){d[h]=m.toISOString();continue}if(m instanceof Error){d[h]=m.message;continue}if(a.has(m)){d[h]="[Circular]";continue}if(l>=u){d[h]="[MaxDepthExceeded]";continue}a.add(m),Object.assign(d,this.flattenProperties(m,h,a,l+1));continue}if(oe(m)){d[h]=m;continue}try{d[h]=JSON.stringify(m)}catch{d[h]=String(m)}}return d}}function ie(i){switch(typeof i==="string"?i.toLowerCase():i){case"trace":return{text:"TRACE",number:E.SeverityNumber.TRACE};case"debug":return{text:"DEBUG",number:E.SeverityNumber.DEBUG};case"warn":case"warning":return{text:"WARN",number:E.SeverityNumber.WARN};case"error":return{text:"ERROR",number:E.SeverityNumber.ERROR};case"fatal":return{text:"FATAL",number:E.SeverityNumber.FATAL};default:return{text:"INFO",number:E.SeverityNumber.INFO}}}function oe(i){return typeof i==="string"||typeof i==="number"||typeof i==="boolean"}var S=je((i)=>Array.isArray(i)?i.filter((n)=>typeof n==="string").map((n)=>n.trim()).filter(Boolean):void 0,o(e()).optional()).transform((i)=>{if(!i)return;let n=[...new Set(i)].sort((a,l)=>a.localeCompare(l));return n.length>0?n:void 0}),ae=s(["basic","agentic"]).catch("agentic"),le=sn(s($i),t({enabled:r()}).strip()).optional(),de=s(["plan","act"]),U=t({telemetryOptOut:r().default(!1).catch(!1),autoUpdateEnabled:r().default(!0).catch(!0),compactionStrategy:ae.optional(),compactionEnabled:r().optional().catch(void 0),planActMode:de.optional().catch(void 0),toolAutoApprove:r().optional().catch(void 0),tuiTheme:e().optional().catch(void 0),cloudModelId:e().optional().catch(void 0),disabledTools:S.optional(),tools:le,disabledPlugins:S.optional(),disabledAgentPlugins:S.optional()}).strip().transform((i)=>{let n={autoUpdateEnabled:i.autoUpdateEnabled,telemetryOptOut:i.telemetryOptOut};if(i.compactionStrategy)n.compactionStrategy=i.compactionStrategy;if(i.compactionEnabled!==void 0)n.compactionEnabled=i.compactionEnabled;if(i.planActMode)n.planActMode=i.planActMode;if(i.toolAutoApprove!==void 0)n.toolAutoApprove=i.toolAutoApprove;if(i.tuiTheme?.trim())n.tuiTheme=i.tuiTheme.trim();if(i.cloudModelId?.trim())n.cloudModelId=i.cloudModelId.trim();if(i.disabledTools?.length)n.disabledTools=i.disabledTools;if(i.tools&&Object.keys(i.tools).length>0)n.tools=i.tools;if(i.disabledPlugins?.length)n.disabledPlugins=i.disabledPlugins;if(i.disabledAgentPlugins?.length)n.disabledAgentPlugins=i.disabledAgentPlugins;return n});function T(){return U.parse({})}var I;function ce(i){if(i.disabledTools)Object.freeze(i.disabledTools);if(i.tools){for(let n of Object.values(i.tools))Object.freeze(n);Object.freeze(i.tools)}if(i.disabledPlugins)Object.freeze(i.disabledPlugins);if(i.disabledAgentPlugins)Object.freeze(i.disabledAgentPlugins);return Object.freeze(i)}function ue(i){let n;try{n=se(i,"utf8")}catch{return{value:T(),loadFailed:!0}}try{let a=U.safeParse(JSON.parse(n));return a.success?{value:a.data,loadFailed:!1}:{value:T(),loadFailed:!0}}catch{return{value:T(),loadFailed:!0}}}function me(){let i=ei(),n=ne(i,{throwIfNoEntry:!1}),a=n?.mtimeMs??0,l=n?.size??0,d=I;if(d&&d.path===i&&d.mtimeMs===a&&d.size===l)return d;let c=n?ue(i):{value:T(),loadFailed:!1},u=ce(c.value);return I={path:i,mtimeMs:a,size:l,value:u,loadFailed:c.loadFailed},I}function pe(){return me().value}function he(){return pe().telemetryOptOut}class K{name;logger;enabled;constructor(i={}){this.name=i.name??"TelemetryLoggerSink",this.logger=i.logger,this.enabled=i.enabled??!0}emit(i,n){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:i,properties:n})}emitRequired(i,n){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:i,properties:n})}recordCounter(i,n,a,l,d){if(!d&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:i,value:n,attributes:a,description:l,required:d===!0})}recordHistogram(i,n,a,l,d){if(!d&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:i,value:n,attributes:a,description:l,required:d===!0})}recordGauge(i,n,a,l,d){if(!d&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:i,value:n,attributes:a,description:l,required:d===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class O{adapters;metadata;distinctId;deviceId;commonProperties;constructor(i={}){if(this.adapters=[...i.adapters??[]],i.logger)this.adapters.push(new K({logger:i.logger}));this.metadata={...i.metadata??{}},this.distinctId=i.distinctId,this.deviceId=i.deviceId??te(),this.commonProperties={...i.commonProperties??{}}}addAdapter(i){this.adapters.push(i)}setDistinctId(i){this.distinctId=i}setMetadata(i){this.metadata={...i}}updateMetadata(i){this.metadata={...this.metadata,...i}}setCommonProperties(i){this.commonProperties={...i}}updateCommonProperties(i){this.commonProperties={...this.commonProperties,...i}}isEnabled(){return this.adapters.some((i)=>i.isEnabled())}capture(i){let n=this.buildAttributes(i.properties);for(let a of this.adapters)a.emit(i.event,n)}captureRequired(i,n){let a=this.buildAttributes(n);for(let l of this.adapters)l.emitRequired(i,a)}recordCounter(i,n,a,l,d=!1){let c=this.buildAttributes(a);for(let u of this.adapters)u.recordCounter(i,n,c,l,d)}recordHistogram(i,n,a,l,d=!1){let c=this.buildAttributes(a);for(let u of this.adapters)u.recordHistogram(i,n,c,l,d)}recordGauge(i,n,a,l,d=!1){let c=this.buildAttributes(a);for(let u of this.adapters)u.recordGauge(i,n,c,l,d)}async flush(){await Promise.all(this.adapters.map((i)=>i.flush()))}async dispose(){await Promise.all(this.adapters.map((i)=>i.dispose()))}buildAttributes(i){let n=typeof i?.distinct_id==="string"&&i.distinct_id.trim()?i.distinct_id.trim():this.distinctId,a={...this.commonProperties,...this.metadata,...i,...n?{distinct_id:n}:{},device_id:this.deviceId};return Object.fromEntries(Object.entries(a).filter(([,l])=>l!==void 0))}}class q{distinctId;metadata;commonProperties;constructor(i={}){this.distinctId=i.distinctId,this.metadata={...i.metadata??{}},this.commonProperties={...i.commonProperties??{}}}setDistinctId(i){this.distinctId=i}setMetadata(i){this.metadata={...i}}updateMetadata(i){this.metadata={...this.metadata,...i}}setCommonProperties(i){this.commonProperties={...i}}updateCommonProperties(i){this.commonProperties={...this.commonProperties,...i}}isEnabled(){return!1}capture(i){this.resolveProperties(i.properties)}captureRequired(i,n){this.resolveProperties(n)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties(i){let n=typeof i?.distinct_id==="string"&&i.distinct_id.trim()?i.distinct_id.trim():this.distinctId,a={...this.commonProperties,...this.metadata,...i,...n?{distinct_id:n}:{}};return Object.fromEntries(Object.entries(a).filter(([,l])=>l!==void 0))}}class H{meterProvider;loggerProvider;tracerProvider;options;constructor(i={}){this.options=i;let n=B.resourceFromAttributes({...i.resourceAttributes,[Pn]:i.serviceName??"cline",...i.serviceVersion?{[Dn]:i.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(n),this.loggerProvider=this.createLoggerProvider(n),this.tracerProvider=this.createTracerProvider(n),this.meterProvider)kn.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)j.logs.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(i="cline",n){return Wi.getTracer(i,n??this.options.serviceVersion)}createAdapter(i){return new D({...i,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService(i){let n=this.createAdapter({name:i.name,enabled:this.options.enabled,metadata:i.metadata});return new O({...i,adapters:[n],distinctId:N(i.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider(i){let n=_(this.options.metricsExporter);if(n.length===0)return null;let a=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),l=Math.min(30000,Math.floor(a*0.8)),d=n.map((c)=>Ee(c,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:a,timeout:l})).filter((c)=>c!==null);if(d.length===0)return null;return new P.MeterProvider({resource:i,readers:d})}createTracerProvider(i){let n=_(this.options.tracesExporter);if(n.length===0)return null;let a=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,l=this.options.otlpTracesHeaders??this.options.otlpHeaders,d=[],c=!1;for(let p of n){let m=be(p,{endpoint:a,headers:l,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(m){if(d.push(m),p!=="console")c=!0}}if(d.length===0)return null;let u=new G.NodeTracerProvider({resource:i,spanProcessors:c?[new Zi,...d]:d});if(c)Vn(u);return u}createLoggerProvider(i){let n=_(this.options.logsExporter);if(n.length===0)return null;let a=n.map((l)=>{let d=ve(l,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!d)return null;return new y.BatchLogRecordProcessor(d,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((l)=>l!==null);if(a.length===0)return null;return new y.LoggerProvider({resource:i,processors:a})}}function fe(i){let n=new H(i),a=n.createTelemetryService(i),l=()=>{a.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:i.enabled??!0,logsExporter:Array.isArray(i.logsExporter)?i.logsExporter.join(","):i.logsExporter,metricsExporter:Array.isArray(i.metricsExporter)?i.metricsExporter.join(","):i.metricsExporter,tracesExporter:Array.isArray(i.tracesExporter)?i.tracesExporter.join(","):i.tracesExporter,otlpProtocol:i.otlpProtocol,hasOtlpEndpoint:Boolean(i.otlpEndpoint),serviceName:i.serviceName,serviceVersion:i.serviceVersion})};if(!i.deferProviderCreatedEvent)l();return{provider:n,telemetry:a,emitProviderCreated:l}}function ge(i){if(he())return{telemetry:new q(i)};if(i.enabled!==!0)return{telemetry:new O({...i,distinctId:N(i.distinctId)})};return fe(i)}function Ye(i){let{telemetry:n,provider:a,emitProviderCreated:l}=ge(i);return{telemetry:n,provider:a,flush:async()=>{let d=a;if(d&&typeof d.forceFlush==="function")try{await d.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([n.dispose(),a?.dispose()])},...i.deferProviderCreatedEvent&&l?{emitProviderCreated:l}:{}}}function _(i){if(!i)return[];return(Array.isArray(i)?i:i.split(",")).map((n)=>n.trim()).filter((n)=>n==="console"||n==="otlp")}function ve(i,n){if(i==="console")return new y.ConsoleLogRecordExporter;if(!n.endpoint)return null;let a=w(n.endpoint,"/v1/logs");return new F.OTLPLogExporter({url:a,headers:n.headers})}function be(i,n){if(i==="console")return new A.SimpleSpanProcessor(new A.ConsoleSpanExporter);if(!n.endpoint)return null;let a=w(n.endpoint,"/v1/traces");return new A.BatchSpanProcessor(new z.OTLPTraceExporter({url:a,headers:n.headers}))}function Ee(i,n){if(i==="console")return new P.PeriodicExportingMetricReader({exporter:new P.ConsoleMetricExporter,exportIntervalMillis:n.interval,exportTimeoutMillis:n.timeout});if(!n.endpoint)return null;let a=w(n.endpoint,"/v1/metrics");return new P.PeriodicExportingMetricReader({exporter:new k.OTLPMetricExporter({url:a,headers:n.headers}),exportIntervalMillis:n.interval,exportTimeoutMillis:n.timeout})}function w(i,n){let a=new URL(i),l=a.pathname.endsWith("/")?a.pathname.slice(0,-1):a.pathname;return a.pathname=l.endsWith(n)?l:`${l}${n}`,a.toString()}var b={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};function Pe(i){let n=[i?.name,i?.platform].filter((a)=>typeof a==="string").join(" ").toLowerCase();if(!n)return;if(n.includes("vscode")||n.includes("visual studio code"))return b.VSCODE;if(n.includes("jetbrains")||n.includes("webstorm")||n.includes("intellij")||n.includes("pycharm")||n.includes("goland")||n.includes("clion")||n.includes("rider")||n.includes("android studio"))return b.JETBRAINS;if(n.includes("neovim"))return b.NEOVIM;if(n.includes("kanban"))return b.KANBAN;if(n.includes("desktop"))return b.DESKTOP;if(n.includes("cline-platform"))return b.WEB;if(n.includes("cline-cli")||n.includes("cline-acp"))return b.CLI;if(n.includes("cline-sdk")||n.includes("cline-core"))return b.CORE;return}function f(i){let n=i?.trim();return n?n:void 0}function ye(i){let n=i.client,a=Pe(n)??f(i.source),l=f(n.version),d=f(n.platform)??f(n.name),c=f(n.platformVersion)??l,u={cline_type:a,extension_version:l,platform:d,platform_version:c};if(i.user?.accountId===void 0)return u;let p=typeof i.user.accountId==="string"?f(i.user.accountId):void 0;return{...u,distinct_id:p??f(i.user.distinctId),user_id:p,account_id:p,account_email:p?f(i.user.email):void 0,organization_id:p?f(i.user.organizationId):void 0}}function Ae(i,n){let a={},l={},d,c=(u)=>({...n,...l,...a,...u,...d?{distinct_id:d}:{}});return{setDistinctId(u){d=f(u)},setMetadata(u){a={...u}},updateMetadata(u){a={...a,...u}},setCommonProperties(u){l={...u}},updateCommonProperties(u){l={...l,...u}},isEnabled:()=>i.isEnabled(),capture:(u)=>i.capture({event:u.event,properties:c(u.properties)}),captureRequired:(u,p)=>i.captureRequired(u,c(p)),recordCounter:(u,p,m,h,g)=>i.recordCounter(u,p,c(m),h,g),recordHistogram:(u,p,m,h,g)=>i.recordHistogram(u,p,c(m),h,g),recordGauge:(u,p,m,h,g)=>i.recordGauge(u,p,c(m),h,g),flush:()=>i.flush(),dispose:async()=>{}}}function et(i,n){return Ae(i,ye(n))}export{D as OpenTelemetryAdapter,H as OpenTelemetryProvider,et as createClientScopedTelemetryService,Ye as createConfiguredTelemetryHandle,ge as createConfiguredTelemetryService,fe as createOpenTelemetryTelemetryService,Ae as createScopedTelemetryService,ye as resolveClientTelemetryProperties,te as resolveCoreDeviceId,N as resolveCoreDistinctId};
@@ -0,0 +1 @@
1
+ import{fp,yp}from"./index-w9n2kgjk.js";import{i}from"./index-edf1hmcw.js";var v=i(function(y,s){var{defineProperty:c,getOwnPropertyDescriptor:_,getOwnPropertyNames:k}=Object,l=Object.prototype.hasOwnProperty,u=(t,e)=>{for(var o in e)c(t,o,{get:e[o],enumerable:!0})},d=(t,e,o,n)=>{if(e&&typeof e==="object"||typeof e==="function"){for(let r of k(e))if(!l.call(t,r)&&r!==o)c(t,r,{get:()=>e[r],enumerable:!(n=_(e,r))||n.enumerable})}return t},O=(t)=>d(c({},"__esModule",{value:!0}),t),f={};u(f,{refreshToken:()=>j});s.exports=O(f);var p=fp(),a=yp();async function j(t){let e=t?.project,o=t?.team;if(!e&&!o){let r=(0,a.findProjectInfo)();e=r.projectId,o=r.teamId}else if(!e||!o){let r=(0,a.findProjectInfo)();e=e??r.projectId,o=o??r.teamId}if(!e)throw new p.VercelOidcTokenError("Failed to refresh OIDC token: No project specified. Try re-linking your project with `vc link`");let n=(0,a.loadToken)(e);if(!n||(0,a.isExpired)((0,a.getTokenPayload)(n.token),t?.expirationBufferMs)){let r=await(0,a.getVercelToken)({expirationBufferMs:t?.expirationBufferMs});if(n=await(0,a.getVercelOidcToken)(r,e,o),!n)throw new p.VercelOidcTokenError("Failed to refresh OIDC token");(0,a.saveToken)(n,e)}process.env.VERCEL_OIDC_TOKEN=n.token;return}});export default v();
@@ -0,0 +1 @@
1
+ import{yp}from"./index-w9n2kgjk.js";export default yp();
@@ -0,0 +1 @@
1
+ import{vl,wl}from"./index-kqacxn3s.js";import"./index-hkmarmve.js";import{Xv,Oo,lt}from"./index-ffna8yzn.js";import"./index-ztb3cjfh.js";function g(e,o){return{...e?{projectId:e}:{},clientOptions:{transporterOptions:{fetchImplementation:o}}}}function a(e,o){let t=e?.[o];return typeof t==="string"&&t.trim().length>0?t:void 0}function p(e,o,t){let r=e?.[o];if(!r||typeof r!=="object"||Array.isArray(r))return;let n=r[t];return typeof n==="string"&&n.trim().length>0?n:void 0}async function v(e,o){let t=a(e.options,"project")??a(e.options,"projectId")??p(e.options,"gcp","projectId")??"",r=a(e.options,"location")??a(e.options,"region")??p(e.options,"gcp","region")??"us-central1",n=t||void 0,d=Oo(e.fetch),u=g(n,d);if(Xv(o.model.id)){let i=wl({project:t,location:r,googleAuthOptions:u,baseURL:e.baseUrl,headers:e.headers,fetch:d});return{operations:{language:(s)=>i(s)}}}let l=vl({project:t,location:r,apiKey:n?void 0:await lt(e),googleAuthOptions:n?u:void 0,baseURL:e.baseUrl,headers:e.headers,fetch:d});return{buildModelTools:(i)=>{let s={};for(let c of i)if(c.name==="web_search")s.web_search={tool:l.tools.googleSearch({})};return s},operations:{language:(i)=>l(i),imageGeneration:(i)=>l.image(i)}}}export{v as createVertexProviderModule};