@zenovay/cli 0.1.22 → 0.1.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agency-DAoX3ia1.js +11 -0
- package/dist/ai-CBcz7gVp.js +11 -0
- package/dist/{analytical-screen-DlNffR1j.js → analytical-screen-B4KwZvWt.js} +1 -1
- package/dist/analytics-CuvSsCi8.js +1 -0
- package/dist/api-keys-BSBJExQx.js +10 -0
- package/dist/api-v2-CfJ_2Z5N.js +1 -0
- package/dist/banner-BPQh2F8l.js +1 -0
- package/dist/bar-C9stEeJd.js +1 -0
- package/dist/bin.js +2 -2
- package/dist/companies-Dej3am51.js +2 -0
- package/dist/confirm-D_aKHknn.js +1 -0
- package/dist/{data-table-EsLUu8Hj.js → data-table-BVWqHy9m.js} +1 -1
- package/dist/deploys-BvO4FZ5h.js +2 -0
- package/dist/devices-DvHjJ1vj.js +1 -0
- package/dist/{doctor-C42TUuU1.js → doctor-DGINy0u2.js} +1 -1
- package/dist/domains-CJJb5eY3.js +4 -0
- package/dist/{emit-BmfLGjqr.js → emit-D7VCOSNk.js} +1 -1
- package/dist/{empty-state-ETu78blH.js → empty-state-Dkho-_3J.js} +1 -1
- package/dist/errors-DUGYxRbL.js +2 -0
- package/dist/{events-tail-Cytm6gdG.js → events-tail-5rwtRF4X.js} +1 -1
- package/dist/funnel-BS7ffNz8.js +3 -0
- package/dist/geo-DYK3YeQM.js +1 -0
- package/dist/goals-D9UeMtcm.js +10 -0
- package/dist/health-gixkqsPr.js +1 -0
- package/dist/{health-T70yG5po.js → health-oHQqxSl8.js} +1 -1
- package/dist/heatmaps-6elfFwGW.js +1 -0
- package/dist/home-rcPngoZx.js +2 -0
- package/dist/{init-3WrfX1Fb.js → init-BAvyI5n6.js} +3 -3
- package/dist/init-Bmp-Yrah.js +1 -0
- package/dist/insights-DKMGpJhD.js +1 -0
- package/dist/integrations-BQIqUYBX.js +10 -0
- package/dist/journeys-DZv7-dFm.js +1 -0
- package/dist/{keybar-DO-sCbJB.js → keybar-C7YkmK1U.js} +1 -1
- package/dist/live-BDP8RD7K.js +1 -0
- package/dist/login-Bo0VXzkT.js +1 -0
- package/dist/{login-DvMRHd3J.js → login-DWaz_EsV.js} +1 -1
- package/dist/{logout-B3V_2DRZ.js → logout-DV5SjEL4.js} +1 -1
- package/dist/{metric-card-CtAoTOEP.js → metric-card-BfVg5VG6.js} +1 -1
- package/dist/notes-Lk4Z4uT0.js +10 -0
- package/dist/pages-CBgdpzq_.js +1 -0
- package/dist/plans-0x-Zd6RV.js +7 -0
- package/dist/profile-BpjuwmG1.js +4 -0
- package/dist/{progress-row-CeP9YRKn.js → progress-row-DFOvHAc5.js} +1 -1
- package/dist/projects-7nUulyES.js +1 -0
- package/dist/projects-Cz7V3Yr9.js +2 -0
- package/dist/prompt-BURfUNxp.js +1 -0
- package/dist/query-D5KYlF3a.js +8 -0
- package/dist/{resolve-site-CKq90Xzu.js → resolve-site-D3e1i32Z.js} +1 -1
- package/dist/retention-BQVRtm1F.js +1 -0
- package/dist/revenue-C9ZiFyIZ.js +2 -0
- package/dist/sessions-BIrSllDo.js +1 -0
- package/dist/settings-CF7Bh7LX.js +4 -0
- package/dist/sources-BQQlIRsz.js +2 -0
- package/dist/stats-DRXUx_G5.js +2 -0
- package/dist/team-GCfHAd8i.js +15 -0
- package/dist/themes-M5zvyaJT.js +4 -0
- package/dist/{ui-BLnL2HSo.js → ui-oBd4Xpw5.js} +1 -1
- package/dist/{update-wMGBdUT-.js → update-DayeuoQd.js} +1 -1
- package/dist/uptime-BL5nXfbf.js +1 -0
- package/dist/{use-DsHE5Eu7.js → use-BvDJ2P2x.js} +1 -1
- package/dist/visitors-2EM5Ft4d.js +2 -0
- package/dist/vitals-DfCohk_c.js +2 -0
- package/dist/watch-CL5zAa_r.js +1 -0
- package/dist/webhooks-forward-C1uJH_7w.js +3 -0
- package/dist/wizard-bin.js +1 -1
- package/package.json +1 -1
- package/dist/ai-DGIoZ2aO.js +0 -11
- package/dist/api-v2-C7yrqNuV.js +0 -1
- package/dist/companies-D30bvUbA.js +0 -2
- package/dist/deploys-CMVAZp4i.js +0 -2
- package/dist/devices-yq4dh7UD.js +0 -1
- package/dist/errors-BlVWrZ86.js +0 -2
- package/dist/funnel-B7yQXVJa.js +0 -3
- package/dist/geo-BqtzfNwp.js +0 -1
- package/dist/health-DOOluwxM.js +0 -1
- package/dist/heatmaps-DtbYa2K3.js +0 -1
- package/dist/init-4dY3jNh8.js +0 -1
- package/dist/insights-C0xGkTYG.js +0 -1
- package/dist/journeys-Bx08wXVO.js +0 -1
- package/dist/live-BGdMxOZ_.js +0 -1
- package/dist/login-Bb_At1Ov.js +0 -1
- package/dist/overview-BieuspgD.js +0 -1
- package/dist/pages-DXpXKnCy.js +0 -1
- package/dist/projects-DKQeDin5.js +0 -2
- package/dist/prompt-CIl9JOlh.js +0 -1
- package/dist/query-B88NMsPY.js +0 -8
- package/dist/retention-C75M6nUk.js +0 -1
- package/dist/revenue-Dsy6ODmG.js +0 -2
- package/dist/sessions-FXL5fAGa.js +0 -1
- package/dist/sources-DkEkhs1V.js +0 -2
- package/dist/stats-B4iRNAEW.js +0 -2
- package/dist/themes-DxPebZga.js +0 -4
- package/dist/uptime-DMK_yhMW.js +0 -1
- package/dist/vitals-pqv_u431.js +0 -2
- package/dist/watch-CbehE_bK.js +0 -1
- package/dist/webhooks-forward-C7gK3C6A.js +0 -3
- /package/dist/{client-vixcHdv-.js → client-WzSy90dG.js} +0 -0
- /package/dist/{completions-CnHbpLqp.js → completions-CNQoXN6L.js} +0 -0
- /package/dist/{formatter-BNYzdX5c.js → formatter-mW0Yk3Nt.js} +0 -0
- /package/dist/{globe-1bi4DjwJ.js → globe-DImE1nyh.js} +0 -0
- /package/dist/{panel-Crm-x-5U.js → panel-uygscwY5.js} +0 -0
- /package/dist/{sparkline-ut0Tvv-E.js → sparkline-Bkfzqe4x.js} +0 -0
- /package/dist/{tier-DJvWU86k.js → tier-RjOGNzda.js} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{readConfig as e,updateConfig as t}from"./config-CZ9IzjIH.js";import{ApiClient as n,readToken as r}from"./api-DXmhz2DM.js";import{parseSseStream as i}from"./client-vixcHdv-.js";import{emit as a,isHeadless as o}from"./emit-BmfLGjqr.js";import{loginCommand as s}from"./login-DvMRHd3J.js";import{Panel as c}from"./panel-Crm-x-5U.js";import{Banner as l,Select as u}from"./prompt-CIl9JOlh.js";import{BrandGradient as d,ProgressRow as f}from"./progress-row-CeP9YRKn.js";import{Keybar as p}from"./keybar-DO-sCbJB.js";import{spark as m}from"./sparkline-ut0Tvv-E.js";import h from"node:path";import{promises as g}from"node:fs";import{z as _}from"zod";import v from"node:os";import y from"node:crypto";import{Box as b,Text as x,render as S,useApp as ee,useInput as C}from"ink";import w,{useEffect as T,useRef as E,useState as D}from"react";import{globby as O}from"globby";import k from"ink-spinner";import{ulid as A}from"ulid";import{applyPatch as j}from"diff";const M=[`@zenovay/tracker`,`@zenovay/next`,`@zenovay/nuxt`,`@zenovay/svelte`,`@zenovay/astro`,`@zenovay/remix`,`@zenovay/node`],N=[`zenovay.config.ts`,`zenovay.config.js`,`zenovay.config.mjs`,`zenovay.config.json`],P=/<script[^>]*src\s*=\s*["']https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+["'][^>]*>\s*<\/script>/gi,F=/data-id\s*=\s*["'](ZV_[A-Za-z0-9]+)["']/i,I=/data-zenovay-site\s*=\s*["']([^"']+)["']/i,L=[{name:`PostHog`,patterns:[/posthog\.com\b/i,/posthog-js/,/window\.posthog/]},{name:`Plausible`,patterns:[/plausible\.io\/js/i,/window\.plausible/]},{name:`Google Analytics`,patterns:[/googletagmanager\.com\/gtag\/js/i,/www\.google-analytics\.com\/analytics\.js/i,/window\.gtag\b/]},{name:`Mixpanel`,patterns:[/cdn\.mxpnl\.com/i,/mixpanel-browser/]},{name:`Segment`,patterns:[/cdn\.segment\.com\/analytics\.js/i,/window\.analytics\b/]},{name:`Hotjar`,patterns:[/static\.hotjar\.com/i,/\(h,o,t,j,a,r\)/i]},{name:`Amplitude`,patterns:[/cdn\.amplitude\.com/i,/amplitude\.getInstance/]},{name:`Heap`,patterns:[/cdn\.heapanalytics\.com/i]},{name:`FullStory`,patterns:[/fullstory\.com\/s\/fs\.js/i,/window\.FS\.identify/]}];async function R(e,t){let n={zenovayInstalled:!1,correctTrackingCode:!1,foundTrackingCodes:[],zenovayFiles:[],competitors:[],summary:``,recommendation:`fresh-install`};try{let t=await g.readFile(h.join(e,`package.json`),`utf8`),r=JSON.parse(t),i={...r.dependencies,...r.devDependencies};for(let e of M)if(e in i){n.zenovayInstalled=!0,n.packageMarker=e;break}}catch{}for(let t of N)try{await g.access(h.join(e,t)),n.zenovayInstalled=!0,n.configFile=t;break}catch{}let r=await O([`**/*.{html,htm,tsx,jsx,vue,svelte,astro,ts,js,mjs}`,`!node_modules/**`,`!.git/**`,`!dist/**`,`!.next/**`,`!.nuxt/**`,`!build/**`,`!.output/**`],{cwd:e,gitignore:!0,deep:4,absolute:!0}).catch(()=>[]),i=new Map,a=new Set;for(let t of r.slice(0,300)){let r;try{r=await g.readFile(t,`utf8`)}catch{continue}let o=h.relative(e,t),s=r.match(P);if(s&&s.length>0){n.zenovayInstalled=!0;let e=s[0].slice(0,200),t=e.match(F)??e.match(I),r=t?.[1]??null;r&&a.add(r),n.zenovayFiles.push({file:o,currentTrackingCode:r,scriptTagCount:s.length,matchSample:e})}for(let e of L)if(e.patterns.some(e=>e.test(r))){let t=i.get(e.name)??new Set;t.add(o),i.set(e.name,t)}}if(n.foundTrackingCodes=Array.from(a),n.competitors=Array.from(i.entries()).map(([e,t])=>({name:e,files:Array.from(t).slice(0,5)})),n.zenovayInstalled)if(n.foundTrackingCodes.length>0){let e=n.foundTrackingCodes.every(e=>e===t);n.correctTrackingCode=e,n.recommendation=e?`no-op`:`update-tracking-code`}else n.correctTrackingCode=!1,n.recommendation=`no-op`;else n.competitors.length>0?n.recommendation=`fresh-install-alongside-competitor`:n.recommendation=`fresh-install`;return n.summary=te(n,t),n}function te(e,t){let n=[];return e.zenovayInstalled?e.foundTrackingCodes.length===0?n.push(`Zenovay package or config detected but no <script> tag found.`):e.correctTrackingCode?n.push(`Zenovay tracker present in ${e.zenovayFiles.length} file(s) with correct ID ${t}.`):n.push(`Zenovay tracker present in ${e.zenovayFiles.length} file(s), but with mismatching ID(s): ${e.foundTrackingCodes.join(`, `)} (target: ${t}).`):n.push(`No Zenovay tracker found.`),e.competitors.length>0&&n.push(`Competitor tracker(s) present (DO NOT modify): ${e.competitors.map(e=>e.name).join(`, `)}.`),n.join(` `)}async function ne(e){let t=await R(e,``);return{installed:t.zenovayInstalled,reasons:t.summary?[t.summary]:[],packageMarker:t.packageMarker,configFile:t.configFile,scriptFile:t.zenovayFiles[0]?.file}}const re=[{name:`openai-proj`,regex:/\bsk-proj-[A-Za-z0-9_-]{20,}\b/g},{name:`anthropic`,regex:/\bsk-ant-[A-Za-z0-9_-]{20,}\b/g},{name:`openai-sk`,regex:/\bsk-[A-Za-z0-9]{20,}\b/g},{name:`github-pat-new`,regex:/\bgithub_pat_[A-Za-z0-9_]{82}\b/g},{name:`github-pat`,regex:/\bghp_[A-Za-z0-9]{36}\b/g},{name:`github-oauth`,regex:/\bgho_[A-Za-z0-9]{36}\b/g},{name:`aws-access-key`,regex:/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g},{name:`stripe-live`,regex:/\b(?:sk|pk)_live_[A-Za-z0-9]{24,}\b/g},{name:`stripe-test`,regex:/\b(?:sk|pk)_test_[A-Za-z0-9]{24,}\b/g},{name:`stripe-restricted`,regex:/\brk_(?:live|test)_[A-Za-z0-9]{24,}\b/g},{name:`stripe-webhook`,regex:/\bwhsec_[A-Za-z0-9]{24,}\b/g},{name:`slack-bot`,regex:/\bxox[bpoa]-[A-Za-z0-9-]{10,}\b/g},{name:`google-api`,regex:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:`jwt`,regex:/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g},{name:`private-key-rsa`,regex:/-----BEGIN (?:RSA|EC|OPENSSH|DSA|PGP) PRIVATE KEY(?: BLOCK)?-----/g},{name:`private-key-pkcs8`,regex:/-----BEGIN PRIVATE KEY-----/g}];function ie(e){let t=e;for(let e of re){let n=new RegExp(e.regex.source,e.regex.flags);t=t.replace(n,`[REDACTED:${e.name}]`)}return t}const ae=[/^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)$/,/^public\/index\.html$/,/^index\.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)$/],oe=[/(^|\/)\.env($|\.(?!example$)[^/]+$)/,/(^|\/)\.git(\/|$)/,/(^|\/)node_modules\//,/(^|\/)\.ssh\//,/(^|\/)\.aws\//,/\.pem$/,/\.key$/,/(^|\/)id_rsa($|\.)/,/(^|\/)\.npmrc$/,/(^|\/)credentials(\.|$)/],z=256*1024,B=50,V=20,H=40;var U=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`SandboxError`}};const W=/<script[^>]*src\s*=\s*["']https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+["'][^>]*>\s*<\/script>/i,G=[{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 K=class{sessionId;cwd;cwdReal;undoRoot;readCount=0;writeCount=0;roundCount=0;writtenPathsSet=new Set;constructor(e){this.sessionId=e.sessionId??A(),this.cwd=e.cwd,this.cwdReal=g.realpath(e.cwd),this.undoRoot=e.undoRoot??h.join(v.homedir(),`.zenovay`,`undo`)}incrementRound(){if(this.roundCount++,this.roundCount>H)throw new U(`round-cap`,`Tool-call recursion cap (${H}) 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 U(`escape`,`Path must be a non-empty string.`);if(e.includes(`\0`))throw new U(`escape`,`Null byte in path.`);if(/^\\\\[?.]\\/.test(e)||/^\\\\[A-Za-z0-9]/.test(e))throw new U(`escape`,`Windows special path prefix: ${e}`);if(/%/.test(e))try{let t=decodeURIComponent(e);if(/%[0-9A-Fa-f]{2}/.test(t))throw new U(`escape`,`Double-encoded path: ${e}`);e=t}catch(t){throw t instanceof U?t:new U(`escape`,`Malformed percent-encoding: ${e}`)}if(e.includes(`\0`))throw new U(`escape`,`Null byte in decoded path.`);if(e.includes(`\\`))throw new U(`escape`,`Backslash in path (Windows-style separator not accepted): ${e}`);let n=await this.cwdReal,r=h.isAbsolute(e)?e:h.join(n,e),i=h.normalize(r),a=i;try{a=await g.realpath(i)}catch(e){if(e.code!==`ENOENT`)throw new U(`escape`,`realpath failed: ${e.message}`);let t=h.dirname(i);try{let e=await g.realpath(t);a=h.join(e,h.basename(i))}catch{}}if(!this.isWithin(a,n))throw new U(`escape`,`Path escapes cwd: ${e}`);let o=h.relative(n,a);for(let e of oe)if(e.test(o)){if(t===`read`&&/(^|\/)node_modules\//.test(o))continue;throw new U(`blocklisted`,`Path is on the hard blocklist: ${o}`)}if(t===`write`){let e=ae.some(e=>e.test(o));if(!e&&!/^\.env(\.local)?$/.test(o)&&!/^\.claude\//.test(o)&&!/^\.cursor\//.test(o))throw new U(`not-allowlisted`,`Write path not on allowlist: ${o}`)}return a}isWithin(e,t){let n=h.relative(t,e);return!n.startsWith(`..`)&&!h.isAbsolute(n)}async safeRead(e){if(this.readCount>=B)throw new U(`read-cap`,`Read cap (${B}) reached.`);let t=await this.resolveForRead(e),n=await g.stat(t);if(n.size>z)throw new U(`too-large`,`File exceeds ${z}B: ${e} (${n.size}B)`);let r=await g.readFile(t),i=r.subarray(0,Math.min(r.length,8192));if(i.includes(0))throw new U(`binary-rejected`,`Binary content in ${e}.`);return this.readCount++,r.toString(`utf8`)}async safeWrite(e,t){if(this.writeCount>=V)throw new U(`write-cap`,`Write cap (${V}) reached.`);if(t.length>z)throw new U(`too-large`,`Write exceeds ${z}B: ${e}`);let n=await this.resolveForWrite(e),r=await g.readFile(n,`utf8`).catch(e=>{if(e.code===`ENOENT`)return null;throw e});if(r!==null){if(W.test(r)&&!W.test(t))throw new U(`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 G)if(i.test(r)&&!i.test(t))throw new U(`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 g.mkdir(h.dirname(n),{recursive:!0}),await g.writeFile(n,t,`utf8`),this.writeCount++;let a=await this.cwdReal;return this.writtenPathsSet.add(h.relative(a,n)),{backupPath:i}}async journalBackup(e){let t=await g.readFile(e).catch(e=>{if(e.code===`ENOENT`)return null;throw e}),n=h.join(this.undoRoot,this.sessionId);await g.mkdir(n,{recursive:!0,mode:448});let r=y.createHash(`sha256`).update(e).digest(`hex`).slice(0,16),i=h.join(n,`${r}.bak`),a=h.join(n,`manifest.jsonl`);t&&await g.writeFile(i,t,{mode:384});let o=JSON.stringify({abs:e,backupPath:t?i:null,ts:Date.now()});return await g.appendFile(a,o+`
|
|
1
|
+
import{readConfig as e,updateConfig as t}from"./config-CZ9IzjIH.js";import{ApiClient as n,readToken as r}from"./api-DXmhz2DM.js";import{parseSseStream as i}from"./client-WzSy90dG.js";import{emit as a,isHeadless as o}from"./emit-D7VCOSNk.js";import{loginCommand as s}from"./login-DWaz_EsV.js";import{Panel as c}from"./panel-uygscwY5.js";import{Banner as l}from"./banner-BPQh2F8l.js";import{BrandGradient as u,ProgressRow as d}from"./progress-row-DFOvHAc5.js";import{Select as f}from"./prompt-BURfUNxp.js";import{Keybar as p}from"./keybar-C7YkmK1U.js";import{spark as m}from"./sparkline-Bkfzqe4x.js";import h from"node:path";import{promises as g}from"node:fs";import{z as _}from"zod";import v from"node:os";import y from"node:crypto";import{Box as b,Text as x,render as S,useApp as ee,useInput as C}from"ink";import w,{useEffect as T,useRef as E,useState as D}from"react";import{globby as O}from"globby";import k from"ink-spinner";import{ulid as A}from"ulid";import{applyPatch as j}from"diff";const M=[`@zenovay/tracker`,`@zenovay/next`,`@zenovay/nuxt`,`@zenovay/svelte`,`@zenovay/astro`,`@zenovay/remix`,`@zenovay/node`],N=[`zenovay.config.ts`,`zenovay.config.js`,`zenovay.config.mjs`,`zenovay.config.json`],P=/<script[^>]*src\s*=\s*["']https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+["'][^>]*>\s*<\/script>/gi,F=/data-id\s*=\s*["'](ZV_[A-Za-z0-9]+)["']/i,I=/data-zenovay-site\s*=\s*["']([^"']+)["']/i,L=[{name:`PostHog`,patterns:[/posthog\.com\b/i,/posthog-js/,/window\.posthog/]},{name:`Plausible`,patterns:[/plausible\.io\/js/i,/window\.plausible/]},{name:`Google Analytics`,patterns:[/googletagmanager\.com\/gtag\/js/i,/www\.google-analytics\.com\/analytics\.js/i,/window\.gtag\b/]},{name:`Mixpanel`,patterns:[/cdn\.mxpnl\.com/i,/mixpanel-browser/]},{name:`Segment`,patterns:[/cdn\.segment\.com\/analytics\.js/i,/window\.analytics\b/]},{name:`Hotjar`,patterns:[/static\.hotjar\.com/i,/\(h,o,t,j,a,r\)/i]},{name:`Amplitude`,patterns:[/cdn\.amplitude\.com/i,/amplitude\.getInstance/]},{name:`Heap`,patterns:[/cdn\.heapanalytics\.com/i]},{name:`FullStory`,patterns:[/fullstory\.com\/s\/fs\.js/i,/window\.FS\.identify/]}];async function R(e,t){let n={zenovayInstalled:!1,correctTrackingCode:!1,foundTrackingCodes:[],zenovayFiles:[],competitors:[],summary:``,recommendation:`fresh-install`};try{let t=await g.readFile(h.join(e,`package.json`),`utf8`),r=JSON.parse(t),i={...r.dependencies,...r.devDependencies};for(let e of M)if(e in i){n.zenovayInstalled=!0,n.packageMarker=e;break}}catch{}for(let t of N)try{await g.access(h.join(e,t)),n.zenovayInstalled=!0,n.configFile=t;break}catch{}let r=await O([`**/*.{html,htm,tsx,jsx,vue,svelte,astro,ts,js,mjs}`,`!node_modules/**`,`!.git/**`,`!dist/**`,`!.next/**`,`!.nuxt/**`,`!build/**`,`!.output/**`],{cwd:e,gitignore:!0,deep:4,absolute:!0}).catch(()=>[]),i=new Map,a=new Set;for(let t of r.slice(0,300)){let r;try{r=await g.readFile(t,`utf8`)}catch{continue}let o=h.relative(e,t),s=r.match(P);if(s&&s.length>0){n.zenovayInstalled=!0;let e=s[0].slice(0,200),t=e.match(F)??e.match(I),r=t?.[1]??null;r&&a.add(r),n.zenovayFiles.push({file:o,currentTrackingCode:r,scriptTagCount:s.length,matchSample:e})}for(let e of L)if(e.patterns.some(e=>e.test(r))){let t=i.get(e.name)??new Set;t.add(o),i.set(e.name,t)}}if(n.foundTrackingCodes=Array.from(a),n.competitors=Array.from(i.entries()).map(([e,t])=>({name:e,files:Array.from(t).slice(0,5)})),n.zenovayInstalled)if(n.foundTrackingCodes.length>0){let e=n.foundTrackingCodes.every(e=>e===t);n.correctTrackingCode=e,n.recommendation=e?`no-op`:`update-tracking-code`}else n.correctTrackingCode=!1,n.recommendation=`no-op`;else n.competitors.length>0?n.recommendation=`fresh-install-alongside-competitor`:n.recommendation=`fresh-install`;return n.summary=te(n,t),n}function te(e,t){let n=[];return e.zenovayInstalled?e.foundTrackingCodes.length===0?n.push(`Zenovay package or config detected but no <script> tag found.`):e.correctTrackingCode?n.push(`Zenovay tracker present in ${e.zenovayFiles.length} file(s) with correct ID ${t}.`):n.push(`Zenovay tracker present in ${e.zenovayFiles.length} file(s), but with mismatching ID(s): ${e.foundTrackingCodes.join(`, `)} (target: ${t}).`):n.push(`No Zenovay tracker found.`),e.competitors.length>0&&n.push(`Competitor tracker(s) present (DO NOT modify): ${e.competitors.map(e=>e.name).join(`, `)}.`),n.join(` `)}async function ne(e){let t=await R(e,``);return{installed:t.zenovayInstalled,reasons:t.summary?[t.summary]:[],packageMarker:t.packageMarker,configFile:t.configFile,scriptFile:t.zenovayFiles[0]?.file}}const re=[{name:`openai-proj`,regex:/\bsk-proj-[A-Za-z0-9_-]{20,}\b/g},{name:`anthropic`,regex:/\bsk-ant-[A-Za-z0-9_-]{20,}\b/g},{name:`openai-sk`,regex:/\bsk-[A-Za-z0-9]{20,}\b/g},{name:`github-pat-new`,regex:/\bgithub_pat_[A-Za-z0-9_]{82}\b/g},{name:`github-pat`,regex:/\bghp_[A-Za-z0-9]{36}\b/g},{name:`github-oauth`,regex:/\bgho_[A-Za-z0-9]{36}\b/g},{name:`aws-access-key`,regex:/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g},{name:`stripe-live`,regex:/\b(?:sk|pk)_live_[A-Za-z0-9]{24,}\b/g},{name:`stripe-test`,regex:/\b(?:sk|pk)_test_[A-Za-z0-9]{24,}\b/g},{name:`stripe-restricted`,regex:/\brk_(?:live|test)_[A-Za-z0-9]{24,}\b/g},{name:`stripe-webhook`,regex:/\bwhsec_[A-Za-z0-9]{24,}\b/g},{name:`slack-bot`,regex:/\bxox[bpoa]-[A-Za-z0-9-]{10,}\b/g},{name:`google-api`,regex:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:`jwt`,regex:/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g},{name:`private-key-rsa`,regex:/-----BEGIN (?:RSA|EC|OPENSSH|DSA|PGP) PRIVATE KEY(?: BLOCK)?-----/g},{name:`private-key-pkcs8`,regex:/-----BEGIN PRIVATE KEY-----/g}];function ie(e){let t=e;for(let e of re){let n=new RegExp(e.regex.source,e.regex.flags);t=t.replace(n,`[REDACTED:${e.name}]`)}return t}const ae=[/^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)$/,/^public\/index\.html$/,/^index\.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)$/],oe=[/(^|\/)\.env($|\.(?!example$)[^/]+$)/,/(^|\/)\.git(\/|$)/,/(^|\/)node_modules\//,/(^|\/)\.ssh\//,/(^|\/)\.aws\//,/\.pem$/,/\.key$/,/(^|\/)id_rsa($|\.)/,/(^|\/)\.npmrc$/,/(^|\/)credentials(\.|$)/],z=256*1024,B=50,V=20,H=40;var U=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`SandboxError`}};const W=/<script[^>]*src\s*=\s*["']https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+["'][^>]*>\s*<\/script>/i,G=[{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 K=class{sessionId;cwd;cwdReal;undoRoot;readCount=0;writeCount=0;roundCount=0;writtenPathsSet=new Set;constructor(e){this.sessionId=e.sessionId??A(),this.cwd=e.cwd,this.cwdReal=g.realpath(e.cwd),this.undoRoot=e.undoRoot??h.join(v.homedir(),`.zenovay`,`undo`)}incrementRound(){if(this.roundCount++,this.roundCount>H)throw new U(`round-cap`,`Tool-call recursion cap (${H}) 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 U(`escape`,`Path must be a non-empty string.`);if(e.includes(`\0`))throw new U(`escape`,`Null byte in path.`);if(/^\\\\[?.]\\/.test(e)||/^\\\\[A-Za-z0-9]/.test(e))throw new U(`escape`,`Windows special path prefix: ${e}`);if(/%/.test(e))try{let t=decodeURIComponent(e);if(/%[0-9A-Fa-f]{2}/.test(t))throw new U(`escape`,`Double-encoded path: ${e}`);e=t}catch(t){throw t instanceof U?t:new U(`escape`,`Malformed percent-encoding: ${e}`)}if(e.includes(`\0`))throw new U(`escape`,`Null byte in decoded path.`);if(e.includes(`\\`))throw new U(`escape`,`Backslash in path (Windows-style separator not accepted): ${e}`);let n=await this.cwdReal,r=h.isAbsolute(e)?e:h.join(n,e),i=h.normalize(r),a=i;try{a=await g.realpath(i)}catch(e){if(e.code!==`ENOENT`)throw new U(`escape`,`realpath failed: ${e.message}`);let t=h.dirname(i);try{let e=await g.realpath(t);a=h.join(e,h.basename(i))}catch{}}if(!this.isWithin(a,n))throw new U(`escape`,`Path escapes cwd: ${e}`);let o=h.relative(n,a);for(let e of oe)if(e.test(o)){if(t===`read`&&/(^|\/)node_modules\//.test(o))continue;throw new U(`blocklisted`,`Path is on the hard blocklist: ${o}`)}if(t===`write`){let e=ae.some(e=>e.test(o));if(!e&&!/^\.env(\.local)?$/.test(o)&&!/^\.claude\//.test(o)&&!/^\.cursor\//.test(o))throw new U(`not-allowlisted`,`Write path not on allowlist: ${o}`)}return a}isWithin(e,t){let n=h.relative(t,e);return!n.startsWith(`..`)&&!h.isAbsolute(n)}async safeRead(e){if(this.readCount>=B)throw new U(`read-cap`,`Read cap (${B}) reached.`);let t=await this.resolveForRead(e),n=await g.stat(t);if(n.size>z)throw new U(`too-large`,`File exceeds ${z}B: ${e} (${n.size}B)`);let r=await g.readFile(t),i=r.subarray(0,Math.min(r.length,8192));if(i.includes(0))throw new U(`binary-rejected`,`Binary content in ${e}.`);return this.readCount++,r.toString(`utf8`)}async safeWrite(e,t){if(this.writeCount>=V)throw new U(`write-cap`,`Write cap (${V}) reached.`);if(t.length>z)throw new U(`too-large`,`Write exceeds ${z}B: ${e}`);let n=await this.resolveForWrite(e),r=await g.readFile(n,`utf8`).catch(e=>{if(e.code===`ENOENT`)return null;throw e});if(r!==null){if(W.test(r)&&!W.test(t))throw new U(`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 G)if(i.test(r)&&!i.test(t))throw new U(`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 g.mkdir(h.dirname(n),{recursive:!0}),await g.writeFile(n,t,`utf8`),this.writeCount++;let a=await this.cwdReal;return this.writtenPathsSet.add(h.relative(a,n)),{backupPath:i}}async journalBackup(e){let t=await g.readFile(e).catch(e=>{if(e.code===`ENOENT`)return null;throw e}),n=h.join(this.undoRoot,this.sessionId);await g.mkdir(n,{recursive:!0,mode:448});let r=y.createHash(`sha256`).update(e).digest(`hex`).slice(0,16),i=h.join(n,`${r}.bak`),a=h.join(n,`manifest.jsonl`);t&&await g.writeFile(i,t,{mode:384});let o=JSON.stringify({abs:e,backupPath:t?i:null,ts:Date.now()});return await g.appendFile(a,o+`
|
|
2
2
|
`,{mode:384}),t?i:null}static wrapForModel(e,t){let n=y.createHash(`sha256`).update(t).digest(`hex`).slice(0,16),r=t.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`);return`<FILE path="${e}" sha256="${n}">\n${r}\n</FILE>`}static scrubSecrets(e){return ie(e)}};const se=[`astro.config.ts`,`astro.config.mjs`,`astro.config.js`];async function ce(e){for(let t of se)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 le(e){let t=e.trackingCode??e.siteId??``,n=`<script defer data-id="${t}" data-allow-localhost="true" 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`."}]}const ue={id:`astro`,displayName:`Astro`,detect:ce,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:le},de=[`app/layout.tsx`,`app/layout.ts`,`app/layout.jsx`,`app/layout.js`];async function fe(e){for(let t of de)if(await e.exists(t))return t;return null}async function pe(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 me(e){let t=await pe(e),n=await e.exists(`app`),r=await fe(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 he(e){let t=`app/layout.tsx`,n=e.trackingCode??e.siteId??``;return[{targetPath:t,anchorKind:`after-imports`,code:`import Script from 'next/script';`,description:`Import next/script to inject the Zenovay tracker.`},{targetPath:t,anchorKind:`wrap-children`,code:`<Script
|
|
3
3
|
defer
|
|
4
4
|
data-id="${n}"
|
|
@@ -50,7 +50,7 @@ export default function App({ Component, pageProps }: AppProps) {
|
|
|
50
50
|
`)+`
|
|
51
51
|
`;if(o)await g.writeFile(i,f,`utf8`);else{let e=await g.open(i,`w`,384);try{await e.writeFile(f,`utf8`)}finally{await e.close()}}return{created:!o,existing:o,addedKeys:c,skippedKeys:l}}const He=`https://api.zenovay.com/mcp`,Ue=_.object({url:_.string().url(),headers:_.record(_.string(),_.string()).optional()}),We=_.object({mcpServers:_.record(_.string(),Ue).optional()}).passthrough();function Ge(e){return e.HOME??e.USERPROFILE??v.homedir()}function Ke(e){return e.APPDATA??null}function qe(e,t){let n=Ge(t),r=Ke(t),i=[];return i.push({id:`cursor`,displayName:`Cursor`,configPath:h.join(n,`.cursor`,`mcp.json`)}),e===`win32`&&r&&i.push({id:`cursor`,displayName:`Cursor (AppData)`,configPath:h.join(r,`Cursor`,`User`,`globalStorage`,`cursor.mcp`,`mcp.json`)}),e===`darwin`?i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:h.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`)}):e===`win32`&&r?i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:h.join(r,`Claude`,`claude_desktop_config.json`)}):i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:h.join(n,`.config`,`Claude`,`claude_desktop_config.json`)}),i.push({id:`vscode`,displayName:`VS Code`,configPath:h.join(n,`.vscode`,`mcp.json`)}),i}async function Je(e){try{return await g.access(e),!0}catch{return!1}}async function Ye(e){try{let t=await g.readFile(e,`utf8`);if(t.trim().length===0)return{};let n=JSON.parse(t),r=We.safeParse(n);return r.success?r.data:n&&typeof n==`object`?n:{}}catch{return{}}}function Xe(e){return{url:He,headers:{Authorization:`Bearer ${e}`}}}async function Y(e){let t=e.env??process.env,n=e.platform??process.platform,r=new Set(e.skip??[]),i=[],a=[],o=[],s=new Set,c=Xe(e.accessToken);for(let e of qe(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 Je(e.configPath);if(!t){a.push(e.displayName);continue}let n=await Ye(e.configPath),r=`${e.configPath}.bak`;await g.copyFile(e.configPath,r);let o={...n,mcpServers:{...n.mcpServers??{},zenovay:c}};await g.mkdir(h.dirname(e.configPath),{recursive:!0}),await g.writeFile(e.configPath,JSON.stringify(o,null,2)+`
|
|
52
52
|
`,`utf8`),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 Ze(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 Qe=_.object({path:_.string().min(1)}),$e=_.object({path:_.string().min(1),content:_.string(),reason:_.string().min(1)}),et=_.object({path:_.string().min(1),patch:_.string().min(1),reason:_.string().min(1)}),tt=_.object({}),nt=_.object({question:_.string().min(1),choices:_.array(_.string()).optional()});async function rt(e,t){let n=Qe.safeParse(t);if(!n.success)return{ok:!1,content:null,error:`invalid_args`};try{let t=await e.safeRead(n.data.path),r=K.scrubSecrets(t);return{ok:!0,content:K.wrapForModel(n.data.path,r)}}catch(e){return{ok:!1,content:null,error:e.message}}}async function it(e,t,n){let r=$e.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 at(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=j(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.`}:it(e,{path:i,content:c,reason:o},n)}async function ot(e){try{let t=Re(e),{adapter:n,ranked:r}=await q(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 st(e,t){let n=nt.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}}}async function ct(e){let{api:t,sandbox:n,approval:r,prompter:a,handlers:o}=e,s=[...e.initialMessages],c=``,l=0;for(;l<H;){n.incrementRound(),l++;let u=await t.openAiStream(`install`,{messages:s,cwd_fingerprint:n.sessionId,diagnosis:e.diagnosis,targetTrackingCode:e.targetTrackingCode}),d=[],f=``;for await(let e of i(u))switch(e.type){case`delta`:f+=e.content,o?.onDelta?.(e.content);break;case`tool_start`:o?.onToolStart?.({id:e.id,name:e.name});break;case`tool_call`:{let t=await lt(e.name,e.arguments,{sandbox:n,cwd:n.cwd,approval:r,prompter:a});d.push({id:e.id,name:e.name,arguments:e.arguments,result:t}),o?.onToolResult?.({id:e.id,name:e.name,result:t});break}case`usage`:o?.onUsage?.(e);break;case`error`:throw o?.onError?.(e),Error(`[${e.code}] ${e.message}`);case`done`:break}if(f&&(c+=f),d.length===0){f&&s.push({role:`assistant`,content:f});break}s.push({role:`assistant`,content:f,toolCalls:d.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))});for(let e of d)s.push({role:`tool`,toolCallId:e.id,toolName:e.name,content:JSON.stringify(e.result)})}return{finalText:c,rounds:l}}async function lt(e,t,n){try{switch(e){case`read_file`:return await rt(n.sandbox,t);case`write_file`:return await it(n.sandbox,t,n.approval);case`patch_file`:return await at(n.sandbox,t,n.approval);case`detect_framework`:return await ot(n.cwd);case`ask_user`:return await st(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 ut=e=>`<script defer\n data-id="${e}"\n data-allow-localhost="true"\n src="https://api.zenovay.com/z.js">\n</script>`;async function dt(e){let t={installed:[],skipped:[],errors:[]},n=await O([`**/*.html`,`!node_modules/**`,`!.git/**`,`!dist/**`,`!.next/**`,`!.nuxt/**`,`!build/**`,`!.output/**`],{cwd:e.cwd,gitignore:!0,absolute:!1});if(n.length===0)return t;let r=ut(e.trackingCode),i=RegExp(`data-id\\s*=\\s*["']${ft(e.trackingCode)}["']`);for(let a of n){let n=h.join(e.cwd,a),o;try{o=await g.readFile(n,`utf8`)}catch(e){t.errors.push({file:a,error:e.message});continue}if(W.test(o)&&i.test(o)){t.skipped.push({file:a,reason:`already installed with correct tracking code`});continue}let s;if(W.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??`
|
|
53
|
-
`,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 G)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 g.writeFile(n,s,`utf8`),t.installed.push(a)}catch(e){t.errors.push({file:a,error:e.message})}}return t}function ft(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function pt(){let e=[12,15,18,22,28,35,41,50,58,64,72,78],t=m(e,24);return[` ↑`,` ${t}`,` └────────────────────────`,` May Jun Jul Aug Sep`]}function mt(){return[` Landing page ████████████████████ 100%`,` ↓ -28%`,` Pricing ██████████████░░░░░░ 72%`,` ↓ -50%`,` Checkout ███████░░░░░░░░░░░░░ 36%`,` ↓ -64%`,` Purchased ███░░░░░░░░░░░░░░░░░ 13%`]}function ht(){return[` ▇▇▇▇▇▇▇▇▇▎ 89 Sarah K. /pricing 🇺🇸`,` ▇▇▇▇▇▇░░░░ 61 anon /docs 🇩🇪`,` ▇▇▇░░░░░░░ 34 anon /changelog 🇯🇵`]}function gt(){return[` LCP ● 2.1s good ████████████░░░░░░`,` INP ● 89ms good ██████████████████`,` CLS ⚠ 0.14 needs ████████████░░░░░░`,` TTFB ● 380ms good ███████████████░░░`]}const X=[{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:pt},{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:mt},{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:ht},{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:gt},{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.`]}],_t=8e3,vt=({width:e,height:t})=>{let[n,r]=D(0);T(()=>{let e=setInterval(()=>{r(e=>(e+1)%X.length)},_t);return()=>clearInterval(e)},[]);let i=X[n],a=i.visual?i.visual():[],o=X.map((e,t)=>t===n?`●`:`·`).join(` `);return w.createElement(b,{flexDirection:`column`,width:e,height:t,paddingX:2,paddingY:1},w.createElement(b,{marginBottom:1},w.createElement(x,{color:`magentaBright`,bold:!0},`Learn`)),w.createElement(b,{marginBottom:1},w.createElement(x,{bold:!0,color:`white`},i.title)),i.body.map((e,t)=>w.createElement(x,{key:t,color:`gray`},e||` `)),a.length>0&&w.createElement(b,{flexDirection:`column`,marginTop:1},a.map((e,t)=>w.createElement(x,{key:t,color:`cyan`},e))),w.createElement(b,{flexGrow:1}),w.createElement(b,{marginTop:1},w.createElement(x,{color:`gray`,dimColor:!0},o,` · `,n+1,` / `,X.length)))},yt={pending:`·`,active:`⠋`,done:`✓`,error:`✗`},bt={pending:`gray`,active:`magenta`,done:`green`,error:`red`},xt=({tasks:e,width:t,height:n,liveLine:r})=>{let i=e.filter(e=>e.status===`done`).length;return w.createElement(b,{flexDirection:`column`,width:t,height:n,paddingX:2,paddingY:1},w.createElement(b,{marginBottom:1},w.createElement(x,{color:`magentaBright`,bold:!0},`Tasks`)),e.map(e=>w.createElement(b,{key:e.id,flexDirection:`column`},w.createElement(b,null,e.status===`active`?w.createElement(x,{color:`magenta`},w.createElement(k,{type:`dots`})):w.createElement(x,{color:bt[e.status]},yt[e.status]),w.createElement(x,null,` `),w.createElement(x,{color:e.status===`pending`?`gray`:`white`},e.label)),e.detail&&w.createElement(b,{paddingLeft:2},w.createElement(x,{color:`gray`,dimColor:!0},e.detail)))),w.createElement(b,{flexGrow:1}),r&&w.createElement(b,{marginTop:1},w.createElement(x,{color:`cyan`},`◆ `),w.createElement(x,{color:`white`},r)),w.createElement(b,{marginTop:1},w.createElement(x,{color:`gray`,dimColor:!0},i,` / `,e.length)))};async function St(e){if(o(e))return Ct(e);let t=`quit`,n=null,r=await new Promise(r=>{let{unmount:i,waitUntilExit:a}=S(w.createElement(wt,{opts:e,onExit:(e,a,o)=>{t=a??`quit`,n=o??null,i(),r(e)}}));a().catch(()=>r(1))});if(r!==0||t===`quit`||!n)return r;let i=n.id;if(t===`watch`){let{watchCommand:t}=await import(`./watch-CbehE_bK.js`);return t({cliVersion:e.cliVersion,siteId:i})}if(t===`events`){let{eventsTailCommand:t}=await import(`./events-tail-Cytm6gdG.js`);return t({cliVersion:e.cliVersion,siteId:i})}return 0}async function Ct(t){try{let i=await e(),o=await ze(t.cwd);if(!o)return a({type:`error`,code:`no_framework`,message:`Could not detect framework (headless mode has no picker).`}),2;a({type:`framework.detected`,framework:o.id,confidence:1});let s=await r({strict:!1});if(!s&&!process.env.ZENOVAY_API_TOKEN)return a({type:`error`,code:`not_logged_in`,message:"Run `zenovay login` first (or set ZENOVAY_API_TOKEN)."}),2;let c=new n({config:i,cliVersion:t.cliVersion,token:s}),l=await c.getSites(),u=t.siteId?l.find(e=>e.id===t.siteId):l[0];if(!u&&t.siteId)return a({type:`error`,code:`site_not_found`,message:`Site ${t.siteId} not found.`}),2;if(!u)return a({type:`error`,code:`no_site`,message:`No sites exist; create one at app.zenovay.com or re-run interactively.`}),2;a({type:`info`,message:`Using site ${u.id} (${u.name}) trackingCode=${u.trackingCode??u.id}`});let d=await J(t.cwd,{[o.envVarName]:u.trackingCode??u.id});return a({type:`info`,message:`env vars added: ${d.addedKeys.join(`,`)}`}),a({type:`done`,command:`init`,exitCode:0}),0}catch(e){return a({type:`error`,code:`init_failed`,message:e.message}),1}}const wt=({opts:t,onExit:i})=>{let{exit:a}=ee(),[o,u]=D(`intro`),[d,f]=D(null),[m,h]=D([]),[g,_]=D(null),[v,y]=D(null),[S,C]=D(null),[O,A]=D([]),[j,M]=D(void 0),[N,P]=D(null),[F,I]=D(0),L=E(!1);return T(()=>(process.stdout.isTTY&&process.stdout.write(`\x1B[?1049h\x1B[H`),()=>{process.stdout.isTTY&&process.stdout.write(`\x1B[?1049l`)}),[]),T(()=>{L.current||(L.current=!0,(async()=>{try{u(`detecting`);let i=await ze(t.cwd);if(!i){C(`Could not detect your framework. Supported: Next.js, Nuxt, SvelteKit, Astro, Remix, plain HTML.`),u(`error`);return}f(i);let a=await r({strict:!1});!process.env.ZENOVAY_API_TOKEN&&!a&&(u(`login`),await s({cliVersion:t.cliVersion})),u(`loading-sites`);let o=await e(),c=await r({strict:!1}),l=new n({config:o,cliVersion:t.cliVersion,token:c}),d=await l.getSites(),p=await Rt(t.cwd),m=zt(d,p);if(h(d),_(p),d.length===0){u(`create-site`);return}if(t.siteId){let e=d.find(e=>e.id===t.siteId);if(!e){C(`Site ${t.siteId} not found in your account.`),u(`error`);return}y(e),Z(e,i,t,{setPhase:u,setErrorMsg:C,setTasks:A,setLiveLine:M,setSandboxStats:P});return}if(t.yes&&m){y(m),Z(m,i,t,{setPhase:u,setErrorMsg:C,setTasks:A,setLiveLine:M,setSandboxStats:P});return}u(`site-picker`)}catch(e){C(e.message),u(`error`)}})())},[]),T(()=>{o===`error`&&setTimeout(()=>{a(),i(1)},8e3)},[o]),w.createElement(b,{flexDirection:`column`},w.createElement(l,{version:t.cliVersion,subtitle:`AI install wizard`}),o===`intro`&&w.createElement(Tt,null),o===`detecting`&&w.createElement(c,{title:`Scanning`,state:`busy`},w.createElement(b,null,w.createElement(x,{color:`magenta`},w.createElement(k,{type:`dots`})),w.createElement(x,null,` Detecting framework…`))),o===`login`&&w.createElement(c,{title:`Authenticating`,state:`busy`},w.createElement(x,null,`Opening browser for login… (paste ZENOVAY_API_TOKEN env var to skip)`)),o===`loading-sites`&&w.createElement(c,{title:`Loading your sites`,state:`busy`},w.createElement(b,null,w.createElement(x,{color:`magenta`},w.createElement(k,{type:`dots`})),w.createElement(x,null,` Fetching your Zenovay sites…`))),o===`site-picker`&&d&&w.createElement(Dt,{sites:m,preselectHint:g,onPick:e=>{if(e===`create-new`){u(`create-site`);return}y(e),Z(e,d,t,{setPhase:u,setErrorMsg:C,setTasks:A,setLiveLine:M,setSandboxStats:P})}}),o===`create-site`&&w.createElement(c,{title:`Create a new site`,state:`warn`},w.createElement(x,{color:`yellow`},"No site picked (or none exist yet). Visit https://app.zenovay.com/websites to create one, then re-run `zenovay init`."),w.createElement(x,{color:`gray`},`(Inline site creation from the CLI is scheduled for V1.1 — it requires a plan-limit check.)`)),o===`agent`&&d&&v&&w.createElement(Et,{adapter:d,site:v,tasks:O,liveLine:j}),o===`install-complete`&&d&&v&&w.createElement(At,{adapter:d,site:v,stats:N,onCommit:()=>u(`commit-prompt`),onSkipCommit:()=>u(`deploy-prompt`)}),o===`commit-prompt`&&v&&w.createElement(jt,{cwd:t.cwd,onDone:e=>{e.committed&&M(`Pushed ${e.shortSha} to ${e.branch}`),u(`deploy-prompt`)},onError:e=>{C(e),u(`error`)}}),o===`deploy-prompt`&&v&&w.createElement(Mt,{site:v,onDeployed:()=>u(`visit-prompt`),onSkip:()=>u(`verify`)}),o===`visit-prompt`&&v&&w.createElement(Nt,{site:v,onContinue:()=>u(`verify`)}),o===`verify`&&v&&w.createElement(Ft,{site:v,elapsed:F,onTick:e=>I(e),onArrived:()=>u(`success`),onTimeout:()=>u(`success`)}),o===`success`&&d&&v&&w.createElement(kt,{adapter:d,site:v,stats:N,onPick:e=>{a(),i(0,e,v)}}),o===`error`&&w.createElement(c,{title:`Install failed`,state:`err`},w.createElement(x,{color:`red`},S??`Unknown error`)),w.createElement(p,{items:[{key:`q`,label:`quit`},{key:`ctrl-c`,label:`abort`}]}))};async function Z(i,a,o,s){try{s.setPhase(`agent`);let c=await e(),l=await r({strict:!1}),u=new n({config:c,cliVersion:o.cliVersion,token:l}),d=new K({cwd:o.cwd}),f=i.trackingCode??i.id;await t({defaultSiteId:i.id,defaultSiteName:i.name}).catch(()=>void 0);let p=await R(o.cwd,f);if(p.recommendation===`no-op`){s.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:`done`,detail:`already installed correctly`}:e)),s.setLiveLine(p.summary),s.setSandboxStats?.({reads:0,writes:0,rounds:0}),!o.skipMcp&&l&&await Y({accessToken:l.accessToken}).catch(()=>void 0),s.setPhase(`install-complete`);return}p.competitors.length>0&&s.setLiveLine(`Detected ${p.competitors.map(e=>e.name).join(`, `)} — will install Zenovay alongside (won't touch their tags).`);let m=a.id===`plain-html`&&(p.recommendation===`fresh-install`||p.recommendation===`fresh-install-alongside-competitor`||p.recommendation===`update-tracking-code`);if(m){s.setTasks(e=>e.map(e=>e.id===`detect`?{...e,status:`done`,detail:`Plain HTML`}:e)),s.setLiveLine(`Plain HTML — using fast install path (no AI needed)…`);let e=await dt({cwd:o.cwd,trackingCode:f,updateOnly:p.recommendation===`update-tracking-code`});if(e.installed.length===0&&e.errors.length===0)throw Error(`No HTML files were modified. Either no .html files contain a <head>...</head> block, or every file already has the correct tracker.`);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}`);s.setTasks(t=>t.map(t=>t.id===`read`||t.id===`write`?{...t,status:`done`,detail:`${e.installed.length} file(s)`}:t)),s.setLiveLine(`Tracker added to ${e.installed.length} file(s). Skipped ${e.skipped.length}, errored ${e.errors.length}.`);let t=await J(o.cwd,{[a.envVarName]:f});if(s.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${t.addedKeys.length} key(s) added`}:e)),!o.skipMcp&&l){let e=await Y({accessToken:l.accessToken}).catch(()=>null);s.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:e&&e.installed.length>0?e.installed.join(`, `):`none detected`}:t))}else s.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));s.setLiveLine(void 0),s.setSandboxStats?.({reads:e.installed.length,writes:e.installed.length,rounds:0}),s.setPhase(`install-complete`);return}let h=a.buildSnippets({trackingCode:f,siteId:i.id}),g=`Install Zenovay tracking into this ${a.displayName} project.\nSite: ${i.name} (trackingCode: ${f}).\n1. Call detect_framework to confirm the framework.\n2. Read the entry file(s) for this framework:\n`+a.files.map(e=>` - ${e.path}`).join(`
|
|
53
|
+
`,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 G)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 g.writeFile(n,s,`utf8`),t.installed.push(a)}catch(e){t.errors.push({file:a,error:e.message})}}return t}function ft(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function pt(){let e=[12,15,18,22,28,35,41,50,58,64,72,78],t=m(e,24);return[` ↑`,` ${t}`,` └────────────────────────`,` May Jun Jul Aug Sep`]}function mt(){return[` Landing page ████████████████████ 100%`,` ↓ -28%`,` Pricing ██████████████░░░░░░ 72%`,` ↓ -50%`,` Checkout ███████░░░░░░░░░░░░░ 36%`,` ↓ -64%`,` Purchased ███░░░░░░░░░░░░░░░░░ 13%`]}function ht(){return[` ▇▇▇▇▇▇▇▇▇▎ 89 Sarah K. /pricing 🇺🇸`,` ▇▇▇▇▇▇░░░░ 61 anon /docs 🇩🇪`,` ▇▇▇░░░░░░░ 34 anon /changelog 🇯🇵`]}function gt(){return[` LCP ● 2.1s good ████████████░░░░░░`,` INP ● 89ms good ██████████████████`,` CLS ⚠ 0.14 needs ████████████░░░░░░`,` TTFB ● 380ms good ███████████████░░░`]}const X=[{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:pt},{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:mt},{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:ht},{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:gt},{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.`]}],_t=8e3,vt=({width:e,height:t})=>{let[n,r]=D(0);T(()=>{let e=setInterval(()=>{r(e=>(e+1)%X.length)},_t);return()=>clearInterval(e)},[]);let i=X[n],a=i.visual?i.visual():[],o=X.map((e,t)=>t===n?`●`:`·`).join(` `);return w.createElement(b,{flexDirection:`column`,width:e,height:t,paddingX:2,paddingY:1},w.createElement(b,{marginBottom:1},w.createElement(x,{color:`magentaBright`,bold:!0},`Learn`)),w.createElement(b,{marginBottom:1},w.createElement(x,{bold:!0,color:`white`},i.title)),i.body.map((e,t)=>w.createElement(x,{key:t,color:`gray`},e||` `)),a.length>0&&w.createElement(b,{flexDirection:`column`,marginTop:1},a.map((e,t)=>w.createElement(x,{key:t,color:`cyan`},e))),w.createElement(b,{flexGrow:1}),w.createElement(b,{marginTop:1},w.createElement(x,{color:`gray`,dimColor:!0},o,` · `,n+1,` / `,X.length)))},yt={pending:`·`,active:`⠋`,done:`✓`,error:`✗`},bt={pending:`gray`,active:`magenta`,done:`green`,error:`red`},xt=({tasks:e,width:t,height:n,liveLine:r})=>{let i=e.filter(e=>e.status===`done`).length;return w.createElement(b,{flexDirection:`column`,width:t,height:n,paddingX:2,paddingY:1},w.createElement(b,{marginBottom:1},w.createElement(x,{color:`magentaBright`,bold:!0},`Tasks`)),e.map(e=>w.createElement(b,{key:e.id,flexDirection:`column`},w.createElement(b,null,e.status===`active`?w.createElement(x,{color:`magenta`},w.createElement(k,{type:`dots`})):w.createElement(x,{color:bt[e.status]},yt[e.status]),w.createElement(x,null,` `),w.createElement(x,{color:e.status===`pending`?`gray`:`white`},e.label)),e.detail&&w.createElement(b,{paddingLeft:2},w.createElement(x,{color:`gray`,dimColor:!0},e.detail)))),w.createElement(b,{flexGrow:1}),r&&w.createElement(b,{marginTop:1},w.createElement(x,{color:`cyan`},`◆ `),w.createElement(x,{color:`white`},r)),w.createElement(b,{marginTop:1},w.createElement(x,{color:`gray`,dimColor:!0},i,` / `,e.length)))};async function St(e){if(o(e))return Ct(e);let t=`quit`,n=null,r=await new Promise(r=>{let{unmount:i,waitUntilExit:a}=S(w.createElement(wt,{opts:e,onExit:(e,a,o)=>{t=a??`quit`,n=o??null,i(),r(e)}}));a().catch(()=>r(1))});if(r!==0||t===`quit`||!n)return r;let i=n.id;if(t===`watch`){let{watchCommand:t}=await import(`./watch-CL5zAa_r.js`);return t({cliVersion:e.cliVersion,siteId:i})}if(t===`events`){let{eventsTailCommand:t}=await import(`./events-tail-5rwtRF4X.js`);return t({cliVersion:e.cliVersion,siteId:i})}return 0}async function Ct(t){try{let i=await e(),o=await ze(t.cwd);if(!o)return a({type:`error`,code:`no_framework`,message:`Could not detect framework (headless mode has no picker).`}),2;a({type:`framework.detected`,framework:o.id,confidence:1});let s=await r({strict:!1});if(!s&&!process.env.ZENOVAY_API_TOKEN)return a({type:`error`,code:`not_logged_in`,message:"Run `zenovay login` first (or set ZENOVAY_API_TOKEN)."}),2;let c=new n({config:i,cliVersion:t.cliVersion,token:s}),l=await c.getSites(),u=t.siteId?l.find(e=>e.id===t.siteId):l[0];if(!u&&t.siteId)return a({type:`error`,code:`site_not_found`,message:`Site ${t.siteId} not found.`}),2;if(!u)return a({type:`error`,code:`no_site`,message:`No sites exist; create one at app.zenovay.com or re-run interactively.`}),2;a({type:`info`,message:`Using site ${u.id} (${u.name}) trackingCode=${u.trackingCode??u.id}`});let d=await J(t.cwd,{[o.envVarName]:u.trackingCode??u.id});return a({type:`info`,message:`env vars added: ${d.addedKeys.join(`,`)}`}),a({type:`done`,command:`init`,exitCode:0}),0}catch(e){return a({type:`error`,code:`init_failed`,message:e.message}),1}}const wt=({opts:t,onExit:i})=>{let{exit:a}=ee(),[o,u]=D(`intro`),[d,f]=D(null),[m,h]=D([]),[g,_]=D(null),[v,y]=D(null),[S,C]=D(null),[O,A]=D([]),[j,M]=D(void 0),[N,P]=D(null),[F,I]=D(0),L=E(!1);return T(()=>(process.stdout.isTTY&&process.stdout.write(`\x1B[?1049h\x1B[H`),()=>{process.stdout.isTTY&&process.stdout.write(`\x1B[?1049l`)}),[]),T(()=>{L.current||(L.current=!0,(async()=>{try{u(`detecting`);let i=await ze(t.cwd);if(!i){C(`Could not detect your framework. Supported: Next.js, Nuxt, SvelteKit, Astro, Remix, plain HTML.`),u(`error`);return}f(i);let a=await r({strict:!1});!process.env.ZENOVAY_API_TOKEN&&!a&&(u(`login`),await s({cliVersion:t.cliVersion})),u(`loading-sites`);let o=await e(),c=await r({strict:!1}),l=new n({config:o,cliVersion:t.cliVersion,token:c}),d=await l.getSites(),p=await Rt(t.cwd),m=zt(d,p);if(h(d),_(p),d.length===0){u(`create-site`);return}if(t.siteId){let e=d.find(e=>e.id===t.siteId);if(!e){C(`Site ${t.siteId} not found in your account.`),u(`error`);return}y(e),Z(e,i,t,{setPhase:u,setErrorMsg:C,setTasks:A,setLiveLine:M,setSandboxStats:P});return}if(t.yes&&m){y(m),Z(m,i,t,{setPhase:u,setErrorMsg:C,setTasks:A,setLiveLine:M,setSandboxStats:P});return}u(`site-picker`)}catch(e){C(e.message),u(`error`)}})())},[]),T(()=>{o===`error`&&setTimeout(()=>{a(),i(1)},8e3)},[o]),w.createElement(b,{flexDirection:`column`},w.createElement(l,{version:t.cliVersion,subtitle:`AI install wizard`}),o===`intro`&&w.createElement(Tt,null),o===`detecting`&&w.createElement(c,{title:`Scanning`,state:`busy`},w.createElement(b,null,w.createElement(x,{color:`magenta`},w.createElement(k,{type:`dots`})),w.createElement(x,null,` Detecting framework…`))),o===`login`&&w.createElement(c,{title:`Authenticating`,state:`busy`},w.createElement(x,null,`Opening browser for login… (paste ZENOVAY_API_TOKEN env var to skip)`)),o===`loading-sites`&&w.createElement(c,{title:`Loading your sites`,state:`busy`},w.createElement(b,null,w.createElement(x,{color:`magenta`},w.createElement(k,{type:`dots`})),w.createElement(x,null,` Fetching your Zenovay sites…`))),o===`site-picker`&&d&&w.createElement(Dt,{sites:m,preselectHint:g,onPick:e=>{if(e===`create-new`){u(`create-site`);return}y(e),Z(e,d,t,{setPhase:u,setErrorMsg:C,setTasks:A,setLiveLine:M,setSandboxStats:P})}}),o===`create-site`&&w.createElement(c,{title:`Create a new site`,state:`warn`},w.createElement(x,{color:`yellow`},"No site picked (or none exist yet). Visit https://app.zenovay.com/websites to create one, then re-run `zenovay init`."),w.createElement(x,{color:`gray`},`(Inline site creation from the CLI is scheduled for V1.1 — it requires a plan-limit check.)`)),o===`agent`&&d&&v&&w.createElement(Et,{adapter:d,site:v,tasks:O,liveLine:j}),o===`install-complete`&&d&&v&&w.createElement(At,{adapter:d,site:v,stats:N,onCommit:()=>u(`commit-prompt`),onSkipCommit:()=>u(`deploy-prompt`)}),o===`commit-prompt`&&v&&w.createElement(jt,{cwd:t.cwd,onDone:e=>{e.committed&&M(`Pushed ${e.shortSha} to ${e.branch}`),u(`deploy-prompt`)},onError:e=>{C(e),u(`error`)}}),o===`deploy-prompt`&&v&&w.createElement(Mt,{site:v,onDeployed:()=>u(`visit-prompt`),onSkip:()=>u(`verify`)}),o===`visit-prompt`&&v&&w.createElement(Nt,{site:v,onContinue:()=>u(`verify`)}),o===`verify`&&v&&w.createElement(Ft,{site:v,elapsed:F,onTick:e=>I(e),onArrived:()=>u(`success`),onTimeout:()=>u(`success`)}),o===`success`&&d&&v&&w.createElement(kt,{adapter:d,site:v,stats:N,onPick:e=>{a(),i(0,e,v)}}),o===`error`&&w.createElement(c,{title:`Install failed`,state:`err`},w.createElement(x,{color:`red`},S??`Unknown error`)),w.createElement(p,{items:[{key:`q`,label:`quit`},{key:`ctrl-c`,label:`abort`}]}))};async function Z(i,a,o,s){try{s.setPhase(`agent`);let c=await e(),l=await r({strict:!1}),u=new n({config:c,cliVersion:o.cliVersion,token:l}),d=new K({cwd:o.cwd}),f=i.trackingCode??i.id;await t({defaultSiteId:i.id,defaultSiteName:i.name}).catch(()=>void 0);let p=await R(o.cwd,f);if(p.recommendation===`no-op`){s.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:`done`,detail:`already installed correctly`}:e)),s.setLiveLine(p.summary),s.setSandboxStats?.({reads:0,writes:0,rounds:0}),!o.skipMcp&&l&&await Y({accessToken:l.accessToken}).catch(()=>void 0),s.setPhase(`install-complete`);return}p.competitors.length>0&&s.setLiveLine(`Detected ${p.competitors.map(e=>e.name).join(`, `)} — will install Zenovay alongside (won't touch their tags).`);let m=a.id===`plain-html`&&(p.recommendation===`fresh-install`||p.recommendation===`fresh-install-alongside-competitor`||p.recommendation===`update-tracking-code`);if(m){s.setTasks(e=>e.map(e=>e.id===`detect`?{...e,status:`done`,detail:`Plain HTML`}:e)),s.setLiveLine(`Plain HTML — using fast install path (no AI needed)…`);let e=await dt({cwd:o.cwd,trackingCode:f,updateOnly:p.recommendation===`update-tracking-code`});if(e.installed.length===0&&e.errors.length===0)throw Error(`No HTML files were modified. Either no .html files contain a <head>...</head> block, or every file already has the correct tracker.`);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}`);s.setTasks(t=>t.map(t=>t.id===`read`||t.id===`write`?{...t,status:`done`,detail:`${e.installed.length} file(s)`}:t)),s.setLiveLine(`Tracker added to ${e.installed.length} file(s). Skipped ${e.skipped.length}, errored ${e.errors.length}.`);let t=await J(o.cwd,{[a.envVarName]:f});if(s.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${t.addedKeys.length} key(s) added`}:e)),!o.skipMcp&&l){let e=await Y({accessToken:l.accessToken}).catch(()=>null);s.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:e&&e.installed.length>0?e.installed.join(`, `):`none detected`}:t))}else s.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));s.setLiveLine(void 0),s.setSandboxStats?.({reads:e.installed.length,writes:e.installed.length,rounds:0}),s.setPhase(`install-complete`);return}let h=a.buildSnippets({trackingCode:f,siteId:i.id}),g=`Install Zenovay tracking into this ${a.displayName} project.\nSite: ${i.name} (trackingCode: ${f}).\n1. Call detect_framework to confirm the framework.\n2. Read the entry file(s) for this framework:\n`+a.files.map(e=>` - ${e.path}`).join(`
|
|
54
54
|
`)+`
|
|
55
55
|
3. Insert the tracker using the snippet below.
|
|
56
56
|
4. Confirm the change with a diff before writing.
|
|
@@ -59,4 +59,4 @@ Snippet reference (anchored by anchorKind — adapt to the actual file):
|
|
|
59
59
|
`+h.map(e=>` ${e.anchorKind} @ ${e.targetPath}:\n ${e.code.replace(/\n/g,`
|
|
60
60
|
`)}`).join(`
|
|
61
61
|
|
|
62
|
-
`);s.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 (Cursor/Claude/VS Code)`,status:`pending`},{id:`verify`,label:`Wait for first event`,status:`pending`}]);let _=(e,t,n)=>{s.setTasks(r=>r.map(r=>r.id===e?{...r,status:t,detail:n??r.detail}:r))},v=null;try{await ct({api:u,sandbox:d,approval:{async approve(){return`y`}},prompter:{async ask({question:e}){return e}},handlers:{onToolStart:({name:e})=>{e===`detect_framework`?(_(`detect`,`active`),s.setLiveLine(`Inspecting package.json + config files…`)):e===`read_file`?(_(`detect`,`done`),_(`read`,`active`)):(e===`write_file`||e===`patch_file`)&&(_(`read`,`done`),_(`write`,`active`))},onToolResult:({name:e,result:t})=>{let n=t?.ok!==!1,r=t?.content??{};e===`detect_framework`&&n&&(_(`detect`,`done`,a.displayName),s.setLiveLine(`Detected ${a.displayName}`)),e===`read_file`&&n&&r.path&&s.setLiveLine(`Read ${r.path}`),(e===`write_file`||e===`patch_file`)&&n&&r.path&&s.setLiveLine(`Wrote ${r.path}`)},onDelta:e=>{let t=e.replace(/\s+/g,` `).trim();t.length>4&&s.setLiveLine(t.slice(0,80))}},initialMessages:[{role:`user`,content:g}],diagnosis:p,targetTrackingCode:f})}catch(e){v=e}let y=d.stats();if(y.writes===0){let e=v?`Agent error: ${v.message}`:`Agent returned without writing any files (${y.reads} reads, ${y.rounds} rounds). The model may have refused or the AI Gateway may be misconfigured. Check api.zenovay.com logs.`;throw Error(e)}let b=a.files.map(e=>e.path),x=y.writtenPaths.some(e=>b.some(t=>e===t||e.endsWith(`/${t}`)));if(!x)throw Error(`Agent wrote to: [${y.writtenPaths.join(`, `)}] but never modified the framework's tracker target file(s): [${b.join(`, `)}]. The tracker is NOT installed. The model likely put the trackingCode into .env.local instead of into the HTML/JSX entry file.`);_(`write`,`done`),_(`env`,`active`),s.setLiveLine(`Adding env var to .env.local`);let S=await J(o.cwd,{[a.envVarName]:f});if(_(`env`,`done`,`${S.addedKeys.length} key(s) added`),!o.skipMcp&&l){_(`mcp`,`active`),s.setLiveLine(`Detecting Cursor / Claude Desktop / VS Code…`);let e=await Y({accessToken:l.accessToken}).catch(()=>null);e&&e.installed.length>0?_(`mcp`,`done`,e.installed.join(`, `)):_(`mcp`,`done`,`none detected`)}else _(`mcp`,`done`,`skipped`);s.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:e.status===`pending`?`done`:e.status}:e)),s.setLiveLine(void 0),s.setSandboxStats?.(y),s.setPhase(`install-complete`)}catch(e){s.setErrorMsg(e.message),s.setPhase(`error`)}}const Tt=()=>w.createElement(c,{title:`Zenovay wants to set up your project`,state:`idle`},w.createElement(x,null,`We'll use AI to analyze your codebase and add the Zenovay tracker.`),w.createElement(x,{color:`gray`},`.env* contents stay on your machine. Only framework metadata reaches api.zenovay.com.`)),Et=({adapter:e,site:t,tasks:n,liveLine:r})=>{let i=process.stdout.columns??100,a=(process.stdout.rows??30)-8,o=Math.floor(i/2)-1,s=Math.max(14,a);return w.createElement(b,{flexDirection:`column`},w.createElement(b,{flexDirection:`row`,minHeight:s,borderStyle:`round`,borderColor:`gray`},w.createElement(b,{width:o,flexDirection:`column`},w.createElement(vt,{width:o,height:s})),w.createElement(b,{width:1,flexDirection:`column`},w.createElement(x,{color:`gray`},`│`)),w.createElement(b,{width:o,flexDirection:`column`},w.createElement(b,{paddingX:2,paddingTop:1},w.createElement(f,{done:n.filter(e=>e.status===`done`).length,total:n.length,label:n.find(e=>e.status===`active`)?.label})),w.createElement(xt,{tasks:n,liveLine:r,width:o,height:s}))),w.createElement(b,{marginTop:1},w.createElement(x,{color:`gray`},`Site: `,t.name,` · code: `,t.trackingCode??t.id,` · Framework: `,e.displayName)))},Dt=({sites:e,preselectHint:t,onPick:n})=>{let r=zt(e,t),i=e.filter(e=>e.id!==r?.id),a=r?[r,...i]:i,o=[...a.map(e=>({label:Lt(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 w.createElement(c,{title:t?`Pick a site (best match: ${t})`:`Pick a site`,state:`idle`},w.createElement(u,{items:o,onSelect:n}))};function Ot(){let e=process.argv[1]??``;return e.includes(`/_npx/`)||e.includes(`\\_npx\\`)||process.env.npm_execpath?.includes(`npx`)?`npx`:`global`}const kt=({adapter:e,site:t,stats:n,onPick:r})=>{let i=Ot(),a=i===`npx`?`npx @zenovay/cli`:`zenovay`;return C((e,t)=>{let n=e.toLowerCase();n===`w`||t.return?r(`watch`):n===`e`?r(`events`):(n===`s`||n===`q`||t.escape)&&r(`quit`)},{isActive:!0}),w.createElement(c,{title:`You're live on Zenovay`,state:`ok`},w.createElement(x,null,w.createElement(d,null,`✔ Installed successfully`)),w.createElement(b,{marginTop:1,flexDirection:`column`},w.createElement(x,null,`Framework: `,w.createElement(x,{color:`cyan`},e.displayName)),w.createElement(x,null,`Site: `,w.createElement(x,{color:`cyan`},t.name),` (`,t.url,`)`),t.trackingCode?w.createElement(x,{color:`gray`},`Tracker: `,t.trackingCode):null,n&&n.rounds>0?w.createElement(x,{color:`gray`},`Modified: `,n.writes,` file(s) across `,n.rounds,` agent round(s)`):n&&n.writes>0?w.createElement(x,{color:`gray`},`Modified: `,n.writes,` file(s) (programmatic install — no AI calls)`):null),w.createElement(b,{marginTop:1,flexDirection:`column`},w.createElement(x,{bold:!0},`What's next?`),w.createElement(x,null,` `),w.createElement(b,null,w.createElement(x,{color:`cyan`},` [W] `),w.createElement(x,null,`Open the live dashboard `),w.createElement(x,{color:`gray`},`— real-time visitors, top pages, sources, vitals`)),w.createElement(b,null,w.createElement(x,{color:`cyan`},` [E] `),w.createElement(x,null,`Stream events as they fire `),w.createElement(x,{color:`gray`},`— page views, custom events, in real time`)),w.createElement(b,null,w.createElement(x,{color:`cyan`},` [S] `),w.createElement(x,null,`Exit to shell`))),i===`npx`?w.createElement(b,{marginTop:1,flexDirection:`column`,borderStyle:`single`,borderColor:`yellow`,paddingX:1},w.createElement(x,{color:`yellow`,bold:!0},`Heads up — you ran via npx`),w.createElement(x,null,w.createElement(x,null,`The `),w.createElement(x,{color:`cyan`},`zenovay`),w.createElement(x,null,` command isn't on your PATH yet. After you exit, run any of:`)),w.createElement(x,null,` `),w.createElement(x,{color:`cyan`},` npm i -g @zenovay/cli `),w.createElement(x,{color:`gray`},"→ then `zenovay watch` works directly"),w.createElement(x,{color:`cyan`},` npx @zenovay/cli watch `),w.createElement(x,{color:`gray`},`→ no install, slower start`)):w.createElement(b,{marginTop:1},w.createElement(x,{color:`gray`},`From your shell: `),w.createElement(x,{color:`cyan`},a,` watch`),w.createElement(x,{color:`gray`},` · `),w.createElement(x,{color:`cyan`},a,` --help`)),w.createElement(b,{marginTop:1},w.createElement(x,{color:`gray`},`Dashboard URL: https://app.zenovay.com/sites/`,t.id)))},At=({adapter:e,site:t,stats:n,onCommit:r,onSkipCommit:i})=>(Q(e=>{e===`y`||e===`Y`||e===`\r`?r():(e===`n`||e===`N`||e===`s`||e===`S`)&&i()}),w.createElement(c,{title:`Tracker installed`,state:`ok`},w.createElement(x,null,w.createElement(d,null,`✔ `),`The Zenovay tracker is in your project.`),w.createElement(b,{marginTop:1},w.createElement(x,{color:`gray`},`Framework: `),w.createElement(x,null,e.displayName)),w.createElement(b,null,w.createElement(x,{color:`gray`},`Site: `),w.createElement(x,null,t.name,` (`,t.url,`)`)),n&&w.createElement(b,null,w.createElement(x,{color:`gray`},`Modified: `),w.createElement(x,null,n.writes,` file(s)`)),w.createElement(b,{marginTop:1},w.createElement(x,null,`Commit + push these changes to git? `),w.createElement(x,{color:`cyan`},`[Y/n]`)))),jt=({cwd:e,onDone:t,onError:n})=>{let[r,i]=D(`committing`),[a,o]=D(`Staging changes…`);return T(()=>{(async()=>{try{let n=await It(e,e=>o(e),e=>i(e));n.committed?o(`Pushed ${n.shortSha} to origin/${n.branch}`):o(`No changes to commit (already up-to-date).`),setTimeout(()=>t(n),800)}catch(e){n(e.message)}})()},[]),w.createElement(c,{title:`Committing to git`,state:`busy`},w.createElement(b,null,w.createElement(x,{color:`magenta`},w.createElement(k,{type:`dots`})),w.createElement(x,null,` `,r===`pushing`?`Pushing to origin`:`Committing`,`…`)),w.createElement(b,{marginTop:1},w.createElement(x,{color:`gray`},a)))},Mt=({site:e,onDeployed:t,onSkip:n})=>(Q(e=>{e===`y`||e===`Y`||e===`\r`||e===`d`||e===`D`?t():(e===`n`||e===`N`||e===`s`||e===`S`)&&n()}),w.createElement(c,{title:`Ready to deploy?`,state:`idle`},w.createElement(x,null,`The tracker is installed locally. To capture events you need it on the live site:`),w.createElement(x,null,` `),w.createElement(b,null,w.createElement(x,{color:`cyan`},` → `),w.createElement(x,null,e.url)),w.createElement(x,null,` `),w.createElement(x,{color:`gray`},`Push the change through your normal deploy pipeline (Vercel auto-deploy, CI/CD, etc.).`),w.createElement(b,{marginTop:1},w.createElement(x,null,`Once it's deployed, press `),w.createElement(x,{color:`cyan`},`[Y]`),w.createElement(x,null,` to verify the tracker is firing. `),w.createElement(x,{color:`gray`},`[s] skip verification`)))),Nt=({site:e,onContinue:t})=>(Q(()=>t()),w.createElement(c,{title:`Visit your site`,state:`idle`},w.createElement(x,null,`To send a test event, open any page on your site:`),w.createElement(x,null,` `),w.createElement(b,null,w.createElement(x,{color:`cyan`},` → `),w.createElement(x,null,e.url)),w.createElement(x,null,` `),w.createElement(x,{color:`gray`},`The tracker fires automatically on page load. We'll verify the next event arrives.`),w.createElement(b,{marginTop:1},w.createElement(x,null,`Press `),w.createElement(x,{color:`cyan`},`[any key]`),w.createElement(x,null,` when you've visited the page.`))));async function Pt(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[^>]*src\s*=\s*["']https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+["'][^>]*>\s*<\/script>/gi,a=/data-id\s*=\s*["'](ZV_[A-Za-z0-9]+)["']/i,o=r.match(i)??[];if(o.length===0)return{state:`tracker-missing`};let s=Array.from(new Set(o.map(e=>e.match(a)?.[1]).filter(e=>!!e)));return s.includes(t)?{state:`tracker-correct`}:{state:`tracker-wrong-id`,foundCodes:s}}catch(e){return{state:`tracker-missing`,networkError:e.message}}}const Ft=({site:t,elapsed:i,onTick:a,onArrived:o,onTimeout:s})=>{let[l,u]=D(`preflight`),[d,f]=D(``),[p,m]=D([]),h=E(!1),g=t.trackingCode??t.id,_=async()=>{u(`preflight`),f(`Fetching ${t.url}…`);let e=await Pt(t.url,g);if(!h.current){if(e.state===`tracker-correct`){u(`polling`),f(`Tracker detected on live site — waiting for first hit…`),v();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`),f(e.networkError?`Couldn't reach ${t.url}: ${e.networkError}`:e.httpStatus?`${t.url} returned HTTP ${e.httpStatus}`:`No Zenovay tracker found on ${t.url}.`)}},v=async()=>{let i=Date.now()-10*60*1e3;try{let s=await e(),c=await r({strict:!1}),l=new n({config:s,cliVersion:`0`,token:c}),d=await Ze(t.id,i,{api:l,timeoutMs:6e4,pollIntervalMs:2500,onTick:e=>{h.current||a(e)}});if(h.current)return;d.received?(u(`success`),o()):u(`timeout`)}catch{h.current||u(`timeout`)}};T(()=>(h.current=!1,_(),()=>{h.current=!0}),[]),C(e=>{(l===`awaiting-deploy`||l===`wrong-id-on-live`||l===`timeout`)&&(e===`r`||e===`R`?_():(e===`s`||e===`S`)&&s())},{isActive:!0});let y=Math.floor(i/1e3);return l===`preflight`?w.createElement(c,{title:`Verifying`,state:`busy`},w.createElement(b,null,w.createElement(x,{color:`magenta`},w.createElement(k,{type:`dots`})),w.createElement(x,null,` Checking your live site for the tracker…`)),w.createElement(b,{marginTop:1},w.createElement(x,{color:`gray`},d))):l===`awaiting-deploy`?w.createElement(c,{title:`Tracker not yet on your live site`,state:`warn`},w.createElement(x,{color:`yellow`},d),w.createElement(b,{marginTop:1,flexDirection:`column`},w.createElement(x,null,`The tracker is in your local repo but hasn't been deployed yet.`),w.createElement(x,{color:`gray`},`Push your changes and wait for your deploy to finish (Vercel / Cloudflare Pages / CI), then retry.`)),w.createElement(b,{marginTop:1},w.createElement(x,null,`Press `),w.createElement(x,{color:`cyan`},`[r]`),w.createElement(x,null,` to re-check, `),w.createElement(x,{color:`cyan`},`[s]`),w.createElement(x,null,` to skip verification.`))):l===`wrong-id-on-live`?w.createElement(c,{title:`Live site has a different tracking code`,state:`warn`},w.createElement(x,{color:`yellow`},`Expected: `,w.createElement(x,{color:`cyan`},g),` `,`Found on live: `,w.createElement(x,{color:`cyan`},p.join(`, `))),w.createElement(b,{marginTop:1,flexDirection:`column`},w.createElement(x,null,`Your local install uses a different ID than what's on `,t.url,`.`),w.createElement(x,{color:`gray`},`Deploy the new local version, then retry — or skip if the existing ID is intentional.`)),w.createElement(b,{marginTop:1},w.createElement(x,null,`Press `),w.createElement(x,{color:`cyan`},`[r]`),w.createElement(x,null,` to re-check, `),w.createElement(x,{color:`cyan`},`[s]`),w.createElement(x,null,` to skip.`))):l===`timeout`?w.createElement(c,{title:`No event arrived in 3 minutes`,state:`warn`},w.createElement(x,{color:`yellow`},`The tracker is on your live site but no hits reached api.zenovay.com.`),w.createElement(b,{marginTop:1},w.createElement(x,{color:`gray`},`Try opening `,t.url,` in a fresh browser tab (no ad-blocker), then retry.`)),w.createElement(b,{marginTop:1},w.createElement(x,null,`Press `),w.createElement(x,{color:`cyan`},`[r]`),w.createElement(x,null,` to re-check, `),w.createElement(x,{color:`cyan`},`[s]`),w.createElement(x,null,` to finish without verification.`))):w.createElement(c,{title:`Waiting for first event`,state:`busy`},w.createElement(b,null,w.createElement(x,{color:`magenta`},w.createElement(k,{type:`dots`})),w.createElement(x,null,` Polling api.zenovay.com for the first hit on `),w.createElement(x,{color:`cyan`},t.url),w.createElement(x,null,` (`,y,`s elapsed)`)),w.createElement(b,{marginTop:1},w.createElement(x,{color:`gray`},`Reload the page if nothing arrives within ~30 seconds.`)))};function Q(e){C((t,n)=>{e(t,{return:n.return,escape:n.escape})},{isActive:!0})}async function It(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.slice(0,80)}). Push manually with: git push origin ${l}`),{committed:!0,shortSha:c,branch:l}}return n(`done`),{committed:!0,shortSha:c,branch:l}}function Lt(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 Rt(e){try{let t=await g.readFile(h.join(e,`package.json`),`utf8`),n=JSON.parse(t);if(n.name)return String(n.name).replace(/^@[^/]+\//,``)}catch{}try{let t=await g.readFile(h.join(e,`.git`,`config`),`utf8`),n=t.match(/url\s*=\s*.*[/:]([^/]+?)(?:\.git)?\s*$/m);if(n&&n[1])return n[1]}catch{}return h.basename(e)}function zt(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=>$(e.name).includes(n)||$(e.url).includes(n));return a??e[0]??null}function $(e){return e.toLowerCase().replace(/[^a-z0-9]/g,``)}export{ne as detectInstalled,St as initCommand};
|
|
62
|
+
`);s.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 (Cursor/Claude/VS Code)`,status:`pending`},{id:`verify`,label:`Wait for first event`,status:`pending`}]);let _=(e,t,n)=>{s.setTasks(r=>r.map(r=>r.id===e?{...r,status:t,detail:n??r.detail}:r))},v=null;try{await ct({api:u,sandbox:d,approval:{async approve(){return`y`}},prompter:{async ask({question:e}){return e}},handlers:{onToolStart:({name:e})=>{e===`detect_framework`?(_(`detect`,`active`),s.setLiveLine(`Inspecting package.json + config files…`)):e===`read_file`?(_(`detect`,`done`),_(`read`,`active`)):(e===`write_file`||e===`patch_file`)&&(_(`read`,`done`),_(`write`,`active`))},onToolResult:({name:e,result:t})=>{let n=t?.ok!==!1,r=t?.content??{};e===`detect_framework`&&n&&(_(`detect`,`done`,a.displayName),s.setLiveLine(`Detected ${a.displayName}`)),e===`read_file`&&n&&r.path&&s.setLiveLine(`Read ${r.path}`),(e===`write_file`||e===`patch_file`)&&n&&r.path&&s.setLiveLine(`Wrote ${r.path}`)},onDelta:e=>{let t=e.replace(/\s+/g,` `).trim();t.length>4&&s.setLiveLine(t.slice(0,80))}},initialMessages:[{role:`user`,content:g}],diagnosis:p,targetTrackingCode:f})}catch(e){v=e}let y=d.stats();if(y.writes===0){let e=v?`Agent error: ${v.message}`:`Agent returned without writing any files (${y.reads} reads, ${y.rounds} rounds). The model may have refused or the AI Gateway may be misconfigured. Check api.zenovay.com logs.`;throw Error(e)}let b=a.files.map(e=>e.path),x=y.writtenPaths.some(e=>b.some(t=>e===t||e.endsWith(`/${t}`)));if(!x)throw Error(`Agent wrote to: [${y.writtenPaths.join(`, `)}] but never modified the framework's tracker target file(s): [${b.join(`, `)}]. The tracker is NOT installed. The model likely put the trackingCode into .env.local instead of into the HTML/JSX entry file.`);_(`write`,`done`),_(`env`,`active`),s.setLiveLine(`Adding env var to .env.local`);let S=await J(o.cwd,{[a.envVarName]:f});if(_(`env`,`done`,`${S.addedKeys.length} key(s) added`),!o.skipMcp&&l){_(`mcp`,`active`),s.setLiveLine(`Detecting Cursor / Claude Desktop / VS Code…`);let e=await Y({accessToken:l.accessToken}).catch(()=>null);e&&e.installed.length>0?_(`mcp`,`done`,e.installed.join(`, `)):_(`mcp`,`done`,`none detected`)}else _(`mcp`,`done`,`skipped`);s.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:e.status===`pending`?`done`:e.status}:e)),s.setLiveLine(void 0),s.setSandboxStats?.(y),s.setPhase(`install-complete`)}catch(e){s.setErrorMsg(e.message),s.setPhase(`error`)}}const Tt=()=>w.createElement(c,{title:`Zenovay wants to set up your project`,state:`idle`},w.createElement(x,null,`We'll use AI to analyze your codebase and add the Zenovay tracker.`),w.createElement(x,{color:`gray`},`.env* contents stay on your machine. Only framework metadata reaches api.zenovay.com.`)),Et=({adapter:e,site:t,tasks:n,liveLine:r})=>{let i=process.stdout.columns??100,a=(process.stdout.rows??30)-8,o=Math.floor(i/2)-1,s=Math.max(14,a);return w.createElement(b,{flexDirection:`column`},w.createElement(b,{flexDirection:`row`,minHeight:s,borderStyle:`round`,borderColor:`gray`},w.createElement(b,{width:o,flexDirection:`column`},w.createElement(vt,{width:o,height:s})),w.createElement(b,{width:1,flexDirection:`column`},w.createElement(x,{color:`gray`},`│`)),w.createElement(b,{width:o,flexDirection:`column`},w.createElement(b,{paddingX:2,paddingTop:1},w.createElement(d,{done:n.filter(e=>e.status===`done`).length,total:n.length,label:n.find(e=>e.status===`active`)?.label})),w.createElement(xt,{tasks:n,liveLine:r,width:o,height:s}))),w.createElement(b,{marginTop:1},w.createElement(x,{color:`gray`},`Site: `,t.name,` · code: `,t.trackingCode??t.id,` · Framework: `,e.displayName)))},Dt=({sites:e,preselectHint:t,onPick:n})=>{let r=zt(e,t),i=e.filter(e=>e.id!==r?.id),a=r?[r,...i]:i,o=[...a.map(e=>({label:Lt(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 w.createElement(c,{title:t?`Pick a site (best match: ${t})`:`Pick a site`,state:`idle`},w.createElement(f,{items:o,onSelect:n}))};function Ot(){let e=process.argv[1]??``;return e.includes(`/_npx/`)||e.includes(`\\_npx\\`)||process.env.npm_execpath?.includes(`npx`)?`npx`:`global`}const kt=({adapter:e,site:t,stats:n,onPick:r})=>{let i=Ot(),a=i===`npx`?`npx @zenovay/cli`:`zenovay`;return C((e,t)=>{let n=e.toLowerCase();n===`w`||t.return?r(`watch`):n===`e`?r(`events`):(n===`s`||n===`q`||t.escape)&&r(`quit`)},{isActive:!0}),w.createElement(c,{title:`You're live on Zenovay`,state:`ok`},w.createElement(x,null,w.createElement(u,null,`✔ Installed successfully`)),w.createElement(b,{marginTop:1,flexDirection:`column`},w.createElement(x,null,`Framework: `,w.createElement(x,{color:`cyan`},e.displayName)),w.createElement(x,null,`Site: `,w.createElement(x,{color:`cyan`},t.name),` (`,t.url,`)`),t.trackingCode?w.createElement(x,{color:`gray`},`Tracker: `,t.trackingCode):null,n&&n.rounds>0?w.createElement(x,{color:`gray`},`Modified: `,n.writes,` file(s) across `,n.rounds,` agent round(s)`):n&&n.writes>0?w.createElement(x,{color:`gray`},`Modified: `,n.writes,` file(s) (programmatic install — no AI calls)`):null),w.createElement(b,{marginTop:1,flexDirection:`column`},w.createElement(x,{bold:!0},`What's next?`),w.createElement(x,null,` `),w.createElement(b,null,w.createElement(x,{color:`cyan`},` [W] `),w.createElement(x,null,`Open the live dashboard `),w.createElement(x,{color:`gray`},`— real-time visitors, top pages, sources, vitals`)),w.createElement(b,null,w.createElement(x,{color:`cyan`},` [E] `),w.createElement(x,null,`Stream events as they fire `),w.createElement(x,{color:`gray`},`— page views, custom events, in real time`)),w.createElement(b,null,w.createElement(x,{color:`cyan`},` [S] `),w.createElement(x,null,`Exit to shell`))),i===`npx`?w.createElement(b,{marginTop:1,flexDirection:`column`,borderStyle:`single`,borderColor:`yellow`,paddingX:1},w.createElement(x,{color:`yellow`,bold:!0},`Heads up — you ran via npx`),w.createElement(x,null,w.createElement(x,null,`The `),w.createElement(x,{color:`cyan`},`zenovay`),w.createElement(x,null,` command isn't on your PATH yet. After you exit, run any of:`)),w.createElement(x,null,` `),w.createElement(x,{color:`cyan`},` npm i -g @zenovay/cli `),w.createElement(x,{color:`gray`},"→ then `zenovay watch` works directly"),w.createElement(x,{color:`cyan`},` npx @zenovay/cli watch `),w.createElement(x,{color:`gray`},`→ no install, slower start`)):w.createElement(b,{marginTop:1},w.createElement(x,{color:`gray`},`From your shell: `),w.createElement(x,{color:`cyan`},a,` watch`),w.createElement(x,{color:`gray`},` · `),w.createElement(x,{color:`cyan`},a,` --help`)),w.createElement(b,{marginTop:1},w.createElement(x,{color:`gray`},`Dashboard URL: https://app.zenovay.com/sites/`,t.id)))},At=({adapter:e,site:t,stats:n,onCommit:r,onSkipCommit:i})=>(Q(e=>{e===`y`||e===`Y`||e===`\r`?r():(e===`n`||e===`N`||e===`s`||e===`S`)&&i()}),w.createElement(c,{title:`Tracker installed`,state:`ok`},w.createElement(x,null,w.createElement(u,null,`✔ `),`The Zenovay tracker is in your project.`),w.createElement(b,{marginTop:1},w.createElement(x,{color:`gray`},`Framework: `),w.createElement(x,null,e.displayName)),w.createElement(b,null,w.createElement(x,{color:`gray`},`Site: `),w.createElement(x,null,t.name,` (`,t.url,`)`)),n&&w.createElement(b,null,w.createElement(x,{color:`gray`},`Modified: `),w.createElement(x,null,n.writes,` file(s)`)),w.createElement(b,{marginTop:1},w.createElement(x,null,`Commit + push these changes to git? `),w.createElement(x,{color:`cyan`},`[Y/n]`)))),jt=({cwd:e,onDone:t,onError:n})=>{let[r,i]=D(`committing`),[a,o]=D(`Staging changes…`);return T(()=>{(async()=>{try{let n=await It(e,e=>o(e),e=>i(e));n.committed?o(`Pushed ${n.shortSha} to origin/${n.branch}`):o(`No changes to commit (already up-to-date).`),setTimeout(()=>t(n),800)}catch(e){n(e.message)}})()},[]),w.createElement(c,{title:`Committing to git`,state:`busy`},w.createElement(b,null,w.createElement(x,{color:`magenta`},w.createElement(k,{type:`dots`})),w.createElement(x,null,` `,r===`pushing`?`Pushing to origin`:`Committing`,`…`)),w.createElement(b,{marginTop:1},w.createElement(x,{color:`gray`},a)))},Mt=({site:e,onDeployed:t,onSkip:n})=>(Q(e=>{e===`y`||e===`Y`||e===`\r`||e===`d`||e===`D`?t():(e===`n`||e===`N`||e===`s`||e===`S`)&&n()}),w.createElement(c,{title:`Ready to deploy?`,state:`idle`},w.createElement(x,null,`The tracker is installed locally. To capture events you need it on the live site:`),w.createElement(x,null,` `),w.createElement(b,null,w.createElement(x,{color:`cyan`},` → `),w.createElement(x,null,e.url)),w.createElement(x,null,` `),w.createElement(x,{color:`gray`},`Push the change through your normal deploy pipeline (Vercel auto-deploy, CI/CD, etc.).`),w.createElement(b,{marginTop:1},w.createElement(x,null,`Once it's deployed, press `),w.createElement(x,{color:`cyan`},`[Y]`),w.createElement(x,null,` to verify the tracker is firing. `),w.createElement(x,{color:`gray`},`[s] skip verification`)))),Nt=({site:e,onContinue:t})=>(Q(()=>t()),w.createElement(c,{title:`Visit your site`,state:`idle`},w.createElement(x,null,`To send a test event, open any page on your site:`),w.createElement(x,null,` `),w.createElement(b,null,w.createElement(x,{color:`cyan`},` → `),w.createElement(x,null,e.url)),w.createElement(x,null,` `),w.createElement(x,{color:`gray`},`The tracker fires automatically on page load. We'll verify the next event arrives.`),w.createElement(b,{marginTop:1},w.createElement(x,null,`Press `),w.createElement(x,{color:`cyan`},`[any key]`),w.createElement(x,null,` when you've visited the page.`))));async function Pt(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[^>]*src\s*=\s*["']https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+["'][^>]*>\s*<\/script>/gi,a=/data-id\s*=\s*["'](ZV_[A-Za-z0-9]+)["']/i,o=r.match(i)??[];if(o.length===0)return{state:`tracker-missing`};let s=Array.from(new Set(o.map(e=>e.match(a)?.[1]).filter(e=>!!e)));return s.includes(t)?{state:`tracker-correct`}:{state:`tracker-wrong-id`,foundCodes:s}}catch(e){return{state:`tracker-missing`,networkError:e.message}}}const Ft=({site:t,elapsed:i,onTick:a,onArrived:o,onTimeout:s})=>{let[l,u]=D(`preflight`),[d,f]=D(``),[p,m]=D([]),h=E(!1),g=t.trackingCode??t.id,_=async()=>{u(`preflight`),f(`Fetching ${t.url}…`);let e=await Pt(t.url,g);if(!h.current){if(e.state===`tracker-correct`){u(`polling`),f(`Tracker detected on live site — waiting for first hit…`),v();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`),f(e.networkError?`Couldn't reach ${t.url}: ${e.networkError}`:e.httpStatus?`${t.url} returned HTTP ${e.httpStatus}`:`No Zenovay tracker found on ${t.url}.`)}},v=async()=>{let i=Date.now()-10*60*1e3;try{let s=await e(),c=await r({strict:!1}),l=new n({config:s,cliVersion:`0`,token:c}),d=await Ze(t.id,i,{api:l,timeoutMs:6e4,pollIntervalMs:2500,onTick:e=>{h.current||a(e)}});if(h.current)return;d.received?(u(`success`),o()):u(`timeout`)}catch{h.current||u(`timeout`)}};T(()=>(h.current=!1,_(),()=>{h.current=!0}),[]),C(e=>{(l===`awaiting-deploy`||l===`wrong-id-on-live`||l===`timeout`)&&(e===`r`||e===`R`?_():(e===`s`||e===`S`)&&s())},{isActive:!0});let y=Math.floor(i/1e3);return l===`preflight`?w.createElement(c,{title:`Verifying`,state:`busy`},w.createElement(b,null,w.createElement(x,{color:`magenta`},w.createElement(k,{type:`dots`})),w.createElement(x,null,` Checking your live site for the tracker…`)),w.createElement(b,{marginTop:1},w.createElement(x,{color:`gray`},d))):l===`awaiting-deploy`?w.createElement(c,{title:`Tracker not yet on your live site`,state:`warn`},w.createElement(x,{color:`yellow`},d),w.createElement(b,{marginTop:1,flexDirection:`column`},w.createElement(x,null,`The tracker is in your local repo but hasn't been deployed yet.`),w.createElement(x,{color:`gray`},`Push your changes and wait for your deploy to finish (Vercel / Cloudflare Pages / CI), then retry.`)),w.createElement(b,{marginTop:1},w.createElement(x,null,`Press `),w.createElement(x,{color:`cyan`},`[r]`),w.createElement(x,null,` to re-check, `),w.createElement(x,{color:`cyan`},`[s]`),w.createElement(x,null,` to skip verification.`))):l===`wrong-id-on-live`?w.createElement(c,{title:`Live site has a different tracking code`,state:`warn`},w.createElement(x,{color:`yellow`},`Expected: `,w.createElement(x,{color:`cyan`},g),` `,`Found on live: `,w.createElement(x,{color:`cyan`},p.join(`, `))),w.createElement(b,{marginTop:1,flexDirection:`column`},w.createElement(x,null,`Your local install uses a different ID than what's on `,t.url,`.`),w.createElement(x,{color:`gray`},`Deploy the new local version, then retry — or skip if the existing ID is intentional.`)),w.createElement(b,{marginTop:1},w.createElement(x,null,`Press `),w.createElement(x,{color:`cyan`},`[r]`),w.createElement(x,null,` to re-check, `),w.createElement(x,{color:`cyan`},`[s]`),w.createElement(x,null,` to skip.`))):l===`timeout`?w.createElement(c,{title:`No event arrived in 3 minutes`,state:`warn`},w.createElement(x,{color:`yellow`},`The tracker is on your live site but no hits reached api.zenovay.com.`),w.createElement(b,{marginTop:1},w.createElement(x,{color:`gray`},`Try opening `,t.url,` in a fresh browser tab (no ad-blocker), then retry.`)),w.createElement(b,{marginTop:1},w.createElement(x,null,`Press `),w.createElement(x,{color:`cyan`},`[r]`),w.createElement(x,null,` to re-check, `),w.createElement(x,{color:`cyan`},`[s]`),w.createElement(x,null,` to finish without verification.`))):w.createElement(c,{title:`Waiting for first event`,state:`busy`},w.createElement(b,null,w.createElement(x,{color:`magenta`},w.createElement(k,{type:`dots`})),w.createElement(x,null,` Polling api.zenovay.com for the first hit on `),w.createElement(x,{color:`cyan`},t.url),w.createElement(x,null,` (`,y,`s elapsed)`)),w.createElement(b,{marginTop:1},w.createElement(x,{color:`gray`},`Reload the page if nothing arrives within ~30 seconds.`)))};function Q(e){C((t,n)=>{e(t,{return:n.return,escape:n.escape})},{isActive:!0})}async function It(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.slice(0,80)}). Push manually with: git push origin ${l}`),{committed:!0,shortSha:c,branch:l}}return n(`done`),{committed:!0,shortSha:c,branch:l}}function Lt(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 Rt(e){try{let t=await g.readFile(h.join(e,`package.json`),`utf8`),n=JSON.parse(t);if(n.name)return String(n.name).replace(/^@[^/]+\//,``)}catch{}try{let t=await g.readFile(h.join(e,`.git`,`config`),`utf8`),n=t.match(/url\s*=\s*.*[/:]([^/]+?)(?:\.git)?\s*$/m);if(n&&n[1])return n[1]}catch{}return h.basename(e)}function zt(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=>$(e.name).includes(n)||$(e.url).includes(n));return a??e[0]??null}function $(e){return e.toLowerCase().replace(/[^a-z0-9]/g,``)}export{ne as detectInstalled,St as initCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./config-CZ9IzjIH.js";import"./api-DXmhz2DM.js";import{initCommand as e}from"./init-BAvyI5n6.js";import"./client-WzSy90dG.js";import"./formatter-mW0Yk3Nt.js";import"./emit-D7VCOSNk.js";import"./login-DWaz_EsV.js";import"./panel-uygscwY5.js";import"./banner-BPQh2F8l.js";import"./progress-row-DFOvHAc5.js";import"./prompt-BURfUNxp.js";import"./keybar-C7YkmK1U.js";import"./sparkline-Bkfzqe4x.js";export{e as initCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readConfig as e}from"./config-CZ9IzjIH.js";import{readToken as t}from"./api-DXmhz2DM.js";import{ApiV2Client as n}from"./api-v2-CfJ_2Z5N.js";import{requireTier as r}from"./tier-RjOGNzda.js";import"./formatter-mW0Yk3Nt.js";import{emit as i,isHeadless as a}from"./emit-D7VCOSNk.js";import{Panel as o}from"./panel-uygscwY5.js";import{Banner as s}from"./banner-BPQh2F8l.js";import"./prompt-BURfUNxp.js";import{Keybar as c}from"./keybar-C7YkmK1U.js";import{resolveSiteId as l}from"./resolve-site-D3e1i32Z.js";import{EmptyState as u}from"./empty-state-Dkho-_3J.js";import{Box as d,Text as f,render as p,useApp as m,useInput as h}from"ink";import g,{useEffect as _,useState as v}from"react";import y from"ink-spinner";function b(e){return e===`critical`?`err`:e===`warning`?`warn`:`ok`}function x(e){return e===`anomaly`?`⚡ anomaly`:e===`recommendation`?`✦ recommendation`:`↗ trend`}async function S(o){let s=await e(),c=await t({strict:!1});if(!c)return process.stderr.write("Not logged in — run `zenovay login` first.\n"),2;let u=new n({config:s,cliVersion:o.cliVersion,token:c});try{await r(u,`pro`)}catch(e){return process.stderr.write(`${e.message}\n`),2}let d,f;try{({siteId:d,site:f}=await l(u,{explicit:o.siteId,headless:!!o.json,cliVersion:o.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let m=f?.url?f.url.replace(/^https?:\/\//,``).replace(/\/$/,``):f?.name??d;if(a(o)){let e=await u.getInsights(d);return i({type:`insights.snapshot`,data:e}),0}return new Promise(e=>{let{unmount:t}=p(g.createElement(C,{api:u,siteId:d,siteLabel:m,cliVersion:o.cliVersion,onExit:n=>{t(),e(n)}}))})}const C=({api:e,siteId:t,siteLabel:n,cliVersion:r,onExit:i})=>{let{exit:a}=m(),[l,p]=v(null),[S,C]=v(!0),[w,T]=v(null);return h(e=>{e===`q`&&(a(),i(0))}),_(()=>{let n=!1;return(async()=>{try{let r=await e.getInsights(t);n||(p(r),C(!1))}catch(e){n||(T(e.message),C(!1))}})(),()=>{n=!0}},[e,t]),S?g.createElement(d,{flexDirection:`column`},g.createElement(s,{version:r,subtitle:`insights · ${n}`}),g.createElement(o,{title:`Loading`,state:`busy`},g.createElement(d,null,g.createElement(f,{color:`magenta`},g.createElement(y,{type:`dots`})),g.createElement(f,null,` Fetching insights…`)))):w?g.createElement(d,{flexDirection:`column`},g.createElement(s,{version:r,subtitle:`insights · ${n}`}),g.createElement(u,{reason:`error`,headline:`Failed to load`,hint:w})):!l||l.length===0?g.createElement(d,{flexDirection:`column`},g.createElement(s,{version:r,subtitle:`insights · ${n}`}),g.createElement(u,{reason:`no-data`,headline:`No insights yet`,hint:`Insights are generated nightly — check back tomorrow`})):g.createElement(d,{flexDirection:`column`},g.createElement(s,{version:r,subtitle:`insights · ${n}`}),l.map((e,t)=>g.createElement(o,{key:t,title:`${x(e.kind)} · ${e.severity}`,state:b(e.severity)},g.createElement(f,{bold:!0},e.title),e.body?g.createElement(f,{color:`gray`},e.body):null)),g.createElement(c,{items:[{key:`q`,label:`quit`}]}))};export{S as insightsCommand};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import{readConfig as e}from"./config-CZ9IzjIH.js";import{readToken as t}from"./api-DXmhz2DM.js";import{ApiV2Client as n}from"./api-v2-CfJ_2Z5N.js";import{confirmDestructive as r}from"./confirm-D_aKHknn.js";import i from"open";async function a(a){let o=await e(),s=await t({strict:!1}),c=new n({config:o,cliVersion:a.cliVersion,token:s});try{switch(a.action){case`list`:{let{integrations:e}=await c.listIntegrations();if(a.json)return process.stdout.write(JSON.stringify({integrations:e},null,2)+`
|
|
2
|
+
`),0;let t=[10,30,14],n=e=>e.map((e,n)=>(e??``).padEnd(t[n])).join(` `);process.stdout.write(`
|
|
3
|
+
`+n([`name`,`service`,`status`])+`
|
|
4
|
+
`),process.stdout.write(n(t.map(e=>`─`.repeat(e)))+`
|
|
5
|
+
`);for(let t of e)process.stdout.write(n([t.name,t.label,t.status])+`
|
|
6
|
+
`);return process.stdout.write(`
|
|
7
|
+
`),0}case`connect`:{if(a.name!==`gsc`&&a.name!==`github`)return process.stderr.write("Error: pass `gsc` or `github` — e.g. `zenovay integrations connect gsc`.\n"),2;let{integrations:e}=await c.listIntegrations(),t=e.find(e=>e.name===a.name),n=t?.connectUrl??`https://app.zenovay.com/integrations/${a.name}`;if(a.json)return process.stdout.write(JSON.stringify({connectUrl:n},null,2)+`
|
|
8
|
+
`),0;process.stdout.write(`Opening browser to connect ${a.name}:\n ${n}\n`);try{await i(n)}catch{}return 0}case`disconnect`:{if(a.name!==`gsc`&&a.name!==`github`)return process.stderr.write("Error: pass `gsc` or `github` — e.g. `zenovay integrations disconnect gsc`.\n"),2;let e=await r({resource:`integration`,name:a.name,yes:a.yes,destructive:!1});if(!e)return process.stdout.write(`Cancelled.
|
|
9
|
+
`),1;let t=await c.disconnectIntegration(a.name);return a.json?(process.stdout.write(JSON.stringify(t,null,2)+`
|
|
10
|
+
`),0):(process.stdout.write(`✔ Disconnected ${a.name}.\n`),0)}}}catch(e){return process.stderr.write(`✗ ${e.message}\n`),1}}export{a as integrationsCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readConfig as e}from"./config-CZ9IzjIH.js";import{readToken as t}from"./api-DXmhz2DM.js";import{ApiV2Client as n}from"./api-v2-CfJ_2Z5N.js";import{requireTier as r}from"./tier-RjOGNzda.js";import"./formatter-mW0Yk3Nt.js";import{emit as i,isHeadless as a}from"./emit-D7VCOSNk.js";import{Panel as o}from"./panel-uygscwY5.js";import{Banner as s}from"./banner-BPQh2F8l.js";import"./prompt-BURfUNxp.js";import{Keybar as c}from"./keybar-C7YkmK1U.js";import{resolveSiteId as l}from"./resolve-site-D3e1i32Z.js";import{EmptyState as u}from"./empty-state-Dkho-_3J.js";import{Box as d,Text as f,render as p,useApp as m,useInput as h}from"ink";import g,{useEffect as _,useState as v}from"react";import y from"ink-spinner";async function b(o){let s=await e(),c=await t({strict:!1});if(!c)return process.stderr.write("Not logged in — run `zenovay login` first.\n"),2;let u=new n({config:s,cliVersion:o.cliVersion,token:c});try{await r(u,`pro`)}catch(e){return process.stderr.write(`${e.message}\n`),2}let d,f;try{({siteId:d,site:f}=await l(u,{explicit:o.siteId,headless:!!o.json,cliVersion:o.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let m=f?.url?f.url.replace(/^https?:\/\//,``).replace(/\/$/,``):f?.name??d;if(a(o)){let e=await u.getJourneys(d);return i({type:`journeys.snapshot`,data:e}),0}return new Promise(e=>{let{unmount:t}=p(g.createElement(x,{api:u,siteId:d,siteLabel:m,cliVersion:o.cliVersion,onExit:n=>{t(),e(n)}}))})}const x=({api:e,siteId:t,siteLabel:n,cliVersion:r,onExit:i})=>{let{exit:a}=m(),[l,p]=v(null),[b,x]=v(!0),[S,C]=v(null);if(h(e=>{e===`q`&&(a(),i(0))}),_(()=>{let n=!1;return(async()=>{try{let r=await e.getJourneys(t);n||(p(r.flows),x(!1))}catch(e){n||(C(e.message),x(!1))}})(),()=>{n=!0}},[e,t]),b)return g.createElement(d,{flexDirection:`column`},g.createElement(s,{version:r,subtitle:`journeys · ${n}`}),g.createElement(o,{title:`Loading`,state:`busy`},g.createElement(d,null,g.createElement(f,{color:`magenta`},g.createElement(y,{type:`dots`})),g.createElement(f,null,` Computing flows…`))));if(S)return g.createElement(d,{flexDirection:`column`},g.createElement(s,{version:r,subtitle:`journeys · ${n}`}),g.createElement(u,{reason:`error`,headline:`Failed to load`,hint:S}));if(!l||l.length===0)return g.createElement(d,{flexDirection:`column`},g.createElement(s,{version:r,subtitle:`journeys · ${n}`}),g.createElement(u,{reason:`no-data`,headline:`No journeys yet`,hint:`Need at least 2 page-views per session to compute flows`}));let w=Math.max(...l.map(e=>e.count),1),T=12;return g.createElement(d,{flexDirection:`column`},g.createElement(s,{version:r,subtitle:`journeys · ${n}`}),g.createElement(o,{title:`Top page transitions (${l.length})`},l.map((e,t)=>{let n=Math.max(1,Math.round(e.count/w*T));return g.createElement(d,{key:t,flexDirection:`row`},g.createElement(f,null,e.from.padEnd(22).slice(0,22)),g.createElement(f,{color:`cyan`},` → `),g.createElement(f,null,e.to.padEnd(22).slice(0,22)),g.createElement(f,{color:`magenta`},` `,`█`.repeat(n),`░`.repeat(T-n)),g.createElement(f,{color:`gray`},` ${e.count}`))})),g.createElement(c,{items:[{key:`q`,label:`quit`}]}))};export{b as journeysCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useTheme as e}from"./panel-
|
|
1
|
+
import{useTheme as e}from"./panel-uygscwY5.js";import{Box as t,Text as n}from"ink";import r from"react";function i({items:i}){let{theme:a}=e();return r.createElement(t,{flexDirection:`row`},i.map((e,i)=>r.createElement(t,{key:`${e.key}-${i}`,flexDirection:`row`},i>0?r.createElement(n,{color:a.dim},` `):null,r.createElement(n,{color:a.muted},`[`),r.createElement(n,{color:a.accent},e.key),r.createElement(n,{color:a.muted},` `,e.label),r.createElement(n,{color:a.muted},`]`))))}export{i as Keybar};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readConfig as e}from"./config-CZ9IzjIH.js";import{readToken as t}from"./api-DXmhz2DM.js";import{ApiV2Client as n}from"./api-v2-CfJ_2Z5N.js";import"./formatter-mW0Yk3Nt.js";import{emit as r,isHeadless as i}from"./emit-D7VCOSNk.js";import{Panel as a}from"./panel-uygscwY5.js";import{Banner as o}from"./banner-BPQh2F8l.js";import"./prompt-BURfUNxp.js";import{Keybar as s}from"./keybar-C7YkmK1U.js";import"./sparkline-Bkfzqe4x.js";import{resolveSiteId as c}from"./resolve-site-D3e1i32Z.js";import{EmptyState as l}from"./empty-state-Dkho-_3J.js";import{MetricCard as u}from"./metric-card-BfVg5VG6.js";import{Globe as d}from"./globe-DImE1nyh.js";import{Box as f,Text as p,render as m,useApp as h,useInput as g}from"ink";import _,{useEffect as v,useState as y}from"react";import b from"ink-spinner";async function x(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 l=new n({config:o,cliVersion:a.cliVersion,token:s}),u,d;try{({siteId:u,site:d}=await c(l,{explicit:a.siteId,headless:!!a.json,cliVersion:a.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let f=d?.url?d.url.replace(/^https?:\/\//,``).replace(/\/$/,``):d?.name??u;if(i(a)){let e=await l.getLive(u);return r({type:`live.snapshot`,data:e}),0}return new Promise(e=>{let{unmount:t}=m(_.createElement(S,{api:l,siteId:u,siteLabel:f,cliVersion:a.cliVersion,onExit:n=>{t(),e(n)}}))})}const S=({api:e,siteId:t,siteLabel:n,cliVersion:r,onExit:i})=>{let{exit:c}=h(),[m,x]=y(null),[S,C]=y(!0),[w,T]=y(null);if(g(e=>{e===`q`&&(c(),i(0))}),v(()=>{let n=!1,r=async()=>{try{let r=await e.getLive(t);n||(x(r),C(!1),T(null))}catch(e){n||(T(e.message),C(!1))}};r();let i=setInterval(r,2e3);return()=>{n=!0,clearInterval(i)}},[e,t]),S)return _.createElement(f,{flexDirection:`column`},_.createElement(o,{version:r,subtitle:`live · ${n}`}),_.createElement(a,{title:`Loading`,state:`busy`},_.createElement(f,null,_.createElement(p,{color:`magenta`},_.createElement(b,{type:`dots`})),_.createElement(p,null,` Connecting…`))));if(w&&!m)return _.createElement(f,{flexDirection:`column`},_.createElement(o,{version:r,subtitle:`live · ${n}`}),_.createElement(l,{reason:`error`,headline:`Failed to load`,hint:w}));let E=process.stdout.columns??80,D=Math.max(20,Math.min(40,Math.floor(E/3)));return _.createElement(f,{flexDirection:`column`},_.createElement(o,{version:r,subtitle:`live · ${n}`}),_.createElement(f,{flexDirection:`row`},_.createElement(u,{title:`Active now`,value:m?.activeVisitors??0,format:`number`,width:D}),_.createElement(a,{title:`Globe`,width:Math.max(40,E-D-4)},_.createElement(d,{data:[],width:Math.max(36,E-D-10),height:10}))),_.createElement(a,{title:`Recent events`},!m||m.recentEvents.length===0?_.createElement(p,{color:`gray`},`— waiting for events —`):m.recentEvents.slice(0,15).map((e,t)=>_.createElement(f,{key:t},_.createElement(p,{color:`cyan`},(e.type??`pageview`).padEnd(10)),_.createElement(p,null,e.path.padEnd(36).slice(0,36)),_.createElement(p,{color:`gray`},e.country??`—`)))),_.createElement(s,{items:[{key:`q`,label:`quit`}]}))};export{x as liveCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./config-CZ9IzjIH.js";import"./api-DXmhz2DM.js";import"./formatter-mW0Yk3Nt.js";import"./emit-D7VCOSNk.js";import{loginCommand as e}from"./login-DWaz_EsV.js";export{e as loginCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readConfig as e}from"./config-CZ9IzjIH.js";import{ApiClient as t,pollDeviceToken as n,startDeviceAuthorization as r,writeToken as i}from"./api-DXmhz2DM.js";import{emit as a,isHeadless as o}from"./emit-
|
|
1
|
+
import{readConfig as e}from"./config-CZ9IzjIH.js";import{ApiClient as t,pollDeviceToken as n,startDeviceAuthorization as r,writeToken as i}from"./api-DXmhz2DM.js";import{emit as a,isHeadless as o}from"./emit-D7VCOSNk.js";import s from"open";async function c(c){let l=await e(),u=o({json:c.json}),d=await r({apiBase:l.apiBase}),f=d.verification_uri_complete??d.verification_uri;u?a({type:`info`,message:`Open ${f} and enter code ${d.user_code}`}):c.onCode?c.onCode({userCode:d.user_code,verificationUri:d.verification_uri,verificationUriComplete:d.verification_uri_complete}):process.stdout.write(`\n Open this URL to authorize the CLI:\n ${f}\n Or enter code: ${d.user_code}\n\n`);let p=c.openBrowser??!u;if(p)try{await s(f)}catch{}let m=await n({apiBase:l.apiBase,deviceCode:d.device_code,interval:d.interval,expiresIn:d.expires_in});await i(m);let h=new t({config:l,cliVersion:c.cliVersion,token:m}),g=await h.me().catch(()=>null);if(g){let e={...m,userId:g.user.id,teamId:g.team?.id,email:g.user.email};await i(e)}return u&&a({type:`done`,command:`login`,exitCode:0}),{email:g?.user.email}}export{c as loginCommand};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readConfig as e}from"./config-CZ9IzjIH.js";import{ApiClient as t,clearToken as n,readToken as r}from"./api-DXmhz2DM.js";import"./formatter-
|
|
1
|
+
import{readConfig as e}from"./config-CZ9IzjIH.js";import{ApiClient as t,clearToken as n,readToken as r}from"./api-DXmhz2DM.js";import"./formatter-mW0Yk3Nt.js";import{emit as i,isHeadless as a}from"./emit-D7VCOSNk.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
2
|
`)}export{o as logoutCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Panel as e,useTheme as t}from"./panel-
|
|
1
|
+
import{Panel as e,useTheme as t}from"./panel-uygscwY5.js";import{spark as n}from"./sparkline-Bkfzqe4x.js";import{Box as r,Text as i}from"ink";import a from"react";function o(e,t){if(typeof e==`string`)return e;switch(t){case`percent`:{let t=Math.abs(e)<=1?e*100:e;return`${t.toFixed(1)}%`}case`duration`:{if(e<60)return`${Math.round(e)}s`;let t=Math.floor(e/60),n=Math.round(e%60);return`${t}m ${n.toString().padStart(2,`0`)}s`}case`currency`:{let t=e/100;return`$${t.toLocaleString(void 0,{minimumFractionDigits:0,maximumFractionDigits:2})}`}case`number`:default:return e.toLocaleString()}}const s=[`• `,`•• `,`•••`,` ••`,` •`,` `];function c(){let[e,t]=a.useState(0);return a.useEffect(()=>{let e=setInterval(()=>{t(e=>(e+1)%s.length)},180);return()=>clearInterval(e)},[]),e}function l({title:l,value:u,series:d,delta:f,format:p=`number`,loading:m=!1,emptyHint:h,width:g}){let{theme:_}=t(),v=c(),y=a.createElement(i,{color:_.typography.label.color,dimColor:_.typography.label.dim},l.toUpperCase());if(m)return a.createElement(e,{width:g},y,a.createElement(i,{color:_.accent},s[v]));let b=typeof u==`number`?u:Number(u),x=(u===``||u===`—`||typeof u==`number`&&!Number.isFinite(b))&&(!d||d.length===0);if(x)return a.createElement(e,{width:g},y,a.createElement(i,{color:_.dim},h??`no data yet`));let S=o(u,p),C=typeof g==`number`?Math.max(8,g-6):16,w=d&&d.length>0?n(d,C):``,T=null;if(typeof f==`number`&&Number.isFinite(f)){let e=Math.abs(f*100);T=e<.5?a.createElement(i,{color:_.dim},` `,`→ `,e.toFixed(1),`%`):f>0?a.createElement(i,{color:_.success},` `,`↑ `,e.toFixed(1),`%`):a.createElement(i,{color:_.error},` `,`↓ `,e.toFixed(1),`%`)}return a.createElement(e,{width:g},y,a.createElement(i,{color:_.typography.headline.color,bold:_.typography.headline.bold},S),w?a.createElement(r,{flexDirection:`row`},a.createElement(i,{color:_.accent},w),T):T?a.createElement(r,{flexDirection:`row`},T):null)}export{l as MetricCard};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import{readConfig as e}from"./config-CZ9IzjIH.js";import{ApiError as t,readToken as n}from"./api-DXmhz2DM.js";import{ApiV2Client as r}from"./api-v2-CfJ_2Z5N.js";import{confirmDestructive as i}from"./confirm-D_aKHknn.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readConfig as e}from"./config-CZ9IzjIH.js";import{readToken as t}from"./api-DXmhz2DM.js";import{ApiV2Client as n}from"./api-v2-CfJ_2Z5N.js";import"./formatter-mW0Yk3Nt.js";import{emit as r,isHeadless as i}from"./emit-D7VCOSNk.js";import{Panel as a}from"./panel-uygscwY5.js";import{Banner as o}from"./banner-BPQh2F8l.js";import"./prompt-BURfUNxp.js";import{Keybar as s}from"./keybar-C7YkmK1U.js";import{resolveSiteId as c}from"./resolve-site-D3e1i32Z.js";import{EmptyState as l}from"./empty-state-Dkho-_3J.js";import{DataTable as u}from"./data-table-BVWqHy9m.js";import{Box as d,Text as f,render as p,useApp as m,useInput as h}from"ink";import g,{useEffect as _,useState as v}from"react";import y from"ink-spinner";async function b(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 l=new n({config:o,cliVersion:a.cliVersion,token:s}),u,d;try{({siteId:u,site:d}=await c(l,{explicit:a.siteId,headless:!!a.json,cliVersion:a.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let f=d?.url?d.url.replace(/^https?:\/\//,``).replace(/\/$/,``):d?.name??u;if(i(a)){let e=await l.getPages(u);return r({type:`pages.snapshot`,data:e}),0}return new Promise(e=>{let{unmount:t}=p(g.createElement(x,{api:l,siteId:u,siteLabel:f,cliVersion:a.cliVersion,onExit:n=>{t(),e(n)}}))})}const x=({api:e,siteId:t,siteLabel:n,cliVersion:r,onExit:i})=>{let{exit:c}=m(),[p,b]=v(null),[x,S]=v(!0),[C,w]=v(null);if(h(e=>{e===`q`&&(c(),i(0))}),_(()=>{let n=!1;return(async()=>{try{let r=await e.getPages(t);n||(b(r),S(!1))}catch(e){n||(w(e.message),S(!1))}})(),()=>{n=!0}},[e,t]),x)return g.createElement(d,{flexDirection:`column`},g.createElement(o,{version:r,subtitle:`pages · ${n}`}),g.createElement(a,{title:`Loading`,state:`busy`},g.createElement(d,null,g.createElement(f,{color:`magenta`},g.createElement(y,{type:`dots`})),g.createElement(f,null,` Fetching pages…`))));if(C)return g.createElement(d,{flexDirection:`column`},g.createElement(o,{version:r,subtitle:`pages · ${n}`}),g.createElement(l,{reason:`error`,headline:`Failed to load`,hint:C}));if(!p||p.length===0)return g.createElement(d,{flexDirection:`column`},g.createElement(o,{version:r,subtitle:`pages · ${n}`}),g.createElement(l,{reason:`no-data`,headline:`No pages yet`,hint:`Visit your site to send the first event`}));let T=[{key:`path`,label:`path`,width:36},{key:`views`,label:`views`,align:`right`,width:8},{key:`uniqueVisitors`,label:`unique`,align:`right`,width:8},{key:`avgTime`,label:`avg time`,align:`right`,width:9,format:e=>typeof e==`number`?`${Math.round(e/1e3)}s`:`—`},{key:`bounceRate`,label:`bounce`,align:`right`,width:7,format:e=>typeof e==`number`?`${(e*100).toFixed(0)}%`:`—`}];return g.createElement(d,{flexDirection:`column`},g.createElement(o,{version:r,subtitle:`pages · ${n}`}),g.createElement(a,{title:`Top pages (${p.length})`},g.createElement(u,{columns:T,data:p,zebra:!0})),g.createElement(s,{items:[{key:`q`,label:`quit`}]}))};export{b as pagesCommand};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{readConfig as e}from"./config-CZ9IzjIH.js";import{ApiError as t,readToken as n}from"./api-DXmhz2DM.js";import{ApiV2Client as r}from"./api-v2-CfJ_2Z5N.js";import i from"open";function a(e,t){let n=e/100;return`${t.toUpperCase()} ${n.toFixed(2)}`}async function o(o){let s=await e(),c=await n({strict:!1}),l=new r({config:s,cliVersion:o.cliVersion,token:c});try{switch(o.action){case`info`:{let e=await l.getPlanInfo();if(o.json)return process.stdout.write(JSON.stringify(e,null,2)+`
|
|
2
|
+
`),0;let t=[``,` plan: ${e.plan}`,` status: ${e.status}${e.cancelAtPeriodEnd?` (cancels at period end)`:``}`,` current period: ${e.currentPeriodStart??`—`} → ${e.currentPeriodEnd??`—`}`,` websites in use: ${e.usage.websites}`];return e.nextInvoice&&t.push(` next invoice: ${a(e.nextInvoice.amountDue,e.nextInvoice.currency)} on ${e.nextInvoice.periodEnd??`—`}`),t.push(``),process.stdout.write(t.join(`
|
|
3
|
+
`)),0}case`upgrade`:if(!o.targetPlan)return process.stderr.write("Error: pass <plan> (pro | scale | enterprise) — e.g. `zenovay plans upgrade pro`.\n"),2;try{let e=await l.upgradePlan(o.targetPlan);return o.json?(process.stdout.write(JSON.stringify(e,null,2)+`
|
|
4
|
+
`),0):(process.stdout.write(`✔ Upgraded to ${e.plan} (subscription ${e.subscriptionId}, status ${e.status}).\n`),0)}catch(e){if(e instanceof t&&e.status===409){let t=e.body??{},n=t.checkoutUrl??`https://app.zenovay.com/plans?upgrade=${o.targetPlan}`;if(o.json)return process.stdout.write(JSON.stringify({requiresCheckout:!0,checkoutUrl:n},null,2)+`
|
|
5
|
+
`),0;process.stdout.write(`Opening browser to complete checkout:\n ${n}\n`);try{await i(n)}catch{}return 0}throw e}case`cancel`:{if(!o.yes)return process.stderr.write("Error: `plans cancel` requires --yes to confirm. Your subscription will continue until the end of the current period.\n"),2;let e=await l.cancelPlan();return o.json?(process.stdout.write(JSON.stringify(e,null,2)+`
|
|
6
|
+
`),0):(process.stdout.write(`✔ Subscription scheduled to cancel on ${e.effectiveAt}.\n`),0)}case`payment`:{if(o.paymentAction!==`update`)return process.stderr.write("Error: only `plans payment update` is supported.\n"),2;let e=`https://app.zenovay.com/billing/portal`;if(o.json)return process.stdout.write(JSON.stringify({portalUrl:e},null,2)+`
|
|
7
|
+
`),0;process.stdout.write(`Opening Stripe Customer Portal:\n ${e}\n`);try{await i(e)}catch{}return 0}}}catch(e){return process.stderr.write(`✗ ${e.message}\n`),1}}export{o as plansCommand};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{readConfig as e}from"./config-CZ9IzjIH.js";import{readToken as t}from"./api-DXmhz2DM.js";import{ApiV2Client as n}from"./api-v2-CfJ_2Z5N.js";async function r(r){let i=await e(),a=await t({strict:!1}),o=new n({config:i,cliVersion:r.cliVersion,token:a});try{switch(r.action){case`show`:{let e=await o.me();if(r.json)return process.stdout.write(JSON.stringify(e,null,2)+`
|
|
2
|
+
`),0;let t=[``,` email: ${e.user.email}`,` name: ${e.user.name??`—`}`,` user id: ${e.user.id}`];return e.team&&(t.push(` team: ${e.team.name} (${e.team.id})`),t.push(` plan: ${e.team.plan}`)),t.push(``),process.stdout.write(t.join(`
|
|
3
|
+
`)),0}case`edit`:{if(r.name===void 0&&r.notifications===void 0)return process.stderr.write("Error: pass --name <n> or --notifications <email|none> for `profile edit`.\n"),2;let e={};r.name!==void 0&&(e.name=r.name),r.notifications!==void 0&&(e.notifications=r.notifications);let t=await o.updateProfile(e);return r.json?(process.stdout.write(JSON.stringify(t,null,2)+`
|
|
4
|
+
`),0):(process.stdout.write(`✔ Profile updated.${t.name?` name → ${t.name}`:``}${t.notifications?` notifications → ${t.notifications}`:``}\n`),0)}}}catch(e){return process.stderr.write(`✗ ${e.message}\n`),1}}export{r as profileCommand};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{BRAND_GRADIENT as e,useTheme as t}from"./panel-
|
|
1
|
+
import{BRAND_GRADIENT as e,useTheme as t}from"./panel-uygscwY5.js";import{Box as n,Text as r}from"ink";import i from"react";function a(e){let t=e.replace(`#`,``).trim(),n=t.length===3?t.split(``).map(e=>e+e).join(``):t,r=parseInt(n.slice(0,2),16),i=parseInt(n.slice(2,4),16),a=parseInt(n.slice(4,6),16);return{r:Number.isNaN(r)?0:r,g:Number.isNaN(i)?0:i,b:Number.isNaN(a)?0:a}}function o({r:e,g:t,b:n}){let r=e=>{let t=Math.max(0,Math.min(255,Math.round(e)));return t.toString(16).padStart(2,`0`)};return`#${r(e)}${r(t)}${r(n)}`}function s(e,t,n){return{r:e.r+(t.r-e.r)*n,g:e.g+(t.g-e.g)*n,b:e.b+(t.b-e.b)*n}}function c(e,t,n,a){if(e.length===0)return[];if(e.length===1)return[i.createElement(r,{key:`${a}-0`,color:o(t)},e)];let c=Array.from(e),l=c.length-1;return c.map((e,c)=>{let u=c/l,d=o(s(t,n,u));return i.createElement(r,{key:`${a}-${c}`,color:d},e)})}function l({from:e,to:t,children:n}){let o=a(e),s=a(t),l=n.split(`
|
|
2
2
|
`),u=[];return l.forEach((e,t)=>{t>0&&u.push(i.createElement(r,{key:`nl-${t}`},`
|
|
3
3
|
`));let n=c(e,o,s,`l${t}`);u.push(...n)}),i.createElement(r,null,u)}function u({children:t}){return i.createElement(l,{from:e.from,to:e.to},t)}const d=({done:e,total:a,label:o})=>{let{theme:s}=t(),c=a>0&&e>=a,l=c?s.success:s.accent,u=c?`Done`:o??``;return i.createElement(n,{flexDirection:`row`},i.createElement(r,{color:l},`[`,e,`/`,a,`]`),u?i.createElement(r,{color:s.fg},` `,u):null)};export{u as BrandGradient,d as ProgressRow};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./config-CZ9IzjIH.js";import"./api-DXmhz2DM.js";import"./api-v2-CfJ_2Z5N.js";import"./formatter-mW0Yk3Nt.js";import"./panel-uygscwY5.js";import"./banner-BPQh2F8l.js";import"./progress-row-DFOvHAc5.js";import"./prompt-BURfUNxp.js";import"./keybar-C7YkmK1U.js";import"./sparkline-Bkfzqe4x.js";import"./resolve-site-D3e1i32Z.js";import"./bar-C9stEeJd.js";import"./analytical-screen-B4KwZvWt.js";import"./ui-oBd4Xpw5.js";import{projectsCommand as e}from"./projects-Cz7V3Yr9.js";export{e as projectsCommand};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{readConfig as e}from"./config-CZ9IzjIH.js";import{readToken as t}from"./api-DXmhz2DM.js";import{ApiV2Client as n}from"./api-v2-CfJ_2Z5N.js";import{formatTabular as r,selectFormat as i}from"./formatter-mW0Yk3Nt.js";import{resolveSiteId as a}from"./resolve-site-D3e1i32Z.js";import{runAnalyticalScreen as o}from"./analytical-screen-B4KwZvWt.js";import{Table as s}from"./ui-oBd4Xpw5.js";import{Text as c}from"ink";import l from"react";function u(){let e=process.stdout.columns??80,t=Math.max(40,e-4-18),n=1,r=t-n,i=Math.max(8,Math.floor(r*.3)),a=Math.max(8,Math.floor(r*.32)),o=Math.max(4,Math.floor(r*.1)),s=Math.max(6,Math.floor(r*.12)),c=Math.max(4,r-i-a-o-s);return{current:n,name:i,domain:a,tier:o,pageviews24h:s,id:c}}async function d(d){let f=await e(),p=await t({strict:!1}),m=new n({config:f,cliVersion:d.cliVersion,token:p}),h,g;try{({siteId:h,site:g}=await a(m,{explicit:d.siteId,headless:!!(d.json||d.csv||d.tsv||d.ndjson),cliVersion:d.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let _=i(d),v=u(),y=[{key:`isCurrent`,header:``,width:v.current,format:e=>e?`*`:` `},{key:`name`,header:`project`,width:v.name},{key:`domain`,header:`domain`,width:v.domain,format:e=>String(e??`—`)},{key:`tier`,header:`tier`,width:v.tier},{key:`pageviews24h`,header:`24h pv`,width:v.pageviews24h,align:`right`},{key:`id`,header:`id`,width:v.id}];return o({cliVersion:d.cliVersion,title:`projects · ${p?.teamId??`—`}`,commandName:`projects`,authToken:p?.accessToken??null,refreshIntervalMs:0,fetcher:e=>m.getProjects(h,e),format:_,headlessEmit:(e,t)=>{if(t===`json`||t===`ndjson`){if(t===`ndjson`)for(let t of e.projects)process.stdout.write(JSON.stringify(t)+`
|
|
2
|
+
`);else process.stdout.write(JSON.stringify(e,null,2));return}process.stdout.write(r(e.projects,[`id`,`name`,`domain`,`tier`,`pageviews24h`,`isCurrent`],t))},keybindings:{s:{label:`switch project (logout + login)`,handler:()=>{process.stderr.write("To switch project: run `zenovay logout` then `zenovay login`.\n")}}},panels:[{id:`projects`,title:`Projects`,render:e=>e.projects.length===0?l.createElement(c,{color:`gray`},`— no projects yet —`):l.createElement(s,{data:e.projects,columns:y})}]})}export{d as projectsCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{useTheme as e}from"./panel-uygscwY5.js";import{Box as t,Text as n,useInput as r}from"ink";import i,{useCallback as a,useState as o}from"react";import s from"ink-select-input";import c from"ink-text-input";function l({hints:t}){let{theme:r}=e();return i.createElement(n,{color:r.dim},t)}function u({items:r,onSelect:c}){let{theme:u}=e(),[d,f]=o(r[0]),[p,m]=o(null),h=a(e=>{m({label:e.label}),setTimeout(()=>c(e.value),200)},[c]),g=a(e=>{f(e)},[]);return p?i.createElement(n,{color:u.success},`✓ `,p.label):i.createElement(t,{flexDirection:`column`},i.createElement(s,{items:r.map((e,t)=>({key:`${t}`,label:e.label,value:e.value})),onSelect:e=>{let t=r.find(t=>t.value===e.value);t&&h(t)},onHighlight:e=>{let t=r.find(t=>t.value===e.value);t&&g(t)}}),d?.description?i.createElement(t,{marginTop:1},i.createElement(n,{color:u.muted},d.description)):null,i.createElement(t,{marginTop:1},i.createElement(l,{hints:`[↑↓/jk nav] [enter select]`})))}function d({question:r,onSubmit:a,placeholder:s,mask:u}){let{theme:d}=e(),[f,p]=o(``);return i.createElement(t,{flexDirection:`column`},i.createElement(t,null,i.createElement(n,{color:d.fg},r,` `),i.createElement(c,{value:f,onChange:p,onSubmit:e=>a(e),placeholder:s,mask:u?`•`:void 0})),i.createElement(l,{hints:`[enter submit]`}))}export{u as Select,d as TextInput};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{readConfig as e}from"./config-CZ9IzjIH.js";import{readToken as t}from"./api-DXmhz2DM.js";import{ApiV2Client as n}from"./api-v2-CfJ_2Z5N.js";import{requireTier as r}from"./tier-RjOGNzda.js";import{formatTabular as i,selectFormat as a}from"./formatter-mW0Yk3Nt.js";import{Panel as o}from"./panel-uygscwY5.js";import{Banner as s}from"./banner-BPQh2F8l.js";import"./progress-row-DFOvHAc5.js";import"./prompt-BURfUNxp.js";import"./keybar-C7YkmK1U.js";import"./sparkline-Bkfzqe4x.js";import{resolveSiteId as c}from"./resolve-site-D3e1i32Z.js";import"./bar-C9stEeJd.js";import{Table as l}from"./ui-oBd4Xpw5.js";import{Box as u,Text as d,useApp as f,useInput as p}from"ink";import m,{useMemo as h,useState as g}from"react";import _ from"ink-text-input";function v({api:e,siteId:t,maxRows:n}){let{exit:r}=f(),[i,a]=g(``),[c,v]=g(null),[y,b]=g(null),[x,S]=g(!1),[C,w]=g([]);p((e,t)=>{t.escape&&r()});let T=async i=>{if(i.trim()){if(i.trim()===`\\q`||i.trim()===`exit`||i.trim()===`quit`){r();return}w(e=>[...e,i]),S(!0),b(null);try{let r=await e.runSqlQuery(t,i,{maxRows:n});v(r)}catch(e){b(e.message),v(null)}finally{S(!1),a(``)}}},E=h(()=>c?c.columns.map(e=>({key:e,header:e,width:18,format:e=>e==null?`∅`:String(e).slice(0,18)})):[],[c]);return m.createElement(u,{flexDirection:`column`},m.createElement(s,{version:`query`}),m.createElement(o,{title:`History`,state:`idle`},C.length===0?m.createElement(d,{color:`gray`},`— no queries yet — Esc or \\q to exit —`):C.slice(-5).map((e,t)=>m.createElement(d,{key:t,color:`gray`},`> ${e.slice(0,80)}${e.length>80?`…`:``}`))),m.createElement(u,null,m.createElement(d,{color:`magenta`},`sql`,`>`,` `),m.createElement(_,{value:i,onChange:a,onSubmit:T})),x?m.createElement(d,{color:`gray`},`running…`):null,y?m.createElement(o,{title:`Error`,state:`err`},m.createElement(d,{color:`red`},y)):null,c?m.createElement(o,{title:`${c.row_count} rows · ${c.duration_ms}ms${c.truncated?` · truncated`:``}`,state:`ok`},c.row_count===0?m.createElement(d,{color:`gray`},`— empty —`):m.createElement(l,{data:c.rows.slice(0,50),columns:E})):null)}async function y(o){let s=await e(),l=await t({strict:!1}),u=new n({config:s,cliVersion:o.cliVersion,token:l});try{await r(u,`scale`)}catch(e){return process.stderr.write(`${e.message}\n`),2}let d;try{({siteId:d}=await c(u,{explicit:o.siteId,headless:!!(o.json||o.csv||o.tsv||o.ndjson),cliVersion:o.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let f=o.maxRows??1e3,p=a(o);if(o.sql)try{let e=await u.runSqlQuery(d,o.sql,{maxRows:f});if(p===`json`)process.stdout.write(JSON.stringify(e,null,2)),process.stdout.write(`
|
|
2
|
+
`);else if(p===`ndjson`)for(let t of e.rows)process.stdout.write(JSON.stringify(t)+`
|
|
3
|
+
`);else if(p===`csv`||p===`tsv`)process.stdout.write(i(e.rows,e.columns,p));else{let t=e.columns.map(t=>Math.max(t.length,...e.rows.map(e=>String(e[t]??``).length))),n=`+`+t.map(e=>`-`.repeat(e+2)).join(`+`)+`+`;process.stdout.write(n+`
|
|
4
|
+
`),process.stdout.write(`|`+e.columns.map((e,n)=>` ${e.padEnd(t[n]??0)} `).join(`|`)+`|
|
|
5
|
+
`),process.stdout.write(n+`
|
|
6
|
+
`);for(let n of e.rows.slice(0,200))process.stdout.write(`|`+e.columns.map((e,r)=>` ${String(n[e]??``).padEnd(t[r]??0)} `).join(`|`)+`|
|
|
7
|
+
`);process.stdout.write(n+`
|
|
8
|
+
`),process.stdout.write(`${e.row_count} rows · ${e.duration_ms}ms${e.truncated?` · truncated`:``}\n`)}return 0}catch(e){return process.stderr.write(`✗ ${e.message}\n`),1}let{render:h}=await import(`ink`);return await h(m.createElement(v,{api:u,siteId:d,maxRows:f})).waitUntilExit(),0}export{y as queryCommand};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readConfig as e,updateConfig as t}from"./config-CZ9IzjIH.js";import{Panel as n}from"./panel-
|
|
1
|
+
import{readConfig as e,updateConfig as t}from"./config-CZ9IzjIH.js";import{Panel as n}from"./panel-uygscwY5.js";import{Banner as r}from"./banner-BPQh2F8l.js";import{Select as i}from"./prompt-BURfUNxp.js";import{Box as a,Text as o,render as s}from"ink";import c from"react";async function l(n,r){if(r.explicit&&r.explicit.trim())return{siteId:r.explicit.trim(),saved:!1};let i=await e(),a;try{a=await n.getSites()}catch(e){if(i.defaultSiteId)return{siteId:i.defaultSiteId,saved:!1};throw Error(`Could not fetch your sites (${e.message}). Pass --site-id <ID> to bypass.`)}if(i.defaultSiteId){let e=a.find(e=>e.id===i.defaultSiteId);if(e)return{siteId:e.id,site:e,saved:!1};await t({defaultSiteId:void 0,defaultSiteName:void 0})}if(a.length===0)throw Error("No sites in your account. Run `zenovay init` to add one, or create one at app.zenovay.com.");if(a.length===1){let e=a[0];return await t({defaultSiteId:e.id,defaultSiteName:e.name}),{siteId:e.id,site:e,saved:!0}}if(r.headless||!process.stdout.isTTY){let e=a.map(e=>` ${e.name.padEnd(24)} ${e.url.padEnd(36)} ${e.id}`).join(`
|
|
2
2
|
`);throw Error(`Multiple sites found — pick one:\n${e}\n\nPass --site-id <ID>, set ZENOVAY_SITE=<ID>, or run \`zenovay use <domain>\` to set a default.`)}let o=await u(a,r.cliVersion);return await t({defaultSiteId:o.id,defaultSiteName:o.name}),{siteId:o.id,site:o,saved:!0}}function u(e,t=`0`){return new Promise((n,r)=>{let i,a=e=>{i?.(),n(e)},o=()=>{i?.(),r(Error(`Site selection cancelled`))},l=s(c.createElement(d,{sites:e,cliVersion:t,onPick:a,onCancel:o}));i=l.unmount})}const d=({sites:e,cliVersion:t,onPick:s})=>{let l=e.map(e=>({label:`${e.name.padEnd(28)} ${e.url.replace(/^https?:\/\//,``).padEnd(28)}`,value:e,description:e.trackingCode?`tracking: ${e.trackingCode}`:void 0}));return c.createElement(a,{flexDirection:`column`},c.createElement(r,{version:t,subtitle:`pick a site`}),c.createElement(n,{title:`Which site?`,state:`idle`},c.createElement(a,{marginBottom:1},c.createElement(o,{color:`gray`},"We'll save your pick as the default — re-run with `zenovay use --reset` to change it.")),c.createElement(i,{items:l,onSelect:s})))};export{l as resolveSiteId};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readConfig as e}from"./config-CZ9IzjIH.js";import{readToken as t}from"./api-DXmhz2DM.js";import{ApiV2Client as n}from"./api-v2-CfJ_2Z5N.js";import{requireTier as r}from"./tier-RjOGNzda.js";import"./formatter-mW0Yk3Nt.js";import{emit as i,isHeadless as a}from"./emit-D7VCOSNk.js";import{Panel as o}from"./panel-uygscwY5.js";import{Banner as s}from"./banner-BPQh2F8l.js";import"./prompt-BURfUNxp.js";import{Keybar as c}from"./keybar-C7YkmK1U.js";import{resolveSiteId as l}from"./resolve-site-D3e1i32Z.js";import{EmptyState as u}from"./empty-state-Dkho-_3J.js";import{Box as d,Text as f,render as p,useApp as m,useInput as h}from"ink";import g,{useEffect as _,useState as v}from"react";import y from"ink-spinner";function b(e){return e>=.6?`magenta`:e>=.4?`cyan`:e>=.2?`blue`:`gray`}function x(e){return!Number.isFinite(e)||e===0?` — `:` ${(e*100).toFixed(0).padStart(3)}% `}async function S(o){let s=await e(),c=await t({strict:!1});if(!c)return process.stderr.write("Not logged in — run `zenovay login` first.\n"),2;let u=new n({config:s,cliVersion:o.cliVersion,token:c});try{await r(u,`pro`)}catch(e){return process.stderr.write(`${e.message}\n`),2}let d,f;try{({siteId:d,site:f}=await l(u,{explicit:o.siteId,headless:!!o.json,cliVersion:o.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let m=f?.url?f.url.replace(/^https?:\/\//,``).replace(/\/$/,``):f?.name??d;if(a(o)){let e=await u.getRetention(d);return i({type:`retention.snapshot`,data:e}),0}return new Promise(e=>{let{unmount:t}=p(g.createElement(C,{api:u,siteId:d,siteLabel:m,cliVersion:o.cliVersion,onExit:n=>{t(),e(n)}}))})}const C=({api:e,siteId:t,siteLabel:n,cliVersion:r,onExit:i})=>{let{exit:a}=m(),[l,p]=v(null),[S,C]=v(!0),[w,T]=v(null);return h(e=>{e===`q`&&(a(),i(0))}),_(()=>{let n=!1;return(async()=>{try{let r=await e.getRetention(t);n||(p(r.cohorts),C(!1))}catch(e){n||(T(e.message),C(!1))}})(),()=>{n=!0}},[e,t]),S?g.createElement(d,{flexDirection:`column`},g.createElement(s,{version:r,subtitle:`retention · ${n}`}),g.createElement(o,{title:`Loading`,state:`busy`},g.createElement(d,null,g.createElement(f,{color:`magenta`},g.createElement(y,{type:`dots`})),g.createElement(f,null,` Crunching cohorts…`)))):w?g.createElement(d,{flexDirection:`column`},g.createElement(s,{version:r,subtitle:`retention · ${n}`}),g.createElement(u,{reason:`error`,headline:`Failed to load`,hint:w})):!l||l.length===0?g.createElement(d,{flexDirection:`column`},g.createElement(s,{version:r,subtitle:`retention · ${n}`}),g.createElement(u,{reason:`no-data`,headline:`No retention data yet`,hint:`Retention needs at least 30 days of traffic`})):g.createElement(d,{flexDirection:`column`},g.createElement(s,{version:r,subtitle:`retention · ${n}`}),g.createElement(o,{title:`Cohort retention (D1 / D7 / D30)`},g.createElement(d,{flexDirection:`row`},g.createElement(f,{bold:!0},`cohort`.padEnd(12)),g.createElement(f,{bold:!0},` D1 `),g.createElement(f,{bold:!0},` D7 `),g.createElement(f,{bold:!0},` D30 `)),l.map(e=>g.createElement(d,{key:e.date,flexDirection:`row`},g.createElement(f,null,e.date.padEnd(12).slice(0,12)),g.createElement(f,{color:b(e.day1)},x(e.day1)),g.createElement(f,{color:b(e.day7)},x(e.day7)),g.createElement(f,{color:b(e.day30)},x(e.day30))))),g.createElement(c,{items:[{key:`q`,label:`quit`}]}))};export{S as retentionCommand};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{readConfig as e}from"./config-CZ9IzjIH.js";import{readToken as t}from"./api-DXmhz2DM.js";import{ApiV2Client as n}from"./api-v2-CfJ_2Z5N.js";import{formatTabular as r,selectFormat as i}from"./formatter-mW0Yk3Nt.js";import"./panel-uygscwY5.js";import"./banner-BPQh2F8l.js";import"./progress-row-DFOvHAc5.js";import"./prompt-BURfUNxp.js";import"./keybar-C7YkmK1U.js";import{spark as a}from"./sparkline-Bkfzqe4x.js";import{resolveSiteId as o}from"./resolve-site-D3e1i32Z.js";import"./bar-C9stEeJd.js";import{runAnalyticalScreen as s}from"./analytical-screen-B4KwZvWt.js";import"./ui-oBd4Xpw5.js";import{Box as c,Text as l}from"ink";import u from"react";function d(e,t){let n=e/100,r=new Intl.NumberFormat(`en-US`,{minimumFractionDigits:0,maximumFractionDigits:0}).format(n),i=(t||`USD`).toUpperCase();return i===`USD`?`$${r}`:i===`EUR`?`€${r}`:i===`GBP`?`£${r}`:`${r} ${i}`}async function f(f){let p=await e(),m=await t({strict:!1}),h=new n({config:p,cliVersion:f.cliVersion,token:m}),g,_;try{({siteId:g,site:_}=await o(h,{explicit:f.siteId,headless:!!(f.json||f.csv||f.tsv||f.ndjson),cliVersion:f.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let v=i(f),y=f.range??`30d`;return s({cliVersion:f.cliVersion,title:`revenue · ${g} · ${y}`,commandName:`revenue`,authToken:m?.accessToken??null,refreshIntervalMs:f.watch?5*6e4:0,fetcher:e=>h.getRevenue(g,y,e),format:v,headlessEmit:(e,t)=>{if(t===`json`||t===`ndjson`){process.stdout.write(JSON.stringify(e,null,t===`json`?2:0)),t===`ndjson`&&process.stdout.write(`
|
|
2
|
+
`);return}process.stdout.write(r(e.series,[`bucket`,`amount`,`currency`,`transactions`],t))},panels:[{id:`totals`,title:`Top line`,render:e=>u.createElement(c,{flexDirection:`column`},u.createElement(l,null,u.createElement(l,{color:`green`,bold:!0},d(e.totalAmount,e.currency)),` `,u.createElement(l,{color:`gray`},`total · `,e.totalTransactions,` transactions`)),typeof e.mrr==`number`?u.createElement(l,null,u.createElement(l,{bold:!0},`MRR `),u.createElement(l,{color:`magenta`},d(e.mrr,e.currency)),typeof e.arpu==`number`?u.createElement(l,{color:`gray`},` · ARPU `,d(e.arpu,e.currency)):null):null)},{id:`series`,title:`Daily (${y})`,render:e=>{let t=e.series.map(e=>e.amount);if(t.length===0)return u.createElement(l,{color:`gray`},`— no transactions —`);let n=Math.max(...t,1);return u.createElement(c,{flexDirection:`column`},u.createElement(l,{color:`magenta`},a(t,Math.min(60,t.length*2))),u.createElement(l,{color:`gray`},`peak: `,d(n,e.currency),` ·`,` `,`avg: `,d(e.totalAmount/Math.max(1,t.length),e.currency)))}},{id:`window`,title:`Window`,render:e=>u.createElement(l,{color:`gray`},new Date(e.windowStart).toISOString().slice(0,10),` →`,` `,new Date(e.windowEnd).toISOString().slice(0,10))}]})}export{f as revenueCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readConfig as e}from"./config-CZ9IzjIH.js";import{readToken as t}from"./api-DXmhz2DM.js";import{ApiV2Client as n}from"./api-v2-CfJ_2Z5N.js";import{requireTier as r}from"./tier-RjOGNzda.js";import"./formatter-mW0Yk3Nt.js";import{emit as i,isHeadless as a}from"./emit-D7VCOSNk.js";import{Panel as o}from"./panel-uygscwY5.js";import{Banner as s}from"./banner-BPQh2F8l.js";import"./prompt-BURfUNxp.js";import{Keybar as c}from"./keybar-C7YkmK1U.js";import{resolveSiteId as l}from"./resolve-site-D3e1i32Z.js";import{EmptyState as u}from"./empty-state-Dkho-_3J.js";import{DataTable as d}from"./data-table-BVWqHy9m.js";import{Box as f,Text as p,render as m,useApp as h,useInput as g}from"ink";import _,{useEffect as v,useState as y}from"react";import b from"ink-spinner";function x(e){if(!e||e<=0)return`—`;let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60);return`${n}m ${(t%60).toString().padStart(2,`0`)}s`}function S(e){if(!e)return`—`;let t=Date.parse(e);if(Number.isNaN(t))return`—`;let n=Math.max(0,Math.floor((Date.now()-t)/1e3));return n<60?`${n}s`:n<3600?`${Math.floor(n/60)}m`:n<86400?`${Math.floor(n/3600)}h`:`${Math.floor(n/86400)}d`}async function C(o){let s=await e(),c=await t({strict:!1});if(!c)return process.stderr.write("Not logged in — run `zenovay login` first.\n"),2;let u=new n({config:s,cliVersion:o.cliVersion,token:c});try{await r(u,`pro`)}catch(e){return process.stderr.write(`${e.message}\n`),2}let d,f;try{({siteId:d,site:f}=await l(u,{explicit:o.siteId,headless:!!o.json,cliVersion:o.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let p=f?.url?f.url.replace(/^https?:\/\//,``).replace(/\/$/,``):f?.name??d;if(a(o)){let e=await u.getSessions(d);return i({type:`sessions.snapshot`,data:e}),0}return new Promise(e=>{let{unmount:t}=m(_.createElement(w,{api:u,siteId:d,siteLabel:p,cliVersion:o.cliVersion,onExit:n=>{t(),e(n)}}))})}const w=({api:e,siteId:t,siteLabel:n,cliVersion:r,onExit:i})=>{let{exit:a}=h(),[l,m]=y(null),[C,w]=y(!0),[T,E]=y(null);if(g(e=>{e===`q`&&(a(),i(0))}),v(()=>{let n=!1;return(async()=>{try{let r=await e.getSessions(t);n||(m(r),w(!1))}catch(e){n||(E(e.message),w(!1))}})(),()=>{n=!0}},[e,t]),C)return _.createElement(f,{flexDirection:`column`},_.createElement(s,{version:r,subtitle:`sessions · ${n}`}),_.createElement(o,{title:`Loading`,state:`busy`},_.createElement(f,null,_.createElement(p,{color:`magenta`},_.createElement(b,{type:`dots`})),_.createElement(p,null,` Fetching sessions…`))));if(T)return _.createElement(f,{flexDirection:`column`},_.createElement(s,{version:r,subtitle:`sessions · ${n}`}),_.createElement(u,{reason:`error`,headline:`Failed to load`,hint:T}));if(!l||l.length===0)return _.createElement(f,{flexDirection:`column`},_.createElement(s,{version:r,subtitle:`sessions · ${n}`}),_.createElement(u,{reason:`no-data`,headline:`No replays yet`,hint:`Enable session replay in your site settings`}));let D=[{key:`id`,label:`session id`,width:24},{key:`visitor`,label:`visitor`,width:18},{key:`duration`,label:`duration`,align:`right`,width:9,format:e=>x(e)},{key:`startedAt`,label:`when`,align:`right`,width:6,format:e=>S(String(e))},{key:`pageCount`,label:`events`,align:`right`,width:7},{key:`deviceType`,label:`device`,width:8,format:e=>String(e??`—`)}];return _.createElement(f,{flexDirection:`column`},_.createElement(s,{version:r,subtitle:`sessions · ${n}`}),_.createElement(o,{title:`Recent sessions (${l.length})`},_.createElement(d,{columns:D,data:l,zebra:!0})),_.createElement(f,{marginTop:1},_.createElement(p,{color:`gray`},`Open any session for replay at https://app.zenovay.com/replay`)),_.createElement(c,{items:[{key:`q`,label:`quit`}]}))};export{C as sessionsCommand};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{readConfig as e}from"./config-CZ9IzjIH.js";import{readToken as t}from"./api-DXmhz2DM.js";import{ApiV2Client as n}from"./api-v2-CfJ_2Z5N.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};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{readConfig as e}from"./config-CZ9IzjIH.js";import{readToken as t}from"./api-DXmhz2DM.js";import{ApiV2Client as n}from"./api-v2-CfJ_2Z5N.js";import{formatTabular as r,selectFormat as i}from"./formatter-mW0Yk3Nt.js";import"./panel-uygscwY5.js";import"./banner-BPQh2F8l.js";import"./progress-row-DFOvHAc5.js";import"./prompt-BURfUNxp.js";import"./keybar-C7YkmK1U.js";import"./sparkline-Bkfzqe4x.js";import{resolveSiteId as a}from"./resolve-site-D3e1i32Z.js";import"./bar-C9stEeJd.js";import{runAnalyticalScreen as o}from"./analytical-screen-B4KwZvWt.js";import{Table as s}from"./ui-oBd4Xpw5.js";import{Box as c,Text as l}from"ink";import u from"react";function d(e,t){let n=Math.round(e/100*t);return`█`.repeat(n)+`░`.repeat(Math.max(0,t-n))}function f(e){return e==null?{glyph:`·`,color:`gray`}:e>.5?{glyph:`▲`,color:`green`}:e<-.5?{glyph:`▼`,color:`red`}:{glyph:`→`,color:`gray`}}async function p(p){let m=await e(),h=await t({strict:!1}),g=new n({config:m,cliVersion:p.cliVersion,token:h}),_,v;try{({siteId:_,site:v}=await a(g,{explicit:p.siteId,headless:!!(p.json||p.csv||p.tsv||p.ndjson),cliVersion:p.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let y=i(p),b=p.period??`30d`,x=[{key:`source`,header:`source`,width:22},{key:`channel`,header:`channel`,width:10,format:e=>String(e??`—`)},{key:`visitors`,header:`visitors`,width:8,align:`right`},{key:`delta`,header:`Δ`,width:6,align:`right`,format:e=>typeof e==`number`?`${e>0?`+`:``}${(e*100).toFixed(1)}%`:`—`}];return o({cliVersion:p.cliVersion,title:`sources · ${_} · ${b}`,commandName:`sources`,authToken:h?.accessToken??null,refreshIntervalMs:6e4,fetcher:e=>g.getSources(_,b,p.compare,e),format:y,headlessEmit:(e,t)=>{if(t===`json`||t===`ndjson`){process.stdout.write(JSON.stringify(e,null,t===`json`?2:0)),t===`ndjson`&&process.stdout.write(`
|
|
2
|
+
`);return}process.stdout.write(r(e.sources,[`source`,`channel`,`visitors`,`conversions`,`revenue`,`delta`],t))},panels:[{id:`summary`,title:`Total`,render:e=>u.createElement(l,null,u.createElement(l,{bold:!0},e.totalVisitors.toLocaleString()),` `,u.createElement(l,{color:`gray`},`visitors · `,e.sources.length,` sources`))},{id:`channels`,title:`By channel`,render:e=>{if(e.sources.length===0)return u.createElement(l,{color:`gray`},`— no source data —`);let t=e.totalVisitors||1,n=[...e.sources].sort((e,t)=>t.visitors-e.visitors).slice(0,12);return u.createElement(c,{flexDirection:`column`},n.map((e,n)=>{let r=e.visitors/t*100,i=f(e.delta);return u.createElement(c,{key:`${e.source}-${n}`},u.createElement(l,null,u.createElement(l,{color:`cyan`},e.source.padEnd(20).slice(0,20)),` `,u.createElement(l,{color:`magenta`},d(r,30)),` `,u.createElement(l,null,e.visitors.toString().padStart(6),` `),u.createElement(l,{color:`gray`},`(`,r.toFixed(1),`%)`),` `,u.createElement(l,{color:i.color},i.glyph)))}))}},{id:`table`,title:`Detail`,render:e=>e.sources.length===0?u.createElement(l,{color:`gray`},`— —`):u.createElement(s,{data:e.sources.slice(0,20),columns:x})}]})}export{p as sourcesCommand};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{readConfig as e}from"./config-CZ9IzjIH.js";import{readToken as t}from"./api-DXmhz2DM.js";import{ApiV2Client as n}from"./api-v2-CfJ_2Z5N.js";import{formatTabular as r,selectFormat as i}from"./formatter-mW0Yk3Nt.js";import"./panel-uygscwY5.js";import"./banner-BPQh2F8l.js";import"./progress-row-DFOvHAc5.js";import"./prompt-BURfUNxp.js";import"./keybar-C7YkmK1U.js";import"./sparkline-Bkfzqe4x.js";import{resolveSiteId as a}from"./resolve-site-D3e1i32Z.js";import"./bar-C9stEeJd.js";import{runAnalyticalScreen as o}from"./analytical-screen-B4KwZvWt.js";import{Table as s}from"./ui-oBd4Xpw5.js";import{Box as c,Text as l}from"ink";import u from"react";function d(e){return`${(e*100).toFixed(1)}%`}function f(e){return e<60?`${Math.round(e)}s`:e<3600?`${Math.floor(e/60)}m ${Math.round(e%60)}s`:`${Math.floor(e/3600)}h ${Math.floor(e%3600/60)}m`}async function p(p){let m=await e(),h=await t({strict:!1}),g=new n({config:m,cliVersion:p.cliVersion,token:h}),_,v;try{({siteId:_,site:v}=await a(g,{explicit:p.siteId,headless:!!(p.json||p.csv||p.tsv||p.ndjson),cliVersion:p.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let y=i(p),b=p.range??`24h`,x=[{key:`url`,header:`page`,width:40,format:e=>String(e??`—`)},{key:`views`,header:`views`,width:8,align:`right`}],S=[{key:`country`,header:`country`,width:8},{key:`visitors`,header:`visitors`,width:8,align:`right`}];return o({cliVersion:p.cliVersion,title:`stats · ${_} · ${b}`,commandName:`stats`,authToken:h?.accessToken??null,refreshIntervalMs:p.watch?6e4:0,fetcher:e=>g.getStats(_,b,e),format:y,headlessEmit:(e,t)=>{if(t===`json`||t===`ndjson`){process.stdout.write(JSON.stringify(e,null,t===`json`?2:0)),t===`ndjson`&&process.stdout.write(`
|
|
2
|
+
`);return}process.stdout.write(r([{range:b,visitors:e.visitors,pageviews:e.pageviews,sessions:e.sessions,bounceRate:d(e.bounceRate),avgSession:f(e.avgSessionSec)}],[`range`,`visitors`,`pageviews`,`sessions`,`bounceRate`,`avgSession`],t))},panels:[{id:`summary`,title:`Summary`,render:e=>u.createElement(c,{flexDirection:`column`},u.createElement(l,null,u.createElement(l,{bold:!0},e.visitors.toLocaleString()),u.createElement(l,{color:`gray`},` visitors `),u.createElement(l,{bold:!0},e.pageviews.toLocaleString()),u.createElement(l,{color:`gray`},` pageviews `),u.createElement(l,{bold:!0},e.sessions.toLocaleString()),u.createElement(l,{color:`gray`},` sessions`)),u.createElement(l,{color:`gray`},`bounce `,d(e.bounceRate),` · avg session `,f(e.avgSessionSec)))},{id:`pages`,title:`Top pages`,render:e=>e.topPages.length===0?u.createElement(l,{color:`gray`},`— no pages —`):u.createElement(s,{data:e.topPages.slice(0,10),columns:x})},{id:`countries`,title:`Top countries`,render:e=>e.topCountries.length===0?u.createElement(l,{color:`gray`},`— no country data —`):u.createElement(s,{data:e.topCountries.slice(0,10),columns:S})}]})}export{p as statsCommand};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import{readConfig as e}from"./config-CZ9IzjIH.js";import{readToken as t}from"./api-DXmhz2DM.js";import{ApiV2Client as n}from"./api-v2-CfJ_2Z5N.js";import{requireTier as r}from"./tier-RjOGNzda.js";import{confirmDestructive as i}from"./confirm-D_aKHknn.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 t({strict:!1}),u=new n({config:c,cliVersion:s.cliVersion,token:l});try{await r(u,`pro`)}catch(e){return process.stderr.write(`✗ ${e.message}\n`),2}try{switch(s.action){case`list`:{let e=await u.listTeam();if(s.json)return process.stdout.write(JSON.stringify(e,null,2)+`
|
|
2
|
+
`),0;if(process.stdout.write(`\nMEMBERS (${e.members.length})\n`),e.members.length===0)process.stdout.write(` — none —
|
|
3
|
+
`);else{let t=[14,32,8,10],n=e=>e.map((e,n)=>(e??``).padEnd(t[n])).join(` `);process.stdout.write(n([`user id`,`email`,`role`,`joined`])+`
|
|
4
|
+
`),process.stdout.write(n(t.map(e=>`─`.repeat(e)))+`
|
|
5
|
+
`);for(let r of e.members)process.stdout.write(n([a(r.userId),(r.email??`—`).slice(0,t[1]),r.role,o(r.joinedAt)])+`
|
|
6
|
+
`)}if(process.stdout.write(`\nPENDING INVITES (${e.invites.length})\n`),e.invites.length===0)process.stdout.write(` — none —
|
|
7
|
+
`);else{let t=[14,32,8,10],n=e=>e.map((e,n)=>(e??``).padEnd(t[n])).join(` `);process.stdout.write(n([`invite id`,`email`,`role`,`expires`])+`
|
|
8
|
+
`),process.stdout.write(n(t.map(e=>`─`.repeat(e)))+`
|
|
9
|
+
`);for(let r of e.invites)process.stdout.write(n([a(r.id),r.email.slice(0,t[1]),r.role,o(r.expiresAt)])+`
|
|
10
|
+
`)}return process.stdout.write(`
|
|
11
|
+
`),0}case`invite`:{if(!s.email)return process.stderr.write("Error: <email> is required for `team invite`.\n"),2;let e=s.role===`admin`?`admin`:`member`,t=await u.inviteTeamMember({email:s.email,role:e});return s.json?(process.stdout.write(JSON.stringify(t)+`
|
|
12
|
+
`),0):t.status===`already_invited`?(process.stdout.write(`Already invited: ${t.email} (id: ${t.invitationId}).\n`),0):(process.stdout.write(`✔ Invited ${t.email} as ${e} (id: ${t.invitationId}).\n`),0)}case`remove`:{if(!s.userId)return process.stderr.write("Error: <user-id> is required for `team remove`.\n"),2;let e=await i({resource:`team member`,name:a(s.userId),yes:s.yes,destructive:!0});if(!e)return process.stdout.write(`Cancelled.
|
|
13
|
+
`),1;let t=await u.removeTeamMember(s.userId);return s.json?(process.stdout.write(JSON.stringify(t)+`
|
|
14
|
+
`),0):(process.stdout.write(`✔ Removed team member ${a(s.userId)}.\n`),0)}case`role`:{if(!s.userId||!s.role)return process.stderr.write("Error: both <user-id> and <new-role> are required for `team role`.\n"),2;let e=s.role===`admin`?`admin`:`member`,t=await u.updateTeamMemberRole(s.userId,e);return s.json?(process.stdout.write(JSON.stringify(t)+`
|
|
15
|
+
`),0):(process.stdout.write(`✔ Set ${a(s.userId)} role → ${t.role}.\n`),0)}}}catch(e){return process.stderr.write(`✗ ${e.message}\n`),1}}export{s as teamCommand};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{dracula as e,latte as t,mocha as n,nord as r,tokyoNight as i}from"./panel-uygscwY5.js";import{Banner as a}from"./banner-BPQh2F8l.js";import"./progress-row-DFOvHAc5.js";import"./prompt-BURfUNxp.js";import"./keybar-C7YkmK1U.js";import"./sparkline-Bkfzqe4x.js";import"./bar-C9stEeJd.js";import"./ui-oBd4Xpw5.js";import{promises as o}from"node:fs";import{Box as s,Text as c,render as l}from"ink";import u from"react";const d=[{name:`mocha`,theme:n,mode:`dark`},{name:`latte`,theme:t,mode:`light`},{name:`dracula`,theme:e,mode:`dark`},{name:`tokyoNight`,theme:i,mode:`dark`},{name:`nord`,theme:r,mode:`dark`}],f=[`name`,`bg`,`fg`,`muted`,`accent`,`accent2`,`success`,`warn`,`error`,`border`,`dim`];function p({name:e,theme:t,mode:n}){let r=[t.accent,t.accent2,t.success,t.warn,t.error];return u.createElement(s,{flexDirection:`row`},u.createElement(c,{bold:!0},e.padEnd(14)),u.createElement(c,{color:`gray`},n.padEnd(7)),r.map((e,t)=>u.createElement(c,{key:t,color:e},`████`,` `)),u.createElement(c,{color:`gray`},t.bg))}function m({themes:e}){return u.createElement(s,{flexDirection:`column`},u.createElement(a,{version:`themes`}),u.createElement(s,{marginTop:1,marginBottom:1},u.createElement(c,{color:`gray`},e.length,` themes — pass --theme <name> to any command, or set in your config.`)),u.createElement(s,{flexDirection:`column`},u.createElement(s,null,u.createElement(c,{bold:!0},`name`.padEnd(14)),u.createElement(c,{bold:!0},`mode`.padEnd(7)),u.createElement(c,{bold:!0},`swatch`.padEnd(28)),u.createElement(c,{bold:!0},`bg`)),e.map(({name:e,theme:t,mode:n})=>u.createElement(p,{key:e,name:e,theme:t,mode:n}))))}async function h(e){if(e.validate){let t;try{let n=await o.readFile(e.validate,`utf8`);t=JSON.parse(n)}catch(t){return process.stderr.write(`✗ Failed to read ${e.validate}: ${t.message}\n`),1}let n=f.filter(e=>t[e]==null);return n.length>0?(process.stderr.write(`✗ Missing required tokens: ${n.join(`, `)}\n`),e.json&&process.stdout.write(JSON.stringify({ok:!1,missing:n},null,2)+`
|
|
2
|
+
`),1):(process.stdout.write(`✔ Valid theme (${f.length} tokens present).\n`),e.json&&process.stdout.write(JSON.stringify({ok:!0,theme:t},null,2)+`
|
|
3
|
+
`),0)}if(e.json)return process.stdout.write(JSON.stringify({themes:d.map(({name:e,theme:t,mode:n})=>({name:e,mode:n,background:t.bg,foreground:t.fg,accent:t.accent}))},null,2)+`
|
|
4
|
+
`),0;let{waitUntilExit:t}=l(u.createElement(m,{themes:d}));return await t(),0}export{h as themesCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useTheme as e}from"./panel-
|
|
1
|
+
import{useTheme as e}from"./panel-uygscwY5.js";import{Box as t,Text as n,useInput as r}from"ink";import i,{useMemo as a,useState as o}from"react";import"diff";function s(e,t){return e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function c(e,t,n){if(e.length>=t)return s(e,t);let r=t-e.length;if(n===`right`)return` `.repeat(r)+e;if(n===`center`){let t=Math.floor(r/2),n=r-t;return` `.repeat(t)+e+` `.repeat(n)}return e+` `.repeat(r)}function l(e,t){return e.map(e=>{if(typeof e.width==`number`&&e.width>0)return e.width;let n=e.header.length;for(let r of t){let t=r[e.key],i=e.format?e.format(t,r):String(t??``);i.length>n&&(n=i.length)}return Math.max(3,n)})}function u({columns:r,data:a,zebra:o=!1}){let{theme:s}=e(),u=l(r,a),d=u.reduce((e,t)=>e+t,0)+r.length*3+1,f=(e,t,n)=>{let r=e;return u.forEach((e,i)=>{r+=`─`.repeat(e+2),r+=i===u.length-1?n:t}),r},p=f(`╭`,`┬`,`╮`),m=f(`├`,`┼`,`┤`),h=f(`╰`,`┴`,`╯`),g=r.map((e,t)=>c(e.header,u[t]??e.header.length,e.align??`left`)).join(` │ `);return i.createElement(t,{flexDirection:`column`,width:d},i.createElement(n,{color:s.border},p),i.createElement(t,{flexDirection:`row`},i.createElement(n,{color:s.border},`│ `),i.createElement(n,{bold:!0,color:s.accent},g),i.createElement(n,{color:s.border},` │`)),i.createElement(n,{color:s.border},m),a.map((e,a)=>{let l=o&&a%2==1,d=l?s.muted:s.fg,f=r.map((t,n)=>{let r=e[t.key],i=t.format?t.format(r,e):String(r??``);return c(i,u[n]??i.length,t.align??`left`)}).join(` │ `);return i.createElement(t,{key:a,flexDirection:`row`},i.createElement(n,{color:s.border},`│ `),i.createElement(n,{color:d},f),i.createElement(n,{color:s.border},` │`))}),i.createElement(n,{color:s.border},h))}export{u as Table};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readConfig as e}from"./config-CZ9IzjIH.js";import{classifyBump as t,fetchManifest as n}from"./check-Comj8AkL.js";import{applyUpdate as r}from"./apply-D2xZJdvQ.js";import"./formatter-
|
|
1
|
+
import{readConfig as e}from"./config-CZ9IzjIH.js";import{classifyBump as t,fetchManifest as n}from"./check-Comj8AkL.js";import{applyUpdate as r}from"./apply-D2xZJdvQ.js";import"./formatter-mW0Yk3Nt.js";import{emit as i,isHeadless as a}from"./emit-D7VCOSNk.js";async function o(o){let s=await e(),c=await n({cliBase:s.cliBase}),l=t(o.cliVersion,c.latest);if(o.check)return a({json:o.json})?i({type:`info`,message:`latest=${c.latest} current=${o.cliVersion} bump=${l}`}):process.stdout.write(`Current: ${o.cliVersion}\nLatest: ${c.latest}\nBump: ${l}\n`),{updated:!1,from:o.cliVersion,to:c.latest};if(l===`none`)return a({json:o.json})||process.stdout.write(`Already on latest (${o.cliVersion}).\n`),{updated:!1,from:o.cliVersion,to:c.latest};if(l===`downgrade`&&!o.forceDowngrade)throw Error(`Refused to downgrade ${o.cliVersion} → ${c.latest}. Pass --force-downgrade if you really want this.`);let u=await r({currentVersion:o.cliVersion,cliBase:s.cliBase,binaryPath:o.binaryPath,forceDowngrade:o.forceDowngrade});return a({json:o.json})?u.updated&&i({type:`update.applied`,from:u.from,to:u.to}):u.updated?process.stdout.write(`Updated ${u.from} → ${u.to}\n`):process.stdout.write(`Not updated (${u.reason??`unknown`}).\n`),u}export{o as updateCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readConfig as e}from"./config-CZ9IzjIH.js";import{readToken as t}from"./api-DXmhz2DM.js";import{ApiV2Client as n}from"./api-v2-CfJ_2Z5N.js";import{requireTier as r}from"./tier-RjOGNzda.js";import"./formatter-mW0Yk3Nt.js";import{emit as i,isHeadless as a}from"./emit-D7VCOSNk.js";import{Panel as o}from"./panel-uygscwY5.js";import{Banner as s}from"./banner-BPQh2F8l.js";import"./prompt-BURfUNxp.js";import{Keybar as c}from"./keybar-C7YkmK1U.js";import{resolveSiteId as l}from"./resolve-site-D3e1i32Z.js";import{EmptyState as u}from"./empty-state-Dkho-_3J.js";import{DataTable as d}from"./data-table-BVWqHy9m.js";import{Box as f,Text as p,render as m,useApp as h,useInput as g}from"ink";import _,{useEffect as v,useState as y}from"react";import b from"ink-spinner";function x(e){return e===`up`?{glyph:`● up`,color:`green`}:e===`down`?{glyph:`● down`,color:`red`}:{glyph:`○ unknown`,color:`gray`}}function S(e){if(!e)return`—`;let t=Date.parse(e);if(Number.isNaN(t))return`—`;let n=Math.round((t-Date.now())/(1e3*60*60*24));return`${n}d`}async function C(o){let s=await e(),c=await t({strict:!1});if(!c)return process.stderr.write("Not logged in — run `zenovay login` first.\n"),2;let u=new n({config:s,cliVersion:o.cliVersion,token:c});try{await r(u,`pro`)}catch(e){return process.stderr.write(`${e.message}\n`),2}let d,f;try{({siteId:d,site:f}=await l(u,{explicit:o.siteId,headless:!!o.json,cliVersion:o.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let p=f?.url?f.url.replace(/^https?:\/\//,``).replace(/\/$/,``):f?.name??d;if(a(o)){let e=await u.getUptime(d);return i({type:`uptime.snapshot`,data:e}),0}return new Promise(e=>{let{unmount:t}=m(_.createElement(w,{api:u,siteId:d,siteLabel:p,cliVersion:o.cliVersion,onExit:n=>{t(),e(n)}}))})}const w=({api:e,siteId:t,siteLabel:n,cliVersion:r,onExit:i})=>{let{exit:a}=h(),[l,m]=y(null),[C,w]=y(!0),[T,E]=y(null);if(g(e=>{e===`q`&&(a(),i(0))}),v(()=>{let n=!1;return(async()=>{try{let r=await e.getUptime(t);n||(m(r.monitors),w(!1))}catch(e){n||(E(e.message),w(!1))}})(),()=>{n=!0}},[e,t]),C)return _.createElement(f,{flexDirection:`column`},_.createElement(s,{version:r,subtitle:`uptime · ${n}`}),_.createElement(o,{title:`Loading`,state:`busy`},_.createElement(f,null,_.createElement(p,{color:`magenta`},_.createElement(b,{type:`dots`})),_.createElement(p,null,` Fetching monitors…`))));if(T)return _.createElement(f,{flexDirection:`column`},_.createElement(s,{version:r,subtitle:`uptime · ${n}`}),_.createElement(u,{reason:`error`,headline:`Failed to load`,hint:T}));if(!l||l.length===0)return _.createElement(f,{flexDirection:`column`},_.createElement(s,{version:r,subtitle:`uptime · ${n}`}),_.createElement(u,{reason:`no-data`,headline:`No monitors configured`,hint:`Add one at app.zenovay.com/uptime`}));let D=[{key:`url`,label:`monitor`,width:36},{key:`status`,label:`status`,width:12,format:e=>x(String(e)).glyph},{key:`p95ms`,label:`p95 ms`,align:`right`,width:8,format:e=>typeof e==`number`?String(e):`—`},{key:`sslExpiry`,label:`ssl exp`,align:`right`,width:7,format:e=>S(e)}];return _.createElement(f,{flexDirection:`column`},_.createElement(s,{version:r,subtitle:`uptime · ${n}`}),_.createElement(o,{title:`Monitors (${l.length})`},_.createElement(d,{columns:D,data:l,zebra:!0})),_.createElement(c,{items:[{key:`q`,label:`quit`}]}))};export{C as uptimeCommand};
|