@zenovay/cli 0.1.10 → 0.1.12
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.
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{readConfig as e}from"./config-ZTGpKEWg.js";import{ApiClient as t,readToken as n}from"./api-BhdaCghp.js";import{detectInstalled as r,initCommand as i}from"./init
|
|
1
|
+
import{readConfig as e}from"./config-ZTGpKEWg.js";import{ApiClient as t,readToken as n}from"./api-BhdaCghp.js";import{detectInstalled as r,initCommand as i}from"./init--eTjzzmh.js";import{parseSseStream as a}from"./client-DZ4Awt8u.js";import"./formatter-45-fT1Hv.js";import{emit as o,isHeadless as s}from"./emit-0WJ_OGeT.js";import"./login-DHLIZV8C.js";import{Panel as c}from"./panel-DglZ755S.js";import"./keybar-D2OI-8rx.js";import{Select as l}from"./prompt-hjzdzlyj.js";import"./sparkline-CR_bzxwB.js";import{Box as u,Text as d,render as f}from"ink";import p from"react";async function m(e){let t=await r(e.cwd),n;if(e.mode)n=e.mode;else if(!t.installed)n=`install`;else if(s(e))return o({type:`error`,code:`no_mode`,message:`Headless mode requires --mode chat|mcp|install`}),2;else n=await h(t);return n===`install`?i({cliVersion:e.cliVersion,cwd:e.cwd,json:e.json}):n===`chat`?g(e):_(e)}async function h(e){return new Promise(t=>{let n=[{label:`Chat with your analytics`,value:`chat`,description:`Ask natural-language questions about your data`},{label:`Manage via MCP`,value:`mcp`,description:`Create goals, funnels, sites, etc. in plain English`},{label:`Re-run install / repair`,value:`install`,description:`Run the install wizard again`}],{unmount:r}=f(p.createElement(u,{flexDirection:`column`},p.createElement(c,{title:`Zenovay detected${e.packageMarker?` (${e.packageMarker})`:``}`,state:`idle`},p.createElement(d,null,`What do you want to do?`)),p.createElement(l,{items:n,onSelect:e=>{r(),t(e)}})))})}async function g(r){let i=await e(),o=await n({strict:!1});if(!o)return process.stderr.write("Not logged in — run `zenovay login` first.\n"),2;let s=new t({config:i,cliVersion:r.cliVersion,token:o});process.stdout.write(`
|
|
2
2
|
Zenovay · chat mode — type your question then press Enter. Ctrl-C to exit.
|
|
3
3
|
|
|
4
4
|
> `);let c=await v();if(!c)return 0;let l=await s.openAiStream(`chat`,{messages:[{role:`user`,content:c}]});for await(let e of a(l)){if(e.type===`delta`&&process.stdout.write(e.content),e.type===`done`){process.stdout.write(`
|
package/dist/bin.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{cac as e}from"cac";import{fork as t}from"node:child_process";import n from"node:path";import{fileURLToPath as r}from"node:url";import{readFileSync as i}from"node:fs";const a=n.dirname(r(import.meta.url)),o=n.join(a,`..`,`package.json`),s=JSON.parse(i(o,`utf8`)),c=s.version,l=process.argv[0]??`zenovay`;function u(){if(!(process.env.ZENOVAY_NO_UPDATE_CHECK===`1`||process.env.CI===`true`))try{let e=n.join(a,`lib`,`update`,`worker.js`),r=t(e,[],{detached:!0,stdio:`ignore`});r.unref()}catch{}}const d=e(`zenovay`);d.version(c),d.help(),d.command(`init`,`AI install wizard — add Zenovay tracking to your codebase`).option(`--json`,`Emit NDJSON events to stdout`).option(`--yes`,`Auto-approve all diffs (for CI)`).option(`--skip-mcp`,`Skip MCP client install`).option(`--skip-verify`,`Skip first-event verification`).action(async e=>{let{initCommand:t}=await import(`./init-DgPZkr1n.js`),n=await t({cliVersion:c,cwd:process.cwd(),json:e.json,yes:e.yes,skipMcp:e.skipMcp,skipVerify:e.skipVerify});process.exitCode=n}),d.command(`login`,`Authenticate via OAuth device flow`).option(`--json`,`Emit NDJSON events`).option(`--no-browser`,`Skip opening the browser automatically`).action(async e=>{let{loginCommand:t}=await import(`./login-D4kNEDVO.js`);await t({cliVersion:c,json:e.json,openBrowser:e.browser!==!1,onCode:e=>{process.stdout.write(`\n Open this URL to authorize the CLI:\n ${e.verificationUriComplete??e.verificationUri}\n Or enter code: ${e.userCode}\n\n`)}})}),d.command(`logout`,`Revoke current session and delete local auth`).option(`--json`,``).action(async e=>{let{logoutCommand:t}=await import(`./logout-DvGiNVs9.js`);await t({cliVersion:c,json:e.json})}),d.command(`ai`,`3-mode AI assistant (install / chat / mcp)`).option(`--mode <mode>`,`install | chat | mcp`).option(`--json`,``).action(async e=>{let{aiCommand:t}=await import(`./ai-BIlR3UnJ.js`),n=await t({cliVersion:c,cwd:process.cwd(),mode:e.mode,json:e.json});process.exitCode=n}),d.command(`watch`,`Live TUI dashboard`).option(`--site-id <id>`,`Site ID`).option(`--interval <ms>`,`Poll interval ms`,{default:15e3}).option(`--json`,``).action(async e=>{let{watchCommand:t}=await import(`./watch-CtIJ1ZAz.js`),n=await t({cliVersion:c,siteId:e.siteId,intervalMs:Number(e.interval),json:e.json});process.exitCode=n}),d.command(`events tail`,`Stream live events`).option(`--site-id <id>`,`Site ID`,{default:``}).option(`--filter <expr>`,`Filter expression (e.g. 'type=pageview AND country=US')`).option(`--forward-to <url>`,`POST each event to a webhook with HMAC-SHA256 signature`).option(`--replay-24h`,`Replay the last 24h before going live`).option(`--set-forward-secret <hex>`,`Persist the HMAC secret used by --forward-to`).option(`--json`,``).action(async e=>{let{eventsTailCommand:t}=await import(`./events-tail-C35jGarq.js`),n=await t({cliVersion:c,siteId:e.siteId,json:e.json,filter:e.filter,forwardTo:e.forwardTo,replay24h:e.replay24h,setForwardSecret:e.setForwardSecret});process.exitCode=n}),d.command(`health`,`Run self-diagnostic checks`).option(`--json`,``).action(async e=>{let{healthCommand:t}=await import(`./health-D-nDYCrN.js`),n=await t({cliVersion:c,binaryPath:l,json:e.json});process.exitCode=n}),d.command(`doctor`,`AI-assisted self-healing`).option(`--json`,``).action(async e=>{let{doctorCommand:t}=await import(`./doctor-y7_iOaxP.js`),n=await t({cliVersion:c,binaryPath:l,json:e.json});process.exitCode=n}),d.command(`stats`,`One-shot dashboard summary (scriptable by default)`).option(`--site-id <id>`,`Site ID`).option(`--range <range>`,`Time range: 24h | 7d | 30d`,{default:`24h`}).option(`--watch`,`Auto-refresh every 60s`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{statsCommand:t}=await import(`./stats-CstuCrtH.js`),n=await t({cliVersion:c,siteId:e.siteId,range:e.range,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),d.command(`sources`,`Traffic source breakdown with delta arrows`).option(`--site-id <id>`,`Site ID`).option(`--period <p>`,`Period: 7d | 30d | 90d | 1y`,{default:`30d`}).option(`--compare <c>`,`Comparison window (use "prev" for period-over-period)`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{sourcesCommand:t}=await import(`./sources-BzZK-YOD.js`),n=await t({cliVersion:c,siteId:e.siteId,period:e.period,compare:e.compare,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),d.command(`vitals`,`Core Web Vitals dashboard (LCP / INP / CLS / TTFB / FCP)`).option(`--site-id <id>`,`Site ID`).option(`--url <path>`,`Filter to a single URL`).option(`--device <type>`,`Filter by device: mobile | desktop`).option(`--window <w>`,`Time window: 24h | 7d | 30d | 90d`,{default:`7d`}).option(`--watch`,`Auto-refresh every 5 minutes`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{vitalsCommand:t}=await import(`./vitals-D_r_rBbw.js`),n=await t({cliVersion:c,siteId:e.siteId,url:e.url,device:e.device,window:e.window,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),d.command(`revenue`,`MRR / ARR / transaction series`).option(`--site-id <id>`,`Site ID`).option(`--range <r>`,`Time range: 24h | 7d | 30d | 1y`,{default:`30d`}).option(`--watch`,`Auto-refresh every 5 minutes`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{revenueCommand:t}=await import(`./revenue-39qQFWdR.js`),n=await t({cliVersion:c,siteId:e.siteId,range:e.range,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),d.command(`funnels`,`List available funnels`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{funnelCommand:t}=await import(`./funnel-BCa_5jW3.js`),n=await t({cliVersion:c,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),d.command(`themes`,`List available themes with colored swatches`).option(`--validate <path>`,`Validate a custom theme JSON file`).option(`--json`,`Emit themes JSON to stdout`).action(async e=>{let{themesCommand:t}=await import(`./themes-F-HUBXpr.js`),n=await t({cliVersion:c,validate:e.validate,json:e.json});process.exitCode=n}),d.command(`completions [shell]`,`Emit shell-completion script (bash | zsh | fish | nushell | pwsh)`).option(`--list`,`List supported shells`).action(async(e,t)=>{let{completionsCommand:n}=await import(`./completions-GDtTbG3B.js`),r=await n({shell:e,list:t.list});process.exitCode=r}),d.command(`query [sql]`,`Restricted SQL REPL over the analytics schema (Scale+)`).option(`--site-id <id>`,`Site ID`).option(`--max-rows <n>`,`Cap result row count`,{default:1e3}).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async(e,t)=>{let{queryCommand:n}=await import(`./query-B8PDpxhG.js`),r=await n({cliVersion:c,siteId:t.siteId,sql:e,maxRows:typeof t.maxRows==`string`?Number(t.maxRows):t.maxRows,json:t.json,csv:t.csv,tsv:t.tsv,ndjson:t.ndjson});process.exitCode=r}),d.command(`companies`,`B2B identification feed (Scale+)`).option(`--site-id <id>`,`Site ID`).option(`--window <w>`,`Time window: 24h | 7d | 30d | 90d`,{default:`24h`}).option(`--limit <n>`,`Max rows`,{default:100}).option(`--new-only`,`Show only newly identified companies (first-seen in last hour)`).option(`--watch`,`Auto-refresh every 30s`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{companiesCommand:t}=await import(`./companies-Z4LkcGcD.js`),n=await t({cliVersion:c,siteId:e.siteId,window:e.window,limit:typeof e.limit==`string`?Number(e.limit):e.limit,newOnly:e.newOnly,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),d.command(`projects`,`List your tracked projects`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{projectsCommand:t}=await import(`./projects-BCK7Jspy.js`),n=await t({cliVersion:c,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),d.command(`deploys`,`Recent GitHub commits overlaid on charts (Wave 4 W5)`).option(`--site-id <id>`,`Site ID`).option(`--branch <name>`,`Filter to a single branch (e.g. main, develop)`).option(`--since <iso>`,`Only commits after this ISO timestamp`).option(`--limit <n>`,`Max rows`,{default:50}).option(`--connect`,`Print the GitHub-integration deep link in app.zenovay.com`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{deploysCommand:t}=await import(`./deploys-28qQkagZ.js`),n=await t({cliVersion:c,siteId:e.siteId,branch:e.branch,since:e.since,limit:typeof e.limit==`string`?Number(e.limit):e.limit,connect:e.connect,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),d.command(`webhooks forward`,`Forward webhook events to a local URL (stripe-listen-style; W3)`).option(`--to <url>`,`Local URL to POST events to (e.g. localhost:3000/webhook)`).option(`--site-id <id>`,`Site ID`).option(`--sign`,`HMAC-sign each forwarded request with X-Zenovay-Signature`).option(`--secret <hex>`,`HMAC secret (auto-derived from tunnel key if --sign without --secret)`).option(`--max-retries <n>`,`Per-request retry count`,{default:3}).action(async e=>{let{webhooksForwardCommand:t}=await import(`./webhooks-forward-QnE7MdSy.js`),n=await t({cliVersion:c,to:e.to,siteId:e.siteId,sign:e.sign,secret:e.secret,maxRetries:typeof e.maxRetries==`string`?Number(e.maxRetries):e.maxRetries});process.exitCode=n}),d.command(`errors`,`Recent error snapshot (Wave 2 lead-in; SSE coming in V2.1)`).option(`--site-id <id>`,`Site ID`).option(`--window <w>`,`Time window: 24h | 7d | 30d | 90d`,{default:`24h`}).option(`--limit <n>`,`Max errors to fetch`,{default:100}).option(`--search <q>`,`Filter by class or message substring`).option(`--watch`,`Auto-refresh every 30s`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{errorsCommand:t}=await import(`./errors-CUUuLToC.js`),n=await t({cliVersion:c,siteId:e.siteId,window:e.window,limit:typeof e.limit==`string`?Number(e.limit):e.limit,search:e.search,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),d.command(`funnel <id>`,`Funnel drop-off chart for a specific funnel`).option(`--site-id <id>`,`Site ID`).option(`--window <w>`,`Time window: 7d | 30d`,{default:`30d`}).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async(e,t)=>{let{funnelCommand:n}=await import(`./funnel-BCa_5jW3.js`),r=await n({cliVersion:c,siteId:t.siteId,funnelId:e,window:t.window,json:t.json,csv:t.csv,tsv:t.tsv,ndjson:t.ndjson});process.exitCode=r}),d.command(`update`,`Manually install the latest version`).option(`--check`,`Don't install — just print latest`).option(`--force-downgrade`,`Allow downgrading to an older version`).option(`--no-update-check`,`Disable auto-update for this invocation`).option(`--json`,``).action(async e=>{let{updateCommand:t}=await import(`./update-2SafBiSk.js`);await t({cliVersion:c,binaryPath:l,check:e.check,forceDowngrade:e.forceDowngrade,json:e.json})}),d.parse(process.argv,{run:!1}),(async()=>{u();try{await d.runMatchedCommand()}catch(e){process.stderr.write(`\n✗ ${e.message}\n`),process.exit(1)}})();
|
|
2
|
+
import{cac as e}from"cac";import{fork as t}from"node:child_process";import n from"node:path";import{fileURLToPath as r}from"node:url";import{readFileSync as i}from"node:fs";const a=n.dirname(r(import.meta.url)),o=n.join(a,`..`,`package.json`),s=JSON.parse(i(o,`utf8`)),c=s.version,l=process.argv[0]??`zenovay`;function u(){if(!(process.env.ZENOVAY_NO_UPDATE_CHECK===`1`||process.env.CI===`true`))try{let e=n.join(a,`lib`,`update`,`worker.js`),r=t(e,[],{detached:!0,stdio:`ignore`});r.unref()}catch{}}const d=e(`zenovay`);d.version(c),d.help(),d.command(`init`,`AI install wizard — add Zenovay tracking to your codebase`).option(`--json`,`Emit NDJSON events to stdout`).option(`--yes`,`Auto-approve all diffs (for CI)`).option(`--skip-mcp`,`Skip MCP client install`).option(`--skip-verify`,`Skip first-event verification`).action(async e=>{let{initCommand:t}=await import(`./init-qzmy4rIN.js`),n=await t({cliVersion:c,cwd:process.cwd(),json:e.json,yes:e.yes,skipMcp:e.skipMcp,skipVerify:e.skipVerify});process.exitCode=n}),d.command(`login`,`Authenticate via OAuth device flow`).option(`--json`,`Emit NDJSON events`).option(`--no-browser`,`Skip opening the browser automatically`).action(async e=>{let{loginCommand:t}=await import(`./login-D4kNEDVO.js`);await t({cliVersion:c,json:e.json,openBrowser:e.browser!==!1,onCode:e=>{process.stdout.write(`\n Open this URL to authorize the CLI:\n ${e.verificationUriComplete??e.verificationUri}\n Or enter code: ${e.userCode}\n\n`)}})}),d.command(`logout`,`Revoke current session and delete local auth`).option(`--json`,``).action(async e=>{let{logoutCommand:t}=await import(`./logout-DvGiNVs9.js`);await t({cliVersion:c,json:e.json})}),d.command(`ai`,`3-mode AI assistant (install / chat / mcp)`).option(`--mode <mode>`,`install | chat | mcp`).option(`--json`,``).action(async e=>{let{aiCommand:t}=await import(`./ai-BkI11rV0.js`),n=await t({cliVersion:c,cwd:process.cwd(),mode:e.mode,json:e.json});process.exitCode=n}),d.command(`watch`,`Live TUI dashboard`).option(`--site-id <id>`,`Site ID`).option(`--interval <ms>`,`Poll interval ms`,{default:15e3}).option(`--json`,``).action(async e=>{let{watchCommand:t}=await import(`./watch-CtIJ1ZAz.js`),n=await t({cliVersion:c,siteId:e.siteId,intervalMs:Number(e.interval),json:e.json});process.exitCode=n}),d.command(`events tail`,`Stream live events`).option(`--site-id <id>`,`Site ID`,{default:``}).option(`--filter <expr>`,`Filter expression (e.g. 'type=pageview AND country=US')`).option(`--forward-to <url>`,`POST each event to a webhook with HMAC-SHA256 signature`).option(`--replay-24h`,`Replay the last 24h before going live`).option(`--set-forward-secret <hex>`,`Persist the HMAC secret used by --forward-to`).option(`--json`,``).action(async e=>{let{eventsTailCommand:t}=await import(`./events-tail-C35jGarq.js`),n=await t({cliVersion:c,siteId:e.siteId,json:e.json,filter:e.filter,forwardTo:e.forwardTo,replay24h:e.replay24h,setForwardSecret:e.setForwardSecret});process.exitCode=n}),d.command(`health`,`Run self-diagnostic checks`).option(`--json`,``).action(async e=>{let{healthCommand:t}=await import(`./health-D-nDYCrN.js`),n=await t({cliVersion:c,binaryPath:l,json:e.json});process.exitCode=n}),d.command(`doctor`,`AI-assisted self-healing`).option(`--json`,``).action(async e=>{let{doctorCommand:t}=await import(`./doctor-y7_iOaxP.js`),n=await t({cliVersion:c,binaryPath:l,json:e.json});process.exitCode=n}),d.command(`stats`,`One-shot dashboard summary (scriptable by default)`).option(`--site-id <id>`,`Site ID`).option(`--range <range>`,`Time range: 24h | 7d | 30d`,{default:`24h`}).option(`--watch`,`Auto-refresh every 60s`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{statsCommand:t}=await import(`./stats-CstuCrtH.js`),n=await t({cliVersion:c,siteId:e.siteId,range:e.range,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),d.command(`sources`,`Traffic source breakdown with delta arrows`).option(`--site-id <id>`,`Site ID`).option(`--period <p>`,`Period: 7d | 30d | 90d | 1y`,{default:`30d`}).option(`--compare <c>`,`Comparison window (use "prev" for period-over-period)`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{sourcesCommand:t}=await import(`./sources-BzZK-YOD.js`),n=await t({cliVersion:c,siteId:e.siteId,period:e.period,compare:e.compare,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),d.command(`vitals`,`Core Web Vitals dashboard (LCP / INP / CLS / TTFB / FCP)`).option(`--site-id <id>`,`Site ID`).option(`--url <path>`,`Filter to a single URL`).option(`--device <type>`,`Filter by device: mobile | desktop`).option(`--window <w>`,`Time window: 24h | 7d | 30d | 90d`,{default:`7d`}).option(`--watch`,`Auto-refresh every 5 minutes`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{vitalsCommand:t}=await import(`./vitals-D_r_rBbw.js`),n=await t({cliVersion:c,siteId:e.siteId,url:e.url,device:e.device,window:e.window,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),d.command(`revenue`,`MRR / ARR / transaction series`).option(`--site-id <id>`,`Site ID`).option(`--range <r>`,`Time range: 24h | 7d | 30d | 1y`,{default:`30d`}).option(`--watch`,`Auto-refresh every 5 minutes`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{revenueCommand:t}=await import(`./revenue-39qQFWdR.js`),n=await t({cliVersion:c,siteId:e.siteId,range:e.range,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),d.command(`funnels`,`List available funnels`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{funnelCommand:t}=await import(`./funnel-BCa_5jW3.js`),n=await t({cliVersion:c,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),d.command(`themes`,`List available themes with colored swatches`).option(`--validate <path>`,`Validate a custom theme JSON file`).option(`--json`,`Emit themes JSON to stdout`).action(async e=>{let{themesCommand:t}=await import(`./themes-F-HUBXpr.js`),n=await t({cliVersion:c,validate:e.validate,json:e.json});process.exitCode=n}),d.command(`completions [shell]`,`Emit shell-completion script (bash | zsh | fish | nushell | pwsh)`).option(`--list`,`List supported shells`).action(async(e,t)=>{let{completionsCommand:n}=await import(`./completions-GDtTbG3B.js`),r=await n({shell:e,list:t.list});process.exitCode=r}),d.command(`query [sql]`,`Restricted SQL REPL over the analytics schema (Scale+)`).option(`--site-id <id>`,`Site ID`).option(`--max-rows <n>`,`Cap result row count`,{default:1e3}).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async(e,t)=>{let{queryCommand:n}=await import(`./query-B8PDpxhG.js`),r=await n({cliVersion:c,siteId:t.siteId,sql:e,maxRows:typeof t.maxRows==`string`?Number(t.maxRows):t.maxRows,json:t.json,csv:t.csv,tsv:t.tsv,ndjson:t.ndjson});process.exitCode=r}),d.command(`companies`,`B2B identification feed (Scale+)`).option(`--site-id <id>`,`Site ID`).option(`--window <w>`,`Time window: 24h | 7d | 30d | 90d`,{default:`24h`}).option(`--limit <n>`,`Max rows`,{default:100}).option(`--new-only`,`Show only newly identified companies (first-seen in last hour)`).option(`--watch`,`Auto-refresh every 30s`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{companiesCommand:t}=await import(`./companies-Z4LkcGcD.js`),n=await t({cliVersion:c,siteId:e.siteId,window:e.window,limit:typeof e.limit==`string`?Number(e.limit):e.limit,newOnly:e.newOnly,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),d.command(`projects`,`List your tracked projects`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{projectsCommand:t}=await import(`./projects-BCK7Jspy.js`),n=await t({cliVersion:c,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),d.command(`deploys`,`Recent GitHub commits overlaid on charts (Wave 4 W5)`).option(`--site-id <id>`,`Site ID`).option(`--branch <name>`,`Filter to a single branch (e.g. main, develop)`).option(`--since <iso>`,`Only commits after this ISO timestamp`).option(`--limit <n>`,`Max rows`,{default:50}).option(`--connect`,`Print the GitHub-integration deep link in app.zenovay.com`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{deploysCommand:t}=await import(`./deploys-28qQkagZ.js`),n=await t({cliVersion:c,siteId:e.siteId,branch:e.branch,since:e.since,limit:typeof e.limit==`string`?Number(e.limit):e.limit,connect:e.connect,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),d.command(`webhooks forward`,`Forward webhook events to a local URL (stripe-listen-style; W3)`).option(`--to <url>`,`Local URL to POST events to (e.g. localhost:3000/webhook)`).option(`--site-id <id>`,`Site ID`).option(`--sign`,`HMAC-sign each forwarded request with X-Zenovay-Signature`).option(`--secret <hex>`,`HMAC secret (auto-derived from tunnel key if --sign without --secret)`).option(`--max-retries <n>`,`Per-request retry count`,{default:3}).action(async e=>{let{webhooksForwardCommand:t}=await import(`./webhooks-forward-QnE7MdSy.js`),n=await t({cliVersion:c,to:e.to,siteId:e.siteId,sign:e.sign,secret:e.secret,maxRetries:typeof e.maxRetries==`string`?Number(e.maxRetries):e.maxRetries});process.exitCode=n}),d.command(`errors`,`Recent error snapshot (Wave 2 lead-in; SSE coming in V2.1)`).option(`--site-id <id>`,`Site ID`).option(`--window <w>`,`Time window: 24h | 7d | 30d | 90d`,{default:`24h`}).option(`--limit <n>`,`Max errors to fetch`,{default:100}).option(`--search <q>`,`Filter by class or message substring`).option(`--watch`,`Auto-refresh every 30s`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{errorsCommand:t}=await import(`./errors-CUUuLToC.js`),n=await t({cliVersion:c,siteId:e.siteId,window:e.window,limit:typeof e.limit==`string`?Number(e.limit):e.limit,search:e.search,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),d.command(`funnel <id>`,`Funnel drop-off chart for a specific funnel`).option(`--site-id <id>`,`Site ID`).option(`--window <w>`,`Time window: 7d | 30d`,{default:`30d`}).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async(e,t)=>{let{funnelCommand:n}=await import(`./funnel-BCa_5jW3.js`),r=await n({cliVersion:c,siteId:t.siteId,funnelId:e,window:t.window,json:t.json,csv:t.csv,tsv:t.tsv,ndjson:t.ndjson});process.exitCode=r}),d.command(`update`,`Manually install the latest version`).option(`--check`,`Don't install — just print latest`).option(`--force-downgrade`,`Allow downgrading to an older version`).option(`--no-update-check`,`Disable auto-update for this invocation`).option(`--json`,``).action(async e=>{let{updateCommand:t}=await import(`./update-2SafBiSk.js`);await t({cliVersion:c,binaryPath:l,check:e.check,forceDowngrade:e.forceDowngrade,json:e.json})}),d.parse(process.argv,{run:!1}),(async()=>{u();try{await d.runMatchedCommand()}catch(e){process.stderr.write(`\n✗ ${e.message}\n`),process.exit(1)}})();
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import{readConfig as e}from"./config-ZTGpKEWg.js";import{ApiClient as t,readToken as n}from"./api-BhdaCghp.js";import{parseSseStream as r}from"./client-DZ4Awt8u.js";import{emit as i,isHeadless as a}from"./emit-0WJ_OGeT.js";import{loginCommand as o}from"./login-DHLIZV8C.js";import{Panel as s}from"./panel-DglZ755S.js";import{Banner as c,BrandGradient as l,Keybar as u}from"./keybar-D2OI-8rx.js";import{Select as d}from"./prompt-hjzdzlyj.js";import{spark as f}from"./sparkline-CR_bzxwB.js";import p from"node:path";import{promises as m}from"node:fs";import{Box as h,Text as g,render as _,useApp as v,useInput as y}from"ink";import b,{useEffect as x,useRef as S,useState as C}from"react";import w from"node:os";import{z as T}from"zod";import{globby as E}from"globby";import D from"ink-spinner";import O from"node:crypto";import{ulid as k}from"ulid";import{applyPatch as ee}from"diff";const A=[`@zenovay/tracker`,`@zenovay/next`,`@zenovay/nuxt`,`@zenovay/svelte`,`@zenovay/astro`,`@zenovay/remix`,`@zenovay/node`],j=[`zenovay.config.ts`,`zenovay.config.js`,`zenovay.config.mjs`,`zenovay.config.json`],M=/<script[^>]*src\s*=\s*["']https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+["'][^>]*>\s*<\/script>/gi,N=/data-id\s*=\s*["'](ZV_[A-Za-z0-9]+)["']/i,P=/data-zenovay-site\s*=\s*["']([^"']+)["']/i,F=[{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 I(e,t){let n={zenovayInstalled:!1,correctTrackingCode:!1,foundTrackingCodes:[],zenovayFiles:[],competitors:[],summary:``,recommendation:`fresh-install`};try{let t=await m.readFile(p.join(e,`package.json`),`utf8`),r=JSON.parse(t),i={...r.dependencies,...r.devDependencies};for(let e of A)if(e in i){n.zenovayInstalled=!0,n.packageMarker=e;break}}catch{}for(let t of j)try{await m.access(p.join(e,t)),n.zenovayInstalled=!0,n.configFile=t;break}catch{}let r=await E([`**/*.{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 m.readFile(t,`utf8`)}catch{continue}let o=p.relative(e,t),s=r.match(M);if(s&&s.length>0){n.zenovayInstalled=!0;let e=s[0].slice(0,200),t=e.match(N)??e.match(P),r=t?.[1]??null;r&&a.add(r),n.zenovayFiles.push({file:o,currentTrackingCode:r,scriptTagCount:s.length,matchSample:e})}for(let e of F)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=L(n,t),n}function L(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 te(e){let t=await I(e,``);return{installed:t.zenovayInstalled,reasons:t.summary?[t.summary]:[],packageMarker:t.packageMarker,configFile:t.configFile,scriptFile:t.zenovayFiles[0]?.file}}const ne=[{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 re(e){let t=e;for(let e of ne){let n=new RegExp(e.regex.source,e.regex.flags);t=t.replace(n,`[REDACTED:${e.name}]`)}return t}const ie=[/^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)$/],ae=[/(^|\/)\.env($|\.(?!example$)[^/]+$)/,/(^|\/)\.git(\/|$)/,/(^|\/)node_modules\//,/(^|\/)\.ssh\//,/(^|\/)\.aws\//,/\.pem$/,/\.key$/,/(^|\/)id_rsa($|\.)/,/(^|\/)\.npmrc$/,/(^|\/)credentials(\.|$)/],R=256*1024,z=50,B=20,V=40;var H=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`SandboxError`}};const U=/<script[^>]*src\s*=\s*["']https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+["'][^>]*>\s*<\/script>/i,oe=[{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 W=class{sessionId;cwd;cwdReal;undoRoot;readCount=0;writeCount=0;roundCount=0;writtenPathsSet=new Set;constructor(e){this.sessionId=e.sessionId??k(),this.cwd=e.cwd,this.cwdReal=m.realpath(e.cwd),this.undoRoot=e.undoRoot??p.join(w.homedir(),`.zenovay`,`undo`)}incrementRound(){if(this.roundCount++,this.roundCount>V)throw new H(`round-cap`,`Tool-call recursion cap (${V}) 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 H(`escape`,`Path must be a non-empty string.`);if(e.includes(`\0`))throw new H(`escape`,`Null byte in path.`);if(/^\\\\[?.]\\/.test(e)||/^\\\\[A-Za-z0-9]/.test(e))throw new H(`escape`,`Windows special path prefix: ${e}`);if(/%/.test(e))try{let t=decodeURIComponent(e);if(/%[0-9A-Fa-f]{2}/.test(t))throw new H(`escape`,`Double-encoded path: ${e}`);e=t}catch(t){throw t instanceof H?t:new H(`escape`,`Malformed percent-encoding: ${e}`)}if(e.includes(`\0`))throw new H(`escape`,`Null byte in decoded path.`);if(e.includes(`\\`))throw new H(`escape`,`Backslash in path (Windows-style separator not accepted): ${e}`);let n=await this.cwdReal,r=p.isAbsolute(e)?e:p.join(n,e),i=p.normalize(r),a=i;try{a=await m.realpath(i)}catch(e){if(e.code!==`ENOENT`)throw new H(`escape`,`realpath failed: ${e.message}`);let t=p.dirname(i);try{let e=await m.realpath(t);a=p.join(e,p.basename(i))}catch{}}if(!this.isWithin(a,n))throw new H(`escape`,`Path escapes cwd: ${e}`);let o=p.relative(n,a);for(let e of ae)if(e.test(o)){if(t===`read`&&/(^|\/)node_modules\//.test(o))continue;throw new H(`blocklisted`,`Path is on the hard blocklist: ${o}`)}if(t===`write`){let e=ie.some(e=>e.test(o));if(!e&&!/^\.env(\.local)?$/.test(o)&&!/^\.claude\//.test(o)&&!/^\.cursor\//.test(o))throw new H(`not-allowlisted`,`Write path not on allowlist: ${o}`)}return a}isWithin(e,t){let n=p.relative(t,e);return!n.startsWith(`..`)&&!p.isAbsolute(n)}async safeRead(e){if(this.readCount>=z)throw new H(`read-cap`,`Read cap (${z}) reached.`);let t=await this.resolveForRead(e),n=await m.stat(t);if(n.size>R)throw new H(`too-large`,`File exceeds ${R}B: ${e} (${n.size}B)`);let r=await m.readFile(t),i=r.subarray(0,Math.min(r.length,8192));if(i.includes(0))throw new H(`binary-rejected`,`Binary content in ${e}.`);return this.readCount++,r.toString(`utf8`)}async safeWrite(e,t){if(this.writeCount>=B)throw new H(`write-cap`,`Write cap (${B}) reached.`);if(t.length>R)throw new H(`too-large`,`Write exceeds ${R}B: ${e}`);let n=await this.resolveForWrite(e),r=await m.readFile(n,`utf8`).catch(e=>{if(e.code===`ENOENT`)return null;throw e});if(r!==null){if(U.test(r)&&!U.test(t))throw new H(`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 oe)if(i.test(r)&&!i.test(t))throw new H(`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 m.mkdir(p.dirname(n),{recursive:!0}),await m.writeFile(n,t,`utf8`),this.writeCount++;let a=await this.cwdReal;return this.writtenPathsSet.add(p.relative(a,n)),{backupPath:i}}async journalBackup(e){let t=await m.readFile(e).catch(e=>{if(e.code===`ENOENT`)return null;throw e}),n=p.join(this.undoRoot,this.sessionId);await m.mkdir(n,{recursive:!0,mode:448});let r=O.createHash(`sha256`).update(e).digest(`hex`).slice(0,16),i=p.join(n,`${r}.bak`),a=p.join(n,`manifest.jsonl`);t&&await m.writeFile(i,t,{mode:384});let o=JSON.stringify({abs:e,backupPath:t?i:null,ts:Date.now()});return await m.appendFile(a,o+`
|
|
2
|
+
`,{mode:384}),t?i:null}static wrapForModel(e,t){let n=O.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 re(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
|
+
defer
|
|
4
|
+
data-id="${n}"
|
|
5
|
+
data-allow-localhost="true"
|
|
6
|
+
src="https://api.zenovay.com/z.js"
|
|
7
|
+
strategy="afterInteractive"
|
|
8
|
+
/>
|
|
9
|
+
{children}`,description:`Add the Zenovay tracker <Script> next to children in the root layout.`}]}const ge={id:`next-app-router`,displayName:`Next.js (App Router)`,detect:me,files:[{path:`app/layout.tsx`,kind:`mutate`,required:!0}],envVarName:`NEXT_PUBLIC_ZENOVAY_SITE`,buildSnippets:he},_e=[`pages/_app.tsx`,`pages/_app.ts`,`pages/_app.jsx`,`pages/_app.js`,`src/pages/_app.tsx`,`src/pages/_app.ts`,`src/pages/_app.jsx`,`src/pages/_app.js`];async function ve(e){for(let t of _e)if(await e.exists(t))return t;return null}async function ye(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 be(e){let t=await ye(e);if(!t)return{matched:!1,confidence:0,reason:"package.json does not list `next` as a dependency."};let n=await ve(e);if(n)return{matched:!0,confidence:.9,reason:`Detected Next.js Pages Router via \`${n}\`.`};let r=await e.exists(`app`),i=await e.glob(`pages/**/*.{tsx,ts,jsx,js}`);return i.length>0&&!r?{matched:!0,confidence:.7,reason:"Found `pages/` directory with route files but no `_app` — will create one."}:{matched:!1,confidence:.2,reason:`Next.js detected, but no pages-router entry point found.`}}function xe(e){let t=`pages/_app.tsx`,n=e.trackingCode??e.siteId??``,r=`import type { AppProps } from 'next/app';
|
|
10
|
+
import Script from 'next/script';
|
|
11
|
+
|
|
12
|
+
export default function App({ Component, pageProps }: AppProps) {
|
|
13
|
+
return (
|
|
14
|
+
<>
|
|
15
|
+
<Script
|
|
16
|
+
defer
|
|
17
|
+
data-id="${n}"
|
|
18
|
+
data-allow-localhost="true"
|
|
19
|
+
src="https://api.zenovay.com/z.js"
|
|
20
|
+
strategy="afterInteractive"
|
|
21
|
+
/>
|
|
22
|
+
<Component {...pageProps} />
|
|
23
|
+
</>
|
|
24
|
+
);
|
|
25
|
+
}
|
|
26
|
+
`;return[{targetPath:t,anchorKind:`after-imports`,code:`import Script from 'next/script';`,description:"Import next/script in `_app`."},{targetPath:t,anchorKind:`wrap-children`,code:`<><Script defer data-id="${n}" data-allow-localhost="true" src="https://api.zenovay.com/z.js" strategy="afterInteractive" /><Component {...pageProps} /></>`,description:`Render the Zenovay tracker alongside the page component.`},{targetPath:t,anchorKind:`replace-file`,code:r,description:"Full replacement when `_app` does not exist yet."}]}const Se={id:`next-pages-router`,displayName:`Next.js (Pages Router)`,detect:be,files:[{path:`pages/_app.tsx`,kind:`mutate`,required:!0}],envVarName:`NEXT_PUBLIC_ZENOVAY_SITE`,buildSnippets:xe},Ce=T.object({modules:T.array(T.string()).optional(),runtimeConfig:T.object({public:T.record(T.string(),T.unknown()).optional()}).optional()}).passthrough();async function we(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json found.`};try{let e=JSON.parse(t),n=!!(e.dependencies?.nuxt??e.devDependencies?.nuxt??e.dependencies?.nuxt3??e.devDependencies?.nuxt3);if(n)return{matched:!0,confidence:.95,reason:"Detected Nuxt via `nuxt` / `nuxt3` dependency."}}catch{}let n=await e.exists(`nuxt.config.ts`)||await e.exists(`nuxt.config.js`)||await e.exists(`nuxt.config.mjs`);return n?{matched:!0,confidence:.6,reason:"Found `nuxt.config.*` but no explicit dependency listing."}:{matched:!1,confidence:0,reason:`No Nuxt dependency or config detected.`}}function Te(e){let t=e.trackingCode??e.siteId??``,n=` app: {
|
|
27
|
+
head: {
|
|
28
|
+
script: [
|
|
29
|
+
{
|
|
30
|
+
defer: true,
|
|
31
|
+
src: 'https://api.zenovay.com/z.js',
|
|
32
|
+
'data-id': '${t}',
|
|
33
|
+
'data-allow-localhost': 'true',
|
|
34
|
+
},
|
|
35
|
+
],
|
|
36
|
+
},
|
|
37
|
+
},`;return[{targetPath:`nuxt.config.ts`,anchorKind:`head-tag`,code:n,description:"Add the Zenovay tracker to Nuxt's `app.head.script` so every page loads it."}]}const Ee={id:`nuxt`,displayName:`Nuxt`,detect:we,files:[{path:`nuxt.config.ts`,kind:`mutate`,required:!0}],envVarName:`NUXT_PUBLIC_ZENOVAY_SITE`,buildSnippets:Te},De=[`index.html`,`public/index.html`,`dist/index.html`];async function Oe(e){for(let t of De)if(await e.exists(t))return{matched:!0,confidence:.5,reason:`Detected plain HTML project via \`${t}\`.`};let t=await e.glob(`**/*.html`);return t.length>0?{matched:!0,confidence:.3,reason:`Found ${t.length} HTML file(s); plain-HTML adapter is usable as fallback.`}:{matched:!1,confidence:0,reason:`No HTML files found in the project.`}}function ke(e){let t=e.siteId??``,n=`<script defer\n data-id="${t}"\n data-allow-localhost="true"\n src="https://api.zenovay.com/z.js">\n</script>`;return[{targetPath:`index.html`,anchorKind:`head-tag`,code:n,description:`Inject the Zenovay tracker inside <head>. Repeat for every HTML file that contains a <head>.`}]}const Ae={id:`plain-html`,displayName:`Plain HTML`,detect:Oe,files:[{path:`index.html`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:ke};async function je(e){let t=await e.readFile(`package.json`);if(t)try{let e=JSON.parse(t),n={...e.dependencies??{},...e.devDependencies??{}},r=Object.keys(n).some(e=>e.startsWith(`@remix-run/`));if(r)return{matched:!0,confidence:.95,reason:"Detected Remix via `@remix-run/*` dependencies."}}catch{}return await e.exists(`remix.config.js`)||await e.exists(`remix.config.ts`)?{matched:!0,confidence:.8,reason:"Detected Remix via `remix.config.*`."}:{matched:!1,confidence:0,reason:`No Remix dependency or config detected.`}}function Me(e){let t=e.trackingCode??e.siteId??``;return[{targetPath:`app/root.tsx`,anchorKind:`head-tag`,code:`<script defer data-id="${t}" data-allow-localhost="true" src="https://api.zenovay.com/z.js"></script>`,description:`Inline the Zenovay tracker <script> inside the document <head>.`}]}const Ne={id:`remix`,displayName:`Remix`,detect:je,files:[{path:`app/root.tsx`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:Me};async function Pe(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json found.`};try{let e=JSON.parse(t),n=!!(e.dependencies?.[`@sveltejs/kit`]??e.devDependencies?.[`@sveltejs/kit`]);return n?{matched:!0,confidence:.95,reason:"Detected SvelteKit via `@sveltejs/kit` dependency."}:{matched:!1,confidence:0,reason:"`@sveltejs/kit` not in dependencies."}}catch{return{matched:!1,confidence:0,reason:`package.json is not valid JSON.`}}}function Fe(e){let t=e.trackingCode??e.siteId??``,n=`<svelte:head>
|
|
38
|
+
<script defer data-id="${t}" data-allow-localhost="true" src="https://api.zenovay.com/z.js"></script>
|
|
39
|
+
</svelte:head>
|
|
40
|
+
|
|
41
|
+
<slot />
|
|
42
|
+
`;return[{targetPath:`src/routes/+layout.svelte`,anchorKind:`replace-file`,code:n,description:`Root layout that loads the Zenovay tracker in every route via <svelte:head>.`}]}const Ie={id:`sveltekit`,displayName:`SvelteKit`,detect:Pe,files:[{path:`src/routes/+layout.svelte`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:Fe},Le=[ge,Se,Ee,Ie,ue,Ne,Ae];async function G(e){let t=[];for(let n of Le){let r=await n.detect(e);t.push({adapter:n,result:r})}let n=[...t].sort((e,t)=>t.result.confidence-e.result.confidence),r=n[0],i=r&&r.result.matched?r.adapter:null;return{adapter:i,ranked:n}}function K(e){let t=t=>p.resolve(e,t);return{cwd:e,async readFile(e){try{return await m.readFile(t(e),`utf8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`EISDIR`)return null;throw e}},async exists(e){try{return await m.access(t(e)),!0}catch{return!1}},async glob(t){return E(t,{cwd:e,dot:!1,gitignore:!0,onlyFiles:!0,followSymbolicLinks:!1})}}}async function q(e,t){let n=K(e),{adapter:r,ranked:i}=await G(n),a=i[0];return r&&a&&a.result.confidence>=.7?r:t?t.pickInteractively(i):r}function Re(e,t){let n=/[\s"'#=]/.test(t)||t===``,r=n?`"${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:t;return`${e}=${r}`}function ze(e){let t=new Set;for(let n of e.split(/\r?\n/)){let e=n.trim();if(!e||e.startsWith(`#`))continue;let r=e.indexOf(`=`);if(r<=0)continue;let i=e.slice(0,r).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(i)&&t.add(i)}return t}async function J(e,t,n={}){let r=n.filename??`.env.local`,i=p.resolve(e,r),a=``,o=!0;try{a=await m.readFile(i,`utf8`)}catch(e){if(e.code===`ENOENT`)o=!1;else throw e}let s=o?ze(a):new Set,c=[],l=[],u=[];for(let[e,n]of Object.entries(t)){if(s.has(e)){l.push(e);continue}u.push(Re(e,n)),c.push(e)}if(c.length===0)return{created:!1,existing:o,addedKeys:c,skippedKeys:l};let d=`# Added by Zenovay CLI`,f;if(o){let e=a.length>0&&!a.endsWith(`
|
|
43
|
+
`);f=a+(e?`
|
|
44
|
+
`:``)+`
|
|
45
|
+
`+d+`
|
|
46
|
+
`+u.join(`
|
|
47
|
+
`)+`
|
|
48
|
+
`}else f=d+`
|
|
49
|
+
`+u.join(`
|
|
50
|
+
`)+`
|
|
51
|
+
`;if(o)await m.writeFile(i,f,`utf8`);else{let e=await m.open(i,`w`,384);try{await e.writeFile(f,`utf8`)}finally{await e.close()}}return{created:!o,existing:o,addedKeys:c,skippedKeys:l}}const Be=`https://api.zenovay.com/mcp`,Ve=T.object({url:T.string().url(),headers:T.record(T.string(),T.string()).optional()}),He=T.object({mcpServers:T.record(T.string(),Ve).optional()}).passthrough();function Ue(e){return e.HOME??e.USERPROFILE??w.homedir()}function We(e){return e.APPDATA??null}function Ge(e,t){let n=Ue(t),r=We(t),i=[];return i.push({id:`cursor`,displayName:`Cursor`,configPath:p.join(n,`.cursor`,`mcp.json`)}),e===`win32`&&r&&i.push({id:`cursor`,displayName:`Cursor (AppData)`,configPath:p.join(r,`Cursor`,`User`,`globalStorage`,`cursor.mcp`,`mcp.json`)}),e===`darwin`?i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:p.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`)}):e===`win32`&&r?i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:p.join(r,`Claude`,`claude_desktop_config.json`)}):i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:p.join(n,`.config`,`Claude`,`claude_desktop_config.json`)}),i.push({id:`vscode`,displayName:`VS Code`,configPath:p.join(n,`.vscode`,`mcp.json`)}),i}async function Ke(e){try{return await m.access(e),!0}catch{return!1}}async function qe(e){try{let t=await m.readFile(e,`utf8`);if(t.trim().length===0)return{};let n=JSON.parse(t),r=He.safeParse(n);return r.success?r.data:n&&typeof n==`object`?n:{}}catch{return{}}}function Je(e){return{url:Be,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=Je(e.accessToken);for(let e of Ge(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 Ke(e.configPath);if(!t){a.push(e.displayName);continue}let n=await qe(e.configPath),r=`${e.configPath}.bak`;await m.copyFile(e.configPath,r);let o={...n,mcpServers:{...n.mcpServers??{},zenovay:c}};await m.mkdir(p.dirname(e.configPath),{recursive:!0}),await m.writeFile(e.configPath,JSON.stringify(o,null,2)+`
|
|
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 Ye(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 Xe=T.object({path:T.string().min(1)}),Ze=T.object({path:T.string().min(1),content:T.string(),reason:T.string().min(1)}),Qe=T.object({path:T.string().min(1),patch:T.string().min(1),reason:T.string().min(1)}),$e=T.object({}),et=T.object({question:T.string().min(1),choices:T.array(T.string()).optional()});async function tt(e,t){let n=Xe.safeParse(t);if(!n.success)return{ok:!1,content:null,error:`invalid_args`};try{let t=await e.safeRead(n.data.path),r=W.scrubSecrets(t);return{ok:!0,content:W.wrapForModel(n.data.path,r)}}catch(e){return{ok:!1,content:null,error:e.message}}}async function nt(e,t,n){let r=Ze.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 rt(e,t,n){let r=Qe.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=ee(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.`}:nt(e,{path:i,content:c,reason:o},n)}async function it(e){try{let t=K(e),{adapter:n,ranked:r}=await G(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 at(e,t){let n=et.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 ot(e){let{api:t,sandbox:n,approval:i,prompter:a,handlers:o}=e,s=[...e.initialMessages],c=``,l=0;for(;l<V;){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 r(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 st(e.name,e.arguments,{sandbox:n,cwd:n.cwd,approval:i,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 st(e,t,n){try{switch(e){case`read_file`:return await tt(n.sandbox,t);case`write_file`:return await nt(n.sandbox,t,n.approval);case`patch_file`:return await rt(n.sandbox,t,n.approval);case`detect_framework`:return await it(n.cwd);case`ask_user`:return await at(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}`}}}function ct(){let e=[12,15,18,22,28,35,41,50,58,64,72,78],t=f(e,24);return[` ↑`,` ${t}`,` └────────────────────────`,` May Jun Jul Aug Sep`]}function lt(){return[` Landing page ████████████████████ 100%`,` ↓ -28%`,` Pricing ██████████████░░░░░░ 72%`,` ↓ -50%`,` Checkout ███████░░░░░░░░░░░░░ 36%`,` ↓ -64%`,` Purchased ███░░░░░░░░░░░░░░░░░ 13%`]}function ut(){return[` ▇▇▇▇▇▇▇▇▇▎ 89 Sarah K. /pricing 🇺🇸`,` ▇▇▇▇▇▇░░░░ 61 anon /docs 🇩🇪`,` ▇▇▇░░░░░░░ 34 anon /changelog 🇯🇵`]}function dt(){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:ct},{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:lt},{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:ut},{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:dt},{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.`]}],ft=8e3,pt=({width:e,height:t})=>{let[n,r]=C(0);x(()=>{let e=setInterval(()=>{r(e=>(e+1)%X.length)},ft);return()=>clearInterval(e)},[]);let i=X[n],a=i.visual?i.visual():[],o=X.map((e,t)=>t===n?`●`:`·`).join(` `);return b.createElement(h,{flexDirection:`column`,width:e,height:t,paddingX:2,paddingY:1},b.createElement(h,{marginBottom:1},b.createElement(g,{color:`magentaBright`,bold:!0},`Learn`)),b.createElement(h,{marginBottom:1},b.createElement(g,{bold:!0,color:`white`},i.title)),i.body.map((e,t)=>b.createElement(g,{key:t,color:`gray`},e||` `)),a.length>0&&b.createElement(h,{flexDirection:`column`,marginTop:1},a.map((e,t)=>b.createElement(g,{key:t,color:`cyan`},e))),b.createElement(h,{flexGrow:1}),b.createElement(h,{marginTop:1},b.createElement(g,{color:`gray`,dimColor:!0},o,` · `,n+1,` / `,X.length)))},mt={pending:`·`,active:`⠋`,done:`✓`,error:`✗`},ht={pending:`gray`,active:`magenta`,done:`green`,error:`red`},gt=({tasks:e,width:t,height:n,liveLine:r})=>{let i=e.filter(e=>e.status===`done`).length;return b.createElement(h,{flexDirection:`column`,width:t,height:n,paddingX:2,paddingY:1},b.createElement(h,{marginBottom:1},b.createElement(g,{color:`magentaBright`,bold:!0},`Tasks`)),e.map(e=>b.createElement(h,{key:e.id,flexDirection:`column`},b.createElement(h,null,e.status===`active`?b.createElement(g,{color:`magenta`},b.createElement(D,{type:`dots`})):b.createElement(g,{color:ht[e.status]},mt[e.status]),b.createElement(g,null,` `),b.createElement(g,{color:e.status===`pending`?`gray`:`white`},e.label)),e.detail&&b.createElement(h,{paddingLeft:2},b.createElement(g,{color:`gray`,dimColor:!0},e.detail)))),b.createElement(h,{flexGrow:1}),r&&b.createElement(h,{marginTop:1},b.createElement(g,{color:`cyan`},`◆ `),b.createElement(g,{color:`white`},r)),b.createElement(h,{marginTop:1},b.createElement(g,{color:`gray`,dimColor:!0},i,` / `,e.length)))};async function _t(e){return a(e)?vt(e):new Promise(t=>{let{unmount:n,waitUntilExit:r}=_(b.createElement(yt,{opts:e,onExit:e=>{n(),t(e)}}));r().catch(()=>t(1))})}async function vt(r){try{let a=await e(),o=await q(r.cwd);if(!o)return i({type:`error`,code:`no_framework`,message:`Could not detect framework (headless mode has no picker).`}),2;i({type:`framework.detected`,framework:o.id,confidence:1});let s=await n({strict:!1});if(!s&&!process.env.ZENOVAY_API_TOKEN)return i({type:`error`,code:`not_logged_in`,message:"Run `zenovay login` first (or set ZENOVAY_API_TOKEN)."}),2;let c=new t({config:a,cliVersion:r.cliVersion,token:s}),l=await c.getSites(),u=r.siteId?l.find(e=>e.id===r.siteId):l[0];if(!u&&r.siteId)return i({type:`error`,code:`site_not_found`,message:`Site ${r.siteId} not found.`}),2;if(!u)return i({type:`error`,code:`no_site`,message:`No sites exist; create one at app.zenovay.com or re-run interactively.`}),2;i({type:`info`,message:`Using site ${u.id} (${u.name}) trackingCode=${u.trackingCode??u.id}`});let d=await J(r.cwd,{[o.envVarName]:u.trackingCode??u.id});return i({type:`info`,message:`env vars added: ${d.addedKeys.join(`,`)}`}),i({type:`done`,command:`init`,exitCode:0}),0}catch(e){return i({type:`error`,code:`init_failed`,message:e.message}),1}}const yt=({opts:r,onExit:i})=>{let{exit:a}=v(),[l,d]=C(`intro`),[f,p]=C(null),[m,_]=C([]),[y,w]=C(null),[T,E]=C(null),[O,k]=C(null),[ee,A]=C([]),[j,M]=C(void 0),[N,P]=C(null),[F,I]=C(0),L=S(!1);return x(()=>(process.stdout.isTTY&&process.stdout.write(`\x1B[?1049h\x1B[H`),()=>{process.stdout.isTTY&&process.stdout.write(`\x1B[?1049l`)}),[]),x(()=>{L.current||(L.current=!0,(async()=>{try{d(`detecting`);let i=await q(r.cwd);if(!i){k(`Could not detect your framework. Supported: Next.js, Nuxt, SvelteKit, Astro, Remix, plain HTML.`),d(`error`);return}p(i);let a=await n({strict:!1});!process.env.ZENOVAY_API_TOKEN&&!a&&(d(`login`),await o({cliVersion:r.cliVersion})),d(`loading-sites`);let s=await e(),c=await n({strict:!1}),l=new t({config:s,cliVersion:r.cliVersion,token:c}),u=await l.getSites(),f=await Mt(r.cwd),m=Nt(u,f);if(_(u),w(f),u.length===0){d(`create-site`);return}if(r.siteId){let e=u.find(e=>e.id===r.siteId);if(!e){k(`Site ${r.siteId} not found in your account.`),d(`error`);return}E(e),Z(e,i,r,{setPhase:d,setErrorMsg:k,setTasks:A,setLiveLine:M,setSandboxStats:P});return}if(r.yes&&m){E(m),Z(m,i,r,{setPhase:d,setErrorMsg:k,setTasks:A,setLiveLine:M,setSandboxStats:P});return}d(`site-picker`)}catch(e){k(e.message),d(`error`)}})())},[]),x(()=>{process.stdout.isTTY&&process.stdout.write(`\x1B[2J\x1B[H`),l===`success`&&setTimeout(()=>{a(),i(0)},1500),l===`error`&&setTimeout(()=>{a(),i(1)},8e3)},[l]),b.createElement(h,{flexDirection:`column`},b.createElement(c,{version:r.cliVersion,subtitle:`AI install wizard`}),l===`intro`&&b.createElement(bt,null),l===`detecting`&&b.createElement(s,{title:`Scanning`,state:`busy`},b.createElement(h,null,b.createElement(g,{color:`magenta`},b.createElement(D,{type:`dots`})),b.createElement(g,null,` Detecting framework…`))),l===`login`&&b.createElement(s,{title:`Authenticating`,state:`busy`},b.createElement(g,null,`Opening browser for login… (paste ZENOVAY_API_TOKEN env var to skip)`)),l===`loading-sites`&&b.createElement(s,{title:`Loading your sites`,state:`busy`},b.createElement(h,null,b.createElement(g,{color:`magenta`},b.createElement(D,{type:`dots`})),b.createElement(g,null,` Fetching your Zenovay sites…`))),l===`site-picker`&&f&&b.createElement(St,{sites:m,preselectHint:y,onPick:e=>{if(e===`create-new`){d(`create-site`);return}E(e),Z(e,f,r,{setPhase:d,setErrorMsg:k,setTasks:A,setLiveLine:M,setSandboxStats:P})}}),l===`create-site`&&b.createElement(s,{title:`Create a new site`,state:`warn`},b.createElement(g,{color:`yellow`},"No site picked (or none exist yet). Visit https://app.zenovay.com/websites to create one, then re-run `zenovay init`."),b.createElement(g,{color:`gray`},`(Inline site creation from the CLI is scheduled for V1.1 — it requires a plan-limit check.)`)),l===`agent`&&f&&T&&b.createElement(xt,{adapter:f,site:T,tasks:ee,liveLine:j}),l===`install-complete`&&f&&T&&b.createElement(wt,{adapter:f,site:T,stats:N,onCommit:()=>d(`commit-prompt`),onSkipCommit:()=>d(`deploy-prompt`)}),l===`commit-prompt`&&T&&b.createElement(Tt,{cwd:r.cwd,onDone:e=>{e.committed&&M(`Pushed ${e.shortSha} to ${e.branch}`),d(`deploy-prompt`)},onError:e=>{k(e),d(`error`)}}),l===`deploy-prompt`&&T&&b.createElement(Et,{site:T,onDeployed:()=>d(`visit-prompt`),onSkip:()=>d(`verify`)}),l===`visit-prompt`&&T&&b.createElement(Dt,{site:T,onContinue:()=>d(`verify`)}),l===`verify`&&T&&b.createElement(kt,{site:T,elapsed:F,onTick:e=>I(e),onArrived:()=>d(`success`),onTimeout:()=>d(`success`)}),l===`success`&&f&&T&&b.createElement(Ct,{adapter:f,site:T,stats:N}),l===`error`&&b.createElement(s,{title:`Install failed`,state:`err`},b.createElement(g,{color:`red`},O??`Unknown error`)),b.createElement(u,{items:[{key:`q`,label:`quit`},{key:`ctrl-c`,label:`abort`}]}))};async function Z(r,i,a,o){try{o.setPhase(`agent`);let s=await e(),c=await n({strict:!1}),l=new t({config:s,cliVersion:a.cliVersion,token:c}),u=new W({cwd:a.cwd}),d=r.trackingCode??r.id,f=await I(a.cwd,d);if(f.recommendation===`no-op`){o.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:`done`,detail:`already installed correctly`}:e)),o.setLiveLine(f.summary),o.setSandboxStats?.({reads:0,writes:0,rounds:0}),!a.skipMcp&&c&&await Y({accessToken:c.accessToken}).catch(()=>void 0),o.setPhase(`install-complete`);return}f.competitors.length>0&&o.setLiveLine(`Detected ${f.competitors.map(e=>e.name).join(`, `)} — will install Zenovay alongside (won't touch their tags).`);let p=i.buildSnippets({trackingCode:d,siteId:r.id}),m=`Install Zenovay tracking into this ${i.displayName} project.\nSite: ${r.name} (trackingCode: ${d}).\n1. Call detect_framework to confirm the framework.\n2. Read the entry file(s) for this framework:\n`+i.files.map(e=>` - ${e.path}`).join(`
|
|
53
|
+
`)+`
|
|
54
|
+
3. Insert the tracker using the snippet below.
|
|
55
|
+
4. Confirm the change with a diff before writing.
|
|
56
|
+
|
|
57
|
+
Snippet reference (anchored by anchorKind — adapt to the actual file):
|
|
58
|
+
`+p.map(e=>` ${e.anchorKind} @ ${e.targetPath}:\n ${e.code.replace(/\n/g,`
|
|
59
|
+
`)}`).join(`
|
|
60
|
+
|
|
61
|
+
`);o.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 h=(e,t,n)=>{o.setTasks(r=>r.map(r=>r.id===e?{...r,status:t,detail:n??r.detail}:r))},g=null;try{await ot({api:l,sandbox:u,approval:{async approve(){return`y`}},prompter:{async ask({question:e}){return e}},handlers:{onToolStart:({name:e})=>{e===`detect_framework`?(h(`detect`,`active`),o.setLiveLine(`Inspecting package.json + config files…`)):e===`read_file`?(h(`detect`,`done`),h(`read`,`active`)):(e===`write_file`||e===`patch_file`)&&(h(`read`,`done`),h(`write`,`active`))},onToolResult:({name:e,result:t})=>{let n=t?.ok!==!1,r=t?.content??{};e===`detect_framework`&&n&&(h(`detect`,`done`,i.displayName),o.setLiveLine(`Detected ${i.displayName}`)),e===`read_file`&&n&&r.path&&o.setLiveLine(`Read ${r.path}`),(e===`write_file`||e===`patch_file`)&&n&&r.path&&o.setLiveLine(`Wrote ${r.path}`)},onDelta:e=>{let t=e.replace(/\s+/g,` `).trim();t.length>4&&o.setLiveLine(t.slice(0,80))}},initialMessages:[{role:`user`,content:m}],diagnosis:f,targetTrackingCode:d})}catch(e){g=e}let _=u.stats();if(_.writes===0){let e=g?`Agent error: ${g.message}`:`Agent returned without writing any files (${_.reads} reads, ${_.rounds} rounds). The model may have refused or the AI Gateway may be misconfigured. Check api.zenovay.com logs.`;throw Error(e)}let v=i.files.map(e=>e.path),y=_.writtenPaths.some(e=>v.some(t=>e===t||e.endsWith(`/${t}`)));if(!y)throw Error(`Agent wrote to: [${_.writtenPaths.join(`, `)}] but never modified the framework's tracker target file(s): [${v.join(`, `)}]. The tracker is NOT installed. The model likely put the trackingCode into .env.local instead of into the HTML/JSX entry file.`);h(`write`,`done`),h(`env`,`active`),o.setLiveLine(`Adding env var to .env.local`);let b=await J(a.cwd,{[i.envVarName]:d});if(h(`env`,`done`,`${b.addedKeys.length} key(s) added`),!a.skipMcp&&c){h(`mcp`,`active`),o.setLiveLine(`Detecting Cursor / Claude Desktop / VS Code…`);let e=await Y({accessToken:c.accessToken}).catch(()=>null);e&&e.installed.length>0?h(`mcp`,`done`,e.installed.join(`, `)):h(`mcp`,`done`,`none detected`)}else h(`mcp`,`done`,`skipped`);o.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:e.status===`pending`?`done`:e.status}:e)),o.setLiveLine(void 0),o.setSandboxStats?.(_),o.setPhase(`install-complete`)}catch(e){o.setErrorMsg(e.message),o.setPhase(`error`)}}const bt=()=>b.createElement(s,{title:`Zenovay wants to set up your project`,state:`idle`},b.createElement(g,null,`We'll use AI to analyze your codebase and add the Zenovay tracker.`),b.createElement(g,{color:`gray`},`.env* contents stay on your machine. Only framework metadata reaches api.zenovay.com.`)),xt=({adapter:e,site:t,tasks:n,liveLine:r})=>{let i=process.stdout.columns??100,a=(process.stdout.rows??30)-6,o=Math.floor(i/2)-1,s=Math.max(14,a);return b.createElement(h,{flexDirection:`column`},b.createElement(h,{flexDirection:`row`,height:s,borderStyle:`round`,borderColor:`gray`},b.createElement(h,{width:o,flexDirection:`column`},b.createElement(pt,{width:o,height:s})),b.createElement(h,{width:1,flexDirection:`column`,height:s},b.createElement(g,{color:`gray`},`│`)),b.createElement(h,{width:o,flexDirection:`column`},b.createElement(gt,{tasks:n,liveLine:r,width:o,height:s}))),b.createElement(h,{marginTop:1},b.createElement(g,{color:`gray`},`Site: `,t.name,` · code: `,t.trackingCode??t.id,` · Framework: `,e.displayName)))},St=({sites:e,preselectHint:t,onPick:n})=>{let r=Nt(e,t),i=e.filter(e=>e.id!==r?.id),a=r?[r,...i]:i,o=[...a.map(e=>({label:jt(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 b.createElement(s,{title:t?`Pick a site (best match: ${t})`:`Pick a site`,state:`idle`},b.createElement(d,{items:o,onSelect:n}))},Ct=({adapter:e,site:t,stats:n})=>b.createElement(s,{title:`You're live on Zenovay`,state:`ok`},b.createElement(g,null,b.createElement(l,null,`✔ Installed successfully`)),b.createElement(g,null,`Framework: `,e.displayName),b.createElement(g,null,`Site: `,t.name,` (`,t.url,`)`),t.trackingCode?b.createElement(g,{color:`gray`},`Tracker code: `,t.trackingCode):null,n?b.createElement(g,{color:`gray`},n.writes,` file(s) modified across `,n.rounds,` agent round(s)`):null,b.createElement(g,{color:`gray`},`Dashboard: https://app.zenovay.com/sites/`,t.id),b.createElement(g,{color:`gray`},"Next: `zenovay watch` for a live TUI.")),wt=({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()}),b.createElement(s,{title:`Tracker installed`,state:`ok`},b.createElement(g,null,b.createElement(l,null,`✔ `),`The Zenovay tracker is in your project.`),b.createElement(h,{marginTop:1},b.createElement(g,{color:`gray`},`Framework: `),b.createElement(g,null,e.displayName)),b.createElement(h,null,b.createElement(g,{color:`gray`},`Site: `),b.createElement(g,null,t.name,` (`,t.url,`)`)),n&&b.createElement(h,null,b.createElement(g,{color:`gray`},`Modified: `),b.createElement(g,null,n.writes,` file(s)`)),b.createElement(h,{marginTop:1},b.createElement(g,null,`Commit + push these changes to git? `),b.createElement(g,{color:`cyan`},`[Y/n]`)))),Tt=({cwd:e,onDone:t,onError:n})=>{let[r,i]=C(`committing`),[a,o]=C(`Staging changes…`);return x(()=>{(async()=>{try{let n=await At(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)}})()},[]),b.createElement(s,{title:`Committing to git`,state:`busy`},b.createElement(h,null,b.createElement(g,{color:`magenta`},b.createElement(D,{type:`dots`})),b.createElement(g,null,` `,r===`pushing`?`Pushing to origin`:`Committing`,`…`)),b.createElement(h,{marginTop:1},b.createElement(g,{color:`gray`},a)))},Et=({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()}),b.createElement(s,{title:`Ready to deploy?`,state:`idle`},b.createElement(g,null,`The tracker is installed locally. To capture events you need it on the live site:`),b.createElement(g,null,` `),b.createElement(h,null,b.createElement(g,{color:`cyan`},` → `),b.createElement(g,null,e.url)),b.createElement(g,null,` `),b.createElement(g,{color:`gray`},`Push the change through your normal deploy pipeline (Vercel auto-deploy, CI/CD, etc.).`),b.createElement(h,{marginTop:1},b.createElement(g,null,`Once it's deployed, press `),b.createElement(g,{color:`cyan`},`[Y]`),b.createElement(g,null,` to verify the tracker is firing. `),b.createElement(g,{color:`gray`},`[s] skip verification`)))),Dt=({site:e,onContinue:t})=>(Q(()=>t()),b.createElement(s,{title:`Visit your site`,state:`idle`},b.createElement(g,null,`To send a test event, open any page on your site:`),b.createElement(g,null,` `),b.createElement(h,null,b.createElement(g,{color:`cyan`},` → `),b.createElement(g,null,e.url)),b.createElement(g,null,` `),b.createElement(g,{color:`gray`},`The tracker fires automatically on page load. We'll verify the next event arrives.`),b.createElement(h,{marginTop:1},b.createElement(g,null,`Press `),b.createElement(g,{color:`cyan`},`[any key]`),b.createElement(g,null,` when you've visited the page.`))));async function Ot(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 kt=({site:r,elapsed:i,onTick:a,onArrived:o,onTimeout:c})=>{let[l,u]=C(`preflight`),[d,f]=C(``),[p,m]=C([]),_=S(!1),v=r.trackingCode??r.id,w=async()=>{u(`preflight`),f(`Fetching ${r.url}…`);let e=await Ot(r.url,v);if(!_.current){if(e.state===`tracker-correct`){u(`polling`),f(`Tracker detected on live site — waiting for first hit…`),T();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 ${r.url}: ${e.networkError}`:e.httpStatus?`${r.url} returned HTTP ${e.httpStatus}`:`No Zenovay tracker found on ${r.url}.`)}},T=async()=>{let i=Date.now();try{let s=await e(),c=await n({strict:!1}),l=new t({config:s,cliVersion:`0`,token:c}),d=await Ye(r.id,i,{api:l,timeoutMs:18e4,pollIntervalMs:2500,onTick:e=>{_.current||a(e)}});if(_.current)return;d.received?(u(`success`),o()):u(`timeout`)}catch{_.current||u(`timeout`)}};x(()=>(_.current=!1,w(),()=>{_.current=!0}),[]),y(e=>{(l===`awaiting-deploy`||l===`wrong-id-on-live`||l===`timeout`)&&(e===`r`||e===`R`?w():(e===`s`||e===`S`)&&c())},{isActive:!0});let E=Math.floor(i/1e3);return l===`preflight`?b.createElement(s,{title:`Verifying`,state:`busy`},b.createElement(h,null,b.createElement(g,{color:`magenta`},b.createElement(D,{type:`dots`})),b.createElement(g,null,` Checking your live site for the tracker…`)),b.createElement(h,{marginTop:1},b.createElement(g,{color:`gray`},d))):l===`awaiting-deploy`?b.createElement(s,{title:`Tracker not yet on your live site`,state:`warn`},b.createElement(g,{color:`yellow`},d),b.createElement(h,{marginTop:1,flexDirection:`column`},b.createElement(g,null,`The tracker is in your local repo but hasn't been deployed yet.`),b.createElement(g,{color:`gray`},`Push your changes and wait for your deploy to finish (Vercel / Cloudflare Pages / CI), then retry.`)),b.createElement(h,{marginTop:1},b.createElement(g,null,`Press `),b.createElement(g,{color:`cyan`},`[r]`),b.createElement(g,null,` to re-check, `),b.createElement(g,{color:`cyan`},`[s]`),b.createElement(g,null,` to skip verification.`))):l===`wrong-id-on-live`?b.createElement(s,{title:`Live site has a different tracking code`,state:`warn`},b.createElement(g,{color:`yellow`},`Expected: `,b.createElement(g,{color:`cyan`},v),` `,`Found on live: `,b.createElement(g,{color:`cyan`},p.join(`, `))),b.createElement(h,{marginTop:1,flexDirection:`column`},b.createElement(g,null,`Your local install uses a different ID than what's on `,r.url,`.`),b.createElement(g,{color:`gray`},`Deploy the new local version, then retry — or skip if the existing ID is intentional.`)),b.createElement(h,{marginTop:1},b.createElement(g,null,`Press `),b.createElement(g,{color:`cyan`},`[r]`),b.createElement(g,null,` to re-check, `),b.createElement(g,{color:`cyan`},`[s]`),b.createElement(g,null,` to skip.`))):l===`timeout`?b.createElement(s,{title:`No event arrived in 3 minutes`,state:`warn`},b.createElement(g,{color:`yellow`},`The tracker is on your live site but no hits reached api.zenovay.com.`),b.createElement(h,{marginTop:1},b.createElement(g,{color:`gray`},`Try opening `,r.url,` in a fresh browser tab (no ad-blocker), then retry.`)),b.createElement(h,{marginTop:1},b.createElement(g,null,`Press `),b.createElement(g,{color:`cyan`},`[r]`),b.createElement(g,null,` to re-check, `),b.createElement(g,{color:`cyan`},`[s]`),b.createElement(g,null,` to finish without verification.`))):b.createElement(s,{title:`Waiting for first event`,state:`busy`},b.createElement(h,null,b.createElement(g,{color:`magenta`},b.createElement(D,{type:`dots`})),b.createElement(g,null,` Polling api.zenovay.com for the first hit on `),b.createElement(g,{color:`cyan`},r.url),b.createElement(g,null,` (`,E,`s elapsed)`)),b.createElement(h,{marginTop:1},b.createElement(g,{color:`gray`},`Reload the page if nothing arrives within ~30 seconds.`)))};function Q(e){y((t,n)=>{e(t,{return:n.return,escape:n.escape})},{isActive:!0})}async function At(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 jt(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 Mt(e){try{let t=await m.readFile(p.join(e,`package.json`),`utf8`),n=JSON.parse(t);if(n.name)return String(n.name).replace(/^@[^/]+\//,``)}catch{}try{let t=await m.readFile(p.join(e,`.git`,`config`),`utf8`),n=t.match(/url\s*=\s*.*[/:]([^/]+?)(?:\.git)?\s*$/m);if(n&&n[1])return n[1]}catch{}return p.basename(e)}function Nt(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{te as detectInstalled,_t as initCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./config-ZTGpKEWg.js";import"./api-BhdaCghp.js";import{initCommand as e}from"./init
|
|
1
|
+
import"./config-ZTGpKEWg.js";import"./api-BhdaCghp.js";import{initCommand as e}from"./init--eTjzzmh.js";import"./client-DZ4Awt8u.js";import"./formatter-45-fT1Hv.js";import"./emit-0WJ_OGeT.js";import"./login-DHLIZV8C.js";import"./panel-DglZ755S.js";import"./keybar-D2OI-8rx.js";import"./prompt-hjzdzlyj.js";import"./sparkline-CR_bzxwB.js";export{e as initCommand};
|
package/dist/wizard-bin.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import(`./init-
|
|
2
|
+
import(`./init-qzmy4rIN.js`).then(async({initCommand:e})=>{let{readFileSync:t}=await import(`node:fs`),n=await import(`node:path`),{fileURLToPath:r}=await import(`node:url`),i=n.dirname(r(import.meta.url)),a=JSON.parse(t(n.join(i,`..`,`package.json`),`utf8`)),o=process.argv.slice(2),s=o.includes(`--json`),c=o.includes(`--yes`),l=o.includes(`--skip-mcp`),u=o.includes(`--skip-verify`),d=await e({cliVersion:a.version,cwd:process.cwd(),json:s,yes:c,skipMcp:l,skipVerify:u});process.exit(d)});
|
package/package.json
CHANGED
package/dist/init-BSCKoJ-F.js
DELETED
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
import{readConfig as e}from"./config-ZTGpKEWg.js";import{ApiClient as t,readToken as n}from"./api-BhdaCghp.js";import{parseSseStream as r}from"./client-DZ4Awt8u.js";import{emit as i,isHeadless as a}from"./emit-0WJ_OGeT.js";import{loginCommand as o}from"./login-DHLIZV8C.js";import{Panel as s}from"./panel-DglZ755S.js";import{Banner as c,BrandGradient as l,Keybar as u}from"./keybar-D2OI-8rx.js";import{Select as d}from"./prompt-hjzdzlyj.js";import{spark as f}from"./sparkline-CR_bzxwB.js";import p from"node:path";import{promises as m}from"node:fs";import{Box as h,Text as g,render as _,useApp as v,useInput as y}from"ink";import b,{useEffect as x,useRef as S,useState as C}from"react";import w from"node:os";import{z as T}from"zod";import{globby as E}from"globby";import D from"ink-spinner";import O from"node:crypto";import{ulid as k}from"ulid";import{applyPatch as ee}from"diff";const A=[`@zenovay/tracker`,`@zenovay/next`,`@zenovay/nuxt`,`@zenovay/svelte`,`@zenovay/astro`,`@zenovay/remix`,`@zenovay/node`],j=[`zenovay.config.ts`,`zenovay.config.js`,`zenovay.config.mjs`,`zenovay.config.json`],M=/<script[^>]*src\s*=\s*["']https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+["'][^>]*>\s*<\/script>/gi,N=/data-id\s*=\s*["'](ZV_[A-Za-z0-9]+)["']/i,P=/data-zenovay-site\s*=\s*["']([^"']+)["']/i,F=[{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 I(e,t){let n={zenovayInstalled:!1,correctTrackingCode:!1,foundTrackingCodes:[],zenovayFiles:[],competitors:[],summary:``,recommendation:`fresh-install`};try{let t=await m.readFile(p.join(e,`package.json`),`utf8`),r=JSON.parse(t),i={...r.dependencies,...r.devDependencies};for(let e of A)if(e in i){n.zenovayInstalled=!0,n.packageMarker=e;break}}catch{}for(let t of j)try{await m.access(p.join(e,t)),n.zenovayInstalled=!0,n.configFile=t;break}catch{}let r=await E([`**/*.{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 m.readFile(t,`utf8`)}catch{continue}let o=p.relative(e,t),s=r.match(M);if(s&&s.length>0){n.zenovayInstalled=!0;let e=s[0].slice(0,200),t=e.match(N)??e.match(P),r=t?.[1]??null;r&&a.add(r),n.zenovayFiles.push({file:o,currentTrackingCode:r,scriptTagCount:s.length,matchSample:e})}for(let e of F)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=L(n,t),n}function L(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 te(e){let t=await I(e,``);return{installed:t.zenovayInstalled,reasons:t.summary?[t.summary]:[],packageMarker:t.packageMarker,configFile:t.configFile,scriptFile:t.zenovayFiles[0]?.file}}const ne=[{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 re(e){let t=e;for(let e of ne){let n=new RegExp(e.regex.source,e.regex.flags);t=t.replace(n,`[REDACTED:${e.name}]`)}return t}const ie=[/^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)$/],ae=[/(^|\/)\.env($|\.(?!example$)[^/]+$)/,/(^|\/)\.git(\/|$)/,/(^|\/)node_modules\//,/(^|\/)\.ssh\//,/(^|\/)\.aws\//,/\.pem$/,/\.key$/,/(^|\/)id_rsa($|\.)/,/(^|\/)\.npmrc$/,/(^|\/)credentials(\.|$)/],R=256*1024,z=50,B=20,V=40;var H=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`SandboxError`}};const U=/<script[^>]*src\s*=\s*["']https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+["'][^>]*>\s*<\/script>/i,oe=[{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 W=class{sessionId;cwd;cwdReal;undoRoot;readCount=0;writeCount=0;roundCount=0;constructor(e){this.sessionId=e.sessionId??k(),this.cwd=e.cwd,this.cwdReal=m.realpath(e.cwd),this.undoRoot=e.undoRoot??p.join(w.homedir(),`.zenovay`,`undo`)}incrementRound(){if(this.roundCount++,this.roundCount>V)throw new H(`round-cap`,`Tool-call recursion cap (${V}) exceeded.`)}stats(){return{sessionId:this.sessionId,reads:this.readCount,writes:this.writeCount,rounds:this.roundCount}}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 H(`escape`,`Path must be a non-empty string.`);if(e.includes(`\0`))throw new H(`escape`,`Null byte in path.`);if(/^\\\\[?.]\\/.test(e)||/^\\\\[A-Za-z0-9]/.test(e))throw new H(`escape`,`Windows special path prefix: ${e}`);if(/%/.test(e))try{let t=decodeURIComponent(e);if(/%[0-9A-Fa-f]{2}/.test(t))throw new H(`escape`,`Double-encoded path: ${e}`);e=t}catch(t){throw t instanceof H?t:new H(`escape`,`Malformed percent-encoding: ${e}`)}if(e.includes(`\0`))throw new H(`escape`,`Null byte in decoded path.`);if(e.includes(`\\`))throw new H(`escape`,`Backslash in path (Windows-style separator not accepted): ${e}`);let n=await this.cwdReal,r=p.isAbsolute(e)?e:p.join(n,e),i=p.normalize(r),a=i;try{a=await m.realpath(i)}catch(e){if(e.code!==`ENOENT`)throw new H(`escape`,`realpath failed: ${e.message}`);let t=p.dirname(i);try{let e=await m.realpath(t);a=p.join(e,p.basename(i))}catch{}}if(!this.isWithin(a,n))throw new H(`escape`,`Path escapes cwd: ${e}`);let o=p.relative(n,a);for(let e of ae)if(e.test(o)){if(t===`read`&&/(^|\/)node_modules\//.test(o))continue;throw new H(`blocklisted`,`Path is on the hard blocklist: ${o}`)}if(t===`write`){let e=ie.some(e=>e.test(o));if(!e&&!/^\.env(\.local)?$/.test(o)&&!/^\.claude\//.test(o)&&!/^\.cursor\//.test(o))throw new H(`not-allowlisted`,`Write path not on allowlist: ${o}`)}return a}isWithin(e,t){let n=p.relative(t,e);return!n.startsWith(`..`)&&!p.isAbsolute(n)}async safeRead(e){if(this.readCount>=z)throw new H(`read-cap`,`Read cap (${z}) reached.`);let t=await this.resolveForRead(e),n=await m.stat(t);if(n.size>R)throw new H(`too-large`,`File exceeds ${R}B: ${e} (${n.size}B)`);let r=await m.readFile(t),i=r.subarray(0,Math.min(r.length,8192));if(i.includes(0))throw new H(`binary-rejected`,`Binary content in ${e}.`);return this.readCount++,r.toString(`utf8`)}async safeWrite(e,t){if(this.writeCount>=B)throw new H(`write-cap`,`Write cap (${B}) reached.`);if(t.length>R)throw new H(`too-large`,`Write exceeds ${R}B: ${e}`);let n=await this.resolveForWrite(e),r=await m.readFile(n,`utf8`).catch(e=>{if(e.code===`ENOENT`)return null;throw e});if(r!==null){if(U.test(r)&&!U.test(t))throw new H(`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 oe)if(i.test(r)&&!i.test(t))throw new H(`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);return await m.mkdir(p.dirname(n),{recursive:!0}),await m.writeFile(n,t,`utf8`),this.writeCount++,{backupPath:i}}async journalBackup(e){let t=await m.readFile(e).catch(e=>{if(e.code===`ENOENT`)return null;throw e}),n=p.join(this.undoRoot,this.sessionId);await m.mkdir(n,{recursive:!0,mode:448});let r=O.createHash(`sha256`).update(e).digest(`hex`).slice(0,16),i=p.join(n,`${r}.bak`),a=p.join(n,`manifest.jsonl`);t&&await m.writeFile(i,t,{mode:384});let o=JSON.stringify({abs:e,backupPath:t?i:null,ts:Date.now()});return await m.appendFile(a,o+`
|
|
2
|
-
`,{mode:384}),t?i:null}static wrapForModel(e,t){let n=O.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 re(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
|
-
defer
|
|
4
|
-
data-id="${n}"
|
|
5
|
-
data-allow-localhost="true"
|
|
6
|
-
src="https://api.zenovay.com/z.js"
|
|
7
|
-
strategy="afterInteractive"
|
|
8
|
-
/>
|
|
9
|
-
{children}`,description:`Add the Zenovay tracker <Script> next to children in the root layout.`}]}const ge={id:`next-app-router`,displayName:`Next.js (App Router)`,detect:me,files:[{path:`app/layout.tsx`,kind:`mutate`,required:!0}],envVarName:`NEXT_PUBLIC_ZENOVAY_SITE`,buildSnippets:he},_e=[`pages/_app.tsx`,`pages/_app.ts`,`pages/_app.jsx`,`pages/_app.js`,`src/pages/_app.tsx`,`src/pages/_app.ts`,`src/pages/_app.jsx`,`src/pages/_app.js`];async function ve(e){for(let t of _e)if(await e.exists(t))return t;return null}async function ye(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 be(e){let t=await ye(e);if(!t)return{matched:!1,confidence:0,reason:"package.json does not list `next` as a dependency."};let n=await ve(e);if(n)return{matched:!0,confidence:.9,reason:`Detected Next.js Pages Router via \`${n}\`.`};let r=await e.exists(`app`),i=await e.glob(`pages/**/*.{tsx,ts,jsx,js}`);return i.length>0&&!r?{matched:!0,confidence:.7,reason:"Found `pages/` directory with route files but no `_app` — will create one."}:{matched:!1,confidence:.2,reason:`Next.js detected, but no pages-router entry point found.`}}function xe(e){let t=`pages/_app.tsx`,n=e.trackingCode??e.siteId??``,r=`import type { AppProps } from 'next/app';
|
|
10
|
-
import Script from 'next/script';
|
|
11
|
-
|
|
12
|
-
export default function App({ Component, pageProps }: AppProps) {
|
|
13
|
-
return (
|
|
14
|
-
<>
|
|
15
|
-
<Script
|
|
16
|
-
defer
|
|
17
|
-
data-id="${n}"
|
|
18
|
-
data-allow-localhost="true"
|
|
19
|
-
src="https://api.zenovay.com/z.js"
|
|
20
|
-
strategy="afterInteractive"
|
|
21
|
-
/>
|
|
22
|
-
<Component {...pageProps} />
|
|
23
|
-
</>
|
|
24
|
-
);
|
|
25
|
-
}
|
|
26
|
-
`;return[{targetPath:t,anchorKind:`after-imports`,code:`import Script from 'next/script';`,description:"Import next/script in `_app`."},{targetPath:t,anchorKind:`wrap-children`,code:`<><Script defer data-id="${n}" data-allow-localhost="true" src="https://api.zenovay.com/z.js" strategy="afterInteractive" /><Component {...pageProps} /></>`,description:`Render the Zenovay tracker alongside the page component.`},{targetPath:t,anchorKind:`replace-file`,code:r,description:"Full replacement when `_app` does not exist yet."}]}const Se={id:`next-pages-router`,displayName:`Next.js (Pages Router)`,detect:be,files:[{path:`pages/_app.tsx`,kind:`mutate`,required:!0}],envVarName:`NEXT_PUBLIC_ZENOVAY_SITE`,buildSnippets:xe},Ce=T.object({modules:T.array(T.string()).optional(),runtimeConfig:T.object({public:T.record(T.string(),T.unknown()).optional()}).optional()}).passthrough();async function we(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json found.`};try{let e=JSON.parse(t),n=!!(e.dependencies?.nuxt??e.devDependencies?.nuxt??e.dependencies?.nuxt3??e.devDependencies?.nuxt3);if(n)return{matched:!0,confidence:.95,reason:"Detected Nuxt via `nuxt` / `nuxt3` dependency."}}catch{}let n=await e.exists(`nuxt.config.ts`)||await e.exists(`nuxt.config.js`)||await e.exists(`nuxt.config.mjs`);return n?{matched:!0,confidence:.6,reason:"Found `nuxt.config.*` but no explicit dependency listing."}:{matched:!1,confidence:0,reason:`No Nuxt dependency or config detected.`}}function Te(e){let t=e.trackingCode??e.siteId??``,n=` app: {
|
|
27
|
-
head: {
|
|
28
|
-
script: [
|
|
29
|
-
{
|
|
30
|
-
defer: true,
|
|
31
|
-
src: 'https://api.zenovay.com/z.js',
|
|
32
|
-
'data-id': '${t}',
|
|
33
|
-
'data-allow-localhost': 'true',
|
|
34
|
-
},
|
|
35
|
-
],
|
|
36
|
-
},
|
|
37
|
-
},`;return[{targetPath:`nuxt.config.ts`,anchorKind:`head-tag`,code:n,description:"Add the Zenovay tracker to Nuxt's `app.head.script` so every page loads it."}]}const Ee={id:`nuxt`,displayName:`Nuxt`,detect:we,files:[{path:`nuxt.config.ts`,kind:`mutate`,required:!0}],envVarName:`NUXT_PUBLIC_ZENOVAY_SITE`,buildSnippets:Te},De=[`index.html`,`public/index.html`,`dist/index.html`];async function Oe(e){for(let t of De)if(await e.exists(t))return{matched:!0,confidence:.5,reason:`Detected plain HTML project via \`${t}\`.`};let t=await e.glob(`**/*.html`);return t.length>0?{matched:!0,confidence:.3,reason:`Found ${t.length} HTML file(s); plain-HTML adapter is usable as fallback.`}:{matched:!1,confidence:0,reason:`No HTML files found in the project.`}}function ke(e){let t=e.siteId??``,n=`<script defer\n data-id="${t}"\n data-allow-localhost="true"\n src="https://api.zenovay.com/z.js">\n</script>`;return[{targetPath:`index.html`,anchorKind:`head-tag`,code:n,description:`Inject the Zenovay tracker inside <head>. Repeat for every HTML file that contains a <head>.`}]}const Ae={id:`plain-html`,displayName:`Plain HTML`,detect:Oe,files:[{path:`index.html`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:ke};async function je(e){let t=await e.readFile(`package.json`);if(t)try{let e=JSON.parse(t),n={...e.dependencies??{},...e.devDependencies??{}},r=Object.keys(n).some(e=>e.startsWith(`@remix-run/`));if(r)return{matched:!0,confidence:.95,reason:"Detected Remix via `@remix-run/*` dependencies."}}catch{}return await e.exists(`remix.config.js`)||await e.exists(`remix.config.ts`)?{matched:!0,confidence:.8,reason:"Detected Remix via `remix.config.*`."}:{matched:!1,confidence:0,reason:`No Remix dependency or config detected.`}}function Me(e){let t=e.trackingCode??e.siteId??``;return[{targetPath:`app/root.tsx`,anchorKind:`head-tag`,code:`<script defer data-id="${t}" data-allow-localhost="true" src="https://api.zenovay.com/z.js"></script>`,description:`Inline the Zenovay tracker <script> inside the document <head>.`}]}const Ne={id:`remix`,displayName:`Remix`,detect:je,files:[{path:`app/root.tsx`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:Me};async function Pe(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json found.`};try{let e=JSON.parse(t),n=!!(e.dependencies?.[`@sveltejs/kit`]??e.devDependencies?.[`@sveltejs/kit`]);return n?{matched:!0,confidence:.95,reason:"Detected SvelteKit via `@sveltejs/kit` dependency."}:{matched:!1,confidence:0,reason:"`@sveltejs/kit` not in dependencies."}}catch{return{matched:!1,confidence:0,reason:`package.json is not valid JSON.`}}}function Fe(e){let t=e.trackingCode??e.siteId??``,n=`<svelte:head>
|
|
38
|
-
<script defer data-id="${t}" data-allow-localhost="true" src="https://api.zenovay.com/z.js"></script>
|
|
39
|
-
</svelte:head>
|
|
40
|
-
|
|
41
|
-
<slot />
|
|
42
|
-
`;return[{targetPath:`src/routes/+layout.svelte`,anchorKind:`replace-file`,code:n,description:`Root layout that loads the Zenovay tracker in every route via <svelte:head>.`}]}const Ie={id:`sveltekit`,displayName:`SvelteKit`,detect:Pe,files:[{path:`src/routes/+layout.svelte`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:Fe},Le=[ge,Se,Ee,Ie,ue,Ne,Ae];async function G(e){let t=[];for(let n of Le){let r=await n.detect(e);t.push({adapter:n,result:r})}let n=[...t].sort((e,t)=>t.result.confidence-e.result.confidence),r=n[0],i=r&&r.result.matched?r.adapter:null;return{adapter:i,ranked:n}}function K(e){let t=t=>p.resolve(e,t);return{cwd:e,async readFile(e){try{return await m.readFile(t(e),`utf8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`EISDIR`)return null;throw e}},async exists(e){try{return await m.access(t(e)),!0}catch{return!1}},async glob(t){return E(t,{cwd:e,dot:!1,gitignore:!0,onlyFiles:!0,followSymbolicLinks:!1})}}}async function q(e,t){let n=K(e),{adapter:r,ranked:i}=await G(n),a=i[0];return r&&a&&a.result.confidence>=.7?r:t?t.pickInteractively(i):r}function Re(e,t){let n=/[\s"'#=]/.test(t)||t===``,r=n?`"${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:t;return`${e}=${r}`}function ze(e){let t=new Set;for(let n of e.split(/\r?\n/)){let e=n.trim();if(!e||e.startsWith(`#`))continue;let r=e.indexOf(`=`);if(r<=0)continue;let i=e.slice(0,r).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(i)&&t.add(i)}return t}async function J(e,t,n={}){let r=n.filename??`.env.local`,i=p.resolve(e,r),a=``,o=!0;try{a=await m.readFile(i,`utf8`)}catch(e){if(e.code===`ENOENT`)o=!1;else throw e}let s=o?ze(a):new Set,c=[],l=[],u=[];for(let[e,n]of Object.entries(t)){if(s.has(e)){l.push(e);continue}u.push(Re(e,n)),c.push(e)}if(c.length===0)return{created:!1,existing:o,addedKeys:c,skippedKeys:l};let d=`# Added by Zenovay CLI`,f;if(o){let e=a.length>0&&!a.endsWith(`
|
|
43
|
-
`);f=a+(e?`
|
|
44
|
-
`:``)+`
|
|
45
|
-
`+d+`
|
|
46
|
-
`+u.join(`
|
|
47
|
-
`)+`
|
|
48
|
-
`}else f=d+`
|
|
49
|
-
`+u.join(`
|
|
50
|
-
`)+`
|
|
51
|
-
`;if(o)await m.writeFile(i,f,`utf8`);else{let e=await m.open(i,`w`,384);try{await e.writeFile(f,`utf8`)}finally{await e.close()}}return{created:!o,existing:o,addedKeys:c,skippedKeys:l}}const Be=`https://api.zenovay.com/mcp`,Ve=T.object({url:T.string().url(),headers:T.record(T.string(),T.string()).optional()}),He=T.object({mcpServers:T.record(T.string(),Ve).optional()}).passthrough();function Ue(e){return e.HOME??e.USERPROFILE??w.homedir()}function We(e){return e.APPDATA??null}function Ge(e,t){let n=Ue(t),r=We(t),i=[];return i.push({id:`cursor`,displayName:`Cursor`,configPath:p.join(n,`.cursor`,`mcp.json`)}),e===`win32`&&r&&i.push({id:`cursor`,displayName:`Cursor (AppData)`,configPath:p.join(r,`Cursor`,`User`,`globalStorage`,`cursor.mcp`,`mcp.json`)}),e===`darwin`?i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:p.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`)}):e===`win32`&&r?i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:p.join(r,`Claude`,`claude_desktop_config.json`)}):i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:p.join(n,`.config`,`Claude`,`claude_desktop_config.json`)}),i.push({id:`vscode`,displayName:`VS Code`,configPath:p.join(n,`.vscode`,`mcp.json`)}),i}async function Ke(e){try{return await m.access(e),!0}catch{return!1}}async function qe(e){try{let t=await m.readFile(e,`utf8`);if(t.trim().length===0)return{};let n=JSON.parse(t),r=He.safeParse(n);return r.success?r.data:n&&typeof n==`object`?n:{}}catch{return{}}}function Je(e){return{url:Be,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=Je(e.accessToken);for(let e of Ge(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 Ke(e.configPath);if(!t){a.push(e.displayName);continue}let n=await qe(e.configPath),r=`${e.configPath}.bak`;await m.copyFile(e.configPath,r);let o={...n,mcpServers:{...n.mcpServers??{},zenovay:c}};await m.mkdir(p.dirname(e.configPath),{recursive:!0}),await m.writeFile(e.configPath,JSON.stringify(o,null,2)+`
|
|
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 Ye(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 Xe=T.object({path:T.string().min(1)}),Ze=T.object({path:T.string().min(1),content:T.string(),reason:T.string().min(1)}),Qe=T.object({path:T.string().min(1),patch:T.string().min(1),reason:T.string().min(1)}),$e=T.object({}),et=T.object({question:T.string().min(1),choices:T.array(T.string()).optional()});async function tt(e,t){let n=Xe.safeParse(t);if(!n.success)return{ok:!1,content:null,error:`invalid_args`};try{let t=await e.safeRead(n.data.path),r=W.scrubSecrets(t);return{ok:!0,content:W.wrapForModel(n.data.path,r)}}catch(e){return{ok:!1,content:null,error:e.message}}}async function nt(e,t,n){let r=Ze.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 rt(e,t,n){let r=Qe.safeParse(t);if(!r.success)return{ok:!1,content:null,error:`invalid_args`};let{path:i,patch:a,reason:o}=r.data,s;try{s=await e.safeRead(i)}catch(e){return{ok:!1,content:null,error:e.message}}let c=ee(s,a);return c===!1||typeof c!=`string`?{ok:!1,content:null,error:`patch_did_not_apply_cleanly`}:nt(e,{path:i,content:c,reason:o},n)}async function it(e){try{let t=K(e),{adapter:n,ranked:r}=await G(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 at(e,t){let n=et.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 ot(e){let{api:t,sandbox:n,approval:i,prompter:a,handlers:o}=e,s=[...e.initialMessages],c=``,l=0;for(;l<V;){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 r(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 st(e.name,e.arguments,{sandbox:n,cwd:n.cwd,approval:i,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 st(e,t,n){switch(e){case`read_file`:return tt(n.sandbox,t);case`write_file`:return nt(n.sandbox,t,n.approval);case`patch_file`:return rt(n.sandbox,t,n.approval);case`detect_framework`:return it(n.cwd);case`ask_user`:return at(n.prompter,t);default:return{ok:!1,content:null,error:`unknown_tool:${e}`}}}function ct(){let e=[12,15,18,22,28,35,41,50,58,64,72,78],t=f(e,24);return[` ↑`,` ${t}`,` └────────────────────────`,` May Jun Jul Aug Sep`]}function lt(){return[` Landing page ████████████████████ 100%`,` ↓ -28%`,` Pricing ██████████████░░░░░░ 72%`,` ↓ -50%`,` Checkout ███████░░░░░░░░░░░░░ 36%`,` ↓ -64%`,` Purchased ███░░░░░░░░░░░░░░░░░ 13%`]}function ut(){return[` ▇▇▇▇▇▇▇▇▇▎ 89 Sarah K. /pricing 🇺🇸`,` ▇▇▇▇▇▇░░░░ 61 anon /docs 🇩🇪`,` ▇▇▇░░░░░░░ 34 anon /changelog 🇯🇵`]}function dt(){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:ct},{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:lt},{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:ut},{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:dt},{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.`]}],ft=8e3,pt=({width:e,height:t})=>{let[n,r]=C(0);x(()=>{let e=setInterval(()=>{r(e=>(e+1)%X.length)},ft);return()=>clearInterval(e)},[]);let i=X[n],a=i.visual?i.visual():[],o=X.map((e,t)=>t===n?`●`:`·`).join(` `);return b.createElement(h,{flexDirection:`column`,width:e,height:t,paddingX:2,paddingY:1},b.createElement(h,{marginBottom:1},b.createElement(g,{color:`magentaBright`,bold:!0},`Learn`)),b.createElement(h,{marginBottom:1},b.createElement(g,{bold:!0,color:`white`},i.title)),i.body.map((e,t)=>b.createElement(g,{key:t,color:`gray`},e||` `)),a.length>0&&b.createElement(h,{flexDirection:`column`,marginTop:1},a.map((e,t)=>b.createElement(g,{key:t,color:`cyan`},e))),b.createElement(h,{flexGrow:1}),b.createElement(h,{marginTop:1},b.createElement(g,{color:`gray`,dimColor:!0},o,` · `,n+1,` / `,X.length)))},mt={pending:`·`,active:`⠋`,done:`✓`,error:`✗`},ht={pending:`gray`,active:`magenta`,done:`green`,error:`red`},gt=({tasks:e,width:t,height:n,liveLine:r})=>{let i=e.filter(e=>e.status===`done`).length;return b.createElement(h,{flexDirection:`column`,width:t,height:n,paddingX:2,paddingY:1},b.createElement(h,{marginBottom:1},b.createElement(g,{color:`magentaBright`,bold:!0},`Tasks`)),e.map(e=>b.createElement(h,{key:e.id,flexDirection:`column`},b.createElement(h,null,e.status===`active`?b.createElement(g,{color:`magenta`},b.createElement(D,{type:`dots`})):b.createElement(g,{color:ht[e.status]},mt[e.status]),b.createElement(g,null,` `),b.createElement(g,{color:e.status===`pending`?`gray`:`white`},e.label)),e.detail&&b.createElement(h,{paddingLeft:2},b.createElement(g,{color:`gray`,dimColor:!0},e.detail)))),b.createElement(h,{flexGrow:1}),r&&b.createElement(h,{marginTop:1},b.createElement(g,{color:`cyan`},`◆ `),b.createElement(g,{color:`white`},r)),b.createElement(h,{marginTop:1},b.createElement(g,{color:`gray`,dimColor:!0},i,` / `,e.length)))};async function _t(e){return a(e)?vt(e):new Promise(t=>{let{unmount:n,waitUntilExit:r}=_(b.createElement(yt,{opts:e,onExit:e=>{n(),t(e)}}));r().catch(()=>t(1))})}async function vt(r){try{let a=await e(),o=await q(r.cwd);if(!o)return i({type:`error`,code:`no_framework`,message:`Could not detect framework (headless mode has no picker).`}),2;i({type:`framework.detected`,framework:o.id,confidence:1});let s=await n({strict:!1});if(!s&&!process.env.ZENOVAY_API_TOKEN)return i({type:`error`,code:`not_logged_in`,message:"Run `zenovay login` first (or set ZENOVAY_API_TOKEN)."}),2;let c=new t({config:a,cliVersion:r.cliVersion,token:s}),l=await c.getSites(),u=r.siteId?l.find(e=>e.id===r.siteId):l[0];if(!u&&r.siteId)return i({type:`error`,code:`site_not_found`,message:`Site ${r.siteId} not found.`}),2;if(!u)return i({type:`error`,code:`no_site`,message:`No sites exist; create one at app.zenovay.com or re-run interactively.`}),2;i({type:`info`,message:`Using site ${u.id} (${u.name}) trackingCode=${u.trackingCode??u.id}`});let d=await J(r.cwd,{[o.envVarName]:u.trackingCode??u.id});return i({type:`info`,message:`env vars added: ${d.addedKeys.join(`,`)}`}),i({type:`done`,command:`init`,exitCode:0}),0}catch(e){return i({type:`error`,code:`init_failed`,message:e.message}),1}}const yt=({opts:r,onExit:i})=>{let{exit:a}=v(),[l,d]=C(`intro`),[f,p]=C(null),[m,_]=C([]),[y,w]=C(null),[T,E]=C(null),[O,k]=C(null),[ee,A]=C([]),[j,M]=C(void 0),[N,P]=C(null),[F,I]=C(0),L=S(!1);return x(()=>(process.stdout.isTTY&&process.stdout.write(`\x1B[?1049h\x1B[H`),()=>{process.stdout.isTTY&&process.stdout.write(`\x1B[?1049l`)}),[]),x(()=>{L.current||(L.current=!0,(async()=>{try{d(`detecting`);let i=await q(r.cwd);if(!i){k(`Could not detect your framework. Supported: Next.js, Nuxt, SvelteKit, Astro, Remix, plain HTML.`),d(`error`);return}p(i);let a=await n({strict:!1});!process.env.ZENOVAY_API_TOKEN&&!a&&(d(`login`),await o({cliVersion:r.cliVersion})),d(`loading-sites`);let s=await e(),c=await n({strict:!1}),l=new t({config:s,cliVersion:r.cliVersion,token:c}),u=await l.getSites(),f=await Mt(r.cwd),m=Nt(u,f);if(_(u),w(f),u.length===0){d(`create-site`);return}if(r.siteId){let e=u.find(e=>e.id===r.siteId);if(!e){k(`Site ${r.siteId} not found in your account.`),d(`error`);return}E(e),Z(e,i,r,{setPhase:d,setErrorMsg:k,setTasks:A,setLiveLine:M,setSandboxStats:P});return}if(r.yes&&m){E(m),Z(m,i,r,{setPhase:d,setErrorMsg:k,setTasks:A,setLiveLine:M,setSandboxStats:P});return}d(`site-picker`)}catch(e){k(e.message),d(`error`)}})())},[]),x(()=>{process.stdout.isTTY&&process.stdout.write(`\x1B[2J\x1B[H`),l===`success`&&setTimeout(()=>{a(),i(0)},1500),l===`error`&&setTimeout(()=>{a(),i(1)},8e3)},[l]),b.createElement(h,{flexDirection:`column`},b.createElement(c,{version:r.cliVersion,subtitle:`AI install wizard`}),l===`intro`&&b.createElement(bt,null),l===`detecting`&&b.createElement(s,{title:`Scanning`,state:`busy`},b.createElement(h,null,b.createElement(g,{color:`magenta`},b.createElement(D,{type:`dots`})),b.createElement(g,null,` Detecting framework…`))),l===`login`&&b.createElement(s,{title:`Authenticating`,state:`busy`},b.createElement(g,null,`Opening browser for login… (paste ZENOVAY_API_TOKEN env var to skip)`)),l===`loading-sites`&&b.createElement(s,{title:`Loading your sites`,state:`busy`},b.createElement(h,null,b.createElement(g,{color:`magenta`},b.createElement(D,{type:`dots`})),b.createElement(g,null,` Fetching your Zenovay sites…`))),l===`site-picker`&&f&&b.createElement(St,{sites:m,preselectHint:y,onPick:e=>{if(e===`create-new`){d(`create-site`);return}E(e),Z(e,f,r,{setPhase:d,setErrorMsg:k,setTasks:A,setLiveLine:M,setSandboxStats:P})}}),l===`create-site`&&b.createElement(s,{title:`Create a new site`,state:`warn`},b.createElement(g,{color:`yellow`},"No site picked (or none exist yet). Visit https://app.zenovay.com/websites to create one, then re-run `zenovay init`."),b.createElement(g,{color:`gray`},`(Inline site creation from the CLI is scheduled for V1.1 — it requires a plan-limit check.)`)),l===`agent`&&f&&T&&b.createElement(xt,{adapter:f,site:T,tasks:ee,liveLine:j}),l===`install-complete`&&f&&T&&b.createElement(wt,{adapter:f,site:T,stats:N,onCommit:()=>d(`commit-prompt`),onSkipCommit:()=>d(`deploy-prompt`)}),l===`commit-prompt`&&T&&b.createElement(Tt,{cwd:r.cwd,onDone:e=>{e.committed&&M(`Pushed ${e.shortSha} to ${e.branch}`),d(`deploy-prompt`)},onError:e=>{k(e),d(`error`)}}),l===`deploy-prompt`&&T&&b.createElement(Et,{site:T,onDeployed:()=>d(`visit-prompt`),onSkip:()=>d(`verify`)}),l===`visit-prompt`&&T&&b.createElement(Dt,{site:T,onContinue:()=>d(`verify`)}),l===`verify`&&T&&b.createElement(kt,{site:T,elapsed:F,onTick:e=>I(e),onArrived:()=>d(`success`),onTimeout:()=>d(`success`)}),l===`success`&&f&&T&&b.createElement(Ct,{adapter:f,site:T,stats:N}),l===`error`&&b.createElement(s,{title:`Install failed`,state:`err`},b.createElement(g,{color:`red`},O??`Unknown error`)),b.createElement(u,{items:[{key:`q`,label:`quit`},{key:`ctrl-c`,label:`abort`}]}))};async function Z(r,i,a,o){try{o.setPhase(`agent`);let s=await e(),c=await n({strict:!1}),l=new t({config:s,cliVersion:a.cliVersion,token:c}),u=new W({cwd:a.cwd}),d=r.trackingCode??r.id,f=await I(a.cwd,d);if(f.recommendation===`no-op`){o.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:`done`,detail:`already installed correctly`}:e)),o.setLiveLine(f.summary),o.setSandboxStats?.({reads:0,writes:0,rounds:0}),!a.skipMcp&&c&&await Y({accessToken:c.accessToken}).catch(()=>void 0),o.setPhase(`install-complete`);return}f.competitors.length>0&&o.setLiveLine(`Detected ${f.competitors.map(e=>e.name).join(`, `)} — will install Zenovay alongside (won't touch their tags).`);let p=i.buildSnippets({trackingCode:d,siteId:r.id}),m=`Install Zenovay tracking into this ${i.displayName} project.\nSite: ${r.name} (trackingCode: ${d}).\n1. Call detect_framework to confirm the framework.\n2. Read the entry file(s) for this framework:\n`+i.files.map(e=>` - ${e.path}`).join(`
|
|
53
|
-
`)+`
|
|
54
|
-
3. Insert the tracker using the snippet below.
|
|
55
|
-
4. Confirm the change with a diff before writing.
|
|
56
|
-
|
|
57
|
-
Snippet reference (anchored by anchorKind — adapt to the actual file):
|
|
58
|
-
`+p.map(e=>` ${e.anchorKind} @ ${e.targetPath}:\n ${e.code.replace(/\n/g,`
|
|
59
|
-
`)}`).join(`
|
|
60
|
-
|
|
61
|
-
`);o.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 h=(e,t,n)=>{o.setTasks(r=>r.map(r=>r.id===e?{...r,status:t,detail:n??r.detail}:r))},g=null;try{await ot({api:l,sandbox:u,approval:{async approve(){return`y`}},prompter:{async ask({question:e}){return e}},handlers:{onToolStart:({name:e})=>{e===`detect_framework`?(h(`detect`,`active`),o.setLiveLine(`Inspecting package.json + config files…`)):e===`read_file`?(h(`detect`,`done`),h(`read`,`active`)):(e===`write_file`||e===`patch_file`)&&(h(`read`,`done`),h(`write`,`active`))},onToolResult:({name:e,result:t})=>{let n=t?.ok!==!1,r=t?.content??{};e===`detect_framework`&&n&&(h(`detect`,`done`,i.displayName),o.setLiveLine(`Detected ${i.displayName}`)),e===`read_file`&&n&&r.path&&o.setLiveLine(`Read ${r.path}`),(e===`write_file`||e===`patch_file`)&&n&&r.path&&o.setLiveLine(`Wrote ${r.path}`)},onDelta:e=>{let t=e.replace(/\s+/g,` `).trim();t.length>4&&o.setLiveLine(t.slice(0,80))}},initialMessages:[{role:`user`,content:m}],diagnosis:f,targetTrackingCode:d})}catch(e){g=e}let _=u.stats();if(_.writes===0){let e=g?`Agent error: ${g.message}`:`Agent returned without writing any files (${_.reads} reads, ${_.rounds} rounds). The model may have refused or the AI Gateway may be misconfigured. Check api.zenovay.com logs.`;throw Error(e)}h(`write`,`done`),h(`env`,`active`),o.setLiveLine(`Adding env var to .env.local`);let v=await J(a.cwd,{[i.envVarName]:d});if(h(`env`,`done`,`${v.addedKeys.length} key(s) added`),!a.skipMcp&&c){h(`mcp`,`active`),o.setLiveLine(`Detecting Cursor / Claude Desktop / VS Code…`);let e=await Y({accessToken:c.accessToken}).catch(()=>null);e&&e.installed.length>0?h(`mcp`,`done`,e.installed.join(`, `)):h(`mcp`,`done`,`none detected`)}else h(`mcp`,`done`,`skipped`);o.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:e.status===`pending`?`done`:e.status}:e)),o.setLiveLine(void 0),o.setSandboxStats?.(_),o.setPhase(`install-complete`)}catch(e){o.setErrorMsg(e.message),o.setPhase(`error`)}}const bt=()=>b.createElement(s,{title:`Zenovay wants to set up your project`,state:`idle`},b.createElement(g,null,`We'll use AI to analyze your codebase and add the Zenovay tracker.`),b.createElement(g,{color:`gray`},`.env* contents stay on your machine. Only framework metadata reaches api.zenovay.com.`)),xt=({adapter:e,site:t,tasks:n,liveLine:r})=>{let i=process.stdout.columns??100,a=(process.stdout.rows??30)-6,o=Math.floor(i/2)-1,s=Math.max(14,a);return b.createElement(h,{flexDirection:`column`},b.createElement(h,{flexDirection:`row`,height:s,borderStyle:`round`,borderColor:`gray`},b.createElement(h,{width:o,flexDirection:`column`},b.createElement(pt,{width:o,height:s})),b.createElement(h,{width:1,flexDirection:`column`,height:s},b.createElement(g,{color:`gray`},`│`)),b.createElement(h,{width:o,flexDirection:`column`},b.createElement(gt,{tasks:n,liveLine:r,width:o,height:s}))),b.createElement(h,{marginTop:1},b.createElement(g,{color:`gray`},`Site: `,t.name,` · code: `,t.trackingCode??t.id,` · Framework: `,e.displayName)))},St=({sites:e,preselectHint:t,onPick:n})=>{let r=Nt(e,t),i=e.filter(e=>e.id!==r?.id),a=r?[r,...i]:i,o=[...a.map(e=>({label:jt(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 b.createElement(s,{title:t?`Pick a site (best match: ${t})`:`Pick a site`,state:`idle`},b.createElement(d,{items:o,onSelect:n}))},Ct=({adapter:e,site:t,stats:n})=>b.createElement(s,{title:`You're live on Zenovay`,state:`ok`},b.createElement(g,null,b.createElement(l,null,`✔ Installed successfully`)),b.createElement(g,null,`Framework: `,e.displayName),b.createElement(g,null,`Site: `,t.name,` (`,t.url,`)`),t.trackingCode?b.createElement(g,{color:`gray`},`Tracker code: `,t.trackingCode):null,n?b.createElement(g,{color:`gray`},n.writes,` file(s) modified across `,n.rounds,` agent round(s)`):null,b.createElement(g,{color:`gray`},`Dashboard: https://app.zenovay.com/sites/`,t.id),b.createElement(g,{color:`gray`},"Next: `zenovay watch` for a live TUI.")),wt=({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()}),b.createElement(s,{title:`Tracker installed`,state:`ok`},b.createElement(g,null,b.createElement(l,null,`✔ `),`The Zenovay tracker is in your project.`),b.createElement(h,{marginTop:1},b.createElement(g,{color:`gray`},`Framework: `),b.createElement(g,null,e.displayName)),b.createElement(h,null,b.createElement(g,{color:`gray`},`Site: `),b.createElement(g,null,t.name,` (`,t.url,`)`)),n&&b.createElement(h,null,b.createElement(g,{color:`gray`},`Modified: `),b.createElement(g,null,n.writes,` file(s)`)),b.createElement(h,{marginTop:1},b.createElement(g,null,`Commit + push these changes to git? `),b.createElement(g,{color:`cyan`},`[Y/n]`)))),Tt=({cwd:e,onDone:t,onError:n})=>{let[r,i]=C(`committing`),[a,o]=C(`Staging changes…`);return x(()=>{(async()=>{try{let n=await At(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)}})()},[]),b.createElement(s,{title:`Committing to git`,state:`busy`},b.createElement(h,null,b.createElement(g,{color:`magenta`},b.createElement(D,{type:`dots`})),b.createElement(g,null,` `,r===`pushing`?`Pushing to origin`:`Committing`,`…`)),b.createElement(h,{marginTop:1},b.createElement(g,{color:`gray`},a)))},Et=({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()}),b.createElement(s,{title:`Ready to deploy?`,state:`idle`},b.createElement(g,null,`The tracker is installed locally. To capture events you need it on the live site:`),b.createElement(g,null,` `),b.createElement(h,null,b.createElement(g,{color:`cyan`},` → `),b.createElement(g,null,e.url)),b.createElement(g,null,` `),b.createElement(g,{color:`gray`},`Push the change through your normal deploy pipeline (Vercel auto-deploy, CI/CD, etc.).`),b.createElement(h,{marginTop:1},b.createElement(g,null,`Once it's deployed, press `),b.createElement(g,{color:`cyan`},`[Y]`),b.createElement(g,null,` to verify the tracker is firing. `),b.createElement(g,{color:`gray`},`[s] skip verification`)))),Dt=({site:e,onContinue:t})=>(Q(()=>t()),b.createElement(s,{title:`Visit your site`,state:`idle`},b.createElement(g,null,`To send a test event, open any page on your site:`),b.createElement(g,null,` `),b.createElement(h,null,b.createElement(g,{color:`cyan`},` → `),b.createElement(g,null,e.url)),b.createElement(g,null,` `),b.createElement(g,{color:`gray`},`The tracker fires automatically on page load. We'll verify the next event arrives.`),b.createElement(h,{marginTop:1},b.createElement(g,null,`Press `),b.createElement(g,{color:`cyan`},`[any key]`),b.createElement(g,null,` when you've visited the page.`))));async function Ot(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 kt=({site:r,elapsed:i,onTick:a,onArrived:o,onTimeout:c})=>{let[l,u]=C(`preflight`),[d,f]=C(``),[p,m]=C([]),_=S(!1),v=r.trackingCode??r.id,w=async()=>{u(`preflight`),f(`Fetching ${r.url}…`);let e=await Ot(r.url,v);if(!_.current){if(e.state===`tracker-correct`){u(`polling`),f(`Tracker detected on live site — waiting for first hit…`),T();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 ${r.url}: ${e.networkError}`:e.httpStatus?`${r.url} returned HTTP ${e.httpStatus}`:`No Zenovay tracker found on ${r.url}.`)}},T=async()=>{let i=Date.now();try{let s=await e(),c=await n({strict:!1}),l=new t({config:s,cliVersion:`0`,token:c}),d=await Ye(r.id,i,{api:l,timeoutMs:18e4,pollIntervalMs:2500,onTick:e=>{_.current||a(e)}});if(_.current)return;d.received?(u(`success`),o()):u(`timeout`)}catch{_.current||u(`timeout`)}};x(()=>(_.current=!1,w(),()=>{_.current=!0}),[]),y(e=>{(l===`awaiting-deploy`||l===`wrong-id-on-live`||l===`timeout`)&&(e===`r`||e===`R`?w():(e===`s`||e===`S`)&&c())},{isActive:!0});let E=Math.floor(i/1e3);return l===`preflight`?b.createElement(s,{title:`Verifying`,state:`busy`},b.createElement(h,null,b.createElement(g,{color:`magenta`},b.createElement(D,{type:`dots`})),b.createElement(g,null,` Checking your live site for the tracker…`)),b.createElement(h,{marginTop:1},b.createElement(g,{color:`gray`},d))):l===`awaiting-deploy`?b.createElement(s,{title:`Tracker not yet on your live site`,state:`warn`},b.createElement(g,{color:`yellow`},d),b.createElement(h,{marginTop:1,flexDirection:`column`},b.createElement(g,null,`The tracker is in your local repo but hasn't been deployed yet.`),b.createElement(g,{color:`gray`},`Push your changes and wait for your deploy to finish (Vercel / Cloudflare Pages / CI), then retry.`)),b.createElement(h,{marginTop:1},b.createElement(g,null,`Press `),b.createElement(g,{color:`cyan`},`[r]`),b.createElement(g,null,` to re-check, `),b.createElement(g,{color:`cyan`},`[s]`),b.createElement(g,null,` to skip verification.`))):l===`wrong-id-on-live`?b.createElement(s,{title:`Live site has a different tracking code`,state:`warn`},b.createElement(g,{color:`yellow`},`Expected: `,b.createElement(g,{color:`cyan`},v),` `,`Found on live: `,b.createElement(g,{color:`cyan`},p.join(`, `))),b.createElement(h,{marginTop:1,flexDirection:`column`},b.createElement(g,null,`Your local install uses a different ID than what's on `,r.url,`.`),b.createElement(g,{color:`gray`},`Deploy the new local version, then retry — or skip if the existing ID is intentional.`)),b.createElement(h,{marginTop:1},b.createElement(g,null,`Press `),b.createElement(g,{color:`cyan`},`[r]`),b.createElement(g,null,` to re-check, `),b.createElement(g,{color:`cyan`},`[s]`),b.createElement(g,null,` to skip.`))):l===`timeout`?b.createElement(s,{title:`No event arrived in 3 minutes`,state:`warn`},b.createElement(g,{color:`yellow`},`The tracker is on your live site but no hits reached api.zenovay.com.`),b.createElement(h,{marginTop:1},b.createElement(g,{color:`gray`},`Try opening `,r.url,` in a fresh browser tab (no ad-blocker), then retry.`)),b.createElement(h,{marginTop:1},b.createElement(g,null,`Press `),b.createElement(g,{color:`cyan`},`[r]`),b.createElement(g,null,` to re-check, `),b.createElement(g,{color:`cyan`},`[s]`),b.createElement(g,null,` to finish without verification.`))):b.createElement(s,{title:`Waiting for first event`,state:`busy`},b.createElement(h,null,b.createElement(g,{color:`magenta`},b.createElement(D,{type:`dots`})),b.createElement(g,null,` Polling api.zenovay.com for the first hit on `),b.createElement(g,{color:`cyan`},r.url),b.createElement(g,null,` (`,E,`s elapsed)`)),b.createElement(h,{marginTop:1},b.createElement(g,{color:`gray`},`Reload the page if nothing arrives within ~30 seconds.`)))};function Q(e){y((t,n)=>{e(t,{return:n.return,escape:n.escape})},{isActive:!0})}async function At(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 jt(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 Mt(e){try{let t=await m.readFile(p.join(e,`package.json`),`utf8`),n=JSON.parse(t);if(n.name)return String(n.name).replace(/^@[^/]+\//,``)}catch{}try{let t=await m.readFile(p.join(e,`.git`,`config`),`utf8`),n=t.match(/url\s*=\s*.*[/:]([^/]+?)(?:\.git)?\s*$/m);if(n&&n[1])return n[1]}catch{}return p.basename(e)}function Nt(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{te as detectInstalled,_t as initCommand};
|