@zenovay/cli 1.0.24 → 1.0.25
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,3 +1,3 @@
|
|
|
1
|
-
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-CBukwv2I.js";import{readToken as t}from"./token-store-CuZEiQNg.js";import{emit as n}from"./telemetry-BgkzI2cW.js";import{ApiV2Client as r}from"./api-v2--DPtrRGv.js";import{detectInstalled as i}from"./detect-installed-DpSaAeH-.js";import"./formatter-PBF-wEt1.js";import{emit$1 as a,isHeadless as o}from"./emit-5vELQfsB.js";import"./open-url-IjqD5f_n.js";import"./secrets-zGZxXoM0.js";import{initCommand as s}from"./init-
|
|
1
|
+
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-CBukwv2I.js";import{readToken as t}from"./token-store-CuZEiQNg.js";import{emit as n}from"./telemetry-BgkzI2cW.js";import{ApiV2Client as r}from"./api-v2--DPtrRGv.js";import{detectInstalled as i}from"./detect-installed-DpSaAeH-.js";import"./formatter-PBF-wEt1.js";import{emit$1 as a,isHeadless as o}from"./emit-5vELQfsB.js";import"./open-url-IjqD5f_n.js";import"./secrets-zGZxXoM0.js";import{initCommand as s}from"./init-BPlqfuUi.js";import{parseSseStream as c}from"./client-DNMRt-Hq.js";import"./snippet-CwowVrmh.js";import"./login-vzW-8q0w.js";import"./theme-DSRmbn9T.js";import{Banner as l,Panel as u,useTheme as d}from"./panel-DbiZwGB3.js";import"./progress-row-BSv_Zm8f.js";import{Select as f}from"./prompt-Dae2nnYJ.js";import"./keybar-BY1csJGI.js";import"./sparkline-B7VaYaxH.js";import{ChatPanel as p}from"./chat-panel-DKVM8gnJ.js";import{resolveSiteId as m}from"./resolve-site-D8PIddP1.js";import{Box as h,Static as g,Text as _,render as v,useApp as y,useInput as ee}from"ink";import b,{useEffect as x,useRef as S,useState as C}from"react";import w from"ink-spinner";import T from"ink-text-input";const E=30,D=9e4;function O(e){return e.replace(/_/g,` `)}function k(e){if(!e)return``;let t=Object.entries(e).map(([e,t])=>`${e}: ${JSON.stringify(t)}`).join(`, `);return t.length>80?t.slice(0,77)+`…`:t}function A(e,t,n){if(t<=0)return{body:``,clipped:0};let r=e.split(`
|
|
2
2
|
`),i=[];for(let e of r)if(e.length<=n||n<=0)i.push(e);else for(let t=0;t<e.length;t+=n)i.push(e.slice(t,t+n));if(i.length<=t)return{body:e,clipped:0};let a=i.slice(i.length-t);return{body:a.join(`
|
|
3
3
|
`),clipped:i.length-t}}const j=({cliVersion:e,api:t,siteId:r,siteLabel:i,initialAllowAll:a=!1,onClose:o})=>{let{theme:s}=d(),{exit:f}=y(),[p,m]=C([]),[v,j]=C(``),[M,N]=C(!1),[P,F]=C(``),[I,L]=C([]),[R,z]=C(null),[B,V]=C(a),[H,U]=C(!1),[W,G]=C(0),K=S(``),q=S(null),J=S(Date.now());x(()=>{if(!M)return;let e=setInterval(()=>{K.current!==P&&F(K.current)},Math.floor(1e3/E));return()=>clearInterval(e)},[M,P]),x(()=>(n(`mcp.open`,{properties:{has_site:!!r}}),()=>{n(`mcp.close`,{duration_ms:Date.now()-J.current})}),[r]),ee((e,t)=>{if(t.escape||t.ctrl&&e===`c`){q.current?.abort(),o();return}if(e===`a`||e===`A`){V(!0),H&&U(!1);return}if(e===`x`||e===`X`){q.current?.abort(),z(`Cancelled.`),U(!1),N(!1);return}if((t.return||e===`y`||e===`Y`)&&H){U(!1);return}if((e===`n`||e===`N`)&&H){q.current?.abort(),z(`Cancelled by user.`),U(!1),N(!1);return}});let Y=async e=>{let i=e.trim();if(!i||M||H)return;j(``),z(null),m(e=>[...e,{role:`user`,content:i}]),K.current=``,F(``),L([]),G(0),N(!0),q.current=new AbortController;let a=setTimeout(()=>{q.current?.abort(),z(`Request timed out after ${D/1e3}s`)},D);try{let e=p.map(e=>({role:e.role,content:e.content}));e.push({role:`user`,content:i});let a=await t.openAiStream(`mcp`,{messages:e,siteId:r},q.current.signal);if(!a.ok){z(`MCP request failed (${a.status})`);return}let o=0,s=new Map;for await(let e of c(a))if(e.type===`delta`)K.current+=e.content;else if(e.type===`tool_call`)s.set(e.id,e.arguments),o+=1,G(o),n(`mcp.tool_call`,{properties:{tool_name:e.name}}),L(t=>[...t,{id:e.id,name:e.name,argsPreview:k(e.arguments),status:`running`}]);else if(e.type===`tool_start`){let t=s.get(e.id);L(r=>r.some(t=>t.id===e.id)?r:(o+=1,G(o),n(`mcp.tool_call`,{properties:{tool_name:e.name}}),[...r,{id:e.id,name:e.name,argsPreview:k(t),status:`running`}]))}else if(e.type===`tool_result`)L(t=>t.map(t=>t.id===e.id?{...t,status:e.error?`error`:`done`,result:e.summary,error:e.error,name:e.name??t.name}:t));else if(e.type===`done`){let e=K.current;m(t=>[...t,{role:`assistant`,content:e||``}]),o>0&&!B&&U(!0);break}else if(e.type===`error`){z(e.message);break}}catch(e){e.name!==`AbortError`&&z(e.message??`unknown error`)}finally{clearTimeout(a),K.current=``,F(``),N(!1),q.current=null}},X=[`mcp`,i].filter(Boolean).join(` · `),Z=process.stdout.rows??40,Q=Math.max(4,Z-16),te=Math.max(20,(process.stdout.columns??80)-4),$=A(P,Q,te);return b.createElement(h,{flexDirection:`column`},b.createElement(l,{version:e,subtitle:X}),p.length===0&&!M?b.createElement(h,{marginTop:1,marginLeft:2,flexDirection:`column`},b.createElement(_,{color:s.muted},`Describe what you want to create or change. Examples:`),b.createElement(h,{marginTop:0,flexDirection:`column`},b.createElement(_,{color:s.dim},` · "Create a goal for newsletter signups"`),b.createElement(_,{color:s.dim},` · "Add a funnel: landing page → signup → dashboard"`),b.createElement(_,{color:s.dim},` · "Annotate today with our product launch"`),b.createElement(_,{color:s.dim},` · "Set up uptime monitoring for /api/health"`)),b.createElement(h,{marginTop:1},b.createElement(_,{color:s.dim},`MCP actions execute server-side. `),b.createElement(_,{color:s.warn},`Review each turn before continuing.`)),b.createElement(h,{marginTop:0,flexDirection:`row`},b.createElement(_,{color:s.accent},`[a]`),b.createElement(_,{color:s.dim},` allow-all · `),b.createElement(_,{color:s.accent},`[Esc]`),b.createElement(_,{color:s.dim},` close`))):null,b.createElement(g,{items:p},(e,t)=>b.createElement(h,{key:t,marginTop:1},b.createElement(u,{title:e.role===`user`?`you`:`Zenovay MCP`,pillColor:e.role===`user`?s.accent:s.info,state:`idle`},b.createElement(_,{color:s.fg,wrap:`wrap`},e.content)))),M?b.createElement(h,{flexDirection:`column`},I.length>0?b.createElement(h,{marginTop:1},b.createElement(u,{title:`Actions${B?` (allow-all)`:``}`,state:I.some(e=>e.status===`running`)?`busy`:`ok`},I.map(e=>b.createElement(h,{key:e.id,flexDirection:`column`,marginBottom:0},b.createElement(h,{flexDirection:`row`},b.createElement(_,{color:e.status===`error`?s.error:e.status===`done`?s.success:s.accent},e.status===`done`?`✓ `:e.status===`error`?`✗ `:`⋯ `),b.createElement(_,{color:s.fg,bold:!0},O(e.name))),e.argsPreview?b.createElement(h,{marginLeft:2},b.createElement(_,{color:s.dim},e.argsPreview)):null,e.status===`done`&&e.result?b.createElement(h,{marginLeft:2},b.createElement(_,{color:s.dim},`→ `,e.result.slice(0,80))):null,e.status===`error`&&e.error?b.createElement(h,{marginLeft:2},b.createElement(_,{color:s.error},`✗ `,e.error.slice(0,80))):null)))):null,P.length>0?b.createElement(h,{marginTop:1},b.createElement(u,{title:`Zenovay MCP`,pillColor:s.info,state:`busy`},$.clipped>0?b.createElement(_,{color:s.dim},` …${$.clipped} earlier line${$.clipped===1?``:`s`} above`):null,b.createElement(_,{color:s.fg,wrap:`wrap`},$.body))):I.every(e=>e.status!==`running`)||I.length===0?b.createElement(h,{marginTop:1,marginLeft:2,flexDirection:`row`},b.createElement(_,{color:s.accent},b.createElement(w,{type:`dots`})),b.createElement(_,{color:s.muted},` Planning actions…`)):null):null,H&&!M?b.createElement(h,{marginTop:1},b.createElement(u,{title:`Continue?`,state:`warn`,pillColor:s.warn},b.createElement(_,{color:s.muted},W,` action`,W===1?``:`s`,` executed this turn. Send another message?`),b.createElement(h,{marginTop:1,flexDirection:`row`},b.createElement(_,{color:s.success},`[Enter / y] `),b.createElement(_,{color:s.dim},`continue `),b.createElement(_,{color:s.error},`[n] `),b.createElement(_,{color:s.dim},`cancel `),b.createElement(_,{color:s.accent},`[a] `),b.createElement(_,{color:s.dim},`allow-all this session `),b.createElement(_,{color:s.warn},`[x] `),b.createElement(_,{color:s.dim},`abort`)))):null,R?b.createElement(h,{marginTop:1,marginLeft:2},b.createElement(_,{color:s.error},`✗ `,R)):null,b.createElement(h,{marginTop:1,marginLeft:2,flexDirection:`column`},b.createElement(h,{flexDirection:`row`},b.createElement(_,{color:M||H?s.dim:s.accent},M?`⋯ `:H?`? `:`> `),b.createElement(T,{value:v,onChange:j,onSubmit:e=>void Y(e),placeholder:M?`executing…`:H?`press Enter to continue, n to cancel…`:`describe what to create or change…`})),b.createElement(h,{marginTop:1,flexDirection:`row`},b.createElement(_,{color:s.dim},`[Enter] send [a] allow-all [x] abort [Esc] close`),B?b.createElement(_,{color:s.success},` ● allow-all`):null)))};async function M(e){if((o(e)||!process.stdin.isTTY)&&e.mode!==`install`)return a({type:`error`,code:`interactive_only`,message:`zenovay ai is interactive; run without --json in a TTY`}),2;let t=await i(e.cwd),n;if(e.mode)n=e.mode;else if(!t.installed)n=`install`;else if(o(e))return a({type:`error`,code:`no_mode`,message:`Headless mode requires --mode chat|mcp|install`}),2;else n=await N(t,e.cliVersion);return n===`install`?s({cliVersion:e.cliVersion,cwd:e.cwd,json:e.json}):n===`chat`?P(e):F(e)}async function N(e,t){return new Promise(n=>{let r=[{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`}],i=e.packageMarker?`detected · ${e.packageMarker}`:`detected`,{unmount:a}=v(b.createElement(h,{flexDirection:`column`},b.createElement(l,{version:t,subtitle:`ai · ${i}`,live:!1}),b.createElement(h,{marginTop:1},b.createElement(u,{title:`Zenovay AI assistant`,state:`idle`},b.createElement(_,null,`What do you want to do?`))),b.createElement(h,{marginTop:1},b.createElement(f,{items:r,onSelect:e=>{a(),n(e)}}))))})}async function P(n){let i=await e(),a=await t({strict:!1});if(!a)return process.stderr.write("Not logged in — run `zenovay login` first.\n"),2;let o=i.defaultSiteId,s=i.defaultSiteName,c=new r({config:i,cliVersion:n.cliVersion,token:a});return new Promise(e=>{let{unmount:t}=v(b.createElement(p,{cliVersion:n.cliVersion,api:c,dashboardContext:{commandName:`ai chat`,siteId:o,siteLabel:s,metricsSnapshot:null},onClose:()=>{t(),e(0)}}))})}async function F(n){let i=await e(),a=await t({strict:!1});if(!a)return process.stderr.write("Not logged in — run `zenovay login` first.\n"),2;let o=new r({config:i,cliVersion:n.cliVersion,token:a}),s,c;try{let e=await m(o,{explicit:void 0,headless:!1,cliVersion:n.cliVersion});s=e.siteId,c=e.site?.url?e.site.url.replace(/^https?:\/\//,``).replace(/\/$/,``):e.site?.name??s}catch{}return new Promise(e=>{let{unmount:t}=v(b.createElement(j,{cliVersion:n.cliVersion,api:o,siteId:s,siteLabel:c,onClose:()=>{t(),e(0)}}))})}export{M as aiCommand};
|
package/dist/bin.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{configDir as e}from"./config-JVhBplSX.js";import"./check-D9G0N7NB.js";import{ensureLatest as t}from"./ensure-latest-CEFXfYj4.js";import"./api-CBukwv2I.js";import"./token-store-CuZEiQNg.js";import{normalizeError as n}from"./error-codes-DZnI2JsI.js";import{EXAMPLES as r}from"./examples-wBHwEUt8.js";import{emit as i,flush as a,initTelemetry as o}from"./telemetry-BgkzI2cW.js";import{cac as s}from"cac";import{fork as c}from"node:child_process";import l from"node:path";import{fileURLToPath as u}from"node:url";import{readFileSync as d}from"node:fs";var f=`@zenovay/cli`,p=`1.0.
|
|
2
|
+
import{configDir as e}from"./config-JVhBplSX.js";import"./check-D9G0N7NB.js";import{ensureLatest as t}from"./ensure-latest-CEFXfYj4.js";import"./api-CBukwv2I.js";import"./token-store-CuZEiQNg.js";import{normalizeError as n}from"./error-codes-DZnI2JsI.js";import{EXAMPLES as r}from"./examples-wBHwEUt8.js";import{emit as i,flush as a,initTelemetry as o}from"./telemetry-BgkzI2cW.js";import{cac as s}from"cac";import{fork as c}from"node:child_process";import l from"node:path";import{fileURLToPath as u}from"node:url";import{readFileSync as d}from"node:fs";var f=`@zenovay/cli`,p=`1.0.25`,m=`Zenovay CLI — AI install wizard + full terminal analytics dashboard`,h=`module`,g={zenovay:`dist/bin.js`,zv:`dist/bin.js`},_=[`dist/**/*.js`,`dist/**/*.cjs`,`dist/**/*.mjs`,`dist/**/*.d.ts`,`README.md`,`LICENSE`],v={dev:`tsx src/bin.ts`,build:`tsdown`,"build:binaries":`tsx scripts/build-binaries.ts`,typecheck:`tsc --noEmit`,lint:`eslint 'src/**/*.{ts,tsx}'`,test:`vitest run`,"test:watch":`vitest`,"test:all":`vitest run tests/unit tests/integration tests/security`,"test:release":`vitest run tests/e2e tests/update --testTimeout=600000`,"test:smoke":`vitest run tests/smoke --testTimeout=60000`,"test:update-golden":`UPDATE_GOLDEN=1 vitest run tests/e2e`,"render:globe":`tsx scripts/render-globe.ts`,smoke:`bash scripts/smoke-test.sh`},y={cac:`^6.7.14`,chalk:`^5.4.1`,diff:`^8.0.3`,globby:`^14.1.0`,ink:`^5.1.0`,"ink-gradient":`^3.0.0`,"ink-select-input":`^6.0.0`,"ink-spinner":`^5.0.0`,"ink-text-input":`^6.0.0`,open:`^10.1.0`,react:`^18.3.1`,semver:`^7.6.3`,"string-width":`^7.2.0`,ulid:`^2.3.0`,ws:`^8.18.0`,zod:`^3.23.8`},b={"@aws-sdk/client-s3":`^3.1036.0`,"@types/node":`^22.10.0`,"@types/react":`^18.3.12`,"@types/semver":`^7.5.8`,"@typescript-eslint/parser":`^8.61.0`,"@vitest/coverage-v8":`^2.1.8`,"csv-parse":`^6.2.1`,eslint:`^9.16.0`,"ink-testing-library":`^4.0.0`,"react-devtools-core":`^4.19.1`,tsdown:`^0.9.0`,tsx:`^4.19.2`,typescript:`^5.7.2`,vitest:`^2.1.8`},x={node:`>=20.0.0`},S=`pnpm@9.15.9`,C={overrides:{"ws@>=8.0.0 <8.21.0":`>=8.21.0`}},w=`Zenovay <cli@zenovay.com>`,T=`SEE LICENSE IN LICENSE`,E=`https://cli.zenovay.com`,D={type:`git`,url:`https://github.com/zenovay/cli-zenovay.git`},O={url:`https://cli.zenovay.com/feedback`},k=[`zenovay`,`analytics`,`cli`,`tui`,`ai-agent`,`install-wizard`],A={name:f,version:p,description:m,type:h,bin:g,files:_,scripts:v,dependencies:y,devDependencies:b,engines:x,packageManager:S,pnpm:C,author:w,license:T,homepage:E,repository:D,bugs:O,keywords:k};const j=l.dirname(u(import.meta.url)),M=A.version,N=process.argv[0]??`zenovay`;function P(){if(process.env.ZENOVAY_BACKGROUND_UPDATE===`1`&&!(process.env.ZENOVAY_NO_UPDATE_CHECK===`1`||process.env.CI===`true`))try{let e=l.join(j,`lib`,`update`,`worker.js`),t=c(e,[],{detached:!0,stdio:`ignore`,env:{...process.env,ZENOVAY_UPDATE_WORKER_FORK:`1`}});t.unref()}catch{}}const F=s(`zenovay`);F.version(M);const I=[`ANALYTICS`,`BEHAVIOR`,`INTELLIGENCE`,`OPERATIONS`,`MANAGE`,`ACCOUNT`];function L(e){let t=/\[([A-Z]+)\]/.exec(e),n=t?I.indexOf(t[1]??``):-1;return n===-1?I.length:n}F.help(e=>{let t=e.filter(e=>{let t=e.title??``;return!/for more info/i.test(t)}),n=t.find(e=>e.title===`Commands`);n&&typeof n.body==`string`&&(n.body=n.body.split(`
|
|
3
3
|
`).map((e,t)=>({line:e,i:t,rank:L(e)})).sort((e,t)=>e.rank-t.rank||e.i-t.i).map(e=>e.line).join(`
|
|
4
|
-
`));let r=F.matchedCommand;return r?.description&&t.splice(1,0,{body:` ${r.description}`}),t.push({body:"Run `zenovay <command> --help` for command-specific options and examples."}),t}),F.option(`-q, --quiet`,`Suppress spinners + interactive UI; implies --json`),F.option(`--team <id>`,"Team override for this command — id only (use `zenovay teams switch <name>` for name lookup)"),(process.argv.includes(`-q`)||process.argv.includes(`--quiet`))&&(process.env.ZENOVAY_FORMAT=`json`,process.argv.includes(`--json`)||process.argv.push(`--json`));let R;for(let e=0;e<process.argv.length;e++){let t=process.argv[e];if(!t)continue;if(t===`--team`){R=process.argv[e+1];break}let n=/^--team=(.+)$/.exec(t);if(n){R=n[1];break}}if(R&&(process.env.ZENOVAY_TEAM_ID=R),!process.env.ZENOVAY_TEAM_ID)try{let t=l.join(e(),`config.json`),n=d(t,`utf8`),r=JSON.parse(n);r.currentTeamId&&(process.env.ZENOVAY_TEAM_ID=r.currentTeamId)}catch{}F.command(`init`,`[OPERATIONS] 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(`--review`,`Review each file write before it is applied`).option(`--skip-mcp`,`Skip MCP client install`).option(`--skip-verify`,`Skip first-event verification`).option(`--undo`,`Revert the file writes from the most recent init session`).option(`--no-first-party`,`Skip the same-origin /api/_z/* proxy setup (first-party tracking)`).option(`--host <host>`,`Deploy host for first-party tracking when it can't be auto-detected: cloudflare-pages | vercel | netlify | nextjs`).option(`--site-id <id>`,`Install for a specific site id (skips the picker)`).action(async e=>{let{initCommand:t}=await import(`./init-
|
|
4
|
+
`));let r=F.matchedCommand;return r?.description&&t.splice(1,0,{body:` ${r.description}`}),t.push({body:"Run `zenovay <command> --help` for command-specific options and examples."}),t}),F.option(`-q, --quiet`,`Suppress spinners + interactive UI; implies --json`),F.option(`--team <id>`,"Team override for this command — id only (use `zenovay teams switch <name>` for name lookup)"),(process.argv.includes(`-q`)||process.argv.includes(`--quiet`))&&(process.env.ZENOVAY_FORMAT=`json`,process.argv.includes(`--json`)||process.argv.push(`--json`));let R;for(let e=0;e<process.argv.length;e++){let t=process.argv[e];if(!t)continue;if(t===`--team`){R=process.argv[e+1];break}let n=/^--team=(.+)$/.exec(t);if(n){R=n[1];break}}if(R&&(process.env.ZENOVAY_TEAM_ID=R),!process.env.ZENOVAY_TEAM_ID)try{let t=l.join(e(),`config.json`),n=d(t,`utf8`),r=JSON.parse(n);r.currentTeamId&&(process.env.ZENOVAY_TEAM_ID=r.currentTeamId)}catch{}F.command(`init`,`[OPERATIONS] 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(`--review`,`Review each file write before it is applied`).option(`--skip-mcp`,`Skip MCP client install`).option(`--skip-verify`,`Skip first-event verification`).option(`--undo`,`Revert the file writes from the most recent init session`).option(`--no-first-party`,`Skip the same-origin /api/_z/* proxy setup (first-party tracking)`).option(`--host <host>`,`Deploy host for first-party tracking when it can't be auto-detected: cloudflare-pages | vercel | netlify | nextjs`).option(`--site-id <id>`,`Install for a specific site id (skips the picker)`).action(async e=>{let{initCommand:t}=await import(`./init-lFYuHty4.js`),n=await t({cliVersion:M,cwd:process.cwd(),json:e.json,yes:e.yes,review:e.review,skipMcp:e.skipMcp,skipVerify:e.skipVerify,undo:e.undo,firstParty:e.firstParty,host:e.host,siteId:e.siteId});process.exitCode=n}),F.command(`login`,`[OPERATIONS] 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-BD9Q3e7S.js`),n=await t({cliVersion:M,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`)}});!e.json&&n.email?process.stdout.write(`\n ✔ Logged in as ${n.email}\n Try \`zenovay overview\` to see your dashboard, or \`zenovay --help\` for the full command list.\n\n`):e.json||process.stdout.write(`
|
|
5
5
|
✔ Logged in.
|
|
6
6
|
|
|
7
|
-
`)}),F.command(`logout`,`[OPERATIONS] Revoke current session and delete local auth`).option(`--json`,``).action(async e=>{let{logoutCommand:t}=await import(`./logout-CQUoX-t4.js`);await t({cliVersion:M,json:e.json})}),F.command(`ai`,`[INTELLIGENCE] 3-mode AI assistant (install / chat / mcp)`).option(`--mode <mode>`,`install | chat | mcp`).option(`--json`,``).action(async e=>{let{aiCommand:t}=await import(`./ai-
|
|
7
|
+
`)}),F.command(`logout`,`[OPERATIONS] Revoke current session and delete local auth`).option(`--json`,``).action(async e=>{let{logoutCommand:t}=await import(`./logout-CQUoX-t4.js`);await t({cliVersion:M,json:e.json})}),F.command(`ai`,`[INTELLIGENCE] 3-mode AI assistant (install / chat / mcp)`).option(`--mode <mode>`,`install | chat | mcp`).option(`--json`,``).action(async e=>{let{aiCommand:t}=await import(`./ai-CxT9VLDB.js`),n=await t({cliVersion:M,cwd:process.cwd(),mode:e.mode,json:e.json});process.exitCode=n}),F.command(`watch`,"[ANALYTICS] Alias for `analytics` (dashboard summary)").option(`--site-id <id>`,`Site ID`).option(`--interval <ms>`,`Poll interval ms (legacy; ignored by analytics)`,{default:15e3}).option(`--json`,``).option(`--csv`,`Emit top-pages as CSV`).option(`--tsv`,`Emit top-pages as TSV`).option(`--ndjson`,`Emit top-pages as NDJSON (one row per line)`).action(async e=>{let{analyticsCommand:t}=await import(`./analytics-DnICaaM-.js`),n=await t({cliVersion:M,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),F.command(`analytics [sub]`,`[ANALYTICS] Landing dashboard — visitors, pageviews, bounce, top pages. Subs: live | funnels | goals | insights | profiles | companies`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).option(`--csv`,`Emit top-pages as CSV`).option(`--tsv`,`Emit top-pages as TSV`).option(`--ndjson`,`Emit top-pages as NDJSON (one row per line)`).action(async(e,t)=>{switch(e){case void 0:{let{analyticsCommand:e}=await import(`./analytics-DnICaaM-.js`);process.exitCode=await e({cliVersion:M,siteId:t.siteId,json:t.json,csv:t.csv,tsv:t.tsv,ndjson:t.ndjson});return}case`live`:{let{liveCommand:e}=await import(`./live-DltW8mP8.js`);process.exitCode=await e({cliVersion:M,siteId:t.siteId,json:t.json});return}case`funnels`:{let{funnelCommand:e}=await import(`./funnel-DsMn91zW.js`);process.exitCode=await e({cliVersion:M,siteId:t.siteId,json:t.json,csv:t.csv,tsv:t.tsv,ndjson:t.ndjson});return}case`goals`:{let{goalsCommand:e}=await import(`./goals-D3oPsLrm.js`);process.exitCode=await e({cliVersion:M,action:`list`,json:t.json});return}case`insights`:{let{insightsCommand:e}=await import(`./insights-DetIAtXK.js`);process.exitCode=await e({cliVersion:M,siteId:t.siteId,json:t.json});return}case`profiles`:{let{visitorsCommand:e}=await import(`./visitors-DMSB-LQP.js`);process.exitCode=await e({cliVersion:M,siteId:t.siteId,json:t.json});return}case`companies`:{let{companiesCommand:e}=await import(`./companies-DH1MOieW.js`);process.exitCode=await e({cliVersion:M,siteId:t.siteId,json:t.json});return}default:process.stderr.write(t.json?JSON.stringify({type:`error`,code:`validation_failed`,message:`Unknown analytics sub-command: ${e}`,hint:`Valid: live | funnels | goals | insights | profiles | companies`})+`
|
|
8
8
|
`:`\n✗ Unknown analytics sub-command: '${e}'\n Valid: live | funnels | goals | insights | profiles | companies. Run \`zenovay analytics --help\`\n`),process.exit(2)}}),F.command(`overview`,"[ANALYTICS] Alias for `analytics`").option(`--site-id <id>`,`Site ID`).option(`--json`,``).option(`--csv`,`Emit top-pages as CSV`).option(`--tsv`,`Emit top-pages as TSV`).option(`--ndjson`,`Emit top-pages as NDJSON (one row per line)`).action(async e=>{let{analyticsCommand:t}=await import(`./analytics-DnICaaM-.js`),n=await t({cliVersion:M,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),F.command(`home`,`[ACCOUNT] Top-level summary — sites + this-week deltas`).option(`--json`,``).action(async e=>{let{homeCommand:t}=await import(`./home-BFzJXK-U.js`);process.exitCode=await t({cliVersion:M,json:e.json})}),F.command(`live`,`[ANALYTICS] Real-time visitors + globe + recent events (2s polling)`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).action(async e=>{let{liveCommand:t}=await import(`./live-DltW8mP8.js`),n=await t({cliVersion:M,siteId:e.siteId,json:e.json});process.exitCode=n}),F.command(`pages`,`[ANALYTICS] Top pages by views — last 24h`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).option(`--csv`,`Emit pages as CSV`).option(`--tsv`,`Emit pages as TSV`).option(`--ndjson`,`Emit pages as NDJSON (one row per line)`).action(async e=>{let{pagesCommand:t}=await import(`./pages-CeZztbJL.js`),n=await t({cliVersion:M,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),F.command(`devices`,`[ANALYTICS] Device / browser / OS breakdown — last 24h`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).option(`--csv`,`Emit devices as CSV`).option(`--tsv`,`Emit devices as TSV`).option(`--ndjson`,`Emit devices as NDJSON (one row per line)`).action(async e=>{let{devicesCommand:t}=await import(`./devices-BG4tGm29.js`),n=await t({cliVersion:M,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),F.command(`geo`,`[ANALYTICS] Countries + cities + globe — last 24h`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).option(`--csv`,`Emit countries as CSV`).option(`--tsv`,`Emit countries as TSV`).option(`--ndjson`,`Emit countries as NDJSON (one row per line)`).action(async e=>{let{geoCommand:t}=await import(`./geo-BXurbfTm.js`),n=await t({cliVersion:M,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),F.command(`retention`,`[BEHAVIOR] Cohort retention heatmap — D1 / D7 / D30 (Pro+)`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).action(async e=>{let{retentionCommand:t}=await import(`./retention-ByySsFfr.js`),n=await t({cliVersion:M,siteId:e.siteId,json:e.json});process.exitCode=n}),F.command(`uptime`,`[BEHAVIOR] Uptime monitors with status + p95 (Pro+)`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).action(async e=>{let{uptimeCommand:t}=await import(`./uptime-42ArloS6.js`),n=await t({cliVersion:M,siteId:e.siteId,json:e.json});process.exitCode=n}),F.command(`sessions`,`[BEHAVIOR] Recent session-replay list (Pro+)`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).action(async e=>{let{sessionsCommand:t}=await import(`./sessions-9dtqST89.js`),n=await t({cliVersion:M,siteId:e.siteId,json:e.json});process.exitCode=n}),F.command(`heatmaps`,`[BEHAVIOR] Recent heatmap captures (Pro+)`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).action(async e=>{let{heatmapsCommand:t}=await import(`./heatmaps-BzMMPGn_.js`),n=await t({cliVersion:M,siteId:e.siteId,json:e.json});process.exitCode=n}),F.command(`journeys`,`[BEHAVIOR] Page-to-page transition flow (Pro+)`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).action(async e=>{let{journeysCommand:t}=await import(`./journeys-CI7lh9Bo.js`),n=await t({cliVersion:M,siteId:e.siteId,json:e.json});process.exitCode=n}),F.command(`insights`,`[INTELLIGENCE] AI-generated anomaly / trend / recommendation cards (Pro+)`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).action(async e=>{let{insightsCommand:t}=await import(`./insights-DetIAtXK.js`),n=await t({cliVersion:M,siteId:e.siteId,json:e.json});process.exitCode=n}),F.command(`events [action]`,`[OPERATIONS] events tail [--filter --forward-to --replay-24h] — 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,t)=>{e!==`tail`&&(process.stderr.write(t.json?JSON.stringify({type:`error`,code:`validation_failed`,message:`Unknown events action: ${e??`(none)`}`,hint:`Usage: zenovay events tail`})+`
|
|
9
9
|
`:`\n✗ Unknown events action: '${e??`(none)`}'\n Usage: zenovay events tail. Run \`zenovay events tail --help\`\n`),process.exit(2));let{eventsTailCommand:n}=await import(`./events-tail-B0RxKP3U.js`),r=await n({cliVersion:M,siteId:t.siteId,json:t.json,filter:t.filter,forwardTo:t.forwardTo,replay24h:t.replay24h,setForwardSecret:t.setForwardSecret});process.exitCode=r}),F.command(`health`,`[OPERATIONS] Run self-diagnostic checks`).option(`--json`,``).action(async e=>{let{healthCommand:t}=await import(`./health-DJweY04d.js`),n=await t({cliVersion:M,binaryPath:N,json:e.json});process.exitCode=n}),F.command(`annotation [action]`,`[OPERATIONS] annotation create [--type --message --occurred-at] (deploy / release / campaign / incident / custom)`).option(`--type <type>`,`One of: deploy, release, campaign, incident, custom`,{default:`custom`}).option(`--message <message>`,`Short description (1–500 chars)`,{default:``}).option(`--occurred-at <iso>`,`ISO 8601 timestamp (default: now)`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).action(async(e,t)=>{let n=e??`create`;if(n!==`create`){process.stderr.write(`Unknown annotation action: ${n}. Try: zenovay annotation create --type=deploy --message="..."\n`),process.exitCode=2;return}let{annotationCreateCommand:r}=await import(`./annotation-DSdNqyEC.js`),i=await r({cliVersion:M,type:t.type,message:t.message,occurredAt:t.occurredAt,siteId:t.siteId,json:t.json});process.exitCode=i}),F.command(`doctor`,`[OPERATIONS] AI-assisted self-healing`).option(`--json`,``).action(async e=>{let{doctorCommand:t}=await import(`./doctor-WAEVPtnG.js`),n=await t({cliVersion:M,binaryPath:N,json:e.json});process.exitCode=n}),F.command(`stats`,`[ANALYTICS] 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-h_juyrDM.js`),n=await t({cliVersion:M,siteId:e.siteId,range:e.range,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),F.command(`sources`,`[ANALYTICS] Traffic source breakdown with delta arrows`).option(`--site-id <id>`,`Site ID`).option(`--range, --period <p>`,`Time range: 7d | 30d | 90d | 1y (--period is a legacy alias)`,{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-DiH5acUP.js`),n=await t({cliVersion:M,siteId:e.siteId,period:e.period,compare:e.compare,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),F.command(`vitals`,`[BEHAVIOR] Core Web Vitals dashboard (LCP / INP / CLS / TTFB / FCP) (Pro+)`).option(`--site-id <id>`,`Site ID`).option(`--url <path>`,`Filter to a single URL`).option(`--device <type>`,`Filter by device: mobile | desktop`).option(`--range, --window <w>`,`Time range: 24h | 7d | 30d | 90d (--window is a legacy alias)`,{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-Q7_u9sxq.js`),n=await t({cliVersion:M,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}),F.command(`revenue`,`[ANALYTICS] 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-CBgvMcDZ.js`),n=await t({cliVersion:M,siteId:e.siteId,range:e.range,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),F.command(`funnels`,`[BEHAVIOR] List available funnels (Pro+)`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{funnelCommand:t}=await import(`./funnel-DsMn91zW.js`),n=await t({cliVersion:M,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),F.command(`themes`,`[OPERATIONS] 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-BBtRXVPz.js`),n=await t({cliVersion:M,validate:e.validate,json:e.json});process.exitCode=n}),F.command(`completions [shell] [valuesType]`,`[OPERATIONS] Emit shell-completion script (bash | zsh | fish | nushell | pwsh)`).option(`--list`,`List supported shells`).action(async(e,t,n)=>{let{completionsCommand:r}=await import(`./completions-DNEK2qom.js`),i=await r({shell:e,valuesType:t,list:n.list});process.exitCode=i}),F.command(`query [sql]`,`[INTELLIGENCE] 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-C3e5w05g.js`),r=await n({cliVersion:M,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}),F.command(`companies`,`[INTELLIGENCE] B2B identification feed (Scale+)`).option(`--site-id <id>`,`Site ID`).option(`--range, --window <w>`,`Time range: 24h | 7d | 30d | 90d (--window is a legacy alias)`,{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-DH1MOieW.js`),n=await t({cliVersion:M,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}),F.command(`projects`,`[OPERATIONS] 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-7ifzwrtn.js`),n=await t({cliVersion:M,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),F.command(`deploys`,`[OPERATIONS] Recent deploy markers overlaid on charts`).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-D261j_D-.js`),n=await t({cliVersion:M,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}),F.command(`errors`,`[BEHAVIOR] Recent JS / HTTP error snapshot`).alias(`error`).option(`--site-id <id>`,`Site ID`).option(`--range, --window <w>`,`Time range: 24h | 7d | 30d | 90d (--window is a legacy alias)`,{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-CTVbJ5V0.js`),n=await t({cliVersion:M,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}),F.command(`funnel <id>`,`[BEHAVIOR] Funnel drop-off chart for a specific funnel (Pro+)`).option(`--site-id <id>`,`Site ID`).option(`--range, --window <w>`,`Time range: 7d | 30d (--window is a legacy alias)`,{default:`30d`}).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async(e,t)=>{let{funnelCommand:n}=await import(`./funnel-DsMn91zW.js`),r=await n({cliVersion:M,siteId:t.siteId,funnelId:e,window:t.window,json:t.json,csv:t.csv,tsv:t.tsv,ndjson:t.ndjson});process.exitCode=r}),F.command(`api-keys [action] [id]`,`[MANAGE] api-keys list | create [--name --scope] | delete <id>`).option(`--name <n>`,`Human-readable label (create)`).option(`--scope <scope>`,`read | write (create)`,{default:`read`}).option(`--yes`,`Skip confirmation (delete)`).option(`--json`,``).action(async(e,t,n)=>{let{apiKeysCommand:r}=await import(`./api-keys-BrHTpsbc.js`),i=e??`list`;process.exitCode=await r({cliVersion:M,action:i,id:t,name:n.name,scope:n.scope===`write`?`write`:`read`,yes:n.yes,json:n.json})}),F.command(`domains [action] [arg]`,`[MANAGE] domains list | add <url> [--name] | delete <id>`).option(`--name <n>`,`Friendly project name (add; default: domain itself)`).option(`--yes`,`Skip confirmation (delete)`).option(`--json`,``).action(async(e,t,n)=>{let{domainsCommand:r}=await import(`./domains-DfLjgM3t.js`),i=e??`list`;process.exitCode=await r({cliVersion:M,action:i,url:i===`add`?t:void 0,id:i===`delete`?t:void 0,name:n.name,yes:n.yes,json:n.json})}),F.command(`team [action] [arg] [arg2]`,`[MANAGE] team list | invite <email> [--role] | remove <userId> | role <userId> <admin|member> (Pro+)`).option(`--role <role>`,`admin | member (invite)`,{default:`member`}).option(`--yes`,`Skip confirmation (remove)`).option(`--json`,``).action(async(e,t,n,r)=>{let{teamCommand:i}=await import(`./team-CtHhMm_t.js`),a=e??`list`,o;a===`role`?o=n===`admin`?`admin`:`member`:a===`invite`&&(o=r.role===`admin`?`admin`:`member`),process.exitCode=await i({cliVersion:M,action:a,email:a===`invite`?t:void 0,userId:a===`remove`||a===`role`?t:void 0,role:o,yes:r.yes,json:r.json})}),F.command(`profile [action]`,`[ACCOUNT] profile show | edit [--name --notifications]`).option(`--name <n>`,`New display name (edit)`).option(`--notifications <pref>`,`email | none (edit)`).option(`--json`,``).action(async(e,t)=>{let n=e??`show`,r=t.notifications===`email`||t.notifications===`none`?t.notifications:void 0,{profileCommand:i}=await import(`./profile-C-CyW8Bx.js`);process.exitCode=await i({cliVersion:M,action:n,name:t.name,notifications:r,json:t.json})}),F.command(`plans [action] [arg] [arg2]`,`[ACCOUNT] plans info | upgrade <pro|scale> | cancel --yes | payment update`).option(`--yes`,"Required for `cancel`").option(`--json`,``).action(async(e,t,n,r)=>{let i=e??`info`,{plansCommand:a}=await import(`./plans-C_j2XLQ4.js`),o;if(i===`upgrade`&&t){let e=String(t).toLowerCase();(e===`pro`||e===`scale`||e===`enterprise`)&&(o=e)}let s=i===`payment`&&t===`update`||i===`payment`?`update`:void 0;process.exitCode=await a({cliVersion:M,action:i,targetPlan:o,paymentAction:s,yes:r.yes,json:r.json})}),F.command(`billing [action]`,"[ACCOUNT] Alias for `plans info`").option(`--json`,``).action(async(e,t)=>{let{plansCommand:n}=await import(`./plans-C_j2XLQ4.js`);process.exitCode=await n({cliVersion:M,action:`info`,json:t.json})}),F.command(`settings [action] [key] [value]`,`[ACCOUNT] settings get [key] | set <key> <value>`).option(`--json`,``).action(async(e,t,n,r)=>{let i=e??`get`,{settingsCommand:a}=await import(`./settings-BPBWCOOH.js`);process.exitCode=await a({cliVersion:M,action:i,key:t||void 0,value:n||void 0,json:r.json})}),F.command(`integrations [action] [name]`,`[ACCOUNT] integrations list | connect <gsc|github> | disconnect <gsc|github>`).option(`--yes`,`Skip confirmation (disconnect)`).option(`--json`,``).action(async(e,t,n)=>{let r=e??`list`,i=t===`gsc`||t===`github`?t:void 0,{integrationsCommand:a}=await import(`./integrations-BqwI6VNk.js`);process.exitCode=await a({cliVersion:M,action:r,name:i,yes:n.yes,json:n.json})}),F.command(`goals [action] [id]`,`[ACCOUNT] goals list | create [--name --type --target] | delete <id> (Pro+)`).option(`--name <n>`,`Goal name (create)`).option(`--type <t>`,`pageview | event (create)`).option(`--target <v>`,`URL pattern or event name (create)`).option(`--yes`,`Skip confirmation (delete)`).option(`--json`,``).action(async(e,t,n)=>{let r=e??`list`,i=n.type===`event`||n.type===`pageview`?n.type:void 0,{goalsCommand:a}=await import(`./goals-D3oPsLrm.js`);process.exitCode=await a({cliVersion:M,action:r,id:t,name:n.name,type:i,target:n.target,yes:n.yes,json:n.json})}),F.command(`notes [action] [id]`,`[ACCOUNT] notes list | create [--content --site-id] | delete <id>`).option(`--content <text>`,`Note body (create)`).option(`--site-id <id>`,`Attach to a specific site (create; defaults to current)`).option(`--yes`,`Skip confirmation (delete)`).option(`--json`,``).action(async(e,t,n)=>{let r=e??`list`,{notesCommand:i}=await import(`./notes-zgu5aUgZ.js`);process.exitCode=await i({cliVersion:M,action:r,id:t,content:n.content,siteId:n.siteId,yes:n.yes,json:n.json})}),F.command(`agency [action] [arg] [arg2]`,`[ACCOUNT] agency clients list | clients add [--email --name] | clients remove <id> | report send <clientId> (Scale+)`).option(`--email <e>`,`Client contact email (clients add)`).option(`--name <n>`,`Client name (clients add)`).option(`--yes`,`Skip confirmation (clients remove)`).option(`--json`,``).action(async(e,t,n,r)=>{let{agencyCommand:i}=await import(`./agency-BNaZxwuI.js`),a=`clients-list`,o;e===`clients`?t===`add`?a=`clients-add`:t===`remove`?(a=`clients-remove`,o=n):a=`clients-list`:e===`report`&&t===`send`&&(a=`report-send`,o=n),process.exitCode=await i({cliVersion:M,action:a,id:o,email:r.email,name:r.name,yes:r.yes,json:r.json})}),F.command(`use [site]`,`[OPERATIONS] Set / show / reset your default site (used when --site-id is omitted)`).option(`--reset`,`Clear the stored default site`).option(`--show`,`Print the current default and exit`).option(`--json`,`Emit JSON`).action(async(e,t)=>{let{useCommand:n}=await import(`./use-CuQ2Z9Aw.js`),r=await n({cliVersion:M,match:e,reset:t.reset,show:t.show,json:t.json});process.exitCode=r}),F.command(`update`,`[OPERATIONS] 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-CXMG8g-D.js`);await t({cliVersion:M,binaryPath:N,check:e.check,forceDowngrade:e.forceDowngrade,json:e.json})}),F.command(`usage`,`[ACCOUNT] Current month events vs plan limits + headcounts`).option(`--json`,``).action(async e=>{let{usageCommand:t}=await import(`./usage-DeNyFk5w.js`);process.exitCode=await t({cliVersion:M,json:e.json})}),F.command(`globe`,`[ANALYTICS] Live 3D globe — visitors plotted on a Braille sphere`).option(`--site-id <id>`,`Site ID`).option(`--browser`,`Open the dashboard's Mapbox globe in your browser instead of the terminal version`).option(`--json`,``).action(async e=>{let{globeCommand:t}=await import(`./globe-ka4CYfJg.js`);process.exitCode=await t({cliVersion:M,siteId:e.siteId,browser:e.browser,json:e.json})}),F.command(`webhooks [action] [arg]`,`[MANAGE] webhooks list | add <url> [--events] | delete <id> | rotate <id> | test <id> | forward [--to]`).option(`--events <list>`,`Comma-separated event types (add)`).option(`--yes`,`Skip confirmation (delete/rotate)`).option(`--to <url>`,`forward: local URL to POST events to (e.g. localhost:3000/webhook)`).option(`--site-id <id>`,`forward: Site ID`).option(`--sign`,`forward: HMAC-sign each forwarded request with X-Zenovay-Signature`).option(`--secret <hex>`,`forward: HMAC secret (auto-derived from tunnel key if --sign without --secret)`).option(`--max-retries <n>`,`forward: per-request retry count`,{default:3}).option(`--json`,``).action(async(e,t,n)=>{let r=e??`list`;if(r===`forward`){let{webhooksForwardCommand:e}=await import(`./webhooks-forward-DfNBzOJ7.js`);process.exitCode=await e({cliVersion:M,to:n.to,siteId:n.siteId,sign:n.sign,secret:n.secret,maxRetries:typeof n.maxRetries==`string`?Number(n.maxRetries):n.maxRetries});return}let{webhooksCommand:i}=await import(`./webhooks-B1eqAQXM.js`);process.exitCode=await i({cliVersion:M,action:r,url:r===`add`?t:void 0,id:r===`delete`||r===`rotate`||r===`test`?t:void 0,events:n.events,yes:n.yes,json:n.json})}),F.command(`audit [action]`,`[ACCOUNT] audit list [--since --action --actor] | export [--format --out] (Pro+)`).option(`--range, --since <window>`,`Time range like 24h, 7d, 30d (list; --since is a legacy alias)`,{default:`7d`}).option(`--action <pattern>`,`Filter by action string (list)`).option(`--actor <userId>`,`Filter by actor user ID (list)`).option(`--format <fmt>`,`ndjson | csv | json (export)`,{default:`ndjson`}).option(`--out <file>`,`Output file path (export). Defaults to stdout`).option(`--json`,``).action(async(e,t)=>{let n=e??`list`,r=t.format??`ndjson`,{auditCommand:i}=await import(`./audit-CIg-teMg.js`);process.exitCode=await i({cliVersion:M,action:n,since:t.since,filterAction:t.action,actor:t.actor,format:r,out:t.out,json:t.json})}),F.command(`share [action]`,`[ACCOUNT] share enable | disable | url — public dashboard share for the current site`).option(`--site-id <id>`,`Site ID (defaults to your current default site)`).option(`--yes`,`Skip confirmation (disable)`).option(`--json`,``).action(async(e,t)=>{let n=e??`url`,{shareCommand:r}=await import(`./share-COuGNR8Q.js`);process.exitCode=await r({cliVersion:M,action:n,siteId:t.siteId,yes:t.yes,json:t.json})}),F.command(`commands`,`[OPERATIONS] Emit the machine-readable command tree (for AI agents and shell-completion regen)`).option(`--json`,``).action(async e=>{let{commandsCommand:t}=await import(`./commands-CGCCx0-s.js`);process.exitCode=await t({cliVersion:M,json:e.json})}),F.command(`teams [action] [arg]`,`[ACCOUNT] teams list | switch <name-or-id> | current | reset`).option(`--json`,``).action(async(e,t,n)=>{let r=e??`list`,{teamsCommand:i}=await import(`./teams-6x1xB5VJ.js`);process.exitCode=await i({cliVersion:M,action:r,match:r===`switch`?t:void 0,json:n.json})}),F.command(`self-test`,`[OPERATIONS] Functional smoke check across every read endpoint and your local install`).option(`--quick`,`Run a 10-test subset (faster)`).option(`--full`,`Include active security probes + CLI meta-tests (dev/CI use)`).option(`--verbose`,`Include full stdout/stderr per test`).option(`--parallel <n>`,`Concurrent subprocesses (default 4)`,{default:4}).option(`--json`,`Emit NDJSON one line per test result + final summary`).action(async e=>{let{selfTestCommand:t}=await import(`./self-test-RTam3wnZ.js`);process.exitCode=await t({cliVersion:M,full:!!e.full,quick:!!e.quick,verbose:!!e.verbose,parallel:Number(e.parallel)||4,json:!!e.json})}),F.command(`tour`,`[OPERATIONS] Interactive 8-step walkthrough of the CLI`).option(`--non-interactive`,`Print all 8 steps as a flat document (no prompts)`).action(async e=>{let{tourCommand:t}=await import(`./tour-CE8jtA2L.js`);process.exitCode=await t({cliVersion:M,nonInteractive:!!(e[`non-interactive`]||e.nonInteractive)})}),F.command(`alerts [action] [id]`,`[MANAGE] alerts list | create [--metric --op --threshold --window] | delete <id> (Pro+)`).option(`--site-id <id>`,`Site ID (defaults to your current default site)`).option(`--metric <name>`,`Metric to watch (visitors|pageviews|bounce_rate|errors|lcp|inp|cls|uptime|revenue)`).option(`--op <gt|lt>`,`Comparison operator`).option(`--threshold <num>`,`Numeric threshold`).option(`--window <e.g. 1h>`,`Rolling window (5m|1h|24h|7d)`).option(`--name <label>`,`Optional friendly label for the alert`).option(`--channel <chan>`,`Notification channel: in_app | email | webhook (default in_app)`).option(`--email <addr>`,`Notification email (required when --channel email)`).option(`--yes`,`Skip confirmation prompt on delete`).option(`--json`,``).action(async(e,t,n)=>{let r=e??`list`,i=new Set([`list`,`create`,`delete`]);i.has(r)||(process.stderr.write(n.json?JSON.stringify({type:`error`,code:`validation_failed`,message:`Unknown alerts action: ${e}`,hint:`Run zenovay alerts --help`})+`
|
|
10
10
|
`:`\n✗ Unknown action: '${e}'\n Valid: list | create | delete. Run \`zenovay alerts --help\`\n`),process.exit(2));let{alertsCommand:a}=await import(`./alerts-pzUmtvMF.js`);process.exitCode=await a({cliVersion:M,action:r,siteId:n[`site-id`]??n.siteId,metric:n.metric,op:n.op,threshold:n.threshold,window:n.window,name:n.name,channel:n.channel,email:n.email,id:t,yes:!!n.yes,json:!!n.json})}),F.command(`export <type>`,`[OPERATIONS] Export data: analytics | sessions (Pro+) | heatmaps (Pro+)`).option(`--site-id <id>`,`Site ID (defaults to your current default site)`).option(`--range <range>`,`Time range: 7d | 30d | 90d`,{default:`30d`}).option(`--format <fmt>`,`Output format: csv | json`,{default:`csv`}).option(`--out <file>`,`Write to file instead of stdout`).option(`--json`,``).action(async(e,t)=>{let n=new Set([`analytics`,`sessions`,`heatmaps`]);n.has(e)||(process.stderr.write(t.json?JSON.stringify({type:`error`,code:`validation_failed`,message:`Unknown export type: ${e}`,hint:`Valid: analytics | sessions | heatmaps`})+`
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{readConfig as e,updateConfig as t}from"./config-JVhBplSX.js";import{ApiClient as n,completionUrlForVerifiedSetup as r,dashboardUrlForSite as i}from"./api-CBukwv2I.js";import{readToken as a}from"./token-store-CuZEiQNg.js";import{diagnoseInstall as o}from"./detect-installed-DpSaAeH-.js";import{emit$1 as s,isHeadless as c}from"./emit-5vELQfsB.js";import{openInBrowser as l}from"./open-url-IjqD5f_n.js";import{scrubSecrets as u}from"./secrets-zGZxXoM0.js";import{parseSseStream as d}from"./client-DNMRt-Hq.js";import{swapToFirstPartySnippet as f}from"./snippet-CwowVrmh.js";import{loginCommand as p,maybeInstallCompletions as m}from"./login-vzW-8q0w.js";import{Banner as h,Panel as g,useTheme as _}from"./panel-DbiZwGB3.js";import{DiffView as v,ProgressRow as y}from"./progress-row-BSv_Zm8f.js";import{Select as b}from"./prompt-Dae2nnYJ.js";import{Keybar as ee}from"./keybar-BY1csJGI.js";import{spark as x}from"./sparkline-B7VaYaxH.js";import{execFile as S}from"node:child_process";import C from"node:path";import{promises as w}from"node:fs";import{z as T}from"zod";import E from"node:os";import D from"node:crypto";import{ulid as O}from"ulid";import{Box as k,Text as A,render as te,useApp as ne,useInput as re}from"ink";import j from"node:fs/promises";import M,{useEffect as N,useRef as P,useState as F}from"react";import{globby as ie}from"globby";import I from"ink-spinner";import{applyPatch as ae}from"diff";import{promisify as oe}from"node:util";const se=[/^(src\/)?app\/(.*\/)?layout\.(tsx|ts|jsx|js)$/,/^(src\/)?app\/root\.(tsx|ts|jsx|js)$/,/^(src\/)?pages\/(_app|_document)\.(tsx|ts|jsx|js)$/,/^src\/layouts\/.*\.(astro|svelte|vue)$/,/^src\/pages\/index\.astro$/,/^(src\/)?components\/.*\.(astro|svelte|vue|tsx|jsx|ts|js)$/,/^src\/routes\/\+layout\.(svelte|ts|js)$/,/^src\/routes\/root\..*$/,/^src\/(root|entry-server|entry-client)\.(tsx|ts|jsx|js)$/,/^src\/main\.(tsx|ts|jsx|js)$/,/^src\/App\.(tsx|ts|jsx|js|svelte|vue)$/,/^gatsby-(ssr|browser|config)\.(js|ts|mjs)$/,/^(next|nuxt|vite|astro|remix|svelte|tailwind|postcss)\.config\.(ts|mts|cts|js|mjs|cjs)$/,/^plugins\/.*\.(ts|js)$/,/^index\.html?$/,/^src\/index\.html?$/],ce=[/(^|\/)\.env($|\.(?!example$)[^/]+$)/,/(^|\/)\.git(\/|$)/,/(^|\/)node_modules\//,/(^|\/)\.ssh\//,/(^|\/)\.aws\//,/\.pem$/,/\.key$/,/(^|\/)id_rsa($|\.)/,/(^|\/)\.npmrc$/,/(^|\/)credentials(\.|$)/],L=256*1024,le=20,R=20,
|
|
2
|
-
`,{mode:384}),this.journaledPaths.set(e,o),o}static wrapForModel(e,t){let n=D.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 u(e)}};const
|
|
3
|
-
`).filter(e=>e.trim().length>0).map(e=>{let t=JSON.parse(e);if(typeof t.abs!=`string`||!C.isAbsolute(t.abs)||t.backupPath!==null&&typeof t.backupPath!=`string`)throw new
|
|
1
|
+
import{readConfig as e,updateConfig as t}from"./config-JVhBplSX.js";import{ApiClient as n,completionUrlForVerifiedSetup as r,dashboardUrlForSite as i}from"./api-CBukwv2I.js";import{readToken as a}from"./token-store-CuZEiQNg.js";import{diagnoseInstall as o}from"./detect-installed-DpSaAeH-.js";import{emit$1 as s,isHeadless as c}from"./emit-5vELQfsB.js";import{openInBrowser as l}from"./open-url-IjqD5f_n.js";import{scrubSecrets as u}from"./secrets-zGZxXoM0.js";import{parseSseStream as d}from"./client-DNMRt-Hq.js";import{swapToFirstPartySnippet as f}from"./snippet-CwowVrmh.js";import{loginCommand as p,maybeInstallCompletions as m}from"./login-vzW-8q0w.js";import{Banner as h,Panel as g,useTheme as _}from"./panel-DbiZwGB3.js";import{DiffView as v,ProgressRow as y}from"./progress-row-BSv_Zm8f.js";import{Select as b}from"./prompt-Dae2nnYJ.js";import{Keybar as ee}from"./keybar-BY1csJGI.js";import{spark as x}from"./sparkline-B7VaYaxH.js";import{execFile as S}from"node:child_process";import C from"node:path";import{promises as w}from"node:fs";import{z as T}from"zod";import E from"node:os";import D from"node:crypto";import{ulid as O}from"ulid";import{Box as k,Text as A,render as te,useApp as ne,useInput as re}from"ink";import j from"node:fs/promises";import M,{useEffect as N,useRef as P,useState as F}from"react";import{globby as ie}from"globby";import I from"ink-spinner";import{applyPatch as ae}from"diff";import{promisify as oe}from"node:util";const se=[/^(src\/)?app\/(.*\/)?layout\.(tsx|ts|jsx|js)$/,/^(src\/)?app\/root\.(tsx|ts|jsx|js)$/,/^(src\/)?pages\/(_app|_document)\.(tsx|ts|jsx|js)$/,/^src\/layouts\/.*\.(astro|svelte|vue)$/,/^src\/pages\/index\.astro$/,/^(src\/)?components\/.*\.(astro|svelte|vue|tsx|jsx|ts|js)$/,/^src\/routes\/\+layout\.(svelte|ts|js)$/,/^src\/routes\/root\..*$/,/^src\/(root|entry-server|entry-client)\.(tsx|ts|jsx|js)$/,/^src\/main\.(tsx|ts|jsx|js)$/,/^src\/App\.(tsx|ts|jsx|js|svelte|vue)$/,/^gatsby-(ssr|browser|config)\.(js|ts|mjs)$/,/^(next|nuxt|vite|astro|remix|svelte|tailwind|postcss)\.config\.(ts|mts|cts|js|mjs|cjs)$/,/^plugins\/.*\.(ts|js)$/,/^index\.html?$/,/^src\/index\.html?$/],ce=[/(^|\/)\.env($|\.(?!example$)[^/]+$)/,/(^|\/)\.git(\/|$)/,/(^|\/)node_modules\//,/(^|\/)\.ssh\//,/(^|\/)\.aws\//,/\.pem$/,/\.key$/,/(^|\/)id_rsa($|\.)/,/(^|\/)\.npmrc$/,/(^|\/)credentials(\.|$)/],L=256*1024,le=20,R=20,z=20;var B=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`SandboxError`}};const V=/<script[^>]*src\s*=\s*["'](?:https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+|[^"']*\/_z\/script\.js[^"']*)["'][^>]*>\s*<\/script>/i,ue=[{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 H=class{sessionId;cwd;cwdReal;undoRoot;readCount=0;writeCount=0;roundCount=0;writtenPathsSet=new Set;prunedOnce=!1;journaledPaths=new Map;constructor(e){this.sessionId=e.sessionId??O(),this.cwd=e.cwd,this.cwdReal=w.realpath(e.cwd),this.undoRoot=e.undoRoot??C.join(E.homedir(),`.zenovay`,`undo`)}incrementRound(){if(this.roundCount++,this.roundCount>z)throw new B(`round-cap`,`Tool-call recursion cap (${z}) 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 journalTrustedWrite(e){if(typeof e!=`string`||e.length===0||e.includes(`\0`))throw new B(`escape`,`Journal path must be a non-empty string without null bytes.`);let t=await this.cwdReal,n=C.resolve(t,e),r=[],i=n,a=null;for(;a===null;)try{let e=await w.realpath(i);a=C.join(e,...r.reverse())}catch(t){if(t.code!==`ENOENT`)throw new B(`escape`,`realpath failed: ${t.message}`);try{let t=await w.lstat(i);if(t.isSymbolicLink())throw new B(`escape`,`Unresolved symlink in journal path: ${e}`)}catch(e){if(e instanceof B)throw e;if(e.code!==`ENOENT`)throw new B(`escape`,`lstat failed: ${e.message}`)}let n=C.dirname(i);if(n===i)throw new B(`escape`,`Could not resolve journal path: ${e}`);r.push(C.basename(i)),i=n}if(!this.isWithin(a,t))throw new B(`escape`,`Path escapes cwd: ${e}`);await this.journalBackup(a)}async resolveSafe(e,t){if(typeof e!=`string`||e.length===0)throw new B(`escape`,`Path must be a non-empty string.`);if(e.includes(`\0`))throw new B(`escape`,`Null byte in path.`);if(/^\\\\[?.]\\/.test(e)||/^\\\\[A-Za-z0-9]/.test(e))throw new B(`escape`,`Windows special path prefix: ${e}`);if(/%/.test(e))try{let t=decodeURIComponent(e);if(/%[0-9A-Fa-f]{2}/.test(t))throw new B(`escape`,`Double-encoded path: ${e}`);e=t}catch(t){throw t instanceof B?t:new B(`escape`,`Malformed percent-encoding: ${e}`)}if(e.includes(`\0`))throw new B(`escape`,`Null byte in decoded path.`);if(e.includes(`\\`))throw new B(`escape`,`Backslash in path (Windows-style separator not accepted): ${e}`);let n=await this.cwdReal,r=C.isAbsolute(e)?e:C.join(n,e),i=C.normalize(r),a=i;try{a=await w.realpath(i)}catch(e){if(e.code!==`ENOENT`)throw new B(`escape`,`realpath failed: ${e.message}`);let t=C.dirname(i);try{let e=await w.realpath(t);a=C.join(e,C.basename(i))}catch{}}if(!this.isWithin(a,n))throw new B(`escape`,`Path escapes cwd: ${e}`);let o=C.relative(n,a),s=o.toLowerCase();for(let e of ce)if(e.test(o)||e.test(s)){if(t===`read`&&/(^|\/)node_modules\//i.test(o))continue;throw new B(`blocklisted`,`Path is on the hard blocklist: ${o}`)}if(t===`write`){let e=se.some(e=>e.test(o));if(!e&&!/^\.env(\.local)?$/.test(o)&&!/^\.claude\//.test(o)&&!/^\.cursor\//.test(o))throw new B(`not-allowlisted`,`Write path not on allowlist: ${o}`)}return a}isWithin(e,t){let n=C.relative(t,e);return!n.startsWith(`..`)&&!C.isAbsolute(n)}async safeRead(e){if(this.readCount>=le)throw new B(`read-cap`,`Read cap (${le}) reached.`);let t=await this.resolveForRead(e),n=await w.stat(t);if(n.size>L)throw new B(`too-large`,`File exceeds ${L}B: ${e} (${n.size}B)`);let r=await w.readFile(t),i=r.subarray(0,Math.min(r.length,8192));if(i.includes(0))throw new B(`binary-rejected`,`Binary content in ${e}.`);return this.readCount++,r.toString(`utf8`)}async safeWrite(e,t){if(this.writeCount>=R)throw new B(`write-cap`,`Write cap (${R}) reached.`);if(t.length>L)throw new B(`too-large`,`Write exceeds ${L}B: ${e}`);let n=await this.resolveForWrite(e),r=await w.readFile(n,`utf8`).catch(e=>{if(e.code===`ENOENT`)return null;throw e});if(r!==null){if(V.test(r)&&!V.test(t))throw new B(`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 ue)if(i.test(r)&&!i.test(t))throw new B(`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 w.mkdir(C.dirname(n),{recursive:!0}),await w.writeFile(n,t,`utf8`),this.writeCount++;let a=await this.cwdReal;return this.writtenPathsSet.add(C.relative(a,n)),{backupPath:i}}async journalBackup(e){if(this.journaledPaths.has(e))return this.journaledPaths.get(e)??null;let t=await w.readFile(e).catch(e=>{if(e.code===`ENOENT`)return null;throw e}),n=C.join(this.undoRoot,this.sessionId);await w.mkdir(n,{recursive:!0,mode:448}),this.prunedOnce||(this.prunedOnce=!0,me(this.undoRoot,this.sessionId));let r=D.createHash(`sha256`).update(e).digest(`hex`).slice(0,16),i=C.join(n,`${r}.bak`),a=C.join(n,`manifest.jsonl`);t!==null&&await w.writeFile(i,t,{mode:384});let o=t===null?null:i,s=JSON.stringify({abs:e,backupPath:o,ts:Date.now()});return await w.appendFile(a,s+`
|
|
2
|
+
`,{mode:384}),this.journaledPaths.set(e,o),o}static wrapForModel(e,t){let n=D.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 u(e)}};const de=20;function U(e,t){let n=C.relative(t,e);return n===``||!n.startsWith(`..`)&&!C.isAbsolute(n)}function fe(e){if(!/^[A-Za-z0-9_-]+$/.test(e))throw new B(`escape`,`Invalid undo session id.`)}async function W(e,t){fe(e);let n=await w.realpath(t),r=await w.realpath(C.join(n,e));if(!U(r,n))throw new B(`escape`,`Undo session escapes the undo root.`);let i=await w.realpath(C.join(r,`manifest.jsonl`));if(!U(i,r))throw new B(`escape`,`Undo manifest escapes its session directory.`);let a=await w.readFile(i,`utf8`),o=a.split(`
|
|
3
|
+
`).filter(e=>e.trim().length>0).map(e=>{let t=JSON.parse(e);if(typeof t.abs!=`string`||!C.isAbsolute(t.abs)||t.backupPath!==null&&typeof t.backupPath!=`string`)throw new B(`escape`,`Undo manifest contains an invalid path entry.`);return{abs:C.resolve(t.abs),backupPath:t.backupPath}});return{entries:o,sessionDir:r}}async function G(e,t){let n=e,r=[];for(;;)try{let i=await w.realpath(n),a=C.join(i,...r.reverse());if(!U(a,t))throw new B(`escape`,`Undo target escapes the current project: ${e}`);return a}catch(t){if(t instanceof B||t.code!==`ENOENT`)throw t;let i=C.dirname(n);if(i===n)throw new B(`escape`,`Could not resolve undo target: ${e}`);r.push(C.basename(n)),n=i}}async function pe(e,t,n){let r=n?.undoRoot??C.join(E.homedir(),`.zenovay`,`undo`),i=await w.realpath(t),{entries:a}=await W(e,r);return a.length>0&&a.every(e=>U(e.abs,i))}async function me(e,t,n=de){try{let r=await w.readdir(e,{withFileTypes:!0}),i=r.filter(e=>e.isDirectory()).map(e=>e.name);if(i.length<=n)return 0;let a=await Promise.all(i.map(async t=>{let n=await w.stat(C.join(e,t)).catch(()=>null);return{name:t,mtime:n?n.mtimeMs:0}}));a.sort((e,t)=>t.mtime-e.mtime);let o=a.slice(n).filter(e=>e.name!==t);return await Promise.all(o.map(t=>w.rm(C.join(e,t.name),{recursive:!0,force:!0}).catch(()=>{}))),o.length}catch{return 0}}async function he(e,t){let n=t?.undoRoot??C.join(E.homedir(),`.zenovay`,`undo`),r,i;try{({entries:r,sessionDir:i}=await W(e,n))}catch(e){if(e.code===`ENOENT`)return{restored:0};throw e}let a=t?.cwd?await w.realpath(t.cwd):null,o=new Set,s=0;for(let e of r.reverse()){if(o.has(e.abs))continue;o.add(e.abs);let t=a?await G(e.abs,a):e.abs;if(e.backupPath===null)await w.unlink(t).catch(()=>void 0),s++;else{let n=await w.realpath(e.backupPath);if(!U(n,i))throw new B(`escape`,`Undo backup escapes its session directory.`);let r=await w.readFile(n);await w.writeFile(t,r),s++}}return{restored:s}}async function K(e){let t=await e.readFile(`package.json`),n=!1;if(t)try{let e=JSON.parse(t);n=!!(e.dependencies?.[`@angular/core`]??e.devDependencies?.[`@angular/core`])}catch{}let r=await e.exists(`angular.json`)||await e.exists(`.angular-cli.json`);if(n||r){let t=await e.exists(`src/index.html`)?`src/index.html`:`index.html`;return{matched:!0,confidence:.9,reason:`Detected Angular via ${n?"`@angular/core`":"`angular.json`"} (shell: ${t}).`}}return{matched:!1,confidence:0,reason:`No Angular dependency or angular.json found.`}}function ge(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`src/index.html`,r=`<script defer\n data-id="${t}"\n src="https://api.zenovay.com/z.js">\n</script>`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Inject the Zenovay tracker inside <head> of the Angular index.html shell.`}]}const _e={id:`angular`,displayName:`Angular`,detect:K,files:[{path:`src/index.html`,kind:`mutate`,required:!0}],envVarName:`NG_ZENOVAY_SITE`,buildSnippets:ge},ve=[`astro.config.ts`,`astro.config.mjs`,`astro.config.js`];async function ye(e){for(let t of ve)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 be(e){let t=e.trackingCode??e.siteId??``,n=`<script defer data-id="${t}" src="https://api.zenovay.com/z.js" is:inline></script>`;return[{targetPath:`src/layouts/Layout.astro`,anchorKind:`head-tag`,code:n,description:`Inject the Zenovay tracker inside <head> of the primary layout.`},{targetPath:`src/layouts/BaseHead.astro`,anchorKind:`head-tag`,code:n,description:"Fallback target when the project uses a dedicated `BaseHead.astro`."},{targetPath:`src/pages/index.astro`,anchorKind:`head-tag`,code:n,description:"Fallback for layout-less projects (e.g. the official `create-astro --template minimal` starter keeps the document <head> inline in src/pages/index.astro)."}]}const q={id:`astro`,displayName:`Astro`,detect:ye,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:be};async function xe(e){let t=await e.readFile(`package.json`);if(t)try{let e=JSON.parse(t);if(e.dependencies?.gatsby??e.devDependencies?.gatsby)return!0}catch{}return await e.exists(`gatsby-config.js`)||await e.exists(`gatsby-config.ts`)}async function Se(e){return await xe(e)?{matched:!0,confidence:.95,reason:"Detected Gatsby via `gatsby` dependency / `gatsby-config`."}:{matched:!1,confidence:0,reason:`No Gatsby dependency or config found.`}}function J(e){let t=e.trackingCode??e.siteId??``,n=`const React = require('react');
|
|
4
4
|
|
|
5
5
|
exports.onRenderBody = ({ setHeadComponents }) => {
|
|
6
6
|
setHeadComponents([
|
|
@@ -12,13 +12,13 @@ exports.onRenderBody = ({ setHeadComponents }) => {
|
|
|
12
12
|
}),
|
|
13
13
|
]);
|
|
14
14
|
};
|
|
15
|
-
`;return[{targetPath:`gatsby-ssr.js`,anchorKind:`replace-file`,code:n,description:`Add the Zenovay tracker via Gatsby SSR onRenderBody → setHeadComponents.`}]}const
|
|
15
|
+
`;return[{targetPath:`gatsby-ssr.js`,anchorKind:`replace-file`,code:n,description:`Add the Zenovay tracker via Gatsby SSR onRenderBody → setHeadComponents.`}]}const Ce={id:`gatsby`,displayName:`Gatsby`,detect:Se,files:[{path:`gatsby-ssr.js`,kind:`create`,required:!0}],envVarName:`GATSBY_ZENOVAY_SITE`,buildSnippets:J},we=[`app/layout.tsx`,`app/layout.ts`,`app/layout.jsx`,`app/layout.js`,`src/app/layout.tsx`,`src/app/layout.ts`,`src/app/layout.jsx`,`src/app/layout.js`];async function Te(e){for(let t of we)if(await e.exists(t))return t;return null}async function Ee(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 De(e){let t=await Ee(e),n=await e.exists(`app`)||await e.exists(`src/app`),r=await Te(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 Oe(e,t=`script`){let n=e.targetPath||`app/layout.tsx`,r=e.trackingCode??e.siteId??``;return t===`npm`?Ae(n,r):ke(n,r)}function ke(e,t){return[{targetPath:e,anchorKind:`after-imports`,code:`import Script from 'next/script';`,description:`Import next/script to inject the Zenovay tracker.`},{targetPath:e,anchorKind:`wrap-children`,code:`<Script
|
|
16
16
|
defer
|
|
17
17
|
data-id="${t}"
|
|
18
18
|
src="https://api.zenovay.com/z.js"
|
|
19
19
|
strategy="afterInteractive"
|
|
20
20
|
/>
|
|
21
|
-
{children}`,description:`Add the Zenovay tracker <Script> next to children in the root layout.`}]}function
|
|
21
|
+
{children}`,description:`Add the Zenovay tracker <Script> next to children in the root layout.`}]}function Ae(e,t){return[{targetPath:`components/zenovay-bootstrap.tsx`,anchorKind:`replace-file`,code:`'use client';
|
|
22
22
|
|
|
23
23
|
import { useEffect } from 'react';
|
|
24
24
|
import { init } from '@zenovay/tracker';
|
|
@@ -35,7 +35,7 @@ export function ZenovayBootstrap() {
|
|
|
35
35
|
return null;
|
|
36
36
|
}
|
|
37
37
|
`,description:`Create a client-component bootstrap that calls init() from @zenovay/tracker.`},{targetPath:e,anchorKind:`after-imports`,code:`import { ZenovayBootstrap } from '@/components/zenovay-bootstrap';`,description:`Import the Zenovay tracker bootstrap into the root layout.`},{targetPath:e,anchorKind:`wrap-children`,code:`<ZenovayBootstrap />
|
|
38
|
-
{children}`,description:`Render the Zenovay tracker bootstrap alongside children in the root layout.`}]}const
|
|
38
|
+
{children}`,description:`Render the Zenovay tracker bootstrap alongside children in the root layout.`}]}const je={id:`next-app-router`,displayName:`Next.js (App Router)`,detect:De,files:[{path:`app/layout.tsx`,kind:`mutate`,required:!0}],envVarName:`NEXT_PUBLIC_ZENOVAY_SITE`,packageDeps:[`@zenovay/tracker`],supportsNpmMode:!0,buildSnippets:Oe},Me=[`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 Ne(e){for(let t of Me)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 Fe(e){let t=await Pe(e);if(!t)return{matched:!1,confidence:0,reason:"package.json does not list `next` as a dependency."};let n=await Ne(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 Ie(e){let t=`pages/_app.tsx`,n=e.trackingCode??e.siteId??``,r=`import type { AppProps } from 'next/app';
|
|
39
39
|
import Script from 'next/script';
|
|
40
40
|
|
|
41
41
|
export default function App({ Component, pageProps }: AppProps) {
|
|
@@ -51,7 +51,7 @@ export default function App({ Component, pageProps }: AppProps) {
|
|
|
51
51
|
</>
|
|
52
52
|
);
|
|
53
53
|
}
|
|
54
|
-
`;return[{targetPath:t,anchorKind:`after-imports`,code:`import Script from 'next/script';`,description:"Import next/script in `_app`."},{targetPath:t,anchorKind:`wrap-children`,code:`<><Script defer data-id="${n}" src="https://api.zenovay.com/z.js" strategy="afterInteractive" /><Component {...pageProps} /></>`,description:`Render the Zenovay tracker alongside the page component.`},{targetPath:t,anchorKind:`replace-file`,code:r,description:"Full replacement when `_app` does not exist yet."}]}const
|
|
54
|
+
`;return[{targetPath:t,anchorKind:`after-imports`,code:`import Script from 'next/script';`,description:"Import next/script in `_app`."},{targetPath:t,anchorKind:`wrap-children`,code:`<><Script defer data-id="${n}" src="https://api.zenovay.com/z.js" strategy="afterInteractive" /><Component {...pageProps} /></>`,description:`Render the Zenovay tracker alongside the page component.`},{targetPath:t,anchorKind:`replace-file`,code:r,description:"Full replacement when `_app` does not exist yet."}]}const Le={id:`next-pages-router`,displayName:`Next.js (Pages Router)`,detect:Fe,files:[{path:`pages/_app.tsx`,kind:`mutate`,required:!0}],envVarName:`NEXT_PUBLIC_ZENOVAY_SITE`,buildSnippets:Ie},Re=T.object({modules:T.array(T.string()).optional(),runtimeConfig:T.object({public:T.record(T.string(),T.unknown()).optional()}).optional()}).passthrough();async function ze(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json found.`};try{let e=JSON.parse(t),n=!!(e.dependencies?.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 Be(e){let t=e.trackingCode??e.siteId??``,n=` app: {
|
|
55
55
|
head: {
|
|
56
56
|
script: [
|
|
57
57
|
{
|
|
@@ -61,20 +61,20 @@ export default function App({ Component, pageProps }: AppProps) {
|
|
|
61
61
|
},
|
|
62
62
|
],
|
|
63
63
|
},
|
|
64
|
-
},`;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
|
|
64
|
+
},`;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 Ve={id:`nuxt`,displayName:`Nuxt`,detect:ze,files:[{path:`nuxt.config.ts`,kind:`mutate`,required:!0}],envVarName:`NUXT_PUBLIC_ZENOVAY_SITE`,buildSnippets:Be},He=[`index.html`,`public/index.html`,`dist/index.html`];async function Ue(e){for(let t of He)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 We(e){let t=e.trackingCode??e.siteId??``,n=`<script defer\n data-id="${t}"\n src="https://api.zenovay.com/z.js">\n</script>`;return[{targetPath:`index.html`,anchorKind:`head-tag`,code:n,description:`Inject the Zenovay tracker inside <head>. Repeat for every HTML file that contains a <head>.`}]}const Ge={id:`plain-html`,displayName:`Plain HTML`,detect:Ue,files:[{path:`index.html`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:We};async function Ke(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json.`};try{let e=JSON.parse(t),n={...e.dependencies??{},...e.devDependencies??{}};if(n[`@builder.io/qwik-city`]??n[`@builder.io/qwik`])return{matched:!0,confidence:.92,reason:"Detected Qwik via `@builder.io/qwik(-city)`."}}catch{}return{matched:!1,confidence:0,reason:`No Qwik dependency found.`}}function qe(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`src/root.tsx`,r=`<script
|
|
65
65
|
defer
|
|
66
66
|
data-id="${t}"
|
|
67
67
|
src="https://api.zenovay.com/z.js"
|
|
68
|
-
/>`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Add the Zenovay tracker into the <head> of the Qwik root document.`}]}const
|
|
68
|
+
/>`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Add the Zenovay tracker into the <head> of the Qwik root document.`}]}const Je={id:`qwik`,displayName:`Qwik`,detect:Ke,files:[{path:`src/root.tsx`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:qe};async function Ye(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 Xe(e){let t=e.trackingCode??e.siteId??``;return[{targetPath:`app/root.tsx`,anchorKind:`head-tag`,code:`<script defer data-id="${t}" src="https://api.zenovay.com/z.js"></script>`,description:`Inline the Zenovay tracker <script> inside the document <head>.`}]}const Ze={id:`remix`,displayName:`Remix`,detect:Ye,files:[{path:`app/root.tsx`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:Xe};async function Qe(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json.`};try{let e=JSON.parse(t),n={...e.dependencies??{},...e.devDependencies??{}};if(n[`@solidjs/start`]??n[`solid-start`])return{matched:!0,confidence:.92,reason:"Detected SolidStart via `@solidjs/start` / `solid-start`."}}catch{}return{matched:!1,confidence:0,reason:`No SolidStart dependency found.`}}function $e(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`src/entry-server.tsx`,r=`<script
|
|
69
69
|
defer
|
|
70
70
|
data-id="${t}"
|
|
71
71
|
src="https://api.zenovay.com/z.js"
|
|
72
|
-
/>`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Add the Zenovay tracker into the document <head> rendered by SolidStart entry-server.`}]}const
|
|
72
|
+
/>`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Add the Zenovay tracker into the document <head> rendered by SolidStart entry-server.`}]}const et={id:`solid-start`,displayName:`SolidStart`,detect:Qe,files:[{path:`src/entry-server.tsx`,kind:`mutate`,required:!0}],envVarName:`VITE_ZENOVAY_SITE`,buildSnippets:$e};async function tt(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 nt(e){let t=e.trackingCode??e.siteId??``,n=`<svelte:head>
|
|
73
73
|
<script defer data-id="${t}" src="https://api.zenovay.com/z.js"></script>
|
|
74
74
|
</svelte:head>
|
|
75
75
|
|
|
76
76
|
<slot />
|
|
77
|
-
`;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
|
|
77
|
+
`;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 rt={id:`sveltekit`,displayName:`SvelteKit`,detect:tt,files:[{path:`src/routes/+layout.svelte`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:nt},it=[`next`,`nuxt`,`nuxt3`,`@sveltejs/kit`,`astro`,`@remix-run/react`,`@builder.io/qwik-city`,`@builder.io/qwik`,`@solidjs/start`,`solid-start`,`@angular/core`,`gatsby`],at=[`index.html`,`public/index.html`];async function ot(e){let t=await e.readFile(`package.json`);if(!t)return{};try{let e=JSON.parse(t);return{...e.dependencies??{},...e.devDependencies??{}}}catch{return{}}}async function st(e){for(let t of at)if(await e.exists(t))return t;return null}async function ct(e){let t=await ot(e);if(it.some(e=>t[e]))return{matched:!1,confidence:0,reason:`A Vite-based meta-framework (Next/Nuxt/SvelteKit/Astro/Remix/Qwik/Solid/Angular) owns this project.`};let n=!!t.vite,r=await st(e);return n&&r?{matched:!0,confidence:.85,reason:`Detected a Vite app via \`vite\` dependency + \`${r}\`.`}:n?{matched:!0,confidence:.55,reason:"Detected `vite` but no index.html — the agent will locate the SPA entry."}:{matched:!1,confidence:0,reason:"No `vite` dependency found."}}function lt(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`index.html`,r=`<script defer\n data-id="${t}"\n src="https://api.zenovay.com/z.js">\n</script>`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Inject the Zenovay tracker inside <head> of the Vite entry HTML.`}]}const ut={id:`vite`,displayName:`Vite`,detect:ct,files:[{path:`index.html`,kind:`mutate`,required:!0}],envVarName:`VITE_ZENOVAY_SITE`,buildSnippets:lt},dt=[je,Le,Ve,rt,q,Ze,Ce,_e,et,Je,ut,Ge];async function ft(e){let t=[];for(let n of dt){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 pt(e){let t=t=>C.resolve(e,t);return{cwd:e,async readFile(e){try{return await w.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 w.access(t(e)),!0}catch{return!1}},async glob(t){return ie(t,{cwd:e,dot:!1,gitignore:!0,onlyFiles:!0,followSymbolicLinks:!1})}}}async function mt(e,t){let n=pt(e),{adapter:r,ranked:i}=await ft(n),a=i[0];return r&&a&&a.result.confidence>=.7?r:t?t.pickInteractively(i):r}function ht(e){let t=/[\s"'#=]/.test(e)||e===``,n=t?`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:e;return n}function gt(e,t){return`${e}=${ht(t)}`}async function Y(e,t,n={}){let r=n.filename??`.env.local`,i=C.resolve(e,r),a=``,o=!0;try{a=await w.readFile(i,`utf8`)}catch(e){if(e.code===`ENOENT`)o=!1;else throw e}let s=[],c=[],l=[],u=[],d=a;for(let[e,n]of Object.entries(t)){let t=RegExp(`^(\\s*)(export\\s+)?(${e})(\\s*=\\s*)(.*)$`,`gm`),r=!1,i=!1;if(d=d.replace(t,(t,a,o,s,c,l)=>{r=!0;let u=ht(n),d=l.trim();return d===u||!/ZENOVAY/i.test(e)?t:(i=!0,`${a}${o??``}${s}${c}${u}`)}),r){i?c.push(e):l.push(e);continue}u.push(gt(e,n)),s.push(e)}if(s.length===0&&c.length===0)return{file:r,created:!1,existing:o,addedKeys:s,updatedKeys:c,skippedKeys:l};let f=`# Added by Zenovay CLI`,p;if(o&&u.length>0){let e=d.length>0&&!d.endsWith(`
|
|
78
78
|
`);p=d+(e?`
|
|
79
79
|
`:``)+`
|
|
80
80
|
`+f+`
|
|
@@ -83,12 +83,13 @@ export default function App({ Component, pageProps }: AppProps) {
|
|
|
83
83
|
`}else p=o?d:f+`
|
|
84
84
|
`+u.join(`
|
|
85
85
|
`)+`
|
|
86
|
-
`;if(await n.beforeWrite?.(i),o)await w.writeFile(i,p,`utf8`);else{let e=await w.open(i,`w`,384);try{await e.writeFile(p,`utf8`)}finally{await e.close()}}return{file:r,created:!o,existing:o,addedKeys:s,updatedKeys:c,skippedKeys:l}}const
|
|
87
|
-
`,`utf8`),await w.chmod(e.configPath,384).catch(()=>void 0),i.push(e.displayName)}catch(t){o.push({client:e.displayName,message:t instanceof Error?t.message:String(t)})}}return{installed:i,skipped:a,errors:o}}async function
|
|
88
|
-
`,i=r.replace(/\n/g,`${n}`);return`${n}${i}${n}</head>`}),s===o){t.skipped.push({file:a,reason:`</head> regex did not match unexpectedly`});continue}}else{t.skipped.push({file:a,reason:`no <head>...</head> in file (fragment or non-page)`});continue}let c=null;for(let{name:e,re:t}of
|
|
86
|
+
`;if(await n.beforeWrite?.(i),o)await w.writeFile(i,p,`utf8`);else{let e=await w.open(i,`w`,384);try{await e.writeFile(p,`utf8`)}finally{await e.close()}}return{file:r,created:!o,existing:o,addedKeys:s,updatedKeys:c,skippedKeys:l}}const _t=`https://api.zenovay.com/mcp`,vt=T.object({url:T.string().url(),headers:T.record(T.string(),T.string()).optional()}).passthrough(),yt=T.object({mcpServers:T.record(T.string(),vt).optional()}).passthrough();function bt(e){return e.HOME??e.USERPROFILE??E.homedir()}function xt(e){return e.APPDATA??null}function St(e,t){let n=bt(t),r=xt(t),i=[];return i.push({id:`claude-code`,displayName:`Claude Code`,configPath:C.join(n,`.claude.json`),serversKey:`mcpServers`,includeType:!0}),i.push({id:`cursor`,displayName:`Cursor`,configPath:C.join(n,`.cursor`,`mcp.json`),serversKey:`mcpServers`,includeType:!1}),e===`win32`&&r&&i.push({id:`cursor`,displayName:`Cursor (AppData)`,configPath:C.join(r,`Cursor`,`User`,`globalStorage`,`cursor.mcp`,`mcp.json`),serversKey:`mcpServers`,includeType:!1}),e===`darwin`?i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:C.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`),serversKey:`mcpServers`,includeType:!0}):e===`win32`&&r?i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:C.join(r,`Claude`,`claude_desktop_config.json`),serversKey:`mcpServers`,includeType:!0}):i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:C.join(n,`.config`,`Claude`,`claude_desktop_config.json`),serversKey:`mcpServers`,includeType:!0}),i.push({id:`vscode`,displayName:`VS Code`,configPath:C.join(n,`.vscode`,`mcp.json`),serversKey:`servers`,includeType:!0}),i}async function Ct(e){try{return await w.access(e),!0}catch{return!1}}async function wt(e){try{let t=await w.readFile(e,`utf8`);if(t.trim().length===0)return{};let n=JSON.parse(t),r=yt.safeParse(n);return r.success?r.data:n&&typeof n==`object`?n:{}}catch{return{}}}function Tt(e){return e?{type:`http`,url:_t}:{url:_t}}function Et(e){return!e||typeof e!=`object`?!1:Object.values(e).some(e=>e&&typeof e==`object`&&e.url===_t)}async function X(e){let t=e.env??process.env,n=e.platform??process.platform,r=new Set(e.skip??[]),i=[],a=[],o=[],s=new Set;for(let e of St(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 Ct(e.configPath);if(!t){a.push(e.displayName);continue}let n=await wt(e.configPath),r=n[e.serversKey];if(Et(r)){i.push(e.displayName);continue}let o=`${e.configPath}.bak`;await w.copyFile(e.configPath,o);let s=r&&typeof r==`object`?r:{},c={...n,[e.serversKey]:{...s,zenovay:Tt(e.includeType)}};await w.mkdir(C.dirname(e.configPath),{recursive:!0}),await w.writeFile(e.configPath,JSON.stringify(c,null,2)+`
|
|
87
|
+
`,`utf8`),await w.chmod(e.configPath,384).catch(()=>void 0),i.push(e.displayName)}catch(t){o.push({client:e.displayName,message:t instanceof Error?t.message:String(t)})}}return{installed:i,skipped:a,errors:o}}async function Dt(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 Ot=T.object({path:T.string().min(1)}),kt=T.object({path:T.string().min(1),content:T.string(),reason:T.string().min(1)}),At=T.object({path:T.string().min(1),patch:T.string().min(1),reason:T.string().min(1)}),jt=T.object({}),Mt=T.object({question:T.string().min(1),choices:T.array(T.string()).optional()});async function Nt(e,t){let n=Ot.safeParse(t);if(!n.success)return{ok:!1,content:null,error:`invalid_args`};try{let t=await e.safeRead(n.data.path),r=H.scrubSecrets(t),i=24e3,a=r.length>i?`${r.slice(0,i)}\n\n[... truncated: file is ${r.length} chars; showing the first ${i}]`:r;return{ok:!0,content:H.wrapForModel(n.data.path,a)}}catch(e){return{ok:!1,content:null,error:e.message}}}async function Pt(e,t,n){let r=kt.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 Ft(e,t,n){let r=At.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=ae(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.`}:Pt(e,{path:i,content:c,reason:o},n)}async function It(e){try{let t=pt(e),{adapter:n,ranked:r}=await ft(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 Lt(e,t){let n=Mt.safeParse(t);if(!n.success)return{ok:!1,content:null,error:`invalid_args`};try{let t=await e.ask(n.data);return{ok:!0,content:{answer:t}}}catch(e){return{ok:!1,content:null,error:e.message}}}const Rt=3;function zt(e,t,n){if(n)return e.delete(t),null;let r=(e.get(t)??0)+1;return e.set(t,r),r>=Rt?`STOP retrying ${t}: it failed ${r} times. Do NOT call write_file/patch_file on ${t} again — edit a different entry file, or if the tracker is already present, stop and return.`:null}async function Bt(e){let{api:t,sandbox:n,approval:r,prompter:i,handlers:a}=e,o=[...e.initialMessages],s=``,c=0,l=new Map;for(;c<z;){n.incrementRound(),c++;let u=new AbortController,f=9e4,p=()=>{let e=setTimeout(()=>u.abort(),f);return e.unref?.(),e},m=p(),h=()=>{clearTimeout(m),m=p()},g;try{g=await t.openAiStream(`install`,{messages:o,cwd_fingerprint:n.sessionId,diagnosis:e.diagnosis,targetTrackingCode:e.targetTrackingCode},u.signal)}catch(e){throw clearTimeout(m),e}let _=[],v=``;for await(let e of d(g))switch(h(),e.type){case`delta`:v+=e.content,a?.onDelta?.(e.content);break;case`tool_start`:a?.onToolStart?.({id:e.id,name:e.name});break;case`tool_call`:{clearTimeout(m);let t=await Vt(e.name,e.arguments,{sandbox:n,cwd:n.cwd,approval:r,prompter:i});h();let o=(e.name===`write_file`||e.name===`patch_file`)&&typeof e.arguments.path==`string`?e.arguments.path:null;if(o){let e=zt(l,o,t.ok!==!1);e&&(t={...t,error:`${t.error??`write_failed`} — ${e}`})}_.push({id:e.id,name:e.name,arguments:e.arguments,result:t}),a?.onToolResult?.({id:e.id,name:e.name,result:t});break}case`usage`:a?.onUsage?.(e);break;case`error`:throw clearTimeout(m),a?.onError?.(e),Error(`[${e.code}] ${e.message}`);case`done`:break}if(clearTimeout(m),v&&(s+=v),_.length===0){v&&o.push({role:`assistant`,content:v});break}o.push({role:`assistant`,content:v,toolCalls:_.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))});for(let e of _)o.push({role:`tool`,toolCallId:e.id,toolName:e.name,content:JSON.stringify(e.result)})}return{finalText:s,rounds:c}}async function Vt(e,t,n){try{switch(e){case`read_file`:return await Nt(n.sandbox,t);case`write_file`:return await Pt(n.sandbox,t,n.approval);case`patch_file`:return await Ft(n.sandbox,t,n.approval);case`detect_framework`:return await It(n.cwd);case`ask_user`:return await Lt(n.prompter,t);default:return{ok:!1,content:null,error:`unknown_tool:${e}`}}}catch(e){return{ok:!1,content:null,error:`tool_threw: ${e.message}`}}}const Ht="What to do: re-run with `--review` to approve each write, or install manually (see https://docs.zenovay.com/en/integrations/cli).";function Ut(e,t,n,r){if(e.writes===0){let t=r?`Agent error: ${r.message}`:`Agent returned without writing any files (${e.reads} reads, ${e.rounds} rounds). The model may have refused or the AI Gateway may be misconfigured.`;return{ok:!1,error:`${t}\n${Ht} Nothing was changed in your project.`}}if(!t.includes(n)){let r=e.writtenPaths.join(`, `)||`(none)`,i=t.length?` (found other code(s): ${t.join(`, `)})`:``;return{ok:!1,error:`Agent wrote to: [${r}] but no Zenovay tracker <script> with your code (${n}) is present in any source file${i} — the tracker is NOT installed. The model likely wrote the code into .env only, or edited the wrong file.\n${Ht} Review/undo what was written under ~/.zenovay/undo/.`}}return{ok:!0}}const Wt=e=>`<script defer\n data-id="${e}"\n src="https://api.zenovay.com/z.js">\n</script>`;async function Gt(e){let t={installed:[],skipped:[],errors:[]};if(!Z(e.trackingCode))return t.errors.push({file:`(input)`,error:`Unexpected tracking-code format: "${e.trackingCode}". Expected letters, digits, "_" or "-".`}),t;let n=await ie(`**/*.html`,{cwd:e.cwd,gitignore:!0,expandDirectories:!1,absolute:!1,ignore:[`node_modules/**`,`.git/**`,`dist/**`,`.next/**`,`.nuxt/**`,`build/**`,`.output/**`]});if(n.length===0)return t;let r=Wt(e.trackingCode),i=RegExp(`data-id\\s*=\\s*["']${Kt(e.trackingCode)}["']`);for(let a of n){let n=C.join(e.cwd,a),o;try{o=await w.readFile(n,`utf8`)}catch(e){t.errors.push({file:a,error:e.message});continue}if(V.test(o)&&i.test(o)){t.skipped.push({file:a,reason:`already installed with correct tracking code`});continue}let s;if(V.test(o))s=o.replace(/(<script[^>]*src\s*=\s*["']https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+["'][^>]*>)/i,t=>t.replace(/data-id\s*=\s*["']ZV_\w+["']/i,`data-id="${e.trackingCode}"`)),s===o&&(s=o.replace(/<script(\s)/i,`<script$1data-id="${e.trackingCode}"$1`));else if(e.updateOnly){t.skipped.push({file:a,reason:`updateOnly=true and no Zenovay tag present`});continue}else if(/<\/head>/i.test(o)){if(s=o.replace(/(\n[\t ]*)?<\/head>/i,(e,t)=>{let n=t??`
|
|
88
|
+
`,i=r.replace(/\n/g,`${n}`);return`${n}${i}${n}</head>`}),s===o){t.skipped.push({file:a,reason:`</head> regex did not match unexpectedly`});continue}}else{t.skipped.push({file:a,reason:`no <head>...</head> in file (fragment or non-page)`});continue}let c=null;for(let{name:e,re:t}of ue)if(t.test(o)&&!t.test(s)){c=e;break}if(c){t.errors.push({file:a,error:`would remove ${c} tracker — refusing to write`});continue}try{await e.beforeWrite?.(n),await w.writeFile(n,s,`utf8`),t.installed.push(a)}catch(e){t.errors.push({file:a,error:e.message})}}return t}function Kt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Z(e){return typeof e==`string`&&e.length>0&&e.length<=64&&/^[A-Za-z0-9_-]+$/.test(e)}function qt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const Jt=/<[Ss]cript\b[^>]*\bsrc\s*=\s*["'`][^"'`]*(?:api\.zenovay\.com\/z\.js|\/(?:api\/)?_z\/script\.js)[^"'`]*["'`][^>]*>/;function Yt(e){return Jt.test(e)}function Xt(e){return/api\.zenovay\.com\/z\.js/i.test(e)||/\/(?:api\/)?_z\/script\.js/i.test(e)}function Zt(e,t){let n=qt(t),r=e.match(new RegExp(Jt.source,`gi`))||[];return r.length===0?!1:r.every(e=>{let t=/\/(?:api\/)?_z\/script\.js/i.test(e);return t?RegExp(`[?&]id=${n}(?:["'\`&\\s/]|$)`).test(e):RegExp(`\\bdata-id\\s*=\\s*["'\`]${n}["'\`]`).test(e)})}function Qt(e,t){return e.replace(/<[Ss]cript\b[^>]*>/g,e=>{let n=/\bsrc\s*=\s*["'`][^"'`]*api\.zenovay\.com\/z\.js/.test(e),r=/\bsrc\s*=\s*["'`][^"'`]*\/(?:api\/)?_z\/script\.js/.test(e);if(!n&&!r)return e;let i=e.replace(/(\bdata-id\s*=\s*["'`])[^"'`]*(["'`])/i,`$1${t}$2`);return r&&(i=i.replace(/([?&]id=)[^&"'`\s]*/i,`$1${encodeURIComponent(t)}`)),i})}const $t=`https://api.zenovay.com/z.js`;function en(e){if(/from\s+['"]next\/script['"]/.test(e))return e;let t=e.split(`
|
|
89
89
|
`),n=-1;for(let e=0;e<t.length;e++)/^\s*import\s/.test(t[e])&&(n=e);let r=`import Script from 'next/script';`;if(n>=0)t.splice(n+1,0,r);else{let e=/^\s*['"]use client['"];?\s*$/.test(t[0]??``);t.splice(e?1:0,0,r)}return t.join(`
|
|
90
|
-
`)}function
|
|
91
|
-
`,n-1)+1,i=(e.slice(r,n).match(/^[ \t]*/)??[``])[0],a=`${i}${t}\n`;return e.slice(0,r)+a+e.slice(r)}async function
|
|
90
|
+
`)}function tn(e,t){let n=/([ \t]*)<\/body>/,r=e.match(n);if(!r)return null;let i=r[1]??``,a=`${i} <Script defer data-id="${t}" src="${$t}" strategy="afterInteractive" />`;return e.replace(n,`${a}\n${i}</body>`)}async function nn(e){let{cwd:t,trackingCode:n}=e,r={installed:[],skipped:[],errors:[],fellThrough:!1};if(!Z(n))return r.errors.push({file:`(input)`,error:`unexpected tracking-code format: "${n}"`}),r;let i;try{i=await ie([`app/**/layout.{tsx,ts,jsx,js}`,`src/app/**/layout.{tsx,ts,jsx,js}`],{cwd:t,gitignore:!1,ignore:[`**/node_modules/**`]})}catch(e){return r.errors.push({file:`app/**/layout`,error:e.message}),r.fellThrough=!0,r}if(i.length===0)return r.fellThrough=!0,r;let a=[];for(let e of i)try{let n=await j.readFile(C.join(t,e),`utf8`);/<body[\s/>]/.test(n)&&a.push({rel:e,src:n,depth:e.split(`/`).length})}catch{}if(a.length===0)return r.fellThrough=!0,r;a.sort((e,t)=>e.depth-t.depth);let o=a[0];if(Zt(o.src,n))return r.skipped.push({file:o.rel,reason:`already installed with correct tracking code`}),r;if(Jt.test(o.src)){let i=Qt(o.src,n);if(i!==o.src){try{let n=C.join(t,o.rel);await e.beforeWrite?.(n),await j.writeFile(n,i),r.installed.push(o.rel)}catch(e){r.errors.push({file:o.rel,error:e.message}),r.fellThrough=!0}return r}return r.fellThrough=!0,r}if(Xt(o.src))return r.fellThrough=!0,r;let s=en(o.src),c=tn(s,n);if(!c)return r.fellThrough=!0,r;try{let n=C.join(t,o.rel);await e.beforeWrite?.(n),await j.writeFile(n,c),r.installed.push(o.rel)}catch(e){r.errors.push({file:o.rel,error:e.message}),r.fellThrough=!0}return r}const rn=`api.zenovay.com/z.js`;async function an(e){try{return await w.readFile(e,`utf8`)}catch{return null}}function on(e,t){let n=e.toLowerCase().lastIndexOf(`</head>`);if(n===-1)return null;let r=e.lastIndexOf(`
|
|
91
|
+
`,n-1)+1,i=(e.slice(r,n).match(/^[ \t]*/)??[``])[0],a=`${i}${t}\n`;return e.slice(0,r)+a+e.slice(r)}async function sn(e,t,n,r,i,a=0,o=new Set){if(a>4)return null;let s=C.dirname(e),c=/import\s+[^;]*?from\s*['"`](\.[^'"`]+\.(?:astro|tsx|jsx|vue|svelte))['"`]/g,l=[],u;for(;(u=c.exec(t))!==null;){let e=C.resolve(s,u[1]);if(o.has(e))continue;o.add(e);let t=await an(e);if(t===null)continue;if(Yt(t)){if(Zt(t,r))return e;let n=Qt(t,r);return n!==t&&(await i?.(e),await w.writeFile(e,n,`utf8`)),e}if(Xt(t))return e;let a=on(t,n);if(a!==null)return await i?.(e),await w.writeFile(e,a,`utf8`),e;l.push({abs:e,content:t})}for(let e of l){let t=await sn(e.abs,e.content,n,r,i,a+1,o);if(t)return t}return null}async function cn(e){if(!Z(e.trackingCode))return{installed:[],skipped:[],errors:[{file:`(input)`,error:`unexpected tracking-code format: "${e.trackingCode}"`}],fellThrough:!1};if(e.adapter.id===`nuxt`)return un(e);if(e.adapter.id===`sveltekit`)return dn(e);let{cwd:t,trackingCode:n,siteId:r,adapter:i}=e,a={installed:[],skipped:[],errors:[],fellThrough:!1},o;try{o=i.buildSnippets({trackingCode:n,siteId:r??``},`script`)}catch{return a.fellThrough=!0,a}if(!o||o.length===0)return a.fellThrough=!0,a;let s=new Set(o.map(e=>e.anchorKind));if(s.size===1&&s.has(`head-tag`)){let r=!1;for(let i of o){let o=C.join(t,i.targetPath),s=await an(o);if(s===null){a.skipped.push({file:i.targetPath,reason:`target file not present`});continue}if(Zt(s,n)){a.skipped.push({file:i.targetPath,reason:`already installed with correct tracking code`}),r=!0;break}if(Yt(s)){let t=Qt(s,n);if(t!==s)try{await e.beforeWrite?.(o),await w.writeFile(o,t,`utf8`),a.installed.push(i.targetPath),r=!0;break}catch(e){a.errors.push({file:i.targetPath,error:e.message});continue}return a.fellThrough=!0,a}if(Xt(s)){a.skipped.push({file:i.targetPath,reason:`tracker present in an unparseable form (not double-inserting)`}),r=!0;break}let c=on(s,i.code);if(c===null){let c=await sn(o,s,i.code,n,e.beforeWrite);if(c){a.installed.push(C.relative(t,c)),r=!0;break}a.skipped.push({file:i.targetPath,reason:`no </head> anchor (inline or in an imported head component)`});continue}try{await e.beforeWrite?.(o),await w.writeFile(o,c,`utf8`),a.installed.push(i.targetPath),r=!0;break}catch(e){a.errors.push({file:i.targetPath,error:e.message})}}return!r&&a.installed.length===0&&a.errors.length===0&&(a.fellThrough=!0),a}if(s.size===1&&s.has(`replace-file`)&&o.length===1){let r=o[0];if(!r)return a.fellThrough=!0,a;let s=i.files.find(e=>e.path===r.targetPath),c=C.join(t,r.targetPath),l=await an(c);if(l!==null)return l.includes(rn)&&l.includes(n)?(a.skipped.push({file:r.targetPath,reason:`already installed with correct tracking code`}),a):(a.fellThrough=!0,a);if(s?.kind===`create`){try{await e.beforeWrite?.(c),await w.mkdir(C.dirname(c),{recursive:!0}),await w.writeFile(c,r.code,`utf8`),a.installed.push(r.targetPath)}catch(e){a.errors.push({file:r.targetPath,error:e.message}),a.fellThrough=a.installed.length===0}return a}return a.fellThrough=!0,a}return a.fellThrough=!0,a}function ln(){return{installed:[],skipped:[],errors:[],fellThrough:!1}}async function un(e){let t=ln(),n=[`nuxt.config.ts`,`nuxt.config.mjs`,`nuxt.config.js`],r=null,i=null,a=null;for(let t of n){let n=C.join(e.cwd,t),o=await an(n);if(o!==null){r=t,i=n,a=o;break}}if(a===null||i===null||r===null)return t.skipped.push({file:`nuxt.config.ts`,reason:`nuxt.config not found`}),t.fellThrough=!0,t;if(a.includes(rn))return a.includes(e.trackingCode)?(t.skipped.push({file:r,reason:`already installed with correct tracking code`}),t):(t.fellThrough=!0,t);if(/\bapp\s*:/.test(a))return t.fellThrough=!0,t;let o=a.match(/defineNuxtConfig\s*\(\s*\{/);if(!o||o.index===void 0)return t.fellThrough=!0,t;let s=e.adapter.buildSnippets({trackingCode:e.trackingCode,siteId:e.siteId??``},`script`)[0]?.code;if(!s)return t.fellThrough=!0,t;let c=o.index+o[0].length,l=`${a.slice(0,c)}\n${s}${a.slice(c)}`;try{await e.beforeWrite?.(i),await w.writeFile(i,l,`utf8`),t.installed.push(r)}catch(e){t.errors.push({file:r,error:e.message}),t.fellThrough=!0}return t}async function dn(e){let t=ln(),n=`src/routes/+layout.svelte`,r=C.join(e.cwd,n),i=await an(r),a=`<svelte:head>\n <script defer data-id="${e.trackingCode}" src="https://api.zenovay.com/z.js"></script>\n</svelte:head>\n`;if(i!==null){if(Zt(i,e.trackingCode))return t.skipped.push({file:n,reason:`already installed with correct tracking code`}),t;if(Yt(i)){let a=Qt(i,e.trackingCode);if(a!==i){try{await e.beforeWrite?.(r),await w.writeFile(r,a,`utf8`),t.installed.push(n)}catch(e){t.errors.push({file:n,error:e.message}),t.fellThrough=!0}return t}return t.fellThrough=!0,t}if(Xt(i))return t.fellThrough=!0,t;let o=i.indexOf(`</svelte:head>`),s=o>=0?i.slice(0,o)+` <script defer data-id="${e.trackingCode}" src="https://api.zenovay.com/z.js"></script>\n`+i.slice(o):`${a}\n${i}`;try{await e.beforeWrite?.(r),await w.writeFile(r,s,`utf8`),t.installed.push(n)}catch(e){t.errors.push({file:n,error:e.message}),t.fellThrough=!0}return t}let o=e.adapter.buildSnippets({trackingCode:e.trackingCode,siteId:e.siteId??``},`script`)[0]?.code;if(!o)return t.fellThrough=!0,t;try{await e.beforeWrite?.(r),await w.mkdir(C.dirname(r),{recursive:!0}),await w.writeFile(r,o,`utf8`),t.installed.push(n)}catch(e){t.errors.push({file:n,error:e.message}),t.fellThrough=!0}return t}async function fn(e,t){try{return await w.access(C.join(e,t)),!0}catch{return!1}}async function pn(e,t){try{let n=await w.stat(C.join(e,t));return n.isDirectory()}catch{return!1}}async function mn(e,t){try{return await w.readFile(C.join(e,t),`utf8`)}catch{return null}}const hn=[`next.config.js`,`next.config.mjs`,`next.config.cjs`,`next.config.ts`];async function gn(e){let t=[],n=await mn(e,`wrangler.toml`),r=n!==null&&/^\s*pages_build_output_dir\s*=/m.test(n),i=await pn(e,`functions`),a=await pn(e,`.cloudflare`);if(r&&t.push(`wrangler.toml has pages_build_output_dir`),i&&t.push(`functions/ directory present`),a&&t.push(`.cloudflare/ directory present`),r||a)return{host:`cloudflare-pages`,signals:t};let o=await fn(e,`vercel.json`),s=await pn(e,`.vercel`);if(o&&t.push(`vercel.json present`),s&&t.push(`.vercel/ directory present`),o||s)return{host:`vercel`,signals:t};let c=await fn(e,`netlify.toml`),l=await fn(e,C.join(`public`,`_redirects`)),u=await fn(e,`_redirects`);if(c&&t.push(`netlify.toml present`),l&&t.push(`public/_redirects present`),u&&t.push(`_redirects present`),c||l||u)return{host:`netlify`,signals:t};let d=null;for(let t of hn)if(await fn(e,t)){d=t;break}return d?(t.push(`${d} present (no Vercel/Netlify/CF-Pages signal)`),{host:`nextjs-server`,signals:t}):(t.push(`no deployment-host signals found`),{host:`unknown`,signals:t})}function _n(e){if(!e)return;let t=e.trim().toLowerCase();if(t===`cloudflare-pages`||t===`cloudflare`||t===`cf-pages`||t===`pages`)return`cloudflare-pages`;if(t===`vercel`)return`vercel`;if(t===`netlify`)return`netlify`;if(t===`nextjs`||t===`next`||t===`nextjs-server`)return`nextjs-server`}const vn=`https://api.zenovay.com`,yn=`// Auto-generated by @zenovay/cli — first-party tracking proxy. Do not edit.`,bn=2;function xn(e){return`${yn}
|
|
92
|
+
// @zenovay/cli-proxy-version: ${bn}
|
|
92
93
|
/**
|
|
93
94
|
* First-Party Proxy for Zenovay Tracking.
|
|
94
95
|
*
|
|
@@ -108,12 +109,37 @@ interface Env {
|
|
|
108
109
|
NEXT_PUBLIC_API_URL?: string
|
|
109
110
|
}
|
|
110
111
|
|
|
112
|
+
interface CloudflareRequestMetadata {
|
|
113
|
+
country?: string
|
|
114
|
+
city?: string
|
|
115
|
+
region?: string
|
|
116
|
+
latitude?: string | number
|
|
117
|
+
longitude?: string | number
|
|
118
|
+
timezone?: string
|
|
119
|
+
}
|
|
120
|
+
|
|
111
121
|
interface EventContext {
|
|
112
|
-
request: Request
|
|
122
|
+
request: Request & { readonly cf?: CloudflareRequestMetadata }
|
|
113
123
|
params: { path?: string[] }
|
|
114
124
|
env: Env
|
|
115
125
|
}
|
|
116
126
|
|
|
127
|
+
// These are the only browser-provided headers the analytics API needs. Never
|
|
128
|
+
// clone request.headers here: this is a same-origin endpoint, so the request can
|
|
129
|
+
// contain the customer's session Cookie, Authorization token, Cloudflare
|
|
130
|
+
// Access assertion, and arbitrary private application headers.
|
|
131
|
+
const ANALYTICS_REQUEST_HEADERS = [
|
|
132
|
+
'Accept',
|
|
133
|
+
'Accept-Language',
|
|
134
|
+
'Content-Type',
|
|
135
|
+
'Content-Encoding',
|
|
136
|
+
'Origin',
|
|
137
|
+
'Referer',
|
|
138
|
+
'User-Agent',
|
|
139
|
+
'Sec-GPC',
|
|
140
|
+
'X-Zenovay-Tracking-Code',
|
|
141
|
+
] as const
|
|
142
|
+
|
|
117
143
|
/**
|
|
118
144
|
* Handle all HTTP methods (GET, POST, OPTIONS).
|
|
119
145
|
*/
|
|
@@ -145,44 +171,37 @@ export async function onRequest(context: EventContext): Promise<Response> {
|
|
|
145
171
|
}
|
|
146
172
|
|
|
147
173
|
try {
|
|
148
|
-
//
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
const
|
|
174
|
+
// CF-Connecting-IP is populated by the Cloudflare runtime. Do not fall
|
|
175
|
+
// back to browser-controlled forwarding headers.
|
|
176
|
+
const clientIP = request.headers.get('CF-Connecting-IP') || ''
|
|
177
|
+
|
|
178
|
+
// Start empty and copy only the documented analytics contract. This keeps
|
|
179
|
+
// ambient customer credentials and spoofed Zenovay trust headers out of
|
|
180
|
+
// the cross-origin request to api.zenovay.com.
|
|
181
|
+
const proxyHeaders = new Headers()
|
|
182
|
+
for (const header of ANALYTICS_REQUEST_HEADERS) {
|
|
183
|
+
const value = request.headers.get(header)
|
|
184
|
+
if (value !== null) proxyHeaders.set(header, value)
|
|
185
|
+
}
|
|
157
186
|
|
|
158
187
|
// Add/set proxy identification headers.
|
|
159
188
|
proxyHeaders.set('X-Zenovay-Proxy', 'first-party')
|
|
160
|
-
proxyHeaders.set('X-Zenovay-Real-IP', clientIP)
|
|
161
|
-
|
|
162
|
-
//
|
|
163
|
-
//
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
if (cfLongitude) proxyHeaders.set('X-Zenovay-CF-Longitude', cfLongitude)
|
|
177
|
-
if (cfTimezone) proxyHeaders.set('X-Zenovay-CF-Timezone', cfTimezone)
|
|
178
|
-
|
|
179
|
-
// Remove headers that shouldn't be forwarded.
|
|
180
|
-
proxyHeaders.delete('Host')
|
|
181
|
-
proxyHeaders.delete('CF-Connecting-IP')
|
|
182
|
-
proxyHeaders.delete('CF-RAY')
|
|
183
|
-
proxyHeaders.delete('CF-Visitor')
|
|
184
|
-
proxyHeaders.delete('CF-IPCountry')
|
|
185
|
-
proxyHeaders.delete('CF-Worker')
|
|
189
|
+
if (clientIP) proxyHeaders.set('X-Zenovay-Real-IP', clientIP)
|
|
190
|
+
|
|
191
|
+
// request.cf is trusted runtime metadata, unlike incoming X-Zenovay-CF-*
|
|
192
|
+
// headers. Re-stamp only values supplied by Cloudflare itself.
|
|
193
|
+
const cf = request.cf || {}
|
|
194
|
+
const trustedGeo: Array<[string, string | number | undefined]> = [
|
|
195
|
+
['X-Zenovay-CF-Country', cf.country],
|
|
196
|
+
['X-Zenovay-CF-City', cf.city],
|
|
197
|
+
['X-Zenovay-CF-Region', cf.region],
|
|
198
|
+
['X-Zenovay-CF-Latitude', cf.latitude],
|
|
199
|
+
['X-Zenovay-CF-Longitude', cf.longitude],
|
|
200
|
+
['X-Zenovay-CF-Timezone', cf.timezone],
|
|
201
|
+
]
|
|
202
|
+
for (const [header, value] of trustedGeo) {
|
|
203
|
+
if (value !== undefined && value !== '') proxyHeaders.set(header, String(value))
|
|
204
|
+
}
|
|
186
205
|
|
|
187
206
|
// Prepare request options. redirect:'manual' so the proxy never follows an
|
|
188
207
|
// upstream redirect to an unexpected origin (defense-in-depth).
|
|
@@ -220,6 +239,9 @@ export async function onRequest(context: EventContext): Promise<Response> {
|
|
|
220
239
|
// Clone response headers.
|
|
221
240
|
const responseHeaders = new Headers(response.headers)
|
|
222
241
|
|
|
242
|
+
// The API must never be able to set a cookie on the customer's origin.
|
|
243
|
+
responseHeaders.delete('Set-Cookie')
|
|
244
|
+
|
|
223
245
|
// Add proxy identification.
|
|
224
246
|
responseHeaders.set('X-Zenovay-Proxied', 'true')
|
|
225
247
|
|
|
@@ -297,33 +319,33 @@ export async function onRequestOptions(_context: EventContext): Promise<Response
|
|
|
297
319
|
},
|
|
298
320
|
})
|
|
299
321
|
}
|
|
300
|
-
`}async function
|
|
322
|
+
`}function Sn(e,t){if(!e.startsWith(`${yn}\n`))return!1;let n=[`export async function onRequest(context: EventContext): Promise<Response>`,"const targetUrl = `${apiBase}/fp/${path}${new URL(request.url).search}`",`const apiBase = env.NEXT_PUBLIC_API_URL || '${t}'`,`responseHeaders.set('X-Zenovay-Proxied', 'true')`,`export async function onRequestOptions`];return n.every(t=>e.includes(t))}async function Cn(e,t){let n=(t.apiBase||vn).replace(/\/+$/,``),r=C.join(e,`functions`,`api`,`_z`),i=C.join(r,`[[path]].ts`),a=xn(n);try{let e=await w.readFile(i,`utf8`);return e===a?{file:i,action:`exists`}:Sn(e,n)?(await t.beforeWrite?.(i),await w.writeFile(i,a,`utf8`),{file:i,action:`updated`}):{file:i,action:`manual`}}catch(e){if(e.code!==`ENOENT`)throw e}return await t.beforeWrite?.(i),await w.mkdir(r,{recursive:!0}),await w.writeFile(i,a,`utf8`),{file:i,action:`created`}}const wn=`https://api.zenovay.com`,Tn=[`next.config.js`,`next.config.mjs`,`next.config.cjs`,`next.config.ts`];function En(e){return` // Zenovay first-party proxy — forwards /api/_z/* to the tracking API
|
|
301
323
|
{
|
|
302
324
|
source: '/api/_z/:path*',
|
|
303
325
|
destination: '${e}/fp/:path*',
|
|
304
|
-
},`}function
|
|
326
|
+
},`}function Dn(e){return`/** @type {import('next').NextConfig} */
|
|
305
327
|
const nextConfig = {
|
|
306
328
|
async rewrites() {
|
|
307
329
|
return [
|
|
308
|
-
${
|
|
330
|
+
${En(e)}
|
|
309
331
|
];
|
|
310
332
|
},
|
|
311
333
|
};
|
|
312
334
|
|
|
313
335
|
export default nextConfig;
|
|
314
|
-
`}async function
|
|
336
|
+
`}async function On(e,t={}){let n=t.apiBase??wn,r=null;for(let t of Tn){let n=C.join(e,t);try{await j.access(n),r=n;break}catch{}}if(!r){let r=C.join(e,`next.config.mjs`);return await t.beforeWrite?.(r),await j.writeFile(r,Dn(n),`utf8`),{file:r,action:`created`}}let i=await j.readFile(r,`utf8`),a=i.includes(`source: '/api/_z/:path*'`)||i.includes(`source: "/api/_z/:path*"`),o=i.includes(`destination: '${n}/fp/:path*'`)||i.includes(`destination: "${n}/fp/:path*"`);if(a&&o)return{file:r,action:`exists`};if(i.includes(`/api/_z/:path*`)||i.includes(`/_z/:path*`)||/\brewrites\s*(?::|=|\()/.test(i)||/\bredirects\s*\(/.test(i))return{file:r,action:`manual`};let s=[...i.matchAll(/(?:module\.exports\s*=\s*|export\s+default\s+|const\s+\w+\s*(?::\s*[^={\n]{1,80})?=\s*)\{/g)],c=s.length===1?s[0]:null;if(!c||c.index===void 0)return{file:r,action:`manual`};let l=c.index+c[0].length-1,u=i.slice(0,l+1),d=i.slice(l+1),f=`
|
|
315
337
|
async rewrites() {
|
|
316
338
|
return [
|
|
317
|
-
${
|
|
339
|
+
${En(n)}
|
|
318
340
|
];
|
|
319
|
-
},`,p=`${u}${f}${d}`;return await t.beforeWrite?.(r),await j.writeFile(r,p,`utf8`),{file:r,action:`updated`}}const
|
|
341
|
+
},`,p=`${u}${f}${d}`;return await t.beforeWrite?.(r),await j.writeFile(r,p,`utf8`),{file:r,action:`updated`}}const kn=`https://api.zenovay.com`;async function An(e,t={}){let n=t.apiBase??kn,r=C.join(e,`vercel.json`),i={source:`/api/_z/(.*)`,destination:`${n}/fp/$1`},a=null;try{a=await j.readFile(r,`utf8`)}catch{a=null}if(a===null){let e={rewrites:[i]};return await t.beforeWrite?.(r),await j.writeFile(r,`${JSON.stringify(e,null,2)}\n`,`utf8`),{file:r,action:`created`}}let o;try{o=JSON.parse(a)}catch{throw Error(`Cannot parse existing vercel.json at ${r}: invalid JSON`)}if(typeof o!=`object`||!o||Array.isArray(o))throw Error(`Cannot merge into vercel.json at ${r}: top-level value is not a JSON object`);let s=Array.isArray(o.rewrites)?o.rewrites:[],c=s.some(e=>e?.source===i.source&&e?.destination===i.destination);if(c)return{file:r,action:`exists`};if(s.some(e=>typeof e?.source==`string`&&e.source.startsWith(`/api/_z`)))throw Error(`Existing /api/_z rewrite in ${r} does not point to ${i.destination}`);return o.rewrites=[...s,i],await t.beforeWrite?.(r),await j.writeFile(r,`${JSON.stringify(o,null,2)}\n`,`utf8`),{file:r,action:`updated`}}const jn=`https://api.zenovay.com`;async function Mn(e){let t=C.join(e,`_redirects`),n=C.join(e,`public`,`_redirects`);for(let e of[t,n])try{return await j.access(e),e}catch{}try{let t=await j.stat(C.join(e,`public`));if(t.isDirectory())return n}catch{}return t}async function Nn(e,t={}){let n=t.apiBase??jn,r=await Mn(e),i=`/api/_z/* ${n}/fp/:splat 200`,a=null;try{a=await j.readFile(r,`utf8`)}catch{a=null}if(a===null)return await t.beforeWrite?.(r),await j.mkdir(C.dirname(r),{recursive:!0}),await j.writeFile(r,`# Zenovay first-party proxy — forwards /api/_z/* to the tracking API\n${i}\n`,`utf8`),{file:r,action:`created`};let o=a.split(/\r?\n/).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`)),s=i.split(/\s+/).join(` `),c=o.some(e=>e.split(/\s+/).join(` `)===s);if(c)return{file:r,action:`exists`};if(o.some(e=>e.startsWith(`/api/_z/`)))throw Error(`Existing /api/_z redirect in ${r} does not match the Zenovay proxy target`);let l=`# Zenovay first-party proxy — forwards /api/_z/* to the tracking API`,u=a.split(/\r?\n/),d=u.findIndex(e=>{let t=e.trim();return t.length===0||t.startsWith(`#`)?!1:t.split(/\s+/)[0]===`/*`}),f;if(d>=0)u.splice(d,0,l,i),f=u.join(`
|
|
320
342
|
`),f.endsWith(`
|
|
321
343
|
`)||(f+=`
|
|
322
344
|
`);else{let e=a.length>0&&!a.endsWith(`
|
|
323
345
|
`)?`
|
|
324
|
-
`:``;f=`${a}${e}${l}\n${i}\n`}return await t.beforeWrite?.(r),await j.writeFile(r,f,`utf8`),{file:r,action:`updated`}}const Mn="Your tracker is already live and working — it counts visitors in Chrome, Firefox and most browsers, no further setup required. First-party tracking is OPTIONAL and adds the rest: Safari, Brave, and browsers with strict tracking prevention block analytics loaded from another company's domain, so to capture those visitors too you serve Zenovay from your OWN domain. That last step is wired at your hosting provider — enable it any time with `zenovay init --host cloudflare-pages` (or `vercel` / `netlify` / `nextjs`).";async function Nn(e,t){let{trackingCode:n,apiBase:r,forceHost:i,beforeWrite:a}=t,o=`unknown`,s=null,c=`skipped`,l=null,u=!1,d=new Set;try{switch(o=i&&i!==`unknown`?i:(await _n(e)).host,o){case`cloudflare-pages`:{let t=await xn(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&d.add(C.relative(e,t.file));break}case`nextjs-server`:{let t=await En(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&d.add(C.relative(e,t.file)),t.action===`manual`&&(l=`Your tracker is live. To also count Safari/Brave visitors, add this rewrite to ${t.file} yourself (its shape couldn't be edited automatically): { source: '/api/_z/:path*', destination: 'https://api.zenovay.com/fp/:path*' }.`);break}case`vercel`:{let t=await On(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&d.add(C.relative(e,t.file));break}case`netlify`:{let t=await jn(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&d.add(C.relative(e,t.file));break}case`unknown`:default:c=`skipped`,l=Mn;break}c===`manual`&&!l&&(l=`An existing proxy configuration could not be verified safely, so Zenovay kept the standard tracker active. Review the /api/_z rule before enabling first-party tracking.`)}catch(e){s=null,c=`skipped`,l=`${Mn} (auto-setup hit an error: ${e.message.slice(0,120)})`}let p=s!==null&&c!==`manual`&&c!==`skipped`;if(p)try{let t=await f(e,{trackingCode:n,beforeWrite:a});u=t.swapped;for(let e of t.files)d.add(e)}catch{u=!1}return{host:o,proxyFile:s,proxyAction:c,snippetSwapped:u,manual:l,changedFiles:[...d]}}const Pn=`\x1B]8;;`,Fn=`\x07`;function In(){return process.env.FORCE_HYPERLINK?!0:!(process.env.NO_COLOR||!process.stdout.isTTY||process.env.CI||(process.env.TERM??``)===`dumb`)}function Ln({url:e,label:t,color:n,arrow:r=!0}){let{theme:i}=_(),a=n??i.fg,o=(t??e)+(r?` ↗`:``);return In()?M.createElement(A,{color:a,underline:!0},Pn,e,Fn,o,Pn,Fn):t&&t!==e?M.createElement(A,{color:a},M.createElement(A,{underline:!0},t),M.createElement(A,{color:i.dim},` (`,e,`)`)):M.createElement(A,{color:a,underline:!0},e)}function Z({label:e,value:t,labelWidth:n=12}){let{theme:r}=_();return M.createElement(k,{flexDirection:`row`},M.createElement(k,{width:n,flexShrink:0},M.createElement(A,{color:r.dim},e.toUpperCase())),typeof t==`string`?M.createElement(A,{color:r.fg},t):t)}function Rn(e){return e.review&&process.stdout.isTTY?`interactive`:`auto`}function zn(e){let t=null,n=null,r=!1,i=!1,a=0,o=new Set,s=()=>{for(let e of o)e(t)};return{async approve(o){if(i)return`n`;if(e.mode===`auto`||r)return`y`;let c=String(++a);return new Promise(e=>{t={id:c,...o},n=t=>{t===`a`&&(r=!0),e(t)},s()})},subscribe(e){return o.add(e),()=>{o.delete(e)}},current(){return t},resolve(e,r){if(!t||t.id!==e||!n)return;let i=n;t=null,n=null,s(),i(r)},abort(){if(i=!0,n){let e=n;t=null,n=null,s(),e(`n`)}}}}function Bn(){let e=[12,15,18,22,28,35,41,50,58,64,72,78],t=x(e,24);return[` ↑`,` ${t}`,` └────────────────────────`,` May Jun Jul Aug Sep`]}function Vn(){return[` Landing page ████████████████████ 100%`,` ↓ -28%`,` Pricing ██████████████░░░░░░ 72%`,` ↓ -50%`,` Checkout ███████░░░░░░░░░░░░░ 36%`,` ↓ -64%`,` Purchased ███░░░░░░░░░░░░░░░░░ 13%`]}function Hn(){return[` ▇▇▇▇▇▇▇▇▇▎ 89 Sarah K. /pricing 🇺🇸`,` ▇▇▇▇▇▇░░░░ 61 anon /docs 🇩🇪`,` ▇▇▇░░░░░░░ 34 anon /changelog 🇯🇵`]}function Un(){return[` LCP ● 2.1s good ████████████░░░░░░`,` INP ● 89ms good ██████████████████`,` CLS ⚠ 0.14 needs ████████████░░░░░░`,` TTFB ● 380ms good ███████████████░░░`]}const Wn=[{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:Bn},{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:Vn},{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:Hn},{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:Un},{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.`]}],Gn=11e3,Kn=9,qn=({width:e,height:t})=>{let{theme:n}=_(),[r,i]=F(0);N(()=>{if(Wn.length<=1)return;let e=setInterval(()=>{i(e=>(e+1)%Wn.length)},Gn);return()=>clearInterval(e)},[]);let a=Wn[r],o=a.visual?a.visual():[];return M.createElement(k,{flexDirection:`column`,width:e,height:t,paddingX:2,paddingY:1},M.createElement(k,{marginBottom:1},M.createElement(A,{color:n.typography.label.color,dimColor:n.typography.label.dim},`LEARN`)),M.createElement(k,{flexDirection:`column`,minHeight:Kn,key:r},M.createElement(k,{marginBottom:1},M.createElement(A,{bold:!0,color:n.fg,wrap:`truncate`},a.title)),a.body.map((e,t)=>M.createElement(A,{key:t,color:n.muted,wrap:`truncate`},e||` `)),o.length>0&&M.createElement(k,{flexDirection:`column`,marginTop:1},o.map((e,t)=>M.createElement(A,{key:t,color:n.accent},e)))),M.createElement(k,{flexGrow:1}),M.createElement(k,{marginTop:1},M.createElement(A,null,Wn.map((e,t)=>M.createElement(A,{key:t,color:t===r?n.muted:n.dim},t===r?`─`:`·`)))))},Jn={pending:`·`,active:`⠋`,done:`✓`,error:`✗`};function Yn(e,t){switch(e){case`pending`:return t.dim;case`active`:return t.accent;case`done`:return t.success;case`error`:return t.error}}const Xn=({tasks:e,width:t,height:n,liveLine:r})=>{let{theme:i}=_();return M.createElement(k,{flexDirection:`column`,width:t,height:n,paddingX:2,paddingY:1},M.createElement(k,{marginBottom:1},M.createElement(A,{color:i.typography.label.color,dimColor:i.typography.label.dim},`TASKS`)),e.map(e=>M.createElement(k,{key:e.id,flexDirection:`column`},M.createElement(k,{flexDirection:`row`},e.status===`active`?M.createElement(A,{color:i.accent},M.createElement(I,{type:`dots`})):M.createElement(A,{color:Yn(e.status,i)},Jn[e.status]),M.createElement(A,null,` `),M.createElement(A,{color:e.status===`pending`?i.muted:i.fg,wrap:`truncate`},e.label)),e.detail&&M.createElement(k,{paddingLeft:2},M.createElement(A,{color:i.dim,wrap:`truncate`},e.detail)))),M.createElement(k,{flexGrow:1}),r&&M.createElement(k,{flexDirection:`row`,marginTop:1},M.createElement(A,{color:i.accent},`◆ `),M.createElement(A,{color:i.fg,wrap:`truncate`},r)))};function Q(e){return e.toLowerCase().replace(/[^a-z0-9]/g,``)}function Zn(e,t){if(e.length===0)return null;if(e.length===1)return e[0]??null;if(!t)return null;let n=Q(t);if(!n)return null;let r=e.find(e=>Q(e.name)===n);if(r)return r;let i=e.find(e=>{let t=new URL(e.url).hostname;return Q(t.split(`.`)[0]??``)===n});if(i)return i;if(n.length<4)return null;let a=e.filter(e=>{let t=Q(e.name),r=Q(new URL(e.url).hostname);return t.includes(n)||r.includes(n)||n.includes(t)||n.includes(r)});return a.length===1?a[0]??null:null}const Qn=oe(S),$n=2e4;async function $(e,t){let n=await Qn(`git`,t,{cwd:e,timeout:$n,maxBuffer:4e6,env:{...process.env,GIT_TERMINAL_PROMPT:`0`}});return{stdout:n.stdout,stderr:n.stderr}}function er(e){let t=e.split(`\0`).filter(Boolean),n=[];for(let e=0;e<t.length;e++){let r=t[e];if(r.length<4)continue;let i=r.slice(0,2);n.push(r.slice(3)),/[RC]/.test(i)&&t[e+1]&&n.push(t[++e])}return[...new Set(n)]}async function tr(e){let{stdout:t}=await $(e,[`status`,`--porcelain=v1`,`-z`,`--untracked-files=all`]);return er(t)}async function nr(e){try{let{stdout:t}=await $(e,[`rev-parse`,`--show-toplevel`]),n=C.resolve(t.trim());return{isRepository:!0,root:n,dirtyPaths:await tr(n)}}catch{return{isRepository:!1,root:null,dirtyPaths:[]}}}async function rr(e,t,n){let r=await w.realpath(e).catch(()=>C.resolve(e)),i=C.resolve(r,n),a=await w.realpath(i).catch(()=>i),o=C.relative(t,a);return!o||o.startsWith(`..`)||C.isAbsolute(o)?null:o.split(C.sep).join(`/`)}function ir(e){return/(^|\/)\.env(?:$|\.(?!example(?:$|\.)))/i.test(e)}async function ar(e){let{cwd:t,baseline:n}=e;if(!n.isRepository||!n.root)return{committed:!1,pushed:!1,reason:`not-repository`,message:`Not a git repository — skipped automatic commit.`};if(n.dirtyPaths.length>0)return{committed:!1,pushed:!1,reason:`dirty-baseline`,message:`The repository already had uncommitted work, so Zenovay left git untouched. Commit the tracker through your normal workflow.`};let r=await Promise.all(e.changedPaths.map(e=>rr(t,n.root,e))),i=[...new Set(r.filter(e=>!!e))];if(i.length===0)return{committed:!1,pushed:!1,reason:`no-journaled-changes`,message:`No Zenovay-written files were recorded — git was left untouched.`};let a=i.filter(e=>!ir(e)),o=i.filter(ir),s=await tr(n.root),c=new Set(i),l=s.filter(e=>!c.has(e));if(l.length>0)return{committed:!1,pushed:!1,reason:`unexpected-changes`,message:`New non-Zenovay changes appeared during setup (${l.join(`, `)}), so git was left untouched.`,unstagedPaths:s};if(a.length===0)return{committed:!1,pushed:!1,reason:`no-staged-changes`,message:`Only local environment files changed; Zenovay intentionally did not commit them.`,unstagedPaths:o};let{stdout:u}=await $(n.root,[`symbolic-ref`,`--quiet`,`--short`,`HEAD`]),d=u.trim();e.onDetail?.(`Staging ${a.length} Zenovay file(s)…`),await $(n.root,[`add`,`--`,...a]);try{return await $(n.root,[`diff`,`--cached`,`--quiet`]),{committed:!1,pushed:!1,reason:`no-staged-changes`,message:`The recorded Zenovay files were already up to date.`,unstagedPaths:o}}catch{}e.onPhase?.(`committing`),e.onDetail?.(`Creating a tracker-only commit…`),await $(n.root,[`commit`,`-m`,`chore(zenovay): install tracking script via @zenovay/cli`]);let{stdout:f}=await $(n.root,[`rev-parse`,`--short`,`HEAD`]),p=f.trim();e.onPhase?.(`pushing`),e.onDetail?.(`Pushing ${p} to origin/${d}…`);try{await $(n.root,[`push`,`origin`,d])}catch(e){let t=e instanceof Error?e.message.split(`
|
|
325
|
-
`)[0]:`unknown git error`;return{committed:!0,pushed:!1,shortSha:p,branch:d,reason:`push-failed`,pushError:t,message:`Commit ${p} was created locally, but it was not pushed. Run: git push origin ${d}`,unstagedPaths:o}}return e.onPhase?.(`done`),{committed:!0,pushed:!0,shortSha:p,branch:d,message:`Pushed ${p} to origin/${d}.`,unstagedPaths:o}}const
|
|
326
|
-
`),0;let r;for(let t of n)if(await me(t,e.cwd).catch(()=>!1)){r=t;break}if(!r){let t=`Nothing to undo — no init session belongs to this project.`;return c(e)?(s({type:`info`,message:t}),s({type:`done`,command:`init`,exitCode:0})):process.stdout.write(`${t}\n`),0}try{let{restored:t}=await ge(r,{cwd:e.cwd}),n=t>0?`Reverted ${t} file(s) from the last install (session ${r}).`:`Nothing to revert in the last session (${r}).`;return c(e)?(s({type:`info`,message:n}),s({type:`done`,command:`init`,exitCode:0})):process.stdout.write(`${n}\n`),0}catch(n){let i=`Undo failed: ${n.message}. The backups are under ${C.join(t,r)} if you need to restore by hand.`;return c(e)?(s({type:`error`,code:`undo_failed`,message:i}),s({type:`done`,command:`init`,exitCode:1})):process.stderr.write(`${i}\n`),1}}async function hr(t){let r=await import(`./telemetry-DIAzAYko.js`).catch(()=>null);r?.emit(`install.start`,{properties:{mode:`headless`}});try{let i=await e(),c=await ht(t.cwd);if(!c)return s({type:`error`,code:`no_framework`,message:`Could not detect framework (headless mode has no picker).`}),r?.emit(`install.error`,{error_code:`no_framework`,properties:{mode:`headless`}}),2;s({type:`framework.detected`,framework:c.id,confidence:1}),r?.emit(`install.framework_detected`,{properties:{framework:c.id}});let l=await a({strict:!1});if(!l&&!process.env.ZENOVAY_API_TOKEN)return s({type:`error`,code:`not_logged_in`,message:"Run `zenovay login` first (or set ZENOVAY_API_TOKEN)."}),2;let u=new n({config:i,cliVersion:t.cliVersion,token:l}),[d,f]=await Promise.all([u.getSites(),o(t.cwd,``).catch(()=>null)]),p;if(t.siteId){if(p=d.find(e=>e.id===t.siteId),!p)return s({type:`error`,code:`site_not_found`,message:`Site ${t.siteId} not found.`}),2}else if(f?.foundTrackingCodes.length){for(let e of f.foundTrackingCodes){let t=d.find(t=>t.trackingCode===e);if(t){p=t;break}}!p&&d.length===1&&(p=d[0])}else p=d.length===1?d[0]:void 0;if(!p)return s({type:`error`,code:d.length===0?`no_site`:`site_required`,message:d.length===0?`No sites exist; create one at app.zenovay.com or re-run interactively.`:`More than one site exists and none matches this project. Pass --site-id <ID> so Zenovay cannot install the wrong tracker.`}),2;let m=p.trackingCode??p.id;if(f&&(f.recommendation===`no-op`||f.foundTrackingCodes.includes(m)))return s({type:`info`,message:`Zenovay already installed correctly for ${p.name} (${m})`}),s({type:`done`,command:`init`,exitCode:0}),0;s({type:`info`,message:`Using site ${p.id} (${p.name}) trackingCode=${p.trackingCode??p.id}`});let h=p.trackingCode??p.id;if(!Jt(h))return s({type:`error`,code:`invalid_tracking_code`,message:`tracking code "${h}" has an unexpected format; aborting to avoid broken markup`}),1;let g=new V({cwd:t.cwd}),_=e=>g.journalTrustedWrite(e);if(c.id===`plain-html`){let e=await Kt({cwd:t.cwd,trackingCode:h,updateOnly:f?.recommendation===`update-tracking-code`,beforeWrite:_});if(e.installed.length===0&&e.skipped.length===0)return s({type:`error`,code:`install_failed`,message:`No .html files with a <head> block found to inject the tracker into (errors: ${e.errors.length}).`}),r?.emit(`install.error`,{error_code:`install_failed`,properties:{mode:`headless`,framework:c.id}}),s({type:`done`,command:`init`,exitCode:1}),1;s({type:`info`,message:`tracker injected into ${e.installed.length} file(s); ${e.skipped.length} already current; ${e.errors.length} error(s)`})}else if(c.id===`next-app-router`){let e=await an({cwd:t.cwd,trackingCode:h,beforeWrite:_});if(e.fellThrough||e.errors.length>0)return s({type:`error`,code:`headless_framework_unsupported`,message:"This Next.js project has a structure the headless installer can't edit safely (no standard document-shell layout found). Run `zenovay init` interactively — the wizard places the tracker in the correct file. Nothing was modified."}),r?.emit(`install.error`,{error_code:`headless_framework_unsupported`,properties:{mode:`headless`,framework:c.id}}),s({type:`done`,command:`init`,exitCode:1}),1;s({type:`info`,message:`tracker inserted: ${e.installed[0]??`already installed — nothing to change`}`})}else{let e=await ln({cwd:t.cwd,trackingCode:h,siteId:p.id,adapter:c,beforeWrite:_}),n=e.skipped.some(e=>/already installed|tracker present/i.test(e.reason));if(e.fellThrough||e.errors.length>0||e.installed.length===0&&!n)return s({type:`error`,code:`headless_framework_unsupported`,message:`${c.displayName}'s tracker insert isn't a mechanical edit the headless mode can apply safely for this project shape. Run \`zenovay init\` interactively — the wizard uses a deterministic fast path and falls back to the AI installer only where judgement is needed. Nothing was modified.`}),r?.emit(`install.error`,{error_code:`headless_framework_unsupported`,properties:{mode:`headless`,framework:c.id}}),s({type:`done`,command:`init`,exitCode:1}),1;s({type:`info`,message:`tracker inserted: ${e.installed[0]??`already installed — nothing to change`}`})}let v=await J(t.cwd,{[c.envVarName]:h},{beforeWrite:_});if(v.addedKeys.length>0&&s({type:`info`,message:`env vars added: ${v.addedKeys.join(`,`)}`}),t.firstParty!==!1){let e=await Nn(t.cwd,{trackingCode:h,forceHost:vn(t.host),beforeWrite:_});e.proxyFile&&e.proxyAction!==`manual`&&e.proxyAction!==`skipped`?s({type:`info`,message:`first-party tracking enabled — analytics now load from your own domain (${vr(t.cwd,e.proxyFile)}), so visitors on Safari/Brave and other strict-privacy browsers are counted too`}):e.manual&&s({type:`info`,message:e.manual})}else s({type:`info`,message:"first-party tracking skipped (--no-first-party) — enable it later with `zenovay init --host <cloudflare-pages|vercel|netlify|nextjs>`"});return s({type:`done`,command:`init`,exitCode:0}),r?.emit(`install.success`,{properties:{framework:c.id,mode:`headless`,env_keys_added:v.addedKeys.length}}),0}catch(e){return s({type:`error`,code:`init_failed`,message:e.message}),r?.emit(`install.error`,{error_code:`init_failed`,properties:{mode:`headless`,error:(e.message??`unknown`).slice(0,128)}}),1}}const gr=({opts:t,onExit:i})=>{let{exit:s}=ne(),{theme:c}=_(),[l,u]=F(`intro`),[d,f]=F(null),[m,v]=F([]),[y,b]=F(null),[x,S]=F(null),[C,w]=F(null),[T,E]=F([]),[D,O]=F(void 0),[te,j]=F(null),[ie,ae]=F(null),[oe,se]=F(null),[ce,L]=F(0),[le,R]=F(`skipped`),[ue,z]=F(null),[B,de]=F(null),[V,fe]=F(null),H=P(new Set),pe=P(!1),U=P(null),W=P(!0),me=M.useCallback(e=>{for(let t of e)t&&H.current.add(t)},[]),[he,ge]=F(null),G=P(null),_e=P(!1),[ve,ye]=F(!1),[be,xe]=F(void 0),K=P(null),Se=M.useCallback(e=>new Promise(t=>{K.current=t,xe(e),ye(!0)}),[]),Ce=M.useCallback(e=>{ye(!1);let t=K.current;K.current=null,t?.(e)},[]),q=M.useCallback((e,t,n,r)=>{W.current&&(W.current=!1,s(),i(e,t,n,r))},[s,i]);re((e,t)=>{let n=e.toLowerCase()===`q`||t.escape;n&&(l===`error`?q(1):l===`create-site`&&q(0))}),N(()=>{let e=process.env.TERM_PROGRAM===`vscode`,t=!!process.stdout.isTTY&&!e;return t&&process.stdout.write(`\x1B[?1049h\x1B[H`),()=>{W.current=!1,G.current?.abort(),K.current?.(null),K.current=null,t&&process.stdout.write(`\x1B[?1049l`)}},[]),N(()=>{_e.current||(_e.current=!0,(async()=>{try{de(await nr(t.cwd));let r=!!process.stdout.isTTY&&!t.yes&&!t.json;r&&await new Promise(e=>setTimeout(e,1400)),u(`detecting`);let i=await ht(t.cwd);if(!i){w(`Could not detect your framework. Supported: Next.js, Nuxt, SvelteKit, Astro, Remix, plain HTML.`),u(`error`);return}f(i);let s=await a({strict:!1});!process.env.ZENOVAY_API_TOKEN&&!s&&(u(`login`),await p({cliVersion:t.cliVersion,offerCompletions:!1})),u(`loading-sites`);let c=await e(),l=await a({strict:!1}),d=new n({config:c,cliVersion:t.cliVersion,token:l}),[m,h]=await Promise.all([d.getSites(),o(t.cwd,``).catch(()=>null)]),g=await zr(t.cwd);if(v(m),b(g),m.length===0){u(`create-site`);return}if(t.siteId){let e=m.find(e=>e.id===t.siteId);if(!e){w(`Site ${t.siteId} not found in your account.`),u(`error`);return}let n=e.trackingCode??e.id;if(h?.foundTrackingCodes.includes(n)){S(e),u(`already-installed`);return}S(e),Sr(e,i,t,{setPhase:u,setErrorMsg:w,setTasks:E,setLiveLine:O,setSandboxStats:j,setVerifyResult:ae,setFirstParty:se,setPendingApproval:ge,askHostChoice:Se,recordChangedPaths:me,registerBridge:e=>{G.current=e}});return}if(h?.foundTrackingCodes.length)for(let e of h.foundTrackingCodes){let t=m.find(t=>t.trackingCode===e);if(t){S(t),u(`already-installed`);return}}let _=Zn(m,g);if(t.yes&&_){S(_),Sr(_,i,t,{setPhase:u,setErrorMsg:w,setTasks:E,setLiveLine:O,setSandboxStats:j,setVerifyResult:ae,setFirstParty:se,setPendingApproval:ge,askHostChoice:Se,recordChangedPaths:me,registerBridge:e=>{G.current=e}});return}u(`site-picker`)}catch(e){w(e.message),u(`error`)}})())},[]),N(()=>{l===`error`&&(G.current?.abort(),setTimeout(()=>q(1),8e3))},[l]);let we=async()=>{if(!pe.current){if(pe.current=!0,R(`verified`),!x){u(`success`);return}try{let i=await e();if(!W.current)return;let o=await a({strict:!1});if(!W.current)return;let s=new n({config:i,cliVersion:t.cliVersion,token:o}),c=await s.getSetupDestination(x.id);if(!W.current)return;z(c);let l=r(x.id,c);if(l){q(0,`quit`,x,l);return}}catch{W.current&&q(0,`quit`,x,r(x.id,null));return}W.current&&u(`success`)}};return M.createElement(k,{flexDirection:`column`},M.createElement(h,{version:t.cliVersion,subtitle:`AI install wizard`}),l===`intro`&&M.createElement(Cr,null),l===`detecting`&&M.createElement(g,{title:`Scanning`,state:`busy`},M.createElement(k,null,M.createElement(A,{color:c.accent},M.createElement(I,{type:`dots`})),M.createElement(A,null,` Detecting framework…`))),l===`login`&&M.createElement(g,{title:`Authenticating`,state:`busy`},M.createElement(A,null,`Opening browser for login… (paste ZENOVAY_API_TOKEN env var to skip)`)),l===`loading-sites`&&M.createElement(g,{title:`Loading your sites`,state:`busy`},M.createElement(k,null,M.createElement(A,{color:c.accent},M.createElement(I,{type:`dots`})),M.createElement(A,null,` Fetching your Zenovay sites…`))),l===`already-installed`&&x&&M.createElement(Er,{site:x,onContinueSetup:()=>{if(t.skipVerify){R(`skipped`),u(`success`);return}U.current=Date.now(),L(0),u(`visit-prompt`)},onReinstall:()=>{u(`site-picker`)},onExit:()=>q(0,`quit`,x)}),l===`site-picker`&&d&&M.createElement(Dr,{sites:m,preselectHint:y,onPick:e=>{if(e===`create-new`){u(`create-site`);return}S(e),Sr(e,d,t,{setPhase:u,setErrorMsg:w,setTasks:E,setLiveLine:O,setSandboxStats:j,setVerifyResult:ae,setFirstParty:se,setPendingApproval:ge,askHostChoice:Se,recordChangedPaths:me,registerBridge:e=>{G.current=e}})}}),l===`create-site`&&M.createElement(g,{title:`Add a site first`,state:`warn`},M.createElement(A,{color:c.warn},`You don't have a Zenovay site yet. Create one at https://app.zenovay.com/websites (takes ~30 seconds), then re-run `,M.createElement(A,{color:c.accent},`zenovay init`),` here.`),M.createElement(k,{marginTop:1},M.createElement(A,{color:c.muted},`Press `),M.createElement(A,{color:c.accent},`q`),M.createElement(A,{color:c.muted},` to exit.`))),l===`agent`&&d&&x&&M.createElement(Tr,{adapter:d,site:x,tasks:T,liveLine:D,pendingApproval:he,onApprove:e=>{he&&G.current?.resolve(he.id,e)},pendingHostChoice:ve,hostChoiceNote:be,onHostChoice:Ce}),l===`install-complete`&&d&&x&&M.createElement(jr,{cwd:t.cwd,adapter:d,site:x,stats:te,verify:ie,firstParty:oe,onCommit:()=>u(`commit-prompt`),onSkipCommit:()=>u(`deploy-prompt`),onQuit:()=>q(0,`quit`,x)}),l===`commit-prompt`&&x&&M.createElement(Nr,{cwd:t.cwd,baseline:B??{isRepository:!1,root:null,dirtyPaths:[]},changedPaths:[...H.current],onDone:e=>{fe(e.message),e.pushed&&O(`Pushed ${e.shortSha} to ${e.branch}`),u(`deploy-prompt`)},onError:e=>{w(e),u(`error`)}}),l===`deploy-prompt`&&x&&M.createElement(Pr,{site:x,notice:V,onDeployed:()=>{t.skipVerify?(R(`skipped`),u(`success`)):(U.current=Date.now(),u(`visit-prompt`))},onSkip:()=>{R(`skipped`),u(`success`)},onQuit:()=>q(0,`quit`,x)}),l===`visit-prompt`&&x&&M.createElement(Fr,{site:x,onContinue:()=>u(`verify`),onQuit:()=>q(0,`quit`,x)}),l===`verify`&&x&&M.createElement(Ir,{site:x,since:U.current??Date.now(),elapsed:ce,onTick:e=>L(e),onArrived:()=>{we()},onTimeout:()=>{R(`unverified`),u(`success`)},onSkip:()=>{R(`skipped`),u(`success`)},onQuit:()=>q(0,`quit`,x)}),l===`success`&&d&&x&&M.createElement(Ar,{adapter:d,site:x,stats:te,outcome:le,dashboardUrl:ue?.kind===`dashboard`?ue.url:void 0,firstParty:oe,onPick:e=>q(0,e,x)}),l===`error`&&M.createElement(g,{title:`Install failed`,state:`err`},M.createElement(A,{color:c.error},C??`Unknown error`)),M.createElement(ee,{items:l===`already-installed`?[{key:`enter`,label:`verify and continue`},{key:`r`,label:`reinstall or change site`},{key:`q`,label:`quit`},{key:`ctrl-c`,label:`abort`}]:[{key:`q`,label:`quit`},{key:`ctrl-c`,label:`abort`}]}))};async function _r(e,t,n,r){if(e.firstParty===!1){n.setFirstParty?.({host:`unknown`,proxyFile:null,proxyAction:`skipped`,snippetSwapped:!1,manual:"First-party tracking skipped (--no-first-party). Safari/Brave and other strict-privacy setups block third-party analytics — add all-browser coverage any time with `zenovay init --host <cloudflare-pages|vercel|netlify|nextjs>`.",changedFiles:[]});return}if(!n.setFirstParty)return;n.setTasks(e=>e.some(e=>e.id===`first-party`)?e.map(e=>e.id===`first-party`?{...e,status:`active`}:e):[...e,{id:`first-party`,label:`Set up first-party tracking (all browsers)`,status:`active`}]),n.setLiveLine(`Setting up first-party tracking (all browsers)…`);let i=vn(e.host),a=null;try{if(a=await Nn(e.cwd,{trackingCode:t,forceHost:i,beforeWrite:r}),n.setFirstParty(a),n.recordChangedPaths?.(a.changedFiles),a.host===`unknown`&&!i&&n.askHostChoice){n.setLiveLine(`Where do you deploy this site? (enables all-browser tracking)`);let i=e.host?`Unrecognized --host "${e.host}" — pick your host below.`:void 0,o=await n.askHostChoice(i);o&&(n.setLiveLine(`Setting up first-party tracking…`),a=await Nn(e.cwd,{trackingCode:t,forceHost:o,beforeWrite:r}),n.setFirstParty(a),n.recordChangedPaths?.(a.changedFiles))}}catch{a={host:`unknown`,proxyFile:null,proxyAction:`skipped`,snippetSwapped:!1,manual:"First-party setup hit an error — your standard tracker is active; add all-browser coverage later with `zenovay init --host <cloudflare-pages|vercel|netlify|nextjs>`.",changedFiles:[]},n.setFirstParty(a)}let o=yr(a,e.cwd);n.setTasks(e=>e.map(e=>e.id===`first-party`?{...e,status:`done`,detail:o}:e)),n.setLiveLine(void 0)}function vr(e,t){let n=C.resolve(e),r=C.isAbsolute(t)?C.normalize(t):C.resolve(n,t),i=C.relative(n,r);return i&&i!==`..`&&!i.startsWith(`..${C.sep}`)&&!C.isAbsolute(i)?i:C.basename(t)}function yr(e,t){return e?e.proxyFile&&e.proxyAction!==`manual`&&e.proxyAction!==`skipped`?`now loads from your domain (${vr(t,e.proxyFile)})`:e.manual?`standard tracking active — see note below for all-browser coverage`:`standard tracking active`:`standard tracking active`}function br(e){return e&&e.installed.length>0?e.installed.join(`, `):e&&e.errors.length>0?`failed: ${e.errors[0]?.message??`unknown error`}`:`none detected`}async function xr(e,t,n){n.setLiveLine(`Verifying the tracker is in your source…`);try{let r=await o(e,t),i=r.recommendation===`no-op`&&r.foundTrackingCodes.includes(t);n.setVerifyResult?.({ok:i,detail:i?`Tracker confirmed in your source files`:`Couldn't auto-confirm the tracker (diagnosis: ${r.recommendation}) — please double-check`})}catch{n.setVerifyResult?.({ok:!1,detail:`Verification check could not run`})}n.setLiveLine(void 0)}async function Sr(r,i,s,c){try{c.setPhase(`agent`);let l=await e(),u=await a({strict:!1}),d=new n({config:l,cliVersion:s.cliVersion,token:u}),f=new V({cwd:s.cwd}),p=e=>f.journalTrustedWrite(e),m=r.trackingCode??r.id;if(!Jt(m)){c.setErrorMsg(`The resolved tracking code "${m}" has an unexpected format (expected letters, digits, "_" or "-"). Aborting to avoid writing broken markup — re-check the site in your dashboard.`),c.setPhase(`error`);return}await t({defaultSiteId:r.id,defaultSiteName:r.name}).catch(()=>void 0);let h=await o(s.cwd,m);if(h.recommendation===`no-op`){c.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:`done`,detail:`already installed correctly`}:e)),c.setLiveLine(h.summary),c.setSandboxStats?.({reads:0,writes:0,rounds:0}),!s.skipMcp&&u&&await Y({accessToken:u.accessToken}).catch(()=>void 0),c.setVerifyResult?.({ok:!0,detail:`Already installed correctly`}),await _r(s,m,c,p),c.setPhase(`install-complete`);return}if(h.competitors.length>0&&c.setLiveLine(`Detected ${h.competitors.map(e=>e.name).join(`, `)} — will install Zenovay alongside (won't touch their tags).`),i.id===`next-app-router`){c.setTasks([{id:`detect`,label:`Detect framework`,status:`done`,detail:`Next.js (App Router)`},{id:`read`,label:`Find the document shell layout`,status:`active`},{id:`write`,label:`Insert tracker <Script>`,status:`pending`},{id:`env`,label:`Write env vars (.env.local)`,status:`pending`},{id:`mcp`,label:`Install MCP clients (Claude Code/Cursor/VS Code)`,status:`pending`},{id:`verify`,label:`Verify the tracker in your source`,status:`pending`}]),c.setLiveLine(`Next.js — locating the document shell layout…`);let e=await an({cwd:s.cwd,trackingCode:m,beforeWrite:p});if(c.recordChangedPaths?.(e.installed),!e.fellThrough&&e.errors.length===0){let t=e.installed[0]??`already installed`;c.setTasks(e=>e.map(e=>e.id===`read`||e.id===`write`?{...e,status:`done`,detail:t}:e));let n=await J(s.cwd,{[i.envVarName]:m},{beforeWrite:p});if((n.addedKeys.length>0||n.updatedKeys.length>0)&&c.recordChangedPaths?.([n.file]),c.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${n.addedKeys.length} key(s) added`}:e)),!s.skipMcp&&u){let e=await Y({accessToken:u.accessToken}).catch(e=>({installed:[],skipped:[],errors:[{client:`mcp`,message:e.message}]}));c.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:br(e)}:t))}else c.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await xr(s.cwd,m,c),c.setTasks(e=>e.map(e=>e.id===`verify`?{...e,status:`done`}:e)),c.setSandboxStats?.({reads:1,writes:e.installed.length,rounds:0}),await _r(s,m,c,p),c.setPhase(`install-complete`);return}c.setLiveLine(`Custom Next.js structure — handing off to the AI agent…`)}let g=i.id===`plain-html`;if(g){c.setTasks([{id:`detect`,label:`Detect framework`,status:`done`,detail:`Plain HTML`},{id:`read`,label:`Scan .html pages`,status:`active`},{id:`write`,label:`Insert tracker <script>`,status:`pending`},{id:`env`,label:`Write env vars`,status:`pending`},{id:`mcp`,label:`Install MCP clients (Claude Code/Cursor/VS Code)`,status:`pending`},{id:`verify`,label:`Verify the tracker in your source`,status:`pending`}]),c.setLiveLine(`Plain HTML — using fast install path (no AI needed)…`);let e=await Kt({cwd:s.cwd,trackingCode:m,updateOnly:h.recommendation===`update-tracking-code`,beforeWrite:p});if(c.recordChangedPaths?.(e.installed),e.installed.length===0&&e.errors.length===0&&e.skipped.length===0)throw Error(`No .html files with a <head>...</head> block were found to inject the tracker into.`);if(e.installed.length===0&&e.errors.length>0)throw Error(`Programmatic install failed for all ${e.errors.length} file(s). First error: ${e.errors[0].file}: ${e.errors[0].error}`);c.setTasks(t=>t.map(t=>t.id===`read`||t.id===`write`?{...t,status:`done`,detail:`${e.installed.length} file(s)`}:t)),c.setLiveLine(`Tracker added to ${e.installed.length} file(s). Skipped ${e.skipped.length}, errored ${e.errors.length}.`);let t=await J(s.cwd,{[i.envVarName]:m},{beforeWrite:p});if((t.addedKeys.length>0||t.updatedKeys.length>0)&&c.recordChangedPaths?.([t.file]),c.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${t.addedKeys.length} key(s) added`}:e)),!s.skipMcp&&u){let e=await Y({accessToken:u.accessToken}).catch(e=>({installed:[],skipped:[],errors:[{client:`mcp`,message:e.message}]}));c.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:br(e)}:t))}else c.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await xr(s.cwd,m,c),c.setSandboxStats?.({reads:e.installed.length,writes:e.installed.length,rounds:0}),await _r(s,m,c,p),c.setPhase(`install-complete`);return}{let e=await ln({cwd:s.cwd,trackingCode:m,siteId:r.id,adapter:i,beforeWrite:p});c.recordChangedPaths?.(e.installed);let t=e.skipped.some(e=>/already installed|tracker present/i.test(e.reason));if(!e.fellThrough&&e.errors.length===0&&(e.installed.length>0||t)){c.setTasks([{id:`detect`,label:`Detect framework`,status:`done`,detail:i.displayName},{id:`write`,label:`Insert tracker snippet`,status:`done`,detail:e.installed[0]??`already installed`},{id:`env`,label:`Write env vars (.env.local)`,status:`active`},{id:`mcp`,label:`Install MCP clients (Claude Code/Cursor/VS Code)`,status:`pending`},{id:`verify`,label:`Verify the tracker in your source`,status:`pending`}]),c.setLiveLine(`${i.displayName} — using fast install path (no AI needed)…`);let t=await J(s.cwd,{[i.envVarName]:m},{beforeWrite:p});if((t.addedKeys.length>0||t.updatedKeys.length>0)&&c.recordChangedPaths?.([t.file]),c.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${t.addedKeys.length} key(s) added`}:e)),!s.skipMcp&&u){let e=await Y({accessToken:u.accessToken}).catch(e=>({installed:[],skipped:[],errors:[{client:`mcp`,message:e.message}]}));c.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:br(e)}:t))}else c.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await xr(s.cwd,m,c),c.setTasks(e=>e.map(e=>e.id===`verify`?{...e,status:`done`}:e)),c.setSandboxStats?.({reads:1,writes:e.installed.length,rounds:0}),await _r(s,m,c,p),c.setPhase(`install-complete`);return}c.setLiveLine(`${i.displayName} needs a closer look — using the AI installer (a bit slower than the fast path)…`)}let _=i.buildSnippets({trackingCode:m,siteId:r.id}),v=`Install Zenovay tracking into this ${i.displayName} project.\nSite: ${r.name} (trackingCode: ${m}).\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(`
|
|
346
|
+
`:``;f=`${a}${e}${l}\n${i}\n`}return await t.beforeWrite?.(r),await j.writeFile(r,f,`utf8`),{file:r,action:`updated`}}const Pn="Your tracker is already live and working — it counts visitors in Chrome, Firefox and most browsers, no further setup required. First-party tracking is OPTIONAL and adds the rest: Safari, Brave, and browsers with strict tracking prevention block analytics loaded from another company's domain, so to capture those visitors too you serve Zenovay from your OWN domain. That last step is wired at your hosting provider — enable it any time with `zenovay init --host cloudflare-pages` (or `vercel` / `netlify` / `nextjs`).";async function Fn(e,t){let{trackingCode:n,apiBase:r,forceHost:i,beforeWrite:a}=t,o=`unknown`,s=null,c=`skipped`,l=null,u=!1,d=new Set;try{switch(o=i&&i!==`unknown`?i:(await gn(e)).host,o){case`cloudflare-pages`:{let t=await Cn(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&d.add(C.relative(e,t.file));break}case`nextjs-server`:{let t=await On(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&d.add(C.relative(e,t.file)),t.action===`manual`&&(l=`Your tracker is live. To also count Safari/Brave visitors, add this rewrite to ${t.file} yourself (its shape couldn't be edited automatically): { source: '/api/_z/:path*', destination: 'https://api.zenovay.com/fp/:path*' }.`);break}case`vercel`:{let t=await An(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&d.add(C.relative(e,t.file));break}case`netlify`:{let t=await Nn(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&d.add(C.relative(e,t.file));break}case`unknown`:default:c=`skipped`,l=Pn;break}c===`manual`&&!l&&(l=`An existing proxy configuration could not be verified safely, so Zenovay kept the standard tracker active. Review the /api/_z rule before enabling first-party tracking.`)}catch(e){s=null,c=`skipped`,l=`${Pn} (auto-setup hit an error: ${e.message.slice(0,120)})`}let p=s!==null&&c!==`manual`&&c!==`skipped`;if(p)try{let t=await f(e,{trackingCode:n,beforeWrite:a});u=t.swapped;for(let e of t.files)d.add(e)}catch{u=!1}return{host:o,proxyFile:s,proxyAction:c,snippetSwapped:u,manual:l,changedFiles:[...d]}}const In=`\x1B]8;;`,Ln=`\x07`;function Rn(){return process.env.FORCE_HYPERLINK?!0:!(process.env.NO_COLOR||!process.stdout.isTTY||process.env.CI||(process.env.TERM??``)===`dumb`)}function zn({url:e,label:t,color:n,arrow:r=!0}){let{theme:i}=_(),a=n??i.fg,o=(t??e)+(r?` ↗`:``);return Rn()?M.createElement(A,{color:a,underline:!0},In,e,Ln,o,In,Ln):t&&t!==e?M.createElement(A,{color:a},M.createElement(A,{underline:!0},t),M.createElement(A,{color:i.dim},` (`,e,`)`)):M.createElement(A,{color:a,underline:!0},e)}function Q({label:e,value:t,labelWidth:n=12}){let{theme:r}=_();return M.createElement(k,{flexDirection:`row`},M.createElement(k,{width:n,flexShrink:0},M.createElement(A,{color:r.dim},e.toUpperCase())),typeof t==`string`?M.createElement(A,{color:r.fg},t):t)}function Bn(e){return e.review&&process.stdout.isTTY?`interactive`:`auto`}function Vn(e){let t=null,n=null,r=!1,i=!1,a=0,o=new Set,s=()=>{for(let e of o)e(t)};return{async approve(o){if(i)return`n`;if(e.mode===`auto`||r)return`y`;let c=String(++a);return new Promise(e=>{t={id:c,...o},n=t=>{t===`a`&&(r=!0),e(t)},s()})},subscribe(e){return o.add(e),()=>{o.delete(e)}},current(){return t},resolve(e,r){if(!t||t.id!==e||!n)return;let i=n;t=null,n=null,s(),i(r)},abort(){if(i=!0,n){let e=n;t=null,n=null,s(),e(`n`)}}}}function Hn(){let e=[12,15,18,22,28,35,41,50,58,64,72,78],t=x(e,24);return[` ↑`,` ${t}`,` └────────────────────────`,` May Jun Jul Aug Sep`]}function Un(){return[` Landing page ████████████████████ 100%`,` ↓ -28%`,` Pricing ██████████████░░░░░░ 72%`,` ↓ -50%`,` Checkout ███████░░░░░░░░░░░░░ 36%`,` ↓ -64%`,` Purchased ███░░░░░░░░░░░░░░░░░ 13%`]}function Wn(){return[` ▇▇▇▇▇▇▇▇▇▎ 89 Sarah K. /pricing 🇺🇸`,` ▇▇▇▇▇▇░░░░ 61 anon /docs 🇩🇪`,` ▇▇▇░░░░░░░ 34 anon /changelog 🇯🇵`]}function Gn(){return[` LCP ● 2.1s good ████████████░░░░░░`,` INP ● 89ms good ██████████████████`,` CLS ⚠ 0.14 needs ████████████░░░░░░`,` TTFB ● 380ms good ███████████████░░░`]}const Kn=[{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:Hn},{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:Un},{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:Wn},{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:Gn},{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.`]}],qn=11e3,Jn=9,Yn=({width:e,height:t})=>{let{theme:n}=_(),[r,i]=F(0);N(()=>{if(Kn.length<=1)return;let e=setInterval(()=>{i(e=>(e+1)%Kn.length)},qn);return()=>clearInterval(e)},[]);let a=Kn[r],o=a.visual?a.visual():[];return M.createElement(k,{flexDirection:`column`,width:e,height:t,paddingX:2,paddingY:1},M.createElement(k,{marginBottom:1},M.createElement(A,{color:n.typography.label.color,dimColor:n.typography.label.dim},`LEARN`)),M.createElement(k,{flexDirection:`column`,minHeight:Jn,key:r},M.createElement(k,{marginBottom:1},M.createElement(A,{bold:!0,color:n.fg,wrap:`truncate`},a.title)),a.body.map((e,t)=>M.createElement(A,{key:t,color:n.muted,wrap:`truncate`},e||` `)),o.length>0&&M.createElement(k,{flexDirection:`column`,marginTop:1},o.map((e,t)=>M.createElement(A,{key:t,color:n.accent},e)))),M.createElement(k,{flexGrow:1}),M.createElement(k,{marginTop:1},M.createElement(A,null,Kn.map((e,t)=>M.createElement(A,{key:t,color:t===r?n.muted:n.dim},t===r?`─`:`·`)))))},Xn={pending:`·`,active:`⠋`,done:`✓`,error:`✗`};function Zn(e,t){switch(e){case`pending`:return t.dim;case`active`:return t.accent;case`done`:return t.success;case`error`:return t.error}}const Qn=({tasks:e,width:t,height:n,liveLine:r})=>{let{theme:i}=_();return M.createElement(k,{flexDirection:`column`,width:t,height:n,paddingX:2,paddingY:1},M.createElement(k,{marginBottom:1},M.createElement(A,{color:i.typography.label.color,dimColor:i.typography.label.dim},`TASKS`)),e.map(e=>M.createElement(k,{key:e.id,flexDirection:`column`},M.createElement(k,{flexDirection:`row`},e.status===`active`?M.createElement(A,{color:i.accent},M.createElement(I,{type:`dots`})):M.createElement(A,{color:Zn(e.status,i)},Xn[e.status]),M.createElement(A,null,` `),M.createElement(A,{color:e.status===`pending`?i.muted:i.fg,wrap:`truncate`},e.label)),e.detail&&M.createElement(k,{paddingLeft:2},M.createElement(A,{color:i.dim,wrap:`truncate`},e.detail)))),M.createElement(k,{flexGrow:1}),r&&M.createElement(k,{flexDirection:`row`,marginTop:1},M.createElement(A,{color:i.accent},`◆ `),M.createElement(A,{color:i.fg,wrap:`truncate`},r)))};function $n(e){return e.toLowerCase().replace(/[^a-z0-9]/g,``)}function er(e,t){if(e.length===0)return null;if(e.length===1)return e[0]??null;if(!t)return null;let n=$n(t);if(!n)return null;let r=e.find(e=>$n(e.name)===n);if(r)return r;let i=e.find(e=>{let t=new URL(e.url).hostname;return $n(t.split(`.`)[0]??``)===n});if(i)return i;if(n.length<4)return null;let a=e.filter(e=>{let t=$n(e.name),r=$n(new URL(e.url).hostname);return t.includes(n)||r.includes(n)||n.includes(t)||n.includes(r)});return a.length===1?a[0]??null:null}const tr=oe(S),nr=2e4;async function $(e,t){let n=await tr(`git`,t,{cwd:e,timeout:nr,maxBuffer:4e6,env:{...process.env,GIT_TERMINAL_PROMPT:`0`}});return{stdout:n.stdout,stderr:n.stderr}}function rr(e){let t=e.split(`\0`).filter(Boolean),n=[];for(let e=0;e<t.length;e++){let r=t[e];if(r.length<4)continue;let i=r.slice(0,2);n.push(r.slice(3)),/[RC]/.test(i)&&t[e+1]&&n.push(t[++e])}return[...new Set(n)]}async function ir(e){let{stdout:t}=await $(e,[`status`,`--porcelain=v1`,`-z`,`--untracked-files=all`]);return rr(t)}async function ar(e){try{let{stdout:t}=await $(e,[`rev-parse`,`--show-toplevel`]),n=C.resolve(t.trim());return{isRepository:!0,root:n,dirtyPaths:await ir(n)}}catch{return{isRepository:!1,root:null,dirtyPaths:[]}}}async function or(e,t,n){let r=await w.realpath(e).catch(()=>C.resolve(e)),i=C.resolve(r,n),a=await w.realpath(i).catch(()=>i),o=C.relative(t,a);return!o||o.startsWith(`..`)||C.isAbsolute(o)?null:o.split(C.sep).join(`/`)}function sr(e){return/(^|\/)\.env(?:$|\.(?!example(?:$|\.)))/i.test(e)}async function cr(e){let{cwd:t,baseline:n}=e;if(!n.isRepository||!n.root)return{committed:!1,pushed:!1,reason:`not-repository`,message:`Not a git repository — skipped automatic commit.`};if(n.dirtyPaths.length>0)return{committed:!1,pushed:!1,reason:`dirty-baseline`,message:`The repository already had uncommitted work, so Zenovay left git untouched. Commit the tracker through your normal workflow.`};let r=await Promise.all(e.changedPaths.map(e=>or(t,n.root,e))),i=[...new Set(r.filter(e=>!!e))];if(i.length===0)return{committed:!1,pushed:!1,reason:`no-journaled-changes`,message:`No Zenovay-written files were recorded — git was left untouched.`};let a=i.filter(e=>!sr(e)),o=i.filter(sr),s=await ir(n.root),c=new Set(i),l=s.filter(e=>!c.has(e));if(l.length>0)return{committed:!1,pushed:!1,reason:`unexpected-changes`,message:`New non-Zenovay changes appeared during setup (${l.join(`, `)}), so git was left untouched.`,unstagedPaths:s};if(a.length===0)return{committed:!1,pushed:!1,reason:`no-staged-changes`,message:`Only local environment files changed; Zenovay intentionally did not commit them.`,unstagedPaths:o};let{stdout:u}=await $(n.root,[`symbolic-ref`,`--quiet`,`--short`,`HEAD`]),d=u.trim();e.onDetail?.(`Staging ${a.length} Zenovay file(s)…`),await $(n.root,[`add`,`--`,...a]);try{return await $(n.root,[`diff`,`--cached`,`--quiet`]),{committed:!1,pushed:!1,reason:`no-staged-changes`,message:`The recorded Zenovay files were already up to date.`,unstagedPaths:o}}catch{}e.onPhase?.(`committing`),e.onDetail?.(`Creating a tracker-only commit…`),await $(n.root,[`commit`,`-m`,`chore(zenovay): install tracking script via @zenovay/cli`]);let{stdout:f}=await $(n.root,[`rev-parse`,`--short`,`HEAD`]),p=f.trim();e.onPhase?.(`pushing`),e.onDetail?.(`Pushing ${p} to origin/${d}…`);try{await $(n.root,[`push`,`origin`,d])}catch(e){let t=e instanceof Error?e.message.split(`
|
|
347
|
+
`)[0]:`unknown git error`;return{committed:!0,pushed:!1,shortSha:p,branch:d,reason:`push-failed`,pushError:t,message:`Commit ${p} was created locally, but it was not pushed. Run: git push origin ${d}`,unstagedPaths:o}}return e.onPhase?.(`done`),{committed:!0,pushed:!0,shortSha:p,branch:d,message:`Pushed ${p} to origin/${d}.`,unstagedPaths:o}}const lr=/<script\b[^>]*\bsrc\s*=\s*["'][^"']*(?:(?:api|cdn)\.zenovay\.com\/|\/(?:api\/)?_z\/script\.js)[^"']*["'][^>]*>/gi,ur=/\bsrc\s*=\s*["']([^"']+)["']/i,dr=/data-id\s*=\s*["'](ZV_[A-Za-z0-9_-]+)["']/i,fr=/[?&]id=(ZV_[A-Za-z0-9_-]+)/i;function pr(e){return e.match(dr)?.[1]??e.match(fr)?.[1]??null}function mr(e){return/\/(?:api\/)?_z\/script\.js/i.test(e)}async function hr(e,t,n=fetch){try{let r=await n(e,{headers:{"User-Agent":`zenovay-cli/preflight`},signal:AbortSignal.timeout(8e3),redirect:`follow`});if(!r.ok)return{state:`tracker-missing`,httpStatus:r.status};let i=await r.text(),a=i.match(lr)??[];if(a.length===0)return{state:`tracker-missing`};let o=[...new Set(a.map(pr).filter(e=>!!e))],s=a.find(e=>pr(e)===t);if(!s)return{state:`tracker-wrong-id`,foundCodes:o};if(!mr(s))return{state:`tracker-correct`};let c=s.match(ur)?.[1]?.replace(/&/gi,`&`);if(!c)return{state:`proxy-broken`,scriptUrl:e,detail:`The first-party tracker tag has no readable script URL.`};let l=new URL(c,r.url||e).toString(),u;try{u=await n(l,{headers:{"User-Agent":`zenovay-cli/preflight`},signal:AbortSignal.timeout(8e3),redirect:`follow`})}catch(e){return{state:`proxy-broken`,scriptUrl:l,detail:`The first-party script could not be reached: ${e instanceof Error?e.message:`network error`}`}}if(!u.ok)return{state:`proxy-broken`,scriptUrl:l,httpStatus:u.status,detail:`The first-party script returned HTTP ${u.status}.`};let d=u.headers.get(`content-type`)??``;if(!/(?:java|ecma)script/i.test(d))return{state:`proxy-broken`,scriptUrl:l,detail:`The first-party route returned ${d||`an unknown content type`} instead of JavaScript.`};if(u.headers.get(`x-zenovay-proxied`)?.toLowerCase()!==`true`)return{state:`proxy-broken`,scriptUrl:l,detail:`The route did not identify itself as a Zenovay first-party proxy.`};let f=await u.text();return f.includes(t)?{state:`tracker-correct`}:{state:`proxy-broken`,scriptUrl:l,detail:`The proxy script was served with a different tracking code.`}}catch(e){return{state:`tracker-missing`,networkError:e instanceof Error?e.message:`network error`}}}async function gr(e){if(e.undo)return _r(e);if(c(e))return vr(e);let t=`quit`,n=null,r=null,i=Promise.resolve(),a=await new Promise(a=>{let{unmount:o,waitUntilExit:s}=te(M.createElement(yr,{opts:e,onExit:(e,i,s,c)=>{t=i??`quit`,n=s??null,r=c??null,o(),a(e)}}),{exitOnCtrlC:!0});i=s(),i.then(()=>a(130),()=>a(1))});if(await i.catch(()=>{}),a===0&&r)return await l(r),0;let o=a===0&&t!==`quit`&&!!n;if(a===0&&!o&&await m().catch(()=>void 0),a!==0||t===`quit`||!n)return a;let s=n.id,u=t===`watch`?[`overview`,`--site-id`,s]:[`events`,`tail`,`--site-id`,s],{spawnSync:d}=await import(`node:child_process`),{realpathSync:f}=await import(`node:fs`),{buildPostInstallReexec:p}=await import(`./ensure-latest-BfsWmA1w.js`),{cmd:h,args:g}=p({execPath:process.execPath,argv1:process.argv[1]??``,sub:u,resolveSymlink:f});await new Promise(e=>setImmediate(e));let _=d(h,g,{stdio:`inherit`});if(_.error){let e=t===`watch`?`overview`:`events tail`;return process.stderr.write(`Run \`zenovay ${e} --site-id ${s}\` to continue.\n`),0}return _.status??0}async function _r(e){let t=C.join(E.homedir(),`.zenovay`,`undo`),n;try{let e=await w.readdir(t,{withFileTypes:!0}),r=e.filter(e=>e.isDirectory()).map(e=>e.name),i=await Promise.all(r.map(async e=>({name:e,mtime:await w.stat(C.join(t,e)).then(e=>e.mtimeMs,()=>0)})));n=i.sort((e,t)=>t.mtime-e.mtime).map(e=>e.name)}catch{n=[]}if(n.length===0)return c(e)?(s({type:`info`,message:`Nothing to undo — no init session has modified project files on this machine.`}),s({type:`done`,command:`init`,exitCode:0})):process.stdout.write(`Nothing to undo — no init session has modified project files on this machine.
|
|
348
|
+
`),0;let r;for(let t of n)if(await pe(t,e.cwd).catch(()=>!1)){r=t;break}if(!r){let t=`Nothing to undo — no init session belongs to this project.`;return c(e)?(s({type:`info`,message:t}),s({type:`done`,command:`init`,exitCode:0})):process.stdout.write(`${t}\n`),0}try{let{restored:t}=await he(r,{cwd:e.cwd}),n=t>0?`Reverted ${t} file(s) from the last install (session ${r}).`:`Nothing to revert in the last session (${r}).`;return c(e)?(s({type:`info`,message:n}),s({type:`done`,command:`init`,exitCode:0})):process.stdout.write(`${n}\n`),0}catch(n){let i=`Undo failed: ${n.message}. The backups are under ${C.join(t,r)} if you need to restore by hand.`;return c(e)?(s({type:`error`,code:`undo_failed`,message:i}),s({type:`done`,command:`init`,exitCode:1})):process.stderr.write(`${i}\n`),1}}async function vr(t){let r=await import(`./telemetry-DIAzAYko.js`).catch(()=>null);r?.emit(`install.start`,{properties:{mode:`headless`}});try{let i=await e(),c=await mt(t.cwd);if(!c)return s({type:`error`,code:`no_framework`,message:`Could not detect framework (headless mode has no picker).`}),r?.emit(`install.error`,{error_code:`no_framework`,properties:{mode:`headless`}}),2;s({type:`framework.detected`,framework:c.id,confidence:1}),r?.emit(`install.framework_detected`,{properties:{framework:c.id}});let l=await a({strict:!1});if(!l&&!process.env.ZENOVAY_API_TOKEN)return s({type:`error`,code:`not_logged_in`,message:"Run `zenovay login` first (or set ZENOVAY_API_TOKEN)."}),2;let u=new n({config:i,cliVersion:t.cliVersion,token:l}),[d,f]=await Promise.all([u.getSites(),o(t.cwd,``).catch(()=>null)]),p;if(t.siteId){if(p=d.find(e=>e.id===t.siteId),!p)return s({type:`error`,code:`site_not_found`,message:`Site ${t.siteId} not found.`}),2}else if(f?.foundTrackingCodes.length){for(let e of f.foundTrackingCodes){let t=d.find(t=>t.trackingCode===e);if(t){p=t;break}}!p&&d.length===1&&(p=d[0])}else p=d.length===1?d[0]:void 0;if(!p)return s({type:`error`,code:d.length===0?`no_site`:`site_required`,message:d.length===0?`No sites exist; create one at app.zenovay.com or re-run interactively.`:`More than one site exists and none matches this project. Pass --site-id <ID> so Zenovay cannot install the wrong tracker.`}),2;let m=p.trackingCode??p.id;if(f&&(f.recommendation===`no-op`||f.foundTrackingCodes.includes(m)))return s({type:`info`,message:`Zenovay already installed correctly for ${p.name} (${m})`}),s({type:`done`,command:`init`,exitCode:0}),0;s({type:`info`,message:`Using site ${p.id} (${p.name}) trackingCode=${p.trackingCode??p.id}`});let h=p.trackingCode??p.id;if(!Z(h))return s({type:`error`,code:`invalid_tracking_code`,message:`tracking code "${h}" has an unexpected format; aborting to avoid broken markup`}),1;let g=new H({cwd:t.cwd}),_=e=>g.journalTrustedWrite(e);if(c.id===`plain-html`){let e=await Gt({cwd:t.cwd,trackingCode:h,updateOnly:f?.recommendation===`update-tracking-code`,beforeWrite:_});if(e.installed.length===0&&e.skipped.length===0)return s({type:`error`,code:`install_failed`,message:`No .html files with a <head> block found to inject the tracker into (errors: ${e.errors.length}).`}),r?.emit(`install.error`,{error_code:`install_failed`,properties:{mode:`headless`,framework:c.id}}),s({type:`done`,command:`init`,exitCode:1}),1;s({type:`info`,message:`tracker injected into ${e.installed.length} file(s); ${e.skipped.length} already current; ${e.errors.length} error(s)`})}else if(c.id===`next-app-router`){let e=await nn({cwd:t.cwd,trackingCode:h,beforeWrite:_});if(e.fellThrough||e.errors.length>0)return s({type:`error`,code:`headless_framework_unsupported`,message:"This Next.js project has a structure the headless installer can't edit safely (no standard document-shell layout found). Run `zenovay init` interactively — the wizard places the tracker in the correct file. Nothing was modified."}),r?.emit(`install.error`,{error_code:`headless_framework_unsupported`,properties:{mode:`headless`,framework:c.id}}),s({type:`done`,command:`init`,exitCode:1}),1;s({type:`info`,message:`tracker inserted: ${e.installed[0]??`already installed — nothing to change`}`})}else{let e=await cn({cwd:t.cwd,trackingCode:h,siteId:p.id,adapter:c,beforeWrite:_}),n=e.skipped.some(e=>/already installed|tracker present/i.test(e.reason));if(e.fellThrough||e.errors.length>0||e.installed.length===0&&!n)return s({type:`error`,code:`headless_framework_unsupported`,message:`${c.displayName}'s tracker insert isn't a mechanical edit the headless mode can apply safely for this project shape. Run \`zenovay init\` interactively — the wizard uses a deterministic fast path and falls back to the AI installer only where judgement is needed. Nothing was modified.`}),r?.emit(`install.error`,{error_code:`headless_framework_unsupported`,properties:{mode:`headless`,framework:c.id}}),s({type:`done`,command:`init`,exitCode:1}),1;s({type:`info`,message:`tracker inserted: ${e.installed[0]??`already installed — nothing to change`}`})}let v=await Y(t.cwd,{[c.envVarName]:h},{beforeWrite:_});if(v.addedKeys.length>0&&s({type:`info`,message:`env vars added: ${v.addedKeys.join(`,`)}`}),t.firstParty!==!1){let e=await Fn(t.cwd,{trackingCode:h,forceHost:_n(t.host),beforeWrite:_});e.proxyFile&&e.proxyAction!==`manual`&&e.proxyAction!==`skipped`?s({type:`info`,message:`first-party tracking enabled — analytics now load from your own domain (${xr(t.cwd,e.proxyFile)}), so visitors on Safari/Brave and other strict-privacy browsers are counted too`}):e.manual&&s({type:`info`,message:e.manual})}else s({type:`info`,message:"first-party tracking skipped (--no-first-party) — enable it later with `zenovay init --host <cloudflare-pages|vercel|netlify|nextjs>`"});return s({type:`done`,command:`init`,exitCode:0}),r?.emit(`install.success`,{properties:{framework:c.id,mode:`headless`,env_keys_added:v.addedKeys.length}}),0}catch(e){return s({type:`error`,code:`init_failed`,message:e.message}),r?.emit(`install.error`,{error_code:`init_failed`,properties:{mode:`headless`,error:(e.message??`unknown`).slice(0,128)}}),1}}const yr=({opts:t,onExit:i})=>{let{exit:s}=ne(),{theme:c}=_(),[l,u]=F(`intro`),[d,f]=F(null),[m,v]=F([]),[y,b]=F(null),[x,S]=F(null),[C,w]=F(null),[T,E]=F([]),[D,O]=F(void 0),[te,j]=F(null),[ie,ae]=F(null),[oe,se]=F(null),[ce,L]=F(0),[le,R]=F(`skipped`),[z,B]=F(null),[V,ue]=F(null),[H,de]=F(null),U=P(new Set),fe=P(!1),W=P(null),G=P(!0),pe=M.useCallback(e=>{for(let t of e)t&&U.current.add(t)},[]),[me,he]=F(null),K=P(null),ge=P(!1),[_e,ve]=F(!1),[ye,be]=F(void 0),q=P(null),xe=M.useCallback(e=>new Promise(t=>{q.current=t,be(e),ve(!0)}),[]),Se=M.useCallback(e=>{ve(!1);let t=q.current;q.current=null,t?.(e)},[]),J=M.useCallback((e,t,n,r)=>{G.current&&(G.current=!1,s(),i(e,t,n,r))},[s,i]);re((e,t)=>{let n=e.toLowerCase()===`q`||t.escape;n&&(l===`error`?J(1):l===`create-site`&&J(0))}),N(()=>{let e=process.env.TERM_PROGRAM===`vscode`,t=!!process.stdout.isTTY&&!e;return t&&process.stdout.write(`\x1B[?1049h\x1B[H`),()=>{G.current=!1,K.current?.abort(),q.current?.(null),q.current=null,t&&process.stdout.write(`\x1B[?1049l`)}},[]),N(()=>{ge.current||(ge.current=!0,(async()=>{try{ue(await ar(t.cwd));let r=!!process.stdout.isTTY&&!t.yes&&!t.json;r&&await new Promise(e=>setTimeout(e,1400)),u(`detecting`);let i=await mt(t.cwd);if(!i){w(`Could not detect your framework. Supported: Next.js, Nuxt, SvelteKit, Astro, Remix, plain HTML.`),u(`error`);return}f(i);let s=await a({strict:!1});!process.env.ZENOVAY_API_TOKEN&&!s&&(u(`login`),await p({cliVersion:t.cliVersion,offerCompletions:!1})),u(`loading-sites`);let c=await e(),l=await a({strict:!1}),d=new n({config:c,cliVersion:t.cliVersion,token:l}),[m,h]=await Promise.all([d.getSites(),o(t.cwd,``).catch(()=>null)]),g=await Hr(t.cwd);if(v(m),b(g),m.length===0){u(`create-site`);return}if(t.siteId){let e=m.find(e=>e.id===t.siteId);if(!e){w(`Site ${t.siteId} not found in your account.`),u(`error`);return}let n=e.trackingCode??e.id;if(h?.foundTrackingCodes.includes(n)){S(e),u(`already-installed`);return}S(e),Tr(e,i,t,{setPhase:u,setErrorMsg:w,setTasks:E,setLiveLine:O,setSandboxStats:j,setVerifyResult:ae,setFirstParty:se,setPendingApproval:he,askHostChoice:xe,recordChangedPaths:pe,registerBridge:e=>{K.current=e}});return}if(h?.foundTrackingCodes.length)for(let e of h.foundTrackingCodes){let t=m.find(t=>t.trackingCode===e);if(t){S(t),u(`already-installed`);return}}let _=er(m,g);if(t.yes&&_){S(_),Tr(_,i,t,{setPhase:u,setErrorMsg:w,setTasks:E,setLiveLine:O,setSandboxStats:j,setVerifyResult:ae,setFirstParty:se,setPendingApproval:he,askHostChoice:xe,recordChangedPaths:pe,registerBridge:e=>{K.current=e}});return}u(`site-picker`)}catch(e){w(e.message),u(`error`)}})())},[]),N(()=>{l===`error`&&(K.current?.abort(),setTimeout(()=>J(1),8e3))},[l]);let Ce=async()=>{if(!fe.current){if(fe.current=!0,R(`verified`),!x){u(`success`);return}try{let i=await e();if(!G.current)return;let o=await a({strict:!1});if(!G.current)return;let s=new n({config:i,cliVersion:t.cliVersion,token:o}),c=await s.getSetupDestination(x.id);if(!G.current)return;B(c);let l=r(x.id,c);if(l){J(0,`quit`,x,l);return}}catch{G.current&&J(0,`quit`,x,r(x.id,null));return}G.current&&u(`success`)}};return M.createElement(k,{flexDirection:`column`},M.createElement(h,{version:t.cliVersion,subtitle:`AI install wizard`}),l===`intro`&&M.createElement(Er,null),l===`detecting`&&M.createElement(g,{title:`Scanning`,state:`busy`},M.createElement(k,null,M.createElement(A,{color:c.accent},M.createElement(I,{type:`dots`})),M.createElement(A,null,` Detecting framework…`))),l===`login`&&M.createElement(g,{title:`Authenticating`,state:`busy`},M.createElement(A,null,`Opening browser for login… (paste ZENOVAY_API_TOKEN env var to skip)`)),l===`loading-sites`&&M.createElement(g,{title:`Loading your sites`,state:`busy`},M.createElement(k,null,M.createElement(A,{color:c.accent},M.createElement(I,{type:`dots`})),M.createElement(A,null,` Fetching your Zenovay sites…`))),l===`already-installed`&&x&&M.createElement(kr,{site:x,onContinueSetup:()=>{if(t.skipVerify){R(`skipped`),u(`success`);return}W.current=Date.now(),L(0),u(`visit-prompt`)},onReinstall:()=>{u(`site-picker`)},onExit:()=>J(0,`quit`,x)}),l===`site-picker`&&d&&M.createElement(Ar,{sites:m,preselectHint:y,onPick:e=>{if(e===`create-new`){u(`create-site`);return}S(e),Tr(e,d,t,{setPhase:u,setErrorMsg:w,setTasks:E,setLiveLine:O,setSandboxStats:j,setVerifyResult:ae,setFirstParty:se,setPendingApproval:he,askHostChoice:xe,recordChangedPaths:pe,registerBridge:e=>{K.current=e}})}}),l===`create-site`&&M.createElement(g,{title:`Add a site first`,state:`warn`},M.createElement(A,{color:c.warn},`You don't have a Zenovay site yet. Create one at https://app.zenovay.com/websites (takes ~30 seconds), then re-run `,M.createElement(A,{color:c.accent},`zenovay init`),` here.`),M.createElement(k,{marginTop:1},M.createElement(A,{color:c.muted},`Press `),M.createElement(A,{color:c.accent},`q`),M.createElement(A,{color:c.muted},` to exit.`))),l===`agent`&&d&&x&&M.createElement(Or,{adapter:d,site:x,tasks:T,liveLine:D,pendingApproval:me,onApprove:e=>{me&&K.current?.resolve(me.id,e)},pendingHostChoice:_e,hostChoiceNote:ye,onHostChoice:Se}),l===`install-complete`&&d&&x&&M.createElement(Pr,{cwd:t.cwd,adapter:d,site:x,stats:te,verify:ie,firstParty:oe,onCommit:()=>u(`commit-prompt`),onSkipCommit:()=>u(`deploy-prompt`),onQuit:()=>J(0,`quit`,x)}),l===`commit-prompt`&&x&&M.createElement(Ir,{cwd:t.cwd,baseline:V??{isRepository:!1,root:null,dirtyPaths:[]},changedPaths:[...U.current],onDone:e=>{de(e.message),e.pushed&&O(`Pushed ${e.shortSha} to ${e.branch}`),u(`deploy-prompt`)},onError:e=>{w(e),u(`error`)}}),l===`deploy-prompt`&&x&&M.createElement(Lr,{site:x,notice:H,onDeployed:()=>{t.skipVerify?(R(`skipped`),u(`success`)):(W.current=Date.now(),u(`visit-prompt`))},onSkip:()=>{R(`skipped`),u(`success`)},onQuit:()=>J(0,`quit`,x)}),l===`visit-prompt`&&x&&M.createElement(Rr,{site:x,onContinue:()=>u(`verify`),onQuit:()=>J(0,`quit`,x)}),l===`verify`&&x&&M.createElement(zr,{site:x,since:W.current??Date.now(),elapsed:ce,onTick:e=>L(e),onArrived:()=>{Ce()},onTimeout:()=>{R(`unverified`),u(`success`)},onSkip:()=>{R(`skipped`),u(`success`)},onQuit:()=>J(0,`quit`,x)}),l===`success`&&d&&x&&M.createElement(Nr,{adapter:d,site:x,stats:te,outcome:le,dashboardUrl:z?.kind===`dashboard`?z.url:void 0,firstParty:oe,onPick:e=>J(0,e,x)}),l===`error`&&M.createElement(g,{title:`Install failed`,state:`err`},M.createElement(A,{color:c.error},C??`Unknown error`)),M.createElement(ee,{items:l===`already-installed`?[{key:`enter`,label:`verify and continue`},{key:`r`,label:`reinstall or change site`},{key:`q`,label:`quit`},{key:`ctrl-c`,label:`abort`}]:[{key:`q`,label:`quit`},{key:`ctrl-c`,label:`abort`}]}))};async function br(e,t,n,r){if(e.firstParty===!1){n.setFirstParty?.({host:`unknown`,proxyFile:null,proxyAction:`skipped`,snippetSwapped:!1,manual:"First-party tracking skipped (--no-first-party). Safari/Brave and other strict-privacy setups block third-party analytics — add all-browser coverage any time with `zenovay init --host <cloudflare-pages|vercel|netlify|nextjs>`.",changedFiles:[]});return}if(!n.setFirstParty)return;n.setTasks(e=>e.some(e=>e.id===`first-party`)?e.map(e=>e.id===`first-party`?{...e,status:`active`}:e):[...e,{id:`first-party`,label:`Set up first-party tracking (all browsers)`,status:`active`}]),n.setLiveLine(`Setting up first-party tracking (all browsers)…`);let i=_n(e.host),a=null;try{if(a=await Fn(e.cwd,{trackingCode:t,forceHost:i,beforeWrite:r}),n.setFirstParty(a),n.recordChangedPaths?.(a.changedFiles),a.host===`unknown`&&!i&&n.askHostChoice){n.setLiveLine(`Where do you deploy this site? (enables all-browser tracking)`);let i=e.host?`Unrecognized --host "${e.host}" — pick your host below.`:void 0,o=await n.askHostChoice(i);o&&(n.setLiveLine(`Setting up first-party tracking…`),a=await Fn(e.cwd,{trackingCode:t,forceHost:o,beforeWrite:r}),n.setFirstParty(a),n.recordChangedPaths?.(a.changedFiles))}}catch{a={host:`unknown`,proxyFile:null,proxyAction:`skipped`,snippetSwapped:!1,manual:"First-party setup hit an error — your standard tracker is active; add all-browser coverage later with `zenovay init --host <cloudflare-pages|vercel|netlify|nextjs>`.",changedFiles:[]},n.setFirstParty(a)}let o=Sr(a,e.cwd);n.setTasks(e=>e.map(e=>e.id===`first-party`?{...e,status:`done`,detail:o}:e)),n.setLiveLine(void 0)}function xr(e,t){let n=C.resolve(e),r=C.isAbsolute(t)?C.normalize(t):C.resolve(n,t),i=C.relative(n,r);return i&&i!==`..`&&!i.startsWith(`..${C.sep}`)&&!C.isAbsolute(i)?i:C.basename(t)}function Sr(e,t){return e?e.proxyFile&&e.proxyAction!==`manual`&&e.proxyAction!==`skipped`?`now loads from your domain (${xr(t,e.proxyFile)})`:e.manual?`standard tracking active — see note below for all-browser coverage`:`standard tracking active`:`standard tracking active`}function Cr(e){return e&&e.installed.length>0?e.installed.join(`, `):e&&e.errors.length>0?`failed: ${e.errors[0]?.message??`unknown error`}`:`none detected`}async function wr(e,t,n){n.setLiveLine(`Verifying the tracker is in your source…`);try{let r=await o(e,t),i=r.recommendation===`no-op`&&r.foundTrackingCodes.includes(t);n.setVerifyResult?.({ok:i,detail:i?`Tracker confirmed in your source files`:`Couldn't auto-confirm the tracker (diagnosis: ${r.recommendation}) — please double-check`})}catch{n.setVerifyResult?.({ok:!1,detail:`Verification check could not run`})}n.setLiveLine(void 0)}async function Tr(r,i,s,c){try{c.setPhase(`agent`);let l=await e(),u=await a({strict:!1}),d=new n({config:l,cliVersion:s.cliVersion,token:u}),f=new H({cwd:s.cwd}),p=e=>f.journalTrustedWrite(e),m=r.trackingCode??r.id;if(!Z(m)){c.setErrorMsg(`The resolved tracking code "${m}" has an unexpected format (expected letters, digits, "_" or "-"). Aborting to avoid writing broken markup — re-check the site in your dashboard.`),c.setPhase(`error`);return}await t({defaultSiteId:r.id,defaultSiteName:r.name}).catch(()=>void 0);let h=await o(s.cwd,m);if(h.recommendation===`no-op`){c.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:`done`,detail:`already installed correctly`}:e)),c.setLiveLine(h.summary),c.setSandboxStats?.({reads:0,writes:0,rounds:0}),!s.skipMcp&&u&&await X({accessToken:u.accessToken}).catch(()=>void 0),c.setVerifyResult?.({ok:!0,detail:`Already installed correctly`}),await br(s,m,c,p),c.setPhase(`install-complete`);return}if(h.competitors.length>0&&c.setLiveLine(`Detected ${h.competitors.map(e=>e.name).join(`, `)} — will install Zenovay alongside (won't touch their tags).`),i.id===`next-app-router`){c.setTasks([{id:`detect`,label:`Detect framework`,status:`done`,detail:`Next.js (App Router)`},{id:`read`,label:`Find the document shell layout`,status:`active`},{id:`write`,label:`Insert tracker <Script>`,status:`pending`},{id:`env`,label:`Write env vars (.env.local)`,status:`pending`},{id:`mcp`,label:`Install MCP clients (Claude Code/Cursor/VS Code)`,status:`pending`},{id:`verify`,label:`Verify the tracker in your source`,status:`pending`}]),c.setLiveLine(`Next.js — locating the document shell layout…`);let e=await nn({cwd:s.cwd,trackingCode:m,beforeWrite:p});if(c.recordChangedPaths?.(e.installed),!e.fellThrough&&e.errors.length===0){let t=e.installed[0]??`already installed`;c.setTasks(e=>e.map(e=>e.id===`read`||e.id===`write`?{...e,status:`done`,detail:t}:e));let n=await Y(s.cwd,{[i.envVarName]:m},{beforeWrite:p});if((n.addedKeys.length>0||n.updatedKeys.length>0)&&c.recordChangedPaths?.([n.file]),c.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${n.addedKeys.length} key(s) added`}:e)),!s.skipMcp&&u){let e=await X({accessToken:u.accessToken}).catch(e=>({installed:[],skipped:[],errors:[{client:`mcp`,message:e.message}]}));c.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:Cr(e)}:t))}else c.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await wr(s.cwd,m,c),c.setTasks(e=>e.map(e=>e.id===`verify`?{...e,status:`done`}:e)),c.setSandboxStats?.({reads:1,writes:e.installed.length,rounds:0}),await br(s,m,c,p),c.setPhase(`install-complete`);return}c.setLiveLine(`Custom Next.js structure — handing off to the AI agent…`)}let g=i.id===`plain-html`;if(g){c.setTasks([{id:`detect`,label:`Detect framework`,status:`done`,detail:`Plain HTML`},{id:`read`,label:`Scan .html pages`,status:`active`},{id:`write`,label:`Insert tracker <script>`,status:`pending`},{id:`env`,label:`Write env vars`,status:`pending`},{id:`mcp`,label:`Install MCP clients (Claude Code/Cursor/VS Code)`,status:`pending`},{id:`verify`,label:`Verify the tracker in your source`,status:`pending`}]),c.setLiveLine(`Plain HTML — using fast install path (no AI needed)…`);let e=await Gt({cwd:s.cwd,trackingCode:m,updateOnly:h.recommendation===`update-tracking-code`,beforeWrite:p});if(c.recordChangedPaths?.(e.installed),e.installed.length===0&&e.errors.length===0&&e.skipped.length===0)throw Error(`No .html files with a <head>...</head> block were found to inject the tracker into.`);if(e.installed.length===0&&e.errors.length>0)throw Error(`Programmatic install failed for all ${e.errors.length} file(s). First error: ${e.errors[0].file}: ${e.errors[0].error}`);c.setTasks(t=>t.map(t=>t.id===`read`||t.id===`write`?{...t,status:`done`,detail:`${e.installed.length} file(s)`}:t)),c.setLiveLine(`Tracker added to ${e.installed.length} file(s). Skipped ${e.skipped.length}, errored ${e.errors.length}.`);let t=await Y(s.cwd,{[i.envVarName]:m},{beforeWrite:p});if((t.addedKeys.length>0||t.updatedKeys.length>0)&&c.recordChangedPaths?.([t.file]),c.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${t.addedKeys.length} key(s) added`}:e)),!s.skipMcp&&u){let e=await X({accessToken:u.accessToken}).catch(e=>({installed:[],skipped:[],errors:[{client:`mcp`,message:e.message}]}));c.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:Cr(e)}:t))}else c.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await wr(s.cwd,m,c),c.setSandboxStats?.({reads:e.installed.length,writes:e.installed.length,rounds:0}),await br(s,m,c,p),c.setPhase(`install-complete`);return}{let e=await cn({cwd:s.cwd,trackingCode:m,siteId:r.id,adapter:i,beforeWrite:p});c.recordChangedPaths?.(e.installed);let t=e.skipped.some(e=>/already installed|tracker present/i.test(e.reason));if(!e.fellThrough&&e.errors.length===0&&(e.installed.length>0||t)){c.setTasks([{id:`detect`,label:`Detect framework`,status:`done`,detail:i.displayName},{id:`write`,label:`Insert tracker snippet`,status:`done`,detail:e.installed[0]??`already installed`},{id:`env`,label:`Write env vars (.env.local)`,status:`active`},{id:`mcp`,label:`Install MCP clients (Claude Code/Cursor/VS Code)`,status:`pending`},{id:`verify`,label:`Verify the tracker in your source`,status:`pending`}]),c.setLiveLine(`${i.displayName} — using fast install path (no AI needed)…`);let t=await Y(s.cwd,{[i.envVarName]:m},{beforeWrite:p});if((t.addedKeys.length>0||t.updatedKeys.length>0)&&c.recordChangedPaths?.([t.file]),c.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${t.addedKeys.length} key(s) added`}:e)),!s.skipMcp&&u){let e=await X({accessToken:u.accessToken}).catch(e=>({installed:[],skipped:[],errors:[{client:`mcp`,message:e.message}]}));c.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:Cr(e)}:t))}else c.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await wr(s.cwd,m,c),c.setTasks(e=>e.map(e=>e.id===`verify`?{...e,status:`done`}:e)),c.setSandboxStats?.({reads:1,writes:e.installed.length,rounds:0}),await br(s,m,c,p),c.setPhase(`install-complete`);return}c.setLiveLine(`${i.displayName} needs a closer look — using the AI installer (a bit slower than the fast path)…`)}let _=i.buildSnippets({trackingCode:m,siteId:r.id}),v=`Install Zenovay tracking into this ${i.displayName} project.\nSite: ${r.name} (trackingCode: ${m}).\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(`
|
|
327
349
|
`)+`
|
|
328
350
|
3. Insert the tracker using the snippet below.
|
|
329
351
|
4. Confirm the change with a diff before writing.
|
|
@@ -332,4 +354,4 @@ Snippet reference (anchored by anchorKind — adapt to the actual file):
|
|
|
332
354
|
`+_.map(e=>` ${e.anchorKind} @ ${e.targetPath}:\n ${e.code.replace(/\n/g,`
|
|
333
355
|
`)}`).join(`
|
|
334
356
|
|
|
335
|
-
`);c.setTasks([{id:`detect`,label:`Detect framework`,status:`active`},{id:`read`,label:`Read project entry files`,status:`pending`},{id:`write`,label:`Insert tracker snippet`,status:`pending`},{id:`env`,label:`Write env vars (.env.local)`,status:`pending`},{id:`mcp`,label:`Install MCP clients (Claude Code/Cursor/VS Code)`,status:`pending`},{id:`verify`,label:`Wait for first event`,status:`pending`}]);let y=(e,t,n)=>{c.setTasks(r=>r.map(r=>r.id===e?{...r,status:t,detail:n??r.detail}:r))},b=zn({mode:Rn(s)});c.registerBridge(b);let ee=b.subscribe(e=>c.setPendingApproval(e)),x=null,S=``,C=0;try{await Vt({api:d,sandbox:f,approval:b,prompter:{async ask({question:e}){return e}},handlers:{onToolStart:({name:e})=>{e===`detect_framework`?(y(`detect`,`active`),c.setLiveLine(`Inspecting package.json + config files…`)):e===`read_file`?(y(`detect`,`done`),y(`read`,`active`)):(e===`write_file`||e===`patch_file`)&&(y(`read`,`done`),y(`write`,`active`))},onToolResult:({name:e,result:t})=>{let n=t?.ok!==!1,r=t?.content??{};e===`detect_framework`&&n&&(y(`detect`,`done`,i.displayName),c.setLiveLine(`Detected ${i.displayName}`)),e===`read_file`&&n&&r.path&&c.setLiveLine(`Read ${r.path}`),(e===`write_file`||e===`patch_file`)&&n&&r.path&&(y(`read`,`done`),y(`write`,`done`,`wrote ${r.path}`),c.setLiveLine(`Wrote ${r.path}`))},onDelta:e=>{S=(S+e).slice(-600);let t=Date.now();if(t-C<280)return;C=t;let n=S.replace(/\s+/g,` `).trim().slice(-80);n.length>4&&c.setLiveLine(n)}},initialMessages:[{role:`user`,content:v}],diagnosis:h,targetTrackingCode:m})}catch(e){x=e}finally{ee(),c.setPendingApproval(null)}let w=f.stats();c.recordChangedPaths?.(w.writtenPaths);let T=w.writes>0?await o(s.cwd,m).catch(()=>null):null,E=Wt(w,T?.foundTrackingCodes??[],m,x);if(!E.ok)throw Error(E.error);y(`write`,`done`),y(`env`,`active`),c.setLiveLine(`Adding env var to .env.local`);let D=await J(s.cwd,{[i.envVarName]:m},{beforeWrite:p});if((D.addedKeys.length>0||D.updatedKeys.length>0)&&c.recordChangedPaths?.([D.file]),y(`env`,`done`,`${D.addedKeys.length} key(s) added`),!s.skipMcp&&u){y(`mcp`,`active`),c.setLiveLine(`Detecting Cursor / Claude Desktop / VS Code…`);let e=await Y({accessToken:u.accessToken}).catch(e=>({installed:[],skipped:[],errors:[{client:`mcp`,message:e.message}]}));y(`mcp`,`done`,br(e))}else y(`mcp`,`done`,`skipped`);c.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:e.status===`pending`?`done`:e.status}:e)),await xr(s.cwd,m,c),c.setSandboxStats?.(w),await _r(s,m,c,p),c.setPhase(`install-complete`)}catch(e){c.setErrorMsg(e.message),c.setPhase(`error`)}}const Cr=()=>{let{theme:e}=_();return M.createElement(g,{title:`Zenovay wants to set up your project`,state:`idle`},M.createElement(A,null,`We'll use AI to analyze your codebase and add the Zenovay tracker.`),M.createElement(A,{color:e.muted},`.env* contents stay on your machine. Only framework metadata reaches api.zenovay.com.`))},wr=({siteName:e,note:t,onChoose:n})=>{let{theme:r}=_(),i=[{label:`Cloudflare Pages`,value:`cloudflare-pages`,description:`writes functions/api/_z/[[path]].ts`},{label:`Vercel`,value:`vercel`,description:`adds a vercel.json rewrite`},{label:`Netlify`,value:`netlify`,description:`adds a _redirects rule`},{label:`Next.js (self-hosted)`,value:`nextjs-server`,description:`adds a next.config rewrite`},{label:`Skip — standard tracking only`,value:`skip`,description:`already works in Chrome, Firefox and most browsers`}];return M.createElement(k,{flexDirection:`column`,paddingX:2,paddingTop:1},M.createElement(A,{bold:!0},`Count visitors in every browser?`),t?M.createElement(A,{color:r.warn},t):null,M.createElement(A,{color:r.muted},`Your tracker already works. Safari, Edge and Brave block analytics loaded from another domain — serving Zenovay from your own domain fixes that. Where is `,e,` deployed?`),M.createElement(k,{marginTop:1},M.createElement(b,{items:i,onSelect:e=>n(e===`skip`?null:e)})))},Tr=({adapter:e,site:t,tasks:n,liveLine:r,pendingApproval:i,onApprove:a,pendingHostChoice:o,hostChoiceNote:s,onHostChoice:c})=>{let{theme:l}=_(),u=process.stdout.columns??100,d=(process.stdout.rows??30)-8,f=Math.floor(u/2)-1,p=Math.max(14,d);return M.createElement(k,{flexDirection:`column`},M.createElement(k,{flexDirection:`row`,minHeight:p,borderStyle:`round`,borderColor:l.border},M.createElement(k,{width:f,flexDirection:`column`},M.createElement(qn,{width:f,height:p})),M.createElement(k,{width:1,flexDirection:`column`},M.createElement(A,{color:l.border},`│`)),M.createElement(k,{width:f,flexDirection:`column`},i?M.createElement(k,{flexDirection:`column`,paddingX:2,paddingTop:1},M.createElement(A,{color:l.warn},`The agent wants to write `,i.path),i.reason?M.createElement(A,{color:l.muted},i.reason):null,M.createElement(v,{key:i.id,filePath:i.path,oldContent:i.oldContent,newContent:i.newContent,onApprove:a})):o&&c?M.createElement(wr,{siteName:t.name,note:s,onChoose:c}):M.createElement(M.Fragment,null,M.createElement(k,{paddingX:2,paddingTop:1},M.createElement(y,{done:n.filter(e=>e.status===`done`).length,total:n.length,label:n.find(e=>e.status===`active`)?.label})),M.createElement(Xn,{tasks:n,liveLine:r,width:f,height:p})))),M.createElement(k,{marginTop:1},M.createElement(A,{color:l.muted},`Site: `,t.name,` · code: `,t.trackingCode??t.id,` · Framework: `,e.displayName)))},Er=({site:e,onContinueSetup:t,onReinstall:n,onExit:r})=>{let{theme:i}=_();re((e,i)=>{let a=e.toLowerCase();if(a===`q`||i.escape){r();return}if(a===`r`){n();return}if(a===`c`||i.return){t();return}});let a=e.url.replace(/^https?:\/\//,``).replace(/\/$/,``);return M.createElement(g,{title:`Already installed`,state:`ok`},M.createElement(k,{flexDirection:`column`,gap:1},M.createElement(k,{flexDirection:`row`,gap:1},M.createElement(A,{color:i.success},`✓`),M.createElement(A,{bold:!0},e.name),M.createElement(A,{color:i.muted},`(`,a,`)`)),M.createElement(A,{color:i.muted},`Zenovay is installed in this project. Verify the live site to continue setup.`),e.trackingCode?M.createElement(A,{color:i.dim},`tracking code: `,e.trackingCode):null,M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(A,null,M.createElement(A,{color:i.accent},`[Enter]`),` Verify the live site and continue setup`),M.createElement(A,null,M.createElement(A,{color:i.accent},`[R]`),` Reinstall or choose a different site`))))},Dr=({sites:e,preselectHint:t,onPick:n})=>{let r=Zn(e,t),i=e.filter(e=>e.id!==r?.id),a=r?[r,...i]:i,o=[...a.map(e=>({label:Rr(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 M.createElement(g,{title:t?`Pick a site (best match: ${t})`:`Pick a site`,state:`idle`},M.createElement(b,{items:o,onSelect:n}))};function Or(){let e=process.argv[1]??``;return e.includes(`/_npx/`)||e.includes(`\\_npx\\`)||process.env.npm_execpath?.includes(`npx`)?`npx`:`global`}const kr=({k:e,primary:t})=>{let{theme:n}=_();return M.createElement(A,null,M.createElement(A,{color:n.muted},`[`),M.createElement(A,{bold:!0,color:t?n.accent:n.fg},e),M.createElement(A,{color:n.muted},`] `))},Ar=({adapter:e,site:t,stats:n,outcome:r,dashboardUrl:a,firstParty:o,onPick:s})=>{let{theme:c}=_(),u=Or(),d=u===`npx`?`npx @zenovay/cli`:`zenovay`,f=a??i(t),p=r===`verified`,m=p?`You’re live on Zenovay`:r===`unverified`?`Tracker installed — not yet verified`:`Tracker installed — verification skipped`,h=p?`✓ First event received from ${t.name}`:r===`unverified`?`Installation finished, but no new event was confirmed.`:`Installation finished without checking for a new event.`,v=n&&n.rounds>0?`${n.writes} file(s) · ${n.rounds} agent round(s)`:n&&n.writes>0?`${n.writes} file(s) · programmatic (no AI calls)`:null;return re((e,t)=>{let n=e.toLowerCase();n===`o`?l(f):n===`q`||t.escape||n===`s`?s(`quit`):p&&(n===`w`||t.return)?s(`watch`):p&&n===`e`?s(`events`):!p&&t.return&&s(`quit`)},{isActive:!0}),M.createElement(g,{title:m,state:p?`ok`:`warn`},M.createElement(A,{bold:!0,color:p?c.success:c.warn},h),M.createElement(A,{color:c.accent},`─`.repeat(18)),M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(Z,{label:`Framework`,value:e.displayName}),M.createElement(Z,{label:`Site`,value:M.createElement(Ln,{url:t.url,label:t.name})}),t.trackingCode?M.createElement(Z,{label:`Tracker`,value:M.createElement(A,{color:c.muted},t.trackingCode)}):M.createElement(Z,{label:`Tracker`,value:M.createElement(A,{color:c.warn},t.id,` (using site ID — verify in dashboard)`)}),v?M.createElement(Z,{label:`Changes`,value:M.createElement(A,{color:c.muted},v)}):null,p?null:M.createElement(Z,{label:`Verification`,value:M.createElement(A,{color:c.warn},r===`unverified`?`No event confirmed`:`Skipped`)}),M.createElement(Z,{label:`Dashboard`,value:M.createElement(Ln,{url:f})})),o&&o.proxyFile&&o.proxyAction!==`manual`&&o.proxyAction!==`skipped`?M.createElement(k,{marginTop:1},M.createElement(A,{color:c.success},`✓ `),M.createElement(A,{color:c.muted},`Analytics now load from your own domain — after you deploy, Safari, Edge and Brave visitors are counted too.`)):o?.manual?M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(A,{color:c.muted},`Counting visitors in every browser (optional):`),M.createElement(A,{color:c.muted},` `,o.manual)):null,M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(A,{color:c.dim},`Next steps`),p?M.createElement(k,{marginTop:1},M.createElement(A,null,` `),M.createElement(kr,{k:`W`,primary:!0}),M.createElement(A,null,`Watch live in this terminal `),M.createElement(A,{color:c.muted},`— visitors, pages, sources, vitals`)):null,M.createElement(k,null,M.createElement(A,null,` `),M.createElement(kr,{k:`O`}),M.createElement(A,null,`Open the dashboard in your browser`)),p?M.createElement(k,null,M.createElement(A,null,` `),M.createElement(kr,{k:`E`}),M.createElement(A,null,`Stream events as they fire `),M.createElement(A,{color:c.muted},`— page views, custom events, live`)):null,M.createElement(k,null,M.createElement(A,null,` `),M.createElement(kr,{k:`S`}),M.createElement(A,null,`Exit to shell`))),u===`npx`?M.createElement(k,{marginTop:1,flexDirection:`column`,borderStyle:`single`,borderColor:c.warn,paddingX:1},M.createElement(A,{color:c.warn,bold:!0},`Heads up — you ran via npx`),M.createElement(A,{color:c.muted},"The `zenovay` command isn’t on your PATH yet. After you exit, run:"),M.createElement(k,{marginTop:1},M.createElement(A,{color:c.fg},` npm i -g @zenovay/cli `),M.createElement(A,{color:c.muted},"→ then `zenovay overview` works directly"))):M.createElement(k,{marginTop:1},M.createElement(A,{color:c.muted},`From your shell: `),M.createElement(A,{color:c.fg},d,` overview`),M.createElement(A,{color:c.muted},` · `),M.createElement(A,{color:c.fg},d,` --help`)))},jr=({cwd:e,adapter:t,site:n,stats:r,verify:i,firstParty:a,onCommit:o,onSkipCommit:s,onQuit:c})=>{let{theme:l}=_();return Lr((e,t)=>{e===`q`||e===`Q`||t.escape?c():e===`y`||e===`Y`||t.return?o():(e===`n`||e===`N`||e===`s`||e===`S`)&&s()}),M.createElement(g,{title:`Tracker installed`,state:i&&!i.ok?`warn`:`ok`},i?M.createElement(A,null,M.createElement(A,{color:i.ok?l.success:l.warn},i.ok?`✔ Verified — `:`⚠ `),i.detail):M.createElement(A,null,M.createElement(A,{color:l.success},`✔ `),`The Zenovay tracker is in your project.`),M.createElement(k,{marginTop:1},M.createElement(A,{color:l.muted},`Framework: `),M.createElement(A,null,t.displayName)),M.createElement(k,null,M.createElement(A,{color:l.muted},`Site: `),M.createElement(A,null,n.name,` (`,n.url,`)`)),r&&M.createElement(k,null,M.createElement(A,{color:l.muted},`Modified: `),M.createElement(A,null,r.writes,` file(s)`)),M.createElement(Mr,{cwd:e,firstParty:a}),M.createElement(k,{marginTop:1},M.createElement(A,null,`Commit + push these changes to git? `),M.createElement(A,{color:l.accent},`[Y/n]`)))},Mr=({cwd:e,firstParty:t})=>{let{theme:n}=_();if(!t)return null;let r=t.proxyFile&&t.proxyAction!==`manual`&&t.proxyAction!==`skipped`?t.proxyFile:null;return r?M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(k,null,M.createElement(A,{color:n.success},`✔ `),M.createElement(A,null,`Analytics now load from your own domain `),M.createElement(A,{color:n.muted},`(`,vr(e,r),`)`)),M.createElement(A,{color:n.muted},`After you deploy, Safari, Edge and Brave visitors are counted too.`)):t.manual?M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(k,null,M.createElement(A,{color:n.muted},`Counting visitors in every browser (optional):`)),M.createElement(A,{color:n.muted},t.manual)):null},Nr=({cwd:e,baseline:t,changedPaths:n,onDone:r,onError:i})=>{let{theme:a}=_(),[o,s]=F(`committing`),[c,l]=F(`Checking the Zenovay file journal…`),u=P(!1);return N(()=>{u.current||(u.current=!0,(async()=>{try{let i=await ar({cwd:e,baseline:t,changedPaths:n,onDetail:e=>l(e),onPhase:e=>s(e)});s(`done`),l(i.message),setTimeout(()=>r(i),800)}catch(e){i(e.message)}})())},[t,n,e,r,i]),M.createElement(g,{title:`Committing to git`,state:`busy`},M.createElement(k,null,o===`done`?M.createElement(A,{color:a.success},`✓`):M.createElement(A,{color:a.accent},M.createElement(I,{type:`dots`})),M.createElement(A,null,` `,o===`pushing`?`Pushing to origin…`:o===`done`?`Git step finished`:`Committing…`)),M.createElement(k,{marginTop:1},M.createElement(A,{color:a.muted},c)))},Pr=({site:e,notice:t,onDeployed:n,onSkip:r,onQuit:i})=>{let{theme:a}=_();return Lr((e,t)=>{e===`q`||e===`Q`||t.escape?i():e===`y`||e===`Y`||t.return||e===`d`||e===`D`?n():(e===`n`||e===`N`||e===`s`||e===`S`)&&r()}),M.createElement(g,{title:`Ready to deploy?`,state:`idle`},M.createElement(A,null,`The tracker is installed locally. To capture events you need it on the live site:`),M.createElement(A,null,` `),M.createElement(k,null,M.createElement(A,{color:a.muted},` → `),M.createElement(Ln,{url:e.url})),M.createElement(A,null,` `),M.createElement(A,{color:a.muted},`Push the change through your normal deploy pipeline (Vercel auto-deploy, CI/CD, etc.).`),t?M.createElement(k,{marginTop:1},M.createElement(A,{color:a.warn},t)):null,M.createElement(k,{marginTop:1},M.createElement(A,null,`Once it’s deployed, press `),M.createElement(A,{color:a.accent},`[Y]`),M.createElement(A,null,` to verify the tracker is firing. `),M.createElement(A,{color:a.muted},`[s] skip verification`)))},Fr=({site:e,onContinue:t,onQuit:n})=>{let{theme:r}=_();return Lr((e,r)=>{e===`q`||e===`Q`||r.escape?n():t()}),M.createElement(g,{title:`Visit your site`,state:`idle`},M.createElement(A,null,`To send a test event, open any page on your site:`),M.createElement(A,null,` `),M.createElement(k,null,M.createElement(A,{color:r.muted},` → `),M.createElement(Ln,{url:e.url})),M.createElement(A,null,` `),M.createElement(A,{color:r.muted},`The tracker fires automatically on page load. We’ll verify the next event arrives.`),M.createElement(k,{marginTop:1},M.createElement(A,null,`Press `),M.createElement(A,{color:r.accent},`[any key]`),M.createElement(A,null,` when you’ve visited the page.`)))},Ir=({site:t,since:r,elapsed:i,onTick:o,onArrived:s,onTimeout:c,onSkip:l,onQuit:u})=>{let{theme:d}=_(),[f,p]=F(`preflight`),[m,h]=F(``),[v,y]=F([]),b=P(!1),ee=t.trackingCode??t.id,x=async()=>{p(`preflight`),h(`Fetching ${t.url}…`);let e=await fr(t.url,ee);if(b.current)return;if(e.state===`tracker-correct`){p(`polling`),h(`Tracker detected on live site — waiting for first hit…`),S();return}if(e.state===`tracker-wrong-id`){p(`wrong-id-on-live`),y(e.foundCodes),h(`Live site has Zenovay but with id(s): ${e.foundCodes.join(`, `)}`);return}if(e.state===`proxy-broken`){p(`proxy-broken`),h(`${e.detail} Route: ${e.scriptUrl}`);return}p(`awaiting-deploy`);let n=e.networkError?/enotfound|getaddrinfo|dns/i.test(e.networkError)?` (DNS lookup failed — check the site URL is correct + deployed)`:/timeout|etimedout|abort|econnrefused|network/i.test(e.networkError)?` (check your internet connection, then retry with [r])`:``:``;h(e.networkError?`Couldn’t reach ${t.url}: ${e.networkError}${n}`:e.httpStatus?`${t.url} returned HTTP ${e.httpStatus}`:`No Zenovay tracker found on ${t.url}.`)},S=async()=>{try{let i=await e(),c=await a({strict:!1}),l=new n({config:i,cliVersion:`0`,token:c}),u=await Ot(t.id,r,{api:l,timeoutMs:6e4,pollIntervalMs:2500,onTick:e=>{b.current||o(e)}});if(b.current)return;u.received?(p(`success`),s()):p(`timeout`)}catch{b.current||p(`timeout`)}};N(()=>(b.current=!1,x(),()=>{b.current=!0}),[]),re((e,t)=>{if(e===`q`||e===`Q`||t.escape){u();return}if(e===`s`||e===`S`){f===`timeout`?c():f!==`success`&&l();return}(f===`awaiting-deploy`||f===`wrong-id-on-live`||f===`proxy-broken`||f===`timeout`)&&(e===`r`||e===`R`)&&x()},{isActive:!0});let C=Math.floor(i/1e3);return f===`preflight`?M.createElement(g,{title:`Verifying`,state:`busy`},M.createElement(k,null,M.createElement(A,{color:d.accent},M.createElement(I,{type:`dots`})),M.createElement(A,null,` Checking your live site for the tracker…`)),M.createElement(k,{marginTop:1},M.createElement(A,{color:d.muted},m))):f===`awaiting-deploy`?M.createElement(g,{title:`Tracker not yet on your live site`,state:`warn`},M.createElement(A,{color:d.warn},m),M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(A,null,`The tracker is in your local repo but hasn’t been deployed yet.`),M.createElement(A,{color:d.muted},`Push your changes and wait for your deploy to finish (Vercel / Cloudflare Pages / CI), then retry.`)),M.createElement(k,{marginTop:1},M.createElement(A,null,`Press `),M.createElement(A,{color:d.accent},`[r]`),M.createElement(A,null,` to re-check, `),M.createElement(A,{color:d.accent},`[s]`),M.createElement(A,null,` to skip verification.`))):f===`wrong-id-on-live`?M.createElement(g,{title:`Live site has a different tracking code`,state:`warn`},M.createElement(A,{color:d.warn},`Expected: `,M.createElement(A,{color:d.accent},ee),` `,`Found on live: `,M.createElement(A,{color:d.accent},v.join(`, `))),M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(A,null,`Your local install uses a different ID than what’s on `,t.url,`.`),M.createElement(A,{color:d.muted},`Deploy the new local version, then retry — or skip if the existing ID is intentional.`)),M.createElement(k,{marginTop:1},M.createElement(A,null,`Press `),M.createElement(A,{color:d.accent},`[r]`),M.createElement(A,null,` to re-check, `),M.createElement(A,{color:d.accent},`[s]`),M.createElement(A,null,` to skip.`))):f===`proxy-broken`?M.createElement(g,{title:`First-party proxy is not working`,state:`warn`},M.createElement(A,{color:d.warn},m),M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(A,null,`The tracker tag is deployed, but its same-origin script route did not return the Zenovay JavaScript.`),M.createElement(A,{color:d.muted},`Check the host rewrite or function route, deploy the fix, then retry.`)),M.createElement(k,{marginTop:1},M.createElement(A,null,`Press `),M.createElement(A,{color:d.accent},`[r]`),M.createElement(A,null,` to re-check, `),M.createElement(A,{color:d.accent},`[s]`),M.createElement(A,null,` to skip.`))):f===`timeout`?M.createElement(g,{title:`No event arrived in 1 minute`,state:`warn`},M.createElement(A,{color:d.warn},`The tracker is on your live site but no hits reached api.zenovay.com.`),M.createElement(k,{marginTop:1},M.createElement(A,{color:d.muted},`Try opening `,t.url,` in a fresh browser tab (no ad-blocker), then retry.`)),M.createElement(k,{marginTop:1},M.createElement(A,null,`Press `),M.createElement(A,{color:d.accent},`[r]`),M.createElement(A,null,` to re-check, `),M.createElement(A,{color:d.accent},`[s]`),M.createElement(A,null,` to finish without verification.`))):f===`success`?M.createElement(g,{title:`First event received`,state:`busy`},M.createElement(k,null,M.createElement(A,{color:d.success},`✓`),M.createElement(A,null,` Resolving your next setup step…`))):M.createElement(g,{title:`Waiting for first event`,state:`busy`},M.createElement(k,null,M.createElement(A,{color:d.accent},M.createElement(I,{type:`dots`})),M.createElement(A,null,` Polling api.zenovay.com for the first hit on `),M.createElement(A,{color:d.accent},t.url),M.createElement(A,null,` (`,C,`s elapsed)`)),M.createElement(k,{marginTop:1},M.createElement(A,{color:d.muted},`Reload the page if nothing arrives within ~30 seconds.`)))};function Lr(e){re((t,n)=>{e(t,{return:n.return,escape:n.escape})},{isActive:!0})}function Rr(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 zr(e){try{let t=await w.readFile(C.join(e,`package.json`),`utf8`),n=JSON.parse(t);if(n.name)return String(n.name).replace(/^@[^/]+\//,``)}catch{}try{let t=await w.readFile(C.join(e,`.git`,`config`),`utf8`),n=t.match(/url\s*=\s*.*[/:]([^/]+?)(?:\.git)?\s*$/m);if(n&&n[1])return n[1]}catch{}return C.basename(e)}export{Er as AlreadyInstalledPanel,wr as HostChoicePanel,pr as initCommand};
|
|
357
|
+
`);c.setTasks([{id:`detect`,label:`Detect framework`,status:`active`},{id:`read`,label:`Read project entry files`,status:`pending`},{id:`write`,label:`Insert tracker snippet`,status:`pending`},{id:`env`,label:`Write env vars (.env.local)`,status:`pending`},{id:`mcp`,label:`Install MCP clients (Claude Code/Cursor/VS Code)`,status:`pending`},{id:`verify`,label:`Wait for first event`,status:`pending`}]);let y=(e,t,n)=>{c.setTasks(r=>r.map(r=>r.id===e?{...r,status:t,detail:n??r.detail}:r))},b=Vn({mode:Bn(s)});c.registerBridge(b);let ee=b.subscribe(e=>c.setPendingApproval(e)),x=null,S=``,C=0;try{await Bt({api:d,sandbox:f,approval:b,prompter:{async ask({question:e}){return e}},handlers:{onToolStart:({name:e})=>{e===`detect_framework`?(y(`detect`,`active`),c.setLiveLine(`Inspecting package.json + config files…`)):e===`read_file`?(y(`detect`,`done`),y(`read`,`active`)):(e===`write_file`||e===`patch_file`)&&(y(`read`,`done`),y(`write`,`active`))},onToolResult:({name:e,result:t})=>{let n=t?.ok!==!1,r=t?.content??{};e===`detect_framework`&&n&&(y(`detect`,`done`,i.displayName),c.setLiveLine(`Detected ${i.displayName}`)),e===`read_file`&&n&&r.path&&c.setLiveLine(`Read ${r.path}`),(e===`write_file`||e===`patch_file`)&&n&&r.path&&(y(`read`,`done`),y(`write`,`done`,`wrote ${r.path}`),c.setLiveLine(`Wrote ${r.path}`))},onDelta:e=>{S=(S+e).slice(-600);let t=Date.now();if(t-C<280)return;C=t;let n=S.replace(/\s+/g,` `).trim().slice(-80);n.length>4&&c.setLiveLine(n)}},initialMessages:[{role:`user`,content:v}],diagnosis:h,targetTrackingCode:m})}catch(e){x=e}finally{ee(),c.setPendingApproval(null)}let w=f.stats();c.recordChangedPaths?.(w.writtenPaths);let T=w.writes>0?await o(s.cwd,m).catch(()=>null):null,E=Ut(w,T?.foundTrackingCodes??[],m,x);if(!E.ok)throw Error(E.error);y(`write`,`done`),y(`env`,`active`),c.setLiveLine(`Adding env var to .env.local`);let D=await Y(s.cwd,{[i.envVarName]:m},{beforeWrite:p});if((D.addedKeys.length>0||D.updatedKeys.length>0)&&c.recordChangedPaths?.([D.file]),y(`env`,`done`,`${D.addedKeys.length} key(s) added`),!s.skipMcp&&u){y(`mcp`,`active`),c.setLiveLine(`Detecting Cursor / Claude Desktop / VS Code…`);let e=await X({accessToken:u.accessToken}).catch(e=>({installed:[],skipped:[],errors:[{client:`mcp`,message:e.message}]}));y(`mcp`,`done`,Cr(e))}else y(`mcp`,`done`,`skipped`);c.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:e.status===`pending`?`done`:e.status}:e)),await wr(s.cwd,m,c),c.setSandboxStats?.(w),await br(s,m,c,p),c.setPhase(`install-complete`)}catch(e){c.setErrorMsg(e.message),c.setPhase(`error`)}}const Er=()=>{let{theme:e}=_();return M.createElement(g,{title:`Zenovay wants to set up your project`,state:`idle`},M.createElement(A,null,`We'll use AI to analyze your codebase and add the Zenovay tracker.`),M.createElement(A,{color:e.muted},`.env* contents stay on your machine. Only framework metadata reaches api.zenovay.com.`))},Dr=({siteName:e,note:t,onChoose:n})=>{let{theme:r}=_(),i=[{label:`Cloudflare Pages`,value:`cloudflare-pages`,description:`writes functions/api/_z/[[path]].ts`},{label:`Vercel`,value:`vercel`,description:`adds a vercel.json rewrite`},{label:`Netlify`,value:`netlify`,description:`adds a _redirects rule`},{label:`Next.js (self-hosted)`,value:`nextjs-server`,description:`adds a next.config rewrite`},{label:`Skip — standard tracking only`,value:`skip`,description:`already works in Chrome, Firefox and most browsers`}];return M.createElement(k,{flexDirection:`column`,paddingX:2,paddingTop:1},M.createElement(A,{bold:!0},`Count visitors in every browser?`),t?M.createElement(A,{color:r.warn},t):null,M.createElement(A,{color:r.muted},`Your tracker already works. Safari, Edge and Brave block analytics loaded from another domain — serving Zenovay from your own domain fixes that. Where is `,e,` deployed?`),M.createElement(k,{marginTop:1},M.createElement(b,{items:i,onSelect:e=>n(e===`skip`?null:e)})))},Or=({adapter:e,site:t,tasks:n,liveLine:r,pendingApproval:i,onApprove:a,pendingHostChoice:o,hostChoiceNote:s,onHostChoice:c})=>{let{theme:l}=_(),u=process.stdout.columns??100,d=(process.stdout.rows??30)-8,f=Math.floor(u/2)-1,p=Math.max(14,d);return M.createElement(k,{flexDirection:`column`},M.createElement(k,{flexDirection:`row`,minHeight:p,borderStyle:`round`,borderColor:l.border},M.createElement(k,{width:f,flexDirection:`column`},M.createElement(Yn,{width:f,height:p})),M.createElement(k,{width:1,flexDirection:`column`},M.createElement(A,{color:l.border},`│`)),M.createElement(k,{width:f,flexDirection:`column`},i?M.createElement(k,{flexDirection:`column`,paddingX:2,paddingTop:1},M.createElement(A,{color:l.warn},`The agent wants to write `,i.path),i.reason?M.createElement(A,{color:l.muted},i.reason):null,M.createElement(v,{key:i.id,filePath:i.path,oldContent:i.oldContent,newContent:i.newContent,onApprove:a})):o&&c?M.createElement(Dr,{siteName:t.name,note:s,onChoose:c}):M.createElement(M.Fragment,null,M.createElement(k,{paddingX:2,paddingTop:1},M.createElement(y,{done:n.filter(e=>e.status===`done`).length,total:n.length,label:n.find(e=>e.status===`active`)?.label})),M.createElement(Qn,{tasks:n,liveLine:r,width:f,height:p})))),M.createElement(k,{marginTop:1},M.createElement(A,{color:l.muted},`Site: `,t.name,` · code: `,t.trackingCode??t.id,` · Framework: `,e.displayName)))},kr=({site:e,onContinueSetup:t,onReinstall:n,onExit:r})=>{let{theme:i}=_();re((e,i)=>{let a=e.toLowerCase();if(a===`q`||i.escape){r();return}if(a===`r`){n();return}if(a===`c`||i.return){t();return}});let a=e.url.replace(/^https?:\/\//,``).replace(/\/$/,``);return M.createElement(g,{title:`Already installed`,state:`ok`},M.createElement(k,{flexDirection:`column`,gap:1},M.createElement(k,{flexDirection:`row`,gap:1},M.createElement(A,{color:i.success},`✓`),M.createElement(A,{bold:!0},e.name),M.createElement(A,{color:i.muted},`(`,a,`)`)),M.createElement(A,{color:i.muted},`Zenovay is installed in this project. Verify the live site to continue setup.`),e.trackingCode?M.createElement(A,{color:i.dim},`tracking code: `,e.trackingCode):null,M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(A,null,M.createElement(A,{color:i.accent},`[Enter]`),` Verify the live site and continue setup`),M.createElement(A,null,M.createElement(A,{color:i.accent},`[R]`),` Reinstall or choose a different site`))))},Ar=({sites:e,preselectHint:t,onPick:n})=>{let r=er(e,t),i=e.filter(e=>e.id!==r?.id),a=r?[r,...i]:i,o=[...a.map(e=>({label:Vr(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 M.createElement(g,{title:t?`Pick a site (best match: ${t})`:`Pick a site`,state:`idle`},M.createElement(b,{items:o,onSelect:n}))};function jr(){let e=process.argv[1]??``;return e.includes(`/_npx/`)||e.includes(`\\_npx\\`)||process.env.npm_execpath?.includes(`npx`)?`npx`:`global`}const Mr=({k:e,primary:t})=>{let{theme:n}=_();return M.createElement(A,null,M.createElement(A,{color:n.muted},`[`),M.createElement(A,{bold:!0,color:t?n.accent:n.fg},e),M.createElement(A,{color:n.muted},`] `))},Nr=({adapter:e,site:t,stats:n,outcome:r,dashboardUrl:a,firstParty:o,onPick:s})=>{let{theme:c}=_(),u=jr(),d=u===`npx`?`npx @zenovay/cli`:`zenovay`,f=a??i(t),p=r===`verified`,m=p?`You’re live on Zenovay`:r===`unverified`?`Tracker installed — not yet verified`:`Tracker installed — verification skipped`,h=p?`✓ First event received from ${t.name}`:r===`unverified`?`Installation finished, but no new event was confirmed.`:`Installation finished without checking for a new event.`,v=n&&n.rounds>0?`${n.writes} file(s) · ${n.rounds} agent round(s)`:n&&n.writes>0?`${n.writes} file(s) · programmatic (no AI calls)`:null;return re((e,t)=>{let n=e.toLowerCase();n===`o`?l(f):n===`q`||t.escape||n===`s`?s(`quit`):p&&(n===`w`||t.return)?s(`watch`):p&&n===`e`?s(`events`):!p&&t.return&&s(`quit`)},{isActive:!0}),M.createElement(g,{title:m,state:p?`ok`:`warn`},M.createElement(A,{bold:!0,color:p?c.success:c.warn},h),M.createElement(A,{color:c.accent},`─`.repeat(18)),M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(Q,{label:`Framework`,value:e.displayName}),M.createElement(Q,{label:`Site`,value:M.createElement(zn,{url:t.url,label:t.name})}),t.trackingCode?M.createElement(Q,{label:`Tracker`,value:M.createElement(A,{color:c.muted},t.trackingCode)}):M.createElement(Q,{label:`Tracker`,value:M.createElement(A,{color:c.warn},t.id,` (using site ID — verify in dashboard)`)}),v?M.createElement(Q,{label:`Changes`,value:M.createElement(A,{color:c.muted},v)}):null,p?null:M.createElement(Q,{label:`Verification`,value:M.createElement(A,{color:c.warn},r===`unverified`?`No event confirmed`:`Skipped`)}),M.createElement(Q,{label:`Dashboard`,value:M.createElement(zn,{url:f})})),o&&o.proxyFile&&o.proxyAction!==`manual`&&o.proxyAction!==`skipped`?M.createElement(k,{marginTop:1},M.createElement(A,{color:c.success},`✓ `),M.createElement(A,{color:c.muted},`Analytics now load from your own domain — after you deploy, Safari, Edge and Brave visitors are counted too.`)):o?.manual?M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(A,{color:c.muted},`Counting visitors in every browser (optional):`),M.createElement(A,{color:c.muted},` `,o.manual)):null,M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(A,{color:c.dim},`Next steps`),p?M.createElement(k,{marginTop:1},M.createElement(A,null,` `),M.createElement(Mr,{k:`W`,primary:!0}),M.createElement(A,null,`Watch live in this terminal `),M.createElement(A,{color:c.muted},`— visitors, pages, sources, vitals`)):null,M.createElement(k,null,M.createElement(A,null,` `),M.createElement(Mr,{k:`O`}),M.createElement(A,null,`Open the dashboard in your browser`)),p?M.createElement(k,null,M.createElement(A,null,` `),M.createElement(Mr,{k:`E`}),M.createElement(A,null,`Stream events as they fire `),M.createElement(A,{color:c.muted},`— page views, custom events, live`)):null,M.createElement(k,null,M.createElement(A,null,` `),M.createElement(Mr,{k:`S`}),M.createElement(A,null,`Exit to shell`))),u===`npx`?M.createElement(k,{marginTop:1,flexDirection:`column`,borderStyle:`single`,borderColor:c.warn,paddingX:1},M.createElement(A,{color:c.warn,bold:!0},`Heads up — you ran via npx`),M.createElement(A,{color:c.muted},"The `zenovay` command isn’t on your PATH yet. After you exit, run:"),M.createElement(k,{marginTop:1},M.createElement(A,{color:c.fg},` npm i -g @zenovay/cli `),M.createElement(A,{color:c.muted},"→ then `zenovay overview` works directly"))):M.createElement(k,{marginTop:1},M.createElement(A,{color:c.muted},`From your shell: `),M.createElement(A,{color:c.fg},d,` overview`),M.createElement(A,{color:c.muted},` · `),M.createElement(A,{color:c.fg},d,` --help`)))},Pr=({cwd:e,adapter:t,site:n,stats:r,verify:i,firstParty:a,onCommit:o,onSkipCommit:s,onQuit:c})=>{let{theme:l}=_();return Br((e,t)=>{e===`q`||e===`Q`||t.escape?c():e===`y`||e===`Y`||t.return?o():(e===`n`||e===`N`||e===`s`||e===`S`)&&s()}),M.createElement(g,{title:`Tracker installed`,state:i&&!i.ok?`warn`:`ok`},i?M.createElement(A,null,M.createElement(A,{color:i.ok?l.success:l.warn},i.ok?`✔ Verified — `:`⚠ `),i.detail):M.createElement(A,null,M.createElement(A,{color:l.success},`✔ `),`The Zenovay tracker is in your project.`),M.createElement(k,{marginTop:1},M.createElement(A,{color:l.muted},`Framework: `),M.createElement(A,null,t.displayName)),M.createElement(k,null,M.createElement(A,{color:l.muted},`Site: `),M.createElement(A,null,n.name,` (`,n.url,`)`)),r&&M.createElement(k,null,M.createElement(A,{color:l.muted},`Modified: `),M.createElement(A,null,r.writes,` file(s)`)),M.createElement(Fr,{cwd:e,firstParty:a}),M.createElement(k,{marginTop:1},M.createElement(A,null,`Commit + push these changes to git? `),M.createElement(A,{color:l.accent},`[Y/n]`)))},Fr=({cwd:e,firstParty:t})=>{let{theme:n}=_();if(!t)return null;let r=t.proxyFile&&t.proxyAction!==`manual`&&t.proxyAction!==`skipped`?t.proxyFile:null;return r?M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(k,null,M.createElement(A,{color:n.success},`✔ `),M.createElement(A,null,`Analytics now load from your own domain `),M.createElement(A,{color:n.muted},`(`,xr(e,r),`)`)),M.createElement(A,{color:n.muted},`After you deploy, Safari, Edge and Brave visitors are counted too.`)):t.manual?M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(k,null,M.createElement(A,{color:n.muted},`Counting visitors in every browser (optional):`)),M.createElement(A,{color:n.muted},t.manual)):null},Ir=({cwd:e,baseline:t,changedPaths:n,onDone:r,onError:i})=>{let{theme:a}=_(),[o,s]=F(`committing`),[c,l]=F(`Checking the Zenovay file journal…`),u=P(!1);return N(()=>{u.current||(u.current=!0,(async()=>{try{let i=await cr({cwd:e,baseline:t,changedPaths:n,onDetail:e=>l(e),onPhase:e=>s(e)});s(`done`),l(i.message),setTimeout(()=>r(i),800)}catch(e){i(e.message)}})())},[t,n,e,r,i]),M.createElement(g,{title:`Committing to git`,state:`busy`},M.createElement(k,null,o===`done`?M.createElement(A,{color:a.success},`✓`):M.createElement(A,{color:a.accent},M.createElement(I,{type:`dots`})),M.createElement(A,null,` `,o===`pushing`?`Pushing to origin…`:o===`done`?`Git step finished`:`Committing…`)),M.createElement(k,{marginTop:1},M.createElement(A,{color:a.muted},c)))},Lr=({site:e,notice:t,onDeployed:n,onSkip:r,onQuit:i})=>{let{theme:a}=_();return Br((e,t)=>{e===`q`||e===`Q`||t.escape?i():e===`y`||e===`Y`||t.return||e===`d`||e===`D`?n():(e===`n`||e===`N`||e===`s`||e===`S`)&&r()}),M.createElement(g,{title:`Ready to deploy?`,state:`idle`},M.createElement(A,null,`The tracker is installed locally. To capture events you need it on the live site:`),M.createElement(A,null,` `),M.createElement(k,null,M.createElement(A,{color:a.muted},` → `),M.createElement(zn,{url:e.url})),M.createElement(A,null,` `),M.createElement(A,{color:a.muted},`Push the change through your normal deploy pipeline (Vercel auto-deploy, CI/CD, etc.).`),t?M.createElement(k,{marginTop:1},M.createElement(A,{color:a.warn},t)):null,M.createElement(k,{marginTop:1},M.createElement(A,null,`Once it’s deployed, press `),M.createElement(A,{color:a.accent},`[Y]`),M.createElement(A,null,` to verify the tracker is firing. `),M.createElement(A,{color:a.muted},`[s] skip verification`)))},Rr=({site:e,onContinue:t,onQuit:n})=>{let{theme:r}=_();return Br((e,r)=>{e===`q`||e===`Q`||r.escape?n():t()}),M.createElement(g,{title:`Visit your site`,state:`idle`},M.createElement(A,null,`To send a test event, open any page on your site:`),M.createElement(A,null,` `),M.createElement(k,null,M.createElement(A,{color:r.muted},` → `),M.createElement(zn,{url:e.url})),M.createElement(A,null,` `),M.createElement(A,{color:r.muted},`The tracker fires automatically on page load. We’ll verify the next event arrives.`),M.createElement(k,{marginTop:1},M.createElement(A,null,`Press `),M.createElement(A,{color:r.accent},`[any key]`),M.createElement(A,null,` when you’ve visited the page.`)))},zr=({site:t,since:r,elapsed:i,onTick:o,onArrived:s,onTimeout:c,onSkip:l,onQuit:u})=>{let{theme:d}=_(),[f,p]=F(`preflight`),[m,h]=F(``),[v,y]=F([]),b=P(!1),ee=t.trackingCode??t.id,x=async()=>{p(`preflight`),h(`Fetching ${t.url}…`);let e=await hr(t.url,ee);if(b.current)return;if(e.state===`tracker-correct`){p(`polling`),h(`Tracker detected on live site — waiting for first hit…`),S();return}if(e.state===`tracker-wrong-id`){p(`wrong-id-on-live`),y(e.foundCodes),h(`Live site has Zenovay but with id(s): ${e.foundCodes.join(`, `)}`);return}if(e.state===`proxy-broken`){p(`proxy-broken`),h(`${e.detail} Route: ${e.scriptUrl}`);return}p(`awaiting-deploy`);let n=e.networkError?/enotfound|getaddrinfo|dns/i.test(e.networkError)?` (DNS lookup failed — check the site URL is correct + deployed)`:/timeout|etimedout|abort|econnrefused|network/i.test(e.networkError)?` (check your internet connection, then retry with [r])`:``:``;h(e.networkError?`Couldn’t reach ${t.url}: ${e.networkError}${n}`:e.httpStatus?`${t.url} returned HTTP ${e.httpStatus}`:`No Zenovay tracker found on ${t.url}.`)},S=async()=>{try{let i=await e(),c=await a({strict:!1}),l=new n({config:i,cliVersion:`0`,token:c}),u=await Dt(t.id,r,{api:l,timeoutMs:6e4,pollIntervalMs:2500,onTick:e=>{b.current||o(e)}});if(b.current)return;u.received?(p(`success`),s()):p(`timeout`)}catch{b.current||p(`timeout`)}};N(()=>(b.current=!1,x(),()=>{b.current=!0}),[]),re((e,t)=>{if(e===`q`||e===`Q`||t.escape){u();return}if(e===`s`||e===`S`){f===`timeout`?c():f!==`success`&&l();return}(f===`awaiting-deploy`||f===`wrong-id-on-live`||f===`proxy-broken`||f===`timeout`)&&(e===`r`||e===`R`)&&x()},{isActive:!0});let C=Math.floor(i/1e3);return f===`preflight`?M.createElement(g,{title:`Verifying`,state:`busy`},M.createElement(k,null,M.createElement(A,{color:d.accent},M.createElement(I,{type:`dots`})),M.createElement(A,null,` Checking your live site for the tracker…`)),M.createElement(k,{marginTop:1},M.createElement(A,{color:d.muted},m))):f===`awaiting-deploy`?M.createElement(g,{title:`Tracker not yet on your live site`,state:`warn`},M.createElement(A,{color:d.warn},m),M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(A,null,`The tracker is in your local repo but hasn’t been deployed yet.`),M.createElement(A,{color:d.muted},`Push your changes and wait for your deploy to finish (Vercel / Cloudflare Pages / CI), then retry.`)),M.createElement(k,{marginTop:1},M.createElement(A,null,`Press `),M.createElement(A,{color:d.accent},`[r]`),M.createElement(A,null,` to re-check, `),M.createElement(A,{color:d.accent},`[s]`),M.createElement(A,null,` to skip verification.`))):f===`wrong-id-on-live`?M.createElement(g,{title:`Live site has a different tracking code`,state:`warn`},M.createElement(A,{color:d.warn},`Expected: `,M.createElement(A,{color:d.accent},ee),` `,`Found on live: `,M.createElement(A,{color:d.accent},v.join(`, `))),M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(A,null,`Your local install uses a different ID than what’s on `,t.url,`.`),M.createElement(A,{color:d.muted},`Deploy the new local version, then retry — or skip if the existing ID is intentional.`)),M.createElement(k,{marginTop:1},M.createElement(A,null,`Press `),M.createElement(A,{color:d.accent},`[r]`),M.createElement(A,null,` to re-check, `),M.createElement(A,{color:d.accent},`[s]`),M.createElement(A,null,` to skip.`))):f===`proxy-broken`?M.createElement(g,{title:`First-party proxy is not working`,state:`warn`},M.createElement(A,{color:d.warn},m),M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(A,null,`The tracker tag is deployed, but its same-origin script route did not return the Zenovay JavaScript.`),M.createElement(A,{color:d.muted},`Check the host rewrite or function route, deploy the fix, then retry.`)),M.createElement(k,{marginTop:1},M.createElement(A,null,`Press `),M.createElement(A,{color:d.accent},`[r]`),M.createElement(A,null,` to re-check, `),M.createElement(A,{color:d.accent},`[s]`),M.createElement(A,null,` to skip.`))):f===`timeout`?M.createElement(g,{title:`No event arrived in 1 minute`,state:`warn`},M.createElement(A,{color:d.warn},`The tracker is on your live site but no hits reached api.zenovay.com.`),M.createElement(k,{marginTop:1},M.createElement(A,{color:d.muted},`Try opening `,t.url,` in a fresh browser tab (no ad-blocker), then retry.`)),M.createElement(k,{marginTop:1},M.createElement(A,null,`Press `),M.createElement(A,{color:d.accent},`[r]`),M.createElement(A,null,` to re-check, `),M.createElement(A,{color:d.accent},`[s]`),M.createElement(A,null,` to finish without verification.`))):f===`success`?M.createElement(g,{title:`First event received`,state:`busy`},M.createElement(k,null,M.createElement(A,{color:d.success},`✓`),M.createElement(A,null,` Resolving your next setup step…`))):M.createElement(g,{title:`Waiting for first event`,state:`busy`},M.createElement(k,null,M.createElement(A,{color:d.accent},M.createElement(I,{type:`dots`})),M.createElement(A,null,` Polling api.zenovay.com for the first hit on `),M.createElement(A,{color:d.accent},t.url),M.createElement(A,null,` (`,C,`s elapsed)`)),M.createElement(k,{marginTop:1},M.createElement(A,{color:d.muted},`Reload the page if nothing arrives within ~30 seconds.`)))};function Br(e){re((t,n)=>{e(t,{return:n.return,escape:n.escape})},{isActive:!0})}function Vr(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 Hr(e){try{let t=await w.readFile(C.join(e,`package.json`),`utf8`),n=JSON.parse(t);if(n.name)return String(n.name).replace(/^@[^/]+\//,``)}catch{}try{let t=await w.readFile(C.join(e,`.git`,`config`),`utf8`),n=t.match(/url\s*=\s*.*[/:]([^/]+?)(?:\.git)?\s*$/m);if(n&&n[1])return n[1]}catch{}return C.basename(e)}export{kr as AlreadyInstalledPanel,Dr as HostChoicePanel,gr as initCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./config-JVhBplSX.js";import"./api-CBukwv2I.js";import"./token-store-CuZEiQNg.js";import"./detect-installed-DpSaAeH-.js";import"./formatter-PBF-wEt1.js";import"./emit-5vELQfsB.js";import"./open-url-IjqD5f_n.js";import"./secrets-zGZxXoM0.js";import{AlreadyInstalledPanel as e,HostChoicePanel as t,initCommand as n}from"./init-
|
|
1
|
+
import"./config-JVhBplSX.js";import"./api-CBukwv2I.js";import"./token-store-CuZEiQNg.js";import"./detect-installed-DpSaAeH-.js";import"./formatter-PBF-wEt1.js";import"./emit-5vELQfsB.js";import"./open-url-IjqD5f_n.js";import"./secrets-zGZxXoM0.js";import{AlreadyInstalledPanel as e,HostChoicePanel as t,initCommand as n}from"./init-BPlqfuUi.js";import"./client-DNMRt-Hq.js";import"./snippet-CwowVrmh.js";import"./login-vzW-8q0w.js";import"./theme-DSRmbn9T.js";import"./panel-DbiZwGB3.js";import"./progress-row-BSv_Zm8f.js";import"./prompt-Dae2nnYJ.js";import"./keybar-BY1csJGI.js";import"./sparkline-B7VaYaxH.js";export{n as initCommand};
|
package/dist/wizard-bin.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import(`./init-
|
|
2
|
+
import(`./init-lFYuHty4.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)});
|