granclaw 0.0.1-beta.48 → 0.0.1-beta.49

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.
@@ -28,6 +28,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
29
  exports.TelegramAdapter = void 0;
30
30
  const telegramify_markdown_1 = __importDefault(require("telegramify-markdown"));
31
+ const flatten_markdown_tables_js_1 = require("../lib/flatten-markdown-tables.js");
31
32
  const telegram_http_client_js_1 = require("./telegram-http-client.js");
32
33
  const agent_db_js_1 = require("../agent-db.js");
33
34
  const i18n_telegram_js_1 = require("../lib/i18n-telegram.js");
@@ -250,31 +251,63 @@ class TelegramAdapter {
250
251
  }
251
252
  async sendReply(chatId, text) {
252
253
  const MAX = 4000;
253
- // Convert standard markdown Telegram MarkdownV2. Fall back to plain
254
- // text if conversion throws (e.g. deeply malformed LLM output).
255
- let body;
256
- let parseMode;
257
- try {
258
- body = (0, telegramify_markdown_1.default)(text, 'escape');
259
- parseMode = 'MarkdownV2';
254
+ // Pre-process: flatten markdown tables into "key: value" lines. Telegram
255
+ // MarkdownV2 has no table support telegramify-markdown treats tables as
256
+ // plain-text unknowns and escapes every special character inside the
257
+ // cells, including link brackets/parens, and the pipe escape sequence
258
+ // `\|` is actually NOT a valid MarkdownV2 escape, so Telegram rejects
259
+ // the whole message, the .catch() fallback re-sends the escape-soup as
260
+ // plain text, and users see a wall of backslashes. Strip tables first.
261
+ const flattened = (0, flatten_markdown_tables_js_1.flattenMarkdownTables)(text);
262
+ // Chunk the ORIGINAL (flattened) text at newline boundaries BEFORE
263
+ // escaping. We then try to send each chunk as MarkdownV2 and, on any
264
+ // Telegram API error, fall back to sending that chunk's original
265
+ // unescaped form — never the escaped body. Previously the fallback
266
+ // used the escaped chunk, which is why users saw `\!` / `\.` / `\|`
267
+ // characters in their messages when MarkdownV2 parsing failed.
268
+ const chunks = [];
269
+ let remaining = flattened;
270
+ while (remaining.length > MAX) {
271
+ const slice = remaining.slice(0, MAX);
272
+ const splitAt = slice.lastIndexOf('\n') > MAX / 2 ? slice.lastIndexOf('\n') : MAX;
273
+ chunks.push(remaining.slice(0, splitAt));
274
+ remaining = remaining.slice(splitAt).trimStart();
260
275
  }
261
- catch {
262
- body = text;
263
- parseMode = undefined;
276
+ if (remaining.length > 0)
277
+ chunks.push(remaining);
278
+ if (chunks.length === 0)
279
+ return;
280
+ for (const chunk of chunks) {
281
+ await this.sendChunkWithFallback(chatId, chunk);
264
282
  }
265
- const send = (chunk) => this.bot
266
- .sendMessage(chatId, chunk, parseMode ? { parse_mode: parseMode } : undefined)
267
- .catch(() => this.bot.sendMessage(chatId, chunk, {})); // plain-text fallback
268
- if (body.length <= MAX) {
269
- await send(body);
283
+ }
284
+ /**
285
+ * Send one chunk as MarkdownV2, falling back to the ORIGINAL unescaped
286
+ * chunk as plain text on any Telegram error. Logs the failure reason so
287
+ * operators can diagnose why MarkdownV2 rendering was rejected.
288
+ */
289
+ async sendChunkWithFallback(chatId, original) {
290
+ let escaped;
291
+ try {
292
+ escaped = (0, telegramify_markdown_1.default)(original, 'escape');
293
+ }
294
+ catch (err) {
295
+ // telegramify-markdown itself crashed — go straight to plain text.
296
+ console.warn(`[telegram-adapter] telegramify-markdown threw, sending plain text: ${err.message}`);
297
+ await this.bot.sendMessage(chatId, original).catch(() => { });
270
298
  return;
271
299
  }
272
- let remaining = body;
273
- while (remaining.length > 0) {
274
- const slice = remaining.slice(0, MAX);
275
- const splitAt = slice.lastIndexOf('\n') > MAX / 2 ? slice.lastIndexOf('\n') : MAX;
276
- await send(remaining.slice(0, splitAt));
277
- remaining = remaining.slice(splitAt).trimStart();
300
+ try {
301
+ await this.bot.sendMessage(chatId, escaped, { parse_mode: 'MarkdownV2' });
302
+ }
303
+ catch (err) {
304
+ // Typical causes: unsupported escape sequence (e.g. `\|` which is not
305
+ // a valid MarkdownV2 escape), nesting limits, or link URLs with an
306
+ // unescaped `)`. Log the reason and send the unescaped ORIGINAL so
307
+ // the user sees a clean message instead of backslash-soup.
308
+ const msg = err.message ?? String(err);
309
+ console.warn(`[telegram-adapter] MarkdownV2 send failed, falling back to plain text: ${msg}`);
310
+ await this.bot.sendMessage(chatId, original).catch(() => { });
278
311
  }
279
312
  }
280
313
  stop() {
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ /**
3
+ * lib/flatten-markdown-tables.ts
4
+ *
5
+ * Telegram's MarkdownV2 parse mode has no table support. When the LLM
6
+ * returns a markdown table and we pass it through telegramify-markdown,
7
+ * the library treats every cell as plain-text-with-unknowns and escapes
8
+ * every special character inside — including the brackets and parens of
9
+ * links. Worse, `\|` (escaped pipe) is NOT a valid MarkdownV2 escape
10
+ * sequence per Telegram's parser spec, so the whole message gets
11
+ * rejected, the adapter falls back to plain text, and users see the
12
+ * raw escape-soup: `\|Precio\|\-\-\-\|\[Ver en...\]\(https://...\)`.
13
+ *
14
+ * This helper detects pipe-delimited markdown tables and rewrites each
15
+ * row as a set of `*Header*: cell` lines separated by blank lines. That
16
+ * renders cleanly in Telegram and preserves any markdown links inside
17
+ * the cells (they were never actually inside a table syntactically —
18
+ * telegramify-markdown just didn't know that).
19
+ *
20
+ * Non-table content passes through unchanged.
21
+ */
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.flattenMarkdownTables = flattenMarkdownTables;
24
+ const TABLE_ROW_RE = /^\s*\|(.+)\|\s*$/;
25
+ // A separator row is a table row whose cells only contain `-` / `:` / spaces.
26
+ const SEPARATOR_ROW_RE = /^\s*\|?[\s:|\-]+\|?\s*$/;
27
+ function parseRow(line) {
28
+ const m = line.match(TABLE_ROW_RE);
29
+ if (!m)
30
+ return null;
31
+ return m[1].split('|').map((c) => c.trim());
32
+ }
33
+ function isSeparatorLine(line) {
34
+ if (!SEPARATOR_ROW_RE.test(line))
35
+ return false;
36
+ // At least one `-` in the line — excludes blank `| | |` rows.
37
+ return /-/.test(line);
38
+ }
39
+ function findTableAt(lines, start) {
40
+ const header = parseRow(lines[start]);
41
+ if (!header)
42
+ return null;
43
+ if (start + 1 >= lines.length)
44
+ return null;
45
+ if (!isSeparatorLine(lines[start + 1]))
46
+ return null;
47
+ const separatorCells = parseRow(lines[start + 1]);
48
+ if (!separatorCells || separatorCells.length !== header.length)
49
+ return null;
50
+ const rows = [];
51
+ let i = start + 2;
52
+ while (i < lines.length) {
53
+ const row = parseRow(lines[i]);
54
+ if (!row)
55
+ break;
56
+ // Pad or truncate to the header width so missing trailing cells don't
57
+ // blow us up.
58
+ const normalised = header.map((_, idx) => row[idx]?.trim() ?? '');
59
+ rows.push(normalised);
60
+ i++;
61
+ }
62
+ // A table with only a header and separator but no data rows is still a
63
+ // table — we'll render it as an empty list, which is rare enough that
64
+ // it's not worth special-casing.
65
+ return { startLine: start, endLine: i - 1, headers: header, rows };
66
+ }
67
+ function renderTableAsLines(table) {
68
+ const out = [];
69
+ for (const row of table.rows) {
70
+ if (out.length > 0)
71
+ out.push(''); // blank line between entries
72
+ for (let j = 0; j < table.headers.length; j++) {
73
+ const header = table.headers[j];
74
+ const cell = row[j] ?? '';
75
+ if (!header && !cell)
76
+ continue;
77
+ if (!cell) {
78
+ out.push(`**${header}**:`);
79
+ }
80
+ else if (!header) {
81
+ out.push(cell);
82
+ }
83
+ else {
84
+ out.push(`**${header}**: ${cell}`);
85
+ }
86
+ }
87
+ }
88
+ return out;
89
+ }
90
+ function flattenMarkdownTables(md) {
91
+ if (!md.includes('|'))
92
+ return md; // fast path
93
+ const lines = md.split('\n');
94
+ const out = [];
95
+ let i = 0;
96
+ while (i < lines.length) {
97
+ const table = findTableAt(lines, i);
98
+ if (table) {
99
+ out.push(...renderTableAsLines(table));
100
+ i = table.endLine + 1;
101
+ }
102
+ else {
103
+ out.push(lines[i]);
104
+ i++;
105
+ }
106
+ }
107
+ return out.join('\n');
108
+ }
@@ -2,22 +2,33 @@
2
2
  /**
3
3
  * lib/i18n-telegram.ts
4
4
  *
5
- * Localized strings + cheap language detection for the Telegram adapter's
5
+ * Localized strings + language detection for the Telegram adapter's
6
6
  * acknowledgment + live status updates.
7
7
  *
8
8
  * Supported languages: English (en), Spanish (es), Simplified Chinese (zh).
9
9
  * Anything else falls back to English.
10
10
  *
11
- * Detection is intentionally heuristic — no ML, no library, no LLM call:
12
- * - zh wins if any CJK ideograph is present
13
- * - es wins if Spanish-only characters (ñ, ¿, ¡) appear or common Spanish
14
- * stopwords occur
15
- * - en is the default
11
+ * Detection cascade (in order):
12
+ * 1. Script-based short-circuits that are objectively correct any
13
+ * CJK ideograph means zh, any of ñ/¿/¡ means es. These win
14
+ * unconditionally because the code points never appear in our other
15
+ * supported languages.
16
+ * 2. For text long enough to be statistically meaningful (~12 chars),
17
+ * delegate to the `tinyld` library — a pure-JS port of Google's CLD
18
+ * with zero runtime deps. Covers the long-tail of phrasings without
19
+ * us maintaining a stopword list.
20
+ * 3. For very short text that tinyld cannot disambiguate confidently
21
+ * (single greetings like "hola", "gracias"), check against a small
22
+ * curated set of the most common Spanish chat openings. Kept tiny
23
+ * on purpose — this is a last-resort edge case, not the primary
24
+ * detection path.
25
+ * 4. Default to English.
16
26
  *
17
- * Misclassification is OK because the only user-visible English text is the
18
- * ack and the tool-step labels. The final agent response is generated by the
19
- * LLM in the user's actual language, so a wrong heuristic just means the
20
- * acknowledgement is slightly off — never the final answer.
27
+ * Misclassification is acceptable because the only user-visible localized
28
+ * text is the ack line, tool-step labels, and a done footer. The final
29
+ * agent response is generated by the LLM in the user's actual language,
30
+ * so a wrong heuristic just means the ack is slightly off — never the
31
+ * final answer.
21
32
  */
22
33
  Object.defineProperty(exports, "__esModule", { value: true });
23
34
  exports.detectLanguage = detectLanguage;
@@ -25,28 +36,61 @@ exports.ackText = ackText;
25
36
  exports.doneText = doneText;
26
37
  exports.toolLabel = toolLabel;
27
38
  exports.moreStepsSuffix = moreStepsSuffix;
28
- const SPANISH_HINTS = [
29
- // Spanish-only chars
30
- /[ñ¿¡]/i,
31
- // Common stopwords / greetings, anchored on word boundaries
32
- /\b(hola|gracias|por favor|qué|cómo|cuándo|dónde|para|porque|también|esto|esta|este|tengo|necesito|quiero)\b/i,
33
- // Common verbs used in everyday requests
34
- /\b(busca|buscar|necesita|necesitas|hace|hacer|dame|dime|ayuda|ayudar|puedo|puede|puedes|tienes|sabes|quieres|mira|mirar|revisa|revisar|crea|crear|escribe|escribir|analiza|analizar|explica|explicar|encuentra|encontrar|muestra|mostrar|abre|abrir|deja|dejar|pon|poner|trae|traer|usa|usar)\b/i,
35
- // Common words that are Spanish-only or statistically dominant in Spanish
36
- /\b(favor|bien|información|informacion|todo|todos|ahora|aquí|aqui|hay|más|mas|pero|solo|muy|cuando|donde|como|cual|cuál|este|esa|ese|eso|algo|alguien|nada|nadie|siempre|nunca|también|tampoco|después|despues|antes|durante|mientras|entonces|luego|además|ademas|sobre|entre|contra|hacia|desde|hasta|mediante|según|segun)\b/i,
37
- // Common greetings / closings not already covered
38
- /\b(buenos|buenas|hasta|hoy|mañana|manana|semana|mes|año|anio|lunes|martes|miércoles|miercoles|jueves|viernes|sábado|sabado|domingo)\b/i,
39
- ];
40
- const CHINESE_RE = /[\u4e00-\u9fff]/;
39
+ const tinyld_1 = require("tinyld");
40
+ // Any CJK ideograph → Chinese. The range covers the CJK Unified Ideographs
41
+ // block used by both Simplified and Traditional Chinese (and Japanese kanji,
42
+ // but we only advertise zh here).
43
+ const CJK_RE = /[\u4e00-\u9fff]/;
44
+ // Characters that appear essentially only in Spanish among our supported
45
+ // languages. ñ is Spanish + Basque/Catalan/etc., ¿/¡ are Spanish-only.
46
+ const SPANISH_ONLY_CHARS_RE = /[ñ¿¡]/i;
47
+ // Short-text disambiguation fallback for things tinyld confuses with other
48
+ // Romance languages (e.g., "hola amigo" pt). Intentionally small — keep
49
+ // it under ~20 entries and only add phrases that are unambiguous greetings
50
+ // or extremely common chat openings.
51
+ const SPANISH_SHORT_PHRASES = new Set([
52
+ 'hola',
53
+ 'hola amigo',
54
+ 'gracias',
55
+ 'de nada',
56
+ 'por favor',
57
+ 'buenos días',
58
+ 'buenos dias',
59
+ 'buenas tardes',
60
+ 'buenas noches',
61
+ 'qué tal',
62
+ 'que tal',
63
+ 'cómo estás',
64
+ 'como estas',
65
+ 'hasta luego',
66
+ 'adiós',
67
+ 'adios',
68
+ ]);
69
+ const TINYLD_MIN_LENGTH = 12;
41
70
  function detectLanguage(text) {
42
71
  if (!text)
43
72
  return 'en';
44
- if (CHINESE_RE.test(text))
73
+ const trimmed = text.trim();
74
+ if (!trimmed)
75
+ return 'en';
76
+ // 1. Scripts — unconditional.
77
+ if (CJK_RE.test(trimmed))
45
78
  return 'zh';
46
- for (const re of SPANISH_HINTS) {
47
- if (re.test(text))
48
- return 'es';
79
+ if (SPANISH_ONLY_CHARS_RE.test(trimmed))
80
+ return 'es';
81
+ // 2. tinyld for anything long enough to be meaningful.
82
+ if (trimmed.length >= TINYLD_MIN_LENGTH) {
83
+ const guess = (0, tinyld_1.detect)(trimmed);
84
+ if (guess === 'es' || guess === 'en' || guess === 'zh')
85
+ return guess;
86
+ // tinyld returned a language we do not support (fr/de/pt/it/...) or
87
+ // an empty string. Fall through to the default.
88
+ return 'en';
49
89
  }
90
+ // 3. Short-text Spanish greeting fallback.
91
+ if (SPANISH_SHORT_PHRASES.has(trimmed.toLowerCase()))
92
+ return 'es';
93
+ // 4. Default.
50
94
  return 'en';
51
95
  }
52
96
  // ── Acknowledgment line ────────────────────────────────────────────────────
@@ -65,7 +65,7 @@ Error generating stack: `+s.message+`
65
65
  *
66
66
  * @license MIT
67
67
  */function Uf(){return Uf=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Uf.apply(this,arguments)}function EN(e,t){if(e==null)return{};var n={},r=Object.keys(e),i,s;for(s=0;s<r.length;s++)i=r[s],!(t.indexOf(i)>=0)&&(n[i]=e[i]);return n}function PN(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function NN(e,t){return e.button===0&&(!t||t==="_self")&&!PN(e)}const jN=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],TN="6";try{window.__reactRouterVersion=TN}catch{}const MN="startTransition",dv=yE[MN];function RN(e){let{basename:t,children:n,future:r,window:i}=e,s=N.useRef();s.current==null&&(s.current=MP({window:i,v5Compat:!0}));let o=s.current,[a,l]=N.useState({action:o.action,location:o.location}),{v7_startTransition:u}=r||{},c=N.useCallback(d=>{u&&dv?dv(()=>l(d)):l(d)},[l,u]);return N.useLayoutEffect(()=>o.listen(c),[o,c]),N.useEffect(()=>wN(r),[r]),N.createElement(SN,{basename:t,children:n,location:a.location,navigationType:a.action,navigator:o,future:r})}const AN=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",IN=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,hv=N.forwardRef(function(t,n){let{onClick:r,relative:i,reloadDocument:s,replace:o,state:a,target:l,to:u,preventScrollReset:c,viewTransition:d}=t,h=EN(t,jN),{basename:p}=N.useContext(ci),g,m=!1;if(typeof u=="string"&&IN.test(u)&&(g=u,AN))try{let _=new URL(window.location.href),k=u.startsWith("//")?new URL(_.protocol+u):new URL(u),w=Jg(k.pathname,p);k.origin===_.origin&&w!=null?u=w+k.search+k.hash:m=!0}catch{}let y=sN(u,{relative:i}),x=ON(u,{replace:o,state:a,target:l,preventScrollReset:c,relative:i,viewTransition:d});function v(_){r&&r(_),_.defaultPrevented||x(_)}return N.createElement("a",Uf({},h,{href:g||y,onClick:m||s?r:v,ref:n,target:l}))});var fv;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(fv||(fv={}));var pv;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(pv||(pv={}));function ON(e,t){let{target:n,replace:r,state:i,preventScrollReset:s,relative:o,viewTransition:a}=t===void 0?{}:t,l=Ki(),u=Xi(),c=Pw(e,{relative:o});return N.useCallback(d=>{if(NN(d,n)){d.preventDefault();let h=r!==void 0?r:lc(u)===lc(c);l(e,{replace:h,state:i,preventScrollReset:s,relative:o,viewTransition:a})}},[u,l,c,r,i,n,e,s,o,a])}var I=typeof window<"u"?window:void 0,ot=typeof globalThis<"u"?globalThis:I;typeof self>"u"&&(ot.self=ot),typeof File>"u"&&(ot.File=function(){});var nn=ot==null?void 0:ot.navigator,X=ot==null?void 0:ot.document,ht=ot==null?void 0:ot.location,qf=ot==null?void 0:ot.fetch,Gf=ot!=null&&ot.XMLHttpRequest&&"withCredentials"in new ot.XMLHttpRequest?ot.XMLHttpRequest:void 0,gv=ot==null?void 0:ot.AbortController,DN=ot==null?void 0:ot.CompressionStream,$t=nn==null?void 0:nn.userAgent,ne=I??{},mv="1.368.2",jt={DEBUG:!1,LIB_VERSION:mv,LIB_NAME:"web",JS_SDK_VERSION:mv};function xv(e,t,n,r,i,s,o){try{var a=e[s](o),l=a.value}catch(u){return void n(u)}a.done?t(l):Promise.resolve(l).then(r,i)}function En(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function o(l){xv(s,r,i,o,a,"next",l)}function a(l){xv(s,r,i,o,a,"throw",l)}o(void 0)})}}function W(){return W=Object.assign?Object.assign.bind():function(e){for(var t=1;arguments.length>t;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},W.apply(null,arguments)}function Mw(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function Rw(){return(Rw=En(function*(e,t,n){t===void 0&&(t=!0);try{var r=new Blob([e],{type:"text/plain"}).stream().pipeThrough(new CompressionStream("gzip"));return yield new Response(r).blob()}catch(i){if(n!=null&&n.rethrow)throw i;return t&&console.error("Failed to gzip compress data",i),null}})).apply(this,arguments)}var LN=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"],FN=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],vv=function(e,t){if(t===void 0&&(t=[]),!e)return!1;var n=e.toLowerCase();return FN.concat(t).some(r=>{var i=r.toLowerCase();return n.indexOf(i)!==-1})};function de(e,t){return e.indexOf(t)!==-1}var td=function(e){return e.trim()},Yf=function(e){return e.replace(/^\$/,"")},Aw=Object.prototype,Iw=Aw.hasOwnProperty,nd=Aw.toString,_e=Array.isArray||function(e){return nd.call(e)==="[object Array]"},ur=e=>typeof e=="function",rt=e=>e===Object(e)&&!_e(e),Ps=e=>{if(rt(e)){for(var t in e)if(Iw.call(e,t))return!1;return!0}return!1},J=e=>e===void 0,et=e=>nd.call(e)=="[object String]",wu=e=>et(e)&&e.trim().length===0,kr=e=>e===null,ge=e=>J(e)||kr(e),On=e=>nd.call(e)=="[object Number]"&&e==e,cs=e=>On(e)&&e>0,Gn=e=>nd.call(e)==="[object Boolean]",$N=e=>e instanceof FormData,zN=e=>de(LN,e);function Ow(e){return e===null||typeof e!="object"}function uc(e,t){return{}.toString.call(e)==="[object "+t+"]"}function tm(e){return typeof Event<"u"&&function(t,n){try{return t instanceof n}catch{return!1}}(e,Event)}var BN=[!0,"true",1,"1","yes"],Gd=e=>de(BN,e),HN=[!1,"false",0,"0","no"];function Yn(e,t,n,r,i){return t>n&&(r.warn("min cannot be greater than max."),t=n),On(e)?e>n?(r.warn(" cannot be greater than max: "+n+". Using max value instead."),n):t>e?(r.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(r.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+i),Yn(i||n,t,n,r))}class VN{constructor(t){this.Pt={},this.Dt=t.Dt,this.jt=Yn(t.bucketSize,0,100,t.qt),this.$t=Yn(t.refillRate,0,this.jt,t.qt),this.Vt=Yn(t.refillInterval,0,864e5,t.qt)}Ht(t,n){var r=Math.floor((n-t.lastAccess)/this.Vt);r>0&&(t.tokens=Math.min(t.tokens+r*this.$t,this.jt),t.lastAccess=t.lastAccess+r*this.Vt)}consumeRateLimit(t){var n,r=Date.now(),i=String(t),s=this.Pt[i];return s?this.Ht(s,r):this.Pt[i]=s={tokens:this.jt,lastAccess:r},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.Dt)==null||n.call(this,t)),s.tokens===0)}stop(){this.Pt={}}}var Dl,yv,Yd,sn="Mobile",cc="iOS",fr="Android",Ys="Tablet",Dw=fr+" "+Ys,Lw="iPad",Fw="Apple",$w=Fw+" Watch",ca="Safari",Xs="BlackBerry",zw="Samsung",Bw=zw+"Browser",Hw=zw+" Internet",Oi="Chrome",WN=Oi+" OS",Vw=Oi+" "+cc,nm="Internet Explorer",Ww=nm+" "+sn,rm="Opera",UN=rm+" Mini",im="Edge",Uw="Microsoft "+im,Ds="Firefox",qw=Ds+" "+cc,Wa="Nintendo",Ua="PlayStation",Ls="Xbox",Gw=fr+" "+sn,Yw=sn+" "+ca,Vo="Windows",Xf=Vo+" Phone",_v="Nokia",Kf="Ouya",Xw="Generic",qN=Xw+" "+sn.toLowerCase(),Kw=Xw+" "+Ys.toLowerCase(),Jf="Konqueror",Nt="(\\d+(\\.\\d+)?)",Xd=new RegExp("Version/"+Nt),GN=new RegExp(Ls,"i"),YN=new RegExp(Ua+" \\w+","i"),XN=new RegExp(Wa+" \\w+","i"),sm=new RegExp(Xs+"|PlayBook|BB10","i"),KN={"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"},Jw=function(e,t){return t=t||"",de(e," OPR/")&&de(e,"Mini")?UN:de(e," OPR/")?rm:sm.test(e)?Xs:de(e,"IE"+sn)||de(e,"WPDesktop")?Ww:de(e,Bw)?Hw:de(e,im)||de(e,"Edg/")?Uw:de(e,"FBIOS")?"Facebook "+sn:de(e,"UCWEB")||de(e,"UCBrowser")?"UC Browser":de(e,"CriOS")?Vw:de(e,"CrMo")||de(e,Oi)?Oi:de(e,fr)&&de(e,ca)?Gw:de(e,"FxiOS")?qw:de(e.toLowerCase(),Jf.toLowerCase())?Jf:((n,r)=>r&&de(r,Fw)||function(i){return de(i,ca)&&!de(i,Oi)&&!de(i,fr)}(n))(e,t)?de(e,sn)?Yw:ca:de(e,Ds)?Ds:de(e,"MSIE")||de(e,"Trident/")?nm:de(e,"Gecko")?Ds:""},JN={[Ww]:[new RegExp("rv:"+Nt)],[Uw]:[new RegExp(im+"?\\/"+Nt)],[Oi]:[new RegExp("("+Oi+"|CrMo)\\/"+Nt)],[Vw]:[new RegExp("CriOS\\/"+Nt)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Nt)],[ca]:[Xd],[Yw]:[Xd],[rm]:[new RegExp("(Opera|OPR)\\/"+Nt)],[Ds]:[new RegExp(Ds+"\\/"+Nt)],[qw]:[new RegExp("FxiOS\\/"+Nt)],[Jf]:[new RegExp("Konqueror[:/]?"+Nt,"i")],[Xs]:[new RegExp(Xs+" "+Nt),Xd],[Gw]:[new RegExp("android\\s"+Nt,"i")],[Hw]:[new RegExp(Bw+"\\/"+Nt)],[nm]:[new RegExp("(rv:|MSIE )"+Nt)],Mozilla:[new RegExp("rv:"+Nt)]},QN=function(e,t){var n=Jw(e,t),r=JN[n];if(J(r))return null;for(var i=0;r.length>i;i++){var s=e.match(r[i]);if(s)return parseFloat(s[s.length-2])}return null},bv=[[new RegExp(Ls+"; "+Ls+" (.*?)[);]","i"),e=>[Ls,e&&e[1]||""]],[new RegExp(Wa,"i"),[Wa,""]],[new RegExp(Ua,"i"),[Ua,""]],[sm,[Xs,""]],[new RegExp(Vo,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[Xf,""];if(new RegExp(sn).test(t)&&!/IEMobile\b/.test(t))return[Vo+" "+sn,""];var n=/Windows NT ([0-9.]+)/i.exec(t);if(n&&n[1]){var r=KN[n[1]]||"";return/arm/i.test(t)&&(r="RT"),[Vo,r]}return[Vo,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>e&&e[3]?[cc,[e[3],e[4],e[5]||"0"].join(".")]:[cc,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{var t="";return e&&e.length>=3&&(t=J(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+fr+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+fr+")","i"),e=>e&&e[2]?[fr,[e[2],e[3],e[4]||"0"].join(".")]:[fr,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{var t=["Mac OS X",""];return e&&e[1]&&(t[1]=[e[1],e[2],e[3]||"0"].join(".")),t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[WN,""]],[/Linux|debian/i,["Linux",""]]],wv=function(e){return XN.test(e)?Wa:YN.test(e)?Ua:GN.test(e)?Ls:new RegExp(Kf,"i").test(e)?Kf:new RegExp("("+Xf+"|WPDesktop)","i").test(e)?Xf:/iPad/.test(e)?Lw:/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(e)?$w:sm.test(e)?Xs:/(kobo)\s(ereader|touch)/i.test(e)?"Kobo":new RegExp(_v,"i").test(e)?_v:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(e)||/(kf[a-z]+)( bui|\)).+silk\//i.test(e)?"Kindle Fire":/(Android|ZTE)/i.test(e)?new RegExp(sn).test(e)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(e)||/pixel[\daxl ]{1,6}/i.test(e)&&!/pixel c/i.test(e)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(e)||/lmy47v/i.test(e)&&!/QTAQZ3/i.test(e)?fr:Dw:new RegExp("(pda|"+sn+")","i").test(e)?qN:new RegExp(Ys,"i").test(e)&&!new RegExp(Ys+" pc","i").test(e)?Kw:""},ZN=e=>e instanceof Error;function ej(e){var t=globalThis._posthogChunkIds;if(t){var n=Object.keys(t);return Yd&&n.length===yv||(yv=n.length,Yd=n.reduce((r,i)=>{Dl||(Dl={});var s=Dl[i];if(s)r[s[0]]=s[1];else for(var o=e(i),a=o.length-1;a>=0;a--){var l=o[a],u=l==null?void 0:l.filename,c=t[i];if(u&&c){r[u]=c,Dl[i]=[u,c];break}}return r},{})),Yd}}class tj{constructor(t,n,r){r===void 0&&(r=[]),this.coercers=t,this.stackParser=n,this.modifiers=r}buildFromUnknown(t,n){n===void 0&&(n={});var r=n&&n.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(r,n,0).apply(t),s=this.buildParsingContext(n),o=this.parseStacktrace(i,s);return{$exception_list:this.convertToExceptionList(o,r),$exception_level:"error"}}modifyFrames(t){var n=this;return En(function*(){for(var r of t)r.stacktrace&&r.stacktrace.frames&&_e(r.stacktrace.frames)&&(r.stacktrace.frames=yield n.applyModifiers(r.stacktrace.frames));return t})()}coerceFallback(t){var n;return{type:"Error",value:"Unknown error",stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(t,n){var r,i;return t.cause!=null&&(r=this.parseStacktrace(t.cause,n)),t.stack!=""&&t.stack!=null&&(i=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?n.skipFirstLines:0),n.chunkIdMap)),W({},t,{cause:r,stack:i})}applyChunkIds(t,n){return t.map(r=>(r.filename&&n&&(r.chunk_id=n[r.filename]),r))}applyCoercers(t,n){for(var r of this.coercers)if(r.match(t))return r.coerce(t,n);return this.coerceFallback(n)}applyModifiers(t){var n=this;return En(function*(){var r=t;for(var i of n.modifiers)r=yield i(r);return r})()}convertToExceptionList(t,n){var r,i,s,o={type:t.type,value:t.value,mechanism:{type:(r=n.type)!==null&&r!==void 0?r:"generic",handled:(i=n.handled)===null||i===void 0||i,synthetic:(s=t.synthetic)!==null&&s!==void 0&&s}};t.stack&&(o.stacktrace={type:"raw",frames:t.stack});var a=[o];return t.cause!=null&&a.push(...this.convertToExceptionList(t.cause,W({},n,{handled:!0}))),a}buildParsingContext(t){var n;return{chunkIdMap:ej(this.stackParser),skipFirstLines:(n=t.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(t,n,r){r===void 0&&(r=0);var i=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(t,n,o);return this.applyCoercers(s,a)}};return W({},n,{syntheticException:r==0?n.syntheticException:void 0,mechanism:t,apply:s=>i(s,r),next:s=>i(s,r+1)})}}var Ks="?";function Qf(e,t,n,r,i){var s={platform:e,filename:t,function:n==="<anonymous>"?Ks:n,in_app:!0};return J(r)||(s.lineno=r),J(i)||(s.colno=i),s}var Qw=(e,t)=>{var n=e.indexOf("safari-extension")!==-1,r=e.indexOf("safari-web-extension")!==-1;return n||r?[e.indexOf("@")!==-1?e.split("@")[0]:Ks,n?"safari-extension:"+t:"safari-web-extension:"+t]:[e,t]},nj=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,rj=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ij=/\((\S*)(?::(\d+))(?::(\d+))\)/,sj=(e,t)=>{var n=nj.exec(e);if(n){var[,r,i,s]=n;return Qf(t,r,Ks,+i,+s)}var o=rj.exec(e);if(o){if(o[2]&&o[2].indexOf("eval")===0){var a=ij.exec(o[2]);a&&(o[2]=a[1],o[3]=a[2],o[4]=a[3])}var[l,u]=Qw(o[1]||Ks,o[2]);return Qf(t,u,l,o[3]?+o[3]:void 0,o[4]?+o[4]:void 0)}},oj=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,aj=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,lj=(e,t)=>{var n=oj.exec(e);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var r=aj.exec(n[3]);r&&(n[1]=n[1]||"eval",n[3]=r[1],n[4]=r[2],n[5]="")}var i=n[3],s=n[1]||Ks;return[s,i]=Qw(s,i),Qf(t,i,s,n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},kv=/\(error: (.*)\)/;class uj{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,n){var r=et(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:r?t.stack:void 0,cause:t.cause?n.next(t.cause):void 0,synthetic:!1}}getType(t){return this.isDOMError(t)?"DOMError":"DOMException"}getValue(t){var n=t.name||(this.isDOMError(t)?"DOMError":"DOMException");return t.message?n+": "+t.message:n}isDOMException(t){return uc(t,"DOMException")}isDOMError(t){return uc(t,"DOMError")}}class cj{match(t){return(n=>n instanceof Error)(t)}coerce(t,n){return{type:this.getType(t),value:this.getMessage(t,n),stack:this.getStack(t),cause:t.cause?n.next(t.cause):void 0,synthetic:!1}}getType(t){return t.name||t.constructor.name}getMessage(t,n){var r=t.message;return String(r.error&&typeof r.error.message=="string"?r.error.message:r)}getStack(t){return t.stacktrace||t.stack||void 0}}class dj{constructor(){}match(t){return uc(t,"ErrorEvent")&&t.error!=null}coerce(t,n){var r;return n.apply(t.error)||{type:"ErrorEvent",value:t.message,stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}}var hj=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class fj{match(t){return typeof t=="string"}coerce(t,n){var r,[i,s]=this.getInfos(t);return{type:i??"Error",value:s??t,stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}getInfos(t){var n="Error",r=t,i=t.match(hj);return i&&(n=i[1],r=i[2]),[n,r]}}var pj=["fatal","error","warning","log","info","debug"];function Zw(e,t){t===void 0&&(t=40);var n=Object.keys(e);if(n.sort(),!n.length)return"[object has no keys]";for(var r=n.length;r>0;r--){var i=n.slice(0,r).join(", ");if(t>=i.length)return r===n.length?i:i.length>t?i.slice(0,t)+"...":i}return""}class gj{match(t){return typeof t=="object"&&t!==null}coerce(t,n){var r,i=this.getErrorPropertyFromObject(t);return i?n.apply(i):{type:this.getType(t),value:this.getValue(t),stack:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return tm(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){var n="'"+t.name+"' captured as exception";return"message"in t&&typeof t.message=="string"&&(n+=" with message: '"+t.message+"'"),n}if("message"in t&&typeof t.message=="string")return t.message;var r=this.getObjectClassName(t);return(r&&r!=="Object"?"'"+r+"'":"Object")+" captured as exception with keys: "+Zw(t)}isSeverityLevel(t){return et(t)&&!wu(t)&&pj.indexOf(t)>=0}getErrorPropertyFromObject(t){for(var n in t)if({}.hasOwnProperty.call(t,n)){var r=t[n];if(ZN(r))return r}}getObjectClassName(t){try{var n=Object.getPrototypeOf(t);return n?n.constructor.name:void 0}catch{return}}}class mj{match(t){return tm(t)}coerce(t,n){var r,i=t.constructor.name;return{type:i,value:i+" captured as exception with keys: "+Zw(t),stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class xj{match(t){return Ow(t)}coerce(t,n){var r;return{type:"Error",value:"Primitive value captured as exception: "+String(t),stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class vj{match(t){return uc(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!tm(t))return!1;try{var n=t.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(t,n){var r,i=this.getUnhandledRejectionReason(t);return Ow(i)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(i),stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}:n.apply(i)}getUnhandledRejectionReason(t){try{if("reason"in t)return t.reason;if("detail"in t&&t.detail!=null&&typeof t.detail=="object"&&"reason"in t.detail)return t.detail.reason}catch{}return t}}var ek=function(e,t){var{debugEnabled:n}=t===void 0?{}:t,r={C(i){if(I&&(jt.DEBUG||ne.POSTHOG_DEBUG||n)&&!J(I.console)&&I.console){for(var s=("__rrweb_original__"in I.console[i])?I.console[i].__rrweb_original__:I.console[i],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(e,...a)}},info(){for(var i=arguments.length,s=new Array(i),o=0;i>o;o++)s[o]=arguments[o];r.C("log",...s)},warn(){for(var i=arguments.length,s=new Array(i),o=0;i>o;o++)s[o]=arguments[o];r.C("warn",...s)},error(){for(var i=arguments.length,s=new Array(i),o=0;i>o;o++)s[o]=arguments[o];r.C("error",...s)},critical(){for(var i=arguments.length,s=new Array(i),o=0;i>o;o++)s[o]=arguments[o];console.error(e,...s)},uninitializedWarning(i){r.error("You must initialize PostHog before calling "+i)},createLogger:(i,s)=>ek(e+" "+i,s)};return r},K=ek("[PostHog.js]"),We=K.createLogger,yj=We("[ExternalScriptsLoader]"),Ll=(e,t,n)=>{if(e.config.disable_external_dependency_loading)return yj.warn(t+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var r=X==null?void 0:X.querySelectorAll("script");if(r){for(var i,s=function(){if(r[o].src===t){var l=r[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)}),l.onerror=u=>n(u),{v:void 0})}},o=0;r.length>o;o++)if(i=s())return i.v}var a=()=>{if(!X)return n("document not found");var l=X.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=t,l.onload=d=>{l.__posthog_loading_callback_fired=!0,n(void 0,d)},l.onerror=d=>n(d),e.config.prepare_external_dependency_script&&(l=e.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(e.config.external_scripts_inject_target==="head")X.head.appendChild(l);else{var u,c=X.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):X.body.appendChild(l)}};X!=null&&X.body?a():X==null||X.addEventListener("DOMContentLoaded",a)};ne.__PosthogExtensions__=ne.__PosthogExtensions__||{},ne.__PosthogExtensions__.loadExternalDependency=(e,t,n)=>{if(t!=="remote-config")if(e._resolvedSdkVersion){var r=e.requestRouter.endpointFor("assets","/static/"+e._resolvedSdkVersion+"/"+t+".js");Ll(e,r,n)}else{var i="/static/"+t+".js?v="+e.version;if(t==="toolbar"){var s=3e5;i=i+"&t="+Math.floor(Date.now()/s)*s}var o=e.requestRouter.endpointFor("assets",i);Ll(e,o,n)}else{var a=e.requestRouter.endpointFor("assets","/array/"+e.config.token+"/config.js");Ll(e,a,n)}},ne.__PosthogExtensions__.loadSiteApp=(e,t,n)=>{var r=e.requestRouter.endpointFor("api",t);Ll(e,r,n)};var tk="$people_distinct_id",dc="$device_id",Wo="__alias",Uo="__timers",Sv="$autocapture_disabled_server_side",Zf="$heatmaps_enabled_server_side",Cv="$exception_capture_enabled_server_side",ep="$error_tracking_suppression_rules",Ev="$error_tracking_capture_extension_exceptions",Pv="$web_vitals_enabled_server_side",nk="$dead_clicks_enabled_server_side",Nv="$product_tours_enabled_server_side",jv="$web_vitals_allowed_metrics",Fl="$session_recording_remote_config",hc="$sesid",rk="$session_is_sampled",Ns="$enabled_feature_flags",qo="$early_access_features",tp="$feature_flag_details",Go="$stored_person_properties",Si="$stored_group_properties",np="$surveys",da="$flag_call_reported",rp="$flag_call_reported_session_id",ip="$feature_flag_errors",fc="$feature_flag_evaluated_at",kn="$user_state",sp="$client_session_props",op="$capture_rate_limit",ap="$initial_campaign_params",lp="$initial_referrer_info",pc="$initial_person_info",gc="$epp",ik="__POSTHOG_TOOLBAR__",$l="$posthog_cookieless",_j=[tk,Wo,"__cmpns",Uo,"$session_recording_enabled_server_side",Zf,hc,Ns,ep,kn,qo,tp,Si,Go,np,da,rp,ip,fc,sp,op,ap,lp,gc,pc],om="PostHog loadExternalDependency extension not found.",ir="on_reject",Pn="always",ns="anonymous",rs="identified",up="identified_only",mc="visibilitychange",xc="beforeunload",ds="$pageview",Kd="$pageleave",Jd="$identify",Tv="$groupidentify";function zl(e,t){_e(e)&&e.forEach(t)}function Re(e,t){if(!ge(e))if(_e(e))e.forEach(t);else if($N(e))e.forEach((r,i)=>t(r,i));else for(var n in e)Iw.call(e,n)&&t(e[n],n)}var Ge=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;t>r;r++)n[r-1]=arguments[r];for(var i of n)for(var s in i)i[s]!==void 0&&(e[s]=i[s]);return e};function ku(e){for(var t=Object.keys(e),n=t.length,r=new Array(n);n--;)r[n]=[t[n],e[t[n]]];return r}var Mv=function(e){try{return e()}catch{return}},bj=function(e){return function(){try{for(var t=arguments.length,n=new Array(t),r=0;t>r;r++)n[r]=arguments[r];return e.apply(this,n)}catch(i){K.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),K.critical(i)}}},am=function(e){var t={};return Re(e,function(n,r){(et(n)&&n.length>0||On(n))&&(t[r]=n)}),t},wj=["herokuapp.com","vercel.app","netlify.app"];function kj(e){var t=e==null?void 0:e.hostname;if(!et(t))return!1;var n=t.split(".").slice(-2).join(".");for(var r of wj)if(n===r)return!1;return!0}function Ze(e,t,n,r){var{capture:i=!1,passive:s=!0}=r??{};e==null||e.addEventListener(t,n,{capture:i,passive:s})}function sk(e){return e.name==="ph_toolbar_internal"}Math.trunc||(Math.trunc=function(e){return 0>e?Math.ceil(e):Math.floor(e)}),Number.isInteger||(Number.isInteger=function(e){return On(e)&&isFinite(e)&&Math.floor(e)===e});class vc{constructor(t){if(this.bytes=t,t.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(t,n,r,i){if(!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(r)||!Number.isInteger(i)||0>t||0>n||0>r||0>i||t>0xffffffffffff||n>4095||r>1073741823||i>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=t/Math.pow(2,40),s[1]=t/Math.pow(2,32),s[2]=t/Math.pow(2,24),s[3]=t/Math.pow(2,16),s[4]=t/Math.pow(2,8),s[5]=t,s[6]=112|n>>>8,s[7]=n,s[8]=128|r>>>24,s[9]=r>>>16,s[10]=r>>>8,s[11]=r,s[12]=i>>>24,s[13]=i>>>16,s[14]=i>>>8,s[15]=i,new vc(s)}toString(){for(var t="",n=0;this.bytes.length>n;n++)t=t+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),n!==3&&n!==5&&n!==7&&n!==9||(t+="-");if(t.length!==36)throw new Error("Invalid UUIDv7 was generated");return t}clone(){return new vc(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(var n=0;16>n;n++){var r=this.bytes[n]-t.bytes[n];if(r!==0)return Math.sign(r)}return 0}}class Sj{constructor(){this.I=0,this.S=0,this.k=new Cj}generate(){var t=this.generateOrAbort();if(J(t)){this.I=0;var n=this.generateOrAbort();if(J(n))throw new Error("Could not generate UUID after timestamp reset");return n}return t}generateOrAbort(){var t=Date.now();if(t>this.I)this.I=t,this.A();else{if(this.I>=t+1e4)return;this.S++,this.S>4398046511103&&(this.I++,this.A())}return vc.fromFieldsV7(this.I,Math.trunc(this.S/Math.pow(2,30)),this.S&Math.pow(2,30)-1,this.k.nextUint32())}A(){this.S=1024*this.k.nextUint32()+(1023&this.k.nextUint32())}}var Rv,ok=e=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var t=0;e.length>t;t++)e[t]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return e};I&&!J(I.crypto)&&crypto.getRandomValues&&(ok=e=>crypto.getRandomValues(e));class Cj{constructor(){this.T=new Uint32Array(8),this.N=1/0}nextUint32(){return this.T.length>this.N||(ok(this.T),this.N=0),this.T[this.N++]}}var Lr=()=>Ej().toString(),Ej=()=>(Rv||(Rv=new Sj)).generate(),ko="",Pj=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,qn={Ut:()=>!!X,Yt(e){K.error("cookieStore error: "+e)},Wt(e){if(X){try{for(var t=e+"=",n=X.cookie.split(";").filter(s=>s.length),r=0;n.length>r;r++){for(var i=n[r];i.charAt(0)==" ";)i=i.substring(1,i.length);if(i.indexOf(t)===0)return decodeURIComponent(i.substring(t.length,i.length))}}catch{}return null}},Gt(e){var t;try{t=JSON.parse(qn.Wt(e))||{}}catch{}return t},Xt(e,t,n,r,i){if(X)try{var s="",o="",a=function(c,d){if(d){var h=function(g,m){if(m===void 0&&(m=X),ko)return ko;if(!m||["localhost","127.0.0.1"].includes(g))return"";for(var y=g.split("."),x=Math.min(y.length,8),v="dmn_chk_"+Lr();!ko&&x--;){var _=y.slice(x).join("."),k=v+"=1;domain=."+_+";path=/";m.cookie=k+";max-age=3",m.cookie.includes(v)&&(m.cookie=k+";max-age=0",ko=_)}return ko}(c);if(!h){var p=(g=>{var m=g.match(Pj);return m?m[0]:""})(c);p!==h&&K.info("Warning: cookie subdomain discovery mismatch",p,h),h=p}return h?"; domain=."+h:""}return""}(X.location.hostname,r);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}i&&(o="; secure");var u=e+"="+encodeURIComponent(JSON.stringify(t))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&K.warn("cookieStore warning: large cookie, len="+u.length),X.cookie=u,u}catch{return}},Jt(e,t){if(X!=null&&X.cookie)try{qn.Xt(e,"",-1,t)}catch{return}}},Qd=null,Be={Ut(){if(!kr(Qd))return Qd;var e=!0;if(J(I))e=!1;else try{var t="__mplssupport__";Be.Xt(t,"xyz"),Be.Wt(t)!=='"xyz"'&&(e=!1),Be.Jt(t)}catch{e=!1}return e||K.error("localStorage unsupported; falling back to cookie store"),Qd=e,e},Yt(e){K.error("localStorage error: "+e)},Wt(e){try{return I==null?void 0:I.localStorage.getItem(e)}catch(t){Be.Yt(t)}return null},Gt(e){try{return JSON.parse(Be.Wt(e))||{}}catch{}return null},Xt(e,t){try{I==null||I.localStorage.setItem(e,JSON.stringify(t))}catch(n){Be.Yt(n)}},Jt(e){try{I==null||I.localStorage.removeItem(e)}catch(t){Be.Yt(t)}}},Nj=[dc,"distinct_id",hc,rk,gc,pc,kn],Bl={},jj={Ut:()=>!0,Yt(e){K.error("memoryStorage error: "+e)},Wt:e=>Bl[e]||null,Gt:e=>Bl[e]||null,Xt(e,t){Bl[e]=t},Jt(e){delete Bl[e]}},pi=null,ft={Ut(){if(!kr(pi))return pi;if(pi=!0,J(I))pi=!1;else try{var e="__support__";ft.Xt(e,"xyz"),ft.Wt(e)!=='"xyz"'&&(pi=!1),ft.Jt(e)}catch{pi=!1}return pi},Yt(e){K.error("sessionStorage error: ",e)},Wt(e){try{return I==null?void 0:I.sessionStorage.getItem(e)}catch(t){ft.Yt(t)}return null},Gt(e){try{return JSON.parse(ft.Wt(e))||null}catch{}return null},Xt(e,t){try{I==null||I.sessionStorage.setItem(e,JSON.stringify(t))}catch(n){ft.Yt(n)}},Jt(e){try{I==null||I.sessionStorage.removeItem(e)}catch(t){ft.Yt(t)}}};class Tj{constructor(t){this._instance=t}get Rt(){return this._instance.config}get consent(){return this.Kt()?0:this.Qt}isOptedOut(){return this.Rt.cookieless_mode===Pn||this.consent===0||this.consent===-1&&(this.Rt.opt_out_capturing_by_default||this.Rt.cookieless_mode===ir)}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}optInOut(t){this.ti.Xt(this.ei,t?1:0,this.Rt.cookie_expiration,this.Rt.cross_subdomain_cookie,this.Rt.secure_cookie)}reset(){this.ti.Jt(this.ei,this.Rt.cross_subdomain_cookie)}get ei(){var{token:t,opt_out_capturing_cookie_prefix:n,consent_persistence_name:r}=this._instance.config;return r||(n?n+t:"__ph_opt_in_out_"+t)}get Qt(){var t=this.ti.Wt(this.ei);return Gd(t)?1:de(HN,t)?0:-1}get ti(){var t=this.Rt.opt_out_capturing_persistence_type,n=t==="localStorage"?Be:qn;if(!this.ii||this.ii!==n){this.ii=n;var r=t==="localStorage"?qn:Be;r.Wt(this.ei)&&(this.ii.Wt(this.ei)||this.optInOut(Gd(r.Wt(this.ei))),r.Jt(this.ei,this.Rt.cross_subdomain_cookie))}return this.ii}Kt(){return!!this.Rt.respect_dnt&&[nn==null?void 0:nn.doNotTrack,nn==null?void 0:nn.msDoNotTrack,ne.doNotTrack].some(t=>Gd(t))}}var Hl=We("[Dead Clicks]"),Mj=()=>!0,Rj=e=>{var t,n=!((t=e.instance.persistence)==null||!t.get_property(nk)),r=e.instance.config.capture_dead_clicks;return Gn(r)?r:!!rt(r)||n};class Av{get lazyLoadedDeadClicksAutocapture(){return this.ri}constructor(t,n,r){this.instance=t,this.isEnabled=n,this.onCapture=r,this.startIfEnabledOrStop()}onRemoteConfig(t){"captureDeadClicks"in t&&(this.instance.persistence&&this.instance.persistence.register({[nk]:t.captureDeadClicks}),this.startIfEnabledOrStop())}startIfEnabledOrStop(){this.isEnabled(this)?this.ni(()=>{this.si()}):this.stop()}ni(t){var n,r;(n=ne.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture&&t(),(r=ne.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"dead-clicks-autocapture",i=>{i?Hl.error("failed to load script",i):t()})}si(){var t;if(X){if(!this.ri&&(t=ne.__PosthogExtensions__)!=null&&t.initDeadClicksAutocapture){var n=rt(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};n.__onCapture=this.onCapture,this.ri=ne.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.ri.start(X),Hl.info("starting...")}}else Hl.error("`document` not found. Cannot start.")}stop(){this.ri&&(this.ri.stop(),this.ri=void 0,Hl.info("stopping..."))}}var Zd=We("[SegmentIntegration]"),ak="posthog-js";function lk(e,t){var{organization:n,projectId:r,prefix:i,severityAllowList:s=["error"],sendExceptionsToPostHog:o=!0}=t===void 0?{}:t;return a=>{var l,u,c,d,h;if(s!=="*"&&!s.includes(a.level)||!e.__loaded)return a;a.tags||(a.tags={});var p=e.requestRouter.endpointFor("ui","/project/"+e.config.token+"/person/"+e.get_distinct_id());a.tags["PostHog Person URL"]=p,e.sessionRecordingStarted()&&(a.tags["PostHog Recording URL"]=e.get_session_replay_url({withTimestamp:!0}));var g,m=((l=a.exception)==null?void 0:l.values)||[],y=m.map(v=>W({},v,{stacktrace:v.stacktrace?W({},v.stacktrace,{type:"raw",frames:(v.stacktrace.frames||[]).map(_=>W({},_,{platform:"web:javascript"}))}):void 0})),x={$exception_message:((u=m[0])==null?void 0:u.value)||a.message,$exception_type:(c=m[0])==null?void 0:c.type,$exception_level:a.level,$exception_list:y,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:((d=m[0])==null?void 0:d.value)||a.message,$sentry_exception_type:(h=m[0])==null?void 0:h.type,$sentry_tags:a.tags};return n&&r&&(x.$sentry_url=(i||"https://sentry.io/organizations/")+n+"/issues/?project="+r+"&query="+a.event_id),o&&((g=e.exceptions)==null||g.sendExceptionEvent(x)),a}}class Aj{constructor(t,n,r,i,s,o){this.name=ak,this.setupOnce=function(a){a(lk(t,{organization:n,projectId:r,prefix:i,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Iv{constructor(t){this.oi=(n,r,i)=>{i&&(i.noSessionId||i.activityTimeout||i.sessionPastMaximumLength)&&(K.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:i}),this.ai=void 0,this._instance.scrollManager.resetContext())},this._instance=t,this.li()}li(){var t;this.ui=(t=this._instance.sessionManager)==null?void 0:t.onSessionId(this.oi)}destroy(){var t;(t=this.ui)==null||t.call(this),this.ui=void 0}doPageView(t,n){var r,i=this.hi(t,n);return this.ai={pathname:(r=I==null?void 0:I.location.pathname)!==null&&r!==void 0?r:"",pageViewId:n,timestamp:t},this._instance.scrollManager.resetContext(),i}doPageLeave(t){var n;return this.hi(t,(n=this.ai)==null?void 0:n.pageViewId)}doEvent(){var t;return{$pageview_id:(t=this.ai)==null?void 0:t.pageViewId}}hi(t,n){var r=this.ai;if(!r)return{$pageview_id:n};var i={$pageview_id:n,$prev_pageview_id:r.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var{maxScrollHeight:o,lastScrollY:a,maxScrollY:l,maxContentHeight:u,lastContentY:c,maxContentY:d}=s;if(!(J(o)||J(a)||J(l)||J(u)||J(c)||J(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?Yn(a/o,0,1,K):1,p=o>1?Yn(l/o,0,1,K):1,g=u>1?Yn(c/u,0,1,K):1,m=u>1?Yn(d/u,0,1,K):1;i=Ge(i,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:g,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:m})}}return r.pathname&&(i.$prev_pageview_pathname=r.pathname),r.timestamp&&(i.$prev_pageview_duration=(t.getTime()-r.timestamp.getTime())/1e3),i}}var yc=e=>{var t=X==null?void 0:X.createElement("a");return J(t)?null:(t.href=e,t)},_c=function(e,t){for(var n,r=((e.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),i=0;r.length>i;i++){var s=r[i].split("=");if(s[0]===t){n=s;break}}if(!_e(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{K.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},qa=function(e,t,n){if(!e||!t||!t.length)return e;for(var r=e.split("#"),i=r[1],s=(r[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");_e(d)&&(t.includes(d[0])?u.push(d[0]+"="+n):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),i!=null&&(h+="#"+i),h},bc=function(e,t){var n=e.match(new RegExp(t+"=([^&]*)"));return n?n[1]:null},Vl="https?://(.*)",Js=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Ij=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...Js],Ga="<masked>",Oj=["li_fat_id"];function uk(e,t,n){if(!X)return{};var r,i=t?[...Js,...n||[]]:[],s=ck(qa(X.URL,i,Ga),e),o=(r={},Re(Oj,function(a){var l=qn.Wt(a);r[a]=l||null}),r);return Ge(o,s)}function ck(e,t){var n=Ij.concat(t||[]),r={};return Re(n,function(i){var s=_c(e,i);r[i]=s||null}),r}function dk(e){var t=function(s){return s?s.search(Vl+"google.([^/?]*)")===0?"google":s.search(Vl+"bing.com")===0?"bing":s.search(Vl+"yahoo.com")===0?"yahoo":s.search(Vl+"duckduckgo.com")===0?"duckduckgo":null:null}(e),n=t!="yahoo"?"q":"p",r={};if(!kr(t)){r.$search_engine=t;var i=X?_c(X.referrer,n):"";i.length&&(r.ph_keyword=i)}return r}function Ov(){return navigator.language||navigator.userLanguage}var wc="$direct";function hk(){return(X==null?void 0:X.referrer)||wc}function fk(e,t){var n=e?[...Js,...t||[]]:[],r=ht==null?void 0:ht.href.substring(0,1e3);return{r:hk().substring(0,1e3),u:r?qa(r,n,Ga):void 0}}function pk(e){var t,{r:n,u:r}=e,i={$referrer:n,$referring_domain:n==null?void 0:n==wc?wc:(t=yc(n))==null?void 0:t.host};if(r){i.$current_url=r;var s=yc(r);i.$host=s==null?void 0:s.host,i.$pathname=s==null?void 0:s.pathname;var o=ck(r);Ge(i,o)}if(n){var a=dk(n);Ge(i,a)}return i}function gk(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Dj(){try{return new Date().getTimezoneOffset()}catch{return}}var Lj=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"];class eh{constructor(t,n){this.Rt=t,this.props={},this.ci=!1,this.di=(r=>{var i="";return r.token&&(i=r.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),r.persistence_name?"ph_"+r.persistence_name:"ph_"+i+"_posthog"})(t),this.ti=this.vi(t),this.load(),t.debug&&K.info("Persistence loaded",t.persistence,W({},this.props)),this.update_config(t,t,n),this.save()}isDisabled(){return!!this.fi}vi(t){Lj.indexOf(t.persistence.toLowerCase())===-1&&(K.critical("Unknown persistence type "+t.persistence+"; falling back to localStorage+cookie"),t.persistence="localStorage+cookie");var n=function(i){i===void 0&&(i=[]);var s=[...Nj,...i];return W({},Be,{Gt(o){try{var a={};try{a=qn.Gt(o)||{}}catch{}var l=Ge(a,JSON.parse(Be.Wt(o)||"{}"));return Be.Xt(o,l),l}catch{}return null},Xt(o,a,l,u,c,d){try{Be.Xt(o,a,void 0,void 0,d);var h={};s.forEach(p=>{a[p]&&(h[p]=a[p])}),Object.keys(h).length&&qn.Xt(o,h,l,u,c,d)}catch(p){Be.Yt(p)}},Jt(o,a){try{I==null||I.localStorage.removeItem(o),qn.Jt(o,a)}catch(l){Be.Yt(l)}}})}(t.cookie_persisted_properties||[]),r=t.persistence.toLowerCase();return r==="localstorage"&&Be.Ut()?Be:r==="localstorage+cookie"&&n.Ut()?n:r==="sessionstorage"&&ft.Ut()?ft:r==="memory"?jj:r==="cookie"?qn:n.Ut()?n:qn}pi(t){var n=t??this.Rt.feature_flag_cache_ttl_ms;if(!n||0>=n)return!1;var r=this.props[fc];return!r||typeof r!="number"||Date.now()-r>n}properties(){var t={};return Re(this.props,(n,r)=>{if(r===Ns&&rt(n)){if(!this.pi())for(var i=Object.keys(n),s=0;i.length>s;s++)t["$feature/"+i[s]]=n[i[s]]}else _j.indexOf(r)===-1&&(t[r]=n)}),t}load(){if(!this.fi){var t=this.ti.Gt(this.di);t&&(this.props=Ge({},t))}}save(){this.fi||this.ti.Xt(this.di,this.props,this.gi,this.mi,this.yi,this.Rt.debug)}remove(){this.ti.Jt(this.di,!1),this.ti.Jt(this.di,!0)}clear(){this.remove(),this.props={}}register_once(t,n,r){if(rt(t)){J(n)&&(n="None"),this.gi=J(r)?this.bi:r;var i=!1;if(Re(t,(s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.props[o]=s,i=!0)}),i)return this.save(),!0}return!1}register(t,n){if(rt(t)){this.gi=J(n)?this.bi:n;var r=!1;if(Re(t,(i,s)=>{t.hasOwnProperty(s)&&this.props[s]!==i&&(this.props[s]=i,r=!0)}),r)return this.save(),!0}return!1}unregister(t){t in this.props&&(delete this.props[t],this.save())}update_campaign_params(){if(!this.ci){var t=uk(this.Rt.custom_campaign_params,this.Rt.mask_personal_data_properties,this.Rt.custom_personal_data_properties);Ps(am(t))||this.register(t),this.ci=!0}}update_search_keyword(){var t;this.register((t=X==null?void 0:X.referrer)?dk(t):{})}update_referrer_info(){var t;this.register_once({$referrer:hk(),$referring_domain:X!=null&&X.referrer&&((t=yc(X.referrer))==null?void 0:t.host)||wc},void 0)}set_initial_person_info(){this.props[ap]||this.props[lp]||this.register_once({[pc]:fk(this.Rt.mask_personal_data_properties,this.Rt.custom_personal_data_properties)},void 0)}get_initial_props(){var t={};Re([lp,ap],o=>{var a=this.props[o];a&&Re(a,function(l,u){t["$initial_"+Yf(u)]=l})});var n,r,i=this.props[pc];if(i){var s=(n=pk(i),r={},Re(n,function(o,a){r["$initial_"+Yf(a)]=o}),r);Ge(t,s)}return t}safe_merge(t){return Re(this.props,function(n,r){r in t||(t[r]=n)}),t}update_config(t,n,r){if(this.bi=this.gi=t.cookie_expiration,this.set_disabled(t.disable_persistence||!!r),this.set_cross_subdomain(t.cross_subdomain_cookie),this.set_secure(t.secure_cookie),t.persistence!==n.persistence||!((o,a)=>{if(o.length!==a.length)return!1;var l=[...o].sort(),u=[...a].sort();return l.every((c,d)=>c===u[d])})(t.cookie_persisted_properties||[],n.cookie_persisted_properties||[])){var i=this.vi(t),s=this.props;this.clear(),this.ti=i,this.props=s,this.save()}}set_disabled(t){this.fi=t,this.fi?this.remove():this.save()}set_cross_subdomain(t){t!==this.mi&&(this.mi=t,this.remove(),this.save())}set_secure(t){t!==this.yi&&(this.yi=t,this.remove(),this.save())}set_event_timer(t,n){var r=this.props[Uo]||{};r[t]=n,this.props[Uo]=r,this.save()}remove_event_timer(t){var n=(this.props[Uo]||{})[t];return J(n)||(delete this.props[Uo][t],this.save()),n}get_property(t){return this.props[t]}set_property(t,n){this.props[t]=n,this.save()}}var So={Activation:"events",Cancellation:"cancelEvents"},th={Popover:"popover",API:"api",Widget:"widget"},Yo={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},nh={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},cp={Popover:"popover",Inline:"inline"},Fj={SHOWN:"product tour shown"},Dv={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Lv=We("[RateLimiter]");class $j{constructor(t){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var r=n.text;if(r&&r.length)try{(JSON.parse(r).quota_limited||[]).forEach(i=>{Lv.info((i||"events")+" is quota limited."),this.serverLimits[i]=new Date().getTime()+6e4})}catch(i){return void Lv.warn('could not rate limit - continuing. Error: "'+(i==null?void 0:i.message)+'"',{text:r})}},this.instance=t,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var t;return((t=this.instance.config.rate_limiting)==null?void 0:t.events_per_second)||10}get captureEventsBurstLimit(){var t;return Math.max(((t=this.instance.config.rate_limiting)==null?void 0:t.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(t){var n,r,i;t===void 0&&(t=!1);var{captureEventsBurstLimit:s,captureEventsPerSecond:o}=this,a=new Date().getTime(),l=(n=(r=this.instance.persistence)==null?void 0:r.get_property(op))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;return u||t||(l.tokens=Math.max(0,l.tokens-1)),!u||this.lastEventRateLimited||t||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+o+" events per second and "+s+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=u,(i=this.instance.persistence)==null||i.set_property(op,l),{isRateLimited:u,remainingTokens:l.tokens}}isServerRateLimited(t){var n=this.serverLimits[t||"events"]||!1;return n!==!1&&new Date().getTime()<n}}var Co=We("[RemoteConfig]");class mk{constructor(t){this._instance=t}get remoteConfig(){var t;return(t=ne._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.config}wi(t){var n,r;(n=ne.__PosthogExtensions__)!=null&&n.loadExternalDependency?(r=ne.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"remote-config",()=>t(this.remoteConfig)):t()}Ii(t){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback(n){t(n.json)}})}load(){try{if(this.remoteConfig)return Co.info("Using preloaded remote config",this.remoteConfig),this.Ci(this.remoteConfig),void this.Si();if(this._instance.ki())return void Co.warn("Remote config is disabled. Falling back to local config.");this.wi(t=>{if(!t)return Co.info("No config found after loading remote JS config. Falling back to JSON."),void this.Ii(n=>{this.Ci(n),this.Si()});this.Ci(t),this.Si()})}catch(t){Co.error("Error loading remote config",t)}}stop(){this.xi&&(clearInterval(this.xi),this.xi=void 0)}refresh(){this._instance.ki()||(X==null?void 0:X.visibilityState)==="hidden"||this._instance.reloadFeatureFlags()}Si(){var t;if(!this.xi){var n=(t=this._instance.config.remote_config_refresh_interval_ms)!==null&&t!==void 0?t:3e5;n!==0&&(this.xi=setInterval(()=>{this.refresh()},n))}}Ci(t){var n;t||Co.error("Failed to fetch remote config from PostHog."),this._instance.Ci(t??{}),(t==null?void 0:t.hasFeatureFlags)!==!1&&(this._instance.config.advanced_disable_feature_flags_on_first_load||(n=this._instance.featureFlags)==null||n.ensureFlagsLoaded())}}var Vn={GZipJS:"gzip-js",Base64:"base64"},vn=Uint8Array,Vt=Uint16Array,Qs=Uint32Array,lm=new vn([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),um=new vn([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Fv=new vn([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),xk=function(e,t){for(var n=new Vt(31),r=0;31>r;++r)n[r]=t+=1<<e[r-1];var i=new Qs(n[30]);for(r=1;30>r;++r)for(var s=n[r];n[r+1]>s;++s)i[s]=s-n[r]<<5|r;return[n,i]},vk=xk(lm,2),dp=vk[1];vk[0][28]=258,dp[258]=28;for(var $v=xk(um,0)[1],yk=new Vt(32768),Ae=0;32768>Ae;++Ae){var is=(43690&Ae)>>>1|(21845&Ae)<<1;yk[Ae]=((65280&(is=(61680&(is=(52428&is)>>>2|(13107&is)<<2))>>>4|(3855&is)<<4))>>>8|(255&is)<<8)>>>1}var ha=function(e,t,n){for(var r=e.length,i=0,s=new Vt(t);r>i;++i)++s[e[i]-1];var o,a=new Vt(t);for(i=0;t>i;++i)a[i]=a[i-1]+s[i-1]<<1;for(o=new Vt(r),i=0;r>i;++i)o[i]=yk[a[e[i]-1]++]>>>15-e[i];return o},Vi=new vn(288);for(Ae=0;144>Ae;++Ae)Vi[Ae]=8;for(Ae=144;256>Ae;++Ae)Vi[Ae]=9;for(Ae=256;280>Ae;++Ae)Vi[Ae]=7;for(Ae=280;288>Ae;++Ae)Vi[Ae]=8;var kc=new vn(32);for(Ae=0;32>Ae;++Ae)kc[Ae]=5;var zj=ha(Vi,9),Bj=ha(kc,5),_k=function(e){return(e/8>>0)+(7&e&&1)},bk=function(e,t,n){(n==null||n>e.length)&&(n=e.length);var r=new(e instanceof Vt?Vt:e instanceof Qs?Qs:vn)(n-t);return r.set(e.subarray(t,n)),r},nr=function(e,t,n){var r=t/8>>0;e[r]|=n<<=7&t,e[r+1]|=n>>>8},Eo=function(e,t,n){var r=t/8>>0;e[r]|=n<<=7&t,e[r+1]|=n>>>8,e[r+2]|=n>>>16},rh=function(e,t){for(var n=[],r=0;e.length>r;++r)e[r]&&n.push({s:r,f:e[r]});var i=n.length,s=n.slice();if(!i)return[new vn(0),0];if(i==1){var o=new vn(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort(function(w,b){return w.f-b.f}),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=i-1;)a=n[n[d].f>n[u].f?u++:d++],l=n[u!=c&&n[d].f>n[u].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=s[0].s;for(r=1;i>r;++r)s[r].s>h&&(h=s[r].s);var p=new Vt(h+1),g=hp(n[c-1],p,0);if(g>t){r=0;var m=0,y=g-t,x=1<<y;for(s.sort(function(w,b){return p[b.s]-p[w.s]||w.f-b.f});i>r;++r){var v=s[r].s;if(t>=p[v])break;m+=x-(1<<g-p[v]),p[v]=t}for(m>>>=y;m>0;){var _=s[r].s;t>p[_]?m-=1<<t-p[_]++-1:++r}for(;r>=0&&m;--r){var k=s[r].s;p[k]==t&&(--p[k],++m)}g=t}return[new vn(p),g]},hp=function(e,t,n){return e.s==-1?Math.max(hp(e.l,t,n+1),hp(e.r,t,n+1)):t[e.s]=n},zv=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new Vt(++t),r=0,i=e[0],s=1,o=function(l){n[r++]=l},a=1;t>=a;++a)if(e[a]==i&&a!=t)++s;else{if(!i&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(i),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(i);s=1,i=e[a]}return[n.subarray(0,r),t]},Po=function(e,t){for(var n=0,r=0;t.length>r;++r)n+=e[r]*t[r];return n},fp=function(e,t,n){var r=n.length,i=_k(t+2);e[i]=255&r,e[i+1]=r>>>8,e[i+2]=255^e[i],e[i+3]=255^e[i+1];for(var s=0;r>s;++s)e[i+s+4]=n[s];return 8*(i+4+r)},Bv=function(e,t,n,r,i,s,o,a,l,u,c){nr(t,c++,n),++i[256];for(var d=rh(i,15),h=d[0],p=d[1],g=rh(s,15),m=g[0],y=g[1],x=zv(h),v=x[0],_=x[1],k=zv(m),w=k[0],b=k[1],S=new Vt(19),P=0;v.length>P;++P)S[31&v[P]]++;for(P=0;w.length>P;++P)S[31&w[P]]++;for(var j=rh(S,7),E=j[0],R=j[1],A=19;A>4&&!E[Fv[A-1]];--A);var L,U,$,Y,Z=u+5<<3,O=Po(i,Vi)+Po(s,kc)+o,M=Po(i,h)+Po(s,m)+o+14+3*A+Po(S,E)+(2*S[16]+3*S[17]+7*S[18]);if(O>=Z&&M>=Z)return fp(t,c,e.subarray(l,l+u));if(nr(t,c,1+(O>M)),c+=2,O>M){L=ha(h,p),U=h,$=ha(m,y),Y=m;var C=ha(E,R);for(nr(t,c,_-257),nr(t,c+5,b-1),nr(t,c+10,A-4),c+=14,P=0;A>P;++P)nr(t,c+3*P,E[Fv[P]]);c+=3*A;for(var z=[v,w],Q=0;2>Q;++Q){var T=z[Q];for(P=0;T.length>P;++P)nr(t,c,C[re=31&T[P]]),c+=E[re],re>15&&(nr(t,c,T[P]>>>5&127),c+=T[P]>>>12)}}else L=zj,U=Vi,$=Bj,Y=kc;for(P=0;a>P;++P)if(r[P]>255){var re;Eo(t,c,L[257+(re=r[P]>>>18&31)]),c+=U[re+257],re>7&&(nr(t,c,r[P]>>>23&31),c+=lm[re]);var le=31&r[P];Eo(t,c,$[le]),c+=Y[le],le>3&&(Eo(t,c,r[P]>>>5&8191),c+=um[le])}else Eo(t,c,L[r[P]]),c+=U[r[P]];return Eo(t,c,L[256]),c+U[256]},Hj=new Qs([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Vj=function(){for(var e=new Qs(256),t=0;256>t;++t){for(var n=t,r=9;--r;)n=(1&n&&3988292384)^n>>>1;e[t]=n}return e}(),ih=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function Wj(e,t){t===void 0&&(t={});var n=function(){var d=4294967295;return{p(h){for(var p=d,g=0;h.length>g;++g)p=Vj[255&p^h[g]]^p>>>8;d=p},d(){return 4294967295^d}}}(),r=e.length;n.p(e);var i,s,o,a,l,u=(a=10+((i=t).filename&&i.filename.length+1||0),l=8,function(d,h,p,g,m,y){var x=d.length,v=new vn(g+x+5*(1+Math.floor(x/7e3))+m),_=v.subarray(g,v.length-m),k=0;if(!h||8>x)for(var w=0;x>=w;w+=65535){var b=w+65535;x>b?k=fp(_,k,d.subarray(w,b)):(_[w]=!0,k=fp(_,k,d.subarray(w,x)))}else{for(var S=Hj[h-1],P=S>>>13,j=8191&S,E=(1<<p)-1,R=new Vt(32768),A=new Vt(E+1),L=Math.ceil(p/3),U=2*L,$=function(ho){return(d[ho]^d[ho+1]<<L^d[ho+2]<<U)&E},Y=new Qs(25e3),Z=new Vt(288),O=new Vt(32),M=0,C=0,z=(w=0,0),Q=0,T=0;x>w;++w){var re=$(w),le=32767&w,F=A[re];if(R[le]=F,A[re]=le,w>=Q){var V=x-w;if((M>7e3||z>24576)&&V>423){k=Bv(d,_,0,Y,Z,O,C,z,T,w-T,k),z=M=C=0,T=w;for(var te=0;286>te;++te)Z[te]=0;for(te=0;30>te;++te)O[te]=0}var ce=2,xe=0,Dn=j,Dt=le-F&32767;if(V>2&&re==$(w-Dt))for(var $e=Math.min(P,V)-1,Yt=Math.min(32767,w),Je=Math.min(258,V);Yt>=Dt&&--Dn&&le!=F;){if(d[w+ce]==d[w+ce-Dt]){for(var nt=0;Je>nt&&d[w+nt]==d[w+nt-Dt];++nt);if(nt>ce){if(ce=nt,xe=Dt,nt>$e)break;var Xt=Math.min(Dt,nt-2),ml=0;for(te=0;Xt>te;++te){var Zi=w-Dt+te+32768&32767,co=Zi-R[Zi]+32768&32767;co>ml&&(ml=co,F=Zi)}}}Dt+=(le=F)-(F=R[le])+32768&32767}if(xe){Y[z++]=268435456|dp[ce]<<18|$v[xe];var xl=31&dp[ce],vl=31&$v[xe];C+=lm[xl]+um[vl],++Z[257+xl],++O[vl],Q=w+ce,++M}else Y[z++]=d[w],++Z[d[w]]}}k=Bv(d,_,!0,Y,Z,O,C,z,T,w-T,k)}return bk(v,0,g+_k(k)+m)}(s=e,(o=t).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return function(d,h){var p=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&ih(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),p){d[3]=8;for(var g=0;p.length>=g;++g)d[g+10]=p.charCodeAt(g)}}(u,t),ih(u,c-8,n.d()),ih(u,c-4,r),u}var Uj=!!Gf||!!qf,wk="text/plain",Hv=!1,rd=function(e,t,n){var r;n===void 0&&(n=!0);var[i,s]=e.split("?"),o=W({},t),a=(r=s==null?void 0:s.split("&").map(u=>{var c,[d,h]=u.split("="),p=n&&(c=o[d])!==null&&c!==void 0?c:h;return delete o[d],d+"="+p}))!==null&&r!==void 0?r:[],l=function(u,c){var d,h;c===void 0&&(c="&");var p=[];return Re(u,function(g,m){J(g)||J(m)||m==="undefined"||(d=encodeURIComponent((y=>y instanceof File)(g)?g.name:g.toString()),h=encodeURIComponent(m),p[p.length]=h+"="+d)}),p.join(c)}(o);return l&&a.push(l),i+"?"+a.join("&")},js=(e,t)=>JSON.stringify(e,(n,r)=>typeof r=="bigint"?r.toString():r,t),sh=e=>{if(e.zt)return e.zt;var{data:t,compression:n}=e;if(t){if(n===Vn.GZipJS){var r=Wj(function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new vn(a.length+(a.length>>>1)),d=0,h=function(y){c[d++]=y},p=0;u>p;++p){if(d+5>c.length){var g=new vn(d+8+(u-p<<1));g.set(c),c=g}var m=a.charCodeAt(p);128>m?h(m):2048>m?(h(192|m>>>6),h(128|63&m)):m>55295&&57344>m?(h(240|(m=65536+(1047552&m)|1023&a.charCodeAt(++p))>>>18),h(128|m>>>12&63),h(128|m>>>6&63),h(128|63&m)):(h(224|m>>>12),h(128|m>>>6&63),h(128|63&m))}return bk(c,0,d)}(js(t)),{mtime:0});return{contentType:wk,body:r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),estimatedSize:r.byteLength}}if(n===Vn.Base64){var i=function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,(l,u)=>String.fromCharCode(parseInt(u,16))))}(js(t)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:js(a)))(i);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=js(t);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},qj=function(){var e=En(function*(t){var n=js(t.data),r=yield function(s,o,a){return Rw.apply(this,arguments)}(n,jt.DEBUG,{rethrow:!0});if(!r)return t;var i=yield r.arrayBuffer();return W({},t,{zt:{contentType:wk,body:i,estimatedSize:i.byteLength}})});return function(t){return e.apply(this,arguments)}}(),Vv=(e,t)=>rd(e,{_:new Date().getTime().toString(),ver:jt.JS_SDK_VERSION,compression:t}),Su=[];qf&&Su.push({transport:"fetch",method(e){var t,n,{contentType:r,body:i,estimatedSize:s}=(t=sh(e))!==null&&t!==void 0?t:{},o=new Headers;Re(e.headers,function(c,d){o.append(d,c)}),r&&o.append("Content-Type",r);var a=e.url,l=null;if(gv){var u=new gv;l={signal:u.signal,timeout:setTimeout(()=>u.abort(),e.timeout)}}qf(a,W({method:(e==null?void 0:e.method)||"GET",headers:o,keepalive:e.method==="POST"&&52428.8>(s||0),body:i,signal:(n=l)==null?void 0:n.signal},e.fetchOptions)).then(c=>c.text().then(d=>{var h={statusCode:c.status,text:d};if(c.status===200)try{h.json=JSON.parse(d)}catch(p){K.error(p)}e.callback==null||e.callback(h)})).catch(c=>{K.error(c),e.callback==null||e.callback({statusCode:0,error:c})}).finally(()=>l?clearTimeout(l.timeout):null)}}),Gf&&Su.push({transport:"XHR",method(e){var t,n=new Gf;n.open(e.method||"GET",e.url,!0);var{contentType:r,body:i}=(t=sh(e))!==null&&t!==void 0?t:{};Re(e.headers,function(s,o){n.setRequestHeader(o,s)}),r&&n.setRequestHeader("Content-Type",r),e.timeout&&(n.timeout=e.timeout),e.disableXHRCredentials||(n.withCredentials=!0),n.onreadystatechange=()=>{if(n.readyState===4){var s={statusCode:n.status,text:n.responseText};if(n.status===200)try{s.json=JSON.parse(n.responseText)}catch{}e.callback==null||e.callback(s)}},n.send(i)}}),nn!=null&&nn.sendBeacon&&Su.push({transport:"sendBeacon",method(e){var t=rd(e.url,{beacon:"1"});try{var n,{contentType:r,body:i}=(n=sh(e))!==null&&n!==void 0?n:{};if(!i)return;var s=i instanceof Blob?i:new Blob([i],{type:r});nn.sendBeacon(t,s)}catch{}}});var pp=3e3;class Gj{constructor(t,n){this.Ti=!0,this.Ai=[],this.Ei=Yn((n==null?void 0:n.flush_interval_ms)||pp,250,5e3,K.createLogger("flush interval"),pp),this.Ri=t}enqueue(t){this.Ai.push(t),this.Ni||this.Mi()}unload(){this.Fi();var t=this.Ai.length>0?this.Oi():{},n=Object.values(t);[...n.filter(r=>r.url.indexOf("/e")===0),...n.filter(r=>r.url.indexOf("/e")!==0)].map(r=>{this.Ri(W({},r,{transport:"sendBeacon"}))})}enable(){this.Ti=!1,this.Mi()}Mi(){var t=this;this.Ti||(this.Ni=setTimeout(()=>{if(this.Fi(),this.Ai.length>0){var n=this.Oi(),r=function(){var s=n[i],o=new Date().getTime();s.data&&_e(s.data)&&Re(s.data,a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp}),t.Ri(s)};for(var i in n)r()}},this.Ei))}Fi(){clearTimeout(this.Ni),this.Ni=void 0}Oi(){var t={};return Re(this.Ai,n=>{var r,i=n,s=(i?i.batchKey:null)||i.url;J(t[s])&&(t[s]=W({},i,{data:[]})),(r=t[s].data)==null||r.push(i.data)}),this.Ai=[],t}}var Yj=["retriesPerformedSoFar"];class Xj{constructor(t){this.Pi=!1,this.Li=3e3,this.Ai=[],this._instance=t,this.Ai=[],this.Di=!0,!J(I)&&"onLine"in I.navigator&&(this.Di=I.navigator.onLine,this.Bi=()=>{this.Di=!0,this.ji()},this.qi=()=>{this.Di=!1},Ze(I,"online",this.Bi),Ze(I,"offline",this.qi))}get length(){return this.Ai.length}retriableRequest(t){var{retriesPerformedSoFar:n}=t,r=Mw(t,Yj);cs(n)&&(r.url=rd(r.url,{retry_count:n})),this._instance._send_request(W({},r,{callback:i=>{i.statusCode===200||i.statusCode>=400&&500>i.statusCode||(n??0)>=10?r.callback==null||r.callback(i):this.Zi(W({retriesPerformedSoFar:n},r))}}))}Zi(t){var n=t.retriesPerformedSoFar||0;t.retriesPerformedSoFar=n+1;var r=function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))}(n),i=Date.now()+r;this.Ai.push({retryAt:i,requestOptions:t});var s="Enqueued failed request for retry in "+r;navigator.onLine||(s+=" (Browser is offline)"),K.warn(s),this.Pi||(this.Pi=!0,this.$i())}$i(){if(this.Vi&&clearTimeout(this.Vi),this.Ai.length===0)return this.Pi=!1,void(this.Vi=void 0);this.Vi=setTimeout(()=>{this.Di&&this.Ai.length>0&&this.ji(),this.$i()},this.Li)}ji(){var t=Date.now(),n=[],r=this.Ai.filter(s=>t>s.retryAt||(n.push(s),!1));if(this.Ai=n,r.length>0)for(var{requestOptions:i}of r)this.retriableRequest(i)}unload(){for(var{requestOptions:t}of(this.Vi&&(clearTimeout(this.Vi),this.Vi=void 0),this.Pi=!1,J(I)||(this.Bi&&(I.removeEventListener("online",this.Bi),this.Bi=void 0),this.qi&&(I.removeEventListener("offline",this.qi),this.qi=void 0)),this.Ai))try{this._instance._send_request(W({},t,{transport:"sendBeacon"}))}catch(n){K.error(n)}this.Ai=[]}}class Kj{constructor(t){this.Hi=()=>{var n,r,i,s;this.zi||(this.zi={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+((o==null?void 0:o.clientHeight)||0),c=(o==null?void 0:o.scrollHeight)||0;this.zi.lastScrollY=Math.ceil(a),this.zi.maxScrollY=Math.max(a,(n=this.zi.maxScrollY)!==null&&n!==void 0?n:0),this.zi.maxScrollHeight=Math.max(l,(r=this.zi.maxScrollHeight)!==null&&r!==void 0?r:0),this.zi.lastContentY=u,this.zi.maxContentY=Math.max(u,(i=this.zi.maxContentY)!==null&&i!==void 0?i:0),this.zi.maxContentHeight=Math.max(c,(s=this.zi.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=t}get Ui(){return this._instance.config.scroll_root_selector}getContext(){return this.zi}resetContext(){var t=this.zi;return setTimeout(this.Hi,0),t}startMeasuringScrollPosition(){Ze(I,"scroll",this.Hi,{capture:!0}),Ze(I,"scrollend",this.Hi,{capture:!0}),Ze(I,"resize",this.Hi)}scrollElement(){if(!this.Ui)return I==null?void 0:I.document.documentElement;var t=_e(this.Ui)?this.Ui:[this.Ui];for(var n of t){var r=I==null?void 0:I.document.querySelector(n);if(r)return r}}scrollY(){if(this.Ui){var t=this.scrollElement();return t&&t.scrollTop||0}return I&&(I.scrollY||I.pageYOffset||I.document.documentElement.scrollTop)||0}scrollX(){if(this.Ui){var t=this.scrollElement();return t&&t.scrollLeft||0}return I&&(I.scrollX||I.pageXOffset||I.document.documentElement.scrollLeft)||0}}var Jj=e=>fk(e==null?void 0:e.config.mask_personal_data_properties,e==null?void 0:e.config.custom_personal_data_properties);class Wv{constructor(t,n,r,i){this.Yi=s=>{var o=this.Wi();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Gi(this._instance)};this.Xi.register({[sp]:a})}},this._instance=t,this.Ji=n,this.Xi=r,this.Gi=i||Jj,this.Ji.onSessionId(this.Yi)}Wi(){return this.Xi.props[sp]}getSetOnceProps(){var t,n=(t=this.Wi())==null?void 0:t.props;return n?"r"in n?pk(n):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var t={};return Re(am(this.getSetOnceProps()),(n,r)=>{r==="$current_url"&&(r="url"),t["$session_entry_"+Yf(r)]=n}),t}}class cm{constructor(){this.Ki={}}on(t,n){return this.Ki[t]||(this.Ki[t]=[]),this.Ki[t].push(n),()=>{this.Ki[t]=this.Ki[t].filter(r=>r!==n)}}emit(t,n){for(var r of this.Ki[t]||[])r(n);for(var i of this.Ki["*"]||[])i(t,n)}}var oh=We("[SessionId]");class Uv{on(t,n){return this.Qi.on(t,n)}constructor(t,n,r){var i;if(this.tr=[],this.er=void 0,this.Qi=new cm,this.ir=(u,c)=>!(!cs(u)||!cs(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!t.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(t.config.cookieless_mode===Pn)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Rt=t.config,this.Xi=t.persistence,this.rr=void 0,this.nr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.sr=n||Lr,this.ar=r||Lr;var s=this.Rt.persistence_name||this.Rt.token;if(this._sessionTimeoutMs=1e3*Yn(this.Rt.session_idle_timeout_seconds||1800,60,36e3,oh.createLogger("session_idle_timeout_seconds"),1800),t.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.lr(),this.ur="ph_"+s+"_window_id",this.hr="ph_"+s+"_primary_window_exists",this.cr()){var o=ft.Gt(this.ur),a=ft.Gt(this.hr);o&&!a?this.rr=o:ft.Jt(this.ur),ft.Xt(this.hr,!0)}if((i=this.Rt.bootstrap)!=null&&i.sessionID)try{var l=(u=>{var c=this.Rt.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.dr(this.Rt.bootstrap.sessionID,new Date().getTime(),l)}catch(u){oh.error("Invalid sessionID in bootstrap",u)}this.vr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(t){return J(this.tr)&&(this.tr=[]),this.tr.push(t),this.nr&&t(this.nr,this.rr),()=>{this.tr=this.tr.filter(n=>n!==t)}}cr(){return this.Rt.persistence!=="memory"&&!this.Xi.fi&&ft.Ut()}pr(t){t!==this.rr&&(this.rr=t,this.cr()&&ft.Xt(this.ur,t))}gr(){return this.rr?this.rr:this.cr()?ft.Gt(this.ur):null}dr(t,n,r){t===this.nr&&n===this._sessionActivityTimestamp&&r===this._sessionStartTimestamp||(this._sessionStartTimestamp=r,this._sessionActivityTimestamp=n,this.nr=t,this.Xi.register({[hc]:[n,t,r]}))}mr(){var t=this.Xi.props[hc];return _e(t)&&t.length===2&&t.push(t[0]),t||[0,null,0]}resetSessionId(){this.dr(null,null,null)}destroy(){clearTimeout(this.yr),this.yr=void 0,this.er&&I&&(I.removeEventListener(xc,this.er,{capture:!1}),this.er=void 0),this.tr=[]}vr(){this.er=()=>{this.cr()&&ft.Jt(this.hr)},Ze(I,xc,this.er,{capture:!1})}checkAndGetSessionAndWindowId(t,n){if(t===void 0&&(t=!1),n===void 0&&(n=null),this.Rt.cookieless_mode===Pn)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=n||new Date().getTime(),[i,s,o]=this.mr(),a=this.gr(),l=cs(o)&&Math.abs(r-o)>864e5,u=!1,c=!s,d=!c&&!t&&this.ir(r,i);c||d||l?(s=this.sr(),a=this.ar(),oh.info("new session ID generated",{sessionId:s,windowId:a,changeReason:{noSessionId:c,activityTimeout:d,sessionPastMaximumLength:l}}),o=r,u=!0):a||(a=this.ar(),u=!0);var h=cs(i)&&t&&!l?i:r,p=cs(o)?o:new Date().getTime();return this.pr(a),this.dr(s,h,p),t||this.lr(),u&&this.tr.forEach(g=>g(s,a,u?{noSessionId:c,activityTimeout:d,sessionPastMaximumLength:l}:void 0)),{sessionId:s,windowId:a,sessionStartTimestamp:p,changeReason:u?{noSessionId:c,activityTimeout:d,sessionPastMaximumLength:l}:void 0,lastActivityTimestamp:i}}lr(){clearTimeout(this.yr),this.yr=setTimeout(()=>{var[t]=this.mr();if(this.ir(new Date().getTime(),t)){var n=this.nr;this.resetSessionId(),this.Qi.emit("forcedIdleReset",{idleSessionId:n})}},1.1*this.sessionTimeoutMs)}}var kk=function(e,t){if(!e)return!1;var n=e.userAgent;if(n&&vv(n,t))return!0;try{var r=e==null?void 0:e.userAgentData;if(r!=null&&r.brands&&r.brands.some(i=>vv(i==null?void 0:i.brand,t)))return!0}catch{}return!!e.webdriver},Sc=function(e,t){if(!function(n){try{new RegExp(n)}catch{return!1}return!0}(t))return!1;try{return new RegExp(t).test(e)}catch{return!1}};function qv(e,t,n){return js({distinct_id:e,userPropertiesToSet:t,userPropertiesToSetOnce:n})}var Sk={exact:(e,t)=>t.some(n=>e.some(r=>n===r)),is_not:(e,t)=>t.every(n=>e.every(r=>n!==r)),regex:(e,t)=>t.some(n=>e.some(r=>Sc(n,r))),not_regex:(e,t)=>t.every(n=>e.every(r=>!Sc(n,r))),icontains:(e,t)=>t.map(Wl).some(n=>e.map(Wl).some(r=>n.includes(r))),not_icontains:(e,t)=>t.map(Wl).every(n=>e.map(Wl).every(r=>!n.includes(r))),gt:(e,t)=>t.some(n=>{var r=parseFloat(n);return!isNaN(r)&&e.some(i=>r>parseFloat(i))}),lt:(e,t)=>t.some(n=>{var r=parseFloat(n);return!isNaN(r)&&e.some(i=>r<parseFloat(i))})},Wl=e=>e.toLowerCase();function Ck(e,t){return!e||Object.entries(e).every(n=>{var[r,i]=n,s=t==null?void 0:t[r];if(J(s)||kr(s))return!1;var o=[String(s)],a=Sk[i.operator];return!!a&&a(i.values,o)})}var gp="custom",Gv="i.posthog.com";class Qj{constructor(t){this.br={},this.instance=t}get apiHost(){var t=this.instance.config.api_host.trim().replace(/\/$/,"");return t==="https://app.posthog.com"?"https://us.i.posthog.com":t}get flagsApiHost(){var t=this.instance.config.flags_api_host;return t?t.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var t,n=(t=this.instance.config.ui_host)==null?void 0:t.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+Gv,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.br[this.apiHost]||(this.br[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":gp),this.br[this.apiHost]}endpointFor(t,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),t==="ui")return this.uiHost+n;if(t==="flags")return this.flagsApiHost+n;if(this.region===gp)return this.apiHost+n;var r=Gv+n;switch(t){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}var Ee=We("[Surveys]"),mp="seenSurvey_",Zj=(e,t)=>{var n="$survey_"+t+"/"+e.id;return e.current_iteration&&e.current_iteration>0&&(n="$survey_"+t+"/"+e.id+"/"+e.current_iteration),n},Yv=e=>((t,n)=>{var r=""+mp+n.id;return n.current_iteration&&n.current_iteration>0&&(r=""+mp+n.id+"_"+n.current_iteration),r})(0,e),eT=[th.Popover,th.Widget,th.API],tT={ignoreConditions:!1,ignoreDelay:!1,displayType:cp.Popover},nT=We("[PostHog ExternalIntegrations]"),rT={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class iT{constructor(t){this._instance=t}ni(t,n){var r;(r=ne.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,t,i=>{if(i)return nT.error("failed to load script",i);n()})}startIfEnabledOrStop(){var t=this,n=function(o){var a,l,u;!i||(a=ne.__PosthogExtensions__)!=null&&(a=a.integrations)!=null&&a[o]||t.ni(rT[o],()=>{var c;(c=ne.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[o])==null||c.start(t._instance)}),!i&&(l=ne.__PosthogExtensions__)!=null&&(l=l.integrations)!=null&&l[o]&&((u=ne.__PosthogExtensions__)==null||(u=u.integrations)==null||(u=u[o])==null||u.stop())};for(var[r,i]of Object.entries((s=this._instance.config.integrations)!==null&&s!==void 0?s:{})){var s;n(r)}}}var ss,fa={},ah=0,xp=()=>{},Xv='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',No="Surveys module not available",Kv="sanitize_properties is deprecated. Use before_send instead",Ek="Invalid value for property_denylist config: ",sT=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,hs="posthog",Pk=!Uj&&($t==null?void 0:$t.indexOf("MSIE"))===-1&&($t==null?void 0:$t.indexOf("Mozilla"))===-1,Jv=e=>{var t;return W({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:kj(X==null?void 0:X.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:xp,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:e??"unset",__preview_deferred_init_extensions:!1,debug:ht&&et(ht==null?void 0:ht.search)&&ht.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disable_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(I==null||(t=I.location)==null?void 0:t.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){K.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:up,before_send:void 0,request_queue_config:{flush_interval_ms:pp},error_tracking:{},_onCapture:xp,__preview_eager_load_replay:!1},(n=>({rageclick:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0}))(e))},oT=[["process_person","person_profiles"],["xhr_headers","request_headers"],["cookie_name","persistence_name"],["disable_cookie","disable_persistence"],["store_google","save_campaign_params"],["verbose","debug"]],Qv=e=>{var t={};for(var[n,r]of oT)J(e[n])||(t[r]=e[n]);var i=Ge({},t,e);return _e(e.property_blacklist)&&(J(e.property_denylist)?i.property_denylist=e.property_blacklist:_e(e.property_denylist)?i.property_denylist=[...e.property_blacklist,...e.property_denylist]:K.error(Ek+e.property_denylist)),i};class aT{constructor(){this.__forceAllowLocalhost=!1}get wr(){return this.__forceAllowLocalhost}set wr(t){K.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=t}}class pn{_r(t,n){if(t){var r=this.Ir.indexOf(t);r!==-1&&this.Ir.splice(r,1)}return this.Ir.push(n),n.initialize==null||n.initialize(),n}get decideEndpointWasHit(){var t,n;return(t=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&t!==void 0&&t}get flagsEndpointWasHit(){var t,n;return(t=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&t!==void 0&&t}constructor(){var t;this.webPerformance=new aT,this.Cr=!1,this.version=jt.LIB_VERSION,this.Sr=new cm,this.Ir=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=Jv(),this.SentryIntegration=Aj,this.sentryIntegration=r=>function(i,s){var o=lk(i,s);return{name:ak,processEvent:a=>o(a)}}(this,r),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.kr=!1,this.Tr=null,this.Ar=null,this.Er=null,this.scrollManager=new Kj(this),this.pageViewManager=new Iv(this),this.rateLimiter=new $j(this),this.requestRouter=new Qj(this),this.consent=new Tj(this),this.externalIntegrations=new iT(this);var n=(t=pn.__defaultExtensionClasses)!==null&&t!==void 0?t:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(r,i,s)=>{var o=et(r)?{[r]:i}:r;this.setPersonProperties(o),s==null||s({})},set_once:(r,i,s)=>{var o=et(r)?{[r]:i}:r;this.setPersonProperties(void 0,o),s==null||s({})}},this.on("eventCaptured",r=>K.info('send "'+(r==null?void 0:r.event)+'"',r))}init(t,n,r){if(r&&r!==hs){var i,s=(i=fa[r])!==null&&i!==void 0?i:new pn;return s._init(t,n,r),fa[r]=s,fa[hs][r]=s,s}return this._init(t,n,r)}_init(t,n,r){var i,s,o,a;if(n===void 0&&(n={}),J(t)||wu(t))return K.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config={},n.debug=this.Rr(n.debug),this.Nr=n,this.Mr=[],n.person_profiles?this.Ar=n.person_profiles:n.process_person&&(this.Ar=n.process_person),this.set_config(Ge({},Jv(n.defaults),Qv(n),{name:r,token:t})),this.config.on_xhr_error&&K.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:Vn.GZipJS;var l=this.Fr();this.persistence=new eh(this.config,l),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new eh(W({},this.config,{persistence:"sessionStorage"}),l);var u=W({},this.persistence.props),c=W({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Or=new Gj(k=>this.Pr(k),this.config.request_queue_config),this.Lr=new Xj(this),this.__request_queue=[];var d=this.config.cookieless_mode===Pn||this.config.cookieless_mode===ir&&this.consent.isExplicitlyOptedOut();d||(this.sessionManager=new Uv(this),this.sessionPropsManager=new Wv(this,this.sessionManager,this.persistence));var h=(i=ne._POSTHOG_REMOTE_CONFIG)==null||(i=i[this.config.token])==null?void 0:i.config,p=h==null||(s=h.sdkVersion)==null?void 0:s.resolved;if(p&&(sT.test(p)?this._resolvedSdkVersion=p:K.warn("Ignoring invalid preloaded sdkVersion.resolved from remote config: "+p)),this.config.__preview_deferred_init_extensions?(K.info("Deferring extension initialization to improve startup performance"),setTimeout(()=>{this.Dr(d)},0)):(K.info("Initializing extensions synchronously"),this.Dr(d)),jt.DEBUG=jt.DEBUG||this.config.debug,jt.DEBUG&&K.info("Starting in debug mode",{this:this,config:n,thisC:W({},this.config),p:u,s:c}),!this.config.identity_distinct_id||(o=n.bootstrap)!=null&&o.distinctID||(n.bootstrap=W({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((a=n.bootstrap)==null?void 0:a.distinctID)!==void 0){var g=n.bootstrap.distinctID,m=this.get_distinct_id(),y=this.persistence.get_property(kn);if(n.bootstrap.isIdentifiedID&&m!=null&&m!==g&&y===ns)this.identify(g);else if(n.bootstrap.isIdentifiedID&&m!=null&&m!==g&&y===rs)K.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var x=this.config.get_device_id(Lr()),v=n.bootstrap.isIdentifiedID?x:g;this.persistence.set_property(kn,n.bootstrap.isIdentifiedID?rs:ns),this.register({distinct_id:g,$device_id:v})}}if(d)this.register_once({distinct_id:$l,$device_id:null},"");else if(!this.get_distinct_id()){var _=this.config.get_device_id(Lr());this.register_once({distinct_id:_,$device_id:_},""),this.persistence.set_property(kn,ns)}return Ze(I,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?function(k,w){var b=k.config.segment;if(!b)return w();(function(S,P){var j=S.config.segment;if(!j)return P();var E=A=>{var L=()=>A.anonymousId()||Lr();S.config.get_device_id=L,A.id()&&(S.register({distinct_id:A.id(),$device_id:L()}),S.persistence.set_property(kn,rs)),P()},R=j.user();"then"in R&&ur(R.then)?R.then(E):E(R)})(k,()=>{b.register((S=>{Promise&&Promise.resolve||Zd.warn("This browser does not have Promise support, and can not use the segment integration");var P=(j,E)=>{if(!E)return j;j.event.userId||j.event.anonymousId===S.get_distinct_id()||(Zd.info("No userId set, resetting PostHog"),S.reset()),j.event.userId&&j.event.userId!==S.get_distinct_id()&&(Zd.info("UserId set, identifying with PostHog"),S.identify(j.event.userId));var R=S.calculateEventProperties(E,j.event.properties);return j.event.properties=Object.assign({},R,j.event.properties),j};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:j=>P(j,j.event.event),page:j=>P(j,ds),identify:j=>P(j,Jd),screen:j=>P(j,"$screen")}})(k)).then(()=>{w()})})}(this,()=>this.Br()):this.Br(),ur(this.config._onCapture)&&this.config._onCapture!==xp&&(K.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",k=>this.config._onCapture(k.event,k))),this.config.ip&&K.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this}Dr(t){var n,r,i,s,o,a,l,u=performance.now(),c=W({},pn.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.featureFlags&&this.Ir.push(this.featureFlags=(n=this.featureFlags)!==null&&n!==void 0?n:new c.featureFlags(this)),c.exceptions&&this.Ir.push(this.exceptions=(r=this.exceptions)!==null&&r!==void 0?r:new c.exceptions(this)),c.historyAutocapture&&this.Ir.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.Ir.push(new c.tracingHeaders(this)),c.siteApps&&this.Ir.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!t&&this.Ir.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push(()=>{this.scrollManager.startMeasuringScrollPosition()}),c.autocapture&&this.Ir.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.Ir.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new c.surveys(this)),c.logs&&this.Ir.push(this.logs=(s=this.logs)!==null&&s!==void 0?s:new c.logs(this)),c.conversations&&this.Ir.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.Ir.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.Ir.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.Ir.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.Ir.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.Ir.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Rj)),c.toolbar&&this.Ir.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.Ir.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.Ir.forEach(h=>{h.initialize&&d.push(()=>{h.initialize==null||h.initialize()})}),d.push(()=>{if(this.jr){var h=this.jr;this.jr=void 0,this.Ci(h)}}),this.qr(d,u)}qr(t,n){for(;t.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&t.length>0)return void setTimeout(()=>{this.qr(t,n)},0);var r=t.shift();if(r)try{r()}catch(s){K.error("Error initializing extension:",s)}}var i=Math.round(performance.now()-n);this.register_for_session({$sdk_debug_extensions_init_method:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",$sdk_debug_extensions_init_time_ms:i}),this.config.__preview_deferred_init_extensions&&K.info("PostHog extensions initialized ("+i+"ms)")}Ci(t){var n;if(!X||!X.body)return K.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(()=>{this.Ci(t)},500);this.config.__preview_deferred_init_extensions&&(this.jr=t),this.compression=void 0,t.supportedCompression&&!this.config.disable_compression&&(this.compression=de(t.supportedCompression,Vn.GZipJS)?Vn.GZipJS:de(t.supportedCompression,Vn.Base64)?Vn.Base64:void 0),(n=t.analytics)!=null&&n.endpoint&&(this.analyticsDefaultEndpoint=t.analytics.endpoint),this.set_config({person_profiles:this.Ar?this.Ar:up}),this.Ir.forEach(r=>r.onRemoteConfig==null?void 0:r.onRemoteConfig(t))}Br(){try{this.config.loaded(this)}catch(r){K.critical("`loaded` function failed",r)}if(this.Zr(),this.config.internal_or_test_user_hostname&&ht!=null&&ht.hostname){var t=ht.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?t===n:n.test(t))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout(()=>{(this.consent.isOptedIn()||this.config.cookieless_mode===Pn)&&this.$r()},1),this.Vr=new mk(this),this.Vr.load()}Zr(){var t;this.is_capturing()&&this.config.request_batching&&((t=this.Or)==null||t.enable())}_dom_loaded(){this.is_capturing()&&zl(this.__request_queue,t=>this.Pr(t)),this.__request_queue=[],this.Zr()}_handle_unload(){var t,n,r,i;(t=this.surveys)==null||t.handlePageUnload(),this.config.request_batching?(this.Hr()&&this.capture(Kd),(n=this.logs)==null||n.flushLogs("sendBeacon"),(r=this.Or)==null||r.unload(),(i=this.Lr)==null||i.unload()):this.Hr()&&this.capture(Kd,null,{transport:"sendBeacon"})}_send_request(t){this.__loaded&&(Pk?this.__request_queue.push(t):this.rateLimiter.isServerRateLimited(t.batchKey)||(t.transport=t.transport||this.config.api_transport,t.url=rd(t.url,{ip:this.config.ip?1:0}),t.headers=W({},this.config.request_headers,t.headers),t.compression=t.compression==="best-available"?this.compression:t.compression,t.disableXHRCredentials=this.config.__preview_disable_xhr_credentials,this.config.__preview_disable_beacon&&(t.disableTransport=["sendBeacon"]),t.fetchOptions=t.fetchOptions||this.config.fetch_options,(n=>{var r,i,s,o=W({},n);o.timeout=o.timeout||6e4,o.url=Vv(o.url,o.compression);var a=(r=o.transport)!==null&&r!==void 0?r:"fetch",l=Su.filter(c=>!o.disableTransport||!c.transport||!o.disableTransport.includes(c.transport)),u=(i=(s=function(c,d){for(var h=0;c.length>h;h++)if(c[h].transport===a)return c[h]}(l))==null?void 0:s.method)!==null&&i!==void 0?i:l[0].method;if(!u)throw new Error("No available transport method");a!=="sendBeacon"&&o.data&&o.compression===Vn.GZipJS&&DN&&!Hv?qj(o).then(c=>{u(c)}).catch(c=>{if((d=>!(!d||typeof d!="object")&&("name"in d?String(d.name):"")==="NotReadableError")(c))return Hv=!0,void u(W({},o,{compression:void 0,url:Vv(n.url,void 0)}));u(o)}):u(o)})(W({},t,{callback:n=>{var r,i;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(r=(i=this.config).on_request_error)==null||r.call(i,n),t.callback==null||t.callback(n)}}))))}Pr(t){this.Lr?this.Lr.retriableRequest(t):this._send_request(t)}_execute_array(t){ah++;try{var n,r=[],i=[],s=[];zl(t,a=>{a&&(_e(n=a[0])?s.push(a):ur(a)?a.call(this):_e(a)&&n==="alias"?r.push(a):_e(a)&&n.indexOf("capture")!==-1&&ur(this[n])?s.push(a):i.push(a))});var o=function(a,l){zl(a,function(u){if(_e(u[0])){var c=l;Re(u,function(d){c=c[d[0]].apply(c,d.slice(1))})}else l[u[0]].apply(l,u.slice(1))})};o(r,this),o(i,this),o(s,this)}finally{ah--}}push(t){if(ah>0&&_e(t)&&et(t[0])){var n=pn.prototype[t[0]];ur(n)&&n.apply(this,t.slice(1))}else this._execute_array([t])}capture(t,n,r){var i,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Or){if(this.is_capturing())if(!J(t)&&et(t)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!et(n==null?void 0:n.$current_url)&&(K.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),t!=="$exception"||r!=null&&r.zr||K.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=(r==null?void 0:r.timestamp)||d,p=Lr(),g={uuid:p,event:t,properties:this.calculateEventProperties(t,n||{},h,p)};t===ds&&this.config.__preview_capture_bot_pageviews&&u&&(g.event="$bot_pageview",g.properties.$browser_type="bot"),c&&(g.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens),r!=null&&r.$set&&(g.$set=r==null?void 0:r.$set);var m,y=this.Ur(r==null?void 0:r.$set_once,t!==Tv,t===Jd);if(y&&(g.$set_once=y),r!=null&&r._noTruncate||(s=this.config.properties_string_max_length,o=g,a=S=>et(S)?S.slice(0,s):S,l=new Set,g=function S(P,j){return P!==Object(P)?a?a(P):P:l.has(P)?void 0:(l.add(P),_e(P)?(E=[],zl(P,R=>{E.push(S(R))})):(E={},Re(P,(R,A)=>{l.has(R)||(E[A]=S(R))})),E);var E}(o)),g.timestamp=h,J(r==null?void 0:r.timestamp)||(g.properties.$event_time_override_provided=!0,g.properties.$event_time_override_system_time=d),t===Yo.DISMISSED||t===Yo.SENT){var x=n==null?void 0:n[nh.SURVEY_ID],v=n==null?void 0:n[nh.SURVEY_ITERATION];m={id:x,current_iteration:v},localStorage.getItem(Yv(m))||localStorage.setItem(Yv(m),"true"),g.$set=W({},g.$set,{[Zj({id:x,current_iteration:v},t===Yo.SENT?"responded":"dismissed")]:!0})}else t===Yo.SHOWN&&(g.$set=W({},g.$set,{[nh.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(t===Fj.SHOWN){var _=n==null?void 0:n[Dv.TOUR_TYPE];_&&(g.$set=W({},g.$set,{[Dv.TOUR_LAST_SEEN_DATE+"/"+_]:new Date().toISOString()}))}var k=W({},g.properties.$set,g.$set);if(Ps(k)||this.setPersonPropertiesForFlags(k),!ge(this.config.before_send)){var w=this.Yr(g);if(!w)return;g=w}this.Sr.emit("eventCaptured",g);var b={method:"POST",url:(i=r==null?void 0:r._url)!==null&&i!==void 0?i:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:g,compression:"best-available",batchKey:r==null?void 0:r._batchKey};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.Pr(b):this.Or.enqueue(b),g}K.critical("This capture call is ignored due to client rate limiting.")}}else K.error("No event name provided to posthog.capture")}else K.uninitializedWarning("posthog.capture")}_addCaptureHook(t){return this.on("eventCaptured",n=>t(n.event,n))}calculateEventProperties(t,n,r,i,s){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(t),a=W({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,(this.config.cookieless_mode==Pn||this.config.cookieless_mode==ir&&this.consent.isExplicitlyOptedOut())&&(a.$cookieless_mode=!0),t==="$snapshot"){var l=W({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!et(a.distinct_id)&&!On(a.distinct_id)||wu(a.distinct_id))&&K.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=function(x,v){var _,k,w,b;if(!$t)return{};var S,P,j,E,R,A,L,U,$=x?[...Js,...v||[]]:[],[Y,Z]=function(O){for(var M=0;bv.length>M;M++){var[C,z]=bv[M],Q=C.exec(O),T=Q&&(ur(z)?z(Q,O):z);if(T)return T}return["",""]}($t);return Ge(am({$os:Y,$os_version:Z,$browser:Jw($t,navigator.vendor),$device:wv($t),$device_type:(P=$t,j={userAgentDataPlatform:(_=navigator)==null||(_=_.userAgentData)==null?void 0:_.platform,maxTouchPoints:(k=navigator)==null?void 0:k.maxTouchPoints,screenWidth:I==null||(w=I.screen)==null?void 0:w.width,screenHeight:I==null||(b=I.screen)==null?void 0:b.height,devicePixelRatio:I==null?void 0:I.devicePixelRatio},U=wv(P),U===Lw||U===Dw||U==="Kobo"||U==="Kindle Fire"||U===Kw?Ys:U===Wa||U===Ls||U===Ua||U===Kf?"Console":U===$w?"Wearable":U?sn:(j==null?void 0:j.userAgentDataPlatform)==="Android"&&((E=j==null?void 0:j.maxTouchPoints)!==null&&E!==void 0?E:0)>0?600>Math.min((R=j==null?void 0:j.screenWidth)!==null&&R!==void 0?R:0,(A=j==null?void 0:j.screenHeight)!==null&&A!==void 0?A:0)/((L=j==null?void 0:j.devicePixelRatio)!==null&&L!==void 0?L:1)?sn:Ys:"Desktop"),$timezone:gk(),$timezone_offset:Dj()}),{$current_url:qa(ht==null?void 0:ht.href,$,Ga),$host:ht==null?void 0:ht.host,$pathname:ht==null?void 0:ht.pathname,$raw_user_agent:$t.length>1e3?$t.substring(0,997)+"...":$t,$browser_version:QN($t,navigator.vendor),$browser_language:Ov(),$browser_language_prefix:(S=Ov(),typeof S=="string"?S.split("-")[0]:void 0),$screen_height:I==null?void 0:I.screen.height,$screen_width:I==null?void 0:I.screen.width,$viewport_height:I==null?void 0:I.innerHeight,$viewport_width:I==null?void 0:I.innerWidth,$lib:jt.LIB_NAME,$lib_version:jt.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3})}(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:d,windowId:h}=this.sessionManager.checkAndGetSessionAndWindowId(s,r.getTime());a.$session_id=d,a.$window_id=h}this.sessionPropsManager&&Ge(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&Ge(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Lr)==null?void 0:p.length}catch(x){a.$sdk_debug_error_capturing_properties=String(x)}if(this.requestRouter.region===gp&&(a.$lib_custom_api_host=this.config.api_host),u=t!==ds||s?t!==Kd||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,i),a=Ge(a,u),t===ds&&X&&(a.title=X.title),!J(o)){var g=r.getTime()-o;a.$duration=parseFloat((g/1e3).toFixed(3))}$t&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser"),(a=Ge({},c,this.persistence.properties(),this.sessionPersistence.properties(),a)).$is_identified=this._isIdentified(),_e(this.config.property_denylist)?Re(this.config.property_denylist,function(x){delete a[x]}):K.error(Ek+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var m=this.config.sanitize_properties;m&&(K.error(Kv),a=m(a,t));var y=this.Wr();return a.$process_person_profile=y,y&&!s&&this.Gr("_calculate_event_properties"),a}Ur(t,n,r){var i;if(n===void 0&&(n=!0),r===void 0&&(r=!1),!this.persistence||!this.Wr()||this.Cr&&!r)return t;var s=this.persistence.get_initial_props(),o=(i=this.sessionPropsManager)==null?void 0:i.getSetOnceProps(),a=Ge({},s,o||{},t||{}),l=this.config.sanitize_properties;return l&&(K.error(Kv),a=l(a,"$set_once")),n&&(this.Cr=!0),Ps(a)?void 0:a}register(t,n){var r;(r=this.persistence)==null||r.register(t,n)}register_once(t,n,r){var i;(i=this.persistence)==null||i.register_once(t,n,r)}register_for_session(t){var n;(n=this.sessionPersistence)==null||n.register(t)}unregister(t){var n;(n=this.persistence)==null||n.unregister(t)}unregister_for_session(t){var n;(n=this.sessionPersistence)==null||n.unregister(t)}Xr(t,n){this.register({[t]:n})}getFeatureFlag(t,n){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlag(t,n)}getFeatureFlagPayload(t){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(t)}getFeatureFlagResult(t,n){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlagResult(t,n)}isFeatureEnabled(t,n){var r;return(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(t,n)}reloadFeatureFlags(){var t;(t=this.featureFlags)==null||t.reloadFeatureFlags()}updateFlags(t,n,r){var i;(i=this.featureFlags)==null||i.updateFlags(t,n,r)}updateEarlyAccessFeatureEnrollment(t,n,r){var i;(i=this.featureFlags)==null||i.updateEarlyAccessFeatureEnrollment(t,n,r)}getEarlyAccessFeatures(t,n,r){var i;return n===void 0&&(n=!1),(i=this.featureFlags)==null?void 0:i.getEarlyAccessFeatures(t,n,r)}on(t,n){return this.Sr.on(t,n)}onFeatureFlags(t){return this.featureFlags?this.featureFlags.onFeatureFlags(t):(t([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(t){return this.surveys?this.surveys.onSurveysLoaded(t):(t([],{isLoaded:!1,error:No}),()=>{})}onSessionId(t){var n,r;return(n=(r=this.sessionManager)==null?void 0:r.onSessionId(t))!==null&&n!==void 0?n:()=>{}}getSurveys(t,n){n===void 0&&(n=!1),this.surveys?this.surveys.getSurveys(t,n):t([],{isLoaded:!1,error:No})}getActiveMatchingSurveys(t,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(t,n):t([],{isLoaded:!1,error:No})}renderSurvey(t,n){var r;(r=this.surveys)==null||r.renderSurvey(t,n)}displaySurvey(t,n){var r;n===void 0&&(n=tT),(r=this.surveys)==null||r.displaySurvey(t,n)}cancelPendingSurvey(t){var n;(n=this.surveys)==null||n.cancelPendingSurvey(t)}canRenderSurvey(t){var n,r;return(n=(r=this.surveys)==null?void 0:r.canRenderSurvey(t))!==null&&n!==void 0?n:{visible:!1,disabledReason:No}}canRenderSurveyAsync(t,n){var r,i;return n===void 0&&(n=!1),(r=(i=this.surveys)==null?void 0:i.canRenderSurveyAsync(t,n))!==null&&r!==void 0?r:Promise.resolve({visible:!1,disabledReason:No})}Jr(t){return!t||wu(t)?(K.critical("Unique user id has not been set in posthog.identify"),!1):t===$l?(K.critical('The string "'+t+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(t.toLowerCase())&&!["undefined","null"].includes(t.toLowerCase())||(K.critical('The string "'+t+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(t,n,r){if(!this.__loaded||!this.persistence)return K.uninitializedWarning("posthog.identify");if(On(t)&&(t=t.toString(),K.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jr(t)&&this.Gr("posthog.identify")){var i=this.get_distinct_id();this.register({$user_id:t}),this.get_property(dc)||this.register_once({$had_persisted_distinct_id:!0,$device_id:i},""),t!==i&&t!==this.get_property(Wo)&&(this.unregister(Wo),this.register({distinct_id:t}));var s,o=(this.persistence.get_property(kn)||ns)===ns;t!==i&&o?(this.persistence.set_property(kn,rs),this.setPersonPropertiesForFlags({$set:n||{},$set_once:r||{}},!1),this.capture(Jd,{distinct_id:t,$anon_distinct_id:i},{$set:n||{},$set_once:r||{}}),this.Er=qv(t,n,r),(s=this.featureFlags)==null||s.setAnonymousDistinctId(i)):(n||r)&&this.setPersonProperties(n,r),t!==i&&(this.reloadFeatureFlags(),this.unregister(da))}}setPersonProperties(t,n){if((t||n)&&this.Gr("posthog.setPersonProperties")){var r=qv(this.get_distinct_id(),t,n);this.Er!==r?(this.setPersonPropertiesForFlags({$set:t||{},$set_once:n||{}},!0),this.capture("$set",{$set:t||{},$set_once:n||{}}),this.Er=r):K.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(t,n,r){if(t&&n){var i=this.getGroups(),s=i[t]!==n;if(s&&this.resetGroupPropertiesForFlags(t),this.register({$groups:W({},i,{[t]:n})}),s||r){var o={$group_type:t,$group_key:n};r&&(o.$group_set=r),this.capture(Tv,o)}r&&this.setGroupPropertiesForFlags({[t]:r}),s&&!r&&this.reloadFeatureFlags()}else K.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(t,n){var r;n===void 0&&(n=!0),(r=this.featureFlags)==null||r.setPersonPropertiesForFlags(t,n)}resetPersonPropertiesForFlags(){var t;(t=this.featureFlags)==null||t.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(t,n){var r;n===void 0&&(n=!0),this.Gr("posthog.setGroupPropertiesForFlags")&&((r=this.featureFlags)==null||r.setGroupPropertiesForFlags(t,n))}resetGroupPropertiesForFlags(t){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(t)}reset(t){var n,r,i,s,o,a,l,u;if(K.info("reset"),!this.__loaded)return K.uninitializedWarning("posthog.reset");var c=this.get_property(dc);if(this.consent.reset(),(n=this.persistence)==null||n.clear(),(r=this.sessionPersistence)==null||r.clear(),(i=this.surveys)==null||i.reset(),(s=this.Vr)==null||s.stop(),(o=this.featureFlags)==null||o.reset(),(a=this.conversations)==null||a.reset(),(l=this.persistence)==null||l.set_property(kn,ns),(u=this.sessionManager)==null||u.resetSessionId(),this.Er=null,this.config.cookieless_mode===Pn)this.register_once({distinct_id:$l,$device_id:null},"");else{var d=this.config.get_device_id(Lr());this.register_once({distinct_id:d,$device_id:t?d:c},"")}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}setIdentity(t,n){var r;this.config.identity_distinct_id=t,this.config.identity_hash=n,this.alias(t),(r=this.conversations)==null||r.Kr()}clearIdentity(){var t;delete this.config.identity_distinct_id,delete this.config.identity_hash,(t=this.conversations)==null||t.Qr()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var t,n;return(t=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&t!==void 0?t:""}get_session_replay_url(t){if(!this.sessionManager)return"";var{sessionId:n,sessionStartTimestamp:r}=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n);if(t!=null&&t.withTimestamp&&r){var s,o=(s=t.timestampLookBack)!==null&&s!==void 0?s:10;if(!r)return i;i+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-o,0)}return i}alias(t,n){return t===this.get_property(tk)?(K.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gr("posthog.alias")?(J(n)&&(n=this.get_distinct_id()),t!==n?(this.Xr(Wo,t),this.capture("$create_alias",{alias:t,distinct_id:n})):(K.warn("alias matches current distinct_id - skipping api call."),this.identify(t),-1)):void 0}set_config(t){var n=W({},this.config);if(rt(t)){var r,i,s,o,a,l,u,c,d;Ge(this.config,Qv(t));var h=this.Fr();(r=this.persistence)==null||r.update_config(this.config,n,h),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new eh(W({},this.config,{persistence:"sessionStorage"}),h);var p=this.Rr(this.config.debug);Gn(p)&&(this.config.debug=p),Gn(this.config.debug)&&(this.config.debug?(jt.DEBUG=!0,Be.Ut()&&Be.Xt("ph_debug",!0),K.info("set_config",{config:t,oldConfig:n,newConfig:W({},this.config)})):(jt.DEBUG=!1,Be.Ut()&&Be.Jt("ph_debug"))),(i=this.exceptionObserver)==null||i.onConfigChange(),(s=this.sessionRecording)==null||s.startIfEnabledOrStop(),(o=this.autocapture)==null||o.startIfEnabled(),(a=this.heatmaps)==null||a.startIfEnabled(),(l=this.exceptionObserver)==null||l.startIfEnabledOrStop(),(u=this.deadClicksAutocapture)==null||u.startIfEnabledOrStop(),(c=this.surveys)==null||c.loadIfEnabled(),this.tn(),(d=this.externalIntegrations)==null||d.startIfEnabledOrStop()}}_overrideSDKInfo(t,n){jt.LIB_NAME=t,jt.LIB_VERSION=n}startSessionRecording(t){var n,r,i,s,o,a=t===!0,l={sampling:a||!(t==null||!t.sampling),linked_flag:a||!(t==null||!t.linked_flag),url_trigger:a||!(t==null||!t.url_trigger),event_trigger:a||!(t==null||!t.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((r=this.sessionRecording)==null||r.overrideSampling()),l.linked_flag&&((i=this.sessionRecording)==null||i.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var t;return!((t=this.sessionRecording)==null||!t.started)}captureException(t,n){if(this.exceptions){var r=new Error("PostHog syntheticException"),i=this.exceptions.buildProperties(t,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(W({},i,n))}}captureLog(t){var n;(n=this.logs)==null||n.captureLog(t)}get logger(){var t,n;return(t=(n=this.logs)==null?void 0:n.logger)!==null&&t!==void 0?t:pn.en}startExceptionAutocapture(t){this.set_config({capture_exceptions:t==null||t})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(t){var n,r;return(n=(r=this.toolbar)==null?void 0:r.loadToolbar(t))!==null&&n!==void 0&&n}get_property(t){var n;return(n=this.persistence)==null?void 0:n.props[t]}getSessionProperty(t){var n;return(n=this.sessionPersistence)==null?void 0:n.props[t]}toString(){var t,n=(t=this.config.name)!==null&&t!==void 0?t:hs;return n!==hs&&(n=hs+"."+n),n}_isIdentified(){var t,n;return((t=this.persistence)==null?void 0:t.get_property(kn))===rs||((n=this.sessionPersistence)==null?void 0:n.get_property(kn))===rs}Wr(){var t,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===up&&!this._isIdentified()&&Ps(this.getGroups())&&((t=this.persistence)==null||(t=t.props)==null||!t[Wo])&&((n=this.persistence)==null||(n=n.props)==null||!n[gc]))}Hr(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Wr()||this.Gr("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gr("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gr(t){return this.config.person_profiles==="never"?(K.error(t+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Xr(gc,!0),!0)}Fr(){if(this.config.cookieless_mode==="always")return!0;var t=this.consent.isOptedOut();return this.config.disable_persistence||t&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==ir)}tn(){var t,n,r,i,s=this.Fr();return((t=this.persistence)==null?void 0:t.fi)!==s&&((r=this.persistence)==null||r.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.fi)!==s&&((i=this.sessionPersistence)==null||i.set_disabled(s)),s}opt_in_capturing(t){var n;if(this.config.cookieless_mode!==Pn){if(this.config.cookieless_mode===ir&&this.consent.isExplicitlyOptedOut()){var r,i,s,o,a;this.reset(!0),(r=this.sessionManager)==null||r.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=new Uv(this),this.pageViewManager=new Iv(this),this.persistence&&(this.sessionPropsManager=new Wv(this,this.sessionManager,this.persistence));var l=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=pn.__defaultExtensionClasses)==null?void 0:a.sessionRecording;l&&(this.sessionRecording=this._r(this.sessionRecording,new l(this)))}var u,c;this.consent.optInOut(!0),this.tn(),this.Zr(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==ir&&((u=this.surveys)==null||u.loadIfEnabled()),(J(t==null?void 0:t.captureEventName)||t!=null&&t.captureEventName)&&this.capture((c=t==null?void 0:t.captureEventName)!==null&&c!==void 0?c:"$opt_in",t==null?void 0:t.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.$r()}else K.warn(Xv)}opt_out_capturing(){var t,n,r;this.config.cookieless_mode!==Pn?(this.config.cookieless_mode===ir&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this.tn(),this.config.cookieless_mode===ir&&(this.register({distinct_id:$l,$device_id:null}),(t=this.sessionManager)==null||t.destroy(),(n=this.pageViewManager)==null||n.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(r=this.sessionRecording)==null||r.stopRecording(),this.sessionRecording=void 0,this.$r())):K.warn(Xv)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var t=this.consent.consent;return t===1?"granted":t===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Pn||(this.config.cookieless_mode===ir?this.consent.isExplicitlyOptedOut()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.tn()}_is_bot(){return nn?kk(nn,this.config.custom_blocked_useragents):void 0}$r(){X&&(X.visibilityState==="visible"?this.kr||(this.kr=!0,this.capture(ds,{title:X.title},{send_instantly:!0}),this.Tr&&(X.removeEventListener(mc,this.Tr),this.Tr=null)):this.Tr||(this.Tr=this.$r.bind(this),Ze(X,mc,this.Tr)))}debug(t){t===!1?(I==null||I.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(I==null||I.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}ki(){var t,n,r,i,s,o,a=this.Nr||{};return"advanced_disable_flags"in a?!!a.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(K.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(r="advanced_disable_decide",i=K,s=(n="advanced_disable_flags")in(t=a)&&!ge(t[n]),o=r in t&&!ge(t[r]),s?t[n]:!!o&&(i&&i.warn("Config field '"+r+"' is deprecated. Please use '"+n+"' instead. The old field will be removed in a future major version."),t[r]))}Yr(t){if(ge(this.config.before_send))return t;var n=_e(this.config.before_send)?this.config.before_send:[this.config.before_send],r=t;for(var i of n){if(r=i(r),ge(r)){var s="Event '"+t.event+"' was rejected in beforeSend function";return zN(t.event)?K.warn(s+". This can cause unexpected behavior."):K.info(s),null}r.properties&&!Ps(r.properties)||K.warn("Event '"+t.event+"' has no properties after beforeSend function, this is likely an error.")}return r}getPageViewId(){var t;return(t=this.pageViewManager.ai)==null?void 0:t.pageViewId}captureTraceFeedback(t,n){this.capture("$ai_feedback",{$ai_trace_id:String(t),$ai_feedback_text:n})}captureTraceMetric(t,n,r){this.capture("$ai_metric",{$ai_trace_id:String(t),$ai_metric_name:n,$ai_metric_value:String(r)})}Rr(t){var n=Gn(t)&&!t,r=Be.Ut()&&Be.Wt("ph_debug")==="true";return!n&&(!!r||t)}}function Zv(e){return e instanceof Element&&(e.id===ik||!(e.closest==null||!e.closest(".toolbar-global-fade-container")))}function id(e){return!!e&&e.nodeType===1}function ti(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function Nk(e){return!!e&&e.nodeType===3}function jk(e){return!!e&&e.nodeType===11}function dm(e){return e?td(e).split(/\s+/):[]}function ey(e){var t=I==null?void 0:I.location.href;return!!(t&&e&&e.some(n=>t.match(n)))}function Cc(e){var t="";switch(typeof e.className){case"string":t=e.className;break;case"object":t=(e.className&&"baseVal"in e.className?e.className.baseVal:null)||e.getAttribute("class")||"";break;default:t=""}return dm(t)}function Tk(e){return ge(e)?null:td(e).split(/(\s+)/).filter(t=>pa(t)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Ya(e){var t="";return yp(e)&&!Rk(e)&&e.childNodes&&e.childNodes.length&&Re(e.childNodes,function(n){var r;Nk(n)&&n.textContent&&(t+=(r=Tk(n.textContent))!==null&&r!==void 0?r:"")}),td(t)}function ty(e){return J(e.target)?e.srcElement||null:(t=e.target)!=null&&t.shadowRoot?e.composedPath()[0]||null:e.target||null;var t}pn.__defaultExtensionClasses={},pn.en={trace:ss=()=>{},debug:ss,info:ss,warn:ss,error:ss,fatal:ss},function(e,t){for(var n=0;t.length>n;n++)e.prototype[t[n]]=bj(e.prototype[t[n]])}(pn,["identify"]);var hm=["a","button","form","input","select","textarea","label"];function ny(e,t){if(J(t))return!0;var n,r=function(s){if(t.some(o=>s.matches(o)))return{v:!0}};for(var i of e)if(n=r(i))return n.v;return!1}function Mk(e){var t=e.parentNode;return!(!t||!id(t))&&t}var lT=["next","previous","prev",">","<"],ry=[".ph-no-rageclick",".ph-no-capture"],vp=e=>!e||ti(e,"html")||!id(e),iy=(e,t)=>{if(!I||vp(e))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,r=[e],i=e;i.parentNode&&!ti(i,"body");)if(jk(i.parentNode))r.push(i.parentNode.host),i=i.parentNode.host;else{var s=Mk(i);if(!s)break;if(t||hm.indexOf(s.tagName.toLowerCase())>-1)n=!0;else{var o=I.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}r.push(s),i=s}return{parentIsUsefulElement:n,targetElementList:r}};function yp(e){for(var t=e;t.parentNode&&!ti(t,"body");t=t.parentNode){var n=Cc(t);if(de(n,"ph-sensitive")||de(n,"ph-no-capture"))return!1}if(de(Cc(e),"ph-include"))return!0;var r=e.type||"";if(et(r))switch(r.toLowerCase()){case"hidden":case"password":return!1}var i=e.name||e.id||"";return!et(i)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(i.replace(/[^a-zA-Z0-9]/g,""))}function Rk(e){return!!(ti(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||ti(e,"select")||ti(e,"textarea")||e.getAttribute("contenteditable")==="true")}var Ak="(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11})",uT=new RegExp("^(?:"+Ak+")$"),cT=new RegExp(Ak),Ik="\\d{3}-?\\d{2}-?\\d{4}",dT=new RegExp("^("+Ik+")$"),hT=new RegExp("("+Ik+")");function pa(e,t){return t===void 0&&(t=!0),!(ge(e)||et(e)&&(e=td(e),(t?uT:cT).test((e||"").replace(/[- ]/g,""))||(t?dT:hT).test(e)))}function sy(e){var t=Ya(e);return pa(t=(t+" "+Ok(e)).trim())?t:""}function Ok(e){var t="";return e&&e.childNodes&&e.childNodes.length&&Re(e.childNodes,function(n){var r;if(n&&((r=n.tagName)==null?void 0:r.toLowerCase())==="span")try{var i=Ya(n);t=(t+" "+i).trim(),n.childNodes&&n.childNodes.length&&(t=(t+" "+Ok(n)).trim())}catch(s){K.error("[AutoCapture]",s)}}),t}function oy(e){return e.replace(/"|\\"/g,'\\"')}function fT(e){var t=e.attr__class;return t?_e(t)?t:dm(t):void 0}class ay{constructor(t){this.disabled=t===!1;var n=rt(t)?t:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(t,n,r){if(this.disabled)return!1;var i=this.clicks[this.clicks.length-1];if(i&&Math.abs(t-i.x)+Math.abs(n-i.y)<this.thresholdPx&&this.timeoutMs>r-i.timestamp){if(this.clicks.push({x:t,y:n,timestamp:r}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:t,y:n,timestamp:r}];return!1}}var lh="$copy_autocapture",ly=We("[AutoCapture]");function uh(e,t){return t.length>e?t.slice(0,e)+"...":t}function pT(e){if(e.previousElementSibling)return e.previousElementSibling;var t=e;do t=t.previousSibling;while(t&&!id(t));return t}function gT(e,t){for(var n,r,{e:i,maskAllElementAttributes:s,maskAllText:o,elementAttributeIgnoreList:a,elementsChainAsString:l}=t,u=[e],c=e;c.parentNode&&!ti(c,"body");)jk(c.parentNode)?(u.push(c.parentNode.host),c=c.parentNode.host):(u.push(c.parentNode),c=c.parentNode);var d,h,p=[],g={},m=!1,y=!1;if(Re(u,w=>{var b=yp(w);w.tagName.toLowerCase()==="a"&&(m=w.getAttribute("href"),m=b&&m&&pa(m)&&m),de(Cc(w),"ph-no-capture")&&(y=!0),p.push(function(P,j,E,R){var A=P.tagName.toLowerCase(),L={tag_name:A};hm.indexOf(A)>-1&&!E&&(L.$el_text=A.toLowerCase()==="a"||A.toLowerCase()==="button"?uh(1024,sy(P)):uh(1024,Ya(P)));var U=Cc(P);U.length>0&&(L.classes=U.filter(function(O){return O!==""})),Re(P.attributes,function(O){var M;if((!Rk(P)||["name","id","class","aria-label"].indexOf(O.name)!==-1)&&(R==null||!R.includes(O.name))&&!j&&pa(O.value)&&(!et(M=O.name)||M.substring(0,10)!=="_ngcontent"&&M.substring(0,7)!=="_nghost")){var C=O.value;O.name==="class"&&(C=dm(C).join(" ")),L["attr__"+O.name]=uh(1024,C)}});for(var $=1,Y=1,Z=P;Z=pT(Z);)$++,Z.tagName===P.tagName&&Y++;return L.nth_child=$,L.nth_of_type=Y,L}(w,s,o,a));var S=function(P){if(!yp(P))return{};var j={};return Re(P.attributes,function(E){if(E.name&&E.name.indexOf("data-ph-capture-attribute")===0){var R=E.name.replace("data-ph-capture-attribute-",""),A=E.value;R&&A&&pa(A)&&(j[R]=A)}}),j}(w);Ge(g,S)}),y)return{props:{},explicitNoCapture:y};if(o||(p[0].$el_text=e.tagName.toLowerCase()==="a"||e.tagName.toLowerCase()==="button"?sy(e):Ya(e)),m){var x,v;p[0].attr__href=m;var _=(x=yc(m))==null?void 0:x.host,k=I==null||(v=I.location)==null?void 0:v.host;_&&k&&_!==k&&(d=m)}return{props:Ge({$event_type:i.type,$ce_version:1},l?{}:{$elements:p},{$elements_chain:(h=p,function(w){return w.map(b=>{var S,P,j="";if(b.tag_name&&(j+=b.tag_name),b.attr_class)for(var E of(b.attr_class.sort(),b.attr_class))j+="."+E.replace(/"/g,"");var R=W({},b.text?{text:b.text}:{},{"nth-child":(S=b.nth_child)!==null&&S!==void 0?S:0,"nth-of-type":(P=b.nth_of_type)!==null&&P!==void 0?P:0},b.href?{href:b.href}:{},b.attr_id?{attr_id:b.attr_id}:{},b.attributes),A={};return ku(R).sort((L,U)=>{var[$]=L,[Y]=U;return $.localeCompare(Y)}).forEach(L=>{var[U,$]=L;return A[oy(U.toString())]=oy($.toString())}),(j+=":")+ku(A).map(L=>{var[U,$]=L;return U+'="'+$+'"'}).join("")}).join(";")}(function(w){return w.map(b=>{var S,P,j={text:(S=b.$el_text)==null?void 0:S.slice(0,400),tag_name:b.tag_name,href:(P=b.attr__href)==null?void 0:P.slice(0,2048),attr_class:fT(b),attr_id:b.attr__id,nth_child:b.nth_child,nth_of_type:b.nth_of_type,attributes:{}};return ku(b).filter(E=>{var[R]=E;return R.indexOf("attr__")===0}).forEach(E=>{var[R,A]=E;return j.attributes[R]=A}),j})}(h)))},(n=p[0])!=null&&n.$el_text?{$el_text:(r=p[0])==null?void 0:r.$el_text}:{},d&&i.type==="click"?{$external_click_url:d}:{},g)}}var jo=We("[ExceptionAutocapture]");function uy(e,t,n){try{if(!(t in e))return()=>{};var r=e[t],i=n(r);return ur(i)&&(i.prototype=i.prototype||{},Object.defineProperties(i,{__posthog_wrapped__:{enumerable:!1,value:!0}})),e[t]=i,()=>{e[t]=r}}catch{return()=>{}}}var mT=We("[TracingHeaders]"),Pr=We("[Web Vitals]"),cy=9e5,dy="disabled",hy="lazy_loading",To="awaiting_config",Ul="missing_config";We("[SessionRecording]");var _p="[SessionRecording]",Nr=We(_p),xT=We("[Heatmaps]");function fy(e){return rt(e)&&"clientX"in e&&"clientY"in e&&On(e.clientX)&&On(e.clientY)}var py=We("[Product Tours]"),ch="ph_product_tours",vT=["$set_once","$set"],jr=We("[SiteApps]"),gy="Error while initializing PostHog app with config id ";function os(e,t,n){if(ge(e))return!1;switch(n){case"exact":return e===t;case"contains":var r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(r,"i").test(e);case"regex":try{return new RegExp(t).test(e)}catch{return!1}default:return!1}}class yT{constructor(t){this.rn=new cm,this.nn=(n,r)=>this.sn(n,r)&&this.an(n,r)&&this.ln(n,r)&&this.un(n,r),this.sn=(n,r)=>r==null||!r.event||(n==null?void 0:n.event)===(r==null?void 0:r.event),this._instance=t,this.hn=new Set,this.cn=new Set}init(){var t,n;J((t=this._instance)==null?void 0:t._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook((r,i)=>{this.on(r,i)})}register(t){var n,r;if(!J((n=this._instance)==null?void 0:n._addCaptureHook)&&(t.forEach(o=>{var a,l;(a=this.cn)==null||a.add(o),(l=o.steps)==null||l.forEach(u=>{var c;(c=this.hn)==null||c.add((u==null?void 0:u.event)||"")})}),(r=this._instance)!=null&&r.autocapture)){var i,s=new Set;t.forEach(o=>{var a;(a=o.steps)==null||a.forEach(l=>{l!=null&&l.selector&&s.add(l==null?void 0:l.selector)})}),(i=this._instance)==null||i.autocapture.setElementSelectors(s)}}on(t,n){var r;n!=null&&t.length!=0&&(this.hn.has(t)||this.hn.has(n==null?void 0:n.event))&&this.cn&&((r=this.cn)==null?void 0:r.size)>0&&this.cn.forEach(i=>{this.dn(n,i)&&this.rn.emit("actionCaptured",i.name)})}vn(t){this.onAction("actionCaptured",n=>t(n))}dn(t,n){if((n==null?void 0:n.steps)==null)return!1;for(var r of n.steps)if(this.nn(t,r))return!0;return!1}onAction(t,n){return this.rn.on(t,n)}an(t,n){if(n!=null&&n.url){var r,i=t==null||(r=t.properties)==null?void 0:r.$current_url;if(!i||typeof i!="string"||!os(i,n.url,n.url_matching||"contains"))return!1}return!0}ln(t,n){return!!this.fn(t,n)&&!!this.pn(t,n)&&!!this.gn(t,n)}fn(t,n){var r;if(n==null||!n.href)return!0;var i=this.mn(t);if(i.length>0)return i.some(a=>os(a.href,n.href,n.href_matching||"exact"));var s,o=(t==null||(r=t.properties)==null?void 0:r.$elements_chain)||"";return!!o&&os((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}pn(t,n){var r;if(n==null||!n.text)return!0;var i=this.mn(t);if(i.length>0)return i.some(u=>os(u.text,n.text,n.text_matching||"exact")||os(u.$el_text,n.text,n.text_matching||"exact"));var s,o,a,l=(t==null||(r=t.properties)==null?void 0:r.$elements_chain)||"";return!!l&&(s=function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!ge(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d}(l),o=n.text,a=n.text_matching||"exact",s.some(u=>os(u,o,a)))}gn(t,n){var r,i;if(n==null||!n.selector)return!0;var s=t==null||(r=t.properties)==null?void 0:r.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(t==null||(i=t.properties)==null?void 0:i.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}mn(t){var n;return(t==null||(n=t.properties)==null?void 0:n.$elements)==null?[]:t==null?void 0:t.properties.$elements}un(t,n){return n==null||!n.properties||n.properties.length===0||Ck(n.properties.reduce((r,i)=>{var s=_e(i.value)?i.value.map(String):i.value!=null?[String(i.value)]:[];return r[i.key]={values:s,operator:i.operator||"exact"},r},{}),t==null?void 0:t.properties)}}class _T{constructor(t){this._instance=t,this.yn=new Map,this.bn=new Map,this.wn=new Map}_n(t,n){return!!t&&Ck(t.propertyFilters,n==null?void 0:n.properties)}In(t,n){var r=new Map;return t.forEach(i=>{var s;(s=i.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach(o=>{if(o!=null&&o.name){var a=r.get(o.name)||[];a.push(i.id),r.set(o.name,a)}})}),r}Cn(t,n,r){var i=(r===So.Activation?this.yn:this.bn).get(t),s=[];return this.Sn(o=>{s=o.filter(a=>i==null?void 0:i.includes(a.id))}),s.filter(o=>{var a,l=(a=o.conditions)==null||(a=a[r])==null||(a=a.values)==null?void 0:a.find(u=>u.name===t);return this._n(l,n)})}register(t){var n;J((n=this._instance)==null?void 0:n._addCaptureHook)||(this.kn(t),this.xn(t))}xn(t){var n=t.filter(r=>{var i,s;return((i=r.conditions)==null?void 0:i.actions)&&((s=r.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0});n.length!==0&&(this.Tn==null&&(this.Tn=new yT(this._instance),this.Tn.init(),this.Tn.vn(r=>{this.onAction(r)})),n.forEach(r=>{var i,s,o,a,l;r.conditions&&(i=r.conditions)!=null&&i.actions&&(s=r.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=r.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Tn)==null||a.register(r.conditions.actions.values),(l=r.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach(u=>{if(u&&u.name){var c=this.wn.get(u.name);c&&c.push(r.id),this.wn.set(u.name,c||[r.id])}}))}))}kn(t){var n,r=t.filter(s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0}),i=t.filter(s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0});r.length===0&&i.length===0||((n=this._instance)==null||n._addCaptureHook((s,o)=>{this.onEvent(s,o)}),this.yn=this.In(t,So.Activation),this.bn=this.In(t,So.Cancellation))}onEvent(t,n){var r,i=this.re(),s=this.An(),o=this.En(),a=((r=this._instance)==null||(r=r.persistence)==null?void 0:r.props[s])||[];if(o===t&&n&&a.length>0){var l,u;i.info("event matched, removing item from activated items",{event:t,eventPayload:n,existingActivatedItems:a});var c=(n==null||(l=n.properties)==null?void 0:l.$survey_id)||(n==null||(u=n.properties)==null?void 0:u.$product_tour_id);if(c){var d=a.indexOf(c);0>d||(a.splice(d,1),this.Rn(a))}}else{if(this.bn.has(t)){var h=this.Cn(t,n,So.Cancellation);h.length>0&&(i.info("cancel event matched, cancelling items",{event:t,itemsToCancel:h.map(g=>g.id)}),h.forEach(g=>{var m=a.indexOf(g.id);0>m||a.splice(m,1),this.Nn(g.id)}),this.Rn(a))}if(this.yn.has(t)){i.info("event name matched",{event:t,eventPayload:n,items:this.yn.get(t)});var p=this.Cn(t,n,So.Activation);this.Rn(a.concat(p.map(g=>g.id)||[]))}}}onAction(t){var n,r=this.An(),i=((n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[r])||[];this.wn.has(t)&&this.Rn(i.concat(this.wn.get(t)||[]))}Rn(t){var n,r=this.re(),i=this.An(),s=[...new Set(t)].filter(o=>!this.Mn(o));r.info("updating activated items",{activatedItems:s}),(n=this._instance)==null||(n=n.persistence)==null||n.register({[i]:s})}getActivatedIds(){var t,n=this.An();return((t=this._instance)==null||(t=t.persistence)==null?void 0:t.props[n])||[]}getEventToItemsMap(){return this.yn}Fn(){return this.Tn}}class bT extends _T{constructor(t){super(t)}An(){return"$surveys_activated"}En(){return Yo.SHOWN}Sn(t){var n;(n=this._instance)==null||n.getSurveys(t)}Nn(t){var n;(n=this._instance)==null||n.cancelPendingSurvey(t)}re(){return Ee}Mn(){return!1}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var dh="SDK is not enabled or survey functionality is not yet loaded",my="Disabled. Not loading surveys.",wT=I!=null&&I.location?bc(I.location.hash,"__posthog")||bc(location.hash,"state"):null,xy="_postHogToolbarParams",vy=We("[Toolbar]"),Pt=We("[FeatureFlags]"),gi=We("[FeatureFlags]",{debugEnabled:!0}),hh=`" failed. Feature flags didn't load in time.`,fh="$active_feature_flags",Tr="$override_feature_flags",yy="$feature_flag_payloads",Mo="$override_feature_flag_payloads",_y="$feature_flag_request_id",by=e=>{for(var t={},n=0;e.length>n;n++)t[e[n]]=!0;return t},wy=e=>{var t={};for(var[n,r]of ku(e||{}))r&&(t[n]=r);return t},ph=We("[Error tracking]"),ky="Refusing to render web experiment since the viewer is a likely bot",kT={icontains:(e,t)=>!!I&&t.href.toLowerCase().indexOf(e.toLowerCase())>-1,not_icontains:(e,t)=>!!I&&t.href.toLowerCase().indexOf(e.toLowerCase())===-1,regex:(e,t)=>!!I&&Sc(t.href,e),not_regex:(e,t)=>!!I&&!Sc(t.href,e),exact:(e,t)=>t.href===e,is_not:(e,t)=>t.href!==e};class vt{get Rt(){return this._instance.config}constructor(t){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),n.getWebExperiments(i=>{vt.On("retrieved web experiments from the server"),n.Pn=new Map,i.forEach(s=>{if(s.feature_flag_key){var o;n.Pn&&(vt.On("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.Pn)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);et(a)&&s.variants[a]&&n.Ln(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];vt.Dn(u)&&n.Ln(s.name,l,u.transforms)}})},r)},this._instance=t,this._instance.onFeatureFlags(r=>{this.onFeatureFlags(r)})}initialize(){}onFeatureFlags(t){if(this._is_bot())vt.On(ky);else if(!this.Rt.disable_web_experiments){if(ge(this.Pn))return this.Pn=new Map,this.loadIfEnabled(),void this.previewWebExperiment();vt.On("applying feature flags",t),t.forEach(n=>{var r;if(this.Pn&&(r=this.Pn)!=null&&r.has(n)){var i,s=this._instance.getFeatureFlag(n),o=(i=this.Pn)==null?void 0:i.get(n);s&&o!=null&&o.variants[s]&&this.Ln(o.name,s,o.variants[s].transforms)}})}}previewWebExperiment(){var t=vt.getWindowLocation();if(t!=null&&t.search){var n=_c(t==null?void 0:t.search,"__experiment_id"),r=_c(t==null?void 0:t.search,"__experiment_variant");n&&r&&(vt.On("previewing web experiments "+n+" && "+r),this.getWebExperiments(i=>{this.Bn(parseInt(n),r,i)},!1,!0))}}loadIfEnabled(){this.Rt.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(t,n,r){if(this.Rt.disable_web_experiments&&!r)return t([]);var i=this._instance.get_property("$web_experiments");if(i&&!n)return t(i);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Rt.token),method:"GET",callback:s=>t(s.statusCode===200&&s.json&&s.json.experiments||[])})}Bn(t,n,r){var i=r.filter(s=>s.id===t);i&&i.length>0&&(vt.On("Previewing web experiment ["+i[0].name+"] with variant ["+n+"]"),this.Ln(i[0].name,n,i[0].variants[n].transforms))}static Dn(t){return!ge(t.conditions)&&vt.jn(t)&&vt.qn(t)}static jn(t){var n;if(ge(t.conditions)||ge((n=t.conditions)==null?void 0:n.url))return!0;var r,i,s,o=vt.getWindowLocation();return!!o&&((r=t.conditions)==null||!r.url||kT[(i=(s=t.conditions)==null?void 0:s.urlMatchType)!==null&&i!==void 0?i:"icontains"](t.conditions.url,o))}static getWindowLocation(){return I==null?void 0:I.location}static qn(t){var n;if(ge(t.conditions)||ge((n=t.conditions)==null?void 0:n.utm))return!0;var r=uk();if(r.utm_source){var i,s,o,a,l,u,c,d,h=(i=t.conditions)==null||(i=i.utm)==null||!i.utm_campaign||((s=t.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==r.utm_campaign,p=(o=t.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=t.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==r.utm_source,g=(l=t.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=t.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==r.utm_medium,m=(c=t.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=t.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==r.utm_term;return h&&g&&m&&p}return!1}static On(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;n>i;i++)r[i-1]=arguments[i];K.info("[WebExperiments] "+t,r)}Ln(t,n,r){this._is_bot()?vt.On(ky):n!=="control"?r.forEach(i=>{if(i.selector){var s;vt.On("applying transform of variant "+n+" for experiment "+t+" ",i);var o=(s=document)==null?void 0:s.querySelectorAll(i.selector);o==null||o.forEach(a=>{var l=a;i.html&&(l.innerHTML=i.html),i.css&&l.setAttribute("style",i.css)})}}):vt.On("Control variants leave the page unmodified.")}_is_bot(){return nn&&this._instance?kk(nn,this.Rt.custom_blocked_useragents):void 0}}var cn=We("[Conversations]"),mi="Conversations not available yet.",Dk={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}},ST=Dk.info;function Lk(e){if(Gn(e))return{boolValue:e};if(On(e))return Number.isInteger(e)?{intValue:e}:{doubleValue:e};if(typeof e=="string")return{stringValue:e};if(_e(e))return{arrayValue:{values:e.map(t=>Lk(t))}};try{return{stringValue:JSON.stringify(e)}}catch{return{stringValue:String(e)}}}function Sy(e){var t=[];for(var n in e){var r=e[n];kr(r)||J(r)||t.push({key:n,value:Lk(r)})}return t}var sd={featureFlags:class{constructor(e){this.Zn=!1,this.$n=!1,this.Vn=!1,this.Hn=!1,this.zn=!1,this.Un=!1,this.Yn=!1,this.Wn=!1,this._instance=e,this.featureFlagEventHandlers=[]}get Rt(){return this._instance.config}get Xi(){return this._instance.persistence}Gn(e){return this._instance.get_property(e)}Xn(){var e,t;return(e=(t=this.Xi)==null?void 0:t.pi(this.Rt.feature_flag_cache_ttl_ms))!==null&&e!==void 0&&e}Jn(){return!!this.Xn()&&(this.Wn||this.Vn||(this.Wn=!0,Pt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Kn(){var e,t=(e=this.Rt.evaluation_contexts)!==null&&e!==void 0?e:this.Rt.evaluation_environments;return!this.Rt.evaluation_environments||this.Rt.evaluation_contexts||this.Yn||(Pt.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.Yn=!0),t!=null&&t.length?t.filter(n=>{var r=n&&typeof n=="string"&&n.trim().length>0;return r||Pt.error("Invalid evaluation context found:",n,"Expected non-empty string"),r}):[]}Qn(){return this.Kn().length>0}initialize(){var e,t,{config:n}=this._instance,r=(e=(t=n.bootstrap)==null?void 0:t.featureFlags)!==null&&e!==void 0?e:{};if(Object.keys(r).length){var i,s,o=(i=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&i!==void 0?i:{},a=Object.keys(r).filter(u=>!!r[u]).reduce((u,c)=>(u[c]=r[c]||!1,u),{}),l=Object.keys(o).filter(u=>a[u]).reduce((u,c)=>(o[c]&&(u[c]=o[c]),u),{});this.receivedFeatureFlags({featureFlags:a,featureFlagPayloads:l})}}updateFlags(e,t,n){var r=n!=null&&n.merge?this.getFlagVariants():{},i=n!=null&&n.merge?this.getFlagPayloads():{},s=W({},r,e),o=W({},i,t),a={};for(var[l,u]of Object.entries(s)){var c=typeof u=="string";a[l]={key:l,enabled:!!c||!!u,variant:c?u:void 0,reason:void 0,metadata:J(o==null?void 0:o[l])?void 0:{id:0,version:void 0,description:void 0,payload:o[l]}}}this.receivedFeatureFlags({flags:a})}get hasLoadedFlags(){return this.$n}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this.Gn(tp),t=this.Gn(Tr),n=this.Gn(Mo);if(!n&&!t)return e||{};var r=Ge({},e||{}),i=[...new Set([...Object.keys(n||{}),...Object.keys(t||{})])];for(var s of i){var o,a,l=r[s],u=t==null?void 0:t[s],c=J(u)?(o=l==null?void 0:l.enabled)!==null&&o!==void 0&&o:!!u,d=J(u)?l.variant:typeof u=="string"?u:void 0,h=n==null?void 0:n[s],p=W({},l,{enabled:c,variant:c?d??(l==null?void 0:l.variant):void 0});c!==(l==null?void 0:l.enabled)&&(p.original_enabled=l==null?void 0:l.enabled),d!==(l==null?void 0:l.variant)&&(p.original_variant=l==null?void 0:l.variant),h&&(p.metadata=W({},l==null?void 0:l.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),r[s]=p}return this.Zn||(Pt.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:n,finalDetails:r}),this.Zn=!0),r}getFlagVariants(){var e=this.Gn(Ns),t=this.Gn(Tr);if(!t)return e||{};for(var n=Ge({},e),r=Object.keys(t),i=0;r.length>i;i++)n[r[i]]=t[r[i]];return this.Zn||(Pt.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:t,finalFlags:n}),this.Zn=!0),n}getFlagPayloads(){var e=this.Gn(yy),t=this.Gn(Mo);if(!t)return e||{};for(var n=Ge({},e||{}),r=Object.keys(t),i=0;r.length>i;i++)n[r[i]]=t[r[i]];return this.Zn||(Pt.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:t,finalPayloads:n}),this.Zn=!0),n}reloadFeatureFlags(){this.Hn||this.Rt.advanced_disable_feature_flags||this.ts||(this._instance.Sr.emit("featureFlagsReloading",!0),this.ts=setTimeout(()=>{this.es()},5))}rs(){clearTimeout(this.ts),this.ts=void 0}ensureFlagsLoaded(){this.$n||this.Vn||this.ts||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.Hn=e}es(e){var t;if(this.rs(),!this._instance.ki())if(this.Vn)this.zn=!0;else{var n=this.Rt.token,r=this.Gn(dc),i={token:n,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:W({},((t=this.Xi)==null?void 0:t.get_initial_props())||{},this.Gn(Go)||{}),group_properties:this.Gn(Si),timezone:gk()};kr(r)||J(r)||(i.$device_id=r),(e!=null&&e.disableFlags||this.Rt.advanced_disable_feature_flags)&&(i.disable_flags=!0),this.Qn()&&(i.evaluation_contexts=this.Kn());var s=this._instance.requestRouter.endpointFor("flags","/flags/?v=2"+(this.Rt.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":""));this.Vn=!0,this._instance._send_request({method:"POST",url:s,data:i,compression:this.Rt.disable_compression?void 0:Vn.Base64,timeout:this.Rt.feature_flag_request_timeout_ms,callback:o=>{var a,l,u,c=!0;if(o.statusCode===200&&(this.zn||(this.$anon_distinct_id=void 0),c=!1),this.Vn=!1,!i.disable_flags||this.zn){this.Un=!c;var d=[];o.error?o.error instanceof Error?d.push(o.error.name==="AbortError"?"timeout":"connection_error"):d.push("unknown_error"):o.statusCode!==200&&d.push("api_error_"+o.statusCode),(a=o.json)!=null&&a.errorsWhileComputingFlags&&d.push("errors_while_computing_flags");var h,p=!((l=o.json)==null||(l=l.quotaLimited)==null||!l.includes("feature_flags"));p&&d.push("quota_limited"),(u=this.Xi)==null||u.register({[ip]:d}),p?Pt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):(i.disable_flags||this.receivedFeatureFlags((h=o.json)!==null&&h!==void 0?h:{},c,{partialResponse:!!this.Rt.advanced_only_evaluate_survey_feature_flags}),this.zn&&(this.zn=!1,this.es()))}}})}}getFeatureFlag(e,t){var n;if(t===void 0&&(t={}),!t.fresh||this.Un)if(this.$n||this.getFlags()&&this.getFlags().length>0){if(!this.Jn()){var r=this.getFeatureFlagResult(e,t);return(n=r==null?void 0:r.variant)!==null&&n!==void 0?n:r==null?void 0:r.enabled}}else Pt.warn('getFeatureFlag for key "'+e+hh)}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){var t=this.getFeatureFlagResult(e,{send_event:!1});return t==null?void 0:t.payload}getFeatureFlagResult(e,t){if(t===void 0&&(t={}),!t.fresh||this.Un)if(this.$n||this.getFlags()&&this.getFlags().length>0){if(!this.Jn()){var n=this.getFlagVariants(),r=e in n,i=n[e],s=this.getFlagPayloads()[e],o=String(i),a=this.Gn(_y)||void 0,l=this.Gn(fc)||void 0,u=this.Gn(da)||{};if(this.Rt.advanced_feature_flags_dedup_per_session){var c,d=this._instance.get_session_id(),h=this.Gn(rp);d&&d!==h&&(u={},(c=this.Xi)==null||c.register({[da]:u,[rp]:d}))}if((t.send_event||!("send_event"in t))&&(!(e in u)||!u[e].includes(o))){var p,g,m,y,x,v,_,k,w,b;_e(u[e])?u[e].push(o):u[e]=[o],(p=this.Xi)==null||p.register({[da]:u});var S=this.getFeatureFlagDetails(e),P=[...(g=this.Gn(ip))!==null&&g!==void 0?g:[]];J(i)&&P.push("flag_missing");var j={$feature_flag:e,$feature_flag_response:i,$feature_flag_payload:s||null,$feature_flag_request_id:a,$feature_flag_evaluated_at:l,$feature_flag_bootstrapped_response:((m=this.Rt.bootstrap)==null||(m=m.featureFlags)==null?void 0:m[e])||null,$feature_flag_bootstrapped_payload:((y=this.Rt.bootstrap)==null||(y=y.featureFlagPayloads)==null?void 0:y[e])||null,$used_bootstrap_value:!this.Un};J(S==null||(x=S.metadata)==null?void 0:x.version)||(j.$feature_flag_version=S.metadata.version);var E,R=(v=S==null||(_=S.reason)==null?void 0:_.description)!==null&&v!==void 0?v:S==null||(k=S.reason)==null?void 0:k.code;R&&(j.$feature_flag_reason=R),S!=null&&(w=S.metadata)!=null&&w.id&&(j.$feature_flag_id=S.metadata.id),J(S==null?void 0:S.original_variant)&&J(S==null?void 0:S.original_enabled)||(j.$feature_flag_original_response=J(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(b=S.metadata)!=null&&b.original_payload&&(j.$feature_flag_original_payload=S==null||(E=S.metadata)==null?void 0:E.original_payload),P.length&&(j.$feature_flag_error=P.join(",")),this._instance.capture("$feature_flag_called",j)}if(r){var A=s;if(!J(s))try{A=JSON.parse(s)}catch{}return{key:e,enabled:!!i,variant:typeof i=="string"?i:void 0,payload:A}}}}else Pt.warn('getFeatureFlagResult for key "'+e+hh)}getRemoteConfigPayload(e,t){var n=this.Rt.token,r={distinct_id:this._instance.get_distinct_id(),token:n};this.Qn()&&(r.evaluation_contexts=this.Kn()),this._instance._send_request({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2"),data:r,compression:this.Rt.disable_compression?void 0:Vn.Base64,timeout:this.Rt.feature_flag_request_timeout_ms,callback(i){var s,o=(s=i.json)==null?void 0:s.featureFlagPayloads;t((o==null?void 0:o[e])||void 0)}})}isFeatureEnabled(e,t){if(t===void 0&&(t={}),!t.fresh||this.Un){if(this.$n||this.getFlags()&&this.getFlags().length>0){var n=this.getFeatureFlag(e,t);return J(n)?void 0:!!n}Pt.warn('isFeatureEnabled for key "'+e+hh)}}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(t=>t!==e)}receivedFeatureFlags(e,t,n){if(this.Xi){this.$n=!0;var r=this.getFlagVariants(),i=this.getFlagPayloads(),s=this.getFlagsWithDetails();(function(o,a,l,u,c,d){l===void 0&&(l={}),u===void 0&&(u={}),c===void 0&&(c={});var h=(P=>{var j=P.flags;return j?(P.featureFlags=Object.fromEntries(Object.keys(j).map(E=>{var R;return[E,(R=j[E].variant)!==null&&R!==void 0?R:j[E].enabled]})),P.featureFlagPayloads=Object.fromEntries(Object.keys(j).filter(E=>j[E].enabled).filter(E=>{var R;return(R=j[E].metadata)==null?void 0:R.payload}).map(E=>{var R;return[E,(R=j[E].metadata)==null?void 0:R.payload]}))):Pt.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),P})(o),p=h.flags,g=h.featureFlags,m=h.featureFlagPayloads;if(g){var y=o.requestId,x=o.evaluatedAt;if(_e(g)){Pt.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var v={};if(g)for(var _=0;g.length>_;_++)v[g[_]]=!0;a&&a.register({[fh]:g,[Ns]:v})}else{var k=g,w=m,b=p;if(d!=null&&d.partialResponse)k=W({},l,k),w=W({},u,w),b=W({},c,b);else if(o.errorsWhileComputingFlags)if(p){var S=new Set(Object.keys(p).filter(P=>{var j;return!((j=p[P])!=null&&j.failed)}));k=W({},l,Object.fromEntries(Object.entries(k).filter(P=>{var[j]=P;return S.has(j)}))),w=W({},u,Object.fromEntries(Object.entries(w||{}).filter(P=>{var[j]=P;return S.has(j)}))),b=W({},c,Object.fromEntries(Object.entries(b||{}).filter(P=>{var[j]=P;return S.has(j)})))}else k=W({},l,k),w=W({},u,w),b=W({},c,b);a&&a.register(W({[fh]:Object.keys(wy(k)),[Ns]:k||{},[yy]:w||{},[tp]:b||{}},y?{[_y]:y}:{},x?{[fc]:x}:{}))}}})(e,this.Xi,r,i,s,n),t||(this.Wn=!1),this.ns(t)}}override(e,t){t===void 0&&(t=!1),Pt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:t})}overrideFeatureFlags(e){if(!this._instance.__loaded||!this.Xi)return Pt.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(e===!1)return this.Xi.unregister(Tr),this.Xi.unregister(Mo),this.ns(),gi.info("All overrides cleared");if(_e(e)){var t=by(e);return this.Xi.register({[Tr]:t}),this.ns(),gi.info("Flag overrides set",{flags:e})}if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var n,r=e;if(this.Zn=!!((n=r.suppressWarning)!==null&&n!==void 0&&n),"flags"in r){if(r.flags===!1)this.Xi.unregister(Tr),gi.info("Flag overrides cleared");else if(r.flags){if(_e(r.flags)){var i=by(r.flags);this.Xi.register({[Tr]:i})}else this.Xi.register({[Tr]:r.flags});gi.info("Flag overrides set",{flags:r.flags})}}return"payloads"in r&&(r.payloads===!1?(this.Xi.unregister(Mo),gi.info("Payload overrides cleared")):r.payloads&&(this.Xi.register({[Mo]:r.payloads}),gi.info("Payload overrides set",{payloads:r.payloads}))),void this.ns()}if(e&&typeof e=="object")return this.Xi.register({[Tr]:e}),this.ns(),gi.info("Flag overrides set",{flags:e});Pt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:e})}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.$n){var{flags:t,flagVariants:n}=this.ss();e(t,n)}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,t,n){var r,i=(this.Gn(qo)||[]).find(l=>l.flagKey===e),s={["$feature_enrollment/"+e]:t},o={$feature_flag:e,$feature_enrollment:t,$set:s};i&&(o.$early_access_feature_name=i.name),n&&(o.$feature_enrollment_stage=n),this._instance.capture("$feature_enrollment_update",o),this.setPersonPropertiesForFlags(s,!1);var a=W({},this.getFlagVariants(),{[e]:t});(r=this.Xi)==null||r.register({[fh]:Object.keys(wy(a)),[Ns]:a}),this.ns()}getEarlyAccessFeatures(e,t,n){t===void 0&&(t=!1);var r=this.Gn(qo),i=n?"&"+n.map(s=>"stage="+s).join("&"):"";if(r&&!t)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this.Rt.token+i),method:"GET",callback:s=>{var o,a;if(s.json){var l=s.json.earlyAccessFeatures;return(o=this.Xi)==null||o.unregister(qo),(a=this.Xi)==null||a.register({[qo]:l}),e(l)}}})}ss(){var e=this.getFlags(),t=this.getFlagVariants();return{flags:e.filter(n=>t[n]),flagVariants:Object.keys(t).filter(n=>t[n]).reduce((n,r)=>(n[r]=t[r],n),{})}}ns(e){var{flags:t,flagVariants:n}=this.ss();this.featureFlagEventHandlers.forEach(r=>r(t,n,{errorsLoading:e}))}setPersonPropertiesForFlags(e,t){t===void 0&&(t=!0);var n=this.Gn(Go)||{},r=(e==null?void 0:e.$set)||(e!=null&&e.$set_once?{}:e),i=e==null?void 0:e.$set_once,s={};if(i)for(var o in i)({}).hasOwnProperty.call(i,o)&&(o in n||(s[o]=i[o]));this._instance.register({[Go]:W({},n,s,r)}),t&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(Go)}setGroupPropertiesForFlags(e,t){t===void 0&&(t=!0);var n=this.Gn(Si)||{};Object.keys(n).length!==0&&Object.keys(n).forEach(r=>{n[r]=W({},n[r],e[r]),delete e[r]}),this._instance.register({[Si]:W({},n,e)}),t&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var t=this.Gn(Si)||{};this._instance.register({[Si]:W({},t,{[e]:{}})})}else this._instance.unregister(Si)}reset(){this.$n=!1,this.Vn=!1,this.Hn=!1,this.zn=!1,this.Un=!1,this.$anon_distinct_id=void 0,this.rs(),this.Zn=!1}}},CT={sessionRecording:class{get Rt(){return this._instance.config}get Xi(){return this._instance.persistence}get started(){var e;return!((e=this.os)==null||!e.isStarted)}get status(){var e,t;return this.ls===To||this.ls===Ul?this.ls:(e=(t=this.os)==null?void 0:t.status)!==null&&e!==void 0?e:this.ls}constructor(e){if(this._forceAllowLocalhostNetworkCapture=!1,this.ls=dy,this.us=void 0,this._instance=e,!this._instance.sessionManager)throw Nr.error("started without valid sessionManager"),new Error(_p+" started without valid sessionManager. This is a bug.");if(this.Rt.cookieless_mode===Pn)throw new Error(_p+' cannot be used with cookieless_mode="always"')}initialize(){this.startIfEnabledOrStop()}get hs(){var e,t=!((e=this._instance.get_property(Fl))==null||!e.enabled),n=!this.Rt.disable_session_recording,r=this.Rt.disable_session_recording||this._instance.consent.isOptedOut();return I&&t&&n&&!r}startIfEnabledOrStop(e){var t;if(!this.hs||(t=this.os)==null||!t.isStarted){var n=!J(Object.assign)&&!J(Array.from);this.hs&&n?(this.cs(e),Nr.info("starting")):(this.ls=dy,this.stopRecording())}}cs(e){var t,n,r;this.hs&&(this.ls!==To&&this.ls!==Ul&&(this.ls=hy),ne!=null&&(t=ne.__PosthogExtensions__)!=null&&(t=t.rrweb)!=null&&t.record&&(n=ne.__PosthogExtensions__)!=null&&n.initSessionRecording?this.ds(e):(r=ne.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,this.vs,i=>{if(i)return Nr.error("could not load recorder",i);this.ds(e)}))}stopRecording(){var e,t;(e=this.us)==null||e.call(this),this.us=void 0,(t=this.os)==null||t.stop()}fs(){var e,t;(e=this.us)==null||e.call(this),this.us=void 0,(t=this.os)==null||t.discard()}ps(){var e;(e=this.Xi)==null||e.unregister(rk)}gs(e,t){if(ge(e))return null;var n,r=On(e)?e:parseFloat(e);return typeof(n=r)!="number"||!Number.isFinite(n)||0>n||n>1?(Nr.warn(t+" must be between 0 and 1. Ignoring invalid value:",e),null):r}ys(e){if(this.Xi){var t,n,r=this.Xi,i=()=>{var s,o=e.sessionRecording===!1?void 0:e.sessionRecording,a=this.gs((s=this.Rt.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.gs(o==null?void 0:o.sampleRate,"remote config sampleRate"),u=a??l;ge(u)&&this.ps();var c=o==null?void 0:o.minimumDurationMilliseconds;r.register({[Fl]:W({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:W({capturePerformance:e.capturePerformance},o==null?void 0:o.networkPayloadCapture),canvasRecording:{enabled:o==null?void 0:o.recordCanvas,fps:o==null?void 0:o.canvasFps,quality:o==null?void 0:o.canvasQuality},sampleRate:u,minimumDurationMilliseconds:J(c)?null:c,endpoint:o==null?void 0:o.endpoint,triggerMatchType:o==null?void 0:o.triggerMatchType,masking:o==null?void 0:o.masking,urlTriggers:o==null?void 0:o.urlTriggers})})};i(),(t=this.us)==null||t.call(this),this.us=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(i)}}onRemoteConfig(e){return"sessionRecording"in e?e.sessionRecording===!1?(this.ys(e),void this.fs()):(this.ys(e),void this.startIfEnabledOrStop()):(this.ls===To&&(this.ls=Ul,Nr.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(e,t){var n;t===void 0&&(t="log"),(n=this.os)!=null&&n.log?this.os.log(e,t):Nr.warn("log called before recorder was ready")}get vs(){var e,t,n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.get_property(Fl);return(n==null||(t=n.scriptConfig)==null?void 0:t.script)||"lazy-recorder"}bs(){var e,t=this._instance.get_property(Fl);if(!t)return!1;var n=(e=(typeof t=="object"?t:JSON.parse(t)).cache_timestamp)!==null&&e!==void 0?e:Date.now();return 36e5>=Date.now()-n}ds(e){var t,n;if((t=ne.__PosthogExtensions__)==null||!t.initSessionRecording)return Nr.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({$sdk_debug_recording_script_not_loaded:!0});if(this.os||(this.os=(n=ne.__PosthogExtensions__)==null?void 0:n.initSessionRecording(this._instance),this.os._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.bs())return this.ls===Ul||this.ls===To?void 0:(this.ls=To,Nr.info("persisted remote config is stale, requesting fresh config before starting"),void new mk(this._instance).load());this.ls=hy,this.os.start(e)}onRRwebEmit(e){var t;(t=this.os)==null||t.onRRwebEmit==null||t.onRRwebEmit(e)}overrideLinkedFlag(){var e,t;this.os||(t=this.Xi)==null||t.register({$replay_override_linked_flag:!0}),(e=this.os)==null||e.overrideLinkedFlag()}overrideSampling(){var e,t;this.os||(t=this.Xi)==null||t.register({$replay_override_sampling:!0}),(e=this.os)==null||e.overrideSampling()}overrideTrigger(e){var t,n;this.os||(n=this.Xi)==null||n.register({[e==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(t=this.os)==null||t.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.os)==null?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,t){var n;return!((n=this.os)==null||!n.tryAddCustomEvent(e,t))}}},ET={autocapture:class{constructor(e){this.ws=!1,this._s=null,this.Is=!1,this.instance=e,this.rageclicks=new ay(e.config.rageclick),this.Cs=null}initialize(){this.startIfEnabled()}get Rt(){var e,t,n=rt(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(e=n.url_allowlist)==null?void 0:e.map(r=>new RegExp(r)),n.url_ignorelist=(t=n.url_ignorelist)==null?void 0:t.map(r=>new RegExp(r)),n}Ss(){if(this.isBrowserSupported()){if(I&&X){var e=n=>{n=n||(I==null?void 0:I.event);try{this.ks(n)}catch(r){ly.error("Failed to capture event",r)}};if(Ze(X,"submit",e,{capture:!0}),Ze(X,"change",e,{capture:!0}),Ze(X,"click",e,{capture:!0}),this.Rt.capture_copied_text){var t=n=>{this.ks(n=n||(I==null?void 0:I.event),lh)};Ze(X,"copy",t,{capture:!0}),Ze(X,"cut",t,{capture:!0})}}}else ly.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.ws&&(this.Ss(),this.ws=!0)}onRemoteConfig(e){e.elementsChainAsString&&(this.Is=e.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[Sv]:!!e.autocapture_opt_out}),this._s=!!e.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(e){this.Cs=e}getElementSelectors(e){var t,n=[];return(t=this.Cs)==null||t.forEach(r=>{var i=X==null?void 0:X.querySelectorAll(r);i==null||i.forEach(s=>{e===s&&n.push(r)})}),n}get isEnabled(){var e,t,n=(e=this.instance.persistence)==null?void 0:e.props[Sv];if(kr(this._s)&&!Gn(n)&&!this.instance.ki())return!1;var r=(t=this._s)!==null&&t!==void 0?t:!!n;return!!this.instance.config.autocapture&&!r}ks(e,t){if(t===void 0&&(t="$autocapture"),this.isEnabled){var n,r=ty(e);Nk(r)&&(r=r.parentNode||null),t==="$autocapture"&&e.type==="click"&&e instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(e.clientX,e.clientY,e.timeStamp||new Date().getTime())&&function(d,h){if(!I||vp(d))return!1;var p,g,m;if(Gn(h)?(p=!!h&&ry,g=void 0):(p=(m=h==null?void 0:h.css_selector_ignorelist)!==null&&m!==void 0?m:ry,g=h==null?void 0:h.content_ignorelist),p===!1)return!1;var{targetElementList:y}=iy(d,!1);return!function(x,v){if(x===!1||J(x))return!1;var _;if(x===!0)_=lT;else{if(!_e(x))return!1;if(x.length>10)return K.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;_=x.map(k=>k.toLowerCase())}return v.some(k=>{var{safeText:w,ariaLabel:b}=k;return _.some(S=>w.includes(S)||b.includes(S))})}(g,y.map(x=>{var v;return{safeText:Ya(x).toLowerCase(),ariaLabel:((v=x.getAttribute("aria-label"))==null?void 0:v.toLowerCase().trim())||""}}))&&!ny(y,p)}(r,this.instance.config.rageclick)&&this.ks(e,"$rageclick");var i=t===lh;if(r&&function(d,h,p,g,m){var y,x,v,_;if(p===void 0&&(p=void 0),!I||vp(d)||(y=p)!=null&&y.url_allowlist&&!ey(p.url_allowlist)||(x=p)!=null&&x.url_ignorelist&&ey(p.url_ignorelist))return!1;if((v=p)!=null&&v.dom_event_allowlist){var k=p.dom_event_allowlist;if(k&&!k.some(j=>h.type===j))return!1}var{parentIsUsefulElement:w,targetElementList:b}=iy(d,g);if(!function(j,E){var R=E==null?void 0:E.element_allowlist;if(J(R))return!0;var A,L=function($){if(R.some(Y=>$.tagName.toLowerCase()===Y))return{v:!0}};for(var U of j)if(A=L(U))return A.v;return!1}(b,p)||!ny(b,(_=p)==null?void 0:_.css_selector_allowlist))return!1;var S=I.getComputedStyle(d);if(S&&S.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0;var P=d.tagName.toLowerCase();switch(P){case"html":return!1;case"form":return(m||["submit"]).indexOf(h.type)>=0;case"input":case"select":case"textarea":return(m||["change","click"]).indexOf(h.type)>=0;default:return w?(m||["click"]).indexOf(h.type)>=0:(m||["click"]).indexOf(h.type)>=0&&(hm.indexOf(P)>-1||d.getAttribute("contenteditable")==="true")}}(r,e,this.Rt,i,i?["copy","cut"]:void 0)){var{props:s,explicitNoCapture:o}=gT(r,{e,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Rt.element_attribute_ignorelist,elementsChainAsString:this.Is});if(o)return!1;var a=this.getElementSelectors(r);if(a&&a.length>0&&(s.$element_selectors=a),t===lh){var l,u=Tk(I==null||(l=I.getSelection())==null?void 0:l.toString()),c=e.type||"clipboard";if(!u)return!1;s.$selected_content=u,s.$copy_type=c}return this.instance.capture(t,s),!0}}}isBrowserSupported(){return ur(X==null?void 0:X.querySelectorAll)}},historyAutocapture:class{constructor(e){var t;this._instance=e,this.xs=(I==null||(t=I.location)==null?void 0:t.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(K.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.Ts&&this.Ts(),this.Ts=void 0,K.info("History API monitoring stopped")}monitorHistoryChanges(){var e,t;if(I&&I.history){var n=this;(e=I.history.pushState)!=null&&e.__posthog_wrapped__||uy(I.history,"pushState",r=>function(i,s,o){r.call(this,i,s,o),n.As("pushState")}),(t=I.history.replaceState)!=null&&t.__posthog_wrapped__||uy(I.history,"replaceState",r=>function(i,s,o){r.call(this,i,s,o),n.As("replaceState")}),this.Es()}}As(e){try{var t,n=I==null||(t=I.location)==null?void 0:t.pathname;if(!n)return;n!==this.xs&&this.isEnabled&&this._instance.capture(ds,{navigation_type:e}),this.xs=n}catch(r){K.error("Error capturing "+e+" pageview",r)}}Es(){if(!this.Ts){var e=()=>{this.As("popstate")};Ze(I,"popstate",e),this.Ts=()=>{I&&I.removeEventListener("popstate",e)}}}},heatmaps:class{get Rt(){return this.instance.config}constructor(e){var t;this.Rs=!1,this.ws=!1,this.Ns=null,this.instance=e,this.Rs=!((t=this.instance.persistence)==null||!t.props[Zf]),this.rageclicks=new ay(e.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var e=5e3;return rt(this.Rt.capture_heatmaps)&&this.Rt.capture_heatmaps.flush_interval_milliseconds&&(e=this.Rt.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return ge(this.Rt.capture_heatmaps)?ge(this.Rt.enable_heatmaps)?this.Rs:this.Rt.enable_heatmaps:this.Rt.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.ws)return;xT.info("starting..."),this.Ms(),this.Tt()}else{var e;clearInterval((e=this.Ns)!==null&&e!==void 0?e:void 0),this.Fs(),this.getAndClearBuffer()}}onRemoteConfig(e){if("heatmaps"in e){var t=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Zf]:t}),this.Rs=t,this.startIfEnabled()}}getAndClearBuffer(){var e=this.T;return this.T=void 0,e}Os(e){this.wt(e.originalEvent,"deadclick")}Tt(){this.Ns&&clearInterval(this.Ns),this.Ns=(X==null?void 0:X.visibilityState)==="visible"?setInterval(this.ji.bind(this),this.flushIntervalMilliseconds):null}Ms(){I&&X&&(this.Ps=this.ji.bind(this),Ze(I,xc,this.Ps),this.Ls=e=>this.wt(e||(I==null?void 0:I.event)),Ze(X,"click",this.Ls,{capture:!0}),this.Ds=e=>this.Bs(e||(I==null?void 0:I.event)),Ze(X,"mousemove",this.Ds,{capture:!0}),this.js=new Av(this.instance,Mj,this.Os.bind(this)),this.js.startIfEnabledOrStop(),this.qs=this.Tt.bind(this),Ze(X,mc,this.qs),this.ws=!0)}Fs(){var e;I&&X&&(this.Ps&&I.removeEventListener(xc,this.Ps),this.Ls&&X.removeEventListener("click",this.Ls,{capture:!0}),this.Ds&&X.removeEventListener("mousemove",this.Ds,{capture:!0}),this.qs&&X.removeEventListener(mc,this.qs),clearTimeout(this.Zs),(e=this.js)==null||e.stop(),this.ws=!1)}$s(e,t){var n=this.instance.scrollManager.scrollY(),r=this.instance.scrollManager.scrollX(),i=this.instance.scrollManager.scrollElement(),s=function(o,a,l){for(var u=o;u&&id(u)&&!ti(u,"body");){if(u===l)return!1;if(de(a,I==null?void 0:I.getComputedStyle(u).position))return!0;u=Mk(u)}return!1}(ty(e),["fixed","sticky"],i);return{x:e.clientX+(s?0:r),y:e.clientY+(s?0:n),target_fixed:s,type:t}}wt(e,t){var n;if(t===void 0&&(t="click"),!Zv(e.target)&&fy(e)){var r=this.$s(e,t);(n=this.rageclicks)!=null&&n.isRageClick(e.clientX,e.clientY,new Date().getTime())&&this.Vs(W({},r,{type:"rageclick"})),this.Vs(r)}}Bs(e){!Zv(e.target)&&fy(e)&&(clearTimeout(this.Zs),this.Zs=setTimeout(()=>{this.Vs(this.$s(e,"mousemove"))},500))}Vs(e){if(I){var t=I.location.href,n=this.Rt.custom_personal_data_properties,r=this.Rt.mask_personal_data_properties?[...Js,...n||[]]:[],i=qa(t,r,Ga);this.T=this.T||{},this.T[i]||(this.T[i]=[]),this.T[i].push(e)}}ji(){this.T&&!Ps(this.T)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Av,webVitalsAutocapture:class{constructor(e){var t;this.Rs=!1,this.ws=!1,this.T={url:void 0,metrics:[],firstMetricTimestamp:void 0},this.Hs=()=>{clearTimeout(this.zs),this.T.metrics.length!==0&&(this._instance.capture("$web_vitals",this.T.metrics.reduce((n,r)=>W({},n,{["$web_vitals_"+r.name+"_event"]:W({},r),["$web_vitals_"+r.name+"_value"]:r.value}),{})),this.T={url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.nt=n=>{var r,i=(r=this._instance.sessionManager)==null?void 0:r.checkAndGetSessionAndWindowId(!0);if(J(i))Pr.error("Could not read session ID. Dropping metrics!");else{this.T=this.T||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var s=this.Us();J(s)||(ge(n==null?void 0:n.name)||ge(n==null?void 0:n.value)?Pr.error("Invalid metric received",n):!this.Ys||this.Ys>n.value?(this.T.url!==s&&(this.Hs(),this.zs=setTimeout(this.Hs,this.flushToCaptureTimeoutMs)),J(this.T.url)&&(this.T.url=s),this.T.firstMetricTimestamp=J(this.T.firstMetricTimestamp)?Date.now():this.T.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0),this.T.metrics.push(W({},n,{$current_url:s,$session_id:i.sessionId,$window_id:i.windowId,timestamp:Date.now()})),this.T.metrics.length===this.allowedMetrics.length&&this.Hs()):Pr.error("Ignoring metric with value >= "+this.Ys,n))}},this.Ws=()=>{if(!this.ws){var n,r,i,s,o=ne.__PosthogExtensions__;J(o)||J(o.postHogWebVitalsCallbacks)||({onLCP:n,onCLS:r,onFCP:i,onINP:s}=o.postHogWebVitalsCallbacks),n&&r&&i&&s?(this.allowedMetrics.indexOf("LCP")>-1&&n(this.nt.bind(this)),this.allowedMetrics.indexOf("CLS")>-1&&r(this.nt.bind(this)),this.allowedMetrics.indexOf("FCP")>-1&&i(this.nt.bind(this)),this.allowedMetrics.indexOf("INP")>-1&&s(this.nt.bind(this)),this.ws=!0):Pr.error("web vitals callbacks not loaded - not starting")}},this._instance=e,this.Rs=!((t=this._instance.persistence)==null||!t.props[Pv]),this.startIfEnabled()}get Gs(){return this._instance.config.capture_performance}get allowedMetrics(){var e,t,n=rt(this.Gs)?(e=this.Gs)==null?void 0:e.web_vitals_allowed_metrics:void 0;return ge(n)?((t=this._instance.persistence)==null?void 0:t.props[jv])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(rt(this.Gs)?this.Gs.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var e=rt(this.Gs)?this.Gs.web_vitals_attribution:void 0;return e!=null&&e}get Ys(){var e=rt(this.Gs)&&On(this.Gs.__web_vitals_max_value)?this.Gs.__web_vitals_max_value:cy;return e>0&&6e4>=e?cy:e}get isEnabled(){var e=ht==null?void 0:ht.protocol;if(e!=="http:"&&e!=="https:")return Pr.info("Web Vitals are disabled on non-http/https protocols"),!1;var t=rt(this.Gs)?this.Gs.web_vitals:Gn(this.Gs)?this.Gs:void 0;return Gn(t)?t:this.Rs}startIfEnabled(){this.isEnabled&&!this.ws&&(Pr.info("enabled, starting..."),this.ni(this.Ws))}onRemoteConfig(e){if("capturePerformance"in e){var t=rt(e.capturePerformance)&&!!e.capturePerformance.web_vitals,n=rt(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Pv]:t}),this._instance.persistence.register({[jv]:n})),this.Rs=t,this.startIfEnabled()}}ni(e){var t,n;(t=ne.__PosthogExtensions__)!=null&&t.postHogWebVitalsCallbacks?e():(n=ne.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,this.useAttribution?"web-vitals-with-attribution":"web-vitals",r=>{r?Pr.error("failed to load script",r):e()})}Us(){var e=I?I.location.href:void 0;if(e){var t=this._instance.config.custom_personal_data_properties,n=this._instance.config.mask_personal_data_properties?[...Js,...t||[]]:[];return qa(e,n,Ga)}Pr.error("Could not determine current URL")}}},PT={exceptionObserver:class{constructor(e){var t,n,r;this.Ws=()=>{var i;if(I&&this.isEnabled&&(i=ne.__PosthogExtensions__)!=null&&i.errorWrappingFunctions){var s=ne.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,o=ne.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,a=ne.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Xs&&this.Rt.capture_unhandled_errors&&(this.Xs=s(this.captureException.bind(this))),!this.Js&&this.Rt.capture_unhandled_rejections&&(this.Js=o(this.captureException.bind(this))),!this.Ks&&this.Rt.capture_console_errors&&(this.Ks=a(this.captureException.bind(this)))}catch(l){jo.error("failed to start",l),this.Qs()}}},this._instance=e,this.eo=!((t=this._instance.persistence)==null||!t.props[Cv]),this.io=new VN({refillRate:(n=this._instance.config.error_tracking.__exceptionRateLimiterRefillRate)!==null&&n!==void 0?n:1,bucketSize:(r=this._instance.config.error_tracking.__exceptionRateLimiterBucketSize)!==null&&r!==void 0?r:10,refillInterval:1e4,qt:jo}),this.Rt=this.ro(),this.startIfEnabledOrStop()}ro(){var e=this._instance.config.capture_exceptions,t={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return rt(e)?t=W({},t,e):(J(e)?this.eo:e)&&(t=W({},t,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),t}get isEnabled(){return this.Rt.capture_console_errors||this.Rt.capture_unhandled_errors||this.Rt.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(jo.info("enabled"),this.Qs(),this.ni(this.Ws)):this.Qs()}ni(e){var t,n;(t=ne.__PosthogExtensions__)!=null&&t.errorWrappingFunctions&&e(),(n=ne.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",r=>{if(r)return jo.error("failed to load script",r);e()})}Qs(){var e,t,n;(e=this.Xs)==null||e.call(this),this.Xs=void 0,(t=this.Js)==null||t.call(this),this.Js=void 0,(n=this.Ks)==null||n.call(this),this.Ks=void 0}onRemoteConfig(e){"autocaptureExceptions"in e&&(this.eo=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[Cv]:this.eo}),this.Rt=this.ro(),this.startIfEnabledOrStop())}onConfigChange(){this.Rt=this.ro()}captureException(e){var t,n,r,i=(t=e==null||(n=e.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&t!==void 0?t:"Exception";this.io.consumeRateLimit(i)?jo.info("Skipping exception capture because of client rate limiting.",{exception:i}):(r=this._instance.exceptions)==null||r.sendExceptionEvent(e)}},exceptions:class{constructor(e){var t,n;this.no=[],this.so=new tj([new uj,new vj,new dj,new cj,new mj,new gj,new fj,new xj],function(r){for(var i=arguments.length,s=new Array(i>1?i-1:0),o=1;i>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(`
68
- `),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var p=kv.test(h)?h.replace(kv,"$1"):h;if(!p.match(/\S*Error: /)){for(var g of s){var m=g(p,r);if(m){u.push(m);break}}if(u.length>=50)break}}}return function(y){if(!y.length)return[];var x=Array.from(y);return x.reverse(),x.slice(0,50).map(v=>{return W({},v,{filename:v.filename||(_=x,_[_.length-1]||{}).filename,function:v.function||Ks});var _})}(u)}}("web:javascript",sj,lj)),this._instance=e,this.no=(t=(n=this._instance.persistence)==null?void 0:n.get_property(ep))!==null&&t!==void 0?t:[]}onRemoteConfig(e){var t,n,r;if("errorTracking"in e){var i=(t=(n=e.errorTracking)==null?void 0:n.suppressionRules)!==null&&t!==void 0?t:[],s=(r=e.errorTracking)==null?void 0:r.captureExtensionExceptions;this.no=i,this._instance.persistence&&this._instance.persistence.register({[ep]:this.no,[Ev]:s})}}get oo(){var e,t=!!this._instance.get_property(Ev),n=this._instance.config.error_tracking.captureExtensionExceptions;return(e=n??t)!==null&&e!==void 0&&e}buildProperties(e,t){return this.so.buildFromUnknown(e,{syntheticException:t==null?void 0:t.syntheticException,mechanism:{handled:t==null?void 0:t.handled}})}sendExceptionEvent(e){var t=e.$exception_list;if(this.ao(t)){if(this.lo(t))return void ph.info("Skipping exception capture because a suppression rule matched");if(!this.oo&&this.uo(t))return void ph.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ho(t))return void ph.info("Skipping exception capture because it was thrown by the PostHog SDK")}return this._instance.capture("$exception",e,{_noTruncate:!0,_batchKey:"exceptionEvent",zr:!0})}lo(e){if(e.length===0)return!1;var t=e.reduce((n,r)=>{var{type:i,value:s}=r;return et(i)&&i.length>0&&n.$exception_types.push(i),et(s)&&s.length>0&&n.$exception_values.push(s),n},{$exception_types:[],$exception_values:[]});return this.no.some(n=>{var r=n.values.map(i=>{var s,o=Sk[i.operator],a=_e(i.value)?i.value:[i.value],l=(s=t[i.key])!==null&&s!==void 0?s:[];return a.length>0&&o(a,l)});return n.type==="OR"?r.some(Boolean):r.every(Boolean)})}uo(e){return e.flatMap(t=>{var n,r;return(n=(r=t.stacktrace)==null?void 0:r.frames)!==null&&n!==void 0?n:[]}).some(t=>t.filename&&t.filename.startsWith("chrome-extension://"))}ho(e){if(e.length>0){var t,n,r,i,s=(t=(n=e[0].stacktrace)==null?void 0:n.frames)!==null&&t!==void 0?t:[],o=s[s.length-1];return(r=o==null||(i=o.filename)==null?void 0:i.includes("posthog.com/static"))!==null&&r!==void 0&&r}return!1}ao(e){return!ge(e)&&_e(e)}}},NT=W({productTours:class{get Xi(){return this._instance.persistence}constructor(e){this.co=null,this.do=null,this._instance=e}initialize(){this.loadIfEnabled()}onRemoteConfig(e){"productTours"in e&&(this.Xi&&this.Xi.register({[Nv]:!!e.productTours}),this.loadIfEnabled())}loadIfEnabled(){var e,t;this.co||(e=this._instance).config.disable_product_tours||(t=e.persistence)==null||!t.get_property(Nv)||this.ni(()=>this.vo())}ni(e){var t,n;(t=ne.__PosthogExtensions__)!=null&&t.generateProductTours?e():(n=ne.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",r=>{r?py.error("Could not load product tours script",r):e()})}vo(){var e;!this.co&&(e=ne.__PosthogExtensions__)!=null&&e.generateProductTours&&(this.co=ne.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,t){if(t===void 0&&(t=!1),!_e(this.do)||t){var n=this.Xi;if(n){var r=n.props[ch];if(_e(r)&&!t)return this.do=r,void e(r,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",callback:i=>{var s=i.statusCode;if(s!==200||!i.json){var o="Product Tours API could not be loaded, status: "+s;return py.error(o),void e([],{isLoaded:!1,error:o})}var a=_e(i.json.product_tours)?i.json.product_tours:[];this.do=a,n&&n.register({[ch]:a}),e(a,{isLoaded:!0})}})}else e(this.do,{isLoaded:!0})}getActiveProductTours(e){ge(this.co)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this.co.getActiveProductTours(e)}showProductTour(e){var t;(t=this.co)==null||t.showTourById(e)}previewTour(e){this.co?this.co.previewTour(e):this.ni(()=>{var t;this.vo(),(t=this.co)==null||t.previewTour(e)})}dismissProductTour(){var e;(e=this.co)==null||e.dismissTour("user_clicked_skip")}nextStep(){var e;(e=this.co)==null||e.nextStep()}previousStep(){var e;(e=this.co)==null||e.previousStep()}clearCache(){var e;this.do=null,(e=this.Xi)==null||e.unregister(ch)}resetTour(e){var t;(t=this.co)==null||t.resetTour(e)}resetAllTours(){var e;(e=this.co)==null||e.resetAllTours()}cancelPendingTour(e){var t;(t=this.co)==null||t.cancelPendingTour(e)}}},sd),jT={siteApps:class{constructor(e){this._instance=e,this.fo=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}po(e,t){if(t){var n=this.globalsForEvent(t);this.fo.push(n),this.fo.length>1e3&&(this.fo=this.fo.slice(10))}}get siteAppLoaders(){var e;return(e=ne._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.siteApps}initialize(){if(this.isEnabled){var e=this._instance._addCaptureHook(this.po.bind(this));this.mo=()=>{e(),this.fo=[],this.mo=void 0}}}globalsForEvent(e){var t,n,r,i,s,o,a;if(!e)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var[d,h]of Object.entries(c))l[d]={id:u[d],type:d,properties:h};var{$set_once:p,$set:g}=e;return{event:W({},Mw(e,vT),{properties:W({},e.properties,g?{$set:W({},(t=(n=e.properties)==null?void 0:n.$set)!==null&&t!==void 0?t:{},g)}:{},p?{$set_once:W({},(r=(i=e.properties)==null?void 0:i.$set_once)!==null&&r!==void 0?r:{},p)}:{}),elements_chain:(s=(o=e.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=e.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}setupSiteApp(e){var t=this.apps[e.id],n=()=>{var o;!t.errored&&this.fo.length&&(jr.info("Processing "+this.fo.length+" events for site app with id "+e.id),this.fo.forEach(a=>t.processEvent==null?void 0:t.processEvent(a)),t.processedBuffer=!0),Object.values(this.apps).every(a=>a.processedBuffer||a.errored)&&((o=this.mo)==null||o.call(this))},r=!1,i=o=>{t.errored=!o,t.loaded=!0,jr.info("Site app with id "+e.id+" "+(o?"loaded":"errored")),r&&n()};try{var{processEvent:s}=e.init({posthog:this._instance,callback(o){i(o)}});s&&(t.processEvent=s),r=!0}catch(o){jr.error(gy+e.id,o),i(!1)}if(r&&t.loaded)try{n()}catch(o){jr.error("Error while processing buffered events PostHog app with config id "+e.id,o),t.errored=!0}}yo(){var e=this.siteAppLoaders||[];for(var t of e)this.apps[t.id]={id:t.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of e)this.setupSiteApp(n)}bo(e){if(Object.keys(this.apps).length!==0){var t=this.globalsForEvent(e);for(var n of Object.values(this.apps))try{n.processEvent==null||n.processEvent(t)}catch(r){jr.error("Error while processing event "+e.event+" for site app "+n.id,r)}}}onRemoteConfig(e){var t,n,r,i=this;if((t=this.siteAppLoaders)!=null&&t.length)return this.isEnabled?(this.yo(),void this._instance.on("eventCaptured",l=>this.bo(l))):void jr.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.mo)==null||n.call(this),(r=e.siteApps)!=null&&r.length)if(this.isEnabled){var s=function(l){var u;ne["__$$ph_site_app_"+l]=i._instance,(u=ne.__PosthogExtensions__)==null||u.loadSiteApp==null||u.loadSiteApp(i._instance,a,c=>{if(c)return jr.error(gy+l,c)})};for(var{id:o,url:a}of e.siteApps)s(o)}else jr.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}},TT={tracingHeaders:class{constructor(e){this.wo=void 0,this._o=void 0,this.Ws=()=>{var t,n;J(this.wo)&&((t=ne.__PosthogExtensions__)==null||(t=t.tracingHeadersPatchFns)==null||t._patchXHR(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager)),J(this._o)&&((n=ne.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null||n._patchFetch(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager))},this._instance=e}initialize(){this.startIfEnabledOrStop()}ni(e){var t,n;(t=ne.__PosthogExtensions__)!=null&&t.tracingHeadersPatchFns&&e(),(n=ne.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",r=>{if(r)return mT.error("failed to load script",r);e()})}startIfEnabledOrStop(){var e,t;this._instance.config.__add_tracing_headers?this.ni(this.Ws):((e=this.wo)==null||e.call(this),(t=this._o)==null||t.call(this),this.wo=void 0,this._o=void 0)}}},MT=W({surveys:class{get Rt(){return this._instance.config}constructor(e){this.Io=void 0,this._surveyManager=null,this.Co=!1,this.So=[],this.ko=null,this._instance=e,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(!this.Rt.disable_surveys){var t=e.surveys;if(ge(t))return Ee.warn("Flags not loaded yet. Not loading surveys.");var n=_e(t);this.Io=n?t.length>0:t,Ee.info("flags response received, isSurveysEnabled: "+this.Io),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],t=0;t<localStorage.length;t++){var n=localStorage.key(t);(n!=null&&n.startsWith(mp)||n!=null&&n.startsWith("inProgressSurvey_"))&&e.push(n)}e.forEach(r=>localStorage.removeItem(r))}loadIfEnabled(){if(!this._surveyManager)if(this.Co)Ee.info("Already initializing surveys, skipping...");else if(this.Rt.disable_surveys)Ee.info(my);else if(this.Rt.cookieless_mode&&this._instance.consent.isOptedOut())Ee.info("Not loading surveys in cookieless mode without consent.");else{var e=ne==null?void 0:ne.__PosthogExtensions__;if(e){if(!J(this.Io)||this.Rt.advanced_enable_surveys){var t=this.Io||this.Rt.advanced_enable_surveys;this.Co=!0;try{var n=e.generateSurveys;if(n)return void this.xo(n,t);var r=e.loadExternalDependency;if(!r)return void this.To(om);r(this._instance,"surveys",i=>{i||!e.generateSurveys?this.To("Could not load surveys script",i):this.xo(e.generateSurveys,t)})}catch(i){throw this.To("Error initializing surveys",i),i}finally{this.Co=!1}}}else Ee.error("PostHog Extensions not found.")}}xo(e,t){this._surveyManager=e(this._instance,t),this._surveyEventReceiver=new bT(this._instance),Ee.info("Surveys loaded successfully"),this.Ao({isLoaded:!0})}To(e,t){Ee.error(e,t),this.Ao({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.So.push(e),this._surveyManager&&this.Ao({isLoaded:!0}),()=>{this.So=this.So.filter(t=>t!==e)}}getSurveys(e,t){if(t===void 0&&(t=!1),this.Rt.disable_surveys)return Ee.info(my),e([]);var n,r=this._instance.get_property(np);if(r&&!t)return e(r,{isLoaded:!0});typeof Promise<"u"&&this.ko?this.ko.then(i=>{var{surveys:s,context:o}=i;return e(s,o)}):(typeof Promise<"u"&&(this.ko=new Promise(i=>{n=i})),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Rt.token),method:"GET",timeout:this.Rt.surveys_request_timeout_ms,callback:i=>{var s;this.ko=null;var o=i.statusCode;if(o!==200||!i.json){var a="Surveys API could not be loaded, status: "+o;Ee.error(a);var l={isLoaded:!1,error:a};return e([],l),void(n==null||n({surveys:[],context:l}))}var u,c=i.json.surveys||[],d=c.filter(p=>function(g){return!(!g.start_date||g.end_date)}(p)&&(function(g){var m;return!((m=g.conditions)==null||(m=m.events)==null||(m=m.values)==null||!m.length)}(p)||function(g){var m;return!((m=g.conditions)==null||(m=m.actions)==null||(m=m.values)==null||!m.length)}(p)));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[np]:c});var h={isLoaded:!0};e(c,h),n==null||n({surveys:c,context:h})}}))}Ao(e){for(var t of this.So)try{if(!e.isLoaded)return t([],e);this.getSurveys(t)}catch(n){Ee.error("Error in survey callback",n)}}getActiveMatchingSurveys(e,t){if(t===void 0&&(t=!1),!ge(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,t);Ee.warn("init was not called")}Eo(e){var t=null;return this.getSurveys(n=>{var r;t=(r=n.find(i=>i.id===e))!==null&&r!==void 0?r:null}),t}Ro(e){if(ge(this._surveyManager))return{eligible:!1,reason:dh};var t=typeof e=="string"?this.Eo(e):e;return t?this._surveyManager.checkSurveyEligibility(t):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(ge(this._surveyManager))return Ee.warn("init was not called"),{visible:!1,disabledReason:dh};var t=this.Ro(e);return{visible:t.eligible,disabledReason:t.reason}}canRenderSurveyAsync(e,t){return ge(this._surveyManager)?(Ee.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:dh})):new Promise(n=>{this.getSurveys(r=>{var i,s=(i=r.find(a=>a.id===e))!==null&&i!==void 0?i:null;if(s){var o=this.Ro(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})},t)})}renderSurvey(e,t,n){var r;if(ge(this._surveyManager))Ee.warn("init was not called");else{var i=typeof e=="string"?this.Eo(e):e;if(i!=null&&i.id)if(eT.includes(i.type)){var s=X==null?void 0:X.querySelector(t);if(s)return(r=i.appearance)!=null&&r.surveyPopupDelaySeconds?(Ee.info("Rendering survey "+i.id+" with delay of "+i.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout(()=>{var o,a;Ee.info("Rendering survey "+i.id+" with delay of "+((o=i.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(i,s,n),Ee.info("Survey "+i.id+" rendered")},1e3*i.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(i,s,n);Ee.warn("Survey element not found")}else Ee.warn("Surveys of type "+i.type+" cannot be rendered in the app");else Ee.warn("Survey not found")}}displaySurvey(e,t){var n;if(ge(this._surveyManager))Ee.warn("init was not called");else{var r=this.Eo(e);if(r){var i=r;if((n=r.appearance)!=null&&n.surveyPopupDelaySeconds&&t.ignoreDelay&&(i=W({},r,{appearance:W({},r.appearance,{surveyPopupDelaySeconds:0})})),t.displayType!==cp.Popover&&t.initialResponses&&Ee.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),t.ignoreConditions===!1){var s=this.canRenderSurvey(r);if(!s.visible)return void Ee.warn("Survey is not eligible to be displayed: ",s.disabledReason)}t.displayType!==cp.Inline?this._surveyManager.handlePopoverSurvey(i,t):this.renderSurvey(i,t.selector,t.properties)}else Ee.warn("Survey not found")}}cancelPendingSurvey(e){ge(this._surveyManager)?Ee.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e;(e=this._surveyManager)==null||e.handlePageUnload()}}},sd),RT={toolbar:class{constructor(e){this.instance=e}No(e){ne.ph_toolbar_state=e}Mo(){var e;return(e=ne.ph_toolbar_state)!==null&&e!==void 0?e:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(e,t,n){if(e===void 0&&(e=void 0),t===void 0&&(t=void 0),n===void 0&&(n=void 0),sk(this.instance.config)||!I||!X)return!1;e=e??I.location,n=n??I.history;try{if(!t){try{I.localStorage.setItem("test","test"),I.localStorage.removeItem("test")}catch{return!1}t=I==null?void 0:I.localStorage}var r,i=wT||bc(e.hash,"__posthog")||bc(e.hash,"state"),s=i?Mv(()=>JSON.parse(atob(decodeURIComponent(i))))||Mv(()=>JSON.parse(decodeURIComponent(i))):null;return s&&s.action==="ph_authorize"?((r=s).source="url",r&&Object.keys(r).length>0&&(s.desiredHash?e.hash=s.desiredHash:n?n.replaceState(n.state,"",e.pathname+e.search):e.hash="")):((r=JSON.parse(t.getItem(xy)||"{}")).source="localstorage",delete r.userIntent),!(!r.token||this.instance.config.token!==r.token||(this.loadToolbar(r),0))}catch{return!1}}Fo(e){var t=ne.ph_load_toolbar||ne.ph_load_editor;!ge(t)&&ur(t)?t(e,this.instance):vy.warn("No toolbar load function found")}loadToolbar(e){var t=!(X==null||!X.getElementById(ik));if(!I||t)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,r=W({token:this.instance.config.token},e,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(I.localStorage.setItem(xy,JSON.stringify(W({},r,{source:void 0}))),this.Mo()===2)this.Fo(r);else if(this.Mo()===0){var i;this.No(1),(i=ne.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"toolbar",s=>{if(s)return vy.error("[Toolbar] Failed to load",s),void this.No(0);this.No(2),this.Fo(r)}),Ze(I,"turbolinks:load",()=>{this.No(0),this.loadToolbar(r)})}return!0}Oo(e){return this.loadToolbar(e)}maybeLoadEditor(e,t,n){return e===void 0&&(e=void 0),t===void 0&&(t=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(e,t,n)}}},AT=W({experiments:vt},sd),IT={conversations:class{constructor(e){this.Po=void 0,this._conversationsManager=null,this.Lo=!1,this.Do=null,this._instance=e}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(!this._instance.config.disable_conversations){var t=e.conversations;ge(t)||(Gn(t)?this.Po=t:(this.Po=t.enabled,this.Do=t),this.loadIfEnabled())}}reset(){var e;(e=this._conversationsManager)==null||e.reset(),this._conversationsManager=null,this.Po=void 0,this.Do=null}loadIfEnabled(){if(!(this._conversationsManager||this.Lo||this._instance.config.disable_conversations||sk(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var e=ne==null?void 0:ne.__PosthogExtensions__;if(e&&!J(this.Po)&&this.Po)if(this.Do&&this.Do.token){this.Lo=!0;try{var t=e.initConversations;if(t)return this.Bo(t),void(this.Lo=!1);var n=e.loadExternalDependency;if(!n)return void this.jo(om);n(this._instance,"conversations",r=>{r||!e.initConversations?this.jo("Could not load conversations script",r):this.Bo(e.initConversations),this.Lo=!1})}catch(r){this.jo("Error initializing conversations",r),this.Lo=!1}}else cn.error("Conversations enabled but missing token in remote config.")}}Bo(e){if(this.Do)try{this._conversationsManager=e(this.Do,this._instance),cn.info("Conversations loaded successfully")}catch(t){this.jo("Error completing conversations initialization",t)}else cn.error("Cannot complete initialization: remote config is null")}jo(e,t){cn.error(e,t),this._conversationsManager=null,this.Lo=!1}show(){this._conversationsManager?this._conversationsManager.show():cn.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Po===!0&&!kr(this._conversationsManager)}isVisible(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.isVisible())!==null&&e!==void 0&&e}sendMessage(e,t,n){var r=this;return En(function*(){return r._conversationsManager?r._conversationsManager.sendMessage(e,t,n):(cn.warn(mi),null)})()}getMessages(e,t){var n=this;return En(function*(){return n._conversationsManager?n._conversationsManager.getMessages(e,t):(cn.warn(mi),null)})()}markAsRead(e){var t=this;return En(function*(){return t._conversationsManager?t._conversationsManager.markAsRead(e):(cn.warn(mi),null)})()}getTickets(e){var t=this;return En(function*(){return t._conversationsManager?t._conversationsManager.getTickets(e):(cn.warn(mi),null)})()}requestRestoreLink(e){var t=this;return En(function*(){return t._conversationsManager?t._conversationsManager.requestRestoreLink(e):(cn.warn(mi),null)})()}restoreFromToken(e){var t=this;return En(function*(){return t._conversationsManager?t._conversationsManager.restoreFromToken(e):(cn.warn(mi),null)})()}restoreFromUrlToken(){var e=this;return En(function*(){return e._conversationsManager?e._conversationsManager.restoreFromUrlToken():(cn.warn(mi),null)})()}getCurrentTicketId(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.getCurrentTicketId())!==null&&e!==void 0?e:null}getWidgetSessionId(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.getWidgetSessionId())!==null&&e!==void 0?e:null}Kr(){var e;(e=this._conversationsManager)==null||e.setIdentity()}Qr(){var e;(e=this._conversationsManager)==null||e.clearIdentity()}}},OT={logs:class{constructor(e){var t;this.qo=!1,this.Zo=!1,this.qt=We("[logs]"),this.$o=[],this.Vo=0,this.Ho=0,this.zo=!1,this._instance=e,this._instance&&(t=this._instance.config.logs)!=null&&t.captureConsoleLogs&&(this.qo=!0)}initialize(){this.loadIfEnabled()}onRemoteConfig(e){var t,n=(t=e.logs)==null?void 0:t.captureConsoleLogs;!ge(n)&&n&&(this.qo=!0,this.loadIfEnabled())}reset(){this.$o=[],this.Ni&&(clearTimeout(this.Ni),this.Ni=void 0),this.Vo=0,this.Ho=0,this.zo=!1}loadIfEnabled(){if(this.qo&&!this.Zo){var e=ne==null?void 0:ne.__PosthogExtensions__;if(e){var t=e.loadExternalDependency;t?t(this._instance,"logs",n=>{var r;n||(r=e.logs)==null||!r.initializeLogs?this.qt.error("Could not load logs script",n):(e.logs.initializeLogs(this._instance),this.Zo=!0)}):this.qt.error(om)}else this.qt.error("PostHog Extensions not found.")}}captureLog(e){var t,n,r,i,s,o;if(this._instance.is_capturing())if(e&&e.body){var a=(t=(n=this._instance.config.logs)==null?void 0:n.flushIntervalMs)!==null&&t!==void 0?t:3e3,l=(r=(i=this._instance.config.logs)==null?void 0:i.maxLogsPerInterval)!==null&&r!==void 0?r:1e3,u=Date.now();if(a>u-this.Ho||(this.Ho=u,this.Vo=0,this.zo=!1),l>this.Vo){this.Vo++;var c=function(d,h){var p=d.level||"info",{text:g,number:m}=Dk[p]||ST,y=String(Date.now())+"000000",x={};h.distinctId&&(x.posthogDistinctId=h.distinctId),h.sessionId&&(x.sessionId=h.sessionId),h.currentUrl&&(x["url.full"]=h.currentUrl),h.activeFeatureFlags&&h.activeFeatureFlags.length>0&&(x.feature_flags=h.activeFeatureFlags);var v=W({},x,d.attributes||{}),_={timeUnixNano:y,observedTimeUnixNano:y,severityNumber:m,severityText:g,body:{stringValue:d.body},attributes:Sy(v)};return d.trace_id&&(_.traceId=d.trace_id),d.span_id&&(_.spanId=d.span_id),J(d.trace_flags)||(_.flags=d.trace_flags),_}(e,this.Uo());this.$o.push({record:c}),((s=(o=this._instance.config.logs)==null?void 0:o.maxBufferSize)!==null&&s!==void 0?s:100)>this.$o.length?this.Yo():this.flushLogs()}else this.zo||(this.qt.warn("captureLog dropping logs: exceeded "+l+" logs per "+a+"ms"),this.zo=!0)}else this.qt.warn("captureLog requires a body")}get logger(){return this.Wo||(this.Wo={trace:(e,t)=>this.captureLog({body:e,level:"trace",attributes:t}),debug:(e,t)=>this.captureLog({body:e,level:"debug",attributes:t}),info:(e,t)=>this.captureLog({body:e,level:"info",attributes:t}),warn:(e,t)=>this.captureLog({body:e,level:"warn",attributes:t}),error:(e,t)=>this.captureLog({body:e,level:"error",attributes:t}),fatal:(e,t)=>this.captureLog({body:e,level:"fatal",attributes:t})}),this.Wo}flushLogs(e){if(this.Ni&&(clearTimeout(this.Ni),this.Ni=void 0),this.$o.length!==0){var t=this.$o;this.$o=[];var n=this._instance.config.logs,r=W({"service.name":(n==null?void 0:n.serviceName)||"unknown_service"},(n==null?void 0:n.environment)&&{"deployment.environment":n.environment},(n==null?void 0:n.serviceVersion)&&{"service.version":n.serviceVersion},n==null?void 0:n.resourceAttributes),i=function(o,a){return{resourceLogs:[{resource:{attributes:Sy(a)},scopeLogs:[{scope:{name:jt.LIB_NAME},logRecords:o}]}]}}(t.map(o=>o.record),r),s=this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token);this._instance.Pr({method:"POST",url:s,data:i,compression:"best-available",batchKey:"logs",transport:e})}}Yo(){var e,t;this.Ni||(this.Ni=setTimeout(()=>{this.Ni=void 0,this.flushLogs()},(e=(t=this._instance.config.logs)==null?void 0:t.flushIntervalMs)!==null&&e!==void 0?e:3e3))}Uo(){var e,t={lib:jt.LIB_NAME};if(t.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var{sessionId:n}=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0);t.sessionId=n}if(ne!=null&&(e=ne.location)!=null&&e.href&&(t.currentUrl=ne.location.href),this._instance.featureFlags){var r=this._instance.featureFlags.getFlags();r&&r.length>0&&(t.activeFeatureFlags=r)}return t}}},DT=W({},sd,CT,ET,PT,NT,jT,MT,TT,RT,AT,IT,OT);pn.__defaultExtensionClasses=W({},DT);var Cy,Fk=(Cy=fa[hs]=new pn,function(){function e(){e.done||(e.done=!0,Pk=!1,Re(fa,function(t){t._dom_loaded()}))}X!=null&&X.addEventListener?X.readyState==="complete"?e():Ze(X,"DOMContentLoaded",e,{capture:!1}):I&&K.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")}(),Cy);const LT="phc_wfkHziMastzp8Ca8aAN8am5P7Xp6iWf5oRyZzwrZiY4h";let $k=!1;function FT(){const e=LT;Fk.init(e,{api_host:"https://us.i.posthog.com",capture_pageview:!1,persistence:"localStorage"}),$k=!0}function bp(e,t){if($k)try{Fk.capture(e,t)}catch{}}function $T(){const e=Xi(),t=Ki(),n=e.pathname.includes("/chat");return f.jsxs("div",{className:"flex h-screen flex-col overflow-hidden bg-surface",children:[f.jsxs("header",{className:"flex h-11 flex-shrink-0 items-center justify-between border-b border-outline-variant/20 bg-surface-low px-3 sm:px-5",children:[f.jsxs("button",{onClick:()=>t("/dashboard"),className:"flex items-center gap-2 hover:opacity-80 transition-opacity min-w-0",children:[f.jsx("img",{src:"/granclaw-logo.png",alt:"GranClaw",className:"h-6 w-6 rounded flex-shrink-0"}),f.jsx("span",{className:"font-display font-semibold text-on-surface tracking-tight truncate",children:"GranClaw"}),f.jsxs("span",{className:"text-xs font-mono text-on-surface/60 flex-shrink-0",children:["v","0.0.1-beta.48"]})]}),f.jsxs("span",{className:"flex items-center gap-1.5 rounded-full bg-secondary-container/20 px-2 sm:px-3 py-1 text-xs font-mono text-secondary flex-shrink-0",children:[f.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-secondary animate-pulse flex-shrink-0"}),f.jsx("span",{className:"hidden sm:inline",children:"sistema "}),"en línea"]})]}),f.jsx("main",{className:`flex-1 overflow-auto min-w-0 ${n?"":"p-3 sm:p-5"}`,children:f.jsx(kN,{})})]})}const se="";async function Ey(){const e=await fetch(`${se}/agents`);if(!e.ok)throw new Error(`fetchAgents: ${e.status}`);return e.json()}async function zT(e,t,n,r,i){const s=await fetch(`${se}/agents`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:e,name:t,model:n,provider:r,...i?{workspaceDir:i}:{}})});if(!s.ok){const o=await s.json().catch(()=>({error:s.statusText}));throw new Error(o.error)}}async function BT(e){const t=await fetch(`${se}/agents/${e}`,{method:"DELETE"});if(!t.ok)throw new Error(`deleteAgent: ${t.status}`)}async function Py(e){const t=await fetch(`${se}/agents/${e}`);if(!t.ok)throw new Error(`fetchAgent: ${t.status}`);return t.json()}async function Ny(e,t="ui"){const n=await fetch(`${se}/agents/${e}/messages?channelId=${t}&sortBy=asc&limit=200`);if(!n.ok)throw new Error(`fetchMessages: ${n.status}`);return n.json()}async function HT(e){const t=await fetch(`${se}/agents/${e}/reset`,{method:"DELETE"});if(!t.ok)throw new Error(`resetAgent: ${t.status}`)}async function VT(e,t=""){const n=await fetch(`${se}/agents/${e}/files?path=${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`fetchFiles: ${n.status}`);return(await n.json()).entries}async function WT(e,t){const n=await fetch(`${se}/agents/${e}/files/read?path=${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`readFile: ${n.status}`);return(await n.json()).content}async function UT(e,t,n){const r=await fetch(`${se}/agents/${e}/files/write?path=${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:n})});if(!r.ok)throw new Error(`writeFile: ${r.status}`)}async function qT(e){const t=await fetch(`${se}/agents/${e}/secrets`);if(!t.ok)throw new Error(`fetchSecrets: ${t.status}`);return t.json()}async function wp(e,t,n){const r=await fetch(`${se}/agents/${e}/secrets`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,value:n})});if(!r.ok)throw new Error(`addSecret: ${r.status}`)}async function zk(e,t){const n=await fetch(`${se}/agents/${e}/secrets/${encodeURIComponent(t)}`,{method:"DELETE"});if(!n.ok)throw new Error(`deleteSecret: ${n.status}`)}async function GT(e,t){const r=await fetch(`${se}/agents/${e}/tasks`);if(!r.ok)throw new Error(`fetchTasks: ${r.status}`);return r.json()}async function YT(e,t){const n=await fetch(`${se}/agents/${e}/tasks/${t}`);if(!n.ok)throw new Error(`fetchTask: ${n.status}`);return n.json()}async function XT(e,t){const n=await fetch(`${se}/agents/${e}/tasks`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(`createTask: ${n.status}`);return n.json()}async function jy(e,t,n){const r=await fetch(`${se}/agents/${e}/tasks/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok)throw new Error(`updateTask: ${r.status}`);return r.json()}async function KT(e,t){const n=await fetch(`${se}/agents/${e}/tasks/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(`deleteTask: ${n.status}`)}async function JT(e,t,n){const r=await fetch(`${se}/agents/${e}/tasks/${t}/comments`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:n})});if(!r.ok)throw new Error(`addTaskComment: ${r.status}`);return r.json()}async function QT(e){const t=await fetch(`${se}/agents/${e}/browser-sessions`);if(!t.ok)throw new Error(`fetchBrowserSessions: ${t.status}`);return t.json()}async function Bk(e,t){const n=await fetch(`${se}/agents/${e}/browser-sessions/${t}`);if(!n.ok)throw new Error(`fetchBrowserSession: ${n.status}`);return n.json()}function ZT(e,t){return`${se}/agents/${e}/browser-sessions/${t}/video`}function Hk(e,t){const n=window.location;return`${n.protocol==="https:"?"wss:":"ws:"}//${n.host}/browser-live/${e}/${t}`}function eM(e){return`${se}/agents/${e}/export`}async function Ty(e,t){const n=new URL(`${se}/agents/import`,window.location.origin);t!=null&&t.id&&n.searchParams.set("id",t.id);const r=await fetch(n.toString().replace(window.location.origin,""),{method:"POST",headers:{"Content-Type":"application/zip"},body:e});if(!r.ok){const i=await r.json().catch(()=>({error:r.statusText}));throw new Error(i.error)}return r.json()}async function My(e,t){const n=await fetch(`${se}/agents/${e}/monitor/jobs/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(`killJob: ${n.status}`)}async function tM(e){const t=await fetch(`${se}/agents/${e}/monitor`);if(!t.ok)throw new Error(`fetchMonitor: ${t.status}`);return t.json()}async function nM(e,t=30){const n=await fetch(`${se}/agents/${e}/usage?days=${t}`);if(!n.ok)throw new Error(`fetchUsage: ${n.status}`);return n.json()}async function rM(e){const t=await fetch(`${se}/agents/${e}/schedules`);if(!t.ok)throw new Error(`fetchSchedules: ${t.status}`);return t.json()}async function iM(e,t,n){const r=await fetch(`${se}/agents/${e}/schedules/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok)throw new Error(`updateSchedule: ${r.status}`);return r.json()}async function sM(e,t){const n=await fetch(`${se}/agents/${e}/schedules/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(`deleteSchedule: ${n.status}`)}async function oM(e,t){const n=await fetch(`${se}/agents/${e}/schedules/${t}/trigger`,{method:"POST"});if(!n.ok)throw new Error(`triggerSchedule: ${n.status}`);return n.json()}async function aM(e,t){const n=await fetch(`${se}/agents/${e}/schedules/${t}/runs`);if(!n.ok)throw new Error(`fetchScheduleRuns: ${n.status}`);return n.json()}async function lM(e,t){const n=await fetch(`${se}/agents/${e}/messages?channelId=${encodeURIComponent(t)}&sortBy=asc&limit=200`);if(!n.ok)throw new Error(`fetchScheduleRunMessages: ${n.status}`);return n.json()}async function uM(e){const t=await fetch(`${se}/agents/${e}/workflows`);if(!t.ok)throw new Error(`fetchWorkflows: ${t.status}`);return t.json()}async function cM(e,t){const n=await fetch(`${se}/agents/${e}/workflows/${t}`);if(!n.ok)throw new Error(`fetchWorkflow: ${n.status}`);return n.json()}async function gh(e,t){const n=await fetch(`${se}/agents/${e}/workflows/${t}/runs`);if(!n.ok)throw new Error(`fetchWorkflowRuns: ${n.status}`);return n.json()}async function dM(e,t,n){const r=await fetch(`${se}/agents/${e}/workflows/${t}/runs/${n}`);if(!r.ok)throw new Error(`fetchWorkflowRun: ${r.status}`);return r.json()}async function hM(e,t){const n=await fetch(`${se}/agents/${e}/workflows/${t}/run`,{method:"POST"});if(!n.ok)throw new Error(`triggerWorkflowRun: ${n.status}`);return n.json()}async function fM(e){const t=new URLSearchParams;e!=null&&e.agentId&&t.set("agentId",e.agentId),e!=null&&e.type&&t.set("type",e.type),e!=null&&e.search&&t.set("search",e.search),(e==null?void 0:e.limit)!=null&&t.set("limit",String(e.limit)),(e==null?void 0:e.offset)!=null&&t.set("offset",String(e.offset));const n=await fetch(`${se}/logs?${t}`);if(!n.ok)throw new Error(`fetchLogs: ${n.status}`);return n.json()}async function Vk(){const e=await fetch(`${se}/settings/provider`);if(!e.ok)throw new Error("Failed to fetch provider settings");return e.json()}async function Wk(){try{const e=await fetch(`${se}/settings/app`);return e.ok?e.json():{showWorkspaceDirConfig:!0,showBraveSearchConfig:!0}}catch{return{showWorkspaceDirConfig:!0,showBraveSearchConfig:!0}}}async function Ry(e,t,n){if(!(await fetch(`${se}/settings/provider`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:e,model:t,apiKey:n})})).ok)throw new Error("Failed to save provider settings")}async function pM(e){if(!(await fetch(`${se}/settings/providers/${encodeURIComponent(e)}`,{method:"DELETE"})).ok)throw new Error("Failed to remove provider")}async function gM(){const e=await fetch(`${se}/settings/search`);return e.ok?e.json():{provider:"brave",configured:!1}}async function mM(e,t){const n=await fetch(`${se}/settings/search`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t})});if(!n.ok)throw new Error(`Failed to save search settings: ${n.status}`)}async function xM(){const e=await fetch(`${se}/settings/search`,{method:"DELETE"});if(!e.ok&&e.status!==204&&e.status!==404)throw new Error(`Failed to clear search settings: ${e.status}`)}const vM={google:[{value:"gemini-2.5-flash",label:"Gemini 2.5 Flash — fast + smart (recommended)"},{value:"gemini-2.5-pro",label:"Gemini 2.5 Pro — most capable"},{value:"gemini-2.5-flash-lite",label:"Gemini 2.5 Flash Lite — cheapest"},{value:"gemini-3-flash-preview",label:"Gemini 3 Flash — preview"},{value:"gemini-3.1-pro-preview",label:"Gemini 3.1 Pro — preview"}],openai:[{value:"gpt-4.1",label:"GPT-4.1 — recommended, 1M ctx"},{value:"gpt-4.1-mini",label:"GPT-4.1 Mini — fast, efficient"},{value:"gpt-4.1-nano",label:"GPT-4.1 Nano — cheapest"}],anthropic:[{value:"claude-sonnet-4-6",label:"Claude Sonnet 4.6 — recommended"},{value:"claude-opus-4-6",label:"Claude Opus 4.6 — most capable"},{value:"claude-haiku-4-5-20251001",label:"Claude Haiku 4.5 — fastest"}],groq:[{value:"openai/gpt-oss-120b",label:"GPT-OSS 120B — flagship, ~500 tok/s"},{value:"openai/gpt-oss-20b",label:"GPT-OSS 20B — fast, efficient"},{value:"llama-3.3-70b-versatile",label:"Llama 3.3 70B — versatile"},{value:"llama-3.1-8b-instant",label:"Llama 3.1 8B — fastest/cheapest"}],openrouter:[{value:"google/gemini-2.5-flash",label:"Gemini 2.5 Flash — best price/perf ($0.30/$2.50 /M)"},{value:"google/gemini-3-flash-preview",label:"Gemini 3 Flash — fast, 1M ctx ($0.50/$3 /M)"},{value:"google/gemini-3.1-pro-preview",label:"Gemini 3.1 Pro — frontier ($2/$12 /M)"},{value:"deepseek/deepseek-v3.2",label:"DeepSeek V3.2 — cheap output ($0.26/$0.38 /M)"},{value:"xiaomi/mimo-v2-pro",label:"MiMo V2 Pro — agentic, 1T params ($1/$3 /M)"},{value:"qwen/qwen3.6-plus",label:"Qwen 3.6 Plus — throughput leader ($0.33/$1.95 /M)"},{value:"minimax/minimax-m2.7",label:"MiniMax M2.7 — agentic ($0.30/$1.20 /M)"},{value:"x-ai/grok-4",label:"Grok 4 — reasoning, 256k ctx ($3/$15 /M)"}],freetier:[{value:"google/gemini-3-flash-preview",label:"Gemini 3 Flash — fast, 1M ctx"}]},Uk=[{value:"google",label:"Google Gemini"},{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"openrouter",label:"OpenRouter"}];function od(e){return vM[e]??[]}function kp(e){var t;return((t=od(e)[0])==null?void 0:t.value)??""}const ga="inline-flex items-center justify-center gap-2 bg-primary text-on-primary px-5 py-2.5 text-sm font-label font-semibold uppercase tracking-widest rounded shadow-sm transition-all hover:bg-surface-tint hover:shadow-md active:scale-[0.98] disabled:opacity-40 disabled:pointer-events-none",yM="inline-flex items-center justify-center gap-2 border border-outline-variant text-on-surface px-5 py-2.5 text-sm font-label font-semibold uppercase tracking-widest rounded transition-all hover:bg-surface-container hover:border-outline active:scale-[0.98] disabled:opacity-40 disabled:pointer-events-none",qk="inline-flex items-center justify-center gap-1.5 text-on-surface-variant px-2.5 py-1.5 text-xs font-label font-medium uppercase tracking-wider rounded transition-colors hover:bg-surface-container hover:text-on-surface disabled:opacity-40 disabled:pointer-events-none",_M="inline-flex items-center justify-center gap-1.5 text-error px-2.5 py-1.5 text-xs font-label font-medium uppercase tracking-wider rounded transition-colors hover:bg-error/10 disabled:opacity-40 disabled:pointer-events-none",Cu="w-full bg-surface-container-lowest text-on-surface placeholder:text-on-surface-variant border border-outline-variant rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20 transition-colors",Ay=Cu.replace("text-sm","text-sm font-mono"),Xa="bg-surface-container-lowest border border-outline-variant/40 rounded-xl shadow-callout",Fs="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-label font-medium uppercase tracking-wider",Sp=`${Fs} bg-surface-container border border-outline-variant/40 text-on-surface-variant`,Gk=`${Fs} bg-success/10 border border-success/20 text-success`,bM=`${Fs} bg-warning/10 border border-warning/20 text-warning`;function wM({agent:e,onDelete:t}){const n=Ki(),r=e.status==="active",i=e.busy===!0;return f.jsxs("div",{onClick:()=>n(`/agents/${e.id}/chat`),className:"group flex items-center gap-4 rounded-xl bg-surface-container-lowest border border-outline-variant/40 p-4 cursor-pointer transition-all hover:border-primary/40 hover:shadow-callout",children:[f.jsxs("div",{className:"flex-1 min-w-0",children:[f.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[f.jsx("span",{className:"font-headline text-lg font-bold text-on-surface",children:e.name}),i?f.jsxs("span",{"data-testid":"busy-badge",className:"inline-flex items-center gap-1 rounded-full bg-secondary/15 border border-secondary/30 px-2 py-0.5 text-[10px] font-label font-semibold uppercase tracking-wider text-secondary",children:[f.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-secondary animate-pulse"}),"busy"]}):f.jsx("span",{className:r?Gk:Sp,children:e.status})]}),f.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[f.jsx("span",{className:"font-mono text-[10px] text-primary/70",children:e.model}),f.jsxs("span",{className:"font-mono text-[10px] text-on-surface-variant/60 hidden sm:inline",children:["id: ",e.id]})]})]}),f.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[f.jsx("div",{className:"hidden sm:flex flex-wrap gap-1",children:e.allowedTools.slice(0,3).map(s=>f.jsx("span",{className:"font-mono text-[9px] text-on-surface-variant bg-surface-container rounded px-1.5 py-0.5",children:s},s))}),f.jsx("button",{onClick:s=>{s.stopPropagation(),t()},className:`${_M} sm:opacity-0 sm:group-hover:opacity-100`,children:"Eliminar"})]})]})}function kM(){const[e,t]=N.useState([]),[n,r]=N.useState(!0),[i,s]=N.useState(null),[o,a]=N.useState({showWorkspaceDirConfig:!0,showBraveSearchConfig:!0}),[l,u]=N.useState(!1),[c,d]=N.useState(""),[h,p]=N.useState(""),[g,m]=N.useState(""),[y,x]=N.useState(""),[v,_]=N.useState(""),[k,w]=N.useState(!1),[b,S]=N.useState(!1),[P,j]=N.useState(null),E=N.useRef(null);async function R(M){var z,Q;const C=(z=M.target.files)==null?void 0:z[0];if(C){S(!0),j(null);try{let T;try{T=await Ty(C)}catch(re){const le=re instanceof Error?re.message:String(re);if(le.includes("already exists")){const F=(Q=prompt(`${le}
68
+ `),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var p=kv.test(h)?h.replace(kv,"$1"):h;if(!p.match(/\S*Error: /)){for(var g of s){var m=g(p,r);if(m){u.push(m);break}}if(u.length>=50)break}}}return function(y){if(!y.length)return[];var x=Array.from(y);return x.reverse(),x.slice(0,50).map(v=>{return W({},v,{filename:v.filename||(_=x,_[_.length-1]||{}).filename,function:v.function||Ks});var _})}(u)}}("web:javascript",sj,lj)),this._instance=e,this.no=(t=(n=this._instance.persistence)==null?void 0:n.get_property(ep))!==null&&t!==void 0?t:[]}onRemoteConfig(e){var t,n,r;if("errorTracking"in e){var i=(t=(n=e.errorTracking)==null?void 0:n.suppressionRules)!==null&&t!==void 0?t:[],s=(r=e.errorTracking)==null?void 0:r.captureExtensionExceptions;this.no=i,this._instance.persistence&&this._instance.persistence.register({[ep]:this.no,[Ev]:s})}}get oo(){var e,t=!!this._instance.get_property(Ev),n=this._instance.config.error_tracking.captureExtensionExceptions;return(e=n??t)!==null&&e!==void 0&&e}buildProperties(e,t){return this.so.buildFromUnknown(e,{syntheticException:t==null?void 0:t.syntheticException,mechanism:{handled:t==null?void 0:t.handled}})}sendExceptionEvent(e){var t=e.$exception_list;if(this.ao(t)){if(this.lo(t))return void ph.info("Skipping exception capture because a suppression rule matched");if(!this.oo&&this.uo(t))return void ph.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ho(t))return void ph.info("Skipping exception capture because it was thrown by the PostHog SDK")}return this._instance.capture("$exception",e,{_noTruncate:!0,_batchKey:"exceptionEvent",zr:!0})}lo(e){if(e.length===0)return!1;var t=e.reduce((n,r)=>{var{type:i,value:s}=r;return et(i)&&i.length>0&&n.$exception_types.push(i),et(s)&&s.length>0&&n.$exception_values.push(s),n},{$exception_types:[],$exception_values:[]});return this.no.some(n=>{var r=n.values.map(i=>{var s,o=Sk[i.operator],a=_e(i.value)?i.value:[i.value],l=(s=t[i.key])!==null&&s!==void 0?s:[];return a.length>0&&o(a,l)});return n.type==="OR"?r.some(Boolean):r.every(Boolean)})}uo(e){return e.flatMap(t=>{var n,r;return(n=(r=t.stacktrace)==null?void 0:r.frames)!==null&&n!==void 0?n:[]}).some(t=>t.filename&&t.filename.startsWith("chrome-extension://"))}ho(e){if(e.length>0){var t,n,r,i,s=(t=(n=e[0].stacktrace)==null?void 0:n.frames)!==null&&t!==void 0?t:[],o=s[s.length-1];return(r=o==null||(i=o.filename)==null?void 0:i.includes("posthog.com/static"))!==null&&r!==void 0&&r}return!1}ao(e){return!ge(e)&&_e(e)}}},NT=W({productTours:class{get Xi(){return this._instance.persistence}constructor(e){this.co=null,this.do=null,this._instance=e}initialize(){this.loadIfEnabled()}onRemoteConfig(e){"productTours"in e&&(this.Xi&&this.Xi.register({[Nv]:!!e.productTours}),this.loadIfEnabled())}loadIfEnabled(){var e,t;this.co||(e=this._instance).config.disable_product_tours||(t=e.persistence)==null||!t.get_property(Nv)||this.ni(()=>this.vo())}ni(e){var t,n;(t=ne.__PosthogExtensions__)!=null&&t.generateProductTours?e():(n=ne.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",r=>{r?py.error("Could not load product tours script",r):e()})}vo(){var e;!this.co&&(e=ne.__PosthogExtensions__)!=null&&e.generateProductTours&&(this.co=ne.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,t){if(t===void 0&&(t=!1),!_e(this.do)||t){var n=this.Xi;if(n){var r=n.props[ch];if(_e(r)&&!t)return this.do=r,void e(r,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",callback:i=>{var s=i.statusCode;if(s!==200||!i.json){var o="Product Tours API could not be loaded, status: "+s;return py.error(o),void e([],{isLoaded:!1,error:o})}var a=_e(i.json.product_tours)?i.json.product_tours:[];this.do=a,n&&n.register({[ch]:a}),e(a,{isLoaded:!0})}})}else e(this.do,{isLoaded:!0})}getActiveProductTours(e){ge(this.co)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this.co.getActiveProductTours(e)}showProductTour(e){var t;(t=this.co)==null||t.showTourById(e)}previewTour(e){this.co?this.co.previewTour(e):this.ni(()=>{var t;this.vo(),(t=this.co)==null||t.previewTour(e)})}dismissProductTour(){var e;(e=this.co)==null||e.dismissTour("user_clicked_skip")}nextStep(){var e;(e=this.co)==null||e.nextStep()}previousStep(){var e;(e=this.co)==null||e.previousStep()}clearCache(){var e;this.do=null,(e=this.Xi)==null||e.unregister(ch)}resetTour(e){var t;(t=this.co)==null||t.resetTour(e)}resetAllTours(){var e;(e=this.co)==null||e.resetAllTours()}cancelPendingTour(e){var t;(t=this.co)==null||t.cancelPendingTour(e)}}},sd),jT={siteApps:class{constructor(e){this._instance=e,this.fo=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}po(e,t){if(t){var n=this.globalsForEvent(t);this.fo.push(n),this.fo.length>1e3&&(this.fo=this.fo.slice(10))}}get siteAppLoaders(){var e;return(e=ne._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.siteApps}initialize(){if(this.isEnabled){var e=this._instance._addCaptureHook(this.po.bind(this));this.mo=()=>{e(),this.fo=[],this.mo=void 0}}}globalsForEvent(e){var t,n,r,i,s,o,a;if(!e)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var[d,h]of Object.entries(c))l[d]={id:u[d],type:d,properties:h};var{$set_once:p,$set:g}=e;return{event:W({},Mw(e,vT),{properties:W({},e.properties,g?{$set:W({},(t=(n=e.properties)==null?void 0:n.$set)!==null&&t!==void 0?t:{},g)}:{},p?{$set_once:W({},(r=(i=e.properties)==null?void 0:i.$set_once)!==null&&r!==void 0?r:{},p)}:{}),elements_chain:(s=(o=e.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=e.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}setupSiteApp(e){var t=this.apps[e.id],n=()=>{var o;!t.errored&&this.fo.length&&(jr.info("Processing "+this.fo.length+" events for site app with id "+e.id),this.fo.forEach(a=>t.processEvent==null?void 0:t.processEvent(a)),t.processedBuffer=!0),Object.values(this.apps).every(a=>a.processedBuffer||a.errored)&&((o=this.mo)==null||o.call(this))},r=!1,i=o=>{t.errored=!o,t.loaded=!0,jr.info("Site app with id "+e.id+" "+(o?"loaded":"errored")),r&&n()};try{var{processEvent:s}=e.init({posthog:this._instance,callback(o){i(o)}});s&&(t.processEvent=s),r=!0}catch(o){jr.error(gy+e.id,o),i(!1)}if(r&&t.loaded)try{n()}catch(o){jr.error("Error while processing buffered events PostHog app with config id "+e.id,o),t.errored=!0}}yo(){var e=this.siteAppLoaders||[];for(var t of e)this.apps[t.id]={id:t.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of e)this.setupSiteApp(n)}bo(e){if(Object.keys(this.apps).length!==0){var t=this.globalsForEvent(e);for(var n of Object.values(this.apps))try{n.processEvent==null||n.processEvent(t)}catch(r){jr.error("Error while processing event "+e.event+" for site app "+n.id,r)}}}onRemoteConfig(e){var t,n,r,i=this;if((t=this.siteAppLoaders)!=null&&t.length)return this.isEnabled?(this.yo(),void this._instance.on("eventCaptured",l=>this.bo(l))):void jr.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.mo)==null||n.call(this),(r=e.siteApps)!=null&&r.length)if(this.isEnabled){var s=function(l){var u;ne["__$$ph_site_app_"+l]=i._instance,(u=ne.__PosthogExtensions__)==null||u.loadSiteApp==null||u.loadSiteApp(i._instance,a,c=>{if(c)return jr.error(gy+l,c)})};for(var{id:o,url:a}of e.siteApps)s(o)}else jr.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}},TT={tracingHeaders:class{constructor(e){this.wo=void 0,this._o=void 0,this.Ws=()=>{var t,n;J(this.wo)&&((t=ne.__PosthogExtensions__)==null||(t=t.tracingHeadersPatchFns)==null||t._patchXHR(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager)),J(this._o)&&((n=ne.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null||n._patchFetch(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager))},this._instance=e}initialize(){this.startIfEnabledOrStop()}ni(e){var t,n;(t=ne.__PosthogExtensions__)!=null&&t.tracingHeadersPatchFns&&e(),(n=ne.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",r=>{if(r)return mT.error("failed to load script",r);e()})}startIfEnabledOrStop(){var e,t;this._instance.config.__add_tracing_headers?this.ni(this.Ws):((e=this.wo)==null||e.call(this),(t=this._o)==null||t.call(this),this.wo=void 0,this._o=void 0)}}},MT=W({surveys:class{get Rt(){return this._instance.config}constructor(e){this.Io=void 0,this._surveyManager=null,this.Co=!1,this.So=[],this.ko=null,this._instance=e,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(!this.Rt.disable_surveys){var t=e.surveys;if(ge(t))return Ee.warn("Flags not loaded yet. Not loading surveys.");var n=_e(t);this.Io=n?t.length>0:t,Ee.info("flags response received, isSurveysEnabled: "+this.Io),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],t=0;t<localStorage.length;t++){var n=localStorage.key(t);(n!=null&&n.startsWith(mp)||n!=null&&n.startsWith("inProgressSurvey_"))&&e.push(n)}e.forEach(r=>localStorage.removeItem(r))}loadIfEnabled(){if(!this._surveyManager)if(this.Co)Ee.info("Already initializing surveys, skipping...");else if(this.Rt.disable_surveys)Ee.info(my);else if(this.Rt.cookieless_mode&&this._instance.consent.isOptedOut())Ee.info("Not loading surveys in cookieless mode without consent.");else{var e=ne==null?void 0:ne.__PosthogExtensions__;if(e){if(!J(this.Io)||this.Rt.advanced_enable_surveys){var t=this.Io||this.Rt.advanced_enable_surveys;this.Co=!0;try{var n=e.generateSurveys;if(n)return void this.xo(n,t);var r=e.loadExternalDependency;if(!r)return void this.To(om);r(this._instance,"surveys",i=>{i||!e.generateSurveys?this.To("Could not load surveys script",i):this.xo(e.generateSurveys,t)})}catch(i){throw this.To("Error initializing surveys",i),i}finally{this.Co=!1}}}else Ee.error("PostHog Extensions not found.")}}xo(e,t){this._surveyManager=e(this._instance,t),this._surveyEventReceiver=new bT(this._instance),Ee.info("Surveys loaded successfully"),this.Ao({isLoaded:!0})}To(e,t){Ee.error(e,t),this.Ao({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.So.push(e),this._surveyManager&&this.Ao({isLoaded:!0}),()=>{this.So=this.So.filter(t=>t!==e)}}getSurveys(e,t){if(t===void 0&&(t=!1),this.Rt.disable_surveys)return Ee.info(my),e([]);var n,r=this._instance.get_property(np);if(r&&!t)return e(r,{isLoaded:!0});typeof Promise<"u"&&this.ko?this.ko.then(i=>{var{surveys:s,context:o}=i;return e(s,o)}):(typeof Promise<"u"&&(this.ko=new Promise(i=>{n=i})),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Rt.token),method:"GET",timeout:this.Rt.surveys_request_timeout_ms,callback:i=>{var s;this.ko=null;var o=i.statusCode;if(o!==200||!i.json){var a="Surveys API could not be loaded, status: "+o;Ee.error(a);var l={isLoaded:!1,error:a};return e([],l),void(n==null||n({surveys:[],context:l}))}var u,c=i.json.surveys||[],d=c.filter(p=>function(g){return!(!g.start_date||g.end_date)}(p)&&(function(g){var m;return!((m=g.conditions)==null||(m=m.events)==null||(m=m.values)==null||!m.length)}(p)||function(g){var m;return!((m=g.conditions)==null||(m=m.actions)==null||(m=m.values)==null||!m.length)}(p)));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[np]:c});var h={isLoaded:!0};e(c,h),n==null||n({surveys:c,context:h})}}))}Ao(e){for(var t of this.So)try{if(!e.isLoaded)return t([],e);this.getSurveys(t)}catch(n){Ee.error("Error in survey callback",n)}}getActiveMatchingSurveys(e,t){if(t===void 0&&(t=!1),!ge(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,t);Ee.warn("init was not called")}Eo(e){var t=null;return this.getSurveys(n=>{var r;t=(r=n.find(i=>i.id===e))!==null&&r!==void 0?r:null}),t}Ro(e){if(ge(this._surveyManager))return{eligible:!1,reason:dh};var t=typeof e=="string"?this.Eo(e):e;return t?this._surveyManager.checkSurveyEligibility(t):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(ge(this._surveyManager))return Ee.warn("init was not called"),{visible:!1,disabledReason:dh};var t=this.Ro(e);return{visible:t.eligible,disabledReason:t.reason}}canRenderSurveyAsync(e,t){return ge(this._surveyManager)?(Ee.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:dh})):new Promise(n=>{this.getSurveys(r=>{var i,s=(i=r.find(a=>a.id===e))!==null&&i!==void 0?i:null;if(s){var o=this.Ro(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})},t)})}renderSurvey(e,t,n){var r;if(ge(this._surveyManager))Ee.warn("init was not called");else{var i=typeof e=="string"?this.Eo(e):e;if(i!=null&&i.id)if(eT.includes(i.type)){var s=X==null?void 0:X.querySelector(t);if(s)return(r=i.appearance)!=null&&r.surveyPopupDelaySeconds?(Ee.info("Rendering survey "+i.id+" with delay of "+i.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout(()=>{var o,a;Ee.info("Rendering survey "+i.id+" with delay of "+((o=i.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(i,s,n),Ee.info("Survey "+i.id+" rendered")},1e3*i.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(i,s,n);Ee.warn("Survey element not found")}else Ee.warn("Surveys of type "+i.type+" cannot be rendered in the app");else Ee.warn("Survey not found")}}displaySurvey(e,t){var n;if(ge(this._surveyManager))Ee.warn("init was not called");else{var r=this.Eo(e);if(r){var i=r;if((n=r.appearance)!=null&&n.surveyPopupDelaySeconds&&t.ignoreDelay&&(i=W({},r,{appearance:W({},r.appearance,{surveyPopupDelaySeconds:0})})),t.displayType!==cp.Popover&&t.initialResponses&&Ee.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),t.ignoreConditions===!1){var s=this.canRenderSurvey(r);if(!s.visible)return void Ee.warn("Survey is not eligible to be displayed: ",s.disabledReason)}t.displayType!==cp.Inline?this._surveyManager.handlePopoverSurvey(i,t):this.renderSurvey(i,t.selector,t.properties)}else Ee.warn("Survey not found")}}cancelPendingSurvey(e){ge(this._surveyManager)?Ee.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e;(e=this._surveyManager)==null||e.handlePageUnload()}}},sd),RT={toolbar:class{constructor(e){this.instance=e}No(e){ne.ph_toolbar_state=e}Mo(){var e;return(e=ne.ph_toolbar_state)!==null&&e!==void 0?e:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(e,t,n){if(e===void 0&&(e=void 0),t===void 0&&(t=void 0),n===void 0&&(n=void 0),sk(this.instance.config)||!I||!X)return!1;e=e??I.location,n=n??I.history;try{if(!t){try{I.localStorage.setItem("test","test"),I.localStorage.removeItem("test")}catch{return!1}t=I==null?void 0:I.localStorage}var r,i=wT||bc(e.hash,"__posthog")||bc(e.hash,"state"),s=i?Mv(()=>JSON.parse(atob(decodeURIComponent(i))))||Mv(()=>JSON.parse(decodeURIComponent(i))):null;return s&&s.action==="ph_authorize"?((r=s).source="url",r&&Object.keys(r).length>0&&(s.desiredHash?e.hash=s.desiredHash:n?n.replaceState(n.state,"",e.pathname+e.search):e.hash="")):((r=JSON.parse(t.getItem(xy)||"{}")).source="localstorage",delete r.userIntent),!(!r.token||this.instance.config.token!==r.token||(this.loadToolbar(r),0))}catch{return!1}}Fo(e){var t=ne.ph_load_toolbar||ne.ph_load_editor;!ge(t)&&ur(t)?t(e,this.instance):vy.warn("No toolbar load function found")}loadToolbar(e){var t=!(X==null||!X.getElementById(ik));if(!I||t)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,r=W({token:this.instance.config.token},e,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(I.localStorage.setItem(xy,JSON.stringify(W({},r,{source:void 0}))),this.Mo()===2)this.Fo(r);else if(this.Mo()===0){var i;this.No(1),(i=ne.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"toolbar",s=>{if(s)return vy.error("[Toolbar] Failed to load",s),void this.No(0);this.No(2),this.Fo(r)}),Ze(I,"turbolinks:load",()=>{this.No(0),this.loadToolbar(r)})}return!0}Oo(e){return this.loadToolbar(e)}maybeLoadEditor(e,t,n){return e===void 0&&(e=void 0),t===void 0&&(t=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(e,t,n)}}},AT=W({experiments:vt},sd),IT={conversations:class{constructor(e){this.Po=void 0,this._conversationsManager=null,this.Lo=!1,this.Do=null,this._instance=e}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(!this._instance.config.disable_conversations){var t=e.conversations;ge(t)||(Gn(t)?this.Po=t:(this.Po=t.enabled,this.Do=t),this.loadIfEnabled())}}reset(){var e;(e=this._conversationsManager)==null||e.reset(),this._conversationsManager=null,this.Po=void 0,this.Do=null}loadIfEnabled(){if(!(this._conversationsManager||this.Lo||this._instance.config.disable_conversations||sk(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var e=ne==null?void 0:ne.__PosthogExtensions__;if(e&&!J(this.Po)&&this.Po)if(this.Do&&this.Do.token){this.Lo=!0;try{var t=e.initConversations;if(t)return this.Bo(t),void(this.Lo=!1);var n=e.loadExternalDependency;if(!n)return void this.jo(om);n(this._instance,"conversations",r=>{r||!e.initConversations?this.jo("Could not load conversations script",r):this.Bo(e.initConversations),this.Lo=!1})}catch(r){this.jo("Error initializing conversations",r),this.Lo=!1}}else cn.error("Conversations enabled but missing token in remote config.")}}Bo(e){if(this.Do)try{this._conversationsManager=e(this.Do,this._instance),cn.info("Conversations loaded successfully")}catch(t){this.jo("Error completing conversations initialization",t)}else cn.error("Cannot complete initialization: remote config is null")}jo(e,t){cn.error(e,t),this._conversationsManager=null,this.Lo=!1}show(){this._conversationsManager?this._conversationsManager.show():cn.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Po===!0&&!kr(this._conversationsManager)}isVisible(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.isVisible())!==null&&e!==void 0&&e}sendMessage(e,t,n){var r=this;return En(function*(){return r._conversationsManager?r._conversationsManager.sendMessage(e,t,n):(cn.warn(mi),null)})()}getMessages(e,t){var n=this;return En(function*(){return n._conversationsManager?n._conversationsManager.getMessages(e,t):(cn.warn(mi),null)})()}markAsRead(e){var t=this;return En(function*(){return t._conversationsManager?t._conversationsManager.markAsRead(e):(cn.warn(mi),null)})()}getTickets(e){var t=this;return En(function*(){return t._conversationsManager?t._conversationsManager.getTickets(e):(cn.warn(mi),null)})()}requestRestoreLink(e){var t=this;return En(function*(){return t._conversationsManager?t._conversationsManager.requestRestoreLink(e):(cn.warn(mi),null)})()}restoreFromToken(e){var t=this;return En(function*(){return t._conversationsManager?t._conversationsManager.restoreFromToken(e):(cn.warn(mi),null)})()}restoreFromUrlToken(){var e=this;return En(function*(){return e._conversationsManager?e._conversationsManager.restoreFromUrlToken():(cn.warn(mi),null)})()}getCurrentTicketId(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.getCurrentTicketId())!==null&&e!==void 0?e:null}getWidgetSessionId(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.getWidgetSessionId())!==null&&e!==void 0?e:null}Kr(){var e;(e=this._conversationsManager)==null||e.setIdentity()}Qr(){var e;(e=this._conversationsManager)==null||e.clearIdentity()}}},OT={logs:class{constructor(e){var t;this.qo=!1,this.Zo=!1,this.qt=We("[logs]"),this.$o=[],this.Vo=0,this.Ho=0,this.zo=!1,this._instance=e,this._instance&&(t=this._instance.config.logs)!=null&&t.captureConsoleLogs&&(this.qo=!0)}initialize(){this.loadIfEnabled()}onRemoteConfig(e){var t,n=(t=e.logs)==null?void 0:t.captureConsoleLogs;!ge(n)&&n&&(this.qo=!0,this.loadIfEnabled())}reset(){this.$o=[],this.Ni&&(clearTimeout(this.Ni),this.Ni=void 0),this.Vo=0,this.Ho=0,this.zo=!1}loadIfEnabled(){if(this.qo&&!this.Zo){var e=ne==null?void 0:ne.__PosthogExtensions__;if(e){var t=e.loadExternalDependency;t?t(this._instance,"logs",n=>{var r;n||(r=e.logs)==null||!r.initializeLogs?this.qt.error("Could not load logs script",n):(e.logs.initializeLogs(this._instance),this.Zo=!0)}):this.qt.error(om)}else this.qt.error("PostHog Extensions not found.")}}captureLog(e){var t,n,r,i,s,o;if(this._instance.is_capturing())if(e&&e.body){var a=(t=(n=this._instance.config.logs)==null?void 0:n.flushIntervalMs)!==null&&t!==void 0?t:3e3,l=(r=(i=this._instance.config.logs)==null?void 0:i.maxLogsPerInterval)!==null&&r!==void 0?r:1e3,u=Date.now();if(a>u-this.Ho||(this.Ho=u,this.Vo=0,this.zo=!1),l>this.Vo){this.Vo++;var c=function(d,h){var p=d.level||"info",{text:g,number:m}=Dk[p]||ST,y=String(Date.now())+"000000",x={};h.distinctId&&(x.posthogDistinctId=h.distinctId),h.sessionId&&(x.sessionId=h.sessionId),h.currentUrl&&(x["url.full"]=h.currentUrl),h.activeFeatureFlags&&h.activeFeatureFlags.length>0&&(x.feature_flags=h.activeFeatureFlags);var v=W({},x,d.attributes||{}),_={timeUnixNano:y,observedTimeUnixNano:y,severityNumber:m,severityText:g,body:{stringValue:d.body},attributes:Sy(v)};return d.trace_id&&(_.traceId=d.trace_id),d.span_id&&(_.spanId=d.span_id),J(d.trace_flags)||(_.flags=d.trace_flags),_}(e,this.Uo());this.$o.push({record:c}),((s=(o=this._instance.config.logs)==null?void 0:o.maxBufferSize)!==null&&s!==void 0?s:100)>this.$o.length?this.Yo():this.flushLogs()}else this.zo||(this.qt.warn("captureLog dropping logs: exceeded "+l+" logs per "+a+"ms"),this.zo=!0)}else this.qt.warn("captureLog requires a body")}get logger(){return this.Wo||(this.Wo={trace:(e,t)=>this.captureLog({body:e,level:"trace",attributes:t}),debug:(e,t)=>this.captureLog({body:e,level:"debug",attributes:t}),info:(e,t)=>this.captureLog({body:e,level:"info",attributes:t}),warn:(e,t)=>this.captureLog({body:e,level:"warn",attributes:t}),error:(e,t)=>this.captureLog({body:e,level:"error",attributes:t}),fatal:(e,t)=>this.captureLog({body:e,level:"fatal",attributes:t})}),this.Wo}flushLogs(e){if(this.Ni&&(clearTimeout(this.Ni),this.Ni=void 0),this.$o.length!==0){var t=this.$o;this.$o=[];var n=this._instance.config.logs,r=W({"service.name":(n==null?void 0:n.serviceName)||"unknown_service"},(n==null?void 0:n.environment)&&{"deployment.environment":n.environment},(n==null?void 0:n.serviceVersion)&&{"service.version":n.serviceVersion},n==null?void 0:n.resourceAttributes),i=function(o,a){return{resourceLogs:[{resource:{attributes:Sy(a)},scopeLogs:[{scope:{name:jt.LIB_NAME},logRecords:o}]}]}}(t.map(o=>o.record),r),s=this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token);this._instance.Pr({method:"POST",url:s,data:i,compression:"best-available",batchKey:"logs",transport:e})}}Yo(){var e,t;this.Ni||(this.Ni=setTimeout(()=>{this.Ni=void 0,this.flushLogs()},(e=(t=this._instance.config.logs)==null?void 0:t.flushIntervalMs)!==null&&e!==void 0?e:3e3))}Uo(){var e,t={lib:jt.LIB_NAME};if(t.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var{sessionId:n}=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0);t.sessionId=n}if(ne!=null&&(e=ne.location)!=null&&e.href&&(t.currentUrl=ne.location.href),this._instance.featureFlags){var r=this._instance.featureFlags.getFlags();r&&r.length>0&&(t.activeFeatureFlags=r)}return t}}},DT=W({},sd,CT,ET,PT,NT,jT,MT,TT,RT,AT,IT,OT);pn.__defaultExtensionClasses=W({},DT);var Cy,Fk=(Cy=fa[hs]=new pn,function(){function e(){e.done||(e.done=!0,Pk=!1,Re(fa,function(t){t._dom_loaded()}))}X!=null&&X.addEventListener?X.readyState==="complete"?e():Ze(X,"DOMContentLoaded",e,{capture:!1}):I&&K.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")}(),Cy);const LT="phc_wfkHziMastzp8Ca8aAN8am5P7Xp6iWf5oRyZzwrZiY4h";let $k=!1;function FT(){const e=LT;Fk.init(e,{api_host:"https://us.i.posthog.com",capture_pageview:!1,persistence:"localStorage"}),$k=!0}function bp(e,t){if($k)try{Fk.capture(e,t)}catch{}}function $T(){const e=Xi(),t=Ki(),n=e.pathname.includes("/chat");return f.jsxs("div",{className:"flex h-screen flex-col overflow-hidden bg-surface",children:[f.jsxs("header",{className:"flex h-11 flex-shrink-0 items-center justify-between border-b border-outline-variant/20 bg-surface-low px-3 sm:px-5",children:[f.jsxs("button",{onClick:()=>t("/dashboard"),className:"flex items-center gap-2 hover:opacity-80 transition-opacity min-w-0",children:[f.jsx("img",{src:"/granclaw-logo.png",alt:"GranClaw",className:"h-6 w-6 rounded flex-shrink-0"}),f.jsx("span",{className:"font-display font-semibold text-on-surface tracking-tight truncate",children:"GranClaw"}),f.jsxs("span",{className:"text-xs font-mono text-on-surface/60 flex-shrink-0",children:["v","0.0.1-beta.49"]})]}),f.jsxs("span",{className:"flex items-center gap-1.5 rounded-full bg-secondary-container/20 px-2 sm:px-3 py-1 text-xs font-mono text-secondary flex-shrink-0",children:[f.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-secondary animate-pulse flex-shrink-0"}),f.jsx("span",{className:"hidden sm:inline",children:"sistema "}),"en línea"]})]}),f.jsx("main",{className:`flex-1 overflow-auto min-w-0 ${n?"":"p-3 sm:p-5"}`,children:f.jsx(kN,{})})]})}const se="";async function Ey(){const e=await fetch(`${se}/agents`);if(!e.ok)throw new Error(`fetchAgents: ${e.status}`);return e.json()}async function zT(e,t,n,r,i){const s=await fetch(`${se}/agents`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:e,name:t,model:n,provider:r,...i?{workspaceDir:i}:{}})});if(!s.ok){const o=await s.json().catch(()=>({error:s.statusText}));throw new Error(o.error)}}async function BT(e){const t=await fetch(`${se}/agents/${e}`,{method:"DELETE"});if(!t.ok)throw new Error(`deleteAgent: ${t.status}`)}async function Py(e){const t=await fetch(`${se}/agents/${e}`);if(!t.ok)throw new Error(`fetchAgent: ${t.status}`);return t.json()}async function Ny(e,t="ui"){const n=await fetch(`${se}/agents/${e}/messages?channelId=${t}&sortBy=asc&limit=200`);if(!n.ok)throw new Error(`fetchMessages: ${n.status}`);return n.json()}async function HT(e){const t=await fetch(`${se}/agents/${e}/reset`,{method:"DELETE"});if(!t.ok)throw new Error(`resetAgent: ${t.status}`)}async function VT(e,t=""){const n=await fetch(`${se}/agents/${e}/files?path=${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`fetchFiles: ${n.status}`);return(await n.json()).entries}async function WT(e,t){const n=await fetch(`${se}/agents/${e}/files/read?path=${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`readFile: ${n.status}`);return(await n.json()).content}async function UT(e,t,n){const r=await fetch(`${se}/agents/${e}/files/write?path=${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:n})});if(!r.ok)throw new Error(`writeFile: ${r.status}`)}async function qT(e){const t=await fetch(`${se}/agents/${e}/secrets`);if(!t.ok)throw new Error(`fetchSecrets: ${t.status}`);return t.json()}async function wp(e,t,n){const r=await fetch(`${se}/agents/${e}/secrets`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,value:n})});if(!r.ok)throw new Error(`addSecret: ${r.status}`)}async function zk(e,t){const n=await fetch(`${se}/agents/${e}/secrets/${encodeURIComponent(t)}`,{method:"DELETE"});if(!n.ok)throw new Error(`deleteSecret: ${n.status}`)}async function GT(e,t){const r=await fetch(`${se}/agents/${e}/tasks`);if(!r.ok)throw new Error(`fetchTasks: ${r.status}`);return r.json()}async function YT(e,t){const n=await fetch(`${se}/agents/${e}/tasks/${t}`);if(!n.ok)throw new Error(`fetchTask: ${n.status}`);return n.json()}async function XT(e,t){const n=await fetch(`${se}/agents/${e}/tasks`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(`createTask: ${n.status}`);return n.json()}async function jy(e,t,n){const r=await fetch(`${se}/agents/${e}/tasks/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok)throw new Error(`updateTask: ${r.status}`);return r.json()}async function KT(e,t){const n=await fetch(`${se}/agents/${e}/tasks/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(`deleteTask: ${n.status}`)}async function JT(e,t,n){const r=await fetch(`${se}/agents/${e}/tasks/${t}/comments`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:n})});if(!r.ok)throw new Error(`addTaskComment: ${r.status}`);return r.json()}async function QT(e){const t=await fetch(`${se}/agents/${e}/browser-sessions`);if(!t.ok)throw new Error(`fetchBrowserSessions: ${t.status}`);return t.json()}async function Bk(e,t){const n=await fetch(`${se}/agents/${e}/browser-sessions/${t}`);if(!n.ok)throw new Error(`fetchBrowserSession: ${n.status}`);return n.json()}function ZT(e,t){return`${se}/agents/${e}/browser-sessions/${t}/video`}function Hk(e,t){const n=window.location;return`${n.protocol==="https:"?"wss:":"ws:"}//${n.host}/browser-live/${e}/${t}`}function eM(e){return`${se}/agents/${e}/export`}async function Ty(e,t){const n=new URL(`${se}/agents/import`,window.location.origin);t!=null&&t.id&&n.searchParams.set("id",t.id);const r=await fetch(n.toString().replace(window.location.origin,""),{method:"POST",headers:{"Content-Type":"application/zip"},body:e});if(!r.ok){const i=await r.json().catch(()=>({error:r.statusText}));throw new Error(i.error)}return r.json()}async function My(e,t){const n=await fetch(`${se}/agents/${e}/monitor/jobs/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(`killJob: ${n.status}`)}async function tM(e){const t=await fetch(`${se}/agents/${e}/monitor`);if(!t.ok)throw new Error(`fetchMonitor: ${t.status}`);return t.json()}async function nM(e,t=30){const n=await fetch(`${se}/agents/${e}/usage?days=${t}`);if(!n.ok)throw new Error(`fetchUsage: ${n.status}`);return n.json()}async function rM(e){const t=await fetch(`${se}/agents/${e}/schedules`);if(!t.ok)throw new Error(`fetchSchedules: ${t.status}`);return t.json()}async function iM(e,t,n){const r=await fetch(`${se}/agents/${e}/schedules/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok)throw new Error(`updateSchedule: ${r.status}`);return r.json()}async function sM(e,t){const n=await fetch(`${se}/agents/${e}/schedules/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(`deleteSchedule: ${n.status}`)}async function oM(e,t){const n=await fetch(`${se}/agents/${e}/schedules/${t}/trigger`,{method:"POST"});if(!n.ok)throw new Error(`triggerSchedule: ${n.status}`);return n.json()}async function aM(e,t){const n=await fetch(`${se}/agents/${e}/schedules/${t}/runs`);if(!n.ok)throw new Error(`fetchScheduleRuns: ${n.status}`);return n.json()}async function lM(e,t){const n=await fetch(`${se}/agents/${e}/messages?channelId=${encodeURIComponent(t)}&sortBy=asc&limit=200`);if(!n.ok)throw new Error(`fetchScheduleRunMessages: ${n.status}`);return n.json()}async function uM(e){const t=await fetch(`${se}/agents/${e}/workflows`);if(!t.ok)throw new Error(`fetchWorkflows: ${t.status}`);return t.json()}async function cM(e,t){const n=await fetch(`${se}/agents/${e}/workflows/${t}`);if(!n.ok)throw new Error(`fetchWorkflow: ${n.status}`);return n.json()}async function gh(e,t){const n=await fetch(`${se}/agents/${e}/workflows/${t}/runs`);if(!n.ok)throw new Error(`fetchWorkflowRuns: ${n.status}`);return n.json()}async function dM(e,t,n){const r=await fetch(`${se}/agents/${e}/workflows/${t}/runs/${n}`);if(!r.ok)throw new Error(`fetchWorkflowRun: ${r.status}`);return r.json()}async function hM(e,t){const n=await fetch(`${se}/agents/${e}/workflows/${t}/run`,{method:"POST"});if(!n.ok)throw new Error(`triggerWorkflowRun: ${n.status}`);return n.json()}async function fM(e){const t=new URLSearchParams;e!=null&&e.agentId&&t.set("agentId",e.agentId),e!=null&&e.type&&t.set("type",e.type),e!=null&&e.search&&t.set("search",e.search),(e==null?void 0:e.limit)!=null&&t.set("limit",String(e.limit)),(e==null?void 0:e.offset)!=null&&t.set("offset",String(e.offset));const n=await fetch(`${se}/logs?${t}`);if(!n.ok)throw new Error(`fetchLogs: ${n.status}`);return n.json()}async function Vk(){const e=await fetch(`${se}/settings/provider`);if(!e.ok)throw new Error("Failed to fetch provider settings");return e.json()}async function Wk(){try{const e=await fetch(`${se}/settings/app`);return e.ok?e.json():{showWorkspaceDirConfig:!0,showBraveSearchConfig:!0}}catch{return{showWorkspaceDirConfig:!0,showBraveSearchConfig:!0}}}async function Ry(e,t,n){if(!(await fetch(`${se}/settings/provider`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:e,model:t,apiKey:n})})).ok)throw new Error("Failed to save provider settings")}async function pM(e){if(!(await fetch(`${se}/settings/providers/${encodeURIComponent(e)}`,{method:"DELETE"})).ok)throw new Error("Failed to remove provider")}async function gM(){const e=await fetch(`${se}/settings/search`);return e.ok?e.json():{provider:"brave",configured:!1}}async function mM(e,t){const n=await fetch(`${se}/settings/search`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t})});if(!n.ok)throw new Error(`Failed to save search settings: ${n.status}`)}async function xM(){const e=await fetch(`${se}/settings/search`,{method:"DELETE"});if(!e.ok&&e.status!==204&&e.status!==404)throw new Error(`Failed to clear search settings: ${e.status}`)}const vM={google:[{value:"gemini-2.5-flash",label:"Gemini 2.5 Flash — fast + smart (recommended)"},{value:"gemini-2.5-pro",label:"Gemini 2.5 Pro — most capable"},{value:"gemini-2.5-flash-lite",label:"Gemini 2.5 Flash Lite — cheapest"},{value:"gemini-3-flash-preview",label:"Gemini 3 Flash — preview"},{value:"gemini-3.1-pro-preview",label:"Gemini 3.1 Pro — preview"}],openai:[{value:"gpt-4.1",label:"GPT-4.1 — recommended, 1M ctx"},{value:"gpt-4.1-mini",label:"GPT-4.1 Mini — fast, efficient"},{value:"gpt-4.1-nano",label:"GPT-4.1 Nano — cheapest"}],anthropic:[{value:"claude-sonnet-4-6",label:"Claude Sonnet 4.6 — recommended"},{value:"claude-opus-4-6",label:"Claude Opus 4.6 — most capable"},{value:"claude-haiku-4-5-20251001",label:"Claude Haiku 4.5 — fastest"}],groq:[{value:"openai/gpt-oss-120b",label:"GPT-OSS 120B — flagship, ~500 tok/s"},{value:"openai/gpt-oss-20b",label:"GPT-OSS 20B — fast, efficient"},{value:"llama-3.3-70b-versatile",label:"Llama 3.3 70B — versatile"},{value:"llama-3.1-8b-instant",label:"Llama 3.1 8B — fastest/cheapest"}],openrouter:[{value:"google/gemini-2.5-flash",label:"Gemini 2.5 Flash — best price/perf ($0.30/$2.50 /M)"},{value:"google/gemini-3-flash-preview",label:"Gemini 3 Flash — fast, 1M ctx ($0.50/$3 /M)"},{value:"google/gemini-3.1-pro-preview",label:"Gemini 3.1 Pro — frontier ($2/$12 /M)"},{value:"deepseek/deepseek-v3.2",label:"DeepSeek V3.2 — cheap output ($0.26/$0.38 /M)"},{value:"xiaomi/mimo-v2-pro",label:"MiMo V2 Pro — agentic, 1T params ($1/$3 /M)"},{value:"qwen/qwen3.6-plus",label:"Qwen 3.6 Plus — throughput leader ($0.33/$1.95 /M)"},{value:"minimax/minimax-m2.7",label:"MiniMax M2.7 — agentic ($0.30/$1.20 /M)"},{value:"x-ai/grok-4",label:"Grok 4 — reasoning, 256k ctx ($3/$15 /M)"}],freetier:[{value:"google/gemini-3-flash-preview",label:"Gemini 3 Flash — fast, 1M ctx"}]},Uk=[{value:"google",label:"Google Gemini"},{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"openrouter",label:"OpenRouter"}];function od(e){return vM[e]??[]}function kp(e){var t;return((t=od(e)[0])==null?void 0:t.value)??""}const ga="inline-flex items-center justify-center gap-2 bg-primary text-on-primary px-5 py-2.5 text-sm font-label font-semibold uppercase tracking-widest rounded shadow-sm transition-all hover:bg-surface-tint hover:shadow-md active:scale-[0.98] disabled:opacity-40 disabled:pointer-events-none",yM="inline-flex items-center justify-center gap-2 border border-outline-variant text-on-surface px-5 py-2.5 text-sm font-label font-semibold uppercase tracking-widest rounded transition-all hover:bg-surface-container hover:border-outline active:scale-[0.98] disabled:opacity-40 disabled:pointer-events-none",qk="inline-flex items-center justify-center gap-1.5 text-on-surface-variant px-2.5 py-1.5 text-xs font-label font-medium uppercase tracking-wider rounded transition-colors hover:bg-surface-container hover:text-on-surface disabled:opacity-40 disabled:pointer-events-none",_M="inline-flex items-center justify-center gap-1.5 text-error px-2.5 py-1.5 text-xs font-label font-medium uppercase tracking-wider rounded transition-colors hover:bg-error/10 disabled:opacity-40 disabled:pointer-events-none",Cu="w-full bg-surface-container-lowest text-on-surface placeholder:text-on-surface-variant border border-outline-variant rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20 transition-colors",Ay=Cu.replace("text-sm","text-sm font-mono"),Xa="bg-surface-container-lowest border border-outline-variant/40 rounded-xl shadow-callout",Fs="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-label font-medium uppercase tracking-wider",Sp=`${Fs} bg-surface-container border border-outline-variant/40 text-on-surface-variant`,Gk=`${Fs} bg-success/10 border border-success/20 text-success`,bM=`${Fs} bg-warning/10 border border-warning/20 text-warning`;function wM({agent:e,onDelete:t}){const n=Ki(),r=e.status==="active",i=e.busy===!0;return f.jsxs("div",{onClick:()=>n(`/agents/${e.id}/chat`),className:"group flex items-center gap-4 rounded-xl bg-surface-container-lowest border border-outline-variant/40 p-4 cursor-pointer transition-all hover:border-primary/40 hover:shadow-callout",children:[f.jsxs("div",{className:"flex-1 min-w-0",children:[f.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[f.jsx("span",{className:"font-headline text-lg font-bold text-on-surface",children:e.name}),i?f.jsxs("span",{"data-testid":"busy-badge",className:"inline-flex items-center gap-1 rounded-full bg-secondary/15 border border-secondary/30 px-2 py-0.5 text-[10px] font-label font-semibold uppercase tracking-wider text-secondary",children:[f.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-secondary animate-pulse"}),"busy"]}):f.jsx("span",{className:r?Gk:Sp,children:e.status})]}),f.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[f.jsx("span",{className:"font-mono text-[10px] text-primary/70",children:e.model}),f.jsxs("span",{className:"font-mono text-[10px] text-on-surface-variant/60 hidden sm:inline",children:["id: ",e.id]})]})]}),f.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[f.jsx("div",{className:"hidden sm:flex flex-wrap gap-1",children:e.allowedTools.slice(0,3).map(s=>f.jsx("span",{className:"font-mono text-[9px] text-on-surface-variant bg-surface-container rounded px-1.5 py-0.5",children:s},s))}),f.jsx("button",{onClick:s=>{s.stopPropagation(),t()},className:`${_M} sm:opacity-0 sm:group-hover:opacity-100`,children:"Eliminar"})]})]})}function kM(){const[e,t]=N.useState([]),[n,r]=N.useState(!0),[i,s]=N.useState(null),[o,a]=N.useState({showWorkspaceDirConfig:!0,showBraveSearchConfig:!0}),[l,u]=N.useState(!1),[c,d]=N.useState(""),[h,p]=N.useState(""),[g,m]=N.useState(""),[y,x]=N.useState(""),[v,_]=N.useState(""),[k,w]=N.useState(!1),[b,S]=N.useState(!1),[P,j]=N.useState(null),E=N.useRef(null);async function R(M){var z,Q;const C=(z=M.target.files)==null?void 0:z[0];if(C){S(!0),j(null);try{let T;try{T=await Ty(C)}catch(re){const le=re instanceof Error?re.message:String(re);if(le.includes("already exists")){const F=(Q=prompt(`${le}
69
69
 
70
70
  Enter a new id for the imported agent:`,""))==null?void 0:Q.trim();if(!F){S(!1);return}T=await Ty(C,{id:F})}else throw re}await A(),L(`/agents/${T.id}/chat`)}catch(T){j(T instanceof Error?T.message:"Importación fallida")}finally{S(!1),E.current&&(E.current.value="")}}}const A=()=>{Promise.all([Ey(),Vk(),Wk()]).then(([M,C,z])=>{var Q;if(t(M),s(C),a(z),!g){const T=(Q=C.providers)==null?void 0:Q[0];T&&(m(T.provider),x(T.model))}}).catch(console.error).finally(()=>r(!1))};N.useEffect(()=>{A();const M=setInterval(()=>{Ey().then(t).catch(()=>{})},2e3);return()=>clearInterval(M)},[]);const L=Ki(),U=(i==null?void 0:i.providers)??[],$=g?od(g):[];function Y(M){m(M),x(kp(M))}async function Z(){if(!(!c.trim()||!h.trim())){w(!0),j(null);try{const M=c.trim();await zT(M,h.trim(),y,g||void 0,v.trim()||void 0),L(`/agents/${M}/chat`)}catch(M){j(M instanceof Error?M.message:"Error al crear"),w(!1)}}}async function O(M,C){confirm(`¿Eliminar agente "${C}" (${M})?
71
71
 
@@ -27,7 +27,7 @@
27
27
  } catch (_) { /* SSR / blocked storage — ignore */ }
28
28
  })();
29
29
  </script>
30
- <script type="module" crossorigin src="/assets/index-t5VU4wm7.js"></script>
30
+ <script type="module" crossorigin src="/assets/index-D16l6LfZ.js"></script>
31
31
  <link rel="stylesheet" crossorigin href="/assets/index-2GRZy6Sb.css">
32
32
  </head>
33
33
  <body class="bg-background text-on-surface">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "granclaw",
3
- "version": "0.0.1-beta.48",
3
+ "version": "0.0.1-beta.49",
4
4
  "description": "A personal AI assistant you run on your own machine.",
5
5
  "license": "MIT",
6
6
  "repository": {