@zenovay/cli 1.0.9 → 1.0.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agency-cNkRWBOo.js → agency-Bqw3lfru.js} +1 -1
- package/dist/{ai-D8vpcxGe.js → ai-Ie8nmOez.js} +1 -1
- package/dist/{alerts-BQ0EMdBT.js → alerts-D1dZSKnQ.js} +1 -1
- package/dist/{analytical-screen-BvQa8oH6.js → analytical-screen-PTC239f2.js} +1 -1
- package/dist/{overview-CmTIumZy.js → analytics-DoueK6LO.js} +2 -2
- package/dist/{annotation-CZ2bEuyD.js → annotation-CjWuuRoC.js} +1 -1
- package/dist/{api-CdcB84ie.js → api-ZZ3ZdI85.js} +1 -1
- package/dist/{api-keys-CLol-4YC.js → api-keys-Dyz_ouly.js} +1 -1
- package/dist/{api-v2-D0mvt__4.js → api-v2-B4DVqn8P.js} +1 -1
- package/dist/api-v2-CHGtX_V0.js +1 -0
- package/dist/{audit-CFlSb0g5.js → audit-CJgQXuFE.js} +1 -1
- package/dist/{bar-NfgovYHe.js → bar-Cn5XyMtE.js} +1 -1
- package/dist/bin.js +6 -6
- package/dist/{chat-panel-D9IjovCR.js → chat-panel-uZc6n7uu.js} +1 -1
- package/dist/{commands-DVRYYbbn.js → commands-DSICboQu.js} +1 -1
- package/dist/{companies-Cpb3yv2Q.js → companies-C4ZM8A-H.js} +1 -1
- package/dist/{completions-XLznfo7H.js → completions-CTEH_uoA.js} +1 -1
- package/dist/csv-emit-CUlMqr7V.js +1 -0
- package/dist/csv-emit-DD55EvKo.js +1 -0
- package/dist/{data-table-BhKjjiOS.js → data-table-D0lOdFTc.js} +1 -1
- package/dist/{deploys-DZ0IR9Re.js → deploys-B6F5VwI9.js} +1 -1
- package/dist/{devices-C_NjBY89.js → devices-BA8DbYb7.js} +1 -1
- package/dist/{doctor-BsEuqZTb.js → doctor-6LRO9b_q.js} +1 -1
- package/dist/{domains-ByXV1O4R.js → domains-fLsPx2CL.js} +1 -1
- package/dist/{emit-D4YlMlzk.js → emit-DBYk96TD.js} +1 -1
- package/dist/{empty-state-D-krMX62.js → empty-state-DsznUe6o.js} +1 -1
- package/dist/ensure-latest-BDqPumYX.js +1 -0
- package/dist/{ensure-latest-YONQtPgH.js → ensure-latest-C78W6C6c.js} +3 -3
- package/dist/error-codes-CZuF4dBR.js +1 -0
- package/dist/{error-codes-ByhvHx2M.js → error-codes-D5D8gtFL.js} +1 -1
- package/dist/{errors-DPRcy7WT.js → errors-DEd4t7q3.js} +1 -1
- package/dist/{events-tail-DEdVkmT0.js → events-tail-Dxm3seuc.js} +1 -1
- package/dist/{export-DhSRfpg_.js → export-qN1Xzj5i.js} +1 -1
- package/dist/{funnel-Cb4-3RJB.js → funnel-eOjoFdXh.js} +1 -1
- package/dist/{geo-ReUNKl3F.js → geo-BZUdoF3v.js} +1 -1
- package/dist/{globe-DwaTDQns.js → globe-B5q14tgM.js} +1 -1
- package/dist/{goals-Ds0QZ4H6.js → goals-DyIHY-Br.js} +1 -1
- package/dist/{grid-CMwhs-Ms.js → grid-DyqUhBPG.js} +1 -1
- package/dist/health-CpZWNKXL.js +1 -0
- package/dist/{health-D6w7hF5q.js → health-DeAvwthB.js} +1 -1
- package/dist/{heatmaps-B-As729q.js → heatmaps-C43TFQRy.js} +1 -1
- package/dist/{home-DGYBSPWi.js → home-D9OXw760.js} +1 -1
- package/dist/init-BgOgQYOa.js +317 -0
- package/dist/init-_KB6R2u1.js +1 -0
- package/dist/{insights-BiqMftak.js → insights-BJOo7Ofg.js} +1 -1
- package/dist/{integrations-CCvt4xb_.js → integrations-DaxRIsTT.js} +1 -1
- package/dist/{journeys-CogDUObU.js → journeys-C2472JLI.js} +1 -1
- package/dist/{keybar-DO5OoZy9.js → keybar-BWZ9d4xa.js} +1 -1
- package/dist/{live-BNX4HBCf.js → live-D-cOZDb6.js} +1 -1
- package/dist/{login-DU1fY88U.js → login-BWCq8ufH.js} +1 -1
- package/dist/login-fLWED5iU.js +1 -0
- package/dist/{logout-BoUfEnN9.js → logout-CMMoQ-Tp.js} +1 -1
- package/dist/{metric-card-C4iqxdww.js → metric-card-2PwsVO7P.js} +1 -1
- package/dist/{notes-BrY4efpr.js → notes-V3k-1lRM.js} +1 -1
- package/dist/{pages-BYVz90uO.js → pages-CBZAM8kP.js} +1 -1
- package/dist/{panel-CTtQ2ue6.js → panel-B9_Bd2So.js} +1 -1
- package/dist/{plans-DT8hilXl.js → plans-CnqVNA2l.js} +1 -1
- package/dist/{profile-CDY3kFEq.js → profile-CQRjMolX.js} +1 -1
- package/dist/{progress-row-Afnt5Ng8.js → progress-row-DDyaTQK9.js} +1 -1
- package/dist/{projects-BdRZaLg8.js → projects-C8VdW246.js} +1 -1
- package/dist/{prompt-BXvg2B4R.js → prompt-CPA77m_S.js} +1 -1
- package/dist/{query-DLC0vi-K.js → query-Dqx_RIpm.js} +1 -1
- package/dist/{range-tabs-CH2cEXOf.js → range-tabs-CqatcGIF.js} +1 -1
- package/dist/{resolve-site-BTVBMF1C.js → resolve-site-DxrmRbGU.js} +1 -1
- package/dist/{retention-DQHXVSG0.js → retention-Cp2WEZsC.js} +1 -1
- package/dist/{revenue-CitFZ4DN.js → revenue-D0PlT1mM.js} +1 -1
- package/dist/secrets-QhhqERDn.js +1 -0
- package/dist/{self-test-BcCqMRQ9.js → self-test-ByYMUdA7.js} +3 -3
- package/dist/{sessions-dPZ32wpz.js → sessions-C45Ta9l-.js} +1 -1
- package/dist/{settings-DO8UOasX.js → settings-XuJphxKY.js} +1 -1
- package/dist/{share-BkvKZuPo.js → share-MIofWPaS.js} +1 -1
- package/dist/{site-switcher-BAoYWp18.js → site-switcher-cEi9WlfJ.js} +1 -1
- package/dist/{sources-lvpcvTTz.js → sources-DSuYx9jv.js} +1 -1
- package/dist/{stats-EeSDu70A.js → stats-CqqSpALA.js} +1 -1
- package/dist/{status-agent-BLIJc81G.js → status-agent-DXdQMIws.js} +1 -1
- package/dist/{team-Bw6dcpI2.js → team-Cp1DSMIM.js} +1 -1
- package/dist/{teams-cwzXaqBH.js → teams-BdJWKPse.js} +1 -1
- package/dist/{telemetry-CgyMy4hV.js → telemetry-B048vzdO.js} +1 -1
- package/dist/{telemetry-Bbh6Vtst.js → telemetry-BaEf884T.js} +1 -1
- package/dist/{themes-BC8U4Od4.js → themes-BpLMRqpK.js} +1 -1
- package/dist/{token-store-QTNSg4TT.js → token-store-DY6bMFE_.js} +1 -1
- package/dist/{tour-ChHRo89U.js → tour-Diao22fI.js} +1 -1
- package/dist/{update-CTxmcvNL.js → update-Avy2aliM.js} +1 -1
- package/dist/{uptime-BA8vRzJQ.js → uptime-S7c3W1rT.js} +1 -1
- package/dist/{usage-CkyXScnm.js → usage-BErw1PLD.js} +1 -1
- package/dist/{use-BW8rVPgW.js → use-D_sTLa2B.js} +1 -1
- package/dist/{visitors-mjvSIKkI.js → visitors-BiQ1TZ52.js} +1 -1
- package/dist/{vitals-D3sMQksQ.js → vitals-BYInEyx6.js} +1 -1
- package/dist/{webhooks-D1PNfhgJ.js → webhooks-BUo3dV1h.js} +1 -1
- package/dist/{webhooks-forward-B8nnKB4f.js → webhooks-forward-BQnkB3co.js} +1 -1
- package/dist/wizard-bin.js +1 -1
- package/dist/{ws-client-MoEdfqAO.js → ws-client-DSQQSnQw.js} +1 -1
- package/package.json +1 -1
- package/dist/analytics-S6AFt20R.js +0 -1
- package/dist/api-v2-Co0dWAP5.js +0 -1
- package/dist/csv-emit-B-5km-O-.js +0 -1
- package/dist/csv-emit-BiRGo6SK.js +0 -1
- package/dist/error-codes-BiKo9PGm.js +0 -1
- package/dist/health-DTR77eQW.js +0 -1
- package/dist/init-DWT0QTiL.js +0 -1
- package/dist/init-wIZnAQe8.js +0 -317
- package/dist/login-CDAP0iKS.js +0 -1
- package/dist/overview-L8jqiSuU.js +0 -1
- package/dist/secrets-c-NB_plk.js +0 -1
- /package/dist/{client-ntsEXSVC.js → client-DkVqZ_Bu.js} +0 -0
- /package/dist/{confirm-DS5wux0g.js → confirm-D1cXwC8I.js} +0 -0
- /package/dist/{examples-CsQBLv9W.js → examples-DikBW-H2.js} +0 -0
- /package/dist/{fmt-xxIPQJX-.js → fmt-iR2sYwsO.js} +0 -0
- /package/dist/{formatter-C4YSOKuq.js → formatter-DutfcQAc.js} +0 -0
- /package/dist/{keybar-deep-link-B4VJn2ko.js → keybar-deep-link-BE5wSyxu.js} +0 -0
- /package/dist/{open-url-BtI5aLgL.js → open-url-DHEOtfXN.js} +0 -0
- /package/dist/{secrets-ApB7yh2A.js → secrets-BGNbID-c.js} +0 -0
- /package/dist/{sparkline-CpoBjjlc.js → sparkline-8ucKVUV7.js} +0 -0
- /package/dist/{telemetry-BV-xvfdt.js → telemetry-DXc0eIRy.js} +0 -0
- /package/dist/{theme-Brz9wK0w.js → theme-DOR-SSzW.js} +0 -0
- /package/dist/{tier-DDIroQbc.js → tier-Bf7cBBa_.js} +0 -0
- /package/dist/{token-store-BvSCse1t.js → token-store-RBywEspd.js} +0 -0
- /package/dist/{ui-BTnLAro-.js → ui-jVbfDs35.js} +0 -0
- /package/dist/{use-fullscreen-ucSyZkjO.js → use-fullscreen-ChKQ108-.js} +0 -0
- /package/dist/{wrapper-Dl9i0Nh7.js → wrapper-aTy3IIek.js} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{configPath as e,readConfig as t}from"./config-JVhBplSX.js";import{fetchManifest as n}from"./check-D9G0N7NB.js";import{ApiClient as r}from"./api-
|
|
1
|
+
import{configPath as e,readConfig as t}from"./config-JVhBplSX.js";import{fetchManifest as n}from"./check-D9G0N7NB.js";import{ApiClient as r}from"./api-ZZ3ZdI85.js";import{readToken as i}from"./token-store-RBywEspd.js";import{isHeadless as a}from"./emit-DBYk96TD.js";import{Banner as o,Panel as s,usePanelWidth as c,useTheme as l}from"./panel-B9_Bd2So.js";import{spawnSync as u}from"node:child_process";import d from"node:path";import{existsSync as f,promises as p,statSync as m}from"node:fs";import h from"node:os";import{Box as g,Text as _,render as v}from"ink";import y from"react";const b=6*60*60*1e3;function x(){return d.join(h.homedir(),`.zenovay`,`update.json`)}async function S(){try{let e=await p.readFile(x(),`utf8`);return JSON.parse(e)}catch{return null}}async function C(e){let t=x();await p.mkdir(d.dirname(t),{recursive:!0,mode:448}),await p.writeFile(t,JSON.stringify(e,null,2))}async function w(){let e=await t();if(e.noUpdateCheck||process.env.ZENOVAY_NO_UPDATE_CHECK===`1`||process.env.CI===`true`)return null;let r=await S();if(r&&Date.now()-r.fetchedAt<b)return r;try{let t=await n({cliBase:e.cliBase}),i={manifest:t,fetchedAt:Date.now(),lastNoticeAt:r?.lastNoticeAt};return await C(i),i}catch{return r}}async function T(){try{await w()}catch{}process.exit(0)}process.env.ZENOVAY_UPDATE_WORKER_FORK===`1`&&T();function E(e){return e.includes(`/Cellar/`)||e.includes(`/opt/homebrew/`)||e.includes(`/usr/local/Cellar/`)?`brew`:e.includes(`.npm-global`)||e.includes(`node_modules/.bin`)||e.includes(`npm/bin`)?`npm-global`:e.endsWith(`/.local/bin/zenovay`)||e.endsWith(`\\.local\\bin\\zenovay.exe`)?`curl-installer`:e.includes(`/lib/node_modules/`)||e.includes(`\\nodejs\\`)?`npm-prefix`:`unknown`}function D(e){let t=process.platform===`win32`,n=t?`where`:`which`,r=t?[e]:[`-a`,e];try{let e=u(n,r,{encoding:`utf8`,timeout:3e3});if(e.status!==0||!e.stdout)return[];let t=e.stdout.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return[...new Set(t)]}catch{return[]}}function O(e){let t=process.platform===`win32`,n=t?`;`:`:`,r=(process.env.PATH??``).split(n).filter(Boolean),i=t?[`.exe`,`.cmd`,``]:[``],a=[];for(let t of r)for(let n of i){let r=d.join(t,e+n);if(f(r))try{let e=m(r);e.isFile()&&a.push(r)}catch{}}return[...new Set(a)]}function k(e=`zenovay`){let t=D(e);t.length===0&&(t=O(e));let n=t.map(e=>({path:e,kind:E(e)})),r=t[0]??null;return{paths:t,active:r,kinds:n}}function A(e,t){if(e.paths.length<2)return``;let n=[];n.push(`Multiple zenovay binaries detected on PATH:`);for(let r of e.kinds){let i=r.path===e.active,a=t&&r.path===t,o=[i&&`(first on PATH)`,a&&`(currently running)`].filter(Boolean).join(` `);n.push(` • ${r.path} [${r.kind}] ${o}`)}n.push(``),n.push(`Pick one and uninstall the others to avoid version drift:`);let r=new Set(e.kinds.map(e=>e.kind));return r.has(`npm-global`)&&n.push(` npm uninstall -g @zenovay/cli # remove the npm-installed one`),r.has(`brew`)&&n.push(` brew uninstall zenovay # remove the Homebrew-installed one`),r.has(`curl-installer`)&&n.push(` rm ~/.local/bin/zenovay # remove the curl-installer one`),n.join(`
|
|
2
2
|
`)}const j=2e3,M=5e3;async function N(e,t){let n=`${e}/mcp`,r=Date.now(),i=new AbortController,a=setTimeout(()=>i.abort(),j);try{let a=await t(n,{method:`GET`,signal:i.signal}),o=Date.now()-r;return a.ok?{name:`MCP server`,status:`pass`,detail:`${e}/mcp · ${o}ms`,latencyMs:o}:{name:`MCP server`,status:`fail`,detail:`HTTP ${a.status}`,latencyMs:o}}catch(e){return{name:`MCP server`,status:`fail`,detail:e.message}}finally{clearTimeout(a)}}async function P(){try{let t=await p.readFile(e(),`utf8`),n=JSON.parse(t),r=n.openaiApiKey;return typeof r==`string`&&r.trim().length>0?{name:`OpenAI key`,status:`pass`,detail:`configured`}:{name:`OpenAI key`,status:`warn`,detail:"not set (run `zenovay ai` to configure)"}}catch(e){return e.code===`ENOENT`?{name:`OpenAI key`,status:`warn`,detail:`no config file`}:{name:`OpenAI key`,status:`warn`,detail:`unreadable config`}}}async function F(){let e=h.homedir(),t=[d.join(e,`.zshrc`),d.join(e,`.bashrc`),d.join(e,`.config`,`fish`,`completions`,`zenovay.fish`)],n=[];for(let e of t)try{let t=await p.readFile(e,`utf8`);(/zenovay\s+(complet|--?complet)/i.test(t)||/_zenovay/.test(t)||/complete\s+-c\s+zenovay/.test(t))&&n.push(d.basename(e))}catch{}return n.length>0?{name:`Completions`,status:`pass`,detail:n.join(`, `)}:{name:`Completions`,status:`warn`,detail:"not installed (run `zenovay completions` after Wave 3)"}}async function I(e,t,n,r){if(!e||!t)return{name:`Events stream`,status:`skip`,detail:`not authenticated`};let i=new AbortController,a=setTimeout(()=>i.abort(),M),o=Date.now();try{let t=await e.openEventsStream(`probe`,i.signal),r=t.body?.getReader();if(r){let e=Promise.race([r.read().then(()=>`first`),new Promise(e=>setTimeout(()=>e(`timeout`),1500))]);await e;try{r.cancel()}catch{}}let a=Date.now()-o;return{name:`Events stream`,status:`pass`,detail:`${n}/v1/cli/events/tail · ${a}ms`,latencyMs:a}}catch(e){let t=e.message;return/40\d/.test(t)?{name:`Events stream`,status:`pass`,detail:`endpoint reachable (auth-gated)`}:{name:`Events stream`,status:`fail`,detail:t}}finally{clearTimeout(a)}}async function L(n){let a=n.fetchImpl??fetch,o=[],s=await t().catch(()=>null);o.push({name:`Binary`,status:`pass`,detail:`v${n.cliVersion} (${n.binaryPath})`});let c=k(`zenovay`);if(c.paths.length>=2){let e=c.kinds.map(e=>e.kind).join(` + `);o.push({name:`Install paths`,status:`warn`,detail:`${c.paths.length} binaries on PATH (${e}). Active: ${c.active}. Run \`zenovay doctor\` for cleanup.`})}else o.push({name:`Install paths`,status:`pass`,detail:c.active??`no zenovay on PATH`});o.push({name:`Config file`,status:s?`pass`:`warn`,detail:e()});let l=await i({strict:!1}).catch(()=>null);o.push({name:`Auth`,status:l?`pass`:`fail`,detail:l?`logged in${l.email?` as ${l.email}`:``}`:`not logged in`});let u=null;if(s)try{u=new r({config:s,cliVersion:n.cliVersion,token:l,fetchImpl:a});let e=await u.ping();o.push({name:`API connection`,status:`pass`,detail:`${s.apiBase.replace(/^https?:\/\//,``)} · ${e.latencyMs}ms`,latencyMs:e.latencyMs})}catch(e){o.push({name:`API connection`,status:`fail`,detail:`${e.message}`})}let d=await S().catch(()=>null);o.push({name:`Auto-update`,status:s?.noUpdateCheck?`warn`:`pass`,detail:s?.noUpdateCheck?`disabled`:d?`latest=${d.manifest.latest}`:`manifest not yet fetched`});let f=s?.apiBase??`https://api.zenovay.com`;return o.push(await N(f,a)),o.push(await P()),o.push(await F()),o.push(await I(u,!!l,f,a)),o}function R(e){return e.some(e=>e.status===`fail`)?1:0}async function z(e){let t=await L(e),n=R(t),r=n===0;return a({json:e.json})?(process.stdout.write(`${JSON.stringify({checks:t,passed:r})}\n`),n):new Promise(r=>{let{unmount:i}=v(y.createElement(V,{checks:t,cliVersion:e.cliVersion}),{exitOnCtrlC:!0});setImmediate(()=>{i(),r(n)})})}const B=({check:e})=>{let{theme:t}=l(),n=c()??80,r=Math.max(8,n-21);return y.createElement(g,{flexDirection:`row`},y.createElement(g,{flexShrink:0},y.createElement(_,{color:U(t,e.status)},H(e.status))),y.createElement(g,{width:19,marginLeft:1,flexShrink:0},y.createElement(_,{color:t.fg,wrap:`truncate`},e.name)),y.createElement(g,{width:r,flexShrink:0},y.createElement(_,{color:t.muted,wrap:`truncate`},e.detail)))},V=({checks:e,cliVersion:t})=>{let{theme:n}=l(),r=e.filter(e=>e.status===`fail`).length,i=e.filter(e=>e.status===`warn`).length,a=r>0?n.error:i>0?n.warn:n.success,c=r>0?`${r} failed${i>0?`, ${i} warning${i===1?``:`s`}`:``}`:i>0?`all healthy · ${i} warning${i===1?``:`s`}`:`all checks passed`,u=r>0?`err`:i>0?`warn`:`ok`;return y.createElement(g,{flexDirection:`column`},t?y.createElement(o,{version:t,subtitle:`health · self-diagnostic`,live:r===0}):null,y.createElement(s,{title:`Zenovay CLI health check`,state:u},e.map(e=>y.createElement(B,{key:e.name,check:e})),y.createElement(g,{marginTop:1},y.createElement(_,{color:a,bold:!0},H(r>0?`fail`:i>0?`warn`:`pass`),` `),y.createElement(_,{color:a},c))))};function H(e){return e===`pass`?`✔`:e===`warn`?`⚠`:e===`skip`?`∼`:`✗`}function U(e,t){return t===`pass`?e.success:t===`warn`?e.warn:t===`skip`?e.dim:e.error}export{V as HealthReport,k as detectInstallPaths,R as exitCodeFor,z as healthCommand,A as remediationHint,L as runHealthChecks};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-
|
|
1
|
+
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-ZZ3ZdI85.js";import{readToken as t}from"./token-store-RBywEspd.js";import{ApiV2Client as n}from"./api-v2-B4DVqn8P.js";import{requireTier as r}from"./tier-Bf7cBBa_.js";import"./formatter-DutfcQAc.js";import{emit$1 as i,isHeadless as a}from"./emit-DBYk96TD.js";import{openInBrowser as o}from"./open-url-DHEOtfXN.js";import"./theme-DOR-SSzW.js";import{Banner as s,Panel as c,useTheme as l}from"./panel-B9_Bd2So.js";import"./prompt-CPA77m_S.js";import{Keybar as u}from"./keybar-BWZ9d4xa.js";import{resolveSiteId as d}from"./resolve-site-DxrmRbGU.js";import{fmtDate as f,stripUrlPrefix as p}from"./fmt-iR2sYwsO.js";import{DataTable as m}from"./data-table-D0lOdFTc.js";import{EmptyState as h}from"./empty-state-DsznUe6o.js";import{deepLinkFor as g}from"./keybar-deep-link-BE5wSyxu.js";import{useFullscreen as _}from"./use-fullscreen-ChKQ108-.js";import{useSiteSwitcher as v}from"./site-switcher-cEi9WlfJ.js";import{Box as y,Text as b,render as x,useApp as S,useInput as C}from"ink";import w,{useEffect as T,useState as E}from"react";import D from"ink-spinner";function O(e,t){let n=Math.max(0,Math.round((t-e)/1e3));if(n<5)return`just now`;if(n<60)return`${n}s ago`;let r=Math.floor(n/60);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}async function k(o){let s=await e(),c=await t({strict:!1});if(!c)return process.stderr.write("Not logged in — run `zenovay login` first.\n"),2;let l=new n({config:s,cliVersion:o.cliVersion,token:c});try{await r(l,`pro`)}catch(e){return process.stderr.write(`${e.message}\n`),2}let u,f;try{({siteId:u,site:f}=await d(l,{explicit:o.siteId,headless:!!o.json,cliVersion:o.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let p=f?.url?f.url.replace(/^https?:\/\//,``).replace(/\/$/,``):f?.name??u;if(a(o)){let e=await l.getHeatmaps(u);return i({type:`heatmaps.snapshot`,data:e}),0}return new Promise(e=>{let{unmount:t}=x(w.createElement(A,{api:l,siteId:u,siteLabel:p,cliVersion:o.cliVersion,onExit:n=>{t(),e(n)}}))})}const A=({api:e,siteId:t,siteLabel:n,cliVersion:r,onExit:i})=>{_();let{exit:a}=S(),{theme:d}=l(),[x,k]=E(null),[A,j]=E(!0),[M,N]=E(null),[P,F]=E(0),[I,L]=E(!1),[R,z]=E(null),[B,V]=E(()=>Date.now()),[H,U]=E(t),[W,G]=E(n),K=v(e,H,e=>{U(e.id),G(e.url.replace(/^https?:\/\//,``).replace(/\/$/,``)),k(null)}),q=[{key:`r`,label:`refresh`},{key:`s`,label:`site`},{key:`o`,label:`browser`},{key:`q`,label:`quit`}];if(C((e,t)=>{if(K.open){(t.escape||e===`s`)&&K.close();return}if(e===`r`||e===`R`){F(e=>e+1);return}if(e===`s`){K.toggle();return}if(e===`o`||e===`O`){o(g(`heatmaps`,{siteId:H}));return}e===`q`&&(a(),i(0))}),T(()=>{let e=setInterval(()=>V(Date.now()),5e3);return()=>clearInterval(e)},[]),T(()=>{let t=!1;return x===null?j(!0):L(!0),(async()=>{try{let n=await e.getHeatmaps(H);if(t)return;k(n),j(!1),L(!1),z(Date.now())}catch(e){t||(N(e.message),j(!1),L(!1))}})(),()=>{t=!0}},[e,H,P]),A)return w.createElement(y,{flexDirection:`column`},w.createElement(s,{version:r,subtitle:`heatmaps · ${W}`,live:!1}),w.createElement(c,{title:`Loading`,state:`busy`},w.createElement(y,null,w.createElement(b,{color:d.accent},w.createElement(D,{type:`dots`})),w.createElement(b,null,` Fetching heatmaps…`))));if(M)return w.createElement(y,{flexDirection:`column`},w.createElement(s,{version:r,subtitle:`heatmaps · ${W}`,live:!1}),w.createElement(h,{reason:`error`,headline:`Couldn't load heatmaps`,hint:M}),w.createElement(u,{items:q,active:`r`}));if(!x||x.length===0)return w.createElement(y,{flexDirection:`column`},w.createElement(s,{version:r,subtitle:`heatmaps · ${W}`,live:!1}),w.createElement(h,{reason:`no-data`,headline:`No heatmaps yet`,hint:`Enable heatmaps in your site settings, press [s] to switch site, then re-run once a page has traffic.`}),K.overlay,w.createElement(u,{items:q,active:`r`}));let J=[{key:`url`,label:`page`,width:36,format:e=>p(String(e??``))},{key:`type`,label:`type`,width:10},{key:`captureCount`,label:`captures`,align:`right`,width:9},{key:`createdAt`,label:`first seen`,width:14,format:e=>f(e,`date`)}],Y=process.stdout.rows??40,X=Math.max(4,Y-14),Z=x.slice(0,X),Q=x.length-Z.length;return w.createElement(y,{flexDirection:`column`},w.createElement(s,{version:r,subtitle:`heatmaps · ${W}`,live:!0}),w.createElement(y,{marginTop:1},w.createElement(c,{title:`Heatmaps (${x.length})`},w.createElement(m,{columns:J,data:Z,zebra:!0}),Q>0?w.createElement(b,{color:d.dim},` +${Q} more · run with --json for all`):null)),w.createElement(y,{marginTop:1},w.createElement(b,{color:d.dim},I?`↻ refreshing…`:R===null?``:`↻ updated ${O(R,B)} · [r] refresh`)),K.overlay,w.createElement(u,{items:q,active:`r`}))};export{k as heatmapsCommand};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-
|
|
1
|
+
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-ZZ3ZdI85.js";import{readToken as t}from"./token-store-RBywEspd.js";import{ApiV2Client as n}from"./api-v2-B4DVqn8P.js";import"./formatter-DutfcQAc.js";import{isHeadless as r}from"./emit-DBYk96TD.js";import{openInBrowser as i}from"./open-url-DHEOtfXN.js";import"./theme-DOR-SSzW.js";import{Banner as a,Panel as o,useTheme as s}from"./panel-B9_Bd2So.js";import{Keybar as c}from"./keybar-BWZ9d4xa.js";import"./sparkline-8ucKVUV7.js";import{DataTable as l}from"./data-table-D0lOdFTc.js";import{EmptyState as u}from"./empty-state-DsznUe6o.js";import{tileWidths as d}from"./grid-DyqUhBPG.js";import{MetricCard as f}from"./metric-card-2PwsVO7P.js";import{deepLinkFor as p}from"./keybar-deep-link-BE5wSyxu.js";import{useFullscreen as m}from"./use-fullscreen-ChKQ108-.js";import{Box as h,Text as g,render as _,useApp as v,useInput as y}from"ink";import b,{useEffect as x,useState as S}from"react";import C from"ink-spinner";function w(e){if(!e)return`—`;let t=new Date(e);return Number.isNaN(t.getTime())?`—`:t.toISOString().slice(0,10)}function T(e,t){let n=Math.max(0,Math.round((t-e)/1e3));if(n<5)return`just now`;if(n<60)return`${n}s ago`;let r=Math.floor(n/60);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}async function E(e){let t=await e.me().catch(()=>null),n=t?.user.name?.trim()||t?.user.email||`you`,r=await e.getSites().catch(()=>[]),i=r.map(e=>({id:e.id,name:e.name,domain:e.url.replace(/^https?:\/\//,``).replace(/\/$/,``),lastActive:e.lastActiveAt??null})),a={visitors:0,pageviews:0,visitorsDelta:null,visitorsSeries:[],pageviewsSeries:[]},o=[0,0,0,0,0,0,0],s=[0,0,0,0,0,0,0],c=0,l=0,u=!1;if(r.length>0){let t=await Promise.all(r.map(t=>e.getStats(t.id,`30d`).catch(()=>null)));for(let e of t){let t=e?.daily??[];if(t.length===0)continue;let n=t.slice(-7);for(let e=0;e<n.length;e++){let t=7-n.length+e;o[t]+=n[e].visitors,s[t]+=n[e].pageviews,c+=n[e].visitors}if(t.length>=14){u=!0;let e=t.slice(-14,-7);for(let t of e)l+=t.visitors}}a.visitors=c,a.pageviews=s.reduce((e,t)=>e+t,0),a.visitorsSeries=o,a.pageviewsSeries=s,u&&l>0&&(a.visitorsDelta=(c-l)/l)}let d=r.length===0?``:r.length===1?i[0].domain:`all ${r.length} sites`;return{sites:i,weekly:a,weeklyScope:d,userLabel:n}}async function D(i){let a=await e(),o=await t({strict:!1});if(!o)return process.stderr.write("Not logged in — run `zenovay login` first.\n"),2;let s=new n({config:a,cliVersion:i.cliVersion,token:o});if(r(i))try{let e=await E(s);return process.stdout.write(JSON.stringify({sites:e.sites,weeklyScope:e.weeklyScope,weekly:{visitors:e.weekly.visitors,pageviews:e.weekly.pageviews,visitorsDelta:e.weekly.visitorsDelta}},null,2)+`
|
|
2
2
|
`),0}catch(e){return process.stderr.write(`✗ ${e.message}\n`),1}return new Promise(e=>{let{unmount:t}=_(b.createElement(O,{api:s,cliVersion:i.cliVersion,onExit:n=>{t(),e(n)}}))})}const O=({api:e,cliVersion:t,onExit:n})=>{m();let{exit:r}=v(),{theme:_}=s(),[D,O]=S(null),[k,A]=S(!0),[j,M]=S(null),[N,P]=S(!1),[F,I]=S(null),[L,R]=S(()=>Date.now()),[z,B]=S(0);x(()=>{let e=setInterval(()=>R(Date.now()),5e3),t=setInterval(()=>B(e=>e+1),3e4);return()=>{clearInterval(e),clearInterval(t)}},[]),y(e=>{if(e===`q`){r(),n(0);return}if(e===`r`||e===`R`){B(e=>e+1);return}if(e===`o`||e===`O`){i(p(`home`));return}}),x(()=>{let t=!1;return D===null?A(!0):P(!0),(async()=>{try{let n=await E(e);t||(O(n),A(!1),P(!1),I(Date.now()))}catch(e){t||(M(e.message),A(!1),P(!1))}})(),()=>{t=!0}},[e,z]);let V=`home · ${D?.userLabel??`…`}`,H=[{key:`r`,label:`refresh`},{key:`o`,label:`browser`},{key:`q`,label:`quit`}];if(k)return b.createElement(h,{flexDirection:`column`},b.createElement(a,{version:t,subtitle:V,live:!1}),b.createElement(o,{title:`Loading`,state:`busy`},b.createElement(h,null,b.createElement(g,{color:_.accent},b.createElement(C,{type:`dots`})),b.createElement(g,null,` Fetching your home dashboard…`))));if(j)return b.createElement(h,{flexDirection:`column`},b.createElement(a,{version:t,subtitle:V,live:!1}),b.createElement(u,{reason:`error`,headline:`Failed to load`,hint:j}),b.createElement(c,{items:H,active:`r`}));if(!D)return b.createElement(h,{flexDirection:`column`},b.createElement(a,{version:t,subtitle:V,live:!1}),b.createElement(u,{reason:`no-data`,headline:`No data`}),b.createElement(c,{items:H,active:`r`}));let U=process.stdout.columns??80,W=d(U,2,2),G=process.stdout.rows??40,K=Math.max(4,G-18),q=Math.max(3,Math.min(14,K)),J=[{key:`name`,label:`site`,width:24},{key:`domain`,label:`domain`,width:32},{key:`lastActive`,label:`last active`,width:12,format:e=>w(e)}],Y=D.weekly.visitors>0||D.weekly.pageviews>0,X=D.weeklyScope?`This week · ${D.weeklyScope}`:`This week`;return b.createElement(h,{flexDirection:`column`},b.createElement(a,{version:t,subtitle:V,live:Y}),b.createElement(h,{marginTop:1},b.createElement(g,{color:_.typography.label.color,dimColor:_.typography.label.dim},X.toUpperCase())),b.createElement(h,{flexDirection:`row`,width:U},b.createElement(h,{flexShrink:0},b.createElement(f,{title:`Visitors`,value:D.weekly.visitors,format:`number`,width:W[0],gap:2,series:D.weekly.visitorsSeries,delta:D.weekly.visitorsDelta??void 0})),b.createElement(h,{flexShrink:0},b.createElement(f,{title:`Pageviews`,value:D.weekly.pageviews,format:`number`,width:W[1],gap:2,series:D.weekly.pageviewsSeries}))),b.createElement(h,{marginTop:1},b.createElement(o,{title:`Your sites (${D.sites.length})`},D.sites.length===0?b.createElement(g,{color:_.muted},"No sites yet — run `zenovay init` to add one."):b.createElement(b.Fragment,null,b.createElement(l,{columns:J,data:D.sites.slice(0,q),zebra:!0}),D.sites.length>q?b.createElement(g,{color:_.dim},` +${D.sites.length-q} more`):null))),b.createElement(h,{marginTop:1},b.createElement(g,{color:_.dim},N?`↻ refreshing…`:F===null?``:`↻ updated ${T(F,L)} · [r] refresh`)),b.createElement(c,{items:H,active:`r`}))};export{D as homeCommand};
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
import{readConfig as e,updateConfig as t}from"./config-JVhBplSX.js";import{ApiClient as n,dashboardUrlForSite as r}from"./api-ZZ3ZdI85.js";import{readToken as i}from"./token-store-RBywEspd.js";import{emit$1 as a,isHeadless as o}from"./emit-DBYk96TD.js";import{openInBrowser as s}from"./open-url-DHEOtfXN.js";import{scrubSecrets as c}from"./secrets-BGNbID-c.js";import{parseSseStream as l}from"./client-DkVqZ_Bu.js";import{loginCommand as u,maybeInstallCompletions as d}from"./login-BWCq8ufH.js";import{Banner as f,Panel as p,useTheme as m}from"./panel-B9_Bd2So.js";import{DiffView as h,ProgressRow as g}from"./progress-row-DDyaTQK9.js";import{Select as _}from"./prompt-CPA77m_S.js";import{Keybar as v}from"./keybar-BWZ9d4xa.js";import{spark as y}from"./sparkline-8ucKVUV7.js";import b from"node:path";import{promises as x}from"node:fs";import{z as S}from"zod";import C from"node:os";import w from"node:crypto";import{ulid as T}from"ulid";import{Box as E,Text as D,render as ee,useApp as te,useInput as O}from"ink";import k from"node:fs/promises";import A,{useEffect as j,useRef as ne,useState as M}from"react";import{globby as N}from"globby";import P from"ink-spinner";import{applyPatch as re}from"diff";const ie=[`@zenovay/tracker`,`@zenovay/next`,`@zenovay/nuxt`,`@zenovay/svelte`,`@zenovay/astro`,`@zenovay/remix`,`@zenovay/node`],F=[`zenovay.config.ts`,`zenovay.config.js`,`zenovay.config.mjs`,`zenovay.config.json`],I=/<[Ss]cript\b[^>]*\bsrc\s*=\s*["'`]https:\/\/(?:api|cdn)\.zenovay\.com\/[^"'`]+["'`][^>]*>/gi,L=/["'`]https:\/\/(?:api|cdn)\.zenovay\.com\/[^"'`]*z\.js[^"'`]*["'`]/gi,ae=/["']?data-?[Ii]d["']?\s*[=:]\s*["'`](ZV_[A-Za-z0-9]+)["'`]/i,oe=/data-zenovay-site\s*[=:]\s*["'`]([^"'`]+)["'`]/i,se=/\binit\s*\(\s*['"`](ZV_[A-Za-z0-9]+)['"`]/g,ce=/<[Ss]cript\b[^>]*\bsrc\s*=\s*["'`][^"'`]*\/_z\/script\.js[^"'`]*["'`][^>]*>/gi,le=/\/_z\/script\.js[^"'`]*[?&]id=(ZV_[A-Za-z0-9]+)/i,ue=[{name:`PostHog`,patterns:[/posthog\.com\b/i,/posthog-js/,/window\.posthog/]},{name:`Plausible`,patterns:[/plausible\.io\/js/i,/window\.plausible/]},{name:`Google Analytics`,patterns:[/googletagmanager\.com\/gtag\/js/i,/www\.google-analytics\.com\/analytics\.js/i,/window\.gtag\b/]},{name:`Mixpanel`,patterns:[/cdn\.mxpnl\.com/i,/mixpanel-browser/]},{name:`Segment`,patterns:[/cdn\.segment\.com\/analytics\.js/i,/window\.analytics\b/]},{name:`Hotjar`,patterns:[/static\.hotjar\.com/i,/\(h,o,t,j,a,r\)/i]},{name:`Amplitude`,patterns:[/cdn\.amplitude\.com/i,/amplitude\.getInstance/]},{name:`Heap`,patterns:[/cdn\.heapanalytics\.com/i]},{name:`FullStory`,patterns:[/fullstory\.com\/s\/fs\.js/i,/window\.FS\.identify/]}];async function R(e,t){let n={zenovayInstalled:!1,correctTrackingCode:!1,foundTrackingCodes:[],zenovayFiles:[],competitors:[],summary:``,recommendation:`fresh-install`};try{let t=await x.readFile(b.join(e,`package.json`),`utf8`),r=JSON.parse(t),i={...r.dependencies,...r.devDependencies};for(let e of ie)if(e in i){n.zenovayInstalled=!0,n.packageMarker=e;break}}catch{}for(let t of F)try{await x.access(b.join(e,t)),n.zenovayInstalled=!0,n.configFile=t;break}catch{}let r=await N([`**/*.{html,htm,tsx,jsx,vue,svelte,astro,ts,js,mjs}`,`!node_modules/**`,`!.git/**`,`!dist/**`,`!.next/**`,`!.nuxt/**`,`!build/**`,`!.output/**`],{cwd:e,gitignore:!0,deep:4,absolute:!0}).catch(()=>[]),i=new Map,a=new Set;for(let t of r.slice(0,300)){let r;try{r=await x.readFile(t,`utf8`)}catch{continue}let o=b.relative(e,t);I.lastIndex=0,L.lastIndex=0,ce.lastIndex=0;let s=r.match(I),c=r.match(L),l=r.match(ce),u=(s?.length??0)+(c?.length??0)+(l?.length??0);if(u>0){n.zenovayInstalled=!0;let e=(s?.[0]??c?.[0]??l?.[0]??``).slice(0,200),t=r.match(ae)??r.match(oe)??r.match(le),i=t?.[1]??null;i&&a.add(i),n.zenovayFiles.push({file:o,currentTrackingCode:i,scriptTagCount:u,matchSample:e})}if(u===0&&/\.[jt]sx?$/.test(t)){se.lastIndex=0;let e;for(;(e=se.exec(r))!==null;){let t=e[1];a.add(t),n.zenovayInstalled=!0,n.zenovayFiles.push({file:o,currentTrackingCode:t,scriptTagCount:0,matchSample:e[0].slice(0,80)})}}for(let e of ue)if(e.patterns.some(e=>e.test(r))){let t=i.get(e.name)??new Set;t.add(o),i.set(e.name,t)}}if(n.foundTrackingCodes=Array.from(a),n.competitors=Array.from(i.entries()).map(([e,t])=>({name:e,files:Array.from(t).slice(0,5)})),n.zenovayInstalled)if(n.foundTrackingCodes.length>0){let e=n.foundTrackingCodes.every(e=>e===t);n.correctTrackingCode=e,n.recommendation=e?`no-op`:`update-tracking-code`}else n.correctTrackingCode=!1,n.recommendation=`no-op`;else n.competitors.length>0?n.recommendation=`fresh-install-alongside-competitor`:n.recommendation=`fresh-install`;return n.summary=z(n,t),n}function z(e,t){let n=[];return e.zenovayInstalled?e.foundTrackingCodes.length===0?n.push(`Zenovay package or config detected but no <script> tag found.`):e.correctTrackingCode?n.push(`Zenovay tracker present in ${e.zenovayFiles.length} file(s) with correct ID ${t}.`):n.push(`Zenovay tracker present in ${e.zenovayFiles.length} file(s), but with mismatching ID(s): ${e.foundTrackingCodes.join(`, `)} (target: ${t}).`):n.push(`No Zenovay tracker found.`),e.competitors.length>0&&n.push(`Competitor tracker(s) present (DO NOT modify): ${e.competitors.map(e=>e.name).join(`, `)}.`),n.join(` `)}async function de(e){let t=await R(e,``);return{installed:t.zenovayInstalled,reasons:t.summary?[t.summary]:[],packageMarker:t.packageMarker,configFile:t.configFile,scriptFile:t.zenovayFiles[0]?.file}}const fe=[/^package\.json$/,/^package-lock\.json$/,/^pnpm-lock\.yaml$/,/^yarn\.lock$/,/^bun\.lock$/,/^tsconfig.*\.json$/,/^(next|nuxt|vite|astro|remix|svelte|tailwind|postcss)\.config\.(ts|mts|cts|js|mjs|cjs)$/,/^app\/.*\.(tsx|ts|jsx|js|svelte|astro|vue)$/,/^pages\/.*\.(tsx|ts|jsx|js)$/,/^src\/app\/.*\.(tsx|ts|jsx|js)$/,/^src\/pages\/.*\.(tsx|ts|jsx|js)$/,/^src\/components\/.*\.(astro|svelte|vue|tsx|ts|jsx|js)$/,/^src\/(root|app|entry-server|entry-client)\.(tsx|ts|jsx|js)$/,/^gatsby-(ssr|browser|config)\.(js|ts|mjs)$/,/\.html?$/,/^src\/main\.(tsx|ts|jsx|js)$/,/^src\/App\.(tsx|ts|jsx|js|svelte|vue)$/,/^src\/routes\/\+layout\.(svelte|ts|js)$/,/^src\/routes\/root\..*$/,/^src\/layouts\/.*\.(astro|svelte|vue)$/,/^\.env\.example$/,/^README\.md$/,/^\.gitignore$/,/^nuxt\.config\.(ts|js|mjs)$/,/^plugins\/.*\.(ts|js)$/],pe=[/(^|\/)\.env($|\.(?!example$)[^/]+$)/,/(^|\/)\.git(\/|$)/,/(^|\/)node_modules\//,/(^|\/)\.ssh\//,/(^|\/)\.aws\//,/\.pem$/,/\.key$/,/(^|\/)id_rsa($|\.)/,/(^|\/)\.npmrc$/,/(^|\/)credentials(\.|$)/],B=256*1024,me=20,V=20,H=20;var U=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`SandboxError`}};const he=/<script[^>]*src\s*=\s*["'](?:https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+|[^"']*\/_z\/script\.js[^"']*)["'][^>]*>\s*<\/script>/i,ge=[{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 _e=class{sessionId;cwd;cwdReal;undoRoot;readCount=0;writeCount=0;roundCount=0;writtenPathsSet=new Set;constructor(e){this.sessionId=e.sessionId??T(),this.cwd=e.cwd,this.cwdReal=x.realpath(e.cwd),this.undoRoot=e.undoRoot??b.join(C.homedir(),`.zenovay`,`undo`)}incrementRound(){if(this.roundCount++,this.roundCount>H)throw new U(`round-cap`,`Tool-call recursion cap (${H}) exceeded.`)}stats(){return{sessionId:this.sessionId,reads:this.readCount,writes:this.writeCount,rounds:this.roundCount,writtenPaths:[...this.writtenPathsSet]}}async resolveForRead(e){return this.resolveSafe(e,`read`)}async resolveForWrite(e){return this.resolveSafe(e,`write`)}async resolveSafe(e,t){if(typeof e!=`string`||e.length===0)throw new U(`escape`,`Path must be a non-empty string.`);if(e.includes(`\0`))throw new U(`escape`,`Null byte in path.`);if(/^\\\\[?.]\\/.test(e)||/^\\\\[A-Za-z0-9]/.test(e))throw new U(`escape`,`Windows special path prefix: ${e}`);if(/%/.test(e))try{let t=decodeURIComponent(e);if(/%[0-9A-Fa-f]{2}/.test(t))throw new U(`escape`,`Double-encoded path: ${e}`);e=t}catch(t){throw t instanceof U?t:new U(`escape`,`Malformed percent-encoding: ${e}`)}if(e.includes(`\0`))throw new U(`escape`,`Null byte in decoded path.`);if(e.includes(`\\`))throw new U(`escape`,`Backslash in path (Windows-style separator not accepted): ${e}`);let n=await this.cwdReal,r=b.isAbsolute(e)?e:b.join(n,e),i=b.normalize(r),a=i;try{a=await x.realpath(i)}catch(e){if(e.code!==`ENOENT`)throw new U(`escape`,`realpath failed: ${e.message}`);let t=b.dirname(i);try{let e=await x.realpath(t);a=b.join(e,b.basename(i))}catch{}}if(!this.isWithin(a,n))throw new U(`escape`,`Path escapes cwd: ${e}`);let o=b.relative(n,a),s=o.toLowerCase();for(let e of pe)if(e.test(o)||e.test(s)){if(t===`read`&&/(^|\/)node_modules\//i.test(o))continue;throw new U(`blocklisted`,`Path is on the hard blocklist: ${o}`)}if(t===`write`){let e=fe.some(e=>e.test(o));if(!e&&!/^\.env(\.local)?$/.test(o)&&!/^\.claude\//.test(o)&&!/^\.cursor\//.test(o))throw new U(`not-allowlisted`,`Write path not on allowlist: ${o}`)}return a}isWithin(e,t){let n=b.relative(t,e);return!n.startsWith(`..`)&&!b.isAbsolute(n)}async safeRead(e){if(this.readCount>=me)throw new U(`read-cap`,`Read cap (${me}) reached.`);let t=await this.resolveForRead(e),n=await x.stat(t);if(n.size>B)throw new U(`too-large`,`File exceeds ${B}B: ${e} (${n.size}B)`);let r=await x.readFile(t),i=r.subarray(0,Math.min(r.length,8192));if(i.includes(0))throw new U(`binary-rejected`,`Binary content in ${e}.`);return this.readCount++,r.toString(`utf8`)}async safeWrite(e,t){if(this.writeCount>=V)throw new U(`write-cap`,`Write cap (${V}) reached.`);if(t.length>B)throw new U(`too-large`,`Write exceeds ${B}B: ${e}`);let n=await this.resolveForWrite(e),r=await x.readFile(n,`utf8`).catch(e=>{if(e.code===`ENOENT`)return null;throw e});if(r!==null){if(he.test(r)&&!he.test(t))throw new U(`destructive-tracker-removal`,`Refusing to write ${e}: existing Zenovay tracker tag would be removed. If you want to change the data-id, use patch_file to swap the attribute value instead of overwriting the file.`);for(let{name:n,re:i}of ge)if(i.test(r)&&!i.test(t))throw new U(`destructive-competitor-removal`,`Refusing to write ${e}: existing ${n} tracker would be removed. Zenovay installs alongside competitors — never replace them.`)}let i=await this.journalBackup(n);await x.mkdir(b.dirname(n),{recursive:!0}),await x.writeFile(n,t,`utf8`),this.writeCount++;let a=await this.cwdReal;return this.writtenPathsSet.add(b.relative(a,n)),{backupPath:i}}async journalBackup(e){let t=await x.readFile(e).catch(e=>{if(e.code===`ENOENT`)return null;throw e}),n=b.join(this.undoRoot,this.sessionId);await x.mkdir(n,{recursive:!0,mode:448});let r=w.createHash(`sha256`).update(e).digest(`hex`).slice(0,16),i=b.join(n,`${r}.bak`),a=b.join(n,`manifest.jsonl`);t&&await x.writeFile(i,t,{mode:384});let o=JSON.stringify({abs:e,backupPath:t?i:null,ts:Date.now()});return await x.appendFile(a,o+`
|
|
2
|
+
`,{mode:384}),t?i:null}static wrapForModel(e,t){let n=w.createHash(`sha256`).update(t).digest(`hex`).slice(0,16),r=t.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`);return`<FILE path="${e}" sha256="${n}">\n${r}\n</FILE>`}static scrubSecrets(e){return c(e)}};async function ve(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 ye(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`src/index.html`,r=`<script defer\n data-id="${t}"\n data-allow-localhost="true"\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 be={id:`angular`,displayName:`Angular`,detect:ve,files:[{path:`src/index.html`,kind:`mutate`,required:!0}],envVarName:`NG_ZENOVAY_SITE`,buildSnippets:ye},xe=[`astro.config.ts`,`astro.config.mjs`,`astro.config.js`];async function Se(e){for(let t of xe)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 Ce(e){let t=e.trackingCode??e.siteId??``,n=`<script defer data-id="${t}" data-allow-localhost="true" src="https://api.zenovay.com/z.js" is:inline></script>`;return[{targetPath:`src/layouts/Layout.astro`,anchorKind:`head-tag`,code:n,description:`Inject the Zenovay tracker inside <head> of the primary layout.`},{targetPath:`src/layouts/BaseHead.astro`,anchorKind:`head-tag`,code:n,description:"Fallback target when the project uses a dedicated `BaseHead.astro`."}]}const we={id:`astro`,displayName:`Astro`,detect:Se,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:Ce};async function Te(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 Ee(e){return await Te(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 De(e){let t=e.trackingCode??e.siteId??``,n=`const React = require('react');
|
|
3
|
+
|
|
4
|
+
exports.onRenderBody = ({ setHeadComponents }) => {
|
|
5
|
+
setHeadComponents([
|
|
6
|
+
React.createElement('script', {
|
|
7
|
+
key: 'zenovay-tracker',
|
|
8
|
+
defer: true,
|
|
9
|
+
'data-id': '${t}',
|
|
10
|
+
'data-allow-localhost': 'true',
|
|
11
|
+
src: 'https://api.zenovay.com/z.js',
|
|
12
|
+
}),
|
|
13
|
+
]);
|
|
14
|
+
};
|
|
15
|
+
`;return[{targetPath:`gatsby-ssr.js`,anchorKind:`replace-file`,code:n,description:`Add the Zenovay tracker via Gatsby SSR onRenderBody → setHeadComponents.`}]}const Oe={id:`gatsby`,displayName:`Gatsby`,detect:Ee,files:[{path:`gatsby-ssr.js`,kind:`create`,required:!0}],envVarName:`GATSBY_ZENOVAY_SITE`,buildSnippets:De},ke=[`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 Ae(e){for(let t of ke)if(await e.exists(t))return t;return null}async function je(e){let t=await e.readFile(`package.json`);if(!t)return!1;try{let e=JSON.parse(t);return!!(e.dependencies?.next??e.devDependencies?.next)}catch{return!1}}async function Me(e){let t=await je(e),n=await e.exists(`app`)||await e.exists(`src/app`),r=await Ae(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 Ne(e,t=`script`){let n=e.targetPath||`app/layout.tsx`,r=e.trackingCode??e.siteId??``;return t===`npm`?Fe(n,r):Pe(n,r)}function Pe(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
|
+
defer
|
|
17
|
+
data-id="${t}"
|
|
18
|
+
data-allow-localhost="true"
|
|
19
|
+
src="https://api.zenovay.com/z.js"
|
|
20
|
+
strategy="afterInteractive"
|
|
21
|
+
/>
|
|
22
|
+
{children}`,description:`Add the Zenovay tracker <Script> next to children in the root layout.`}]}function Fe(e,t){return[{targetPath:`components/zenovay-bootstrap.tsx`,anchorKind:`replace-file`,code:`'use client';
|
|
23
|
+
|
|
24
|
+
import { useEffect } from 'react';
|
|
25
|
+
import { init } from '@zenovay/tracker';
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Mounts the Zenovay tracker exactly once on the client. Equivalent to the
|
|
29
|
+
* canonical <script src="https://api.zenovay.com/z.js"> tag — init() injects
|
|
30
|
+
* the same loader internally.
|
|
31
|
+
*/
|
|
32
|
+
export function ZenovayBootstrap() {
|
|
33
|
+
useEffect(() => {
|
|
34
|
+
init('${t}', { allowLocalhost: true });
|
|
35
|
+
}, []);
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
`,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 />
|
|
39
|
+
{children}`,description:`Render the Zenovay tracker bootstrap alongside children in the root layout.`}]}const Ie={id:`next-app-router`,displayName:`Next.js (App Router)`,detect:Me,files:[{path:`app/layout.tsx`,kind:`mutate`,required:!0}],envVarName:`NEXT_PUBLIC_ZENOVAY_SITE`,packageDeps:[`@zenovay/tracker`],supportsNpmMode:!0,buildSnippets:Ne},Le=[`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 Re(e){for(let t of Le)if(await e.exists(t))return t;return null}async function ze(e){let t=await e.readFile(`package.json`);if(!t)return!1;try{let e=JSON.parse(t);return!!(e.dependencies?.next??e.devDependencies?.next)}catch{return!1}}async function Be(e){let t=await ze(e);if(!t)return{matched:!1,confidence:0,reason:"package.json does not list `next` as a dependency."};let n=await Re(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 Ve(e){let t=`pages/_app.tsx`,n=e.trackingCode??e.siteId??``,r=`import type { AppProps } from 'next/app';
|
|
40
|
+
import Script from 'next/script';
|
|
41
|
+
|
|
42
|
+
export default function App({ Component, pageProps }: AppProps) {
|
|
43
|
+
return (
|
|
44
|
+
<>
|
|
45
|
+
<Script
|
|
46
|
+
defer
|
|
47
|
+
data-id="${n}"
|
|
48
|
+
data-allow-localhost="true"
|
|
49
|
+
src="https://api.zenovay.com/z.js"
|
|
50
|
+
strategy="afterInteractive"
|
|
51
|
+
/>
|
|
52
|
+
<Component {...pageProps} />
|
|
53
|
+
</>
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
`;return[{targetPath:t,anchorKind:`after-imports`,code:`import Script from 'next/script';`,description:"Import next/script in `_app`."},{targetPath:t,anchorKind:`wrap-children`,code:`<><Script defer data-id="${n}" data-allow-localhost="true" src="https://api.zenovay.com/z.js" strategy="afterInteractive" /><Component {...pageProps} /></>`,description:`Render the Zenovay tracker alongside the page component.`},{targetPath:t,anchorKind:`replace-file`,code:r,description:"Full replacement when `_app` does not exist yet."}]}const He={id:`next-pages-router`,displayName:`Next.js (Pages Router)`,detect:Be,files:[{path:`pages/_app.tsx`,kind:`mutate`,required:!0}],envVarName:`NEXT_PUBLIC_ZENOVAY_SITE`,buildSnippets:Ve},Ue=S.object({modules:S.array(S.string()).optional(),runtimeConfig:S.object({public:S.record(S.string(),S.unknown()).optional()}).optional()}).passthrough();async function We(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json found.`};try{let e=JSON.parse(t),n=!!(e.dependencies?.nuxt??e.devDependencies?.nuxt??e.dependencies?.nuxt3??e.devDependencies?.nuxt3);if(n)return{matched:!0,confidence:.95,reason:"Detected Nuxt via `nuxt` / `nuxt3` dependency."}}catch{}let n=await e.exists(`nuxt.config.ts`)||await e.exists(`nuxt.config.js`)||await e.exists(`nuxt.config.mjs`);return n?{matched:!0,confidence:.6,reason:"Found `nuxt.config.*` but no explicit dependency listing."}:{matched:!1,confidence:0,reason:`No Nuxt dependency or config detected.`}}function Ge(e){let t=e.trackingCode??e.siteId??``,n=` app: {
|
|
57
|
+
head: {
|
|
58
|
+
script: [
|
|
59
|
+
{
|
|
60
|
+
defer: true,
|
|
61
|
+
src: 'https://api.zenovay.com/z.js',
|
|
62
|
+
'data-id': '${t}',
|
|
63
|
+
'data-allow-localhost': 'true',
|
|
64
|
+
},
|
|
65
|
+
],
|
|
66
|
+
},
|
|
67
|
+
},`;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 Ke={id:`nuxt`,displayName:`Nuxt`,detect:We,files:[{path:`nuxt.config.ts`,kind:`mutate`,required:!0}],envVarName:`NUXT_PUBLIC_ZENOVAY_SITE`,buildSnippets:Ge},qe=[`index.html`,`public/index.html`,`dist/index.html`];async function Je(e){for(let t of qe)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 Ye(e){let t=e.siteId??``,n=`<script defer\n data-id="${t}"\n data-allow-localhost="true"\n src="https://api.zenovay.com/z.js">\n</script>`;return[{targetPath:`index.html`,anchorKind:`head-tag`,code:n,description:`Inject the Zenovay tracker inside <head>. Repeat for every HTML file that contains a <head>.`}]}const Xe={id:`plain-html`,displayName:`Plain HTML`,detect:Je,files:[{path:`index.html`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:Ye};async function Ze(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json.`};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
|
|
68
|
+
defer
|
|
69
|
+
data-id="${t}"
|
|
70
|
+
data-allow-localhost="true"
|
|
71
|
+
src="https://api.zenovay.com/z.js"
|
|
72
|
+
/>`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Add the Zenovay tracker into the <head> of the Qwik root document.`}]}const $e={id:`qwik`,displayName:`Qwik`,detect:Ze,files:[{path:`src/root.tsx`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:Qe};async function et(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 tt(e){let t=e.trackingCode??e.siteId??``;return[{targetPath:`app/root.tsx`,anchorKind:`head-tag`,code:`<script defer data-id="${t}" data-allow-localhost="true" src="https://api.zenovay.com/z.js"></script>`,description:`Inline the Zenovay tracker <script> inside the document <head>.`}]}const nt={id:`remix`,displayName:`Remix`,detect:et,files:[{path:`app/root.tsx`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:tt};async function rt(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 it(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`src/entry-server.tsx`,r=`<script
|
|
73
|
+
defer
|
|
74
|
+
data-id="${t}"
|
|
75
|
+
data-allow-localhost="true"
|
|
76
|
+
src="https://api.zenovay.com/z.js"
|
|
77
|
+
/>`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Add the Zenovay tracker into the document <head> rendered by SolidStart entry-server.`}]}const at={id:`solid-start`,displayName:`SolidStart`,detect:rt,files:[{path:`src/entry-server.tsx`,kind:`mutate`,required:!0}],envVarName:`VITE_ZENOVAY_SITE`,buildSnippets:it};async function ot(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 st(e){let t=e.trackingCode??e.siteId??``,n=`<svelte:head>
|
|
78
|
+
<script defer data-id="${t}" data-allow-localhost="true" src="https://api.zenovay.com/z.js"></script>
|
|
79
|
+
</svelte:head>
|
|
80
|
+
|
|
81
|
+
<slot />
|
|
82
|
+
`;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 ct={id:`sveltekit`,displayName:`SvelteKit`,detect:ot,files:[{path:`src/routes/+layout.svelte`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:st},lt=[`next`,`nuxt`,`nuxt3`,`@sveltejs/kit`,`astro`,`@remix-run/react`,`@builder.io/qwik-city`,`@builder.io/qwik`,`@solidjs/start`,`solid-start`,`@angular/core`,`gatsby`],ut=[`index.html`,`public/index.html`];async function dt(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 ft(e){for(let t of ut)if(await e.exists(t))return t;return null}async function pt(e){let t=await dt(e);if(lt.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 ft(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 mt(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`index.html`,r=`<script defer\n data-id="${t}"\n data-allow-localhost="true"\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 ht={id:`vite`,displayName:`Vite`,detect:pt,files:[{path:`index.html`,kind:`mutate`,required:!0}],envVarName:`VITE_ZENOVAY_SITE`,buildSnippets:mt},gt=[Ie,He,Ke,ct,we,nt,Oe,be,at,$e,ht,Xe];async function _t(e){let t=[];for(let n of gt){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 vt(e){let t=t=>b.resolve(e,t);return{cwd:e,async readFile(e){try{return await x.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 x.access(t(e)),!0}catch{return!1}},async glob(t){return N(t,{cwd:e,dot:!1,gitignore:!0,onlyFiles:!0,followSymbolicLinks:!1})}}}async function yt(e,t){let n=vt(e),{adapter:r,ranked:i}=await _t(n),a=i[0];return r&&a&&a.result.confidence>=.7?r:t?t.pickInteractively(i):r}function bt(e,t){let n=/[\s"'#=]/.test(t)||t===``,r=n?`"${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:t;return`${e}=${r}`}function xt(e){let t=new Set;for(let n of e.split(/\r?\n/)){let e=n.trim();if(!e||e.startsWith(`#`))continue;let r=e.indexOf(`=`);if(r<=0)continue;let i=e.slice(0,r).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(i)&&t.add(i)}return t}async function W(e,t,n={}){let r=n.filename??`.env.local`,i=b.resolve(e,r),a=``,o=!0;try{a=await x.readFile(i,`utf8`)}catch(e){if(e.code===`ENOENT`)o=!1;else throw e}let s=o?xt(a):new Set,c=[],l=[],u=[];for(let[e,n]of Object.entries(t)){if(s.has(e)){l.push(e);continue}u.push(bt(e,n)),c.push(e)}if(c.length===0)return{created:!1,existing:o,addedKeys:c,skippedKeys:l};let d=`# Added by Zenovay CLI`,f;if(o){let e=a.length>0&&!a.endsWith(`
|
|
83
|
+
`);f=a+(e?`
|
|
84
|
+
`:``)+`
|
|
85
|
+
`+d+`
|
|
86
|
+
`+u.join(`
|
|
87
|
+
`)+`
|
|
88
|
+
`}else f=d+`
|
|
89
|
+
`+u.join(`
|
|
90
|
+
`)+`
|
|
91
|
+
`;if(o)await x.writeFile(i,f,`utf8`);else{let e=await x.open(i,`w`,384);try{await e.writeFile(f,`utf8`)}finally{await e.close()}}return{created:!o,existing:o,addedKeys:c,skippedKeys:l}}const St=`https://api.zenovay.com/mcp`,Ct=S.object({url:S.string().url(),headers:S.record(S.string(),S.string()).optional()}).passthrough(),wt=S.object({mcpServers:S.record(S.string(),Ct).optional()}).passthrough();function Tt(e){return e.HOME??e.USERPROFILE??C.homedir()}function Et(e){return e.APPDATA??null}function Dt(e,t){let n=Tt(t),r=Et(t),i=[];return i.push({id:`claude-code`,displayName:`Claude Code`,configPath:b.join(n,`.claude.json`),serversKey:`mcpServers`,includeType:!0}),i.push({id:`cursor`,displayName:`Cursor`,configPath:b.join(n,`.cursor`,`mcp.json`),serversKey:`mcpServers`,includeType:!1}),e===`win32`&&r&&i.push({id:`cursor`,displayName:`Cursor (AppData)`,configPath:b.join(r,`Cursor`,`User`,`globalStorage`,`cursor.mcp`,`mcp.json`),serversKey:`mcpServers`,includeType:!1}),e===`darwin`?i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:b.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:b.join(r,`Claude`,`claude_desktop_config.json`),serversKey:`mcpServers`,includeType:!0}):i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:b.join(n,`.config`,`Claude`,`claude_desktop_config.json`),serversKey:`mcpServers`,includeType:!0}),i.push({id:`vscode`,displayName:`VS Code`,configPath:b.join(n,`.vscode`,`mcp.json`),serversKey:`servers`,includeType:!0}),i}async function Ot(e){try{return await x.access(e),!0}catch{return!1}}async function kt(e){try{let t=await x.readFile(e,`utf8`);if(t.trim().length===0)return{};let n=JSON.parse(t),r=wt.safeParse(n);return r.success?r.data:n&&typeof n==`object`?n:{}}catch{return{}}}function At(e){return e?{type:`http`,url:St}:{url:St}}function jt(e){return!e||typeof e!=`object`?!1:Object.values(e).some(e=>e&&typeof e==`object`&&e.url===St)}async function G(e){let t=e.env??process.env,n=e.platform??process.platform,r=new Set(e.skip??[]),i=[],a=[],o=[],s=new Set;for(let e of Dt(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 Ot(e.configPath);if(!t){a.push(e.displayName);continue}let n=await kt(e.configPath),r=n[e.serversKey];if(jt(r)){i.push(e.displayName);continue}let o=`${e.configPath}.bak`;await x.copyFile(e.configPath,o);let s=r&&typeof r==`object`?r:{},c={...n,[e.serversKey]:{...s,zenovay:At(e.includeType)}};await x.mkdir(b.dirname(e.configPath),{recursive:!0}),await x.writeFile(e.configPath,JSON.stringify(c,null,2)+`
|
|
92
|
+
`,`utf8`),i.push(e.displayName)}catch(t){o.push({client:e.displayName,message:t instanceof Error?t.message:String(t)})}}return{installed:i,skipped:a,errors:o}}async function Mt(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 Nt=S.object({path:S.string().min(1)}),Pt=S.object({path:S.string().min(1),content:S.string(),reason:S.string().min(1)}),Ft=S.object({path:S.string().min(1),patch:S.string().min(1),reason:S.string().min(1)}),It=S.object({}),Lt=S.object({question:S.string().min(1),choices:S.array(S.string()).optional()});async function Rt(e,t){let n=Nt.safeParse(t);if(!n.success)return{ok:!1,content:null,error:`invalid_args`};try{let t=await e.safeRead(n.data.path),r=_e.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:_e.wrapForModel(n.data.path,a)}}catch(e){return{ok:!1,content:null,error:e.message}}}async function zt(e,t,n){let r=Pt.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 Bt(e,t,n){let r=Ft.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=re(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.`}:zt(e,{path:i,content:c,reason:o},n)}async function Vt(e){try{let t=vt(e),{adapter:n,ranked:r}=await _t(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 Ht(e,t){let n=Lt.safeParse(t);if(!n.success)return{ok:!1,content:null,error:`invalid_args`};try{let t=await e.ask(n.data);return{ok:!0,content:{answer:t}}}catch(e){return{ok:!1,content:null,error:e.message}}}async function Ut(e){let{api:t,sandbox:n,approval:r,prompter:i,handlers:a}=e,o=[...e.initialMessages],s=``,c=0;for(;c<H;){n.incrementRound(),c++;let u=await t.openAiStream(`install`,{messages:o,cwd_fingerprint:n.sessionId,diagnosis:e.diagnosis,targetTrackingCode:e.targetTrackingCode}),d=[],f=``;for await(let e of l(u))switch(e.type){case`delta`:f+=e.content,a?.onDelta?.(e.content);break;case`tool_start`:a?.onToolStart?.({id:e.id,name:e.name});break;case`tool_call`:{let t=await Wt(e.name,e.arguments,{sandbox:n,cwd:n.cwd,approval:r,prompter:i});d.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 a?.onError?.(e),Error(`[${e.code}] ${e.message}`);case`done`:break}if(f&&(s+=f),d.length===0){f&&o.push({role:`assistant`,content:f});break}o.push({role:`assistant`,content:f,toolCalls:d.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))});for(let e of d)o.push({role:`tool`,toolCallId:e.id,toolName:e.name,content:JSON.stringify(e.result)})}return{finalText:s,rounds:c}}async function Wt(e,t,n){try{switch(e){case`read_file`:return await Rt(n.sandbox,t);case`write_file`:return await zt(n.sandbox,t,n.approval);case`patch_file`:return await Bt(n.sandbox,t,n.approval);case`detect_framework`:return await Vt(n.cwd);case`ask_user`:return await Ht(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 Gt=e=>`<script defer\n data-id="${e}"\n data-allow-localhost="true"\n src="https://api.zenovay.com/z.js">\n</script>`;async function Kt(e){let t={installed:[],skipped:[],errors:[]},n=await N([`**/*.html`,`!node_modules/**`,`!.git/**`,`!dist/**`,`!.next/**`,`!.nuxt/**`,`!build/**`,`!.output/**`],{cwd:e.cwd,gitignore:!0,absolute:!1});if(n.length===0)return t;let r=Gt(e.trackingCode),i=RegExp(`data-id\\s*=\\s*["']${qt(e.trackingCode)}["']`);for(let a of n){let n=b.join(e.cwd,a),o;try{o=await x.readFile(n,`utf8`)}catch(e){t.errors.push({file:a,error:e.message});continue}if(he.test(o)&&i.test(o)){t.skipped.push({file:a,reason:`already installed with correct tracking code`});continue}let s;if(he.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??`
|
|
93
|
+
`,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 ge)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 x.writeFile(n,s,`utf8`),t.installed.push(a)}catch(e){t.errors.push({file:a,error:e.message})}}return t}function qt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const Jt=`https://api.zenovay.com/z.js`;function Yt(e,t){return e.includes(Jt)&&e.includes(t)}function Xt(e){if(/from\s+['"]next\/script['"]/.test(e))return e;let t=e.split(`
|
|
94
|
+
`),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(`
|
|
95
|
+
`)}function Zt(e,t){let n=/([ \t]*)<\/body>/,r=e.match(n);if(!r)return null;let i=r[1]??``,a=`${i} <Script defer data-id="${t}" data-allow-localhost="true" src="${Jt}" strategy="afterInteractive" />`;return e.replace(n,`${a}\n${i}</body>`)}async function Qt(e){let{cwd:t,trackingCode:n}=e,r={installed:[],skipped:[],errors:[],fellThrough:!1},i;try{i=await N([`app/**/layout.{tsx,ts,jsx,js}`,`src/app/**/layout.{tsx,ts,jsx,js}`],{cwd:t,gitignore:!1,ignore:[`**/node_modules/**`]})}catch(e){return r.errors.push({file:`app/**/layout`,error:e.message}),r.fellThrough=!0,r}if(i.length===0)return r.fellThrough=!0,r;let a=[];for(let e of i)try{let n=await k.readFile(b.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(Yt(o.src,n))return r.skipped.push({file:o.rel,reason:`already installed with correct tracking code`}),r;let s=Xt(o.src),c=Zt(s,n);if(!c)return r.fellThrough=!0,r;try{await k.writeFile(b.join(t,o.rel),c),r.installed.push(o.rel)}catch(e){r.errors.push({file:o.rel,error:e.message}),r.fellThrough=!0}return r}const K=`api.zenovay.com/z.js`;async function q(e){try{return await x.readFile(e,`utf8`)}catch{return null}}function $t(e,t){let n=e.toLowerCase().lastIndexOf(`</head>`);if(n===-1)return null;let r=e.lastIndexOf(`
|
|
96
|
+
`,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 en(e,t,n){let r=b.dirname(e),i=/import\s+[^;]*?from\s*['"`](\.[^'"`]+\.(?:astro|tsx|jsx|vue|svelte))['"`]/g,a;for(;(a=i.exec(t))!==null;){let e=b.resolve(r,a[1]),t=await q(e);if(t===null)continue;if(t.includes(K))return e;let i=$t(t,n);if(i!==null)return await x.writeFile(e,i,`utf8`),e}return null}async function tn(e){if(e.adapter.id===`nuxt`)return rn(e);if(e.adapter.id===`sveltekit`)return an(e);let{cwd:t,trackingCode:n,siteId:r,adapter:i}=e,a={installed:[],skipped:[],errors:[],fellThrough:!1},o;try{o=i.buildSnippets({trackingCode:n,siteId:r??``},`script`)}catch{return a.fellThrough=!0,a}if(!o||o.length===0)return a.fellThrough=!0,a;let s=new Set(o.map(e=>e.anchorKind));if(s.size===1&&s.has(`head-tag`)){let e=!1;for(let n of o){let r=b.join(t,n.targetPath),i=await q(r);if(i===null){a.skipped.push({file:n.targetPath,reason:`target file not present`});continue}if(i.includes(K)){a.skipped.push({file:n.targetPath,reason:`tracker already present`}),e=!0;break}let o=$t(i,n.code);if(o===null){let o=await en(r,i,n.code);if(o){a.installed.push(b.relative(t,o)),e=!0;break}a.skipped.push({file:n.targetPath,reason:`no </head> anchor (inline or in an imported head component)`});continue}try{await x.writeFile(r,o,`utf8`),a.installed.push(n.targetPath),e=!0;break}catch(e){a.errors.push({file:n.targetPath,error:e.message})}}return!e&&a.installed.length===0&&a.errors.length===0&&(a.fellThrough=!0),a}if(s.size===1&&s.has(`replace-file`)&&o.length===1){let e=o[0];if(!e)return a.fellThrough=!0,a;let n=i.files.find(t=>t.path===e.targetPath),r=b.join(t,e.targetPath),s=await q(r);if(s!==null)return s.includes(K)?(a.skipped.push({file:e.targetPath,reason:`tracker already present`}),a):(a.fellThrough=!0,a);if(n?.kind===`create`){try{await x.mkdir(b.dirname(r),{recursive:!0}),await x.writeFile(r,e.code,`utf8`),a.installed.push(e.targetPath)}catch(t){a.errors.push({file:e.targetPath,error:t.message}),a.fellThrough=a.installed.length===0}return a}return a.fellThrough=!0,a}return a.fellThrough=!0,a}function nn(){return{installed:[],skipped:[],errors:[],fellThrough:!1}}async function rn(e){let t=nn(),n=[`nuxt.config.ts`,`nuxt.config.mjs`,`nuxt.config.js`],r=null,i=null,a=null;for(let t of n){let n=b.join(e.cwd,t),o=await q(n);if(o!==null){r=t,i=n,a=o;break}}if(a===null||i===null||r===null)return t.skipped.push({file:`nuxt.config.ts`,reason:`nuxt.config not found`}),t.fellThrough=!0,t;if(a.includes(K))return t.skipped.push({file:r,reason:`tracker already present`}),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 x.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 an(e){let t=nn(),n=`src/routes/+layout.svelte`,r=b.join(e.cwd,n),i=await q(r),a=`<svelte:head>\n <script defer data-id="${e.trackingCode}" data-allow-localhost="true" src="https://api.zenovay.com/z.js"></script>\n</svelte:head>\n`;if(i!==null){if(i.includes(K))return t.skipped.push({file:n,reason:`tracker already present`}),t;try{await x.writeFile(r,`${a}\n${i}`,`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 x.mkdir(b.dirname(r),{recursive:!0}),await x.writeFile(r,o,`utf8`),t.installed.push(n)}catch(e){t.errors.push({file:n,error:e.message}),t.fellThrough=!0}return t}async function J(e,t){try{return await x.access(b.join(e,t)),!0}catch{return!1}}async function on(e,t){try{let n=await x.stat(b.join(e,t));return n.isDirectory()}catch{return!1}}async function sn(e,t){try{return await x.readFile(b.join(e,t),`utf8`)}catch{return null}}const cn=[`next.config.js`,`next.config.mjs`,`next.config.cjs`,`next.config.ts`];async function ln(e){let t=[],n=await sn(e,`wrangler.toml`),r=n!==null&&/^\s*pages_build_output_dir\s*=/m.test(n),i=await on(e,`functions`),a=await on(e,`.cloudflare`);if(r&&t.push(`wrangler.toml has pages_build_output_dir`),i&&t.push(`functions/ directory present`),a&&t.push(`.cloudflare/ directory present`),r||i||a)return{host:`cloudflare-pages`,signals:t};let o=await J(e,`vercel.json`),s=await on(e,`.vercel`);if(o&&t.push(`vercel.json present`),s&&t.push(`.vercel/ directory present`),o||s)return{host:`vercel`,signals:t};let c=await J(e,`netlify.toml`),l=await J(e,b.join(`public`,`_redirects`)),u=await J(e,`_redirects`);if(c&&t.push(`netlify.toml present`),l&&t.push(`public/_redirects present`),u&&t.push(`_redirects present`),c||l||u)return{host:`netlify`,signals:t};let d=null;for(let t of cn)if(await J(e,t)){d=t;break}return d?(t.push(`${d} present (no Vercel/Netlify/CF-Pages signal)`),{host:`nextjs-server`,signals:t}):(t.push(`no deployment-host signals found`),{host:`unknown`,signals:t})}function un(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 dn=`https://api.zenovay.com`;function fn(e){return`// Auto-generated by @zenovay/cli — first-party tracking proxy. Do not edit.
|
|
97
|
+
/**
|
|
98
|
+
* First-Party Proxy for Zenovay Tracking.
|
|
99
|
+
*
|
|
100
|
+
* This Cloudflare Pages Function proxies tracking requests from your site to
|
|
101
|
+
* ${e}/fp/* — making tracking requests "first-party" to bypass browser
|
|
102
|
+
* tracking protection (Firefox ETP, Edge Tracking Prevention, Safari ITP, Brave).
|
|
103
|
+
*
|
|
104
|
+
* Routes (this function lives at functions/_z/[[path]].ts → /_z/*):
|
|
105
|
+
* - GET /_z/script.js → ${e}/fp/script.js
|
|
106
|
+
* - GET /_z/load → ${e}/fp/load
|
|
107
|
+
* - POST /_z/e/:trackingCode → ${e}/fp/e/:trackingCode
|
|
108
|
+
* - POST /_z/events → ${e}/fp/events
|
|
109
|
+
* - GET /_z/settings/:trackingCode → ${e}/fp/settings/:trackingCode
|
|
110
|
+
*/
|
|
111
|
+
|
|
112
|
+
interface Env {
|
|
113
|
+
NEXT_PUBLIC_API_URL?: string
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
interface EventContext {
|
|
117
|
+
request: Request
|
|
118
|
+
params: { path?: string[] }
|
|
119
|
+
env: Env
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Handle all HTTP methods (GET, POST, OPTIONS).
|
|
124
|
+
*/
|
|
125
|
+
export async function onRequest(context: EventContext): Promise<Response> {
|
|
126
|
+
const { request, params, env } = context
|
|
127
|
+
|
|
128
|
+
// Build the path from the catch-all parameter.
|
|
129
|
+
const pathSegments = params.path || []
|
|
130
|
+
const path = pathSegments.join('/')
|
|
131
|
+
|
|
132
|
+
// API base URL — defaults to the value baked in at generation time, but an
|
|
133
|
+
// env var override (NEXT_PUBLIC_API_URL) still wins if present.
|
|
134
|
+
const apiBase = env.NEXT_PUBLIC_API_URL || '${e}'
|
|
135
|
+
|
|
136
|
+
// Build target URL — proxy to /fp/* endpoints.
|
|
137
|
+
const targetUrl = \`\${apiBase}/fp/\${path}\${new URL(request.url).search}\`
|
|
138
|
+
|
|
139
|
+
// Handle OPTIONS (CORS preflight).
|
|
140
|
+
if (request.method === 'OPTIONS') {
|
|
141
|
+
return new Response(null, {
|
|
142
|
+
status: 204,
|
|
143
|
+
headers: {
|
|
144
|
+
'Access-Control-Allow-Origin': '*',
|
|
145
|
+
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
|
146
|
+
'Access-Control-Allow-Headers': 'Content-Type, X-Zenovay-Tracking-Code',
|
|
147
|
+
'Access-Control-Max-Age': '86400',
|
|
148
|
+
},
|
|
149
|
+
})
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
try {
|
|
153
|
+
// Get the real client IP from Cloudflare headers.
|
|
154
|
+
const clientIP =
|
|
155
|
+
request.headers.get('CF-Connecting-IP') ||
|
|
156
|
+
request.headers.get('X-Forwarded-For')?.split(',')[0]?.trim() ||
|
|
157
|
+
request.headers.get('X-Real-IP') ||
|
|
158
|
+
''
|
|
159
|
+
|
|
160
|
+
// Clone the original headers.
|
|
161
|
+
const proxyHeaders = new Headers(request.headers)
|
|
162
|
+
|
|
163
|
+
// Add/set proxy identification headers.
|
|
164
|
+
proxyHeaders.set('X-Zenovay-Proxy', 'first-party')
|
|
165
|
+
proxyHeaders.set('X-Zenovay-Real-IP', clientIP)
|
|
166
|
+
|
|
167
|
+
// Forward the visitor's real CF geo data as custom headers before deleting
|
|
168
|
+
// the originals. When this Worker proxies to ${e}, Cloudflare
|
|
169
|
+
// overwrites CF-* headers with the Worker datacenter's info — these custom
|
|
170
|
+
// headers preserve the visitor's real geo.
|
|
171
|
+
const cfCountry = request.headers.get('CF-IPCountry')
|
|
172
|
+
const cfCity = request.headers.get('CF-IPCity')
|
|
173
|
+
const cfRegion = request.headers.get('CF-Region')
|
|
174
|
+
const cfLatitude = request.headers.get('CF-IPLatitude')
|
|
175
|
+
const cfLongitude = request.headers.get('CF-IPLongitude')
|
|
176
|
+
const cfTimezone = request.headers.get('CF-Timezone')
|
|
177
|
+
if (cfCountry) proxyHeaders.set('X-Zenovay-CF-Country', cfCountry)
|
|
178
|
+
if (cfCity) proxyHeaders.set('X-Zenovay-CF-City', cfCity)
|
|
179
|
+
if (cfRegion) proxyHeaders.set('X-Zenovay-CF-Region', cfRegion)
|
|
180
|
+
if (cfLatitude) proxyHeaders.set('X-Zenovay-CF-Latitude', cfLatitude)
|
|
181
|
+
if (cfLongitude) proxyHeaders.set('X-Zenovay-CF-Longitude', cfLongitude)
|
|
182
|
+
if (cfTimezone) proxyHeaders.set('X-Zenovay-CF-Timezone', cfTimezone)
|
|
183
|
+
|
|
184
|
+
// Remove headers that shouldn't be forwarded.
|
|
185
|
+
proxyHeaders.delete('Host')
|
|
186
|
+
proxyHeaders.delete('CF-Connecting-IP')
|
|
187
|
+
proxyHeaders.delete('CF-RAY')
|
|
188
|
+
proxyHeaders.delete('CF-Visitor')
|
|
189
|
+
proxyHeaders.delete('CF-IPCountry')
|
|
190
|
+
proxyHeaders.delete('CF-Worker')
|
|
191
|
+
|
|
192
|
+
// Prepare request options.
|
|
193
|
+
const requestInit: RequestInit = {
|
|
194
|
+
method: request.method,
|
|
195
|
+
headers: proxyHeaders,
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// Forward the body for POST/PUT/PATCH requests.
|
|
199
|
+
if (request.method === 'POST' || request.method === 'PUT' || request.method === 'PATCH') {
|
|
200
|
+
requestInit.body = await request.arrayBuffer()
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Forward the request to the API.
|
|
204
|
+
// Use cf options to bypass Cloudflare edge cache for fresh script responses.
|
|
205
|
+
const response = await fetch(targetUrl, {
|
|
206
|
+
...requestInit,
|
|
207
|
+
cf: {
|
|
208
|
+
// Bypass cache for scripts to ensure fresh versions.
|
|
209
|
+
cacheTtl: path.endsWith('.js') || path.includes('script') ? 0 : 60,
|
|
210
|
+
cacheEverything: false,
|
|
211
|
+
},
|
|
212
|
+
} as RequestInit)
|
|
213
|
+
|
|
214
|
+
// Clone response headers.
|
|
215
|
+
const responseHeaders = new Headers(response.headers)
|
|
216
|
+
|
|
217
|
+
// Add proxy identification.
|
|
218
|
+
responseHeaders.set('X-Zenovay-Proxied', 'true')
|
|
219
|
+
|
|
220
|
+
// For scripts, ensure the proper content type and no caching.
|
|
221
|
+
if (path.endsWith('.js') || path.includes('script') || path.includes('load')) {
|
|
222
|
+
responseHeaders.set('Content-Type', 'application/javascript; charset=utf-8')
|
|
223
|
+
|
|
224
|
+
// Don't cache scripts so the latest API config (apiUrl, trackingCode) is
|
|
225
|
+
// always served.
|
|
226
|
+
responseHeaders.set('Cache-Control', 'no-cache, no-store, must-revalidate')
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// CORS headers for the proxied response.
|
|
230
|
+
responseHeaders.set('Access-Control-Allow-Origin', '*')
|
|
231
|
+
responseHeaders.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
|
|
232
|
+
responseHeaders.set('Access-Control-Allow-Headers', 'Content-Type, X-Zenovay-Tracking-Code')
|
|
233
|
+
|
|
234
|
+
// Return the proxied response.
|
|
235
|
+
return new Response(response.body, {
|
|
236
|
+
status: response.status,
|
|
237
|
+
statusText: response.statusText,
|
|
238
|
+
headers: responseHeaders,
|
|
239
|
+
})
|
|
240
|
+
} catch (error) {
|
|
241
|
+
console.error('[Zenovay First-Party Proxy] Error:', error)
|
|
242
|
+
|
|
243
|
+
return new Response(
|
|
244
|
+
JSON.stringify({
|
|
245
|
+
error: 'Proxy error',
|
|
246
|
+
message: error instanceof Error ? error.message : 'Unknown error',
|
|
247
|
+
}),
|
|
248
|
+
{
|
|
249
|
+
status: 502,
|
|
250
|
+
headers: {
|
|
251
|
+
'Content-Type': 'application/json',
|
|
252
|
+
'Access-Control-Allow-Origin': '*',
|
|
253
|
+
},
|
|
254
|
+
}
|
|
255
|
+
)
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Handle GET requests specifically.
|
|
261
|
+
*/
|
|
262
|
+
export async function onRequestGet(context: EventContext): Promise<Response> {
|
|
263
|
+
return onRequest(context)
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Handle POST requests specifically.
|
|
268
|
+
*/
|
|
269
|
+
export async function onRequestPost(context: EventContext): Promise<Response> {
|
|
270
|
+
return onRequest(context)
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Handle OPTIONS requests specifically (CORS preflight).
|
|
275
|
+
*/
|
|
276
|
+
export async function onRequestOptions(_context: EventContext): Promise<Response> {
|
|
277
|
+
return new Response(null, {
|
|
278
|
+
status: 204,
|
|
279
|
+
headers: {
|
|
280
|
+
'Access-Control-Allow-Origin': '*',
|
|
281
|
+
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
|
282
|
+
'Access-Control-Allow-Headers': 'Content-Type, X-Zenovay-Tracking-Code',
|
|
283
|
+
'Access-Control-Max-Age': '86400',
|
|
284
|
+
},
|
|
285
|
+
})
|
|
286
|
+
}
|
|
287
|
+
`}async function pn(e,t){let n=(t.apiBase||dn).replace(/\/+$/,``),r=b.join(e,`functions`,`_z`),i=b.join(r,`[[path]].ts`);try{return await x.access(i),{file:i,action:`exists`}}catch{}return await x.mkdir(r,{recursive:!0}),await x.writeFile(i,fn(n),`utf8`),{file:i,action:`created`}}const mn=`https://api.zenovay.com`,hn=[`next.config.js`,`next.config.mjs`,`next.config.ts`];function gn(e){return` // Zenovay first-party proxy — forwards /_z/* to the tracking API
|
|
288
|
+
{
|
|
289
|
+
source: '/_z/:path*',
|
|
290
|
+
destination: '${e}/fp/:path*',
|
|
291
|
+
},`}function _n(e){return`/** @type {import('next').NextConfig} */
|
|
292
|
+
const nextConfig = {
|
|
293
|
+
async rewrites() {
|
|
294
|
+
return [
|
|
295
|
+
${gn(e)}
|
|
296
|
+
];
|
|
297
|
+
},
|
|
298
|
+
};
|
|
299
|
+
|
|
300
|
+
export default nextConfig;
|
|
301
|
+
`}async function vn(e,t={}){let n=t.apiBase??mn,r=null;for(let t of hn){let n=b.join(e,t);try{await k.access(n),r=n;break}catch{}}if(!r){let t=b.join(e,`next.config.mjs`);return await k.writeFile(t,_n(n),`utf8`),{file:t,action:`created`}}let i=await k.readFile(r,`utf8`);if(i.includes(`/_z/:path*`))return{file:r,action:`updated`};if(/\brewrites\s*(?::|=|\()/.test(i)||/\bredirects\s*\(/.test(i))return{file:r,action:`manual`};let a=i.match(/(?:module\.exports\s*=\s*|export\s+default\s+|const\s+\w+\s*=\s*)\{/);if(!a||a.index===void 0)return{file:r,action:`manual`};let o=a.index+a[0].length-1,s=i.slice(0,o+1),c=i.slice(o+1),l=`
|
|
302
|
+
async rewrites() {
|
|
303
|
+
return [
|
|
304
|
+
${gn(n)}
|
|
305
|
+
];
|
|
306
|
+
},`,u=`${s}${l}${c}`;return await k.writeFile(r,u,`utf8`),{file:r,action:`updated`}}const yn=`https://api.zenovay.com`;async function bn(e,t={}){let n=t.apiBase??yn,r=b.join(e,`vercel.json`),i={source:`/_z/(.*)`,destination:`${n}/fp/$1`},a=null;try{a=await k.readFile(r,`utf8`)}catch{a=null}if(a===null){let e={rewrites:[i]};return await k.writeFile(r,`${JSON.stringify(e,null,2)}\n`,`utf8`),{file:r,action:`created`}}let o;try{o=JSON.parse(a)}catch{throw Error(`Cannot parse existing vercel.json at ${r}: invalid JSON`)}let s=Array.isArray(o.rewrites)?o.rewrites:[],c=s.some(e=>typeof e?.source==`string`&&e.source.startsWith(`/_z`));return c?{file:r,action:`exists`}:(o.rewrites=[...s,i],await k.writeFile(r,`${JSON.stringify(o,null,2)}\n`,`utf8`),{file:r,action:`updated`})}const xn=`https://api.zenovay.com`;async function Sn(e){let t=b.join(e,`_redirects`),n=b.join(e,`public`,`_redirects`);for(let e of[t,n])try{return await k.access(e),e}catch{}try{let t=await k.stat(b.join(e,`public`));if(t.isDirectory())return n}catch{}return t}async function Cn(e,t={}){let n=t.apiBase??xn,r=await Sn(e),i=`/_z/* ${n}/fp/:splat 200`,a=null;try{a=await k.readFile(r,`utf8`)}catch{a=null}if(a===null)return await k.mkdir(b.dirname(r),{recursive:!0}),await k.writeFile(r,`# Zenovay first-party proxy — forwards /_z/* to the tracking API\n${i}\n`,`utf8`),{file:r,action:`created`};let o=a.split(/\r?\n/).some(e=>{let t=e.trim();return t.length>0&&!t.startsWith(`#`)&&t.startsWith(`/_z/`)});if(o)return{file:r,action:`exists`};let s=a.length>0&&!a.endsWith(`
|
|
307
|
+
`)?`
|
|
308
|
+
`:``,c=`${a}${s}# Zenovay first-party proxy — forwards /_z/* to the tracking API\n${i}\n`;return await k.writeFile(r,c,`utf8`),{file:r,action:`updated`}}function wn(e){return`<script defer src="/_z/script.js?id=${e}"></script>`}const Y=/<script\b(?=[^>]*\bsrc\s*=\s*["'`]https:\/\/api\.zenovay\.com\/z\.js["'`])[^>]*>(?:\s*<\/script>)?/gi,Tn=/\bdata-id\s*=\s*["'`]([^"'`]+)["'`]/i;function En(e,t){let n=e.match(Tn),r=n?.[1]??t;return wn(r)}async function Dn(e,t){let n=await N([`**/*.{html,htm,tsx,jsx,vue,svelte,astro,ts,js,mjs}`,`!node_modules/**`,`!.git/**`,`!dist/**`,`!.next/**`,`!.nuxt/**`,`!build/**`,`!.output/**`],{cwd:e,gitignore:!0,deep:4,absolute:!0}).catch(()=>[]),r=[];for(let i of n.slice(0,300)){let n;try{n=await x.readFile(i,`utf8`)}catch{continue}if(Y.lastIndex=0,!Y.test(n))continue;Y.lastIndex=0;let a=n.replace(Y,e=>En(e,t.trackingCode));if(a!==n){try{await x.writeFile(i,a,`utf8`)}catch{continue}r.push(b.relative(e,i))}}return{swapped:r.length>0,files:r}}const On="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, Edge and Brave 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 kn(e,t){let{trackingCode:n,apiBase:r,forceHost:i}=t,a=`unknown`,o=null,s=`skipped`,c=null,l=!1;try{switch(a=i&&i!==`unknown`?i:(await ln(e)).host,a){case`cloudflare-pages`:{let t=await pn(e,{apiBase:r});o=t.file,s=t.action;break}case`nextjs-server`:{let t=await vn(e,{apiBase:r});o=t.file,s=t.action,t.action===`manual`&&(c=`Your tracker is live. To also count Safari/Edge/Brave visitors, add this rewrite to ${t.file} yourself (it already defines rewrites, so we didn't edit it): { source: '/_z/:path*', destination: 'https://api.zenovay.com/fp/:path*' }.`);break}case`vercel`:{let t=await bn(e,{apiBase:r});o=t.file,s=t.action;break}case`netlify`:{let t=await Cn(e,{apiBase:r});o=t.file,s=t.action;break}case`unknown`:default:s=`skipped`,c=On;break}}catch(e){o=null,s=`skipped`,c=`${On} (auto-setup hit an error: ${e.message.slice(0,120)})`}let u=o!==null&&s!==`manual`&&s!==`skipped`;if(u)try{let t=await Dn(e,{trackingCode:n});l=t.swapped}catch{l=!1}return{host:a,proxyFile:o,proxyAction:s,snippetSwapped:l,manual:c}}const An=`\x1B]8;;`,jn=`\x07`;function Mn(){return process.env.FORCE_HYPERLINK?!0:!(process.env.NO_COLOR||!process.stdout.isTTY||process.env.CI||(process.env.TERM??``)===`dumb`)}function Nn({url:e,label:t,color:n,arrow:r=!0}){let{theme:i}=m(),a=n??i.fg,o=(t??e)+(r?` ↗`:``);return Mn()?A.createElement(D,{color:a,underline:!0},An,e,jn,o,An,jn):t&&t!==e?A.createElement(D,{color:a},A.createElement(D,{underline:!0},t),A.createElement(D,{color:i.dim},` (`,e,`)`)):A.createElement(D,{color:a,underline:!0},e)}function X({label:e,value:t,labelWidth:n=12}){let{theme:r}=m();return A.createElement(E,{flexDirection:`row`},A.createElement(E,{width:n,flexShrink:0},A.createElement(D,{color:r.dim},e.toUpperCase())),typeof t==`string`?A.createElement(D,{color:r.fg},t):t)}function Pn(e){return e.review&&process.stdout.isTTY?`interactive`:`auto`}function Fn(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 In(){let e=[12,15,18,22,28,35,41,50,58,64,72,78],t=y(e,24);return[` ↑`,` ${t}`,` └────────────────────────`,` May Jun Jul Aug Sep`]}function Ln(){return[` Landing page ████████████████████ 100%`,` ↓ -28%`,` Pricing ██████████████░░░░░░ 72%`,` ↓ -50%`,` Checkout ███████░░░░░░░░░░░░░ 36%`,` ↓ -64%`,` Purchased ███░░░░░░░░░░░░░░░░░ 13%`]}function Rn(){return[` ▇▇▇▇▇▇▇▇▇▎ 89 Sarah K. /pricing 🇺🇸`,` ▇▇▇▇▇▇░░░░ 61 anon /docs 🇩🇪`,` ▇▇▇░░░░░░░ 34 anon /changelog 🇯🇵`]}function zn(){return[` LCP ● 2.1s good ████████████░░░░░░`,` INP ● 89ms good ██████████████████`,` CLS ⚠ 0.14 needs ████████████░░░░░░`,` TTFB ● 380ms good ███████████████░░░`]}const Bn=[{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:In},{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:Ln},{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:Rn},{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:zn},{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.`]}],Vn=11e3,Hn=9,Un=({width:e,height:t})=>{let{theme:n}=m(),[r,i]=M(0);j(()=>{if(Bn.length<=1)return;let e=setInterval(()=>{i(e=>(e+1)%Bn.length)},Vn);return()=>clearInterval(e)},[]);let a=Bn[r],o=a.visual?a.visual():[];return A.createElement(E,{flexDirection:`column`,width:e,height:t,paddingX:2,paddingY:1},A.createElement(E,{marginBottom:1},A.createElement(D,{color:n.typography.label.color,dimColor:n.typography.label.dim},`LEARN`)),A.createElement(E,{flexDirection:`column`,minHeight:Hn,key:r},A.createElement(E,{marginBottom:1},A.createElement(D,{bold:!0,color:n.fg,wrap:`truncate`},a.title)),a.body.map((e,t)=>A.createElement(D,{key:t,color:n.muted,wrap:`truncate`},e||` `)),o.length>0&&A.createElement(E,{flexDirection:`column`,marginTop:1},o.map((e,t)=>A.createElement(D,{key:t,color:n.accent},e)))),A.createElement(E,{flexGrow:1}),A.createElement(E,{marginTop:1},A.createElement(D,null,Bn.map((e,t)=>A.createElement(D,{key:t,color:t===r?n.muted:n.dim},t===r?`─`:`·`)))))},Wn={pending:`·`,active:`⠋`,done:`✓`,error:`✗`};function Gn(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 Kn=({tasks:e,width:t,height:n,liveLine:r})=>{let{theme:i}=m();return A.createElement(E,{flexDirection:`column`,width:t,height:n,paddingX:2,paddingY:1},A.createElement(E,{marginBottom:1},A.createElement(D,{color:i.typography.label.color,dimColor:i.typography.label.dim},`TASKS`)),e.map(e=>A.createElement(E,{key:e.id,flexDirection:`column`},A.createElement(E,{flexDirection:`row`},e.status===`active`?A.createElement(D,{color:i.accent},A.createElement(P,{type:`dots`})):A.createElement(D,{color:Gn(e.status,i)},Wn[e.status]),A.createElement(D,null,` `),A.createElement(D,{color:e.status===`pending`?i.muted:i.fg,wrap:`truncate`},e.label)),e.detail&&A.createElement(E,{paddingLeft:2},A.createElement(D,{color:i.dim,wrap:`truncate`},e.detail)))),A.createElement(E,{flexGrow:1}),r&&A.createElement(E,{flexDirection:`row`,marginTop:1},A.createElement(D,{color:i.accent},`◆ `),A.createElement(D,{color:i.fg,wrap:`truncate`},r)))};async function qn(e){if(o(e))return Jn(e);let t=`quit`,n=null,r=Promise.resolve(),i=await new Promise(i=>{let{unmount:a,waitUntilExit:o}=ee(A.createElement(Yn,{opts:e,onExit:(e,r,o)=>{t=r??`quit`,n=o??null,a(),i(e)}}),{exitOnCtrlC:!0});r=o(),r.catch(()=>i(1))});await r.catch(()=>{});let a=i===0&&t!==`quit`&&!!n;if(i===0&&!a&&await d().catch(()=>void 0),i!==0||t===`quit`||!n)return i;let s=n.id,c=t===`watch`?[`overview`,`--site-id`,s]:[`events`,`tail`,`--site-id`,s],{spawnSync:l}=await import(`node:child_process`),{realpathSync:u}=await import(`node:fs`),{detectInstallMethod:f,buildPostInstallReexec:p}=await import(`./ensure-latest-BDqPumYX.js`),{cmd:m,args:h}=p({method:f(),execPath:process.execPath,argv1:process.argv[1]??``,sub:c,resolveSymlink:u});await new Promise(e=>setImmediate(e));let g=l(m,h,{stdio:`inherit`});if(g.error){let e=t===`watch`?`overview`:`events tail`;return process.stderr.write(`Run \`zenovay ${e} --site-id ${s}\` to continue.\n`),0}return g.status??0}async function Jn(t){let r=await import(`./telemetry-BaEf884T.js`).catch(()=>null);r?.emit(`install.start`,{properties:{mode:`headless`}});try{let o=await e(),s=await yt(t.cwd);if(!s)return a({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;a({type:`framework.detected`,framework:s.id,confidence:1}),r?.emit(`install.framework_detected`,{properties:{framework:s.id}});let c=await i({strict:!1});if(!c&&!process.env.ZENOVAY_API_TOKEN)return a({type:`error`,code:`not_logged_in`,message:"Run `zenovay login` first (or set ZENOVAY_API_TOKEN)."}),2;let l=new n({config:o,cliVersion:t.cliVersion,token:c}),[u,d]=await Promise.all([l.getSites(),R(t.cwd,``).catch(()=>null)]),f;if(t.siteId){if(f=u.find(e=>e.id===t.siteId),!f)return a({type:`error`,code:`site_not_found`,message:`Site ${t.siteId} not found.`}),2}else if(d?.foundTrackingCodes.length){for(let e of d.foundTrackingCodes){let t=u.find(t=>t.trackingCode===e);if(t){f=t;break}}f||=u[0]}else f=u[0];if(!f)return a({type:`error`,code:`no_site`,message:`No sites exist; create one at app.zenovay.com or re-run interactively.`}),2;let p=f.trackingCode??f.id;if(d&&(d.recommendation===`no-op`||d.foundTrackingCodes.includes(p)))return a({type:`info`,message:`Zenovay already installed correctly for ${f.name} (${p})`}),a({type:`done`,command:`init`,exitCode:0}),0;a({type:`info`,message:`Using site ${f.id} (${f.name}) trackingCode=${f.trackingCode??f.id}`});let m=f.trackingCode??f.id,h=await W(t.cwd,{[s.envVarName]:m});if(a({type:`info`,message:`env vars added: ${h.addedKeys.join(`,`)}`}),s.id===`plain-html`){let e=await Kt({cwd:t.cwd,trackingCode:m,updateOnly:d?.recommendation===`update-tracking-code`});if(e.installed.length===0&&e.skipped.length===0)return a({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:s.id}}),1;if(a({type:`info`,message:`tracker injected into ${e.installed.length} file(s); ${e.skipped.length} already current; ${e.errors.length} error(s)`}),t.firstParty!==!1){let e=await kn(t.cwd,{trackingCode:m,forceHost:un(t.host)});e.proxyFile&&e.proxyAction!==`manual`&&e.proxyAction!==`skipped`?a({type:`info`,message:`first-party tracking enabled — analytics now load from your own domain (${e.proxyFile}), so Safari/Edge/Brave visitors are counted too`}):e.manual&&a({type:`info`,message:e.manual})}}else return a({type:`error`,code:`headless_framework_unsupported`,message:`Headless install can only auto-inject the tracker for plain-HTML projects. For ${s.displayName}, run \`zenovay init\` interactively — the AI wizard places the <Script> in the correct entry file. (The env var ${h.addedKeys.join(`, `)||s.envVarName} was written.)`}),r?.emit(`install.error`,{error_code:`headless_framework_unsupported`,properties:{mode:`headless`,framework:s.id}}),1;return a({type:`done`,command:`init`,exitCode:0}),r?.emit(`install.success`,{properties:{framework:s.id,mode:`headless`,env_keys_added:h.addedKeys.length}}),0}catch(e){return a({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 Yn=({opts:t,onExit:r})=>{let{exit:a}=te(),{theme:o}=m(),[s,c]=M(`intro`),[l,d]=M(null),[h,g]=M([]),[_,y]=M(null),[b,x]=M(null),[S,C]=M(null),[w,T]=M([]),[ee,k]=M(void 0),[N,re]=M(null),[ie,F]=M(null),[I,L]=M(null),[ae,oe]=M(0),[se,ce]=M(!1),[le,ue]=M(null),z=ne(null),de=ne(!1),[fe,pe]=M(!1),[B,me]=M(void 0),V=ne(null),H=A.useCallback(e=>new Promise(t=>{V.current=t,me(e),pe(!0)}),[]),U=A.useCallback(e=>{pe(!1);let t=V.current;V.current=null,t?.(e)},[]);return O((e,t)=>{s===`error`&&(e.toLowerCase()===`q`||t.escape)&&(a(),r(1))}),j(()=>(process.stdout.isTTY&&process.stdout.write(`\x1B[?1049h\x1B[H`),()=>{z.current?.abort(),V.current?.(null),V.current=null,process.stdout.isTTY&&process.stdout.write(`\x1B[?1049l`)}),[]),j(()=>{de.current||(de.current=!0,(async()=>{try{c(`detecting`);let r=await yt(t.cwd);if(!r){C(`Could not detect your framework. Supported: Next.js, Nuxt, SvelteKit, Astro, Remix, plain HTML.`),c(`error`);return}d(r);let a=await i({strict:!1});!process.env.ZENOVAY_API_TOKEN&&!a&&(c(`login`),await u({cliVersion:t.cliVersion,offerCompletions:!1})),c(`loading-sites`);let o=await e(),s=await i({strict:!1}),l=new n({config:o,cliVersion:t.cliVersion,token:s}),[f,p]=await Promise.all([l.getSites(),R(t.cwd,``).catch(()=>null)]),m=await gr(t.cwd);if(g(f),y(m),f.length===0){c(`create-site`);return}if(p?.foundTrackingCodes.length)for(let e of p.foundTrackingCodes){let t=f.find(t=>t.trackingCode===e);if(t){x(t),c(`already-installed`);return}}if(t.siteId){let e=f.find(e=>e.id===t.siteId);if(!e){C(`Site ${t.siteId} not found in your account.`),c(`error`);return}x(e),Qn(e,r,t,{setPhase:c,setErrorMsg:C,setTasks:T,setLiveLine:k,setSandboxStats:re,setVerifyResult:F,setFirstParty:L,setPendingApproval:ue,askHostChoice:H,registerBridge:e=>{z.current=e}});return}let h=_r(f,m);if(t.yes&&h){x(h),Qn(h,r,t,{setPhase:c,setErrorMsg:C,setTasks:T,setLiveLine:k,setSandboxStats:re,setVerifyResult:F,setFirstParty:L,setPendingApproval:ue,askHostChoice:H,registerBridge:e=>{z.current=e}});return}c(`site-picker`)}catch(e){C(e.message),c(`error`)}})())},[]),j(()=>{s===`error`&&(z.current?.abort(),setTimeout(()=>{a(),r(1)},8e3))},[s]),A.createElement(E,{flexDirection:`column`},A.createElement(f,{version:t.cliVersion,subtitle:`AI install wizard`}),s===`intro`&&A.createElement($n,null),s===`detecting`&&A.createElement(p,{title:`Scanning`,state:`busy`},A.createElement(E,null,A.createElement(D,{color:o.accent},A.createElement(P,{type:`dots`})),A.createElement(D,null,` Detecting framework…`))),s===`login`&&A.createElement(p,{title:`Authenticating`,state:`busy`},A.createElement(D,null,`Opening browser for login… (paste ZENOVAY_API_TOKEN env var to skip)`)),s===`loading-sites`&&A.createElement(p,{title:`Loading your sites`,state:`busy`},A.createElement(E,null,A.createElement(D,{color:o.accent},A.createElement(P,{type:`dots`})),A.createElement(D,null,` Fetching your Zenovay sites…`))),s===`already-installed`&&b&&A.createElement(nr,{site:b,onContinue:()=>{c(`site-picker`)},onExit:()=>{a(),r(0,`quit`,b)}}),s===`site-picker`&&l&&A.createElement(rr,{sites:h,preselectHint:_,onPick:e=>{if(e===`create-new`){c(`create-site`);return}x(e),Qn(e,l,t,{setPhase:c,setErrorMsg:C,setTasks:T,setLiveLine:k,setSandboxStats:re,setVerifyResult:F,setFirstParty:L,setPendingApproval:ue,askHostChoice:H,registerBridge:e=>{z.current=e}})}}),s===`create-site`&&A.createElement(p,{title:`Create a new site`,state:`warn`},A.createElement(D,{color:o.warn},"No site picked (or none exist yet). Visit https://app.zenovay.com/websites to create one, then re-run `zenovay init`."),A.createElement(D,{color:o.muted},`(Inline site creation from the CLI is scheduled for V1.1 — it requires a plan-limit check.)`)),s===`agent`&&l&&b&&A.createElement(tr,{adapter:l,site:b,tasks:w,liveLine:ee,pendingApproval:le,onApprove:e=>{le&&z.current?.resolve(le.id,e)},pendingHostChoice:fe,hostChoiceNote:B,onHostChoice:U}),s===`install-complete`&&l&&b&&A.createElement(or,{adapter:l,site:b,stats:N,verify:ie,firstParty:I,onCommit:()=>c(`commit-prompt`),onSkipCommit:()=>c(`deploy-prompt`)}),s===`commit-prompt`&&b&&A.createElement(cr,{cwd:t.cwd,onDone:e=>{e.committed&&k(`Pushed ${e.shortSha} to ${e.branch}`),c(`deploy-prompt`)},onError:e=>{C(e),c(`error`)}}),s===`deploy-prompt`&&b&&A.createElement(lr,{site:b,onDeployed:()=>c(`visit-prompt`),onSkip:()=>c(`verify`)}),s===`visit-prompt`&&b&&A.createElement(ur,{site:b,onContinue:()=>c(`verify`)}),s===`verify`&&b&&A.createElement(fr,{site:b,elapsed:ae,onTick:e=>oe(e),onArrived:()=>{ce(!0),c(`success`)},onTimeout:()=>c(`success`)}),s===`success`&&l&&b&&A.createElement(ar,{adapter:l,site:b,stats:N,arrived:se,firstParty:I,onPick:e=>{a(),r(0,e,b)}}),s===`error`&&A.createElement(p,{title:`Install failed`,state:`err`},A.createElement(D,{color:o.error},S??`Unknown error`)),A.createElement(v,{items:s===`already-installed`?[{key:`q`,label:`quit`},{key:`r`,label:`re-run wizard`},{key:`ctrl-c`,label:`abort`}]:[{key:`q`,label:`quit`},{key:`ctrl-c`,label:`abort`}]}))};async function Z(e,t,n){if(e.firstParty===!1||!n.setFirstParty)return;n.setTasks(e=>e.some(e=>e.id===`first-party`)?e.map(e=>e.id===`first-party`?{...e,status:`active`}:e):[...e,{id:`first-party`,label:`Set up first-party tracking (all browsers)`,status:`active`}]),n.setLiveLine(`Setting up first-party tracking (all browsers)…`);let r=un(e.host),i=null;try{if(i=await kn(e.cwd,{trackingCode:t,forceHost:r}),n.setFirstParty(i),i.host===`unknown`&&!r&&n.askHostChoice){n.setLiveLine(`Where do you deploy this site? (enables all-browser tracking)`);let r=e.host?`Unrecognized --host "${e.host}" — pick your host below.`:void 0,a=await n.askHostChoice(r);a&&(n.setLiveLine(`Setting up first-party tracking…`),i=await kn(e.cwd,{trackingCode:t,forceHost:a}),n.setFirstParty(i))}}catch{n.setFirstParty(null)}let a=Xn(i);n.setTasks(e=>e.map(e=>e.id===`first-party`?{...e,status:`done`,detail:a}:e)),n.setLiveLine(void 0)}function Xn(e){return e?e.proxyFile&&e.proxyAction!==`manual`&&e.proxyAction!==`skipped`?`now loads from your domain (${b.basename(e.proxyFile)})`:e.manual?`standard tracking active — see note below for all-browser coverage`:`standard tracking active`:`standard tracking active`}async function Zn(e,t,n){n.setLiveLine(`Verifying the tracker is in your source…`);try{let r=await R(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 Qn(r,a,o,s){try{s.setPhase(`agent`);let c=await e(),l=await i({strict:!1}),u=new n({config:c,cliVersion:o.cliVersion,token:l}),d=new _e({cwd:o.cwd}),f=r.trackingCode??r.id;await t({defaultSiteId:r.id,defaultSiteName:r.name}).catch(()=>void 0);let p=await R(o.cwd,f);if(p.recommendation===`no-op`){s.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:`done`,detail:`already installed correctly`}:e)),s.setLiveLine(p.summary),s.setSandboxStats?.({reads:0,writes:0,rounds:0}),!o.skipMcp&&l&&await G({accessToken:l.accessToken}).catch(()=>void 0),s.setVerifyResult?.({ok:!0,detail:`Already installed correctly`}),await Z(o,f,s),s.setPhase(`install-complete`);return}if(p.competitors.length>0&&s.setLiveLine(`Detected ${p.competitors.map(e=>e.name).join(`, `)} — will install Zenovay alongside (won't touch their tags).`),a.id===`next-app-router`){s.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`}]),s.setLiveLine(`Next.js — locating the document shell layout…`);let e=await Qt({cwd:o.cwd,trackingCode:f});if(!e.fellThrough&&e.errors.length===0){let t=e.installed[0]??`already installed`;s.setTasks(e=>e.map(e=>e.id===`read`||e.id===`write`?{...e,status:`done`,detail:t}:e));let n=await W(o.cwd,{[a.envVarName]:f});if(s.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${n.addedKeys.length} key(s) added`}:e)),!o.skipMcp&&l){let e=await G({accessToken:l.accessToken}).catch(()=>null);s.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:e&&e.installed.length>0?e.installed.join(`, `):`none detected`}:t))}else s.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await Zn(o.cwd,f,s),s.setTasks(e=>e.map(e=>e.id===`verify`?{...e,status:`done`}:e)),s.setSandboxStats?.({reads:1,writes:e.installed.length,rounds:0}),await Z(o,f,s),s.setPhase(`install-complete`);return}s.setLiveLine(`Custom Next.js structure — handing off to the AI agent…`)}let m=a.id===`plain-html`;if(m){s.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`}]),s.setLiveLine(`Plain HTML — using fast install path (no AI needed)…`);let e=await Kt({cwd:o.cwd,trackingCode:f,updateOnly:p.recommendation===`update-tracking-code`});if(e.installed.length===0&&e.errors.length===0&&e.skipped.length===0)throw Error(`No .html files with a <head>...</head> block were found to inject the tracker into.`);if(e.installed.length===0&&e.errors.length>0)throw Error(`Programmatic install failed for all ${e.errors.length} file(s). First error: ${e.errors[0].file}: ${e.errors[0].error}`);s.setTasks(t=>t.map(t=>t.id===`read`||t.id===`write`?{...t,status:`done`,detail:`${e.installed.length} file(s)`}:t)),s.setLiveLine(`Tracker added to ${e.installed.length} file(s). Skipped ${e.skipped.length}, errored ${e.errors.length}.`);let t=await W(o.cwd,{[a.envVarName]:f});if(s.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${t.addedKeys.length} key(s) added`}:e)),!o.skipMcp&&l){let e=await G({accessToken:l.accessToken}).catch(()=>null);s.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:e&&e.installed.length>0?e.installed.join(`, `):`none detected`}:t))}else s.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await Zn(o.cwd,f,s),s.setSandboxStats?.({reads:e.installed.length,writes:e.installed.length,rounds:0}),await Z(o,f,s),s.setPhase(`install-complete`);return}{let e=await tn({cwd:o.cwd,trackingCode:f,siteId:r.id,adapter:a}),t=e.skipped.some(e=>/already present/.test(e.reason));if(!e.fellThrough&&e.errors.length===0&&(e.installed.length>0||t)){s.setTasks([{id:`detect`,label:`Detect framework`,status:`done`,detail:a.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`}]),s.setLiveLine(`${a.displayName} — using fast install path (no AI needed)…`);let t=await W(o.cwd,{[a.envVarName]:f});if(s.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${t.addedKeys.length} key(s) added`}:e)),!o.skipMcp&&l){let e=await G({accessToken:l.accessToken}).catch(()=>null);s.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:e&&e.installed.length>0?e.installed.join(`, `):`none detected`}:t))}else s.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await Zn(o.cwd,f,s),s.setTasks(e=>e.map(e=>e.id===`verify`?{...e,status:`done`}:e)),s.setSandboxStats?.({reads:1,writes:e.installed.length,rounds:0}),await Z(o,f,s),s.setPhase(`install-complete`);return}s.setLiveLine(`${a.displayName} — handing off to the AI agent…`)}let h=a.buildSnippets({trackingCode:f,siteId:r.id}),g=`Install Zenovay tracking into this ${a.displayName} project.\nSite: ${r.name} (trackingCode: ${f}).\n1. Call detect_framework to confirm the framework.\n2. Read the entry file(s) for this framework:\n`+a.files.map(e=>` - ${e.path}`).join(`
|
|
309
|
+
`)+`
|
|
310
|
+
3. Insert the tracker using the snippet below.
|
|
311
|
+
4. Confirm the change with a diff before writing.
|
|
312
|
+
|
|
313
|
+
Snippet reference (anchored by anchorKind — adapt to the actual file):
|
|
314
|
+
`+h.map(e=>` ${e.anchorKind} @ ${e.targetPath}:\n ${e.code.replace(/\n/g,`
|
|
315
|
+
`)}`).join(`
|
|
316
|
+
|
|
317
|
+
`);s.setTasks([{id:`detect`,label:`Detect framework`,status:`active`},{id:`read`,label:`Read project entry files`,status:`pending`},{id:`write`,label:`Insert tracker snippet`,status:`pending`},{id:`env`,label:`Write env vars (.env.local)`,status:`pending`},{id:`mcp`,label:`Install MCP clients (Claude Code/Cursor/VS Code)`,status:`pending`},{id:`verify`,label:`Wait for first event`,status:`pending`}]);let _=(e,t,n)=>{s.setTasks(r=>r.map(r=>r.id===e?{...r,status:t,detail:n??r.detail}:r))},v=Fn({mode:Pn(o)});s.registerBridge(v);let y=v.subscribe(e=>s.setPendingApproval(e)),b=null,x=``,S=0;try{await Ut({api:u,sandbox:d,approval:v,prompter:{async ask({question:e}){return e}},handlers:{onToolStart:({name:e})=>{e===`detect_framework`?(_(`detect`,`active`),s.setLiveLine(`Inspecting package.json + config files…`)):e===`read_file`?(_(`detect`,`done`),_(`read`,`active`)):(e===`write_file`||e===`patch_file`)&&(_(`read`,`done`),_(`write`,`active`))},onToolResult:({name:e,result:t})=>{let n=t?.ok!==!1,r=t?.content??{};e===`detect_framework`&&n&&(_(`detect`,`done`,a.displayName),s.setLiveLine(`Detected ${a.displayName}`)),e===`read_file`&&n&&r.path&&s.setLiveLine(`Read ${r.path}`),(e===`write_file`||e===`patch_file`)&&n&&r.path&&(_(`read`,`done`),_(`write`,`done`,`wrote ${r.path}`),s.setLiveLine(`Wrote ${r.path}`))},onDelta:e=>{x=(x+e).slice(-600);let t=Date.now();if(t-S<280)return;S=t;let n=x.replace(/\s+/g,` `).trim().slice(-80);n.length>4&&s.setLiveLine(n)}},initialMessages:[{role:`user`,content:g}],diagnosis:p,targetTrackingCode:f})}catch(e){b=e}finally{y(),s.setPendingApproval(null)}let C=d.stats();if(C.writes===0){let e=b?`Agent error: ${b.message}`:`Agent returned without writing any files (${C.reads} reads, ${C.rounds} rounds). The model may have refused or the AI Gateway may be misconfigured. Check api.zenovay.com logs.`;throw Error(e)}let w=a.files.map(e=>e.path),T=C.writtenPaths.some(e=>w.some(t=>e===t||e.endsWith(`/${t}`)));if(!T)throw Error(`Agent wrote to: [${C.writtenPaths.join(`, `)}] but never modified the framework's tracker target file(s): [${w.join(`, `)}]. The tracker is NOT installed. The model likely put the trackingCode into .env.local instead of into the HTML/JSX entry file.`);_(`write`,`done`),_(`env`,`active`),s.setLiveLine(`Adding env var to .env.local`);let E=await W(o.cwd,{[a.envVarName]:f});if(_(`env`,`done`,`${E.addedKeys.length} key(s) added`),!o.skipMcp&&l){_(`mcp`,`active`),s.setLiveLine(`Detecting Cursor / Claude Desktop / VS Code…`);let e=await G({accessToken:l.accessToken}).catch(()=>null);e&&e.installed.length>0?_(`mcp`,`done`,e.installed.join(`, `)):_(`mcp`,`done`,`none detected`)}else _(`mcp`,`done`,`skipped`);s.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:e.status===`pending`?`done`:e.status}:e)),await Zn(o.cwd,f,s),s.setSandboxStats?.(C),await Z(o,f,s),s.setPhase(`install-complete`)}catch(e){s.setErrorMsg(e.message),s.setPhase(`error`)}}const $n=()=>{let{theme:e}=m();return A.createElement(p,{title:`Zenovay wants to set up your project`,state:`idle`},A.createElement(D,null,`We'll use AI to analyze your codebase and add the Zenovay tracker.`),A.createElement(D,{color:e.muted},`.env* contents stay on your machine. Only framework metadata reaches api.zenovay.com.`))},er=({siteName:e,note:t,onChoose:n})=>{let{theme:r}=m(),i=[{label:`Cloudflare Pages`,value:`cloudflare-pages`,description:`writes functions/_z/[[path]].ts`},{label:`Vercel`,value:`vercel`,description:`adds a vercel.json rewrite`},{label:`Netlify`,value:`netlify`,description:`adds a _redirects rule`},{label:`Next.js (self-hosted)`,value:`nextjs-server`,description:`adds a next.config rewrite`},{label:`Skip — standard tracking only`,value:`skip`,description:`already works in Chrome, Firefox and most browsers`}];return A.createElement(E,{flexDirection:`column`,paddingX:2,paddingTop:1},A.createElement(D,{bold:!0},`Count visitors in every browser?`),t?A.createElement(D,{color:r.warn},t):null,A.createElement(D,{color:r.muted},`Your tracker already works. Safari, Edge and Brave block analytics loaded from another domain — serving Zenovay from your own domain fixes that. Where is `,e,` deployed?`),A.createElement(E,{marginTop:1},A.createElement(_,{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}=m(),u=process.stdout.columns??100,d=(process.stdout.rows??30)-8,f=Math.floor(u/2)-1,p=Math.max(14,d);return A.createElement(E,{flexDirection:`column`},A.createElement(E,{flexDirection:`row`,minHeight:p,borderStyle:`round`,borderColor:l.border},A.createElement(E,{width:f,flexDirection:`column`},A.createElement(Un,{width:f,height:p})),A.createElement(E,{width:1,flexDirection:`column`},A.createElement(D,{color:l.border},`│`)),A.createElement(E,{width:f,flexDirection:`column`},i?A.createElement(E,{flexDirection:`column`,paddingX:2,paddingTop:1},A.createElement(D,{color:l.warn},`The agent wants to write `,i.path),i.reason?A.createElement(D,{color:l.muted},i.reason):null,A.createElement(h,{key:i.id,filePath:i.path,oldContent:i.oldContent,newContent:i.newContent,onApprove:a})):o&&c?A.createElement(er,{siteName:t.name,note:s,onChoose:c}):A.createElement(A.Fragment,null,A.createElement(E,{paddingX:2,paddingTop:1},A.createElement(g,{done:n.filter(e=>e.status===`done`).length,total:n.length,label:n.find(e=>e.status===`active`)?.label})),A.createElement(Kn,{tasks:n,liveLine:r,width:f,height:p})))),A.createElement(E,{marginTop:1},A.createElement(D,{color:l.muted},`Site: `,t.name,` · code: `,t.trackingCode??t.id,` · Framework: `,e.displayName)))},nr=({site:e,onContinue:t,onExit:n})=>{let{theme:r}=m();O((e,r)=>{if(e===`q`||r.escape){n();return}if(e===`r`||e===`R`){t();return}});let i=e.url.replace(/^https?:\/\//,``).replace(/\/$/,``);return A.createElement(p,{title:`Already installed`,state:`ok`},A.createElement(E,{flexDirection:`column`,gap:1},A.createElement(E,{flexDirection:`row`,gap:1},A.createElement(D,{color:r.success},`✓`),A.createElement(D,{bold:!0},e.name),A.createElement(D,{color:r.muted},`(`,i,`)`)),A.createElement(D,{color:r.muted},`Zenovay is already tracking this project. No changes needed.`),e.trackingCode?A.createElement(D,{color:r.dim},`tracking code: `,e.trackingCode):null))},rr=({sites:e,preselectHint:t,onPick:n})=>{let r=_r(e,t),i=e.filter(e=>e.id!==r?.id),a=r?[r,...i]:i,o=[...a.map(e=>({label:hr(e,e.id===r?.id),value:e,description:e.trackingCode?`trackingCode: ${e.trackingCode}`:void 0})),{label:`+ Create new site on app.zenovay.com`,value:`create-new`,description:`Open the dashboard to add a new website`}];return A.createElement(p,{title:t?`Pick a site (best match: ${t})`:`Pick a site`,state:`idle`},A.createElement(_,{items:o,onSelect:n}))};function ir(){let e=process.argv[1]??``;return e.includes(`/_npx/`)||e.includes(`\\_npx\\`)||process.env.npm_execpath?.includes(`npx`)?`npx`:`global`}const Q=({k:e,primary:t})=>{let{theme:n}=m();return A.createElement(D,null,A.createElement(D,{color:n.muted},`[`),A.createElement(D,{bold:!0,color:t?n.accent:n.fg},e),A.createElement(D,{color:n.muted},`] `))},ar=({adapter:e,site:t,stats:n,arrived:i,firstParty:a,onPick:o})=>{let{theme:c}=m(),l=ir(),u=l===`npx`?`npx @zenovay/cli`:`zenovay`,d=r(t),f=n&&n.rounds>0?`${n.writes} file(s) · ${n.rounds} agent round(s)`:n&&n.writes>0?`${n.writes} file(s) · programmatic (no AI calls)`:null;return O((e,t)=>{let n=e.toLowerCase();n===`w`||t.return?o(`watch`):n===`o`?s(d).catch(()=>void 0):n===`e`?o(`events`):(n===`s`||n===`q`||t.escape)&&o(`quit`)},{isActive:!0}),A.createElement(p,{title:`You're live on Zenovay`,state:`ok`},A.createElement(D,{bold:!0,color:c.success},i?`✓ First event received from ${t.name}`:`✓ Installed successfully`),A.createElement(D,{color:c.accent},`─`.repeat(18)),A.createElement(E,{marginTop:1,flexDirection:`column`},A.createElement(X,{label:`Framework`,value:e.displayName}),A.createElement(X,{label:`Site`,value:A.createElement(Nn,{url:t.url,label:t.name})}),t.trackingCode?A.createElement(X,{label:`Tracker`,value:A.createElement(D,{color:c.muted},t.trackingCode)}):null,f?A.createElement(X,{label:`Changes`,value:A.createElement(D,{color:c.muted},f)}):null,A.createElement(X,{label:`Dashboard`,value:A.createElement(Nn,{url:d})})),a&&a.proxyFile&&a.proxyAction!==`manual`&&a.proxyAction!==`skipped`?A.createElement(E,{marginTop:1},A.createElement(D,{color:c.success},`✓ `),A.createElement(D,{color:c.muted},`Analytics now load from your own domain — after you deploy, Safari, Edge and Brave visitors are counted too.`)):a?.manual?A.createElement(E,{marginTop:1,flexDirection:`column`},A.createElement(D,{color:c.muted},`Counting visitors in every browser (optional):`),A.createElement(D,{color:c.muted},` `,a.manual)):null,A.createElement(E,{marginTop:1,flexDirection:`column`},A.createElement(D,{color:c.dim},`WHAT'S NEXT`),A.createElement(E,{marginTop:1},A.createElement(D,null,` `),A.createElement(Q,{k:`W`,primary:!0}),A.createElement(D,null,`Watch live in this terminal `),A.createElement(D,{color:c.muted},`— visitors, pages, sources, vitals`)),A.createElement(E,null,A.createElement(D,null,` `),A.createElement(Q,{k:`O`}),A.createElement(D,null,`Open the dashboard in your browser`)),A.createElement(E,null,A.createElement(D,null,` `),A.createElement(Q,{k:`E`}),A.createElement(D,null,`Stream events as they fire `),A.createElement(D,{color:c.muted},`— page views, custom events, live`)),A.createElement(E,null,A.createElement(D,null,` `),A.createElement(Q,{k:`S`}),A.createElement(D,null,`Exit to shell`))),l===`npx`?A.createElement(E,{marginTop:1,flexDirection:`column`,borderStyle:`single`,borderColor:c.warn,paddingX:1},A.createElement(D,{color:c.warn,bold:!0},`Heads up — you ran via npx`),A.createElement(D,{color:c.muted},"The `zenovay` command isn't on your PATH yet. After you exit, run:"),A.createElement(E,{marginTop:1},A.createElement(D,{color:c.fg},` npm i -g @zenovay/cli `),A.createElement(D,{color:c.muted},"→ then `zenovay overview` works directly"))):A.createElement(E,{marginTop:1},A.createElement(D,{color:c.muted},`From your shell: `),A.createElement(D,{color:c.fg},u,` overview`),A.createElement(D,{color:c.muted},` · `),A.createElement(D,{color:c.fg},u,` --help`)))},or=({adapter:e,site:t,stats:n,verify:r,firstParty:i,onCommit:a,onSkipCommit:o})=>{let{theme:s}=m();return pr(e=>{e===`y`||e===`Y`||e===`\r`?a():(e===`n`||e===`N`||e===`s`||e===`S`)&&o()}),A.createElement(p,{title:`Tracker installed`,state:r&&!r.ok?`warn`:`ok`},r?A.createElement(D,null,A.createElement(D,{color:r.ok?s.success:s.warn},r.ok?`✔ Verified — `:`⚠ `),r.detail):A.createElement(D,null,A.createElement(D,{color:s.success},`✔ `),`The Zenovay tracker is in your project.`),A.createElement(E,{marginTop:1},A.createElement(D,{color:s.muted},`Framework: `),A.createElement(D,null,e.displayName)),A.createElement(E,null,A.createElement(D,{color:s.muted},`Site: `),A.createElement(D,null,t.name,` (`,t.url,`)`)),n&&A.createElement(E,null,A.createElement(D,{color:s.muted},`Modified: `),A.createElement(D,null,n.writes,` file(s)`)),A.createElement(sr,{firstParty:i}),A.createElement(E,{marginTop:1},A.createElement(D,null,`Commit + push these changes to git? `),A.createElement(D,{color:s.accent},`[Y/n]`)))},sr=({firstParty:e})=>{let{theme:t}=m();if(!e)return null;let n=e.proxyFile&&e.proxyAction!==`manual`&&e.proxyAction!==`skipped`;return n?A.createElement(E,{marginTop:1,flexDirection:`column`},A.createElement(E,null,A.createElement(D,{color:t.success},`✔ `),A.createElement(D,null,`Analytics now load from your own domain `),A.createElement(D,{color:t.muted},`(`,e.proxyFile,`)`)),A.createElement(D,{color:t.muted},`After you deploy, Safari, Edge and Brave visitors are counted too.`)):e.manual?A.createElement(E,{marginTop:1,flexDirection:`column`},A.createElement(E,null,A.createElement(D,{color:t.muted},`Counting visitors in every browser (optional):`)),A.createElement(D,{color:t.muted},e.manual)):null},cr=({cwd:e,onDone:t,onError:n})=>{let{theme:r}=m(),[i,a]=M(`committing`),[o,s]=M(`Staging changes…`);return j(()=>{(async()=>{try{let n=await mr(e,e=>s(e),e=>a(e));n.committed?s(`Pushed ${n.shortSha} to origin/${n.branch}`):s(`No changes to commit (already up-to-date).`),setTimeout(()=>t(n),800)}catch(e){n(e.message)}})()},[]),A.createElement(p,{title:`Committing to git`,state:`busy`},A.createElement(E,null,A.createElement(D,{color:r.accent},A.createElement(P,{type:`dots`})),A.createElement(D,null,` `,i===`pushing`?`Pushing to origin`:`Committing`,`…`)),A.createElement(E,{marginTop:1},A.createElement(D,{color:r.muted},o)))},lr=({site:e,onDeployed:t,onSkip:n})=>{let{theme:r}=m();return pr(e=>{e===`y`||e===`Y`||e===`\r`||e===`d`||e===`D`?t():(e===`n`||e===`N`||e===`s`||e===`S`)&&n()}),A.createElement(p,{title:`Ready to deploy?`,state:`idle`},A.createElement(D,null,`The tracker is installed locally. To capture events you need it on the live site:`),A.createElement(D,null,` `),A.createElement(E,null,A.createElement(D,{color:r.muted},` → `),A.createElement(Nn,{url:e.url})),A.createElement(D,null,` `),A.createElement(D,{color:r.muted},`Push the change through your normal deploy pipeline (Vercel auto-deploy, CI/CD, etc.).`),A.createElement(E,{marginTop:1},A.createElement(D,null,`Once it's deployed, press `),A.createElement(D,{color:r.accent},`[Y]`),A.createElement(D,null,` to verify the tracker is firing. `),A.createElement(D,{color:r.muted},`[s] skip verification`)))},ur=({site:e,onContinue:t})=>{let{theme:n}=m();return pr(()=>t()),A.createElement(p,{title:`Visit your site`,state:`idle`},A.createElement(D,null,`To send a test event, open any page on your site:`),A.createElement(D,null,` `),A.createElement(E,null,A.createElement(D,{color:n.muted},` → `),A.createElement(Nn,{url:e.url})),A.createElement(D,null,` `),A.createElement(D,{color:n.muted},`The tracker fires automatically on page load. We'll verify the next event arrives.`),A.createElement(E,{marginTop:1},A.createElement(D,null,`Press `),A.createElement(D,{color:n.accent},`[any key]`),A.createElement(D,null,` when you've visited the page.`)))};async function dr(e,t){try{let n=await fetch(e,{headers:{"User-Agent":`zenovay-cli/preflight`},signal:AbortSignal.timeout(8e3),redirect:`follow`});if(!n.ok)return{state:`tracker-missing`,httpStatus:n.status};let r=await n.text(),i=/<script[^>]*src\s*=\s*["']https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+["'][^>]*>\s*<\/script>/gi,a=/data-id\s*=\s*["'](ZV_[A-Za-z0-9]+)["']/i,o=r.match(i)??[];if(o.length===0)return{state:`tracker-missing`};let s=Array.from(new Set(o.map(e=>e.match(a)?.[1]).filter(e=>!!e)));return s.includes(t)?{state:`tracker-correct`}:{state:`tracker-wrong-id`,foundCodes:s}}catch(e){return{state:`tracker-missing`,networkError:e.message}}}const fr=({site:t,elapsed:r,onTick:a,onArrived:o,onTimeout:s})=>{let{theme:c}=m(),[l,u]=M(`preflight`),[d,f]=M(``),[h,g]=M([]),_=ne(!1),v=t.trackingCode??t.id,y=async()=>{u(`preflight`),f(`Fetching ${t.url}…`);let e=await dr(t.url,v);if(!_.current){if(e.state===`tracker-correct`){u(`polling`),f(`Tracker detected on live site — waiting for first hit…`),b();return}if(e.state===`tracker-wrong-id`){u(`wrong-id-on-live`),g(e.foundCodes),f(`Live site has Zenovay but with id(s): ${e.foundCodes.join(`, `)}`);return}u(`awaiting-deploy`),f(e.networkError?`Couldn't reach ${t.url}: ${e.networkError}`:e.httpStatus?`${t.url} returned HTTP ${e.httpStatus}`:`No Zenovay tracker found on ${t.url}.`)}},b=async()=>{let r=Date.now()-10*60*1e3;try{let s=await e(),c=await i({strict:!1}),l=new n({config:s,cliVersion:`0`,token:c}),d=await Mt(t.id,r,{api:l,timeoutMs:6e4,pollIntervalMs:2500,onTick:e=>{_.current||a(e)}});if(_.current)return;d.received?(u(`success`),o()):u(`timeout`)}catch{_.current||u(`timeout`)}};j(()=>(_.current=!1,y(),()=>{_.current=!0}),[]),O(e=>{(l===`awaiting-deploy`||l===`wrong-id-on-live`||l===`timeout`)&&(e===`r`||e===`R`?y():(e===`s`||e===`S`)&&s())},{isActive:!0});let x=Math.floor(r/1e3);return l===`preflight`?A.createElement(p,{title:`Verifying`,state:`busy`},A.createElement(E,null,A.createElement(D,{color:c.accent},A.createElement(P,{type:`dots`})),A.createElement(D,null,` Checking your live site for the tracker…`)),A.createElement(E,{marginTop:1},A.createElement(D,{color:c.muted},d))):l===`awaiting-deploy`?A.createElement(p,{title:`Tracker not yet on your live site`,state:`warn`},A.createElement(D,{color:c.warn},d),A.createElement(E,{marginTop:1,flexDirection:`column`},A.createElement(D,null,`The tracker is in your local repo but hasn't been deployed yet.`),A.createElement(D,{color:c.muted},`Push your changes and wait for your deploy to finish (Vercel / Cloudflare Pages / CI), then retry.`)),A.createElement(E,{marginTop:1},A.createElement(D,null,`Press `),A.createElement(D,{color:c.accent},`[r]`),A.createElement(D,null,` to re-check, `),A.createElement(D,{color:c.accent},`[s]`),A.createElement(D,null,` to skip verification.`))):l===`wrong-id-on-live`?A.createElement(p,{title:`Live site has a different tracking code`,state:`warn`},A.createElement(D,{color:c.warn},`Expected: `,A.createElement(D,{color:c.accent},v),` `,`Found on live: `,A.createElement(D,{color:c.accent},h.join(`, `))),A.createElement(E,{marginTop:1,flexDirection:`column`},A.createElement(D,null,`Your local install uses a different ID than what's on `,t.url,`.`),A.createElement(D,{color:c.muted},`Deploy the new local version, then retry — or skip if the existing ID is intentional.`)),A.createElement(E,{marginTop:1},A.createElement(D,null,`Press `),A.createElement(D,{color:c.accent},`[r]`),A.createElement(D,null,` to re-check, `),A.createElement(D,{color:c.accent},`[s]`),A.createElement(D,null,` to skip.`))):l===`timeout`?A.createElement(p,{title:`No event arrived in 3 minutes`,state:`warn`},A.createElement(D,{color:c.warn},`The tracker is on your live site but no hits reached api.zenovay.com.`),A.createElement(E,{marginTop:1},A.createElement(D,{color:c.muted},`Try opening `,t.url,` in a fresh browser tab (no ad-blocker), then retry.`)),A.createElement(E,{marginTop:1},A.createElement(D,null,`Press `),A.createElement(D,{color:c.accent},`[r]`),A.createElement(D,null,` to re-check, `),A.createElement(D,{color:c.accent},`[s]`),A.createElement(D,null,` to finish without verification.`))):A.createElement(p,{title:`Waiting for first event`,state:`busy`},A.createElement(E,null,A.createElement(D,{color:c.accent},A.createElement(P,{type:`dots`})),A.createElement(D,null,` Polling api.zenovay.com for the first hit on `),A.createElement(D,{color:c.accent},t.url),A.createElement(D,null,` (`,x,`s elapsed)`)),A.createElement(E,{marginTop:1},A.createElement(D,{color:c.muted},`Reload the page if nothing arrives within ~30 seconds.`)))};function pr(e){O((t,n)=>{e(t,{return:n.return,escape:n.escape})},{isActive:!0})}async function mr(e,t,n){let{execFile:r}=await import(`node:child_process`),{promisify:i}=await import(`node:util`),a=i(r),o=async(t,n)=>{let{stdout:r}=await a(t,n,{cwd:e,maxBuffer:4e6});return r.trim()};try{await o(`git`,[`rev-parse`,`--is-inside-work-tree`])}catch{return t(`Not a git repository — skipped.`),{committed:!1}}let s=await o(`git`,[`status`,`--porcelain`]);if(!s)return{committed:!1};t(`Staging tracker changes…`),await o(`git`,[`add`,`-A`]),t(`Creating commit…`),await o(`git`,[`commit`,`-m`,`chore(zenovay): install tracking script via @zenovay/cli`]);let c=await o(`git`,[`rev-parse`,`--short`,`HEAD`]),l=await o(`git`,[`rev-parse`,`--abbrev-ref`,`HEAD`]);n(`pushing`),t(`Pushing to origin/${l}…`);try{await o(`git`,[`push`,`origin`,l])}catch(e){return t(`Commit ${c} created locally; push failed (${e.message.slice(0,80)}). Push manually with: git push origin ${l}`),{committed:!0,shortSha:c,branch:l}}return n(`done`),{committed:!0,shortSha:c,branch:l}}function hr(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 gr(e){try{let t=await x.readFile(b.join(e,`package.json`),`utf8`),n=JSON.parse(t);if(n.name)return String(n.name).replace(/^@[^/]+\//,``)}catch{}try{let t=await x.readFile(b.join(e,`.git`,`config`),`utf8`),n=t.match(/url\s*=\s*.*[/:]([^/]+?)(?:\.git)?\s*$/m);if(n&&n[1])return n[1]}catch{}return b.basename(e)}function _r(e,t){if(!t||e.length===0)return e[0]??null;let n=$(t),r=e.find(e=>$(e.name)===n);if(r)return r;let i=e.find(e=>{let t=e.url.replace(/^https?:\/\//,``).replace(/\/.*$/,``),[r]=t.split(`.`);return $(r??``)===n});if(i)return i;let a=e.find(e=>{let t=$(e.name),r=$(e.url);return t.includes(n)||r.includes(n)||n.includes(t)||n.includes(r)});return a??e[0]??null}function $(e){return e.toLowerCase().replace(/[^a-z0-9]/g,``)}export{er as HostChoicePanel,de as detectInstalled,qn as initCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./config-JVhBplSX.js";import"./api-ZZ3ZdI85.js";import"./token-store-RBywEspd.js";import{HostChoicePanel as e,initCommand as t}from"./init-BgOgQYOa.js";import"./formatter-DutfcQAc.js";import"./emit-DBYk96TD.js";import"./open-url-DHEOtfXN.js";import"./secrets-BGNbID-c.js";import"./client-DkVqZ_Bu.js";import"./login-BWCq8ufH.js";import"./theme-DOR-SSzW.js";import"./panel-B9_Bd2So.js";import"./progress-row-DDyaTQK9.js";import"./prompt-CPA77m_S.js";import"./keybar-BWZ9d4xa.js";import"./sparkline-8ucKVUV7.js";export{t as initCommand};
|