@zenovay/cli 1.0.21 → 1.0.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/dist/{agency-DUOvPsjr.js → agency-CXn6ghSg.js} +1 -1
  2. package/dist/{ai-BCRvtUiJ.js → ai-BhP4sLv5.js} +1 -1
  3. package/dist/{alerts-BEKm2Kb-.js → alerts-DQhW7iBJ.js} +1 -1
  4. package/dist/analytical-screen-CwzTTWSN.js +2 -0
  5. package/dist/{analytics-ByGhOggY.js → analytics-B6LX4KtS.js} +2 -2
  6. package/dist/{annotation-C6fb7vkz.js → annotation-BFjhrp0W.js} +1 -1
  7. package/dist/api-BjI2Fkpj.js +1 -0
  8. package/dist/api-keys-CcYmhFAn.js +4 -0
  9. package/dist/api-v2-C08aT2tD.js +1 -0
  10. package/dist/api-v2-D4BD6BTF.js +1 -0
  11. package/dist/audit-ByQTzk4F.js +9 -0
  12. package/dist/{bar-nBOPOEQR.js → bar-DjNjvYQO.js} +1 -1
  13. package/dist/bin.js +10 -8
  14. package/dist/{chat-panel-CwOboIau.js → chat-panel-DKVM8gnJ.js} +2 -2
  15. package/dist/commands-CGCCx0-s.js +2 -0
  16. package/dist/{companies-Bhem7pPh.js → companies-DoWVWT3n.js} +1 -1
  17. package/dist/{completions-Baz_aHlL.js → completions-BQZk2_z8.js} +1 -1
  18. package/dist/csv-emit-CBCNHfG-.js +1 -0
  19. package/dist/csv-emit-D-SdR7uI.js +1 -0
  20. package/dist/{data-table-DeR2tIOP.js → data-table-Bd1OPNrr.js} +1 -1
  21. package/dist/{deploys-BtIsWSf1.js → deploys-fslHuzcI.js} +1 -1
  22. package/dist/{detect-installed-CCdJVPQv.js → detect-installed-CC80b52i.js} +1 -1
  23. package/dist/detect-installed-DpSaAeH-.js +1 -0
  24. package/dist/{devices-CVEOIi8r.js → devices-DBlXlKpl.js} +1 -1
  25. package/dist/{doctor-yFe0eRpP.js → doctor-CUcGEDQ3.js} +3 -3
  26. package/dist/{domains-CunfRyoi.js → domains-C8k_-uxF.js} +3 -3
  27. package/dist/{emit-B0sTh9z5.js → emit-5vELQfsB.js} +1 -1
  28. package/dist/{empty-state-Dfv6x-qP.js → empty-state-CwrzE-7m.js} +1 -1
  29. package/dist/{ensure-latest-B3P4wX40.js → ensure-latest-BfsWmA1w.js} +1 -1
  30. package/dist/ensure-latest-CEFXfYj4.js +5 -0
  31. package/dist/error-codes-B34VS5kE.js +1 -0
  32. package/dist/{error-codes-DrGIAUrC.js → error-codes-DBKSLU_H.js} +1 -1
  33. package/dist/{errors-1Ycg_pbc.js → errors-D0ZAKyyp.js} +1 -1
  34. package/dist/{events-tail-4uzcTSQ-.js → events-tail-ChBWUY2U.js} +1 -1
  35. package/dist/examples-Zsrvr0vP.js +1 -0
  36. package/dist/{examples-DoW9tZ3o.js → examples-wBHwEUt8.js} +1 -1
  37. package/dist/{export-BwJAwucf.js → export-BNTMuFkm.js} +1 -1
  38. package/dist/{funnel-CmCBy6sa.js → funnel-DUADVc08.js} +1 -1
  39. package/dist/{geo-Dg-but7d.js → geo-BPJo25Kz.js} +1 -1
  40. package/dist/{globe-Bas4niFl.js → globe-BihtdD3C.js} +2 -2
  41. package/dist/goals-DOrNec3J.js +7 -0
  42. package/dist/{grid-BD6OXmy5.js → grid-ClgMBAEr.js} +1 -1
  43. package/dist/health--A4ohPuM.js +1 -0
  44. package/dist/{health-Bs11dlkZ.js → health-1qT1VvMd.js} +2 -2
  45. package/dist/{heatmaps-DwUqUELX.js → heatmaps-B57AUVWd.js} +1 -1
  46. package/dist/{home-CTzxOPq2.js → home-cBUICiVc.js} +1 -1
  47. package/dist/init-DEjXba3A.js +1 -0
  48. package/dist/init-fhEg3cPZ.js +335 -0
  49. package/dist/{insights-Bbaaxoi9.js → insights-1_6dityO.js} +1 -1
  50. package/dist/{integrations-WzOxgaoO.js → integrations-DnGjzmxX.js} +1 -1
  51. package/dist/{journeys-DcjeIm6F.js → journeys-cWX23e27.js} +1 -1
  52. package/dist/{keybar-BHiS3lI4.js → keybar-BY1csJGI.js} +1 -1
  53. package/dist/live-CztLfKw_.js +1 -0
  54. package/dist/{login-CuDPS4Cd.js → login-B0HQYYBk.js} +1 -1
  55. package/dist/login-BJ5CNvdO.js +1 -0
  56. package/dist/logout-D_z-o7Df.js +4 -0
  57. package/dist/{metric-card-249MQpWf.js → metric-card-D8RL2Pev.js} +1 -1
  58. package/dist/notes-GM2yOOui.js +10 -0
  59. package/dist/{open-url-DHEOtfXN.js → open-url-IjqD5f_n.js} +1 -1
  60. package/dist/{pages-XkYcO2cd.js → pages-C2cFd2kA.js} +1 -1
  61. package/dist/{panel-Css3a3Vm.js → panel-DbiZwGB3.js} +1 -1
  62. package/dist/{plans-CyQj8W7p.js → plans-CWVJxcHz.js} +6 -6
  63. package/dist/{profile-auZaonOa.js → profile-Uqw7PTNA.js} +3 -3
  64. package/dist/{progress-row-BYWJ4T_0.js → progress-row-BSv_Zm8f.js} +1 -1
  65. package/dist/{projects-2Ra66UOH.js → projects-Bf_yPgg2.js} +1 -1
  66. package/dist/{prompt-BL4GzAMK.js → prompt-Dae2nnYJ.js} +1 -1
  67. package/dist/{query-CDXYdMQb.js → query-BRI6jsCB.js} +1 -1
  68. package/dist/{range-tabs-BpEan2yY.js → range-tabs-Dw9sc3My.js} +1 -1
  69. package/dist/{resolve-site-DQFFFm9Z.js → resolve-site-D8PIddP1.js} +1 -1
  70. package/dist/{retention-DpcRgaFr.js → retention-DiJO8tEO.js} +1 -1
  71. package/dist/{revenue-C8YvxmBq.js → revenue-BknSw-ON.js} +1 -1
  72. package/dist/secrets-D8e4AxoX.js +1 -0
  73. package/dist/{self-test-C1WfpOav.js → self-test-ZJq1IFy0.js} +3 -3
  74. package/dist/{sessions-kkwgdpgl.js → sessions-TMh968Eh.js} +1 -1
  75. package/dist/settings-BNtoRxL2.js +4 -0
  76. package/dist/share-BkAcPmBB.js +6 -0
  77. package/dist/{site-switcher-CGS1OOLY.js → site-switcher-B4-Gvl06.js} +1 -1
  78. package/dist/snippet-6eEjdvB0.js +1 -0
  79. package/dist/snippet-CwowVrmh.js +1 -0
  80. package/dist/{sources-Drq6ROo8.js → sources-Cc8KehCL.js} +1 -1
  81. package/dist/{stats-jbvWz1ZK.js → stats-CyQ30WQQ.js} +1 -1
  82. package/dist/{status-agent-CGeRBXSk.js → status-agent-CCtrc_xJ.js} +1 -1
  83. package/dist/team-BxIB_sx7.js +9 -0
  84. package/dist/{teams-CtvJZzsC.js → teams-C17B3ARm.js} +1 -1
  85. package/dist/{telemetry-BXfmSPM0.js → telemetry-CyIcWTLw.js} +1 -1
  86. package/dist/{telemetry-CX5wsUWl.js → telemetry-DIAzAYko.js} +1 -1
  87. package/dist/{themes-BuPMuJMs.js → themes-BBtRXVPz.js} +1 -1
  88. package/dist/token-store-CuZEiQNg.js +1 -0
  89. package/dist/{token-store-DY6bMFE_.js → token-store-UmKB69od.js} +1 -1
  90. package/dist/{tour-Bb7ED8Uj.js → tour-CE8jtA2L.js} +1 -1
  91. package/dist/unknown-action-Wungfmqy.js +2 -0
  92. package/dist/update-CXMG8g-D.js +1 -0
  93. package/dist/{uptime-DDH2cepm.js → uptime-Bi495745.js} +1 -1
  94. package/dist/{usage-wEiuzkc0.js → usage-ET7C0T4C.js} +1 -1
  95. package/dist/{use-BT-ej7R9.js → use-B9zOU23-.js} +1 -1
  96. package/dist/{visitors-BKZb0Ixg.js → visitors-BVZI0rsU.js} +1 -1
  97. package/dist/{vitals-BjT7vtpR.js → vitals-scWZhFJZ.js} +1 -1
  98. package/dist/webhooks-6Gab0Im6.js +10 -0
  99. package/dist/{webhooks-forward-irxiUEF3.js → webhooks-forward-CaSdkBXY.js} +1 -1
  100. package/dist/wizard-bin.js +1 -1
  101. package/package.json +2 -1
  102. package/dist/analytical-screen-D2ZDbL0D.js +0 -2
  103. package/dist/api-BU8ms-ed.js +0 -1
  104. package/dist/api-keys-9rE9HNIP.js +0 -4
  105. package/dist/api-v2-CFFds1re.js +0 -1
  106. package/dist/api-v2-Dd_z970e.js +0 -1
  107. package/dist/audit-TaFmviA1.js +0 -9
  108. package/dist/commands-DG6gq7ie.js +0 -2
  109. package/dist/csv-emit-CrghX3KQ.js +0 -1
  110. package/dist/csv-emit-MW4T5xF3.js +0 -1
  111. package/dist/detect-installed-D7dm7BtK.js +0 -1
  112. package/dist/ensure-latest-gssSkWZE.js +0 -5
  113. package/dist/error-codes-wgbAWxJ0.js +0 -1
  114. package/dist/goals-C1ezvLt4.js +0 -7
  115. package/dist/health-t65mGFyE.js +0 -1
  116. package/dist/init-BlFwCB6A.js +0 -1
  117. package/dist/init-Tiu7BLrh.js +0 -332
  118. package/dist/live-l55FqeaU.js +0 -1
  119. package/dist/login-CmqOFBin.js +0 -1
  120. package/dist/logout-CtME85nb.js +0 -2
  121. package/dist/notes-DXYCFcwk.js +0 -10
  122. package/dist/secrets-CxinAdt5.js +0 -1
  123. package/dist/settings-Ch7ztjkK.js +0 -4
  124. package/dist/share-BQ3NaiF1.js +0 -6
  125. package/dist/snippet-Cm_Lv1Oj.js +0 -1
  126. package/dist/snippet-p5qtQicp.js +0 -1
  127. package/dist/team-DmHyv4tG.js +0 -9
  128. package/dist/token-store-RBywEspd.js +0 -1
  129. package/dist/update-g1_LBM_v.js +0 -1
  130. package/dist/webhooks-BkUV1tpC.js +0 -10
  131. /package/dist/{client-AII1aQbd.js → client-DNMRt-Hq.js} +0 -0
  132. /package/dist/{confirm-DS5wux0g.js → confirm-R8wMITfX.js} +0 -0
  133. /package/dist/{fmt-DGdql3Z7.js → fmt-DKoQbgLw.js} +0 -0
  134. /package/dist/{formatter-C4QJnLxB.js → formatter-PBF-wEt1.js} +0 -0
  135. /package/dist/{keybar-deep-link-Bbky2z_r.js → keybar-deep-link-pVNTDhfX.js} +0 -0
  136. /package/dist/{secrets-BdzQxqfz.js → secrets-zGZxXoM0.js} +0 -0
  137. /package/dist/{sparkline-BICNgdIH.js → sparkline-B7VaYaxH.js} +0 -0
  138. /package/dist/{telemetry-B1hu6Mwi.js → telemetry-BgkzI2cW.js} +0 -0
  139. /package/dist/{theme-DnsyTVQs.js → theme-DSRmbn9T.js} +0 -0
  140. /package/dist/{tier-DCh08hhD.js → tier-Cz2KfGwA.js} +0 -0
  141. /package/dist/{ui-GZ-KcD3b.js → ui-aT7D3OhH.js} +0 -0
  142. /package/dist/{use-fullscreen-B9LnCYar.js → use-fullscreen-BxfNad7W.js} +0 -0
  143. /package/dist/{ws-client-DYT7tqCw.js → ws-client-BTP1c9s8.js} +0 -0
@@ -1,332 +0,0 @@
1
- import{readConfig as e,updateConfig as t}from"./config-JVhBplSX.js";import{ApiClient as n,dashboardUrlForSite as r}from"./api-BU8ms-ed.js";import{readToken as i}from"./token-store-RBywEspd.js";import{diagnoseInstall as a}from"./detect-installed-D7dm7BtK.js";import{emit$1 as o,isHeadless as s}from"./emit-B0sTh9z5.js";import{openInBrowser as c}from"./open-url-DHEOtfXN.js";import{scrubSecrets as l}from"./secrets-BdzQxqfz.js";import{parseSseStream as u}from"./client-AII1aQbd.js";import{swapToFirstPartySnippet as d}from"./snippet-p5qtQicp.js";import{loginCommand as f,maybeInstallCompletions as p}from"./login-CuDPS4Cd.js";import{Banner as m,Panel as h,useTheme as g}from"./panel-Css3a3Vm.js";import{DiffView as _,ProgressRow as v}from"./progress-row-BYWJ4T_0.js";import{Select as y}from"./prompt-BL4GzAMK.js";import{Keybar as ee}from"./keybar-BHiS3lI4.js";import{spark as b}from"./sparkline-BICNgdIH.js";import x from"node:path";import{promises as S}from"node:fs";import{z as C}from"zod";import te from"node:os";import w from"node:crypto";import{ulid as ne}from"ulid";import{Box as T,Text as E,render as D,useApp as re,useInput as O}from"ink";import k from"node:fs/promises";import A,{useEffect as j,useRef as M,useState as N}from"react";import{globby as P}from"globby";import F from"ink-spinner";import{applyPatch as ie}from"diff";const I=[/^package\.json$/,/^package-lock\.json$/,/^pnpm-lock\.yaml$/,/^yarn\.lock$/,/^bun\.lock$/,/^tsconfig.*\.json$/,/^(next|nuxt|vite|astro|remix|svelte|tailwind|postcss)\.config\.(ts|mts|cts|js|mjs|cjs)$/,/^app\/.*\.(tsx|ts|jsx|js|svelte|astro|vue)$/,/^pages\/.*\.(tsx|ts|jsx|js)$/,/^src\/app\/.*\.(tsx|ts|jsx|js)$/,/^src\/pages\/.*\.(tsx|ts|jsx|js|astro)$/,/^src\/components\/.*\.(astro|svelte|vue|tsx|ts|jsx|js)$/,/^src\/(root|app|entry-server|entry-client)\.(tsx|ts|jsx|js)$/,/^gatsby-(ssr|browser|config)\.(js|ts|mjs)$/,/\.html?$/,/^src\/main\.(tsx|ts|jsx|js)$/,/^src\/App\.(tsx|ts|jsx|js|svelte|vue)$/,/^src\/routes\/\+layout\.(svelte|ts|js)$/,/^src\/routes\/root\..*$/,/^src\/layouts\/.*\.(astro|svelte|vue)$/,/^\.env\.example$/,/^README\.md$/,/^\.gitignore$/,/^nuxt\.config\.(ts|js|mjs)$/,/^plugins\/.*\.(ts|js)$/],ae=[/(^|\/)\.env($|\.(?!example$)[^/]+$)/,/(^|\/)\.git(\/|$)/,/(^|\/)node_modules\//,/(^|\/)\.ssh\//,/(^|\/)\.aws\//,/\.pem$/,/\.key$/,/(^|\/)id_rsa($|\.)/,/(^|\/)\.npmrc$/,/(^|\/)credentials(\.|$)/],L=256*1024,oe=20,se=20,ce=20;var R=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`SandboxError`}};const z=/<script[^>]*src\s*=\s*["'](?:https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+|[^"']*\/_z\/script\.js[^"']*)["'][^>]*>\s*<\/script>/i,B=[{name:`PostHog`,re:/posthog\.com\b|posthog-js|window\.posthog/i},{name:`Plausible`,re:/plausible\.io\/js|window\.plausible/i},{name:`Google Analytics`,re:/googletagmanager\.com\/gtag\/js|google-analytics\.com\/analytics\.js|window\.gtag\b/i},{name:`Mixpanel`,re:/cdn\.mxpnl\.com|mixpanel-browser/i},{name:`Segment`,re:/cdn\.segment\.com\/analytics\.js|window\.analytics\b/i},{name:`Hotjar`,re:/static\.hotjar\.com|\(h,o,t,j,a,r\)/i},{name:`Amplitude`,re:/cdn\.amplitude\.com|amplitude\.getInstance/i},{name:`Heap`,re:/cdn\.heapanalytics\.com/i},{name:`FullStory`,re:/fullstory\.com\/s\/fs\.js|window\.FS\.identify/i}];var V=class{sessionId;cwd;cwdReal;undoRoot;readCount=0;writeCount=0;roundCount=0;writtenPathsSet=new Set;prunedOnce=!1;constructor(e){this.sessionId=e.sessionId??ne(),this.cwd=e.cwd,this.cwdReal=S.realpath(e.cwd),this.undoRoot=e.undoRoot??x.join(te.homedir(),`.zenovay`,`undo`)}incrementRound(){if(this.roundCount++,this.roundCount>ce)throw new R(`round-cap`,`Tool-call recursion cap (${ce}) exceeded.`)}stats(){return{sessionId:this.sessionId,reads:this.readCount,writes:this.writeCount,rounds:this.roundCount,writtenPaths:[...this.writtenPathsSet]}}async resolveForRead(e){return this.resolveSafe(e,`read`)}async resolveForWrite(e){return this.resolveSafe(e,`write`)}async resolveSafe(e,t){if(typeof e!=`string`||e.length===0)throw new R(`escape`,`Path must be a non-empty string.`);if(e.includes(`\0`))throw new R(`escape`,`Null byte in path.`);if(/^\\\\[?.]\\/.test(e)||/^\\\\[A-Za-z0-9]/.test(e))throw new R(`escape`,`Windows special path prefix: ${e}`);if(/%/.test(e))try{let t=decodeURIComponent(e);if(/%[0-9A-Fa-f]{2}/.test(t))throw new R(`escape`,`Double-encoded path: ${e}`);e=t}catch(t){throw t instanceof R?t:new R(`escape`,`Malformed percent-encoding: ${e}`)}if(e.includes(`\0`))throw new R(`escape`,`Null byte in decoded path.`);if(e.includes(`\\`))throw new R(`escape`,`Backslash in path (Windows-style separator not accepted): ${e}`);let n=await this.cwdReal,r=x.isAbsolute(e)?e:x.join(n,e),i=x.normalize(r),a=i;try{a=await S.realpath(i)}catch(e){if(e.code!==`ENOENT`)throw new R(`escape`,`realpath failed: ${e.message}`);let t=x.dirname(i);try{let e=await S.realpath(t);a=x.join(e,x.basename(i))}catch{}}if(!this.isWithin(a,n))throw new R(`escape`,`Path escapes cwd: ${e}`);let o=x.relative(n,a),s=o.toLowerCase();for(let e of ae)if(e.test(o)||e.test(s)){if(t===`read`&&/(^|\/)node_modules\//i.test(o))continue;throw new R(`blocklisted`,`Path is on the hard blocklist: ${o}`)}if(t===`write`){let e=I.some(e=>e.test(o));if(!e&&!/^\.env(\.local)?$/.test(o)&&!/^\.claude\//.test(o)&&!/^\.cursor\//.test(o))throw new R(`not-allowlisted`,`Write path not on allowlist: ${o}`)}return a}isWithin(e,t){let n=x.relative(t,e);return!n.startsWith(`..`)&&!x.isAbsolute(n)}async safeRead(e){if(this.readCount>=oe)throw new R(`read-cap`,`Read cap (${oe}) reached.`);let t=await this.resolveForRead(e),n=await S.stat(t);if(n.size>L)throw new R(`too-large`,`File exceeds ${L}B: ${e} (${n.size}B)`);let r=await S.readFile(t),i=r.subarray(0,Math.min(r.length,8192));if(i.includes(0))throw new R(`binary-rejected`,`Binary content in ${e}.`);return this.readCount++,r.toString(`utf8`)}async safeWrite(e,t){if(this.writeCount>=se)throw new R(`write-cap`,`Write cap (${se}) reached.`);if(t.length>L)throw new R(`too-large`,`Write exceeds ${L}B: ${e}`);let n=await this.resolveForWrite(e),r=await S.readFile(n,`utf8`).catch(e=>{if(e.code===`ENOENT`)return null;throw e});if(r!==null){if(z.test(r)&&!z.test(t))throw new R(`destructive-tracker-removal`,`Refusing to write ${e}: existing Zenovay tracker tag would be removed. If you want to change the data-id, use patch_file to swap the attribute value instead of overwriting the file.`);for(let{name:n,re:i}of B)if(i.test(r)&&!i.test(t))throw new R(`destructive-competitor-removal`,`Refusing to write ${e}: existing ${n} tracker would be removed. Zenovay installs alongside competitors — never replace them.`)}let i=await this.journalBackup(n);await S.mkdir(x.dirname(n),{recursive:!0}),await S.writeFile(n,t,`utf8`),this.writeCount++;let a=await this.cwdReal;return this.writtenPathsSet.add(x.relative(a,n)),{backupPath:i}}async journalBackup(e){let t=await S.readFile(e).catch(e=>{if(e.code===`ENOENT`)return null;throw e}),n=x.join(this.undoRoot,this.sessionId);await S.mkdir(n,{recursive:!0,mode:448}),this.prunedOnce||(this.prunedOnce=!0,ue(this.undoRoot,this.sessionId));let r=w.createHash(`sha256`).update(e).digest(`hex`).slice(0,16),i=x.join(n,`${r}.bak`),a=x.join(n,`manifest.jsonl`);t&&await S.writeFile(i,t,{mode:384});let o=JSON.stringify({abs:e,backupPath:t?i:null,ts:Date.now()});return await S.appendFile(a,o+`
2
- `,{mode:384}),t?i:null}static wrapForModel(e,t){let n=w.createHash(`sha256`).update(t).digest(`hex`).slice(0,16),r=t.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`);return`<FILE path="${e}" sha256="${n}">\n${r}\n</FILE>`}static scrubSecrets(e){return l(e)}};const le=20;async function ue(e,t,n=le){try{let r=await S.readdir(e,{withFileTypes:!0}),i=r.filter(e=>e.isDirectory()).map(e=>e.name);if(i.length<=n)return 0;let a=await Promise.all(i.map(async t=>{let n=await S.stat(x.join(e,t)).catch(()=>null);return{name:t,mtime:n?n.mtimeMs:0}}));a.sort((e,t)=>t.mtime-e.mtime);let o=a.slice(n).filter(e=>e.name!==t);return await Promise.all(o.map(t=>S.rm(x.join(e,t.name),{recursive:!0,force:!0}).catch(()=>{}))),o.length}catch{return 0}}async function de(e){let t=await e.readFile(`package.json`),n=!1;if(t)try{let e=JSON.parse(t);n=!!(e.dependencies?.[`@angular/core`]??e.devDependencies?.[`@angular/core`])}catch{}let r=await e.exists(`angular.json`)||await e.exists(`.angular-cli.json`);if(n||r){let t=await e.exists(`src/index.html`)?`src/index.html`:`index.html`;return{matched:!0,confidence:.9,reason:`Detected Angular via ${n?"`@angular/core`":"`angular.json`"} (shell: ${t}).`}}return{matched:!1,confidence:0,reason:`No Angular dependency or angular.json found.`}}function fe(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`src/index.html`,r=`<script defer\n data-id="${t}"\n src="https://api.zenovay.com/z.js">\n</script>`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Inject the Zenovay tracker inside <head> of the Angular index.html shell.`}]}const pe={id:`angular`,displayName:`Angular`,detect:de,files:[{path:`src/index.html`,kind:`mutate`,required:!0}],envVarName:`NG_ZENOVAY_SITE`,buildSnippets:fe},H=[`astro.config.ts`,`astro.config.mjs`,`astro.config.js`];async function U(e){for(let t of H)if(await e.exists(t))return{matched:!0,confidence:.95,reason:`Detected Astro via \`${t}\`.`};let t=await e.readFile(`package.json`);if(t)try{let e=JSON.parse(t);if(e.dependencies?.astro??e.devDependencies?.astro)return{matched:!0,confidence:.8,reason:"Detected Astro via `astro` dependency."}}catch{}return{matched:!1,confidence:0,reason:"No astro.config.* or `astro` dependency found."}}function me(e){let t=e.trackingCode??e.siteId??``,n=`<script defer data-id="${t}" src="https://api.zenovay.com/z.js" is:inline></script>`;return[{targetPath:`src/layouts/Layout.astro`,anchorKind:`head-tag`,code:n,description:`Inject the Zenovay tracker inside <head> of the primary layout.`},{targetPath:`src/layouts/BaseHead.astro`,anchorKind:`head-tag`,code:n,description:"Fallback target when the project uses a dedicated `BaseHead.astro`."},{targetPath:`src/pages/index.astro`,anchorKind:`head-tag`,code:n,description:"Fallback for layout-less projects (e.g. the official `create-astro --template minimal` starter keeps the document <head> inline in src/pages/index.astro)."}]}const he={id:`astro`,displayName:`Astro`,detect:U,files:[{path:`src/layouts/Layout.astro`,kind:`mutate`,required:!1},{path:`src/layouts/BaseHead.astro`,kind:`mutate`,required:!1},{path:`.env`,kind:`create`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:me};async function ge(e){let t=await e.readFile(`package.json`);if(t)try{let e=JSON.parse(t);if(e.dependencies?.gatsby??e.devDependencies?.gatsby)return!0}catch{}return await e.exists(`gatsby-config.js`)||await e.exists(`gatsby-config.ts`)}async function _e(e){return await ge(e)?{matched:!0,confidence:.95,reason:"Detected Gatsby via `gatsby` dependency / `gatsby-config`."}:{matched:!1,confidence:0,reason:`No Gatsby dependency or config found.`}}function ve(e){let t=e.trackingCode??e.siteId??``,n=`const React = require('react');
3
-
4
- exports.onRenderBody = ({ setHeadComponents }) => {
5
- setHeadComponents([
6
- React.createElement('script', {
7
- key: 'zenovay-tracker',
8
- defer: true,
9
- 'data-id': '${t}',
10
- src: 'https://api.zenovay.com/z.js',
11
- }),
12
- ]);
13
- };
14
- `;return[{targetPath:`gatsby-ssr.js`,anchorKind:`replace-file`,code:n,description:`Add the Zenovay tracker via Gatsby SSR onRenderBody → setHeadComponents.`}]}const ye={id:`gatsby`,displayName:`Gatsby`,detect:_e,files:[{path:`gatsby-ssr.js`,kind:`create`,required:!0}],envVarName:`GATSBY_ZENOVAY_SITE`,buildSnippets:ve},be=[`app/layout.tsx`,`app/layout.ts`,`app/layout.jsx`,`app/layout.js`,`src/app/layout.tsx`,`src/app/layout.ts`,`src/app/layout.jsx`,`src/app/layout.js`];async function xe(e){for(let t of be)if(await e.exists(t))return t;return null}async function Se(e){let t=await e.readFile(`package.json`);if(!t)return!1;try{let e=JSON.parse(t);return!!(e.dependencies?.next??e.devDependencies?.next)}catch{return!1}}async function Ce(e){let t=await Se(e),n=await e.exists(`app`)||await e.exists(`src/app`),r=await xe(e);return t?n?r?{matched:!0,confidence:.95,reason:`Detected Next.js App Router via \`next\` dep + \`${r}\`.`}:{matched:!1,confidence:.4,reason:"Found `app/` but no root layout file (layout.tsx/ts/jsx/js)."}:{matched:!1,confidence:0,reason:"No `app/` directory found — not an App Router project."}:{matched:!1,confidence:0,reason:"package.json does not list `next` as a dependency."}}function we(e,t=`script`){let n=e.targetPath||`app/layout.tsx`,r=e.trackingCode??e.siteId??``;return t===`npm`?Ee(n,r):Te(n,r)}function Te(e,t){return[{targetPath:e,anchorKind:`after-imports`,code:`import Script from 'next/script';`,description:`Import next/script to inject the Zenovay tracker.`},{targetPath:e,anchorKind:`wrap-children`,code:`<Script
15
- defer
16
- data-id="${t}"
17
- src="https://api.zenovay.com/z.js"
18
- strategy="afterInteractive"
19
- />
20
- {children}`,description:`Add the Zenovay tracker <Script> next to children in the root layout.`}]}function Ee(e,t){return[{targetPath:`components/zenovay-bootstrap.tsx`,anchorKind:`replace-file`,code:`'use client';
21
-
22
- import { useEffect } from 'react';
23
- import { init } from '@zenovay/tracker';
24
-
25
- /**
26
- * Mounts the Zenovay tracker exactly once on the client. Equivalent to the
27
- * canonical <script src="https://api.zenovay.com/z.js"> tag — init() injects
28
- * the same loader internally.
29
- */
30
- export function ZenovayBootstrap() {
31
- useEffect(() => {
32
- init(${JSON.stringify(t)});
33
- }, []);
34
- return null;
35
- }
36
- `,description:`Create a client-component bootstrap that calls init() from @zenovay/tracker.`},{targetPath:e,anchorKind:`after-imports`,code:`import { ZenovayBootstrap } from '@/components/zenovay-bootstrap';`,description:`Import the Zenovay tracker bootstrap into the root layout.`},{targetPath:e,anchorKind:`wrap-children`,code:`<ZenovayBootstrap />
37
- {children}`,description:`Render the Zenovay tracker bootstrap alongside children in the root layout.`}]}const De={id:`next-app-router`,displayName:`Next.js (App Router)`,detect:Ce,files:[{path:`app/layout.tsx`,kind:`mutate`,required:!0}],envVarName:`NEXT_PUBLIC_ZENOVAY_SITE`,packageDeps:[`@zenovay/tracker`],supportsNpmMode:!0,buildSnippets:we},Oe=[`pages/_app.tsx`,`pages/_app.ts`,`pages/_app.jsx`,`pages/_app.js`,`src/pages/_app.tsx`,`src/pages/_app.ts`,`src/pages/_app.jsx`,`src/pages/_app.js`];async function ke(e){for(let t of Oe)if(await e.exists(t))return t;return null}async function Ae(e){let t=await e.readFile(`package.json`);if(!t)return!1;try{let e=JSON.parse(t);return!!(e.dependencies?.next??e.devDependencies?.next)}catch{return!1}}async function je(e){let t=await Ae(e);if(!t)return{matched:!1,confidence:0,reason:"package.json does not list `next` as a dependency."};let n=await ke(e);if(n)return{matched:!0,confidence:.9,reason:`Detected Next.js Pages Router via \`${n}\`.`};let r=await e.exists(`app`),i=await e.glob(`pages/**/*.{tsx,ts,jsx,js}`);return i.length>0&&!r?{matched:!0,confidence:.7,reason:"Found `pages/` directory with route files but no `_app` — will create one."}:{matched:!1,confidence:.2,reason:`Next.js detected, but no pages-router entry point found.`}}function Me(e){let t=`pages/_app.tsx`,n=e.trackingCode??e.siteId??``,r=`import type { AppProps } from 'next/app';
38
- import Script from 'next/script';
39
-
40
- export default function App({ Component, pageProps }: AppProps) {
41
- return (
42
- <>
43
- <Script
44
- defer
45
- data-id="${n}"
46
- src="https://api.zenovay.com/z.js"
47
- strategy="afterInteractive"
48
- />
49
- <Component {...pageProps} />
50
- </>
51
- );
52
- }
53
- `;return[{targetPath:t,anchorKind:`after-imports`,code:`import Script from 'next/script';`,description:"Import next/script in `_app`."},{targetPath:t,anchorKind:`wrap-children`,code:`<><Script defer data-id="${n}" src="https://api.zenovay.com/z.js" strategy="afterInteractive" /><Component {...pageProps} /></>`,description:`Render the Zenovay tracker alongside the page component.`},{targetPath:t,anchorKind:`replace-file`,code:r,description:"Full replacement when `_app` does not exist yet."}]}const Ne={id:`next-pages-router`,displayName:`Next.js (Pages Router)`,detect:je,files:[{path:`pages/_app.tsx`,kind:`mutate`,required:!0}],envVarName:`NEXT_PUBLIC_ZENOVAY_SITE`,buildSnippets:Me},Pe=C.object({modules:C.array(C.string()).optional(),runtimeConfig:C.object({public:C.record(C.string(),C.unknown()).optional()}).optional()}).passthrough();async function Fe(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json found.`};try{let e=JSON.parse(t),n=!!(e.dependencies?.nuxt??e.devDependencies?.nuxt??e.dependencies?.nuxt3??e.devDependencies?.nuxt3);if(n)return{matched:!0,confidence:.95,reason:"Detected Nuxt via `nuxt` / `nuxt3` dependency."}}catch{}let n=await e.exists(`nuxt.config.ts`)||await e.exists(`nuxt.config.js`)||await e.exists(`nuxt.config.mjs`);return n?{matched:!0,confidence:.6,reason:"Found `nuxt.config.*` but no explicit dependency listing."}:{matched:!1,confidence:0,reason:`No Nuxt dependency or config detected.`}}function Ie(e){let t=e.trackingCode??e.siteId??``,n=` app: {
54
- head: {
55
- script: [
56
- {
57
- defer: true,
58
- src: 'https://api.zenovay.com/z.js',
59
- 'data-id': '${t}',
60
- },
61
- ],
62
- },
63
- },`;return[{targetPath:`nuxt.config.ts`,anchorKind:`head-tag`,code:n,description:"Add the Zenovay tracker to Nuxt's `app.head.script` so every page loads it."}]}const Le={id:`nuxt`,displayName:`Nuxt`,detect:Fe,files:[{path:`nuxt.config.ts`,kind:`mutate`,required:!0}],envVarName:`NUXT_PUBLIC_ZENOVAY_SITE`,buildSnippets:Ie},Re=[`index.html`,`public/index.html`,`dist/index.html`];async function ze(e){for(let t of Re)if(await e.exists(t))return{matched:!0,confidence:.5,reason:`Detected plain HTML project via \`${t}\`.`};let t=await e.glob(`**/*.html`);return t.length>0?{matched:!0,confidence:.3,reason:`Found ${t.length} HTML file(s); plain-HTML adapter is usable as fallback.`}:{matched:!1,confidence:0,reason:`No HTML files found in the project.`}}function Be(e){let t=e.trackingCode??e.siteId??``,n=`<script defer\n data-id="${t}"\n src="https://api.zenovay.com/z.js">\n</script>`;return[{targetPath:`index.html`,anchorKind:`head-tag`,code:n,description:`Inject the Zenovay tracker inside <head>. Repeat for every HTML file that contains a <head>.`}]}const Ve={id:`plain-html`,displayName:`Plain HTML`,detect:ze,files:[{path:`index.html`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:Be};async function He(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json.`};try{let e=JSON.parse(t),n={...e.dependencies??{},...e.devDependencies??{}};if(n[`@builder.io/qwik-city`]??n[`@builder.io/qwik`])return{matched:!0,confidence:.92,reason:"Detected Qwik via `@builder.io/qwik(-city)`."}}catch{}return{matched:!1,confidence:0,reason:`No Qwik dependency found.`}}function Ue(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`src/root.tsx`,r=`<script
64
- defer
65
- data-id="${t}"
66
- src="https://api.zenovay.com/z.js"
67
- />`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Add the Zenovay tracker into the <head> of the Qwik root document.`}]}const We={id:`qwik`,displayName:`Qwik`,detect:He,files:[{path:`src/root.tsx`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:Ue};async function Ge(e){let t=await e.readFile(`package.json`);if(t)try{let e=JSON.parse(t),n={...e.dependencies??{},...e.devDependencies??{}},r=Object.keys(n).some(e=>e.startsWith(`@remix-run/`));if(r)return{matched:!0,confidence:.95,reason:"Detected Remix via `@remix-run/*` dependencies."}}catch{}return await e.exists(`remix.config.js`)||await e.exists(`remix.config.ts`)?{matched:!0,confidence:.8,reason:"Detected Remix via `remix.config.*`."}:{matched:!1,confidence:0,reason:`No Remix dependency or config detected.`}}function Ke(e){let t=e.trackingCode??e.siteId??``;return[{targetPath:`app/root.tsx`,anchorKind:`head-tag`,code:`<script defer data-id="${t}" src="https://api.zenovay.com/z.js"></script>`,description:`Inline the Zenovay tracker <script> inside the document <head>.`}]}const qe={id:`remix`,displayName:`Remix`,detect:Ge,files:[{path:`app/root.tsx`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:Ke};async function Je(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json.`};try{let e=JSON.parse(t),n={...e.dependencies??{},...e.devDependencies??{}};if(n[`@solidjs/start`]??n[`solid-start`])return{matched:!0,confidence:.92,reason:"Detected SolidStart via `@solidjs/start` / `solid-start`."}}catch{}return{matched:!1,confidence:0,reason:`No SolidStart dependency found.`}}function Ye(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`src/entry-server.tsx`,r=`<script
68
- defer
69
- data-id="${t}"
70
- src="https://api.zenovay.com/z.js"
71
- />`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Add the Zenovay tracker into the document <head> rendered by SolidStart entry-server.`}]}const Xe={id:`solid-start`,displayName:`SolidStart`,detect:Je,files:[{path:`src/entry-server.tsx`,kind:`mutate`,required:!0}],envVarName:`VITE_ZENOVAY_SITE`,buildSnippets:Ye};async function Ze(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json found.`};try{let e=JSON.parse(t),n=!!(e.dependencies?.[`@sveltejs/kit`]??e.devDependencies?.[`@sveltejs/kit`]);return n?{matched:!0,confidence:.95,reason:"Detected SvelteKit via `@sveltejs/kit` dependency."}:{matched:!1,confidence:0,reason:"`@sveltejs/kit` not in dependencies."}}catch{return{matched:!1,confidence:0,reason:`package.json is not valid JSON.`}}}function Qe(e){let t=e.trackingCode??e.siteId??``,n=`<svelte:head>
72
- <script defer data-id="${t}" src="https://api.zenovay.com/z.js"></script>
73
- </svelte:head>
74
-
75
- <slot />
76
- `;return[{targetPath:`src/routes/+layout.svelte`,anchorKind:`replace-file`,code:n,description:`Root layout that loads the Zenovay tracker in every route via <svelte:head>.`}]}const $e={id:`sveltekit`,displayName:`SvelteKit`,detect:Ze,files:[{path:`src/routes/+layout.svelte`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:Qe},et=[`next`,`nuxt`,`nuxt3`,`@sveltejs/kit`,`astro`,`@remix-run/react`,`@builder.io/qwik-city`,`@builder.io/qwik`,`@solidjs/start`,`solid-start`,`@angular/core`,`gatsby`],tt=[`index.html`,`public/index.html`];async function nt(e){let t=await e.readFile(`package.json`);if(!t)return{};try{let e=JSON.parse(t);return{...e.dependencies??{},...e.devDependencies??{}}}catch{return{}}}async function rt(e){for(let t of tt)if(await e.exists(t))return t;return null}async function it(e){let t=await nt(e);if(et.some(e=>t[e]))return{matched:!1,confidence:0,reason:`A Vite-based meta-framework (Next/Nuxt/SvelteKit/Astro/Remix/Qwik/Solid/Angular) owns this project.`};let n=!!t.vite,r=await rt(e);return n&&r?{matched:!0,confidence:.85,reason:`Detected a Vite app via \`vite\` dependency + \`${r}\`.`}:n?{matched:!0,confidence:.55,reason:"Detected `vite` but no index.html — the agent will locate the SPA entry."}:{matched:!1,confidence:0,reason:"No `vite` dependency found."}}function at(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`index.html`,r=`<script defer\n data-id="${t}"\n src="https://api.zenovay.com/z.js">\n</script>`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Inject the Zenovay tracker inside <head> of the Vite entry HTML.`}]}const ot={id:`vite`,displayName:`Vite`,detect:it,files:[{path:`index.html`,kind:`mutate`,required:!0}],envVarName:`VITE_ZENOVAY_SITE`,buildSnippets:at},st=[De,Ne,Le,$e,he,qe,ye,pe,Xe,We,ot,Ve];async function ct(e){let t=[];for(let n of st){let r=await n.detect(e);t.push({adapter:n,result:r})}let n=[...t].sort((e,t)=>t.result.confidence-e.result.confidence),r=n[0],i=r&&r.result.matched?r.adapter:null;return{adapter:i,ranked:n}}function lt(e){let t=t=>x.resolve(e,t);return{cwd:e,async readFile(e){try{return await S.readFile(t(e),`utf8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`EISDIR`)return null;throw e}},async exists(e){try{return await S.access(t(e)),!0}catch{return!1}},async glob(t){return P(t,{cwd:e,dot:!1,gitignore:!0,onlyFiles:!0,followSymbolicLinks:!1})}}}async function ut(e,t){let n=lt(e),{adapter:r,ranked:i}=await ct(n),a=i[0];return r&&a&&a.result.confidence>=.7?r:t?t.pickInteractively(i):r}function dt(e,t){let n=/[\s"'#=]/.test(t)||t===``,r=n?`"${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:t;return`${e}=${r}`}function ft(e){let t=new Set;for(let n of e.split(/\r?\n/)){let e=n.trim();if(!e||e.startsWith(`#`))continue;let r=e.indexOf(`=`);if(r<=0)continue;let i=e.slice(0,r).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(i)&&t.add(i)}return t}async function W(e,t,n={}){let r=n.filename??`.env.local`,i=x.resolve(e,r),a=``,o=!0;try{a=await S.readFile(i,`utf8`)}catch(e){if(e.code===`ENOENT`)o=!1;else throw e}let s=o?ft(a):new Set,c=[],l=[],u=[];for(let[e,n]of Object.entries(t)){if(s.has(e)){l.push(e);continue}u.push(dt(e,n)),c.push(e)}if(c.length===0)return{created:!1,existing:o,addedKeys:c,skippedKeys:l};let d=`# Added by Zenovay CLI`,f;if(o){let e=a.length>0&&!a.endsWith(`
77
- `);f=a+(e?`
78
- `:``)+`
79
- `+d+`
80
- `+u.join(`
81
- `)+`
82
- `}else f=d+`
83
- `+u.join(`
84
- `)+`
85
- `;if(o)await S.writeFile(i,f,`utf8`);else{let e=await S.open(i,`w`,384);try{await e.writeFile(f,`utf8`)}finally{await e.close()}}return{created:!o,existing:o,addedKeys:c,skippedKeys:l}}const pt=`https://api.zenovay.com/mcp`,mt=C.object({url:C.string().url(),headers:C.record(C.string(),C.string()).optional()}).passthrough(),ht=C.object({mcpServers:C.record(C.string(),mt).optional()}).passthrough();function gt(e){return e.HOME??e.USERPROFILE??te.homedir()}function _t(e){return e.APPDATA??null}function vt(e,t){let n=gt(t),r=_t(t),i=[];return i.push({id:`claude-code`,displayName:`Claude Code`,configPath:x.join(n,`.claude.json`),serversKey:`mcpServers`,includeType:!0}),i.push({id:`cursor`,displayName:`Cursor`,configPath:x.join(n,`.cursor`,`mcp.json`),serversKey:`mcpServers`,includeType:!1}),e===`win32`&&r&&i.push({id:`cursor`,displayName:`Cursor (AppData)`,configPath:x.join(r,`Cursor`,`User`,`globalStorage`,`cursor.mcp`,`mcp.json`),serversKey:`mcpServers`,includeType:!1}),e===`darwin`?i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:x.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`),serversKey:`mcpServers`,includeType:!0}):e===`win32`&&r?i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:x.join(r,`Claude`,`claude_desktop_config.json`),serversKey:`mcpServers`,includeType:!0}):i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:x.join(n,`.config`,`Claude`,`claude_desktop_config.json`),serversKey:`mcpServers`,includeType:!0}),i.push({id:`vscode`,displayName:`VS Code`,configPath:x.join(n,`.vscode`,`mcp.json`),serversKey:`servers`,includeType:!0}),i}async function yt(e){try{return await S.access(e),!0}catch{return!1}}async function bt(e){try{let t=await S.readFile(e,`utf8`);if(t.trim().length===0)return{};let n=JSON.parse(t),r=ht.safeParse(n);return r.success?r.data:n&&typeof n==`object`?n:{}}catch{return{}}}function xt(e){return e?{type:`http`,url:pt}:{url:pt}}function St(e){return!e||typeof e!=`object`?!1:Object.values(e).some(e=>e&&typeof e==`object`&&e.url===pt)}async function G(e){let t=e.env??process.env,n=e.platform??process.platform,r=new Set(e.skip??[]),i=[],a=[],o=[],s=new Set;for(let e of vt(n,t)){if(r.has(e.id)){a.push(e.displayName);continue}if(s.has(e.configPath))continue;s.add(e.configPath);try{let t=await yt(e.configPath);if(!t){a.push(e.displayName);continue}let n=await bt(e.configPath),r=n[e.serversKey];if(St(r)){i.push(e.displayName);continue}let o=`${e.configPath}.bak`;await S.copyFile(e.configPath,o);let s=r&&typeof r==`object`?r:{},c={...n,[e.serversKey]:{...s,zenovay:xt(e.includeType)}};await S.mkdir(x.dirname(e.configPath),{recursive:!0}),await S.writeFile(e.configPath,JSON.stringify(c,null,2)+`
86
- `,`utf8`),await S.chmod(e.configPath,384).catch(()=>void 0),i.push(e.displayName)}catch(t){o.push({client:e.displayName,message:t instanceof Error?t.message:String(t)})}}return{installed:i,skipped:a,errors:o}}async function Ct(e,t,n){let r=n.timeoutMs??18e4,i=n.pollIntervalMs??2e3,a=n.now??(()=>Date.now()),o=n.sleep??(e=>new Promise(t=>setTimeout(t,e))),s=a(),c=s+r;for(n.onTick?.(0);;){let l=await n.api.getFirstEvent({siteId:e,since:t});if(l.received)return{received:!0,event:l.event};let u=a()-s;if(u>=r)return{received:!1};let d=c-a(),f=Math.min(i,Math.max(0,d));if(f<=0)return{received:!1};await o(f),n.onTick?.(a()-s)}}const wt=C.object({path:C.string().min(1)}),Tt=C.object({path:C.string().min(1),content:C.string(),reason:C.string().min(1)}),Et=C.object({path:C.string().min(1),patch:C.string().min(1),reason:C.string().min(1)}),Dt=C.object({}),Ot=C.object({question:C.string().min(1),choices:C.array(C.string()).optional()});async function kt(e,t){let n=wt.safeParse(t);if(!n.success)return{ok:!1,content:null,error:`invalid_args`};try{let t=await e.safeRead(n.data.path),r=V.scrubSecrets(t),i=24e3,a=r.length>i?`${r.slice(0,i)}\n\n[... truncated: file is ${r.length} chars; showing the first ${i}]`:r;return{ok:!0,content:V.wrapForModel(n.data.path,a)}}catch(e){return{ok:!1,content:null,error:e.message}}}async function At(e,t,n){let r=Tt.safeParse(t);if(!r.success)return{ok:!1,content:null,error:`invalid_args`};let{path:i,content:a,reason:o}=r.data,s=``;try{s=await e.safeRead(i)}catch{s=``}let c=await n.approve({path:i,oldContent:s,newContent:a,reason:o});if(c===`n`)return{ok:!1,content:null,error:`skipped_by_user`};if(c===`e`)return{ok:!1,content:null,error:`deferred_to_user_edit`};try{let{backupPath:t}=await e.safeWrite(i,a);return{ok:!0,content:{path:i,backupPath:t}}}catch(e){return{ok:!1,content:null,error:e.message}}}async function jt(e,t,n){let r=Et.safeParse(t);if(!r.success)return{ok:!1,content:null,error:`invalid_args`};let{path:i,patch:a,reason:o}=r.data;if(/^\*\*\*\s+Begin Patch/m.test(a)||/^\*\*\*\s+Update File:/m.test(a))return{ok:!1,content:null,error:'unsupported_patch_format: This tool only accepts STANDARD unified diff with `--- a/...`, `+++ b/...`, and `@@ -N,M +N,M @@` headers. The "*** Begin Patch / *** Update File:" V4A format is NOT supported. Please call write_file with the full new file content instead.'};let s;try{s=await e.safeRead(i)}catch(e){return{ok:!1,content:null,error:e.message}}let c;try{c=ie(s,a)}catch(e){return{ok:!1,content:null,error:`patch_failed: ${e.message}. Please call write_file with the full new file content instead — write_file is more reliable than patch_file for this use case.`}}return c===!1||typeof c!=`string`?{ok:!1,content:null,error:`patch_did_not_apply_cleanly. The patch context may not match the file. Please call write_file with the full new file content instead.`}:At(e,{path:i,content:c,reason:o},n)}async function Mt(e){try{let t=lt(e),{adapter:n,ranked:r}=await ct(t);return{ok:!0,content:{matched:n!==null,adapter:n?.id,displayName:n?.displayName,ranked:r.map(e=>({id:e.adapter.id,confidence:e.result.confidence,reason:e.result.reason}))}}}catch(e){return{ok:!1,content:null,error:e.message}}}async function Nt(e,t){let n=Ot.safeParse(t);if(!n.success)return{ok:!1,content:null,error:`invalid_args`};try{let t=await e.ask(n.data);return{ok:!0,content:{answer:t}}}catch(e){return{ok:!1,content:null,error:e.message}}}const Pt=3;function Ft(e,t,n){if(n)return e.delete(t),null;let r=(e.get(t)??0)+1;return e.set(t,r),r>=Pt?`STOP retrying ${t}: it failed ${r} times. Do NOT call write_file/patch_file on ${t} again — edit a different entry file, or if the tracker is already present, stop and return.`:null}async function It(e){let{api:t,sandbox:n,approval:r,prompter:i,handlers:a}=e,o=[...e.initialMessages],s=``,c=0,l=new Map;for(;c<ce;){n.incrementRound(),c++;let d=new AbortController,f=9e4,p=()=>{let e=setTimeout(()=>d.abort(),f);return e.unref?.(),e},m=p(),h=()=>{clearTimeout(m),m=p()},g;try{g=await t.openAiStream(`install`,{messages:o,cwd_fingerprint:n.sessionId,diagnosis:e.diagnosis,targetTrackingCode:e.targetTrackingCode},d.signal)}catch(e){throw clearTimeout(m),e}let _=[],v=``;for await(let e of u(g))switch(h(),e.type){case`delta`:v+=e.content,a?.onDelta?.(e.content);break;case`tool_start`:a?.onToolStart?.({id:e.id,name:e.name});break;case`tool_call`:{clearTimeout(m);let t=await Lt(e.name,e.arguments,{sandbox:n,cwd:n.cwd,approval:r,prompter:i});h();let o=(e.name===`write_file`||e.name===`patch_file`)&&typeof e.arguments.path==`string`?e.arguments.path:null;if(o){let e=Ft(l,o,t.ok!==!1);e&&(t={...t,error:`${t.error??`write_failed`} — ${e}`})}_.push({id:e.id,name:e.name,arguments:e.arguments,result:t}),a?.onToolResult?.({id:e.id,name:e.name,result:t});break}case`usage`:a?.onUsage?.(e);break;case`error`:throw clearTimeout(m),a?.onError?.(e),Error(`[${e.code}] ${e.message}`);case`done`:break}if(clearTimeout(m),v&&(s+=v),_.length===0){v&&o.push({role:`assistant`,content:v});break}o.push({role:`assistant`,content:v,toolCalls:_.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))});for(let e of _)o.push({role:`tool`,toolCallId:e.id,toolName:e.name,content:JSON.stringify(e.result)})}return{finalText:s,rounds:c}}async function Lt(e,t,n){try{switch(e){case`read_file`:return await kt(n.sandbox,t);case`write_file`:return await At(n.sandbox,t,n.approval);case`patch_file`:return await jt(n.sandbox,t,n.approval);case`detect_framework`:return await Mt(n.cwd);case`ask_user`:return await Nt(n.prompter,t);default:return{ok:!1,content:null,error:`unknown_tool:${e}`}}}catch(e){return{ok:!1,content:null,error:`tool_threw: ${e.message}`}}}const Rt="What to do: re-run with `--review` to approve each write, or install manually (see https://docs.zenovay.com/en/integrations/cli).";function zt(e,t,n,r){if(e.writes===0){let t=r?`Agent error: ${r.message}`:`Agent returned without writing any files (${e.reads} reads, ${e.rounds} rounds). The model may have refused or the AI Gateway may be misconfigured.`;return{ok:!1,error:`${t}\n${Rt} Nothing was changed in your project.`}}if(!t.includes(n)){let r=e.writtenPaths.join(`, `)||`(none)`,i=t.length?` (found other code(s): ${t.join(`, `)})`:``;return{ok:!1,error:`Agent wrote to: [${r}] but no Zenovay tracker <script> with your code (${n}) is present in any source file${i} — the tracker is NOT installed. The model likely wrote the code into .env only, or edited the wrong file.\n${Rt} Review/undo what was written under ~/.zenovay/undo/.`}}return{ok:!0}}const Bt=e=>`<script defer\n data-id="${e}"\n src="https://api.zenovay.com/z.js">\n</script>`;async function Vt(e){let t={installed:[],skipped:[],errors:[]};if(!K(e.trackingCode))return t.errors.push({file:`(input)`,error:`Unexpected tracking-code format: "${e.trackingCode}". Expected letters, digits, "_" or "-".`}),t;let n=await P([`**/*.html`,`!node_modules/**`,`!.git/**`,`!dist/**`,`!.next/**`,`!.nuxt/**`,`!build/**`,`!.output/**`],{cwd:e.cwd,gitignore:!0,absolute:!1});if(n.length===0)return t;let r=Bt(e.trackingCode),i=RegExp(`data-id\\s*=\\s*["']${Ht(e.trackingCode)}["']`);for(let a of n){let n=x.join(e.cwd,a),o;try{o=await S.readFile(n,`utf8`)}catch(e){t.errors.push({file:a,error:e.message});continue}if(z.test(o)&&i.test(o)){t.skipped.push({file:a,reason:`already installed with correct tracking code`});continue}let s;if(z.test(o))s=o.replace(/(<script[^>]*src\s*=\s*["']https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+["'][^>]*>)/i,t=>t.replace(/data-id\s*=\s*["']ZV_\w+["']/i,`data-id="${e.trackingCode}"`)),s===o&&(s=o.replace(/<script(\s)/i,`<script$1data-id="${e.trackingCode}"$1`));else if(e.updateOnly){t.skipped.push({file:a,reason:`updateOnly=true and no Zenovay tag present`});continue}else if(/<\/head>/i.test(o)){if(s=o.replace(/(\n[\t ]*)?<\/head>/i,(e,t)=>{let n=t??`
87
- `,i=r.replace(/\n/g,`${n}`);return`${n}${i}${n}</head>`}),s===o){t.skipped.push({file:a,reason:`</head> regex did not match unexpectedly`});continue}}else{t.skipped.push({file:a,reason:`no <head>...</head> in file (fragment or non-page)`});continue}let c=null;for(let{name:e,re:t}of B)if(t.test(o)&&!t.test(s)){c=e;break}if(c){t.errors.push({file:a,error:`would remove ${c} tracker — refusing to write`});continue}try{await S.writeFile(n,s,`utf8`),t.installed.push(a)}catch(e){t.errors.push({file:a,error:e.message})}}return t}function Ht(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function K(e){return typeof e==`string`&&e.length>0&&e.length<=64&&/^[A-Za-z0-9_-]+$/.test(e)}function Ut(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const Wt=/<[Ss]cript\b[^>]*\bsrc\s*=\s*["'`][^"'`]*(?:api\.zenovay\.com\/z\.js|\/(?:api\/)?_z\/script\.js)[^"'`]*["'`][^>]*>/;function Gt(e){return Wt.test(e)}function Kt(e){return/api\.zenovay\.com\/z\.js/i.test(e)||/\/(?:api\/)?_z\/script\.js/i.test(e)}function qt(e,t){let n=Ut(t),r=e.match(new RegExp(Wt.source,`gi`))||[];return r.length===0?!1:r.every(e=>{let t=/\/(?:api\/)?_z\/script\.js/i.test(e);return t?RegExp(`[?&]id=${n}(?:["'\`&\\s/]|$)`).test(e):RegExp(`\\bdata-id\\s*=\\s*["'\`]${n}["'\`]`).test(e)})}function Jt(e,t){return e.replace(/<[Ss]cript\b[^>]*>/g,e=>{let n=/\bsrc\s*=\s*["'`][^"'`]*api\.zenovay\.com\/z\.js/.test(e),r=/\bsrc\s*=\s*["'`][^"'`]*\/(?:api\/)?_z\/script\.js/.test(e);if(!n&&!r)return e;let i=e.replace(/(\bdata-id\s*=\s*["'`])[^"'`]*(["'`])/i,`$1${t}$2`);return r&&(i=i.replace(/([?&]id=)[^&"'`\s]*/i,`$1${encodeURIComponent(t)}`)),i})}const Yt=`https://api.zenovay.com/z.js`;function Xt(e){if(/from\s+['"]next\/script['"]/.test(e))return e;let t=e.split(`
88
- `),n=-1;for(let e=0;e<t.length;e++)/^\s*import\s/.test(t[e])&&(n=e);let r=`import Script from 'next/script';`;if(n>=0)t.splice(n+1,0,r);else{let e=/^\s*['"]use client['"];?\s*$/.test(t[0]??``);t.splice(e?1:0,0,r)}return t.join(`
89
- `)}function Zt(e,t){let n=/([ \t]*)<\/body>/,r=e.match(n);if(!r)return null;let i=r[1]??``,a=`${i} <Script defer data-id="${t}" src="${Yt}" strategy="afterInteractive" />`;return e.replace(n,`${a}\n${i}</body>`)}async function Qt(e){let{cwd:t,trackingCode:n}=e,r={installed:[],skipped:[],errors:[],fellThrough:!1};if(!K(n))return r.errors.push({file:`(input)`,error:`unexpected tracking-code format: "${n}"`}),r;let i;try{i=await P([`app/**/layout.{tsx,ts,jsx,js}`,`src/app/**/layout.{tsx,ts,jsx,js}`],{cwd:t,gitignore:!1,ignore:[`**/node_modules/**`]})}catch(e){return r.errors.push({file:`app/**/layout`,error:e.message}),r.fellThrough=!0,r}if(i.length===0)return r.fellThrough=!0,r;let a=[];for(let e of i)try{let n=await k.readFile(x.join(t,e),`utf8`);/<body[\s/>]/.test(n)&&a.push({rel:e,src:n,depth:e.split(`/`).length})}catch{}if(a.length===0)return r.fellThrough=!0,r;a.sort((e,t)=>e.depth-t.depth);let o=a[0];if(qt(o.src,n))return r.skipped.push({file:o.rel,reason:`already installed with correct tracking code`}),r;if(Wt.test(o.src)){let e=Jt(o.src,n);if(e!==o.src){try{await k.writeFile(x.join(t,o.rel),e),r.installed.push(o.rel)}catch(e){r.errors.push({file:o.rel,error:e.message}),r.fellThrough=!0}return r}return r.fellThrough=!0,r}if(Kt(o.src))return r.fellThrough=!0,r;let s=Xt(o.src),c=Zt(s,n);if(!c)return r.fellThrough=!0,r;try{await k.writeFile(x.join(t,o.rel),c),r.installed.push(o.rel)}catch(e){r.errors.push({file:o.rel,error:e.message}),r.fellThrough=!0}return r}const $t=`api.zenovay.com/z.js`;async function q(e){try{return await S.readFile(e,`utf8`)}catch{return null}}function en(e,t){let n=e.toLowerCase().lastIndexOf(`</head>`);if(n===-1)return null;let r=e.lastIndexOf(`
90
- `,n-1)+1,i=(e.slice(r,n).match(/^[ \t]*/)??[``])[0],a=`${i}${t}\n`;return e.slice(0,r)+a+e.slice(r)}async function tn(e,t,n,r,i=0,a=new Set){if(i>4)return null;let o=x.dirname(e),s=/import\s+[^;]*?from\s*['"`](\.[^'"`]+\.(?:astro|tsx|jsx|vue|svelte))['"`]/g,c=[],l;for(;(l=s.exec(t))!==null;){let e=x.resolve(o,l[1]);if(a.has(e))continue;a.add(e);let t=await q(e);if(t===null)continue;if(Gt(t)){if(qt(t,r))return e;let n=Jt(t,r);return n!==t&&await S.writeFile(e,n,`utf8`),e}if(Kt(t))return e;let i=en(t,n);if(i!==null)return await S.writeFile(e,i,`utf8`),e;c.push({abs:e,content:t})}for(let e of c){let t=await tn(e.abs,e.content,n,r,i+1,a);if(t)return t}return null}async function nn(e){if(!K(e.trackingCode))return{installed:[],skipped:[],errors:[{file:`(input)`,error:`unexpected tracking-code format: "${e.trackingCode}"`}],fellThrough:!1};if(e.adapter.id===`nuxt`)return an(e);if(e.adapter.id===`sveltekit`)return on(e);let{cwd:t,trackingCode:n,siteId:r,adapter:i}=e,a={installed:[],skipped:[],errors:[],fellThrough:!1},o;try{o=i.buildSnippets({trackingCode:n,siteId:r??``},`script`)}catch{return a.fellThrough=!0,a}if(!o||o.length===0)return a.fellThrough=!0,a;let s=new Set(o.map(e=>e.anchorKind));if(s.size===1&&s.has(`head-tag`)){let e=!1;for(let r of o){let i=x.join(t,r.targetPath),o=await q(i);if(o===null){a.skipped.push({file:r.targetPath,reason:`target file not present`});continue}if(qt(o,n)){a.skipped.push({file:r.targetPath,reason:`already installed with correct tracking code`}),e=!0;break}if(Gt(o)){let t=Jt(o,n);if(t!==o)try{await S.writeFile(i,t,`utf8`),a.installed.push(r.targetPath),e=!0;break}catch(e){a.errors.push({file:r.targetPath,error:e.message});continue}return a.fellThrough=!0,a}if(Kt(o)){a.skipped.push({file:r.targetPath,reason:`tracker present in an unparseable form (not double-inserting)`}),e=!0;break}let s=en(o,r.code);if(s===null){let s=await tn(i,o,r.code,n);if(s){a.installed.push(x.relative(t,s)),e=!0;break}a.skipped.push({file:r.targetPath,reason:`no </head> anchor (inline or in an imported head component)`});continue}try{await S.writeFile(i,s,`utf8`),a.installed.push(r.targetPath),e=!0;break}catch(e){a.errors.push({file:r.targetPath,error:e.message})}}return!e&&a.installed.length===0&&a.errors.length===0&&(a.fellThrough=!0),a}if(s.size===1&&s.has(`replace-file`)&&o.length===1){let e=o[0];if(!e)return a.fellThrough=!0,a;let r=i.files.find(t=>t.path===e.targetPath),s=x.join(t,e.targetPath),c=await q(s);if(c!==null)return c.includes($t)&&c.includes(n)?(a.skipped.push({file:e.targetPath,reason:`already installed with correct tracking code`}),a):(a.fellThrough=!0,a);if(r?.kind===`create`){try{await S.mkdir(x.dirname(s),{recursive:!0}),await S.writeFile(s,e.code,`utf8`),a.installed.push(e.targetPath)}catch(t){a.errors.push({file:e.targetPath,error:t.message}),a.fellThrough=a.installed.length===0}return a}return a.fellThrough=!0,a}return a.fellThrough=!0,a}function rn(){return{installed:[],skipped:[],errors:[],fellThrough:!1}}async function an(e){let t=rn(),n=[`nuxt.config.ts`,`nuxt.config.mjs`,`nuxt.config.js`],r=null,i=null,a=null;for(let t of n){let n=x.join(e.cwd,t),o=await q(n);if(o!==null){r=t,i=n,a=o;break}}if(a===null||i===null||r===null)return t.skipped.push({file:`nuxt.config.ts`,reason:`nuxt.config not found`}),t.fellThrough=!0,t;if(a.includes($t))return a.includes(e.trackingCode)?(t.skipped.push({file:r,reason:`already installed with correct tracking code`}),t):(t.fellThrough=!0,t);if(/\bapp\s*:/.test(a))return t.fellThrough=!0,t;let o=a.match(/defineNuxtConfig\s*\(\s*\{/);if(!o||o.index===void 0)return t.fellThrough=!0,t;let s=e.adapter.buildSnippets({trackingCode:e.trackingCode,siteId:e.siteId??``},`script`)[0]?.code;if(!s)return t.fellThrough=!0,t;let c=o.index+o[0].length,l=`${a.slice(0,c)}\n${s}${a.slice(c)}`;try{await S.writeFile(i,l,`utf8`),t.installed.push(r)}catch(e){t.errors.push({file:r,error:e.message}),t.fellThrough=!0}return t}async function on(e){let t=rn(),n=`src/routes/+layout.svelte`,r=x.join(e.cwd,n),i=await q(r),a=`<svelte:head>\n <script defer data-id="${e.trackingCode}" src="https://api.zenovay.com/z.js"></script>\n</svelte:head>\n`;if(i!==null){if(qt(i,e.trackingCode))return t.skipped.push({file:n,reason:`already installed with correct tracking code`}),t;if(Gt(i)){let a=Jt(i,e.trackingCode);if(a!==i){try{await S.writeFile(r,a,`utf8`),t.installed.push(n)}catch(e){t.errors.push({file:n,error:e.message}),t.fellThrough=!0}return t}return t.fellThrough=!0,t}if(Kt(i))return t.fellThrough=!0,t;let o=i.indexOf(`</svelte:head>`),s=o>=0?i.slice(0,o)+` <script defer data-id="${e.trackingCode}" src="https://api.zenovay.com/z.js"></script>\n`+i.slice(o):`${a}\n${i}`;try{await S.writeFile(r,s,`utf8`),t.installed.push(n)}catch(e){t.errors.push({file:n,error:e.message}),t.fellThrough=!0}return t}let o=e.adapter.buildSnippets({trackingCode:e.trackingCode,siteId:e.siteId??``},`script`)[0]?.code;if(!o)return t.fellThrough=!0,t;try{await S.mkdir(x.dirname(r),{recursive:!0}),await S.writeFile(r,o,`utf8`),t.installed.push(n)}catch(e){t.errors.push({file:n,error:e.message}),t.fellThrough=!0}return t}async function J(e,t){try{return await S.access(x.join(e,t)),!0}catch{return!1}}async function sn(e,t){try{let n=await S.stat(x.join(e,t));return n.isDirectory()}catch{return!1}}async function cn(e,t){try{return await S.readFile(x.join(e,t),`utf8`)}catch{return null}}const ln=[`next.config.js`,`next.config.mjs`,`next.config.cjs`,`next.config.ts`];async function un(e){let t=[],n=await cn(e,`wrangler.toml`),r=n!==null&&/^\s*pages_build_output_dir\s*=/m.test(n),i=await sn(e,`functions`),a=await sn(e,`.cloudflare`);if(r&&t.push(`wrangler.toml has pages_build_output_dir`),i&&t.push(`functions/ directory present`),a&&t.push(`.cloudflare/ directory present`),r||i||a)return{host:`cloudflare-pages`,signals:t};let o=await J(e,`vercel.json`),s=await sn(e,`.vercel`);if(o&&t.push(`vercel.json present`),s&&t.push(`.vercel/ directory present`),o||s)return{host:`vercel`,signals:t};let c=await J(e,`netlify.toml`),l=await J(e,x.join(`public`,`_redirects`)),u=await J(e,`_redirects`);if(c&&t.push(`netlify.toml present`),l&&t.push(`public/_redirects present`),u&&t.push(`_redirects present`),c||l||u)return{host:`netlify`,signals:t};let d=null;for(let t of ln)if(await J(e,t)){d=t;break}return d?(t.push(`${d} present (no Vercel/Netlify/CF-Pages signal)`),{host:`nextjs-server`,signals:t}):(t.push(`no deployment-host signals found`),{host:`unknown`,signals:t})}function dn(e){if(!e)return;let t=e.trim().toLowerCase();if(t===`cloudflare-pages`||t===`cloudflare`||t===`cf-pages`||t===`pages`)return`cloudflare-pages`;if(t===`vercel`)return`vercel`;if(t===`netlify`)return`netlify`;if(t===`nextjs`||t===`next`||t===`nextjs-server`)return`nextjs-server`}const fn=`https://api.zenovay.com`;function pn(e){return`// Auto-generated by @zenovay/cli — first-party tracking proxy. Do not edit.
91
- /**
92
- * First-Party Proxy for Zenovay Tracking.
93
- *
94
- * This Cloudflare Pages Function proxies tracking requests from your site to
95
- * ${e}/fp/* — making tracking requests "first-party" to bypass browser
96
- * tracking protection (Firefox ETP, Edge Tracking Prevention, Safari ITP, Brave).
97
- *
98
- * Routes (this function lives at functions/api/_z/[[path]].ts → /api/_z/*):
99
- * - GET /api/_z/script.js → ${e}/fp/script.js
100
- * - GET /api/_z/load → ${e}/fp/load
101
- * - POST /api/_z/e/:trackingCode → ${e}/fp/e/:trackingCode
102
- * - POST /api/_z/events → ${e}/fp/events
103
- * - GET /api/_z/settings/:trackingCode → ${e}/fp/settings/:trackingCode
104
- */
105
-
106
- interface Env {
107
- NEXT_PUBLIC_API_URL?: string
108
- }
109
-
110
- interface EventContext {
111
- request: Request
112
- params: { path?: string[] }
113
- env: Env
114
- }
115
-
116
- /**
117
- * Handle all HTTP methods (GET, POST, OPTIONS).
118
- */
119
- export async function onRequest(context: EventContext): Promise<Response> {
120
- const { request, params, env } = context
121
-
122
- // Build the path from the catch-all parameter.
123
- const pathSegments = params.path || []
124
- const path = pathSegments.join('/')
125
-
126
- // API base URL — defaults to the value baked in at generation time, but an
127
- // env var override (NEXT_PUBLIC_API_URL) still wins if present.
128
- const apiBase = env.NEXT_PUBLIC_API_URL || '${e}'
129
-
130
- // Build target URL — proxy to /fp/* endpoints.
131
- const targetUrl = \`\${apiBase}/fp/\${path}\${new URL(request.url).search}\`
132
-
133
- // Handle OPTIONS (CORS preflight).
134
- if (request.method === 'OPTIONS') {
135
- return new Response(null, {
136
- status: 204,
137
- headers: {
138
- 'Access-Control-Allow-Origin': '*',
139
- 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
140
- 'Access-Control-Allow-Headers': 'Content-Type, X-Zenovay-Tracking-Code',
141
- 'Access-Control-Max-Age': '86400',
142
- },
143
- })
144
- }
145
-
146
- try {
147
- // Get the real client IP from Cloudflare headers.
148
- const clientIP =
149
- request.headers.get('CF-Connecting-IP') ||
150
- request.headers.get('X-Forwarded-For')?.split(',')[0]?.trim() ||
151
- request.headers.get('X-Real-IP') ||
152
- ''
153
-
154
- // Clone the original headers.
155
- const proxyHeaders = new Headers(request.headers)
156
-
157
- // Add/set proxy identification headers.
158
- proxyHeaders.set('X-Zenovay-Proxy', 'first-party')
159
- proxyHeaders.set('X-Zenovay-Real-IP', clientIP)
160
-
161
- // Forward the visitor's real CF geo data as custom headers before deleting
162
- // the originals. When this Worker proxies to ${e}, Cloudflare
163
- // overwrites CF-* headers with the Worker datacenter's info — these custom
164
- // headers preserve the visitor's real geo.
165
- const cfCountry = request.headers.get('CF-IPCountry')
166
- const cfCity = request.headers.get('CF-IPCity')
167
- const cfRegion = request.headers.get('CF-Region')
168
- const cfLatitude = request.headers.get('CF-IPLatitude')
169
- const cfLongitude = request.headers.get('CF-IPLongitude')
170
- const cfTimezone = request.headers.get('CF-Timezone')
171
- if (cfCountry) proxyHeaders.set('X-Zenovay-CF-Country', cfCountry)
172
- if (cfCity) proxyHeaders.set('X-Zenovay-CF-City', cfCity)
173
- if (cfRegion) proxyHeaders.set('X-Zenovay-CF-Region', cfRegion)
174
- if (cfLatitude) proxyHeaders.set('X-Zenovay-CF-Latitude', cfLatitude)
175
- if (cfLongitude) proxyHeaders.set('X-Zenovay-CF-Longitude', cfLongitude)
176
- if (cfTimezone) proxyHeaders.set('X-Zenovay-CF-Timezone', cfTimezone)
177
-
178
- // Remove headers that shouldn't be forwarded.
179
- proxyHeaders.delete('Host')
180
- proxyHeaders.delete('CF-Connecting-IP')
181
- proxyHeaders.delete('CF-RAY')
182
- proxyHeaders.delete('CF-Visitor')
183
- proxyHeaders.delete('CF-IPCountry')
184
- proxyHeaders.delete('CF-Worker')
185
-
186
- // Prepare request options. redirect:'manual' so the proxy never follows an
187
- // upstream redirect to an unexpected origin (defense-in-depth).
188
- const requestInit: RequestInit = {
189
- method: request.method,
190
- headers: proxyHeaders,
191
- redirect: 'manual',
192
- }
193
-
194
- // Forward the body for POST/PUT/PATCH requests.
195
- if (request.method === 'POST' || request.method === 'PUT' || request.method === 'PATCH') {
196
- requestInit.body = await request.arrayBuffer()
197
- }
198
-
199
- // Forward the request to the API with a 5s timeout — tracking is
200
- // fire-and-forget, so a slow/hung upstream must never block the visitor's
201
- // page. On timeout we return a fast 204 (see the catch below).
202
- const ctl = new AbortController()
203
- const timer = setTimeout(() => ctl.abort(), 5000)
204
- let response: Response
205
- try {
206
- response = await fetch(targetUrl, {
207
- ...requestInit,
208
- signal: ctl.signal,
209
- cf: {
210
- // Bypass cache for scripts to ensure fresh versions.
211
- cacheTtl: path.endsWith('.js') || path.includes('script') ? 0 : 60,
212
- cacheEverything: false,
213
- },
214
- } as RequestInit)
215
- } finally {
216
- clearTimeout(timer)
217
- }
218
-
219
- // Clone response headers.
220
- const responseHeaders = new Headers(response.headers)
221
-
222
- // Add proxy identification.
223
- responseHeaders.set('X-Zenovay-Proxied', 'true')
224
-
225
- // For scripts, ensure the proper content type and no caching.
226
- if (path.endsWith('.js') || path.includes('script') || path.includes('load')) {
227
- responseHeaders.set('Content-Type', 'application/javascript; charset=utf-8')
228
-
229
- // Don't cache scripts so the latest API config (apiUrl, trackingCode) is
230
- // always served.
231
- responseHeaders.set('Cache-Control', 'no-cache, no-store, must-revalidate')
232
- }
233
-
234
- // CORS headers for the proxied response.
235
- responseHeaders.set('Access-Control-Allow-Origin', '*')
236
- responseHeaders.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
237
- responseHeaders.set('Access-Control-Allow-Headers', 'Content-Type, X-Zenovay-Tracking-Code')
238
-
239
- // Return the proxied response.
240
- return new Response(response.body, {
241
- status: response.status,
242
- statusText: response.statusText,
243
- headers: responseHeaders,
244
- })
245
- } catch (error) {
246
- // Timeout/abort → fail fast + silent (204) so tracking never blocks the page.
247
- if (error instanceof Error && error.name === 'AbortError') {
248
- return new Response(null, {
249
- status: 204,
250
- headers: { 'Access-Control-Allow-Origin': '*' },
251
- })
252
- }
253
- console.error('[Zenovay First-Party Proxy] Error:', error)
254
-
255
- return new Response(
256
- JSON.stringify({
257
- error: 'Proxy error',
258
- message: error instanceof Error ? error.message : 'Unknown error',
259
- }),
260
- {
261
- status: 502,
262
- headers: {
263
- 'Content-Type': 'application/json',
264
- 'Access-Control-Allow-Origin': '*',
265
- },
266
- }
267
- )
268
- }
269
- }
270
-
271
- /**
272
- * Handle GET requests specifically.
273
- */
274
- export async function onRequestGet(context: EventContext): Promise<Response> {
275
- return onRequest(context)
276
- }
277
-
278
- /**
279
- * Handle POST requests specifically.
280
- */
281
- export async function onRequestPost(context: EventContext): Promise<Response> {
282
- return onRequest(context)
283
- }
284
-
285
- /**
286
- * Handle OPTIONS requests specifically (CORS preflight).
287
- */
288
- export async function onRequestOptions(_context: EventContext): Promise<Response> {
289
- return new Response(null, {
290
- status: 204,
291
- headers: {
292
- 'Access-Control-Allow-Origin': '*',
293
- 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
294
- 'Access-Control-Allow-Headers': 'Content-Type, X-Zenovay-Tracking-Code',
295
- 'Access-Control-Max-Age': '86400',
296
- },
297
- })
298
- }
299
- `}async function mn(e,t){let n=(t.apiBase||fn).replace(/\/+$/,``),r=x.join(e,`functions`,`api`,`_z`),i=x.join(r,`[[path]].ts`);try{return await S.access(i),{file:i,action:`exists`}}catch{}return await S.mkdir(r,{recursive:!0}),await S.writeFile(i,pn(n),`utf8`),{file:i,action:`created`}}const hn=`https://api.zenovay.com`,gn=[`next.config.js`,`next.config.mjs`,`next.config.ts`];function _n(e){return` // Zenovay first-party proxy — forwards /api/_z/* to the tracking API
300
- {
301
- source: '/api/_z/:path*',
302
- destination: '${e}/fp/:path*',
303
- },`}function vn(e){return`/** @type {import('next').NextConfig} */
304
- const nextConfig = {
305
- async rewrites() {
306
- return [
307
- ${_n(e)}
308
- ];
309
- },
310
- };
311
-
312
- export default nextConfig;
313
- `}async function yn(e,t={}){let n=t.apiBase??hn,r=null;for(let t of gn){let n=x.join(e,t);try{await k.access(n),r=n;break}catch{}}if(!r){let t=x.join(e,`next.config.mjs`);return await k.writeFile(t,vn(n),`utf8`),{file:t,action:`created`}}let i=await k.readFile(r,`utf8`);if(i.includes(`/api/_z/:path*`)||i.includes(`/_z/:path*`))return{file:r,action:`updated`};if(/\brewrites\s*(?::|=|\()/.test(i)||/\bredirects\s*\(/.test(i))return{file:r,action:`manual`};let a=i.match(/(?:module\.exports\s*=\s*|export\s+default\s+|const\s+\w+\s*(?::\s*[^={\n]{1,80})?=\s*)\{/);if(!a||a.index===void 0)return{file:r,action:`manual`};let o=a.index+a[0].length-1,s=i.slice(0,o+1),c=i.slice(o+1),l=`
314
- async rewrites() {
315
- return [
316
- ${_n(n)}
317
- ];
318
- },`,u=`${s}${l}${c}`;return await k.writeFile(r,u,`utf8`),{file:r,action:`updated`}}const bn=`https://api.zenovay.com`;async function xn(e,t={}){let n=t.apiBase??bn,r=x.join(e,`vercel.json`),i={source:`/api/_z/(.*)`,destination:`${n}/fp/$1`},a=null;try{a=await k.readFile(r,`utf8`)}catch{a=null}if(a===null){let e={rewrites:[i]};return await k.writeFile(r,`${JSON.stringify(e,null,2)}\n`,`utf8`),{file:r,action:`created`}}let o;try{o=JSON.parse(a)}catch{throw Error(`Cannot parse existing vercel.json at ${r}: invalid JSON`)}if(typeof o!=`object`||!o||Array.isArray(o))throw Error(`Cannot merge into vercel.json at ${r}: top-level value is not a JSON object`);let s=Array.isArray(o.rewrites)?o.rewrites:[],c=s.some(e=>typeof e?.source==`string`&&(e.source.startsWith(`/api/_z`)||e.source.startsWith(`/_z`)));return c?{file:r,action:`exists`}:(o.rewrites=[...s,i],await k.writeFile(r,`${JSON.stringify(o,null,2)}\n`,`utf8`),{file:r,action:`updated`})}const Sn=`https://api.zenovay.com`;async function Cn(e){let t=x.join(e,`_redirects`),n=x.join(e,`public`,`_redirects`);for(let e of[t,n])try{return await k.access(e),e}catch{}try{let t=await k.stat(x.join(e,`public`));if(t.isDirectory())return n}catch{}return t}async function wn(e,t={}){let n=t.apiBase??Sn,r=await Cn(e),i=`/api/_z/* ${n}/fp/:splat 200`,a=null;try{a=await k.readFile(r,`utf8`)}catch{a=null}if(a===null)return await k.mkdir(x.dirname(r),{recursive:!0}),await k.writeFile(r,`# Zenovay first-party proxy — forwards /api/_z/* to the tracking API\n${i}\n`,`utf8`),{file:r,action:`created`};let o=a.split(/\r?\n/).some(e=>{let t=e.trim();return t.length>0&&!t.startsWith(`#`)&&(t.startsWith(`/api/_z/`)||t.startsWith(`/_z/`))});if(o)return{file:r,action:`exists`};let s=`# Zenovay first-party proxy — forwards /api/_z/* to the tracking API`,c=a.split(/\r?\n/),l=c.findIndex(e=>{let t=e.trim();return t.length===0||t.startsWith(`#`)?!1:t.split(/\s+/)[0]===`/*`}),u;if(l>=0)c.splice(l,0,s,i),u=c.join(`
319
- `),u.endsWith(`
320
- `)||(u+=`
321
- `);else{let e=a.length>0&&!a.endsWith(`
322
- `)?`
323
- `:``;u=`${a}${e}${s}\n${i}\n`}return await k.writeFile(r,u,`utf8`),{file:r,action:`updated`}}const Tn="Your tracker is already live and working — it counts visitors in Chrome, Firefox and most browsers, no further setup required. First-party tracking is OPTIONAL and adds the rest: Safari, Brave, and browsers with strict tracking prevention block analytics loaded from another company's domain, so to capture those visitors too you serve Zenovay from your OWN domain. That last step is wired at your hosting provider — enable it any time with `zenovay init --host cloudflare-pages` (or `vercel` / `netlify` / `nextjs`).";async function En(e,t){let{trackingCode:n,apiBase:r,forceHost:i}=t,a=`unknown`,o=null,s=`skipped`,c=null,l=!1;try{switch(a=i&&i!==`unknown`?i:(await un(e)).host,a){case`cloudflare-pages`:{let t=await mn(e,{apiBase:r});o=t.file,s=t.action;break}case`nextjs-server`:{let t=await yn(e,{apiBase:r});o=t.file,s=t.action,t.action===`manual`&&(c=`Your tracker is live. To also count Safari/Brave visitors, add this rewrite to ${t.file} yourself (its shape couldn't be edited automatically): { source: '/api/_z/:path*', destination: 'https://api.zenovay.com/fp/:path*' }.`);break}case`vercel`:{let t=await xn(e,{apiBase:r});o=t.file,s=t.action;break}case`netlify`:{let t=await wn(e,{apiBase:r});o=t.file,s=t.action;break}case`unknown`:default:s=`skipped`,c=Tn;break}}catch(e){o=null,s=`skipped`,c=`${Tn} (auto-setup hit an error: ${e.message.slice(0,120)})`}let u=o!==null&&s!==`manual`&&s!==`skipped`;if(u)try{let t=await d(e,{trackingCode:n});l=t.swapped}catch{l=!1}return{host:a,proxyFile:o,proxyAction:s,snippetSwapped:l,manual:c}}const Dn=`\x1B]8;;`,On=`\x07`;function kn(){return process.env.FORCE_HYPERLINK?!0:!(process.env.NO_COLOR||!process.stdout.isTTY||process.env.CI||(process.env.TERM??``)===`dumb`)}function An({url:e,label:t,color:n,arrow:r=!0}){let{theme:i}=g(),a=n??i.fg,o=(t??e)+(r?` ↗`:``);return kn()?A.createElement(E,{color:a,underline:!0},Dn,e,On,o,Dn,On):t&&t!==e?A.createElement(E,{color:a},A.createElement(E,{underline:!0},t),A.createElement(E,{color:i.dim},` (`,e,`)`)):A.createElement(E,{color:a,underline:!0},e)}function Y({label:e,value:t,labelWidth:n=12}){let{theme:r}=g();return A.createElement(T,{flexDirection:`row`},A.createElement(T,{width:n,flexShrink:0},A.createElement(E,{color:r.dim},e.toUpperCase())),typeof t==`string`?A.createElement(E,{color:r.fg},t):t)}function jn(e){return e.review&&process.stdout.isTTY?`interactive`:`auto`}function Mn(e){let t=null,n=null,r=!1,i=!1,a=0,o=new Set,s=()=>{for(let e of o)e(t)};return{async approve(o){if(i)return`n`;if(e.mode===`auto`||r)return`y`;let c=String(++a);return new Promise(e=>{t={id:c,...o},n=t=>{t===`a`&&(r=!0),e(t)},s()})},subscribe(e){return o.add(e),()=>{o.delete(e)}},current(){return t},resolve(e,r){if(!t||t.id!==e||!n)return;let i=n;t=null,n=null,s(),i(r)},abort(){if(i=!0,n){let e=n;t=null,n=null,s(),e(`n`)}}}}function Nn(){let e=[12,15,18,22,28,35,41,50,58,64,72,78],t=b(e,24);return[` ↑`,` ${t}`,` └────────────────────────`,` May Jun Jul Aug Sep`]}function Pn(){return[` Landing page ████████████████████ 100%`,` ↓ -28%`,` Pricing ██████████████░░░░░░ 72%`,` ↓ -50%`,` Checkout ███████░░░░░░░░░░░░░ 36%`,` ↓ -64%`,` Purchased ███░░░░░░░░░░░░░░░░░ 13%`]}function Fn(){return[` ▇▇▇▇▇▇▇▇▇▎ 89 Sarah K. /pricing 🇺🇸`,` ▇▇▇▇▇▇░░░░ 61 anon /docs 🇩🇪`,` ▇▇▇░░░░░░░ 34 anon /changelog 🇯🇵`]}function In(){return[` LCP ● 2.1s good ████████████░░░░░░`,` INP ● 89ms good ██████████████████`,` CLS ⚠ 0.14 needs ████████████░░░░░░`,` TTFB ● 380ms good ███████████████░░░`]}const Ln=[{title:`Welcome`,body:[`The wizard is an agent — it handles the entire`,`Zenovay setup process on your behalf.`,``,`Reading your project, deciding where the tracker`,`belongs, and writing the snippet for you.`]},{title:`Events`,body:[`Events are the foundation of Zenovay analytics.`,``,`Every pageview, click, and custom action is an`,`event. Group them into Goals to track conversions.`]},{title:`Trends`,body:[`Use trends to measure growth.`,``,`See how visitors, signups, and revenue have`,`changed over the last week, month, or quarter.`],visual:Nn},{title:`Funnels`,body:[`Funnels reveal where users drop off.`,``,`Define the steps you care about — landing,`,`pricing, checkout, purchase — and Zenovay shows`,`the per-step conversion rate.`],visual:Pn},{title:`Live visitors`,body:[`Watch every visitor in real time, ranked by an`,`AI score that highlights high-intent traffic.`,``,"Use `zenovay visitors --live` after install."],visual:Fn},{title:`Core Web Vitals`,body:[`LCP, INP, CLS — Google's page-experience metrics,`,`collected automatically once the tracker is in.`,``,"Use `zenovay vitals` to see them per page + device."],visual:In},{title:`MCP integration`,body:[`Your CLI session can install Zenovay's MCP server`,`into Cursor / Claude Desktop / VS Code.`,``,`Then ask your AI: "what were my top pages today?"`,`and it queries Zenovay directly.`]},{title:`AI insights`,body:[`Zenovay watches your data and surfaces anomalies`,`automatically — traffic spikes, error bursts,`,`revenue drops — without you needing to ask.`,``,"Run `zenovay ai` after install to chat with them."]},{title:`Privacy-first`,body:[`No cookies required. No third-party trackers.`,`Cookieless mode is one toggle in your dashboard.`,``,`GDPR, CCPA, and PECR-compliant out of the box.`]}],Rn=11e3,zn=9,Bn=({width:e,height:t})=>{let{theme:n}=g(),[r,i]=N(0);j(()=>{if(Ln.length<=1)return;let e=setInterval(()=>{i(e=>(e+1)%Ln.length)},Rn);return()=>clearInterval(e)},[]);let a=Ln[r],o=a.visual?a.visual():[];return A.createElement(T,{flexDirection:`column`,width:e,height:t,paddingX:2,paddingY:1},A.createElement(T,{marginBottom:1},A.createElement(E,{color:n.typography.label.color,dimColor:n.typography.label.dim},`LEARN`)),A.createElement(T,{flexDirection:`column`,minHeight:zn,key:r},A.createElement(T,{marginBottom:1},A.createElement(E,{bold:!0,color:n.fg,wrap:`truncate`},a.title)),a.body.map((e,t)=>A.createElement(E,{key:t,color:n.muted,wrap:`truncate`},e||` `)),o.length>0&&A.createElement(T,{flexDirection:`column`,marginTop:1},o.map((e,t)=>A.createElement(E,{key:t,color:n.accent},e)))),A.createElement(T,{flexGrow:1}),A.createElement(T,{marginTop:1},A.createElement(E,null,Ln.map((e,t)=>A.createElement(E,{key:t,color:t===r?n.muted:n.dim},t===r?`─`:`·`)))))},Vn={pending:`·`,active:`⠋`,done:`✓`,error:`✗`};function Hn(e,t){switch(e){case`pending`:return t.dim;case`active`:return t.accent;case`done`:return t.success;case`error`:return t.error}}const Un=({tasks:e,width:t,height:n,liveLine:r})=>{let{theme:i}=g();return A.createElement(T,{flexDirection:`column`,width:t,height:n,paddingX:2,paddingY:1},A.createElement(T,{marginBottom:1},A.createElement(E,{color:i.typography.label.color,dimColor:i.typography.label.dim},`TASKS`)),e.map(e=>A.createElement(T,{key:e.id,flexDirection:`column`},A.createElement(T,{flexDirection:`row`},e.status===`active`?A.createElement(E,{color:i.accent},A.createElement(F,{type:`dots`})):A.createElement(E,{color:Hn(e.status,i)},Vn[e.status]),A.createElement(E,null,` `),A.createElement(E,{color:e.status===`pending`?i.muted:i.fg,wrap:`truncate`},e.label)),e.detail&&A.createElement(T,{paddingLeft:2},A.createElement(E,{color:i.dim,wrap:`truncate`},e.detail)))),A.createElement(T,{flexGrow:1}),r&&A.createElement(T,{flexDirection:`row`,marginTop:1},A.createElement(E,{color:i.accent},`◆ `),A.createElement(E,{color:i.fg,wrap:`truncate`},r)))};async function Wn(e){if(s(e))return Gn(e);let t=`quit`,n=null,r=Promise.resolve(),i=await new Promise(i=>{let{unmount:a,waitUntilExit:o}=D(A.createElement(Kn,{opts:e,onExit:(e,r,o)=>{t=r??`quit`,n=o??null,a(),i(e)}}),{exitOnCtrlC:!0});r=o(),r.catch(()=>i(1))});await r.catch(()=>{});let a=i===0&&t!==`quit`&&!!n;if(i===0&&!a&&await p().catch(()=>void 0),i!==0||t===`quit`||!n)return i;let o=n.id,c=t===`watch`?[`overview`,`--site-id`,o]:[`events`,`tail`,`--site-id`,o],{spawnSync:l}=await import(`node:child_process`),{realpathSync:u}=await import(`node:fs`),{buildPostInstallReexec:d}=await import(`./ensure-latest-B3P4wX40.js`),{cmd:f,args:m}=d({execPath:process.execPath,argv1:process.argv[1]??``,sub:c,resolveSymlink:u});await new Promise(e=>setImmediate(e));let h=l(f,m,{stdio:`inherit`});if(h.error){let e=t===`watch`?`overview`:`events tail`;return process.stderr.write(`Run \`zenovay ${e} --site-id ${o}\` to continue.\n`),0}return h.status??0}async function Gn(t){let r=await import(`./telemetry-CX5wsUWl.js`).catch(()=>null);r?.emit(`install.start`,{properties:{mode:`headless`}});try{let s=await e(),c=await ut(t.cwd);if(!c)return o({type:`error`,code:`no_framework`,message:`Could not detect framework (headless mode has no picker).`}),r?.emit(`install.error`,{error_code:`no_framework`,properties:{mode:`headless`}}),2;o({type:`framework.detected`,framework:c.id,confidence:1}),r?.emit(`install.framework_detected`,{properties:{framework:c.id}});let l=await i({strict:!1});if(!l&&!process.env.ZENOVAY_API_TOKEN)return o({type:`error`,code:`not_logged_in`,message:"Run `zenovay login` first (or set ZENOVAY_API_TOKEN)."}),2;let u=new n({config:s,cliVersion:t.cliVersion,token:l}),[d,f]=await Promise.all([u.getSites(),a(t.cwd,``).catch(()=>null)]),p;if(t.siteId){if(p=d.find(e=>e.id===t.siteId),!p)return o({type:`error`,code:`site_not_found`,message:`Site ${t.siteId} not found.`}),2}else if(f?.foundTrackingCodes.length){for(let e of f.foundTrackingCodes){let t=d.find(t=>t.trackingCode===e);if(t){p=t;break}}p||=d[0]}else p=d[0];if(!p)return o({type:`error`,code:`no_site`,message:`No sites exist; create one at app.zenovay.com or re-run interactively.`}),2;let m=p.trackingCode??p.id;if(f&&(f.recommendation===`no-op`||f.foundTrackingCodes.includes(m)))return o({type:`info`,message:`Zenovay already installed correctly for ${p.name} (${m})`}),o({type:`done`,command:`init`,exitCode:0}),0;o({type:`info`,message:`Using site ${p.id} (${p.name}) trackingCode=${p.trackingCode??p.id}`});let h=p.trackingCode??p.id;if(!K(h))return o({type:`error`,code:`invalid_tracking_code`,message:`tracking code "${h}" has an unexpected format; aborting to avoid broken markup`}),1;if(c.id===`plain-html`){let e=await Vt({cwd:t.cwd,trackingCode:h,updateOnly:f?.recommendation===`update-tracking-code`});if(e.installed.length===0&&e.skipped.length===0)return o({type:`error`,code:`install_failed`,message:`No .html files with a <head> block found to inject the tracker into (errors: ${e.errors.length}).`}),r?.emit(`install.error`,{error_code:`install_failed`,properties:{mode:`headless`,framework:c.id}}),o({type:`done`,command:`init`,exitCode:1}),1;o({type:`info`,message:`tracker injected into ${e.installed.length} file(s); ${e.skipped.length} already current; ${e.errors.length} error(s)`})}else if(c.id===`next-app-router`){let e=await Qt({cwd:t.cwd,trackingCode:h});if(e.fellThrough||e.errors.length>0)return o({type:`error`,code:`headless_framework_unsupported`,message:"This Next.js project has a structure the headless installer can't edit safely (no standard document-shell layout found). Run `zenovay init` interactively — the wizard places the tracker in the correct file. Nothing was modified."}),r?.emit(`install.error`,{error_code:`headless_framework_unsupported`,properties:{mode:`headless`,framework:c.id}}),o({type:`done`,command:`init`,exitCode:1}),1;o({type:`info`,message:`tracker inserted: ${e.installed[0]??`already installed — nothing to change`}`})}else{let e=await nn({cwd:t.cwd,trackingCode:h,siteId:p.id,adapter:c}),n=e.skipped.some(e=>/already installed|tracker present/i.test(e.reason));if(e.fellThrough||e.errors.length>0||e.installed.length===0&&!n)return o({type:`error`,code:`headless_framework_unsupported`,message:`${c.displayName}'s tracker insert isn't a mechanical edit the headless mode can apply safely for this project shape. Run \`zenovay init\` interactively — the wizard uses a deterministic fast path and falls back to the AI installer only where judgement is needed. Nothing was modified.`}),r?.emit(`install.error`,{error_code:`headless_framework_unsupported`,properties:{mode:`headless`,framework:c.id}}),o({type:`done`,command:`init`,exitCode:1}),1;o({type:`info`,message:`tracker inserted: ${e.installed[0]??`already installed — nothing to change`}`})}let g=await W(t.cwd,{[c.envVarName]:h});if(g.addedKeys.length>0&&o({type:`info`,message:`env vars added: ${g.addedKeys.join(`,`)}`}),t.firstParty!==!1){let e=await En(t.cwd,{trackingCode:h,forceHost:dn(t.host)});e.proxyFile&&e.proxyAction!==`manual`&&e.proxyAction!==`skipped`?o({type:`info`,message:`first-party tracking enabled — analytics now load from your own domain (${e.proxyFile}), so visitors on Safari/Brave and other strict-privacy browsers are counted too`}):e.manual&&o({type:`info`,message:e.manual})}else o({type:`info`,message:"first-party tracking skipped (--no-first-party) — enable it later with `zenovay init --host <cloudflare-pages|vercel|netlify|nextjs>`"});return o({type:`done`,command:`init`,exitCode:0}),r?.emit(`install.success`,{properties:{framework:c.id,mode:`headless`,env_keys_added:g.addedKeys.length}}),0}catch(e){return o({type:`error`,code:`init_failed`,message:e.message}),r?.emit(`install.error`,{error_code:`init_failed`,properties:{mode:`headless`,error:(e.message??`unknown`).slice(0,128)}}),1}}const Kn=({opts:t,onExit:r})=>{let{exit:o}=re(),{theme:s}=g(),[c,l]=N(`intro`),[u,d]=N(null),[p,_]=N([]),[v,y]=N(null),[b,x]=N(null),[S,C]=N(null),[te,w]=N([]),[ne,D]=N(void 0),[k,P]=N(null),[ie,I]=N(null),[ae,L]=N(null),[oe,se]=N(0),[ce,R]=N(!1),[z,B]=N(null),V=M(null),le=M(!1),[ue,de]=N(!1),[fe,pe]=N(void 0),H=M(null),U=A.useCallback(e=>new Promise(t=>{H.current=t,pe(e),de(!0)}),[]),me=A.useCallback(e=>{de(!1);let t=H.current;H.current=null,t?.(e)},[]);return O((e,t)=>{c===`error`&&(e.toLowerCase()===`q`||t.escape)&&(o(),r(1))}),j(()=>{let e=process.env.TERM_PROGRAM===`vscode`,t=!!process.stdout.isTTY&&!e;return t&&process.stdout.write(`\x1B[?1049h\x1B[H`),()=>{V.current?.abort(),H.current?.(null),H.current=null,t&&process.stdout.write(`\x1B[?1049l`)}},[]),j(()=>{le.current||(le.current=!0,(async()=>{try{l(`detecting`);let r=await ut(t.cwd);if(!r){C(`Could not detect your framework. Supported: Next.js, Nuxt, SvelteKit, Astro, Remix, plain HTML.`),l(`error`);return}d(r);let o=await i({strict:!1});!process.env.ZENOVAY_API_TOKEN&&!o&&(l(`login`),await f({cliVersion:t.cliVersion,offerCompletions:!1})),l(`loading-sites`);let s=await e(),c=await i({strict:!1}),u=new n({config:s,cliVersion:t.cliVersion,token:c}),[p,m]=await Promise.all([u.getSites(),a(t.cwd,``).catch(()=>null)]),h=await pr(t.cwd);if(_(p),y(h),p.length===0){l(`create-site`);return}if(m?.foundTrackingCodes.length)for(let e of m.foundTrackingCodes){let t=p.find(t=>t.trackingCode===e);if(t){x(t),l(`already-installed`);return}}if(t.siteId){let e=p.find(e=>e.id===t.siteId);if(!e){C(`Site ${t.siteId} not found in your account.`),l(`error`);return}x(e),Yn(e,r,t,{setPhase:l,setErrorMsg:C,setTasks:w,setLiveLine:D,setSandboxStats:P,setVerifyResult:I,setFirstParty:L,setPendingApproval:B,askHostChoice:U,registerBridge:e=>{V.current=e}});return}let g=mr(p,h);if(t.yes&&g){x(g),Yn(g,r,t,{setPhase:l,setErrorMsg:C,setTasks:w,setLiveLine:D,setSandboxStats:P,setVerifyResult:I,setFirstParty:L,setPendingApproval:B,askHostChoice:U,registerBridge:e=>{V.current=e}});return}l(`site-picker`)}catch(e){C(e.message),l(`error`)}})())},[]),j(()=>{c===`error`&&(V.current?.abort(),setTimeout(()=>{o(),r(1)},8e3))},[c]),A.createElement(T,{flexDirection:`column`},A.createElement(m,{version:t.cliVersion,subtitle:`AI install wizard`}),c===`intro`&&A.createElement(Xn,null),c===`detecting`&&A.createElement(h,{title:`Scanning`,state:`busy`},A.createElement(T,null,A.createElement(E,{color:s.accent},A.createElement(F,{type:`dots`})),A.createElement(E,null,` Detecting framework…`))),c===`login`&&A.createElement(h,{title:`Authenticating`,state:`busy`},A.createElement(E,null,`Opening browser for login… (paste ZENOVAY_API_TOKEN env var to skip)`)),c===`loading-sites`&&A.createElement(h,{title:`Loading your sites`,state:`busy`},A.createElement(T,null,A.createElement(E,{color:s.accent},A.createElement(F,{type:`dots`})),A.createElement(E,null,` Fetching your Zenovay sites…`))),c===`already-installed`&&b&&A.createElement($n,{site:b,onContinue:()=>{l(`site-picker`)},onExit:()=>{o(),r(0,`quit`,b)}}),c===`site-picker`&&u&&A.createElement(er,{sites:p,preselectHint:v,onPick:e=>{if(e===`create-new`){l(`create-site`);return}x(e),Yn(e,u,t,{setPhase:l,setErrorMsg:C,setTasks:w,setLiveLine:D,setSandboxStats:P,setVerifyResult:I,setFirstParty:L,setPendingApproval:B,askHostChoice:U,registerBridge:e=>{V.current=e}})}}),c===`create-site`&&A.createElement(h,{title:`Create a new site`,state:`warn`},A.createElement(E,{color:s.warn},"No site picked (or none exist yet). Visit https://app.zenovay.com/websites to create one, then re-run `zenovay init`."),A.createElement(E,{color:s.muted},`(Inline site creation from the CLI is scheduled for V1.1 — it requires a plan-limit check.)`)),c===`agent`&&u&&b&&A.createElement(Qn,{adapter:u,site:b,tasks:te,liveLine:ne,pendingApproval:z,onApprove:e=>{z&&V.current?.resolve(z.id,e)},pendingHostChoice:ue,hostChoiceNote:fe,onHostChoice:me}),c===`install-complete`&&u&&b&&A.createElement(rr,{adapter:u,site:b,stats:k,verify:ie,firstParty:ae,onCommit:()=>l(`commit-prompt`),onSkipCommit:()=>l(`deploy-prompt`)}),c===`commit-prompt`&&b&&A.createElement(ar,{cwd:t.cwd,onDone:e=>{e.committed&&D(`Pushed ${e.shortSha} to ${e.branch}`),l(`deploy-prompt`)},onError:e=>{C(e),l(`error`)}}),c===`deploy-prompt`&&b&&A.createElement(or,{site:b,onDeployed:()=>l(`visit-prompt`),onSkip:()=>l(t.skipVerify?`success`:`verify`)}),c===`visit-prompt`&&b&&A.createElement(sr,{site:b,onContinue:()=>l(t.skipVerify?`success`:`verify`)}),c===`verify`&&b&&A.createElement(lr,{site:b,elapsed:oe,onTick:e=>se(e),onArrived:()=>{R(!0),l(`success`)},onTimeout:()=>l(`success`)}),c===`success`&&u&&b&&A.createElement(nr,{adapter:u,site:b,stats:k,arrived:ce,firstParty:ae,onPick:e=>{o(),r(0,e,b)}}),c===`error`&&A.createElement(h,{title:`Install failed`,state:`err`},A.createElement(E,{color:s.error},S??`Unknown error`)),A.createElement(ee,{items:c===`already-installed`?[{key:`q`,label:`quit`},{key:`r`,label:`re-run wizard`},{key:`ctrl-c`,label:`abort`}]:[{key:`q`,label:`quit`},{key:`ctrl-c`,label:`abort`}]}))};async function X(e,t,n){if(e.firstParty===!1){n.setFirstParty?.({host:`unknown`,proxyFile:null,proxyAction:`skipped`,snippetSwapped:!1,manual:"First-party tracking skipped (--no-first-party). Safari/Brave and other strict-privacy setups block third-party analytics — add all-browser coverage any time with `zenovay init --host <cloudflare-pages|vercel|netlify|nextjs>`."});return}if(!n.setFirstParty)return;n.setTasks(e=>e.some(e=>e.id===`first-party`)?e.map(e=>e.id===`first-party`?{...e,status:`active`}:e):[...e,{id:`first-party`,label:`Set up first-party tracking (all browsers)`,status:`active`}]),n.setLiveLine(`Setting up first-party tracking (all browsers)…`);let r=dn(e.host),i=null;try{if(i=await En(e.cwd,{trackingCode:t,forceHost:r}),n.setFirstParty(i),i.host===`unknown`&&!r&&n.askHostChoice){n.setLiveLine(`Where do you deploy this site? (enables all-browser tracking)`);let r=e.host?`Unrecognized --host "${e.host}" — pick your host below.`:void 0,a=await n.askHostChoice(r);a&&(n.setLiveLine(`Setting up first-party tracking…`),i=await En(e.cwd,{trackingCode:t,forceHost:a}),n.setFirstParty(i))}}catch{i={host:`unknown`,proxyFile:null,proxyAction:`skipped`,snippetSwapped:!1,manual:"First-party setup hit an error — your standard tracker is active; add all-browser coverage later with `zenovay init --host <cloudflare-pages|vercel|netlify|nextjs>`."},n.setFirstParty(i)}let a=qn(i);n.setTasks(e=>e.map(e=>e.id===`first-party`?{...e,status:`done`,detail:a}:e)),n.setLiveLine(void 0)}function qn(e){return e?e.proxyFile&&e.proxyAction!==`manual`&&e.proxyAction!==`skipped`?`now loads from your domain (${x.basename(e.proxyFile)})`:e.manual?`standard tracking active — see note below for all-browser coverage`:`standard tracking active`:`standard tracking active`}function Z(e){return e&&e.installed.length>0?e.installed.join(`, `):e&&e.errors.length>0?`failed: ${e.errors[0]?.message??`unknown error`}`:`none detected`}async function Jn(e,t,n){n.setLiveLine(`Verifying the tracker is in your source…`);try{let r=await a(e,t),i=r.recommendation===`no-op`&&r.foundTrackingCodes.includes(t);n.setVerifyResult?.({ok:i,detail:i?`Tracker confirmed in your source files`:`Couldn't auto-confirm the tracker (diagnosis: ${r.recommendation}) — please double-check`})}catch{n.setVerifyResult?.({ok:!1,detail:`Verification check could not run`})}n.setLiveLine(void 0)}async function Yn(r,o,s,c){try{c.setPhase(`agent`);let l=await e(),u=await i({strict:!1}),d=new n({config:l,cliVersion:s.cliVersion,token:u}),f=new V({cwd:s.cwd}),p=r.trackingCode??r.id;if(!K(p)){c.setErrorMsg(`The resolved tracking code "${p}" has an unexpected format (expected letters, digits, "_" or "-"). Aborting to avoid writing broken markup — re-check the site in your dashboard.`),c.setPhase(`error`);return}await t({defaultSiteId:r.id,defaultSiteName:r.name}).catch(()=>void 0);let m=await a(s.cwd,p);if(m.recommendation===`no-op`){c.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:`done`,detail:`already installed correctly`}:e)),c.setLiveLine(m.summary),c.setSandboxStats?.({reads:0,writes:0,rounds:0}),!s.skipMcp&&u&&await G({accessToken:u.accessToken}).catch(()=>void 0),c.setVerifyResult?.({ok:!0,detail:`Already installed correctly`}),await X(s,p,c),c.setPhase(`install-complete`);return}if(m.competitors.length>0&&c.setLiveLine(`Detected ${m.competitors.map(e=>e.name).join(`, `)} — will install Zenovay alongside (won't touch their tags).`),o.id===`next-app-router`){c.setTasks([{id:`detect`,label:`Detect framework`,status:`done`,detail:`Next.js (App Router)`},{id:`read`,label:`Find the document shell layout`,status:`active`},{id:`write`,label:`Insert tracker <Script>`,status:`pending`},{id:`env`,label:`Write env vars (.env.local)`,status:`pending`},{id:`mcp`,label:`Install MCP clients (Claude Code/Cursor/VS Code)`,status:`pending`},{id:`verify`,label:`Verify the tracker in your source`,status:`pending`}]),c.setLiveLine(`Next.js — locating the document shell layout…`);let e=await Qt({cwd:s.cwd,trackingCode:p});if(!e.fellThrough&&e.errors.length===0){let t=e.installed[0]??`already installed`;c.setTasks(e=>e.map(e=>e.id===`read`||e.id===`write`?{...e,status:`done`,detail:t}:e));let n=await W(s.cwd,{[o.envVarName]:p});if(c.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${n.addedKeys.length} key(s) added`}:e)),!s.skipMcp&&u){let e=await G({accessToken:u.accessToken}).catch(e=>({installed:[],skipped:[],errors:[{client:`mcp`,message:e.message}]}));c.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:Z(e)}:t))}else c.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await Jn(s.cwd,p,c),c.setTasks(e=>e.map(e=>e.id===`verify`?{...e,status:`done`}:e)),c.setSandboxStats?.({reads:1,writes:e.installed.length,rounds:0}),await X(s,p,c),c.setPhase(`install-complete`);return}c.setLiveLine(`Custom Next.js structure — handing off to the AI agent…`)}let h=o.id===`plain-html`;if(h){c.setTasks([{id:`detect`,label:`Detect framework`,status:`done`,detail:`Plain HTML`},{id:`read`,label:`Scan .html pages`,status:`active`},{id:`write`,label:`Insert tracker <script>`,status:`pending`},{id:`env`,label:`Write env vars`,status:`pending`},{id:`mcp`,label:`Install MCP clients (Claude Code/Cursor/VS Code)`,status:`pending`},{id:`verify`,label:`Verify the tracker in your source`,status:`pending`}]),c.setLiveLine(`Plain HTML — using fast install path (no AI needed)…`);let e=await Vt({cwd:s.cwd,trackingCode:p,updateOnly:m.recommendation===`update-tracking-code`});if(e.installed.length===0&&e.errors.length===0&&e.skipped.length===0)throw Error(`No .html files with a <head>...</head> block were found to inject the tracker into.`);if(e.installed.length===0&&e.errors.length>0)throw Error(`Programmatic install failed for all ${e.errors.length} file(s). First error: ${e.errors[0].file}: ${e.errors[0].error}`);c.setTasks(t=>t.map(t=>t.id===`read`||t.id===`write`?{...t,status:`done`,detail:`${e.installed.length} file(s)`}:t)),c.setLiveLine(`Tracker added to ${e.installed.length} file(s). Skipped ${e.skipped.length}, errored ${e.errors.length}.`);let t=await W(s.cwd,{[o.envVarName]:p});if(c.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${t.addedKeys.length} key(s) added`}:e)),!s.skipMcp&&u){let e=await G({accessToken:u.accessToken}).catch(e=>({installed:[],skipped:[],errors:[{client:`mcp`,message:e.message}]}));c.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:Z(e)}:t))}else c.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await Jn(s.cwd,p,c),c.setSandboxStats?.({reads:e.installed.length,writes:e.installed.length,rounds:0}),await X(s,p,c),c.setPhase(`install-complete`);return}{let e=await nn({cwd:s.cwd,trackingCode:p,siteId:r.id,adapter:o}),t=e.skipped.some(e=>/already installed|tracker present/i.test(e.reason));if(!e.fellThrough&&e.errors.length===0&&(e.installed.length>0||t)){c.setTasks([{id:`detect`,label:`Detect framework`,status:`done`,detail:o.displayName},{id:`write`,label:`Insert tracker snippet`,status:`done`,detail:e.installed[0]??`already installed`},{id:`env`,label:`Write env vars (.env.local)`,status:`active`},{id:`mcp`,label:`Install MCP clients (Claude Code/Cursor/VS Code)`,status:`pending`},{id:`verify`,label:`Verify the tracker in your source`,status:`pending`}]),c.setLiveLine(`${o.displayName} — using fast install path (no AI needed)…`);let t=await W(s.cwd,{[o.envVarName]:p});if(c.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${t.addedKeys.length} key(s) added`}:e)),!s.skipMcp&&u){let e=await G({accessToken:u.accessToken}).catch(e=>({installed:[],skipped:[],errors:[{client:`mcp`,message:e.message}]}));c.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:Z(e)}:t))}else c.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await Jn(s.cwd,p,c),c.setTasks(e=>e.map(e=>e.id===`verify`?{...e,status:`done`}:e)),c.setSandboxStats?.({reads:1,writes:e.installed.length,rounds:0}),await X(s,p,c),c.setPhase(`install-complete`);return}c.setLiveLine(`${o.displayName} needs a closer look — using the AI installer (a bit slower than the fast path)…`)}let g=o.buildSnippets({trackingCode:p,siteId:r.id}),_=`Install Zenovay tracking into this ${o.displayName} project.\nSite: ${r.name} (trackingCode: ${p}).\n1. Call detect_framework to confirm the framework.\n2. Read the entry file(s) for this framework:\n`+o.files.map(e=>` - ${e.path}`).join(`
324
- `)+`
325
- 3. Insert the tracker using the snippet below.
326
- 4. Confirm the change with a diff before writing.
327
-
328
- Snippet reference (anchored by anchorKind — adapt to the actual file):
329
- `+g.map(e=>` ${e.anchorKind} @ ${e.targetPath}:\n ${e.code.replace(/\n/g,`
330
- `)}`).join(`
331
-
332
- `);c.setTasks([{id:`detect`,label:`Detect framework`,status:`active`},{id:`read`,label:`Read project entry files`,status:`pending`},{id:`write`,label:`Insert tracker snippet`,status:`pending`},{id:`env`,label:`Write env vars (.env.local)`,status:`pending`},{id:`mcp`,label:`Install MCP clients (Claude Code/Cursor/VS Code)`,status:`pending`},{id:`verify`,label:`Wait for first event`,status:`pending`}]);let v=(e,t,n)=>{c.setTasks(r=>r.map(r=>r.id===e?{...r,status:t,detail:n??r.detail}:r))},y=Mn({mode:jn(s)});c.registerBridge(y);let ee=y.subscribe(e=>c.setPendingApproval(e)),b=null,x=``,S=0;try{await It({api:d,sandbox:f,approval:y,prompter:{async ask({question:e}){return e}},handlers:{onToolStart:({name:e})=>{e===`detect_framework`?(v(`detect`,`active`),c.setLiveLine(`Inspecting package.json + config files…`)):e===`read_file`?(v(`detect`,`done`),v(`read`,`active`)):(e===`write_file`||e===`patch_file`)&&(v(`read`,`done`),v(`write`,`active`))},onToolResult:({name:e,result:t})=>{let n=t?.ok!==!1,r=t?.content??{};e===`detect_framework`&&n&&(v(`detect`,`done`,o.displayName),c.setLiveLine(`Detected ${o.displayName}`)),e===`read_file`&&n&&r.path&&c.setLiveLine(`Read ${r.path}`),(e===`write_file`||e===`patch_file`)&&n&&r.path&&(v(`read`,`done`),v(`write`,`done`,`wrote ${r.path}`),c.setLiveLine(`Wrote ${r.path}`))},onDelta:e=>{x=(x+e).slice(-600);let t=Date.now();if(t-S<280)return;S=t;let n=x.replace(/\s+/g,` `).trim().slice(-80);n.length>4&&c.setLiveLine(n)}},initialMessages:[{role:`user`,content:_}],diagnosis:m,targetTrackingCode:p})}catch(e){b=e}finally{ee(),c.setPendingApproval(null)}let C=f.stats(),te=C.writes>0?await a(s.cwd,p).catch(()=>null):null,w=zt(C,te?.foundTrackingCodes??[],p,b);if(!w.ok)throw Error(w.error);v(`write`,`done`),v(`env`,`active`),c.setLiveLine(`Adding env var to .env.local`);let ne=await W(s.cwd,{[o.envVarName]:p});if(v(`env`,`done`,`${ne.addedKeys.length} key(s) added`),!s.skipMcp&&u){v(`mcp`,`active`),c.setLiveLine(`Detecting Cursor / Claude Desktop / VS Code…`);let e=await G({accessToken:u.accessToken}).catch(e=>({installed:[],skipped:[],errors:[{client:`mcp`,message:e.message}]}));v(`mcp`,`done`,Z(e))}else v(`mcp`,`done`,`skipped`);c.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:e.status===`pending`?`done`:e.status}:e)),await Jn(s.cwd,p,c),c.setSandboxStats?.(C),await X(s,p,c),c.setPhase(`install-complete`)}catch(e){c.setErrorMsg(e.message),c.setPhase(`error`)}}const Xn=()=>{let{theme:e}=g();return A.createElement(h,{title:`Zenovay wants to set up your project`,state:`idle`},A.createElement(E,null,`We'll use AI to analyze your codebase and add the Zenovay tracker.`),A.createElement(E,{color:e.muted},`.env* contents stay on your machine. Only framework metadata reaches api.zenovay.com.`))},Zn=({siteName:e,note:t,onChoose:n})=>{let{theme:r}=g(),i=[{label:`Cloudflare Pages`,value:`cloudflare-pages`,description:`writes functions/api/_z/[[path]].ts`},{label:`Vercel`,value:`vercel`,description:`adds a vercel.json rewrite`},{label:`Netlify`,value:`netlify`,description:`adds a _redirects rule`},{label:`Next.js (self-hosted)`,value:`nextjs-server`,description:`adds a next.config rewrite`},{label:`Skip — standard tracking only`,value:`skip`,description:`already works in Chrome, Firefox and most browsers`}];return A.createElement(T,{flexDirection:`column`,paddingX:2,paddingTop:1},A.createElement(E,{bold:!0},`Count visitors in every browser?`),t?A.createElement(E,{color:r.warn},t):null,A.createElement(E,{color:r.muted},`Your tracker already works. Safari, Edge and Brave block analytics loaded from another domain — serving Zenovay from your own domain fixes that. Where is `,e,` deployed?`),A.createElement(T,{marginTop:1},A.createElement(y,{items:i,onSelect:e=>n(e===`skip`?null:e)})))},Qn=({adapter:e,site:t,tasks:n,liveLine:r,pendingApproval:i,onApprove:a,pendingHostChoice:o,hostChoiceNote:s,onHostChoice:c})=>{let{theme:l}=g(),u=process.stdout.columns??100,d=(process.stdout.rows??30)-8,f=Math.floor(u/2)-1,p=Math.max(14,d);return A.createElement(T,{flexDirection:`column`},A.createElement(T,{flexDirection:`row`,minHeight:p,borderStyle:`round`,borderColor:l.border},A.createElement(T,{width:f,flexDirection:`column`},A.createElement(Bn,{width:f,height:p})),A.createElement(T,{width:1,flexDirection:`column`},A.createElement(E,{color:l.border},`│`)),A.createElement(T,{width:f,flexDirection:`column`},i?A.createElement(T,{flexDirection:`column`,paddingX:2,paddingTop:1},A.createElement(E,{color:l.warn},`The agent wants to write `,i.path),i.reason?A.createElement(E,{color:l.muted},i.reason):null,A.createElement(_,{key:i.id,filePath:i.path,oldContent:i.oldContent,newContent:i.newContent,onApprove:a})):o&&c?A.createElement(Zn,{siteName:t.name,note:s,onChoose:c}):A.createElement(A.Fragment,null,A.createElement(T,{paddingX:2,paddingTop:1},A.createElement(v,{done:n.filter(e=>e.status===`done`).length,total:n.length,label:n.find(e=>e.status===`active`)?.label})),A.createElement(Un,{tasks:n,liveLine:r,width:f,height:p})))),A.createElement(T,{marginTop:1},A.createElement(E,{color:l.muted},`Site: `,t.name,` · code: `,t.trackingCode??t.id,` · Framework: `,e.displayName)))},$n=({site:e,onContinue:t,onExit:n})=>{let{theme:r}=g();O((e,r)=>{if(e===`q`||r.escape){n();return}if(e===`r`||e===`R`){t();return}});let i=e.url.replace(/^https?:\/\//,``).replace(/\/$/,``);return A.createElement(h,{title:`Already installed`,state:`ok`},A.createElement(T,{flexDirection:`column`,gap:1},A.createElement(T,{flexDirection:`row`,gap:1},A.createElement(E,{color:r.success},`✓`),A.createElement(E,{bold:!0},e.name),A.createElement(E,{color:r.muted},`(`,i,`)`)),A.createElement(E,{color:r.muted},`Zenovay is already tracking this project. No changes needed.`),e.trackingCode?A.createElement(E,{color:r.dim},`tracking code: `,e.trackingCode):null))},er=({sites:e,preselectHint:t,onPick:n})=>{let r=mr(e,t),i=e.filter(e=>e.id!==r?.id),a=r?[r,...i]:i,o=[...a.map(e=>({label:fr(e,e.id===r?.id),value:e,description:e.trackingCode?`trackingCode: ${e.trackingCode}`:void 0})),{label:`+ Create new site on app.zenovay.com`,value:`create-new`,description:`Open the dashboard to add a new website`}];return A.createElement(h,{title:t?`Pick a site (best match: ${t})`:`Pick a site`,state:`idle`},A.createElement(y,{items:o,onSelect:n}))};function tr(){let e=process.argv[1]??``;return e.includes(`/_npx/`)||e.includes(`\\_npx\\`)||process.env.npm_execpath?.includes(`npx`)?`npx`:`global`}const Q=({k:e,primary:t})=>{let{theme:n}=g();return A.createElement(E,null,A.createElement(E,{color:n.muted},`[`),A.createElement(E,{bold:!0,color:t?n.accent:n.fg},e),A.createElement(E,{color:n.muted},`] `))},nr=({adapter:e,site:t,stats:n,arrived:i,firstParty:a,onPick:o})=>{let{theme:s}=g(),l=tr(),u=l===`npx`?`npx @zenovay/cli`:`zenovay`,d=r(t),f=n&&n.rounds>0?`${n.writes} file(s) · ${n.rounds} agent round(s)`:n&&n.writes>0?`${n.writes} file(s) · programmatic (no AI calls)`:null;return O((e,t)=>{let n=e.toLowerCase();n===`w`||t.return?o(`watch`):n===`o`?c(d).catch(()=>void 0):n===`e`?o(`events`):(n===`s`||n===`q`||t.escape)&&o(`quit`)},{isActive:!0}),A.createElement(h,{title:`You're live on Zenovay`,state:`ok`},A.createElement(E,{bold:!0,color:s.success},i?`✓ First event received from ${t.name}`:`✓ Installed successfully`),A.createElement(E,{color:s.accent},`─`.repeat(18)),A.createElement(T,{marginTop:1,flexDirection:`column`},A.createElement(Y,{label:`Framework`,value:e.displayName}),A.createElement(Y,{label:`Site`,value:A.createElement(An,{url:t.url,label:t.name})}),t.trackingCode?A.createElement(Y,{label:`Tracker`,value:A.createElement(E,{color:s.muted},t.trackingCode)}):A.createElement(Y,{label:`Tracker`,value:A.createElement(E,{color:s.warn},t.id,` (using site ID — verify in dashboard)`)}),f?A.createElement(Y,{label:`Changes`,value:A.createElement(E,{color:s.muted},f)}):null,A.createElement(Y,{label:`Dashboard`,value:A.createElement(An,{url:d})})),a&&a.proxyFile&&a.proxyAction!==`manual`&&a.proxyAction!==`skipped`?A.createElement(T,{marginTop:1},A.createElement(E,{color:s.success},`✓ `),A.createElement(E,{color:s.muted},`Analytics now load from your own domain — after you deploy, Safari, Edge and Brave visitors are counted too.`)):a?.manual?A.createElement(T,{marginTop:1,flexDirection:`column`},A.createElement(E,{color:s.muted},`Counting visitors in every browser (optional):`),A.createElement(E,{color:s.muted},` `,a.manual)):null,A.createElement(T,{marginTop:1,flexDirection:`column`},A.createElement(E,{color:s.dim},`WHAT'S NEXT`),A.createElement(T,{marginTop:1},A.createElement(E,null,` `),A.createElement(Q,{k:`W`,primary:!0}),A.createElement(E,null,`Watch live in this terminal `),A.createElement(E,{color:s.muted},`— visitors, pages, sources, vitals`)),A.createElement(T,null,A.createElement(E,null,` `),A.createElement(Q,{k:`O`}),A.createElement(E,null,`Open the dashboard in your browser`)),A.createElement(T,null,A.createElement(E,null,` `),A.createElement(Q,{k:`E`}),A.createElement(E,null,`Stream events as they fire `),A.createElement(E,{color:s.muted},`— page views, custom events, live`)),A.createElement(T,null,A.createElement(E,null,` `),A.createElement(Q,{k:`S`}),A.createElement(E,null,`Exit to shell`))),l===`npx`?A.createElement(T,{marginTop:1,flexDirection:`column`,borderStyle:`single`,borderColor:s.warn,paddingX:1},A.createElement(E,{color:s.warn,bold:!0},`Heads up — you ran via npx`),A.createElement(E,{color:s.muted},"The `zenovay` command isn't on your PATH yet. After you exit, run:"),A.createElement(T,{marginTop:1},A.createElement(E,{color:s.fg},` npm i -g @zenovay/cli `),A.createElement(E,{color:s.muted},"→ then `zenovay overview` works directly"))):A.createElement(T,{marginTop:1},A.createElement(E,{color:s.muted},`From your shell: `),A.createElement(E,{color:s.fg},u,` overview`),A.createElement(E,{color:s.muted},` · `),A.createElement(E,{color:s.fg},u,` --help`)))},rr=({adapter:e,site:t,stats:n,verify:r,firstParty:i,onCommit:a,onSkipCommit:o})=>{let{theme:s}=g();return ur(e=>{e===`y`||e===`Y`||e===`\r`?a():(e===`n`||e===`N`||e===`s`||e===`S`)&&o()}),A.createElement(h,{title:`Tracker installed`,state:r&&!r.ok?`warn`:`ok`},r?A.createElement(E,null,A.createElement(E,{color:r.ok?s.success:s.warn},r.ok?`✔ Verified — `:`⚠ `),r.detail):A.createElement(E,null,A.createElement(E,{color:s.success},`✔ `),`The Zenovay tracker is in your project.`),A.createElement(T,{marginTop:1},A.createElement(E,{color:s.muted},`Framework: `),A.createElement(E,null,e.displayName)),A.createElement(T,null,A.createElement(E,{color:s.muted},`Site: `),A.createElement(E,null,t.name,` (`,t.url,`)`)),n&&A.createElement(T,null,A.createElement(E,{color:s.muted},`Modified: `),A.createElement(E,null,n.writes,` file(s)`)),A.createElement(ir,{firstParty:i}),A.createElement(T,{marginTop:1},A.createElement(E,null,`Commit + push these changes to git? `),A.createElement(E,{color:s.accent},`[Y/n]`)))},ir=({firstParty:e})=>{let{theme:t}=g();if(!e)return null;let n=e.proxyFile&&e.proxyAction!==`manual`&&e.proxyAction!==`skipped`;return n?A.createElement(T,{marginTop:1,flexDirection:`column`},A.createElement(T,null,A.createElement(E,{color:t.success},`✔ `),A.createElement(E,null,`Analytics now load from your own domain `),A.createElement(E,{color:t.muted},`(`,e.proxyFile,`)`)),A.createElement(E,{color:t.muted},`After you deploy, Safari, Edge and Brave visitors are counted too.`)):e.manual?A.createElement(T,{marginTop:1,flexDirection:`column`},A.createElement(T,null,A.createElement(E,{color:t.muted},`Counting visitors in every browser (optional):`)),A.createElement(E,{color:t.muted},e.manual)):null},ar=({cwd:e,onDone:t,onError:n})=>{let{theme:r}=g(),[i,a]=N(`committing`),[o,s]=N(`Staging changes…`);return j(()=>{(async()=>{try{let n=await dr(e,e=>s(e),e=>a(e));n.committed?s(`Pushed ${n.shortSha} to origin/${n.branch}`):s(`No changes to commit (already up-to-date).`),setTimeout(()=>t(n),800)}catch(e){n(e.message)}})()},[]),A.createElement(h,{title:`Committing to git`,state:`busy`},A.createElement(T,null,A.createElement(E,{color:r.accent},A.createElement(F,{type:`dots`})),A.createElement(E,null,` `,i===`pushing`?`Pushing to origin`:`Committing`,`…`)),A.createElement(T,{marginTop:1},A.createElement(E,{color:r.muted},o)))},or=({site:e,onDeployed:t,onSkip:n})=>{let{theme:r}=g();return ur(e=>{e===`y`||e===`Y`||e===`\r`||e===`d`||e===`D`?t():(e===`n`||e===`N`||e===`s`||e===`S`)&&n()}),A.createElement(h,{title:`Ready to deploy?`,state:`idle`},A.createElement(E,null,`The tracker is installed locally. To capture events you need it on the live site:`),A.createElement(E,null,` `),A.createElement(T,null,A.createElement(E,{color:r.muted},` → `),A.createElement(An,{url:e.url})),A.createElement(E,null,` `),A.createElement(E,{color:r.muted},`Push the change through your normal deploy pipeline (Vercel auto-deploy, CI/CD, etc.).`),A.createElement(T,{marginTop:1},A.createElement(E,null,`Once it's deployed, press `),A.createElement(E,{color:r.accent},`[Y]`),A.createElement(E,null,` to verify the tracker is firing. `),A.createElement(E,{color:r.muted},`[s] skip verification`)))},sr=({site:e,onContinue:t})=>{let{theme:n}=g();return ur(()=>t()),A.createElement(h,{title:`Visit your site`,state:`idle`},A.createElement(E,null,`To send a test event, open any page on your site:`),A.createElement(E,null,` `),A.createElement(T,null,A.createElement(E,{color:n.muted},` → `),A.createElement(An,{url:e.url})),A.createElement(E,null,` `),A.createElement(E,{color:n.muted},`The tracker fires automatically on page load. We'll verify the next event arrives.`),A.createElement(T,{marginTop:1},A.createElement(E,null,`Press `),A.createElement(E,{color:n.accent},`[any key]`),A.createElement(E,null,` when you've visited the page.`)))};async function cr(e,t){try{let n=await fetch(e,{headers:{"User-Agent":`zenovay-cli/preflight`},signal:AbortSignal.timeout(8e3),redirect:`follow`});if(!n.ok)return{state:`tracker-missing`,httpStatus:n.status};let r=await n.text(),i=/<script\b[^>]*\bsrc\s*=\s*["'][^"']*(?:(?:api|cdn)\.zenovay\.com\/|\/(?:api\/)?_z\/script\.js)[^"']*["'][^>]*>/gi,a=/data-id\s*=\s*["'](ZV_[A-Za-z0-9]+)["']/i,o=/[?&]id=(ZV_[A-Za-z0-9]+)/i,s=r.match(i)??[];if(s.length===0)return{state:`tracker-missing`};let c=Array.from(new Set(s.map(e=>e.match(a)?.[1]??e.match(o)?.[1]).filter(e=>!!e)));return c.includes(t)?{state:`tracker-correct`}:{state:`tracker-wrong-id`,foundCodes:c}}catch(e){return{state:`tracker-missing`,networkError:e.message}}}const lr=({site:t,elapsed:r,onTick:a,onArrived:o,onTimeout:s})=>{let{theme:c}=g(),[l,u]=N(`preflight`),[d,f]=N(``),[p,m]=N([]),_=M(!1),v=t.trackingCode??t.id,y=async()=>{u(`preflight`),f(`Fetching ${t.url}…`);let e=await cr(t.url,v);if(_.current)return;if(e.state===`tracker-correct`){u(`polling`),f(`Tracker detected on live site — waiting for first hit…`),ee();return}if(e.state===`tracker-wrong-id`){u(`wrong-id-on-live`),m(e.foundCodes),f(`Live site has Zenovay but with id(s): ${e.foundCodes.join(`, `)}`);return}u(`awaiting-deploy`);let n=e.networkError?/enotfound|getaddrinfo|dns/i.test(e.networkError)?` (DNS lookup failed — check the site URL is correct + deployed)`:/timeout|etimedout|abort|econnrefused|network/i.test(e.networkError)?` (check your internet connection, then retry with [r])`:``:``;f(e.networkError?`Couldn't reach ${t.url}: ${e.networkError}${n}`:e.httpStatus?`${t.url} returned HTTP ${e.httpStatus}`:`No Zenovay tracker found on ${t.url}.`)},ee=async()=>{let r=Date.now()-10*60*1e3;try{let s=await e(),c=await i({strict:!1}),l=new n({config:s,cliVersion:`0`,token:c}),d=await Ct(t.id,r,{api:l,timeoutMs:6e4,pollIntervalMs:2500,onTick:e=>{_.current||a(e)}});if(_.current)return;d.received?(u(`success`),o()):u(`timeout`)}catch{_.current||u(`timeout`)}};j(()=>(_.current=!1,y(),()=>{_.current=!0}),[]),O(e=>{(l===`awaiting-deploy`||l===`wrong-id-on-live`||l===`timeout`)&&(e===`r`||e===`R`?y():(e===`s`||e===`S`)&&s())},{isActive:!0});let b=Math.floor(r/1e3);return l===`preflight`?A.createElement(h,{title:`Verifying`,state:`busy`},A.createElement(T,null,A.createElement(E,{color:c.accent},A.createElement(F,{type:`dots`})),A.createElement(E,null,` Checking your live site for the tracker…`)),A.createElement(T,{marginTop:1},A.createElement(E,{color:c.muted},d))):l===`awaiting-deploy`?A.createElement(h,{title:`Tracker not yet on your live site`,state:`warn`},A.createElement(E,{color:c.warn},d),A.createElement(T,{marginTop:1,flexDirection:`column`},A.createElement(E,null,`The tracker is in your local repo but hasn't been deployed yet.`),A.createElement(E,{color:c.muted},`Push your changes and wait for your deploy to finish (Vercel / Cloudflare Pages / CI), then retry.`)),A.createElement(T,{marginTop:1},A.createElement(E,null,`Press `),A.createElement(E,{color:c.accent},`[r]`),A.createElement(E,null,` to re-check, `),A.createElement(E,{color:c.accent},`[s]`),A.createElement(E,null,` to skip verification.`))):l===`wrong-id-on-live`?A.createElement(h,{title:`Live site has a different tracking code`,state:`warn`},A.createElement(E,{color:c.warn},`Expected: `,A.createElement(E,{color:c.accent},v),` `,`Found on live: `,A.createElement(E,{color:c.accent},p.join(`, `))),A.createElement(T,{marginTop:1,flexDirection:`column`},A.createElement(E,null,`Your local install uses a different ID than what's on `,t.url,`.`),A.createElement(E,{color:c.muted},`Deploy the new local version, then retry — or skip if the existing ID is intentional.`)),A.createElement(T,{marginTop:1},A.createElement(E,null,`Press `),A.createElement(E,{color:c.accent},`[r]`),A.createElement(E,null,` to re-check, `),A.createElement(E,{color:c.accent},`[s]`),A.createElement(E,null,` to skip.`))):l===`timeout`?A.createElement(h,{title:`No event arrived in 3 minutes`,state:`warn`},A.createElement(E,{color:c.warn},`The tracker is on your live site but no hits reached api.zenovay.com.`),A.createElement(T,{marginTop:1},A.createElement(E,{color:c.muted},`Try opening `,t.url,` in a fresh browser tab (no ad-blocker), then retry.`)),A.createElement(T,{marginTop:1},A.createElement(E,null,`Press `),A.createElement(E,{color:c.accent},`[r]`),A.createElement(E,null,` to re-check, `),A.createElement(E,{color:c.accent},`[s]`),A.createElement(E,null,` to finish without verification.`))):A.createElement(h,{title:`Waiting for first event`,state:`busy`},A.createElement(T,null,A.createElement(E,{color:c.accent},A.createElement(F,{type:`dots`})),A.createElement(E,null,` Polling api.zenovay.com for the first hit on `),A.createElement(E,{color:c.accent},t.url),A.createElement(E,null,` (`,b,`s elapsed)`)),A.createElement(T,{marginTop:1},A.createElement(E,{color:c.muted},`Reload the page if nothing arrives within ~30 seconds.`)))};function ur(e){O((t,n)=>{e(t,{return:n.return,escape:n.escape})},{isActive:!0})}async function dr(e,t,n){let{execFile:r}=await import(`node:child_process`),{promisify:i}=await import(`node:util`),a=i(r),o=async(t,n)=>{let{stdout:r}=await a(t,n,{cwd:e,maxBuffer:4e6});return r.trim()};try{await o(`git`,[`rev-parse`,`--is-inside-work-tree`])}catch{return t(`Not a git repository — skipped.`),{committed:!1}}let s=await o(`git`,[`status`,`--porcelain`]);if(!s)return{committed:!1};t(`Staging tracker changes…`),await o(`git`,[`add`,`-A`]),t(`Creating commit…`),await o(`git`,[`commit`,`-m`,`chore(zenovay): install tracking script via @zenovay/cli`]);let c=await o(`git`,[`rev-parse`,`--short`,`HEAD`]),l=await o(`git`,[`rev-parse`,`--abbrev-ref`,`HEAD`]);n(`pushing`),t(`Pushing to origin/${l}…`);try{await o(`git`,[`push`,`origin`,l])}catch(e){return t(`Commit ${c} created locally; push failed: ${e.message.trim()}\nPush manually with: git push origin ${l}`),{committed:!0,shortSha:c,branch:l}}return n(`done`),{committed:!0,shortSha:c,branch:l}}function fr(e,t){let n=`${e.name}`.padEnd(30,` `).slice(0,30),r=e.url.replace(/^https?:\/\//,``).padEnd(28,` `).slice(0,28),i=t?` ← best match`:``;return`${n} ${r}${i}`}async function pr(e){try{let t=await S.readFile(x.join(e,`package.json`),`utf8`),n=JSON.parse(t);if(n.name)return String(n.name).replace(/^@[^/]+\//,``)}catch{}try{let t=await S.readFile(x.join(e,`.git`,`config`),`utf8`),n=t.match(/url\s*=\s*.*[/:]([^/]+?)(?:\.git)?\s*$/m);if(n&&n[1])return n[1]}catch{}return x.basename(e)}function mr(e,t){if(!t||e.length===0)return e[0]??null;let n=$(t),r=e.find(e=>$(e.name)===n);if(r)return r;let i=e.find(e=>{let t=e.url.replace(/^https?:\/\//,``).replace(/\/.*$/,``),[r]=t.split(`.`);return $(r??``)===n});if(i)return i;let a=e.find(e=>{let t=$(e.name),r=$(e.url);return t.includes(n)||r.includes(n)||n.includes(t)||n.includes(r)});return a??e[0]??null}function $(e){return e.toLowerCase().replace(/[^a-z0-9]/g,``)}export{Zn as HostChoicePanel,Wn as initCommand};
@@ -1 +0,0 @@
1
- import{readConfig as e}from"./config-JVhBplSX.js";import"./api-BU8ms-ed.js";import{readToken as t}from"./token-store-RBywEspd.js";import"./telemetry-B1hu6Mwi.js";import{ApiV2Client as n}from"./api-v2-Dd_z970e.js";import"./formatter-C4QJnLxB.js";import{emit$1 as r,isHeadless as i}from"./emit-B0sTh9z5.js";import{openInBrowser as a}from"./open-url-DHEOtfXN.js";import"./client-AII1aQbd.js";import"./theme-DnsyTVQs.js";import{Banner as o,Panel as s,useTheme as c}from"./panel-Css3a3Vm.js";import"./prompt-BL4GzAMK.js";import{Keybar as l}from"./keybar-BHiS3lI4.js";import"./sparkline-BICNgdIH.js";import{ChatPanel as u}from"./chat-panel-CwOboIau.js";import{resolveSiteId as d}from"./resolve-site-DQFFFm9Z.js";import{stripUrlPrefix as f}from"./fmt-DGdql3Z7.js";import{DataTable as p}from"./data-table-DeR2tIOP.js";import{EmptyState as ee}from"./empty-state-Dfv6x-qP.js";import{tileWidths as m}from"./grid-BD6OXmy5.js";import{MetricCard as h}from"./metric-card-249MQpWf.js";import{deepLinkFor as g}from"./keybar-deep-link-Bbky2z_r.js";import{useFullscreen as te}from"./use-fullscreen-B9LnCYar.js";import{useSiteSwitcher as ne}from"./site-switcher-CGS1OOLY.js";import{Box as _,Text as v,render as y,useApp as b,useInput as x}from"ink";import S,{useEffect as re,useState as C}from"react";import ie from"ink-spinner";function ae(e,t){let n=Math.max(0,Math.round((t-e)/1e3));if(n<5)return`just now`;if(n<60)return`${n}s ago`;let r=Math.floor(n/60);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}async function w(a){let o=await e(),s=await t({strict:!1});if(!s)return process.stderr.write("Not logged in — run `zenovay login` first.\n"),2;let c=new n({config:o,cliVersion:a.cliVersion,token:s}),l,u;try{({siteId:l,site:u}=await d(c,{explicit:a.siteId,headless:!!a.json,cliVersion:a.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let f=u?.url?u.url.replace(/^https?:\/\//,``).replace(/\/$/,``):u?.name??l;if(i(a)){let e=await c.getLive(l);return r({type:`live.snapshot`,data:e}),0}return new Promise(e=>{let{unmount:t}=y(S.createElement(T,{api:c,siteId:l,siteLabel:f,cliVersion:a.cliVersion,onExit:n=>{t(),e(n)}}))})}const T=({api:e,siteId:t,siteLabel:n,cliVersion:r,onExit:i})=>{te();let{exit:d}=b(),{theme:y}=c(),[w,T]=C(null),[E,D]=C(!0),[O,k]=C(null),[A,j]=C(null),[M,N]=C(()=>Date.now()),[P,F]=C(!1),[I,L]=C(t),[R,z]=C(n),B=ne(e,I,e=>{L(e.id),z(e.url.replace(/^https?:\/\//,``).replace(/\/$/,``)),T(null),D(!0)});if(x((e,t)=>{if(!P){if(B.open){(t.escape||e===`s`)&&B.close();return}if(e===`/`){F(!0);return}if(e===`o`||e===`O`){a(g(`live`,{siteId:I}));return}if(e===`s`){B.toggle();return}e===`q`&&(d(),i(0))}}),re(()=>{if(P)return;let t=!1,n=async()=>{try{let n=await e.getLive(I);t||(T(n),D(!1),k(null),j(Date.now()),N(Date.now()))}catch(e){t||(k(e.message),D(!1))}};n();let r=setInterval(n,2e3);return()=>{t=!0,clearInterval(r)}},[e,I,P]),P)return S.createElement(u,{cliVersion:r,api:e,dashboardContext:{commandName:`live`,siteId:I,siteLabel:R,metricsSnapshot:w},onClose:()=>F(!1)});let V=`live · ${R}`,H=[{key:`/`,label:`ask AI`},{key:`s`,label:`site`},{key:`o`,label:`browser`},{key:`q`,label:`quit`}];if(E)return S.createElement(_,{flexDirection:`column`},S.createElement(o,{version:r,subtitle:V,live:!1}),S.createElement(s,{title:`Loading`,state:`busy`},S.createElement(_,null,S.createElement(v,{color:y.accent},S.createElement(ie,{type:`dots`})),S.createElement(v,null,` Connecting…`))));if(O&&!w)return S.createElement(_,{flexDirection:`column`},S.createElement(o,{version:r,subtitle:V,live:!1}),S.createElement(ee,{reason:`error`,headline:`Failed to load`,hint:O}),B.overlay,S.createElement(l,{items:H}));let U=process.stdout.columns??80,oe=m(U,3,2)[0],W=w?.recentEvents??[],G=w?.activeVisitors??0,se=process.stdout.rows??40,K=Math.max(5,Math.min(20,se-16)),q=W.slice(0,K),J=W.length-q.length,Y=new Map;for(let e of W){let t=e.country??`—`;Y.set(t,(Y.get(t)??0)+1)}let X=[...Y.entries()].sort((e,t)=>t[1]-e[1]).slice(0,K),ce=[{key:`type`,label:`event`,width:10,format:e=>String(e??`pageview`)},{key:`path`,label:`path`,width:30,format:e=>f(String(e??``))},{key:`country`,label:`country`,width:8,format:e=>String(e??`—`)}],Z=X.length>0,[Q,$]=Z?(()=>{let[e,t]=m(U,3,2);return[e+t+2,m(U,3,2)[2]]})():[U,0];return S.createElement(_,{flexDirection:`column`},S.createElement(o,{version:r,subtitle:V,live:G>0}),S.createElement(_,{flexDirection:`row`,marginTop:1},S.createElement(h,{title:`Active now`,value:G,format:`number`,width:oe,gap:0})),S.createElement(_,{marginTop:1,flexDirection:`row`,width:U},S.createElement(_,{width:Q,flexShrink:0,marginRight:Z?2:0},S.createElement(s,{title:`Recent events`,width:Q},q.length===0?S.createElement(v,{color:y.dim},`No events in the last few seconds`):S.createElement(S.Fragment,null,S.createElement(p,{columns:ce,data:q,zebra:!0}),J>0?S.createElement(v,{color:y.dim},` +${J} more in this window`):null))),Z?S.createElement(_,{width:$,flexShrink:0},S.createElement(s,{title:`By country (live)`,width:$},X.map(([e,t])=>S.createElement(_,{key:e,flexDirection:`row`},S.createElement(_,{width:6},S.createElement(v,{wrap:`truncate`},e)),S.createElement(_,{flexGrow:1,justifyContent:`flex-end`},S.createElement(v,{color:y.fg},t.toLocaleString())))),Array.from({length:Math.max(0,K-X.length)},(e,t)=>S.createElement(_,{key:`pad-${t}`,height:1})))):null),S.createElement(_,{marginTop:1},S.createElement(v,{color:y.dim},A===null?``:`↻ live · updated ${ae(A,M)}`)),B.overlay,S.createElement(l,{items:H,active:`/`}))};export{w as liveCommand};
@@ -1 +0,0 @@
1
- import"./config-JVhBplSX.js";import"./api-BU8ms-ed.js";import"./token-store-RBywEspd.js";import"./formatter-C4QJnLxB.js";import"./emit-B0sTh9z5.js";import"./open-url-DHEOtfXN.js";import{loginCommand as e,maybeInstallCompletions as t}from"./login-CuDPS4Cd.js";export{e as loginCommand};
@@ -1,2 +0,0 @@
1
- import{readConfig as e}from"./config-JVhBplSX.js";import{ApiClient as t}from"./api-BU8ms-ed.js";import{clearToken as n,readToken as r}from"./token-store-RBywEspd.js";import"./formatter-C4QJnLxB.js";import{emit$1 as i,isHeadless as a}from"./emit-B0sTh9z5.js";async function o(o){let s=await e(),c=await r({strict:!1}).catch(()=>null);if(c)try{let e=new t({config:s,cliVersion:o.cliVersion,token:c});await e.revokeCurrentToken()}catch{}await n(),a({json:o.json})?i({type:`done`,command:`logout`,exitCode:0}):process.stdout.write(`Logged out.
2
- `)}export{o as logoutCommand};
@@ -1,10 +0,0 @@
1
- import{readConfig as e}from"./config-JVhBplSX.js";import{ApiError as t}from"./api-BU8ms-ed.js";import{readToken as n}from"./token-store-RBywEspd.js";import{ApiV2Client as r}from"./api-v2-Dd_z970e.js";import{confirmDestructive as i}from"./confirm-DS5wux0g.js";function a(e){return e.length>12?`${e.slice(0,8)}…${e.slice(-4)}`:e}function o(e){return e?new Date(e).toISOString().slice(0,10):`—`}async function s(s){let c=await e(),l=await n({strict:!1}),u=new r({config:c,cliVersion:s.cliVersion,token:l});try{switch(s.action){case`list`:{let{notes:e}=await u.listNotes();if(s.json)return process.stdout.write(JSON.stringify({notes:e},null,2)+`
2
- `),0;if(e.length===0)return process.stdout.write('No notes yet. Create one with `zenovay notes create --content "<text>"`.\n'),0;let t=[14,12,50],n=e=>e.map((e,n)=>(e??``).padEnd(t[n])).join(` `);process.stdout.write(`
3
- `+n([`id`,`created`,`content`])+`
4
- `),process.stdout.write(n(t.map(e=>`─`.repeat(e)))+`
5
- `);for(let r of e)process.stdout.write(n([a(r.id),o(r.createdAt),r.content.slice(0,t[2])])+`
6
- `);return process.stdout.write(`
7
- `),0}case`create`:if(!s.content)return process.stderr.write('Error: --content "<text>" is required for `notes create`.\n'),2;try{let e=await u.createNote({content:s.content,siteId:s.siteId});return s.json?(process.stdout.write(JSON.stringify(e,null,2)+`
8
- `),0):(process.stdout.write(`✔ Note created (id ${e.id}).\n`),0)}catch(e){if(e instanceof t&&e.status===501){let t=e.body??{};return process.stderr.write(`Notes are not available on this environment yet. ${t.hint??``}\n`),2}throw e}case`delete`:{if(!s.id)return process.stderr.write("Error: note id is required for `notes delete`.\n"),2;let e=await i({resource:`note`,name:a(s.id),yes:s.yes,destructive:!0});if(!e)return process.stdout.write(`Cancelled.
9
- `),1;let t=await u.deleteNote(s.id);return s.json?(process.stdout.write(JSON.stringify(t)+`
10
- `),0):(process.stdout.write(`✔ Deleted note ${a(s.id)}.\n`),0)}}}catch(e){return process.stderr.write(`✗ ${e.message}\n`),1}}export{s as notesCommand};
@@ -1 +0,0 @@
1
- import{SECRET_PATTERNS as e,scrubSecrets as t}from"./secrets-BdzQxqfz.js";export{e as SECRET_PATTERNS,t as scrubSecrets};
@@ -1,4 +0,0 @@
1
- import{readConfig as e}from"./config-JVhBplSX.js";import"./api-BU8ms-ed.js";import{readToken as t}from"./token-store-RBywEspd.js";import{ApiV2Client as n}from"./api-v2-Dd_z970e.js";function r(e){try{return JSON.parse(e)}catch{return e}}async function i(i){let a=await e(),o=await t({strict:!1}),s=new n({config:a,cliVersion:i.cliVersion,token:o});try{switch(i.action){case`get`:{let{settings:e}=await s.getSettings();if(i.key){let t=e[i.key];return t===void 0?(process.stderr.write(`Unknown setting: ${i.key}\n`),2):(i.json?process.stdout.write(JSON.stringify({[i.key]:t},null,2)+`
2
- `):process.stdout.write(`${i.key} = ${t===null?`—`:JSON.stringify(t)}\n`),0)}if(i.json)return process.stdout.write(JSON.stringify({settings:e},null,2)+`
3
- `),0;for(let[t,n]of Object.entries(e))process.stdout.write(`${t.padEnd(28)} ${n===null?`—`:JSON.stringify(n)}\n`);return 0}case`set`:{if(!i.key||i.value===void 0)return process.stderr.write("Error: usage `zenovay settings set <key> <value>`.\n"),2;let e=r(i.value),t=await s.setSetting(i.key,e);return i.json?(process.stdout.write(JSON.stringify(t,null,2)+`
4
- `),0):(process.stdout.write(`✔ Set ${i.key} → ${JSON.stringify(e)}\n`),0)}}}catch(e){return process.stderr.write(`✗ ${e.message}\n`),1}}export{i as settingsCommand};
@@ -1,6 +0,0 @@
1
- import{readConfig as e}from"./config-JVhBplSX.js";import"./api-BU8ms-ed.js";import{readToken as t}from"./token-store-RBywEspd.js";import{ApiV2Client as n}from"./api-v2-Dd_z970e.js";import{confirmDestructive as r}from"./confirm-DS5wux0g.js";import"./theme-DnsyTVQs.js";import"./panel-Css3a3Vm.js";import"./prompt-BL4GzAMK.js";import{resolveSiteId as i}from"./resolve-site-DQFFFm9Z.js";async function a(a){let o=await e(),s=await t({strict:!1}),c=new n({config:o,cliVersion:a.cliVersion,token:s}),l,u;try{({siteId:l,site:u}=await i(c,{explicit:a.siteId,headless:!!a.json,cliVersion:a.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let d=u?.url?u.url.replace(/^https?:\/\//,``).replace(/\/$/,``):u?.name??l;try{switch(a.action){case`enable`:{let e=await c.enableShare(l);if(a.json)return process.stdout.write(JSON.stringify(e,null,2)+`
2
- `),0;let t=`═`.repeat(72);return process.stdout.write(`\n${t}\n Public dashboard sharing enabled\n url: ${e.url}\n${t}\n\n Anyone with this link can view your dashboard. Disable with\n \`zenovay share disable\` to invalidate the link immediately.\n\n`),0}case`disable`:{let e=await r({resource:`public share link`,name:d,yes:a.yes,destructive:!0});if(!e)return process.stdout.write(`Cancelled.
3
- `),1;let t=await c.disableShare(l);return a.json?(process.stdout.write(JSON.stringify(t)+`
4
- `),0):(process.stdout.write(`✔ Public sharing disabled. The previous link is no longer valid.
5
- `),0)}case`url`:{let e=await c.getShare(l);return a.json?(process.stdout.write(JSON.stringify(e,null,2)+`
6
- `),0):e.enabled?(process.stdout.write(`Public URL: ${e.url??`—`}\n`),0):(process.stdout.write("Public sharing is disabled. Enable with `zenovay share enable`.\n"),0)}}}catch(e){return process.stderr.write(`✗ ${e.message}\n`),1}}export{a as shareCommand};
@@ -1 +0,0 @@
1
- import{firstPartySnippet as e,isAlreadyFirstParty as t,swapToFirstPartySnippet as n}from"./snippet-p5qtQicp.js";export{t as isAlreadyFirstParty};
@@ -1 +0,0 @@
1
- import e from"node:path";import{promises as t}from"node:fs";import{globby as n}from"globby";function r(e){return`<script defer src="/api/_z/script.js?id=${encodeURIComponent(e)}"></script>`}const i=/<script\b(?=[^>]*\bsrc\s*=\s*["'`]https:\/\/api\.zenovay\.com\/z\.js["'`])[^>]*>(?:\s*<\/script>)?/gi,a=/<script\b[^>]*\bsrc\s*=\s*["'`][^"'`]*\/(?:api\/)?_z\/script\.js[^"'`]*["'`][^>]*>/i,o=/\bdata-id\s*=\s*["'`]([^"'`]+)["'`]/i;function s(e,t){let n=e.match(o),i=n?.[1]??t;return r(i)}async function c(r,a){let o=await n([`**/*.{html,htm,tsx,jsx,vue,svelte,astro,ts,js,mjs}`,`!node_modules/**`,`!.git/**`,`!dist/**`,`!.next/**`,`!.nuxt/**`,`!build/**`,`!.output/**`],{cwd:r,gitignore:!0,deep:4,absolute:!0}).catch(()=>[]),c=[];for(let n of o.slice(0,300)){let o;try{o=await t.readFile(n,`utf8`)}catch{continue}if(i.lastIndex=0,!i.test(o))continue;i.lastIndex=0;let l=o.replace(i,e=>s(e,a.trackingCode));if(l!==o){try{await t.writeFile(n,l,`utf8`)}catch{continue}c.push(e.relative(r,n))}}return{swapped:c.length>0,files:c}}function l(e){return a.test(e)}export{r as firstPartySnippet,l as isAlreadyFirstParty,c as swapToFirstPartySnippet};