@zenovay/cli 1.0.25 → 1.0.26
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/{ai-CxT9VLDB.js → ai-SE5JnMDQ.js} +1 -1
- package/dist/bin.js +3 -3
- package/dist/init-B9onI_od.js +1 -0
- package/dist/init-C6wegGPC.js +357 -0
- package/dist/wizard-bin.js +1 -1
- package/package.json +1 -1
- package/dist/init-BPlqfuUi.js +0 -357
- package/dist/init-lFYuHty4.js +0 -1
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import{readConfig as e,updateConfig as t}from"./config-JVhBplSX.js";import{ApiClient as n,completionUrlForVerifiedSetup as r,dashboardUrlForSite as i}from"./api-CBukwv2I.js";import{readToken as a}from"./token-store-CuZEiQNg.js";import{diagnoseInstall as o}from"./detect-installed-DpSaAeH-.js";import{emit$1 as s,isHeadless as c}from"./emit-5vELQfsB.js";import{openInBrowser as l}from"./open-url-IjqD5f_n.js";import{scrubSecrets as u}from"./secrets-zGZxXoM0.js";import{parseSseStream as d}from"./client-DNMRt-Hq.js";import{swapToFirstPartySnippet as f}from"./snippet-CwowVrmh.js";import{loginCommand as p,maybeInstallCompletions as m}from"./login-vzW-8q0w.js";import{Banner as h,Panel as g,useTheme as _}from"./panel-DbiZwGB3.js";import{DiffView as v,ProgressRow as y}from"./progress-row-BSv_Zm8f.js";import{Select as b}from"./prompt-Dae2nnYJ.js";import{Keybar as ee}from"./keybar-BY1csJGI.js";import{spark as x}from"./sparkline-B7VaYaxH.js";import{execFile as S}from"node:child_process";import C from"node:path";import{promises as w}from"node:fs";import{z as T}from"zod";import E from"node:os";import D from"node:crypto";import{ulid as O}from"ulid";import{Box as k,Text as A,render as te,useApp as ne,useInput as re}from"ink";import j from"node:fs/promises";import M,{useEffect as N,useRef as P,useState as F}from"react";import{globby as ie}from"globby";import I from"ink-spinner";import{applyPatch as ae}from"diff";import{promisify as oe}from"node:util";const se=[/^(src\/)?app\/(.*\/)?layout\.(tsx|ts|jsx|js)$/,/^(src\/)?app\/root\.(tsx|ts|jsx|js)$/,/^(src\/)?pages\/(_app|_document)\.(tsx|ts|jsx|js)$/,/^src\/layouts\/.*\.(astro|svelte|vue)$/,/^src\/pages\/index\.astro$/,/^(src\/)?components\/.*\.(astro|svelte|vue|tsx|jsx|ts|js)$/,/^src\/routes\/\+layout\.(svelte|ts|js)$/,/^src\/routes\/root\..*$/,/^src\/(root|entry-server|entry-client)\.(tsx|ts|jsx|js)$/,/^src\/main\.(tsx|ts|jsx|js)$/,/^src\/App\.(tsx|ts|jsx|js|svelte|vue)$/,/^gatsby-(ssr|browser|config)\.(js|ts|mjs)$/,/^(next|nuxt|vite|astro|remix|svelte|tailwind|postcss)\.config\.(ts|mts|cts|js|mjs|cjs)$/,/^plugins\/.*\.(ts|js)$/,/^index\.html?$/,/^src\/index\.html?$/],ce=[/(^|\/)\.env($|\.(?!example$)[^/]+$)/,/(^|\/)\.git(\/|$)/,/(^|\/)node_modules\//,/(^|\/)\.ssh\//,/(^|\/)\.aws\//,/\.pem$/,/\.key$/,/(^|\/)id_rsa($|\.)/,/(^|\/)\.npmrc$/,/(^|\/)credentials(\.|$)/],L=256*1024,le=20,R=20,ue=20;var z=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`SandboxError`}};const B=/<script[^>]*src\s*=\s*["'](?:https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+|[^"']*\/_z\/script\.js[^"']*)["'][^>]*>\s*<\/script>/i,de=[{name:`PostHog`,re:/posthog\.com\b|posthog-js|window\.posthog/i},{name:`Plausible`,re:/plausible\.io\/js|window\.plausible/i},{name:`Google Analytics`,re:/googletagmanager\.com\/gtag\/js|google-analytics\.com\/analytics\.js|window\.gtag\b/i},{name:`Mixpanel`,re:/cdn\.mxpnl\.com|mixpanel-browser/i},{name:`Segment`,re:/cdn\.segment\.com\/analytics\.js|window\.analytics\b/i},{name:`Hotjar`,re:/static\.hotjar\.com|\(h,o,t,j,a,r\)/i},{name:`Amplitude`,re:/cdn\.amplitude\.com|amplitude\.getInstance/i},{name:`Heap`,re:/cdn\.heapanalytics\.com/i},{name:`FullStory`,re:/fullstory\.com\/s\/fs\.js|window\.FS\.identify/i}];var V=class{sessionId;cwd;cwdReal;undoRoot;readCount=0;writeCount=0;roundCount=0;writtenPathsSet=new Set;prunedOnce=!1;journaledPaths=new Map;constructor(e){this.sessionId=e.sessionId??O(),this.cwd=e.cwd,this.cwdReal=w.realpath(e.cwd),this.undoRoot=e.undoRoot??C.join(E.homedir(),`.zenovay`,`undo`)}incrementRound(){if(this.roundCount++,this.roundCount>ue)throw new z(`round-cap`,`Tool-call recursion cap (${ue}) exceeded.`)}stats(){return{sessionId:this.sessionId,reads:this.readCount,writes:this.writeCount,rounds:this.roundCount,writtenPaths:[...this.writtenPathsSet]}}async resolveForRead(e){return this.resolveSafe(e,`read`)}async resolveForWrite(e){return this.resolveSafe(e,`write`)}async journalTrustedWrite(e){if(typeof e!=`string`||e.length===0||e.includes(`\0`))throw new z(`escape`,`Journal path must be a non-empty string without null bytes.`);let t=await this.cwdReal,n=C.resolve(t,e),r=[],i=n,a=null;for(;a===null;)try{let e=await w.realpath(i);a=C.join(e,...r.reverse())}catch(t){if(t.code!==`ENOENT`)throw new z(`escape`,`realpath failed: ${t.message}`);try{let t=await w.lstat(i);if(t.isSymbolicLink())throw new z(`escape`,`Unresolved symlink in journal path: ${e}`)}catch(e){if(e instanceof z)throw e;if(e.code!==`ENOENT`)throw new z(`escape`,`lstat failed: ${e.message}`)}let n=C.dirname(i);if(n===i)throw new z(`escape`,`Could not resolve journal path: ${e}`);r.push(C.basename(i)),i=n}if(!this.isWithin(a,t))throw new z(`escape`,`Path escapes cwd: ${e}`);await this.journalBackup(a)}async resolveSafe(e,t){if(typeof e!=`string`||e.length===0)throw new z(`escape`,`Path must be a non-empty string.`);if(e.includes(`\0`))throw new z(`escape`,`Null byte in path.`);if(/^\\\\[?.]\\/.test(e)||/^\\\\[A-Za-z0-9]/.test(e))throw new z(`escape`,`Windows special path prefix: ${e}`);if(/%/.test(e))try{let t=decodeURIComponent(e);if(/%[0-9A-Fa-f]{2}/.test(t))throw new z(`escape`,`Double-encoded path: ${e}`);e=t}catch(t){throw t instanceof z?t:new z(`escape`,`Malformed percent-encoding: ${e}`)}if(e.includes(`\0`))throw new z(`escape`,`Null byte in decoded path.`);if(e.includes(`\\`))throw new z(`escape`,`Backslash in path (Windows-style separator not accepted): ${e}`);let n=await this.cwdReal,r=C.isAbsolute(e)?e:C.join(n,e),i=C.normalize(r),a=i;try{a=await w.realpath(i)}catch(e){if(e.code!==`ENOENT`)throw new z(`escape`,`realpath failed: ${e.message}`);let t=C.dirname(i);try{let e=await w.realpath(t);a=C.join(e,C.basename(i))}catch{}}if(!this.isWithin(a,n))throw new z(`escape`,`Path escapes cwd: ${e}`);let o=C.relative(n,a),s=o.toLowerCase();for(let e of ce)if(e.test(o)||e.test(s)){if(t===`read`&&/(^|\/)node_modules\//i.test(o))continue;throw new z(`blocklisted`,`Path is on the hard blocklist: ${o}`)}if(t===`write`){let e=se.some(e=>e.test(o));if(!e&&!/^\.env(\.local)?$/.test(o)&&!/^\.claude\//.test(o)&&!/^\.cursor\//.test(o))throw new z(`not-allowlisted`,`Write path not on allowlist: ${o}`)}return a}isWithin(e,t){let n=C.relative(t,e);return!n.startsWith(`..`)&&!C.isAbsolute(n)}async safeRead(e){if(this.readCount>=le)throw new z(`read-cap`,`Read cap (${le}) reached.`);let t=await this.resolveForRead(e),n=await w.stat(t);if(n.size>L)throw new z(`too-large`,`File exceeds ${L}B: ${e} (${n.size}B)`);let r=await w.readFile(t),i=r.subarray(0,Math.min(r.length,8192));if(i.includes(0))throw new z(`binary-rejected`,`Binary content in ${e}.`);return this.readCount++,r.toString(`utf8`)}async safeWrite(e,t){if(this.writeCount>=R)throw new z(`write-cap`,`Write cap (${R}) reached.`);if(t.length>L)throw new z(`too-large`,`Write exceeds ${L}B: ${e}`);let n=await this.resolveForWrite(e),r=await w.readFile(n,`utf8`).catch(e=>{if(e.code===`ENOENT`)return null;throw e});if(r!==null){if(B.test(r)&&!B.test(t))throw new z(`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 de)if(i.test(r)&&!i.test(t))throw new z(`destructive-competitor-removal`,`Refusing to write ${e}: existing ${n} tracker would be removed. Zenovay installs alongside competitors — never replace them.`)}let i=await this.journalBackup(n);await w.mkdir(C.dirname(n),{recursive:!0}),await w.writeFile(n,t,`utf8`),this.writeCount++;let a=await this.cwdReal;return this.writtenPathsSet.add(C.relative(a,n)),{backupPath:i}}async journalBackup(e){if(this.journaledPaths.has(e))return this.journaledPaths.get(e)??null;let t=await w.readFile(e).catch(e=>{if(e.code===`ENOENT`)return null;throw e}),n=C.join(this.undoRoot,this.sessionId);await w.mkdir(n,{recursive:!0,mode:448}),this.prunedOnce||(this.prunedOnce=!0,U(this.undoRoot,this.sessionId));let r=D.createHash(`sha256`).update(e).digest(`hex`).slice(0,16),i=C.join(n,`${r}.bak`),a=C.join(n,`manifest.jsonl`);t!==null&&await w.writeFile(i,t,{mode:384});let o=t===null?null:i,s=JSON.stringify({abs:e,backupPath:o,ts:Date.now()});return await w.appendFile(a,s+`
|
|
2
|
+
`,{mode:384}),this.journaledPaths.set(e,o),o}static wrapForModel(e,t){let n=D.createHash(`sha256`).update(t).digest(`hex`).slice(0,16),r=t.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`);return`<FILE path="${e}" sha256="${n}">\n${r}\n</FILE>`}static scrubSecrets(e){return u(e)}};const fe=20;function H(e,t){let n=C.relative(t,e);return n===``||!n.startsWith(`..`)&&!C.isAbsolute(n)}function pe(e){if(!/^[A-Za-z0-9_-]+$/.test(e))throw new z(`escape`,`Invalid undo session id.`)}async function me(e,t){pe(e);let n=await w.realpath(t),r=await w.realpath(C.join(n,e));if(!H(r,n))throw new z(`escape`,`Undo session escapes the undo root.`);let i=await w.realpath(C.join(r,`manifest.jsonl`));if(!H(i,r))throw new z(`escape`,`Undo manifest escapes its session directory.`);let a=await w.readFile(i,`utf8`),o=a.split(`
|
|
3
|
+
`).filter(e=>e.trim().length>0).map(e=>{let t=JSON.parse(e);if(typeof t.abs!=`string`||!C.isAbsolute(t.abs)||t.backupPath!==null&&typeof t.backupPath!=`string`)throw new z(`escape`,`Undo manifest contains an invalid path entry.`);return{abs:C.resolve(t.abs),backupPath:t.backupPath}});return{entries:o,sessionDir:r}}async function he(e,t){let n=e,r=[];for(;;)try{let i=await w.realpath(n),a=C.join(i,...r.reverse());if(!H(a,t))throw new z(`escape`,`Undo target escapes the current project: ${e}`);return a}catch(t){if(t instanceof z||t.code!==`ENOENT`)throw t;let i=C.dirname(n);if(i===n)throw new z(`escape`,`Could not resolve undo target: ${e}`);r.push(C.basename(n)),n=i}}async function ge(e,t,n){let r=n?.undoRoot??C.join(E.homedir(),`.zenovay`,`undo`),i=await w.realpath(t),{entries:a}=await me(e,r);return a.length>0&&a.every(e=>H(e.abs,i))}async function U(e,t,n=fe){try{let r=await w.readdir(e,{withFileTypes:!0}),i=r.filter(e=>e.isDirectory()).map(e=>e.name);if(i.length<=n)return 0;let a=await Promise.all(i.map(async t=>{let n=await w.stat(C.join(e,t)).catch(()=>null);return{name:t,mtime:n?n.mtimeMs:0}}));a.sort((e,t)=>t.mtime-e.mtime);let o=a.slice(n).filter(e=>e.name!==t);return await Promise.all(o.map(t=>w.rm(C.join(e,t.name),{recursive:!0,force:!0}).catch(()=>{}))),o.length}catch{return 0}}async function _e(e,t){let n=t?.undoRoot??C.join(E.homedir(),`.zenovay`,`undo`),r,i;try{({entries:r,sessionDir:i}=await me(e,n))}catch(e){if(e.code===`ENOENT`)return{restored:0};throw e}let a=t?.cwd?await w.realpath(t.cwd):null,o=new Set,s=0;for(let e of r.reverse()){if(o.has(e.abs))continue;o.add(e.abs);let t=a?await he(e.abs,a):e.abs;if(e.backupPath===null)await w.unlink(t).catch(()=>void 0),s++;else{let n=await w.realpath(e.backupPath);if(!H(n,i))throw new z(`escape`,`Undo backup escapes its session directory.`);let r=await w.readFile(n);await w.writeFile(t,r),s++}}return{restored:s}}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 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 W={id:`angular`,displayName:`Angular`,detect:ve,files:[{path:`src/index.html`,kind:`mutate`,required:!0}],envVarName:`NG_ZENOVAY_SITE`,buildSnippets:ye},be=[`astro.config.ts`,`astro.config.mjs`,`astro.config.js`];async function xe(e){for(let t of be)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 Se(e){let t=e.trackingCode??e.siteId??``,n=`<script defer data-id="${t}" src="https://api.zenovay.com/z.js" is:inline></script>`;return[{targetPath:`src/layouts/Layout.astro`,anchorKind:`head-tag`,code:n,description:`Inject the Zenovay tracker inside <head> of the primary layout.`},{targetPath:`src/layouts/BaseHead.astro`,anchorKind:`head-tag`,code:n,description:"Fallback target when the project uses a dedicated `BaseHead.astro`."},{targetPath:`src/pages/index.astro`,anchorKind:`head-tag`,code:n,description:"Fallback for layout-less projects (e.g. the official `create-astro --template minimal` starter keeps the document <head> inline in src/pages/index.astro)."}]}const Ce={id:`astro`,displayName:`Astro`,detect:xe,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:Se};async function we(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 G(e){return await we(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 Te(e){let t=e.trackingCode??e.siteId??``,n=`const React = require('react');
|
|
4
|
+
|
|
5
|
+
exports.onRenderBody = ({ setHeadComponents }) => {
|
|
6
|
+
setHeadComponents([
|
|
7
|
+
React.createElement('script', {
|
|
8
|
+
key: 'zenovay-tracker',
|
|
9
|
+
defer: true,
|
|
10
|
+
'data-id': '${t}',
|
|
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 Ee={id:`gatsby`,displayName:`Gatsby`,detect:G,files:[{path:`gatsby-ssr.js`,kind:`create`,required:!0}],envVarName:`GATSBY_ZENOVAY_SITE`,buildSnippets:Te},K=[`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 De(e){for(let t of K)if(await e.exists(t))return t;return null}async function Oe(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 ke(e){let t=await Oe(e),n=await e.exists(`app`)||await e.exists(`src/app`),r=await De(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 Ae(e,t=`script`){let n=e.targetPath||`app/layout.tsx`,r=e.trackingCode??e.siteId??``;return t===`npm`?Me(n,r):je(n,r)}function je(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
|
+
src="https://api.zenovay.com/z.js"
|
|
19
|
+
strategy="afterInteractive"
|
|
20
|
+
/>
|
|
21
|
+
{children}`,description:`Add the Zenovay tracker <Script> next to children in the root layout.`}]}function Me(e,t){return[{targetPath:`components/zenovay-bootstrap.tsx`,anchorKind:`replace-file`,code:`'use client';
|
|
22
|
+
|
|
23
|
+
import { useEffect } from 'react';
|
|
24
|
+
import { init } from '@zenovay/tracker';
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Mounts the Zenovay tracker exactly once on the client. Equivalent to the
|
|
28
|
+
* canonical <script src="https://api.zenovay.com/z.js"> tag — init() injects
|
|
29
|
+
* the same loader internally.
|
|
30
|
+
*/
|
|
31
|
+
export function ZenovayBootstrap() {
|
|
32
|
+
useEffect(() => {
|
|
33
|
+
init(${JSON.stringify(t)});
|
|
34
|
+
}, []);
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
`,description:`Create a client-component bootstrap that calls init() from @zenovay/tracker.`},{targetPath:e,anchorKind:`after-imports`,code:`import { ZenovayBootstrap } from '@/components/zenovay-bootstrap';`,description:`Import the Zenovay tracker bootstrap into the root layout.`},{targetPath:e,anchorKind:`wrap-children`,code:`<ZenovayBootstrap />
|
|
38
|
+
{children}`,description:`Render the Zenovay tracker bootstrap alongside children in the root layout.`}]}const Ne={id:`next-app-router`,displayName:`Next.js (App Router)`,detect:ke,files:[{path:`app/layout.tsx`,kind:`mutate`,required:!0}],envVarName:`NEXT_PUBLIC_ZENOVAY_SITE`,packageDeps:[`@zenovay/tracker`],supportsNpmMode:!0,buildSnippets:Ae},Pe=[`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 Fe(e){for(let t of Pe)if(await e.exists(t))return t;return null}async function Ie(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 Le(e){let t=await Ie(e);if(!t)return{matched:!1,confidence:0,reason:"package.json does not list `next` as a dependency."};let n=await Fe(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 Re(e){let t=`pages/_app.tsx`,n=e.trackingCode??e.siteId??``,r=`import type { AppProps } from 'next/app';
|
|
39
|
+
import Script from 'next/script';
|
|
40
|
+
|
|
41
|
+
export default function App({ Component, pageProps }: AppProps) {
|
|
42
|
+
return (
|
|
43
|
+
<>
|
|
44
|
+
<Script
|
|
45
|
+
defer
|
|
46
|
+
data-id="${n}"
|
|
47
|
+
src="https://api.zenovay.com/z.js"
|
|
48
|
+
strategy="afterInteractive"
|
|
49
|
+
/>
|
|
50
|
+
<Component {...pageProps} />
|
|
51
|
+
</>
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
`;return[{targetPath:t,anchorKind:`after-imports`,code:`import Script from 'next/script';`,description:"Import next/script in `_app`."},{targetPath:t,anchorKind:`wrap-children`,code:`<><Script defer data-id="${n}" src="https://api.zenovay.com/z.js" strategy="afterInteractive" /><Component {...pageProps} /></>`,description:`Render the Zenovay tracker alongside the page component.`},{targetPath:t,anchorKind:`replace-file`,code:r,description:"Full replacement when `_app` does not exist yet."}]}const ze={id:`next-pages-router`,displayName:`Next.js (Pages Router)`,detect:Le,files:[{path:`pages/_app.tsx`,kind:`mutate`,required:!0}],envVarName:`NEXT_PUBLIC_ZENOVAY_SITE`,buildSnippets:Re},Be=T.object({modules:T.array(T.string()).optional(),runtimeConfig:T.object({public:T.record(T.string(),T.unknown()).optional()}).optional()}).passthrough();async function Ve(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 He(e){let t=e.trackingCode??e.siteId??``,n=` app: {
|
|
55
|
+
head: {
|
|
56
|
+
script: [
|
|
57
|
+
{
|
|
58
|
+
defer: true,
|
|
59
|
+
src: 'https://api.zenovay.com/z.js',
|
|
60
|
+
'data-id': '${t}',
|
|
61
|
+
},
|
|
62
|
+
],
|
|
63
|
+
},
|
|
64
|
+
},`;return[{targetPath:`nuxt.config.ts`,anchorKind:`head-tag`,code:n,description:"Add the Zenovay tracker to Nuxt's `app.head.script` so every page loads it."}]}const Ue={id:`nuxt`,displayName:`Nuxt`,detect:Ve,files:[{path:`nuxt.config.ts`,kind:`mutate`,required:!0}],envVarName:`NUXT_PUBLIC_ZENOVAY_SITE`,buildSnippets:He},We=[`index.html`,`public/index.html`,`dist/index.html`];async function Ge(e){for(let t of We)if(await e.exists(t))return{matched:!0,confidence:.5,reason:`Detected plain HTML project via \`${t}\`.`};let t=await e.glob(`**/*.html`);return t.length>0?{matched:!0,confidence:.3,reason:`Found ${t.length} HTML file(s); plain-HTML adapter is usable as fallback.`}:{matched:!1,confidence:0,reason:`No HTML files found in the project.`}}function Ke(e){let t=e.trackingCode??e.siteId??``,n=`<script defer\n data-id="${t}"\n src="https://api.zenovay.com/z.js">\n</script>`;return[{targetPath:`index.html`,anchorKind:`head-tag`,code:n,description:`Inject the Zenovay tracker inside <head>. Repeat for every HTML file that contains a <head>.`}]}const qe={id:`plain-html`,displayName:`Plain HTML`,detect:Ge,files:[{path:`index.html`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:Ke};async function Je(e){let t=await e.readFile(`package.json`);if(!t)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 Ye(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`src/root.tsx`,r=`<script
|
|
65
|
+
defer
|
|
66
|
+
data-id="${t}"
|
|
67
|
+
src="https://api.zenovay.com/z.js"
|
|
68
|
+
/>`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Add the Zenovay tracker into the <head> of the Qwik root document.`}]}const Xe={id:`qwik`,displayName:`Qwik`,detect:Je,files:[{path:`src/root.tsx`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:Ye};async function Ze(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 Qe(e){let t=e.trackingCode??e.siteId??``;return[{targetPath:`app/root.tsx`,anchorKind:`head-tag`,code:`<script defer data-id="${t}" src="https://api.zenovay.com/z.js"></script>`,description:`Inline the Zenovay tracker <script> inside the document <head>.`}]}const $e={id:`remix`,displayName:`Remix`,detect:Ze,files:[{path:`app/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)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 tt(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`src/entry-server.tsx`,r=`<script
|
|
69
|
+
defer
|
|
70
|
+
data-id="${t}"
|
|
71
|
+
src="https://api.zenovay.com/z.js"
|
|
72
|
+
/>`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Add the Zenovay tracker into the document <head> rendered by SolidStart entry-server.`}]}const nt={id:`solid-start`,displayName:`SolidStart`,detect:et,files:[{path:`src/entry-server.tsx`,kind:`mutate`,required:!0}],envVarName:`VITE_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 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 it(e){let t=e.trackingCode??e.siteId??``,n=`<svelte:head>
|
|
73
|
+
<script defer data-id="${t}" src="https://api.zenovay.com/z.js"></script>
|
|
74
|
+
</svelte:head>
|
|
75
|
+
|
|
76
|
+
<slot />
|
|
77
|
+
`;return[{targetPath:`src/routes/+layout.svelte`,anchorKind:`replace-file`,code:n,description:`Root layout that loads the Zenovay tracker in every route via <svelte:head>.`}]}const at={id:`sveltekit`,displayName:`SvelteKit`,detect:rt,files:[{path:`src/routes/+layout.svelte`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:it},ot=[`next`,`nuxt`,`nuxt3`,`@sveltejs/kit`,`astro`,`@remix-run/react`,`@builder.io/qwik-city`,`@builder.io/qwik`,`@solidjs/start`,`solid-start`,`@angular/core`,`gatsby`],st=[`index.html`,`public/index.html`];async function ct(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 lt(e){for(let t of st)if(await e.exists(t))return t;return null}async function ut(e){let t=await ct(e);if(ot.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 lt(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 dt(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`index.html`,r=`<script defer\n data-id="${t}"\n src="https://api.zenovay.com/z.js">\n</script>`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Inject the Zenovay tracker inside <head> of the Vite entry HTML.`}]}const ft={id:`vite`,displayName:`Vite`,detect:ut,files:[{path:`index.html`,kind:`mutate`,required:!0}],envVarName:`VITE_ZENOVAY_SITE`,buildSnippets:dt},pt=[Ne,ze,Ue,at,Ce,$e,Ee,W,nt,Xe,ft,qe];async function mt(e){let t=[];for(let n of pt){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 ht(e){let t=t=>C.resolve(e,t);return{cwd:e,async readFile(e){try{return await w.readFile(t(e),`utf8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`EISDIR`)return null;throw e}},async exists(e){try{return await w.access(t(e)),!0}catch{return!1}},async glob(t){return ie(t,{cwd:e,dot:!1,gitignore:!0,onlyFiles:!0,followSymbolicLinks:!1})}}}async function gt(e,t){let n=ht(e),{adapter:r,ranked:i}=await mt(n),a=i[0];return r&&a&&a.result.confidence>=.7?r:t?t.pickInteractively(i):r}function _t(e){let t=/[\s"'#=]/.test(e)||e===``,n=t?`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:e;return n}function vt(e,t){return`${e}=${_t(t)}`}async function q(e,t,n={}){let r=n.filename??`.env.local`,i=C.resolve(e,r),a=``,o=!0;try{a=await w.readFile(i,`utf8`)}catch(e){if(e.code===`ENOENT`)o=!1;else throw e}let s=[],c=[],l=[],u=[],d=a;for(let[e,n]of Object.entries(t)){let t=RegExp(`^(\\s*)(export\\s+)?(${e})(\\s*=\\s*)(.*)$`,`gm`),r=!1,i=!1;if(d=d.replace(t,(t,a,o,s,c,l)=>{r=!0;let u=_t(n),d=l.trim();return d===u||!/ZENOVAY/i.test(e)?t:(i=!0,`${a}${o??``}${s}${c}${u}`)}),r){i?c.push(e):l.push(e);continue}u.push(vt(e,n)),s.push(e)}if(s.length===0&&c.length===0)return{file:r,created:!1,existing:o,addedKeys:s,updatedKeys:c,skippedKeys:l};let f=`# Added by Zenovay CLI`,p;if(o&&u.length>0){let e=d.length>0&&!d.endsWith(`
|
|
78
|
+
`);p=d+(e?`
|
|
79
|
+
`:``)+`
|
|
80
|
+
`+f+`
|
|
81
|
+
`+u.join(`
|
|
82
|
+
`)+`
|
|
83
|
+
`}else p=o?d:f+`
|
|
84
|
+
`+u.join(`
|
|
85
|
+
`)+`
|
|
86
|
+
`;if(await n.beforeWrite?.(i),o)await w.writeFile(i,p,`utf8`);else{let e=await w.open(i,`w`,384);try{await e.writeFile(p,`utf8`)}finally{await e.close()}}return{file:r,created:!o,existing:o,addedKeys:s,updatedKeys:c,skippedKeys:l}}const yt=`https://api.zenovay.com/mcp`,bt=T.object({url:T.string().url(),headers:T.record(T.string(),T.string()).optional()}).passthrough(),xt=T.object({mcpServers:T.record(T.string(),bt).optional()}).passthrough();function St(e){return e.HOME??e.USERPROFILE??E.homedir()}function Ct(e){return e.APPDATA??null}function wt(e,t){let n=St(t),r=Ct(t),i=[];return i.push({id:`claude-code`,displayName:`Claude Code`,configPath:C.join(n,`.claude.json`),serversKey:`mcpServers`,includeType:!0}),i.push({id:`cursor`,displayName:`Cursor`,configPath:C.join(n,`.cursor`,`mcp.json`),serversKey:`mcpServers`,includeType:!1}),e===`win32`&&r&&i.push({id:`cursor`,displayName:`Cursor (AppData)`,configPath:C.join(r,`Cursor`,`User`,`globalStorage`,`cursor.mcp`,`mcp.json`),serversKey:`mcpServers`,includeType:!1}),e===`darwin`?i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:C.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`),serversKey:`mcpServers`,includeType:!0}):e===`win32`&&r?i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:C.join(r,`Claude`,`claude_desktop_config.json`),serversKey:`mcpServers`,includeType:!0}):i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:C.join(n,`.config`,`Claude`,`claude_desktop_config.json`),serversKey:`mcpServers`,includeType:!0}),i.push({id:`vscode`,displayName:`VS Code`,configPath:C.join(n,`.vscode`,`mcp.json`),serversKey:`servers`,includeType:!0}),i}async function Tt(e){try{return await w.access(e),!0}catch{return!1}}async function Et(e){try{let t=await w.readFile(e,`utf8`);if(t.trim().length===0)return{};let n=JSON.parse(t),r=xt.safeParse(n);return r.success?r.data:n&&typeof n==`object`?n:{}}catch{return{}}}function Dt(e){return e?{type:`http`,url:yt}:{url:yt}}function Ot(e){return!e||typeof e!=`object`?!1:Object.values(e).some(e=>e&&typeof e==`object`&&e.url===yt)}async function kt(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 wt(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 Tt(e.configPath);if(!t){a.push(e.displayName);continue}let n=await Et(e.configPath),r=n[e.serversKey];if(Ot(r)){i.push(e.displayName);continue}let o=`${e.configPath}.bak`;await w.copyFile(e.configPath,o);let s=r&&typeof r==`object`?r:{},c={...n,[e.serversKey]:{...s,zenovay:Dt(e.includeType)}};await w.mkdir(C.dirname(e.configPath),{recursive:!0}),await w.writeFile(e.configPath,JSON.stringify(c,null,2)+`
|
|
87
|
+
`,`utf8`),await w.chmod(e.configPath,384).catch(()=>void 0),i.push(e.displayName)}catch(t){o.push({client:e.displayName,message:t instanceof Error?t.message:String(t)})}}return{installed:i,skipped:a,errors:o}}async function At(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 jt=T.object({path:T.string().min(1)}),Mt=T.object({path:T.string().min(1),content:T.string(),reason:T.string().min(1)}),Nt=T.object({path:T.string().min(1),patch:T.string().min(1),reason:T.string().min(1)}),Pt=T.object({}),Ft=T.object({question:T.string().min(1),choices:T.array(T.string()).optional()});async function It(e,t){let n=jt.safeParse(t);if(!n.success)return{ok:!1,content:null,error:`invalid_args`};try{let t=await e.safeRead(n.data.path),r=V.scrubSecrets(t),i=24e3,a=r.length>i?`${r.slice(0,i)}\n\n[... truncated: file is ${r.length} chars; showing the first ${i}]`:r;return{ok:!0,content:V.wrapForModel(n.data.path,a)}}catch(e){return{ok:!1,content:null,error:e.message}}}async function Lt(e,t,n){let r=Mt.safeParse(t);if(!r.success)return{ok:!1,content:null,error:`invalid_args`};let{path:i,content:a,reason:o}=r.data,s=``;try{s=await e.safeRead(i)}catch{s=``}let c=await n.approve({path:i,oldContent:s,newContent:a,reason:o});if(c===`n`)return{ok:!1,content:null,error:`skipped_by_user`};if(c===`e`)return{ok:!1,content:null,error:`deferred_to_user_edit`};try{let{backupPath:t}=await e.safeWrite(i,a);return{ok:!0,content:{path:i,backupPath:t}}}catch(e){return{ok:!1,content:null,error:e.message}}}async function Rt(e,t,n){let r=Nt.safeParse(t);if(!r.success)return{ok:!1,content:null,error:`invalid_args`};let{path:i,patch:a,reason:o}=r.data;if(/^\*\*\*\s+Begin Patch/m.test(a)||/^\*\*\*\s+Update File:/m.test(a))return{ok:!1,content:null,error:'unsupported_patch_format: This tool only accepts STANDARD unified diff with `--- a/...`, `+++ b/...`, and `@@ -N,M +N,M @@` headers. The "*** Begin Patch / *** Update File:" V4A format is NOT supported. Please call write_file with the full new file content instead.'};let s;try{s=await e.safeRead(i)}catch(e){return{ok:!1,content:null,error:e.message}}let c;try{c=ae(s,a)}catch(e){return{ok:!1,content:null,error:`patch_failed: ${e.message}. Please call write_file with the full new file content instead — write_file is more reliable than patch_file for this use case.`}}return c===!1||typeof c!=`string`?{ok:!1,content:null,error:`patch_did_not_apply_cleanly. The patch context may not match the file. Please call write_file with the full new file content instead.`}:Lt(e,{path:i,content:c,reason:o},n)}async function zt(e){try{let t=ht(e),{adapter:n,ranked:r}=await mt(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 Bt(e,t){let n=Ft.safeParse(t);if(!n.success)return{ok:!1,content:null,error:`invalid_args`};try{let t=await e.ask(n.data);return{ok:!0,content:{answer:t}}}catch(e){return{ok:!1,content:null,error:e.message}}}const Vt=3;function Ht(e,t,n){if(n)return e.delete(t),null;let r=(e.get(t)??0)+1;return e.set(t,r),r>=Vt?`STOP retrying ${t}: it failed ${r} times. Do NOT call write_file/patch_file on ${t} again — edit a different entry file, or if the tracker is already present, stop and return.`:null}async function Ut(e){let{api:t,sandbox:n,approval:r,prompter:i,handlers:a}=e,o=[...e.initialMessages],s=``,c=0,l=new Map;for(;c<ue;){n.incrementRound(),c++;let u=new AbortController,f=9e4,p=()=>{let e=setTimeout(()=>u.abort(),f);return e.unref?.(),e},m=p(),h=()=>{clearTimeout(m),m=p()},g;try{g=await t.openAiStream(`install`,{messages:o,cwd_fingerprint:n.sessionId,diagnosis:e.diagnosis,targetTrackingCode:e.targetTrackingCode},u.signal)}catch(e){throw clearTimeout(m),e}let _=[],v=``;for await(let e of d(g))switch(h(),e.type){case`delta`:v+=e.content,a?.onDelta?.(e.content);break;case`tool_start`:a?.onToolStart?.({id:e.id,name:e.name});break;case`tool_call`:{clearTimeout(m);let t=await Wt(e.name,e.arguments,{sandbox:n,cwd:n.cwd,approval:r,prompter:i});h();let o=(e.name===`write_file`||e.name===`patch_file`)&&typeof e.arguments.path==`string`?e.arguments.path:null;if(o){let e=Ht(l,o,t.ok!==!1);e&&(t={...t,error:`${t.error??`write_failed`} — ${e}`})}_.push({id:e.id,name:e.name,arguments:e.arguments,result:t}),a?.onToolResult?.({id:e.id,name:e.name,result:t});break}case`usage`:a?.onUsage?.(e);break;case`error`:throw clearTimeout(m),a?.onError?.(e),Error(`[${e.code}] ${e.message}`);case`done`:break}if(clearTimeout(m),v&&(s+=v),_.length===0){v&&o.push({role:`assistant`,content:v});break}o.push({role:`assistant`,content:v,toolCalls:_.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))});for(let e of _)o.push({role:`tool`,toolCallId:e.id,toolName:e.name,content:JSON.stringify(e.result)})}return{finalText:s,rounds:c}}async function Wt(e,t,n){try{switch(e){case`read_file`:return await It(n.sandbox,t);case`write_file`:return await Lt(n.sandbox,t,n.approval);case`patch_file`:return await Rt(n.sandbox,t,n.approval);case`detect_framework`:return await zt(n.cwd);case`ask_user`:return await Bt(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="What to do: re-run with `--review` to approve each write, or install manually (see https://docs.zenovay.com/en/integrations/cli).";function Kt(e,t,n,r){if(e.writes===0){let t=r?`Agent error: ${r.message}`:`Agent returned without writing any files (${e.reads} reads, ${e.rounds} rounds). The model may have refused or the AI Gateway may be misconfigured.`;return{ok:!1,error:`${t}\n${Gt} Nothing was changed in your project.`}}if(!t.includes(n)){let r=e.writtenPaths.join(`, `)||`(none)`,i=t.length?` (found other code(s): ${t.join(`, `)})`:``;return{ok:!1,error:`Agent wrote to: [${r}] but no Zenovay tracker <script> with your code (${n}) is present in any source file${i} — the tracker is NOT installed. The model likely wrote the code into .env only, or edited the wrong file.\n${Gt} Review/undo what was written under ~/.zenovay/undo/.`}}return{ok:!0}}const qt=e=>`<script defer\n data-id="${e}"\n src="https://api.zenovay.com/z.js">\n</script>`;async function Jt(e){let t={installed:[],skipped:[],errors:[]};if(!J(e.trackingCode))return t.errors.push({file:`(input)`,error:`Unexpected tracking-code format: "${e.trackingCode}". Expected letters, digits, "_" or "-".`}),t;let n=await ie(`**/*.html`,{cwd:e.cwd,gitignore:!0,expandDirectories:!1,absolute:!1,ignore:[`node_modules/**`,`.git/**`,`dist/**`,`.next/**`,`.nuxt/**`,`build/**`,`.output/**`]});if(n.length===0)return t;let r=qt(e.trackingCode),i=RegExp(`data-id\\s*=\\s*["']${Yt(e.trackingCode)}["']`);for(let a of n){let n=C.join(e.cwd,a),o;try{o=await w.readFile(n,`utf8`)}catch(e){t.errors.push({file:a,error:e.message});continue}if(B.test(o)&&i.test(o)){t.skipped.push({file:a,reason:`already installed with correct tracking code`});continue}let s;if(B.test(o))s=o.replace(/(<script[^>]*src\s*=\s*["']https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+["'][^>]*>)/i,t=>t.replace(/data-id\s*=\s*["']ZV_\w+["']/i,`data-id="${e.trackingCode}"`)),s===o&&(s=o.replace(/<script(\s)/i,`<script$1data-id="${e.trackingCode}"$1`));else if(e.updateOnly){t.skipped.push({file:a,reason:`updateOnly=true and no Zenovay tag present`});continue}else if(/<\/head>/i.test(o)){if(s=o.replace(/(\n[\t ]*)?<\/head>/i,(e,t)=>{let n=t??`
|
|
88
|
+
`,i=r.replace(/\n/g,`${n}`);return`${n}${i}${n}</head>`}),s===o){t.skipped.push({file:a,reason:`</head> regex did not match unexpectedly`});continue}}else{t.skipped.push({file:a,reason:`no <head>...</head> in file (fragment or non-page)`});continue}let c=null;for(let{name:e,re:t}of de)if(t.test(o)&&!t.test(s)){c=e;break}if(c){t.errors.push({file:a,error:`would remove ${c} tracker — refusing to write`});continue}try{await e.beforeWrite?.(n),await w.writeFile(n,s,`utf8`),t.installed.push(a)}catch(e){t.errors.push({file:a,error:e.message})}}return t}function Yt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function J(e){return typeof e==`string`&&e.length>0&&e.length<=64&&/^[A-Za-z0-9_-]+$/.test(e)}function Xt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const Zt=/<[Ss]cript\b[^>]*\bsrc\s*=\s*["'`][^"'`]*(?:api\.zenovay\.com\/z\.js|\/(?:api\/)?_z\/script\.js)[^"'`]*["'`][^>]*>/;function Qt(e){return Zt.test(e)}function $t(e){return/api\.zenovay\.com\/z\.js/i.test(e)||/\/(?:api\/)?_z\/script\.js/i.test(e)}function en(e,t){let n=Xt(t),r=e.match(new RegExp(Zt.source,`gi`))||[];return r.length===0?!1:r.every(e=>{let t=/\/(?:api\/)?_z\/script\.js/i.test(e);return t?RegExp(`[?&]id=${n}(?:["'\`&\\s/]|$)`).test(e):RegExp(`\\bdata-id\\s*=\\s*["'\`]${n}["'\`]`).test(e)})}function tn(e,t){return e.replace(/<[Ss]cript\b[^>]*>/g,e=>{let n=/\bsrc\s*=\s*["'`][^"'`]*api\.zenovay\.com\/z\.js/.test(e),r=/\bsrc\s*=\s*["'`][^"'`]*\/(?:api\/)?_z\/script\.js/.test(e);if(!n&&!r)return e;let i=e.replace(/(\bdata-id\s*=\s*["'`])[^"'`]*(["'`])/i,`$1${t}$2`);return r&&(i=i.replace(/([?&]id=)[^&"'`\s]*/i,`$1${encodeURIComponent(t)}`)),i})}const nn=`https://api.zenovay.com/z.js`;function rn(e){if(/from\s+['"]next\/script['"]/.test(e))return e;let t=e.split(`
|
|
89
|
+
`),n=-1;for(let e=0;e<t.length;e++)/^\s*import\s/.test(t[e])&&(n=e);let r=`import Script from 'next/script';`;if(n>=0)t.splice(n+1,0,r);else{let e=/^\s*['"]use client['"];?\s*$/.test(t[0]??``);t.splice(e?1:0,0,r)}return t.join(`
|
|
90
|
+
`)}function an(e,t){let n=/([ \t]*)<\/body>/,r=e.match(n);if(!r)return null;let i=r[1]??``,a=`${i} <Script defer data-id="${t}" src="${nn}" strategy="afterInteractive" />`;return e.replace(n,`${a}\n${i}</body>`)}async function on(e){let{cwd:t,trackingCode:n}=e,r={installed:[],skipped:[],errors:[],fellThrough:!1};if(!J(n))return r.errors.push({file:`(input)`,error:`unexpected tracking-code format: "${n}"`}),r;let i;try{i=await ie([`app/**/layout.{tsx,ts,jsx,js}`,`src/app/**/layout.{tsx,ts,jsx,js}`],{cwd:t,gitignore:!1,ignore:[`**/node_modules/**`]})}catch(e){return r.errors.push({file:`app/**/layout`,error:e.message}),r.fellThrough=!0,r}if(i.length===0)return r.fellThrough=!0,r;let a=[];for(let e of i)try{let n=await j.readFile(C.join(t,e),`utf8`);/<body[\s/>]/.test(n)&&a.push({rel:e,src:n,depth:e.split(`/`).length})}catch{}if(a.length===0)return r.fellThrough=!0,r;a.sort((e,t)=>e.depth-t.depth);let o=a[0];if(en(o.src,n))return r.skipped.push({file:o.rel,reason:`already installed with correct tracking code`}),r;if(Zt.test(o.src)){let i=tn(o.src,n);if(i!==o.src){try{let n=C.join(t,o.rel);await e.beforeWrite?.(n),await j.writeFile(n,i),r.installed.push(o.rel)}catch(e){r.errors.push({file:o.rel,error:e.message}),r.fellThrough=!0}return r}return r.fellThrough=!0,r}if($t(o.src))return r.fellThrough=!0,r;let s=rn(o.src),c=an(s,n);if(!c)return r.fellThrough=!0,r;try{let n=C.join(t,o.rel);await e.beforeWrite?.(n),await j.writeFile(n,c),r.installed.push(o.rel)}catch(e){r.errors.push({file:o.rel,error:e.message}),r.fellThrough=!0}return r}const sn=`api.zenovay.com/z.js`;async function Y(e){try{return await w.readFile(e,`utf8`)}catch{return null}}function cn(e,t){let n=e.toLowerCase().lastIndexOf(`</head>`);if(n===-1)return null;let r=e.lastIndexOf(`
|
|
91
|
+
`,n-1)+1,i=(e.slice(r,n).match(/^[ \t]*/)??[``])[0],a=`${i}${t}\n`;return e.slice(0,r)+a+e.slice(r)}async function ln(e,t,n,r,i,a=0,o=new Set){if(a>4)return null;let s=C.dirname(e),c=/import\s+[^;]*?from\s*['"`](\.[^'"`]+\.(?:astro|tsx|jsx|vue|svelte))['"`]/g,l=[],u;for(;(u=c.exec(t))!==null;){let e=C.resolve(s,u[1]);if(o.has(e))continue;o.add(e);let t=await Y(e);if(t===null)continue;if(Qt(t)){if(en(t,r))return e;let n=tn(t,r);return n!==t&&(await i?.(e),await w.writeFile(e,n,`utf8`)),e}if($t(t))return e;let a=cn(t,n);if(a!==null)return await i?.(e),await w.writeFile(e,a,`utf8`),e;l.push({abs:e,content:t})}for(let e of l){let t=await ln(e.abs,e.content,n,r,i,a+1,o);if(t)return t}return null}async function un(e){if(!J(e.trackingCode))return{installed:[],skipped:[],errors:[{file:`(input)`,error:`unexpected tracking-code format: "${e.trackingCode}"`}],fellThrough:!1};if(e.adapter.id===`nuxt`)return fn(e);if(e.adapter.id===`sveltekit`)return pn(e);let{cwd:t,trackingCode:n,siteId:r,adapter:i}=e,a={installed:[],skipped:[],errors:[],fellThrough:!1},o;try{o=i.buildSnippets({trackingCode:n,siteId:r??``},`script`)}catch{return a.fellThrough=!0,a}if(!o||o.length===0)return a.fellThrough=!0,a;let s=new Set(o.map(e=>e.anchorKind));if(s.size===1&&s.has(`head-tag`)){let r=!1;for(let i of o){let o=C.join(t,i.targetPath),s=await Y(o);if(s===null){a.skipped.push({file:i.targetPath,reason:`target file not present`});continue}if(en(s,n)){a.skipped.push({file:i.targetPath,reason:`already installed with correct tracking code`}),r=!0;break}if(Qt(s)){let t=tn(s,n);if(t!==s)try{await e.beforeWrite?.(o),await w.writeFile(o,t,`utf8`),a.installed.push(i.targetPath),r=!0;break}catch(e){a.errors.push({file:i.targetPath,error:e.message});continue}return a.fellThrough=!0,a}if($t(s)){a.skipped.push({file:i.targetPath,reason:`tracker present in an unparseable form (not double-inserting)`}),r=!0;break}let c=cn(s,i.code);if(c===null){let c=await ln(o,s,i.code,n,e.beforeWrite);if(c){a.installed.push(C.relative(t,c)),r=!0;break}a.skipped.push({file:i.targetPath,reason:`no </head> anchor (inline or in an imported head component)`});continue}try{await e.beforeWrite?.(o),await w.writeFile(o,c,`utf8`),a.installed.push(i.targetPath),r=!0;break}catch(e){a.errors.push({file:i.targetPath,error:e.message})}}return!r&&a.installed.length===0&&a.errors.length===0&&(a.fellThrough=!0),a}if(s.size===1&&s.has(`replace-file`)&&o.length===1){let r=o[0];if(!r)return a.fellThrough=!0,a;let s=i.files.find(e=>e.path===r.targetPath),c=C.join(t,r.targetPath),l=await Y(c);if(l!==null)return l.includes(sn)&&l.includes(n)?(a.skipped.push({file:r.targetPath,reason:`already installed with correct tracking code`}),a):(a.fellThrough=!0,a);if(s?.kind===`create`){try{await e.beforeWrite?.(c),await w.mkdir(C.dirname(c),{recursive:!0}),await w.writeFile(c,r.code,`utf8`),a.installed.push(r.targetPath)}catch(e){a.errors.push({file:r.targetPath,error:e.message}),a.fellThrough=a.installed.length===0}return a}return a.fellThrough=!0,a}return a.fellThrough=!0,a}function dn(){return{installed:[],skipped:[],errors:[],fellThrough:!1}}async function fn(e){let t=dn(),n=[`nuxt.config.ts`,`nuxt.config.mjs`,`nuxt.config.js`],r=null,i=null,a=null;for(let t of n){let n=C.join(e.cwd,t),o=await Y(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(sn))return a.includes(e.trackingCode)?(t.skipped.push({file:r,reason:`already installed with correct tracking code`}),t):(t.fellThrough=!0,t);if(/\bapp\s*:/.test(a))return t.fellThrough=!0,t;let o=a.match(/defineNuxtConfig\s*\(\s*\{/);if(!o||o.index===void 0)return t.fellThrough=!0,t;let s=e.adapter.buildSnippets({trackingCode:e.trackingCode,siteId:e.siteId??``},`script`)[0]?.code;if(!s)return t.fellThrough=!0,t;let c=o.index+o[0].length,l=`${a.slice(0,c)}\n${s}${a.slice(c)}`;try{await e.beforeWrite?.(i),await w.writeFile(i,l,`utf8`),t.installed.push(r)}catch(e){t.errors.push({file:r,error:e.message}),t.fellThrough=!0}return t}async function pn(e){let t=dn(),n=`src/routes/+layout.svelte`,r=C.join(e.cwd,n),i=await Y(r),a=`<svelte:head>\n <script defer data-id="${e.trackingCode}" src="https://api.zenovay.com/z.js"></script>\n</svelte:head>\n`;if(i!==null){if(en(i,e.trackingCode))return t.skipped.push({file:n,reason:`already installed with correct tracking code`}),t;if(Qt(i)){let a=tn(i,e.trackingCode);if(a!==i){try{await e.beforeWrite?.(r),await w.writeFile(r,a,`utf8`),t.installed.push(n)}catch(e){t.errors.push({file:n,error:e.message}),t.fellThrough=!0}return t}return t.fellThrough=!0,t}if($t(i))return t.fellThrough=!0,t;let o=i.indexOf(`</svelte:head>`),s=o>=0?i.slice(0,o)+` <script defer data-id="${e.trackingCode}" src="https://api.zenovay.com/z.js"></script>\n`+i.slice(o):`${a}\n${i}`;try{await e.beforeWrite?.(r),await w.writeFile(r,s,`utf8`),t.installed.push(n)}catch(e){t.errors.push({file:n,error:e.message}),t.fellThrough=!0}return t}let o=e.adapter.buildSnippets({trackingCode:e.trackingCode,siteId:e.siteId??``},`script`)[0]?.code;if(!o)return t.fellThrough=!0,t;try{await e.beforeWrite?.(r),await w.mkdir(C.dirname(r),{recursive:!0}),await w.writeFile(r,o,`utf8`),t.installed.push(n)}catch(e){t.errors.push({file:n,error:e.message}),t.fellThrough=!0}return t}async function mn(e,t){try{return await w.access(C.join(e,t)),!0}catch{return!1}}async function hn(e,t){try{let n=await w.stat(C.join(e,t));return n.isDirectory()}catch{return!1}}async function gn(e,t){try{return await w.readFile(C.join(e,t),`utf8`)}catch{return null}}const _n=[`next.config.js`,`next.config.mjs`,`next.config.cjs`,`next.config.ts`];async function vn(e){let t=[],n=await gn(e,`wrangler.toml`),r=n!==null&&/^\s*pages_build_output_dir\s*=/m.test(n),i=await hn(e,`functions`),a=await hn(e,`.cloudflare`);if(r&&t.push(`wrangler.toml has pages_build_output_dir`),i&&t.push(`functions/ directory present`),a&&t.push(`.cloudflare/ directory present`),r||a)return{host:`cloudflare-pages`,signals:t};let o=await mn(e,`vercel.json`),s=await hn(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 mn(e,`netlify.toml`),l=await mn(e,C.join(`public`,`_redirects`)),u=await mn(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 _n)if(await mn(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 yn(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 bn=`https://api.zenovay.com`,xn=`// Auto-generated by @zenovay/cli — first-party tracking proxy. Do not edit.`,Sn=2;function Cn(e){return`${xn}
|
|
92
|
+
// @zenovay/cli-proxy-version: ${Sn}
|
|
93
|
+
/**
|
|
94
|
+
* First-Party Proxy for Zenovay Tracking.
|
|
95
|
+
*
|
|
96
|
+
* This Cloudflare Pages Function proxies tracking requests from your site to
|
|
97
|
+
* ${e}/fp/* — making tracking requests "first-party" to bypass browser
|
|
98
|
+
* tracking protection (Firefox ETP, Edge Tracking Prevention, Safari ITP, Brave).
|
|
99
|
+
*
|
|
100
|
+
* Routes (this function lives at functions/api/_z/[[path]].ts → /api/_z/*):
|
|
101
|
+
* - GET /api/_z/script.js → ${e}/fp/script.js
|
|
102
|
+
* - GET /api/_z/load → ${e}/fp/load
|
|
103
|
+
* - POST /api/_z/e/:trackingCode → ${e}/fp/e/:trackingCode
|
|
104
|
+
* - POST /api/_z/events → ${e}/fp/events
|
|
105
|
+
* - GET /api/_z/settings/:trackingCode → ${e}/fp/settings/:trackingCode
|
|
106
|
+
*/
|
|
107
|
+
|
|
108
|
+
interface Env {
|
|
109
|
+
NEXT_PUBLIC_API_URL?: string
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
interface CloudflareRequestMetadata {
|
|
113
|
+
country?: string
|
|
114
|
+
city?: string
|
|
115
|
+
region?: string
|
|
116
|
+
latitude?: string | number
|
|
117
|
+
longitude?: string | number
|
|
118
|
+
timezone?: string
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
interface EventContext {
|
|
122
|
+
request: Request & { readonly cf?: CloudflareRequestMetadata }
|
|
123
|
+
params: { path?: string[] }
|
|
124
|
+
env: Env
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// These are the only browser-provided headers the analytics API needs. Never
|
|
128
|
+
// clone request.headers here: this is a same-origin endpoint, so the request can
|
|
129
|
+
// contain the customer's session Cookie, Authorization token, Cloudflare
|
|
130
|
+
// Access assertion, and arbitrary private application headers.
|
|
131
|
+
const ANALYTICS_REQUEST_HEADERS = [
|
|
132
|
+
'Accept',
|
|
133
|
+
'Accept-Language',
|
|
134
|
+
'Content-Type',
|
|
135
|
+
'Content-Encoding',
|
|
136
|
+
'Origin',
|
|
137
|
+
'Referer',
|
|
138
|
+
'User-Agent',
|
|
139
|
+
'Sec-GPC',
|
|
140
|
+
'X-Zenovay-Tracking-Code',
|
|
141
|
+
] as const
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Handle all HTTP methods (GET, POST, OPTIONS).
|
|
145
|
+
*/
|
|
146
|
+
export async function onRequest(context: EventContext): Promise<Response> {
|
|
147
|
+
const { request, params, env } = context
|
|
148
|
+
|
|
149
|
+
// Build the path from the catch-all parameter.
|
|
150
|
+
const pathSegments = params.path || []
|
|
151
|
+
const path = pathSegments.join('/')
|
|
152
|
+
|
|
153
|
+
// API base URL — defaults to the value baked in at generation time, but an
|
|
154
|
+
// env var override (NEXT_PUBLIC_API_URL) still wins if present.
|
|
155
|
+
const apiBase = env.NEXT_PUBLIC_API_URL || '${e}'
|
|
156
|
+
|
|
157
|
+
// Build target URL — proxy to /fp/* endpoints.
|
|
158
|
+
const targetUrl = \`\${apiBase}/fp/\${path}\${new URL(request.url).search}\`
|
|
159
|
+
|
|
160
|
+
// Handle OPTIONS (CORS preflight).
|
|
161
|
+
if (request.method === 'OPTIONS') {
|
|
162
|
+
return new Response(null, {
|
|
163
|
+
status: 204,
|
|
164
|
+
headers: {
|
|
165
|
+
'Access-Control-Allow-Origin': '*',
|
|
166
|
+
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
|
167
|
+
'Access-Control-Allow-Headers': 'Content-Type, X-Zenovay-Tracking-Code',
|
|
168
|
+
'Access-Control-Max-Age': '86400',
|
|
169
|
+
},
|
|
170
|
+
})
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
try {
|
|
174
|
+
// CF-Connecting-IP is populated by the Cloudflare runtime. Do not fall
|
|
175
|
+
// back to browser-controlled forwarding headers.
|
|
176
|
+
const clientIP = request.headers.get('CF-Connecting-IP') || ''
|
|
177
|
+
|
|
178
|
+
// Start empty and copy only the documented analytics contract. This keeps
|
|
179
|
+
// ambient customer credentials and spoofed Zenovay trust headers out of
|
|
180
|
+
// the cross-origin request to api.zenovay.com.
|
|
181
|
+
const proxyHeaders = new Headers()
|
|
182
|
+
for (const header of ANALYTICS_REQUEST_HEADERS) {
|
|
183
|
+
const value = request.headers.get(header)
|
|
184
|
+
if (value !== null) proxyHeaders.set(header, value)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Add/set proxy identification headers.
|
|
188
|
+
proxyHeaders.set('X-Zenovay-Proxy', 'first-party')
|
|
189
|
+
if (clientIP) proxyHeaders.set('X-Zenovay-Real-IP', clientIP)
|
|
190
|
+
|
|
191
|
+
// request.cf is trusted runtime metadata, unlike incoming X-Zenovay-CF-*
|
|
192
|
+
// headers. Re-stamp only values supplied by Cloudflare itself.
|
|
193
|
+
const cf = request.cf || {}
|
|
194
|
+
const trustedGeo: Array<[string, string | number | undefined]> = [
|
|
195
|
+
['X-Zenovay-CF-Country', cf.country],
|
|
196
|
+
['X-Zenovay-CF-City', cf.city],
|
|
197
|
+
['X-Zenovay-CF-Region', cf.region],
|
|
198
|
+
['X-Zenovay-CF-Latitude', cf.latitude],
|
|
199
|
+
['X-Zenovay-CF-Longitude', cf.longitude],
|
|
200
|
+
['X-Zenovay-CF-Timezone', cf.timezone],
|
|
201
|
+
]
|
|
202
|
+
for (const [header, value] of trustedGeo) {
|
|
203
|
+
if (value !== undefined && value !== '') proxyHeaders.set(header, String(value))
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Prepare request options. redirect:'manual' so the proxy never follows an
|
|
207
|
+
// upstream redirect to an unexpected origin (defense-in-depth).
|
|
208
|
+
const requestInit: RequestInit = {
|
|
209
|
+
method: request.method,
|
|
210
|
+
headers: proxyHeaders,
|
|
211
|
+
redirect: 'manual',
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// Forward the body for POST/PUT/PATCH requests.
|
|
215
|
+
if (request.method === 'POST' || request.method === 'PUT' || request.method === 'PATCH') {
|
|
216
|
+
requestInit.body = await request.arrayBuffer()
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Forward the request to the API with a 5s timeout — tracking is
|
|
220
|
+
// fire-and-forget, so a slow/hung upstream must never block the visitor's
|
|
221
|
+
// page. On timeout we return a fast 204 (see the catch below).
|
|
222
|
+
const ctl = new AbortController()
|
|
223
|
+
const timer = setTimeout(() => ctl.abort(), 5000)
|
|
224
|
+
let response: Response
|
|
225
|
+
try {
|
|
226
|
+
response = await fetch(targetUrl, {
|
|
227
|
+
...requestInit,
|
|
228
|
+
signal: ctl.signal,
|
|
229
|
+
cf: {
|
|
230
|
+
// Bypass cache for scripts to ensure fresh versions.
|
|
231
|
+
cacheTtl: path.endsWith('.js') || path.includes('script') ? 0 : 60,
|
|
232
|
+
cacheEverything: false,
|
|
233
|
+
},
|
|
234
|
+
} as RequestInit)
|
|
235
|
+
} finally {
|
|
236
|
+
clearTimeout(timer)
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// Clone response headers.
|
|
240
|
+
const responseHeaders = new Headers(response.headers)
|
|
241
|
+
|
|
242
|
+
// The API must never be able to set a cookie on the customer's origin.
|
|
243
|
+
responseHeaders.delete('Set-Cookie')
|
|
244
|
+
|
|
245
|
+
// Add proxy identification.
|
|
246
|
+
responseHeaders.set('X-Zenovay-Proxied', 'true')
|
|
247
|
+
|
|
248
|
+
// For scripts, ensure the proper content type and no caching.
|
|
249
|
+
if (path.endsWith('.js') || path.includes('script') || path.includes('load')) {
|
|
250
|
+
responseHeaders.set('Content-Type', 'application/javascript; charset=utf-8')
|
|
251
|
+
|
|
252
|
+
// Don't cache scripts so the latest API config (apiUrl, trackingCode) is
|
|
253
|
+
// always served.
|
|
254
|
+
responseHeaders.set('Cache-Control', 'no-cache, no-store, must-revalidate')
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// CORS headers for the proxied response.
|
|
258
|
+
responseHeaders.set('Access-Control-Allow-Origin', '*')
|
|
259
|
+
responseHeaders.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
|
|
260
|
+
responseHeaders.set('Access-Control-Allow-Headers', 'Content-Type, X-Zenovay-Tracking-Code')
|
|
261
|
+
|
|
262
|
+
// Return the proxied response.
|
|
263
|
+
return new Response(response.body, {
|
|
264
|
+
status: response.status,
|
|
265
|
+
statusText: response.statusText,
|
|
266
|
+
headers: responseHeaders,
|
|
267
|
+
})
|
|
268
|
+
} catch (error) {
|
|
269
|
+
// Timeout/abort → fail fast + silent (204) so tracking never blocks the page.
|
|
270
|
+
if (error instanceof Error && error.name === 'AbortError') {
|
|
271
|
+
return new Response(null, {
|
|
272
|
+
status: 204,
|
|
273
|
+
headers: { 'Access-Control-Allow-Origin': '*' },
|
|
274
|
+
})
|
|
275
|
+
}
|
|
276
|
+
console.error('[Zenovay First-Party Proxy] Error:', error)
|
|
277
|
+
|
|
278
|
+
return new Response(
|
|
279
|
+
JSON.stringify({
|
|
280
|
+
error: 'Proxy error',
|
|
281
|
+
message: error instanceof Error ? error.message : 'Unknown error',
|
|
282
|
+
}),
|
|
283
|
+
{
|
|
284
|
+
status: 502,
|
|
285
|
+
headers: {
|
|
286
|
+
'Content-Type': 'application/json',
|
|
287
|
+
'Access-Control-Allow-Origin': '*',
|
|
288
|
+
},
|
|
289
|
+
}
|
|
290
|
+
)
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Handle GET requests specifically.
|
|
296
|
+
*/
|
|
297
|
+
export async function onRequestGet(context: EventContext): Promise<Response> {
|
|
298
|
+
return onRequest(context)
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Handle POST requests specifically.
|
|
303
|
+
*/
|
|
304
|
+
export async function onRequestPost(context: EventContext): Promise<Response> {
|
|
305
|
+
return onRequest(context)
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Handle OPTIONS requests specifically (CORS preflight).
|
|
310
|
+
*/
|
|
311
|
+
export async function onRequestOptions(_context: EventContext): Promise<Response> {
|
|
312
|
+
return new Response(null, {
|
|
313
|
+
status: 204,
|
|
314
|
+
headers: {
|
|
315
|
+
'Access-Control-Allow-Origin': '*',
|
|
316
|
+
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
|
317
|
+
'Access-Control-Allow-Headers': 'Content-Type, X-Zenovay-Tracking-Code',
|
|
318
|
+
'Access-Control-Max-Age': '86400',
|
|
319
|
+
},
|
|
320
|
+
})
|
|
321
|
+
}
|
|
322
|
+
`}function wn(e,t){if(!e.startsWith(`${xn}\n`))return!1;let n=[`export async function onRequest(context: EventContext): Promise<Response>`,"const targetUrl = `${apiBase}/fp/${path}${new URL(request.url).search}`",`const apiBase = env.NEXT_PUBLIC_API_URL || '${t}'`,`responseHeaders.set('X-Zenovay-Proxied', 'true')`,`export async function onRequestOptions`];return n.every(t=>e.includes(t))}async function Tn(e,t){let n=(t.apiBase||bn).replace(/\/+$/,``),r=C.join(e,`functions`,`api`,`_z`),i=C.join(r,`[[path]].ts`),a=Cn(n);try{let e=await w.readFile(i,`utf8`);return e===a?{file:i,action:`exists`}:wn(e,n)?(await t.beforeWrite?.(i),await w.writeFile(i,a,`utf8`),{file:i,action:`updated`}):{file:i,action:`manual`}}catch(e){if(e.code!==`ENOENT`)throw e}return await t.beforeWrite?.(i),await w.mkdir(r,{recursive:!0}),await w.writeFile(i,a,`utf8`),{file:i,action:`created`}}const En=`https://api.zenovay.com`,Dn=[`next.config.js`,`next.config.mjs`,`next.config.cjs`,`next.config.ts`];function On(e){return` // Zenovay first-party proxy — forwards /api/_z/* to the tracking API
|
|
323
|
+
{
|
|
324
|
+
source: '/api/_z/:path*',
|
|
325
|
+
destination: '${e}/fp/:path*',
|
|
326
|
+
},`}function kn(e){return`/** @type {import('next').NextConfig} */
|
|
327
|
+
const nextConfig = {
|
|
328
|
+
async rewrites() {
|
|
329
|
+
return [
|
|
330
|
+
${On(e)}
|
|
331
|
+
];
|
|
332
|
+
},
|
|
333
|
+
};
|
|
334
|
+
|
|
335
|
+
export default nextConfig;
|
|
336
|
+
`}async function An(e,t={}){let n=t.apiBase??En,r=null;for(let t of Dn){let n=C.join(e,t);try{await j.access(n),r=n;break}catch{}}if(!r){let r=C.join(e,`next.config.mjs`);return await t.beforeWrite?.(r),await j.writeFile(r,kn(n),`utf8`),{file:r,action:`created`}}let i=await j.readFile(r,`utf8`),a=i.includes(`source: '/api/_z/:path*'`)||i.includes(`source: "/api/_z/:path*"`),o=i.includes(`destination: '${n}/fp/:path*'`)||i.includes(`destination: "${n}/fp/:path*"`);if(a&&o)return{file:r,action:`exists`};if(i.includes(`/api/_z/:path*`)||i.includes(`/_z/:path*`)||/\brewrites\s*(?::|=|\()/.test(i)||/\bredirects\s*\(/.test(i))return{file:r,action:`manual`};let s=[...i.matchAll(/(?:module\.exports\s*=\s*|export\s+default\s+|const\s+\w+\s*(?::\s*[^={\n]{1,80})?=\s*)\{/g)],c=s.length===1?s[0]:null;if(!c||c.index===void 0)return{file:r,action:`manual`};let l=c.index+c[0].length-1,u=i.slice(0,l+1),d=i.slice(l+1),f=`
|
|
337
|
+
async rewrites() {
|
|
338
|
+
return [
|
|
339
|
+
${On(n)}
|
|
340
|
+
];
|
|
341
|
+
},`,p=`${u}${f}${d}`;return await t.beforeWrite?.(r),await j.writeFile(r,p,`utf8`),{file:r,action:`updated`}}const jn=`https://api.zenovay.com`;async function Mn(e,t={}){let n=t.apiBase??jn,r=C.join(e,`vercel.json`),i={source:`/api/_z/(.*)`,destination:`${n}/fp/$1`},a=null;try{a=await j.readFile(r,`utf8`)}catch{a=null}if(a===null){let e={rewrites:[i]};return await t.beforeWrite?.(r),await j.writeFile(r,`${JSON.stringify(e,null,2)}\n`,`utf8`),{file:r,action:`created`}}let o;try{o=JSON.parse(a)}catch{throw Error(`Cannot parse existing vercel.json at ${r}: invalid JSON`)}if(typeof o!=`object`||!o||Array.isArray(o))throw Error(`Cannot merge into vercel.json at ${r}: top-level value is not a JSON object`);let s=Array.isArray(o.rewrites)?o.rewrites:[],c=s.some(e=>e?.source===i.source&&e?.destination===i.destination);if(c)return{file:r,action:`exists`};if(s.some(e=>typeof e?.source==`string`&&e.source.startsWith(`/api/_z`)))throw Error(`Existing /api/_z rewrite in ${r} does not point to ${i.destination}`);return o.rewrites=[...s,i],await t.beforeWrite?.(r),await j.writeFile(r,`${JSON.stringify(o,null,2)}\n`,`utf8`),{file:r,action:`updated`}}const Nn=`https://api.zenovay.com`;async function Pn(e){let t=C.join(e,`_redirects`),n=C.join(e,`public`,`_redirects`);for(let e of[t,n])try{return await j.access(e),e}catch{}try{let t=await j.stat(C.join(e,`public`));if(t.isDirectory())return n}catch{}return t}async function Fn(e,t={}){let n=t.apiBase??Nn,r=await Pn(e),i=`/api/_z/* ${n}/fp/:splat 200`,a=null;try{a=await j.readFile(r,`utf8`)}catch{a=null}if(a===null)return await t.beforeWrite?.(r),await j.mkdir(C.dirname(r),{recursive:!0}),await j.writeFile(r,`# Zenovay first-party proxy — forwards /api/_z/* to the tracking API\n${i}\n`,`utf8`),{file:r,action:`created`};let o=a.split(/\r?\n/).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`)),s=i.split(/\s+/).join(` `),c=o.some(e=>e.split(/\s+/).join(` `)===s);if(c)return{file:r,action:`exists`};if(o.some(e=>e.startsWith(`/api/_z/`)))throw Error(`Existing /api/_z redirect in ${r} does not match the Zenovay proxy target`);let l=`# Zenovay first-party proxy — forwards /api/_z/* to the tracking API`,u=a.split(/\r?\n/),d=u.findIndex(e=>{let t=e.trim();return t.length===0||t.startsWith(`#`)?!1:t.split(/\s+/)[0]===`/*`}),f;if(d>=0)u.splice(d,0,l,i),f=u.join(`
|
|
342
|
+
`),f.endsWith(`
|
|
343
|
+
`)||(f+=`
|
|
344
|
+
`);else{let e=a.length>0&&!a.endsWith(`
|
|
345
|
+
`)?`
|
|
346
|
+
`:``;f=`${a}${e}${l}\n${i}\n`}return await t.beforeWrite?.(r),await j.writeFile(r,f,`utf8`),{file:r,action:`updated`}}const In="Your tracker is already live and working — it counts visitors in Chrome, Firefox and most browsers, no further setup required. First-party tracking is OPTIONAL and adds the rest: Safari, Brave, and browsers with strict tracking prevention block analytics loaded from another company's domain, so to capture those visitors too you serve Zenovay from your OWN domain. That last step is wired at your hosting provider — enable it any time with `zenovay init --host cloudflare-pages` (or `vercel` / `netlify` / `nextjs`).";async function Ln(e,t){let{trackingCode:n,apiBase:r,forceHost:i,beforeWrite:a}=t,o=`unknown`,s=null,c=`skipped`,l=null,u=!1,d=new Set;try{switch(o=i&&i!==`unknown`?i:(await vn(e)).host,o){case`cloudflare-pages`:{let t=await Tn(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&d.add(C.relative(e,t.file));break}case`nextjs-server`:{let t=await An(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&d.add(C.relative(e,t.file)),t.action===`manual`&&(l=`Your tracker is live. To also count Safari/Brave visitors, add this rewrite to ${t.file} yourself (its shape couldn't be edited automatically): { source: '/api/_z/:path*', destination: 'https://api.zenovay.com/fp/:path*' }.`);break}case`vercel`:{let t=await Mn(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&d.add(C.relative(e,t.file));break}case`netlify`:{let t=await Fn(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&d.add(C.relative(e,t.file));break}case`unknown`:default:c=`skipped`,l=In;break}c===`manual`&&!l&&(l=`An existing proxy configuration could not be verified safely, so Zenovay kept the standard tracker active. Review the /api/_z rule before enabling first-party tracking.`)}catch(e){s=null,c=`skipped`,l=`${In} (auto-setup hit an error: ${e.message.slice(0,120)})`}let p=s!==null&&c!==`manual`&&c!==`skipped`;if(p)try{let t=await f(e,{trackingCode:n,beforeWrite:a});u=t.swapped;for(let e of t.files)d.add(e)}catch{u=!1}return{host:o,proxyFile:s,proxyAction:c,snippetSwapped:u,manual:l,changedFiles:[...d]}}const Rn=`\x1B]8;;`,zn=`\x07`;function Bn(){return process.env.FORCE_HYPERLINK?!0:!(process.env.NO_COLOR||!process.stdout.isTTY||process.env.CI||(process.env.TERM??``)===`dumb`)}function Vn({url:e,label:t,color:n,arrow:r=!0}){let{theme:i}=_(),a=n??i.fg,o=(t??e)+(r?` ↗`:``);return Bn()?M.createElement(A,{color:a,underline:!0},Rn,e,zn,o,Rn,zn):t&&t!==e?M.createElement(A,{color:a},M.createElement(A,{underline:!0},t),M.createElement(A,{color:i.dim},` (`,e,`)`)):M.createElement(A,{color:a,underline:!0},e)}function X({label:e,value:t,labelWidth:n=12}){let{theme:r}=_();return M.createElement(k,{flexDirection:`row`},M.createElement(k,{width:n,flexShrink:0},M.createElement(A,{color:r.dim},e.toUpperCase())),typeof t==`string`?M.createElement(A,{color:r.fg},t):t)}function Hn(e){return e.review&&process.stdout.isTTY?`interactive`:`auto`}function Un(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 Wn(){let e=[12,15,18,22,28,35,41,50,58,64,72,78],t=x(e,24);return[` ↑`,` ${t}`,` └────────────────────────`,` May Jun Jul Aug Sep`]}function Gn(){return[` Landing page ████████████████████ 100%`,` ↓ -28%`,` Pricing ██████████████░░░░░░ 72%`,` ↓ -50%`,` Checkout ███████░░░░░░░░░░░░░ 36%`,` ↓ -64%`,` Purchased ███░░░░░░░░░░░░░░░░░ 13%`]}function Kn(){return[` ▇▇▇▇▇▇▇▇▇▎ 89 Sarah K. /pricing 🇺🇸`,` ▇▇▇▇▇▇░░░░ 61 anon /docs 🇩🇪`,` ▇▇▇░░░░░░░ 34 anon /changelog 🇯🇵`]}function qn(){return[` LCP ● 2.1s good ████████████░░░░░░`,` INP ● 89ms good ██████████████████`,` CLS ⚠ 0.14 needs ████████████░░░░░░`,` TTFB ● 380ms good ███████████████░░░`]}const Jn=[{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:Wn},{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:Gn},{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:Kn},{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:qn},{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.`]}],Yn=11e3,Xn=9,Zn=({width:e,height:t})=>{let{theme:n}=_(),[r,i]=F(0);N(()=>{if(Jn.length<=1)return;let e=setInterval(()=>{i(e=>(e+1)%Jn.length)},Yn);return()=>clearInterval(e)},[]);let a=Jn[r],o=a.visual?a.visual():[];return M.createElement(k,{flexDirection:`column`,width:e,height:t,paddingX:2,paddingY:1},M.createElement(k,{marginBottom:1},M.createElement(A,{color:n.typography.label.color,dimColor:n.typography.label.dim},`LEARN`)),M.createElement(k,{flexDirection:`column`,minHeight:Xn,key:r},M.createElement(k,{marginBottom:1},M.createElement(A,{bold:!0,color:n.fg,wrap:`truncate`},a.title)),a.body.map((e,t)=>M.createElement(A,{key:t,color:n.muted,wrap:`truncate`},e||` `)),o.length>0&&M.createElement(k,{flexDirection:`column`,marginTop:1},o.map((e,t)=>M.createElement(A,{key:t,color:n.accent},e)))),M.createElement(k,{flexGrow:1}),M.createElement(k,{marginTop:1},M.createElement(A,null,Jn.map((e,t)=>M.createElement(A,{key:t,color:t===r?n.muted:n.dim},t===r?`─`:`·`)))))},Qn={pending:`·`,active:`⠋`,done:`✓`,error:`✗`};function $n(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 er=({tasks:e,width:t,height:n,liveLine:r})=>{let{theme:i}=_();return M.createElement(k,{flexDirection:`column`,width:t,height:n,paddingX:2,paddingY:1},M.createElement(k,{marginBottom:1},M.createElement(A,{color:i.typography.label.color,dimColor:i.typography.label.dim},`TASKS`)),e.map(e=>M.createElement(k,{key:e.id,flexDirection:`column`},M.createElement(k,{flexDirection:`row`},e.status===`active`?M.createElement(A,{color:i.accent},M.createElement(I,{type:`dots`})):M.createElement(A,{color:$n(e.status,i)},Qn[e.status]),M.createElement(A,null,` `),M.createElement(A,{color:e.status===`pending`?i.muted:i.fg,wrap:`truncate`},e.label)),e.detail&&M.createElement(k,{paddingLeft:2},M.createElement(A,{color:i.dim,wrap:`truncate`},e.detail)))),M.createElement(k,{flexGrow:1}),r&&M.createElement(k,{flexDirection:`row`,marginTop:1},M.createElement(A,{color:i.accent},`◆ `),M.createElement(A,{color:i.fg,wrap:`truncate`},r)))};function Z(e){return e.toLowerCase().replace(/[^a-z0-9]/g,``)}function tr(e,t){if(e.length===0)return null;if(e.length===1)return e[0]??null;if(!t)return null;let n=Z(t);if(!n)return null;let r=e.find(e=>Z(e.name)===n);if(r)return r;let i=e.find(e=>{let t=new URL(e.url).hostname;return Z(t.split(`.`)[0]??``)===n});if(i)return i;if(n.length<4)return null;let a=e.filter(e=>{let t=Z(e.name),r=Z(new URL(e.url).hostname);return t.includes(n)||r.includes(n)||n.includes(t)||n.includes(r)});return a.length===1?a[0]??null:null}const nr=oe(S),rr=2e4;async function Q(e,t){let n=await nr(`git`,t,{cwd:e,timeout:rr,maxBuffer:4e6,env:{...process.env,GIT_TERMINAL_PROMPT:`0`}});return{stdout:n.stdout,stderr:n.stderr}}function ir(e){let t=e.split(`\0`).filter(Boolean),n=[];for(let e=0;e<t.length;e++){let r=t[e];if(r.length<4)continue;let i=r.slice(0,2);n.push(r.slice(3)),/[RC]/.test(i)&&t[e+1]&&n.push(t[++e])}return[...new Set(n)]}async function ar(e){let{stdout:t}=await Q(e,[`status`,`--porcelain=v1`,`-z`,`--untracked-files=all`]);return ir(t)}async function or(e){try{let{stdout:t}=await Q(e,[`rev-parse`,`--show-toplevel`]),n=C.resolve(t.trim());return{isRepository:!0,root:n,dirtyPaths:await ar(n)}}catch{return{isRepository:!1,root:null,dirtyPaths:[]}}}async function sr(e,t,n){let r=await w.realpath(e).catch(()=>C.resolve(e)),i=C.resolve(r,n),a=await w.realpath(i).catch(()=>i),o=C.relative(t,a);return!o||o.startsWith(`..`)||C.isAbsolute(o)?null:o.split(C.sep).join(`/`)}function cr(e){return/(^|\/)\.env(?:$|\.(?!example(?:$|\.)))/i.test(e)}async function lr(e){let{cwd:t,baseline:n}=e;if(!n.isRepository||!n.root)return{committed:!1,pushed:!1,reason:`not-repository`,message:`Not a git repository — skipped automatic commit.`};if(n.dirtyPaths.length>0)return{committed:!1,pushed:!1,reason:`dirty-baseline`,message:`The repository already had uncommitted work, so Zenovay left git untouched. Commit the tracker through your normal workflow.`};let r=await Promise.all(e.changedPaths.map(e=>sr(t,n.root,e))),i=[...new Set(r.filter(e=>!!e))];if(i.length===0)return{committed:!1,pushed:!1,reason:`no-journaled-changes`,message:`No Zenovay-written files were recorded — git was left untouched.`};let a=i.filter(e=>!cr(e)),o=i.filter(cr),s=await ar(n.root),c=new Set(i),l=s.filter(e=>!c.has(e));if(l.length>0)return{committed:!1,pushed:!1,reason:`unexpected-changes`,message:`New non-Zenovay changes appeared during setup (${l.join(`, `)}), so git was left untouched.`,unstagedPaths:s};if(a.length===0)return{committed:!1,pushed:!1,reason:`no-staged-changes`,message:`Only local environment files changed; Zenovay intentionally did not commit them.`,unstagedPaths:o};let{stdout:u}=await Q(n.root,[`symbolic-ref`,`--quiet`,`--short`,`HEAD`]),d=u.trim();e.onDetail?.(`Staging ${a.length} Zenovay file(s)…`),await Q(n.root,[`add`,`--`,...a]);try{return await Q(n.root,[`diff`,`--cached`,`--quiet`]),{committed:!1,pushed:!1,reason:`no-staged-changes`,message:`The recorded Zenovay files were already up to date.`,unstagedPaths:o}}catch{}e.onPhase?.(`committing`),e.onDetail?.(`Creating a tracker-only commit…`),await Q(n.root,[`commit`,`-m`,`chore(zenovay): install tracking script via @zenovay/cli`]);let{stdout:f}=await Q(n.root,[`rev-parse`,`--short`,`HEAD`]),p=f.trim();e.onPhase?.(`pushing`),e.onDetail?.(`Pushing ${p} to origin/${d}…`);try{await Q(n.root,[`push`,`origin`,d])}catch(e){let t=e instanceof Error?e.message.split(`
|
|
347
|
+
`)[0]:`unknown git error`;return{committed:!0,pushed:!1,shortSha:p,branch:d,reason:`push-failed`,pushError:t,message:`Commit ${p} was created locally, but it was not pushed. Run: git push origin ${d}`,unstagedPaths:o}}return e.onPhase?.(`done`),{committed:!0,pushed:!0,shortSha:p,branch:d,message:`Pushed ${p} to origin/${d}.`,unstagedPaths:o}}const ur=/<script\b[^>]*\bsrc\s*=\s*["'][^"']*(?:(?:api|cdn)\.zenovay\.com\/|\/(?:api\/)?_z\/script\.js)[^"']*["'][^>]*>/gi,dr=/\bsrc\s*=\s*["']([^"']+)["']/i,fr=/data-id\s*=\s*["'](ZV_[A-Za-z0-9_-]+)["']/i,pr=/[?&]id=(ZV_[A-Za-z0-9_-]+)/i;function mr(e){return e.match(fr)?.[1]??e.match(pr)?.[1]??null}function hr(e){return/\/(?:api\/)?_z\/script\.js/i.test(e)}async function gr(e,t,n=fetch){try{let r=await n(e,{headers:{"User-Agent":`zenovay-cli/preflight`},signal:AbortSignal.timeout(8e3),redirect:`follow`});if(!r.ok)return{state:`tracker-missing`,httpStatus:r.status};let i=await r.text(),a=i.match(ur)??[];if(a.length===0)return{state:`tracker-missing`};let o=[...new Set(a.map(mr).filter(e=>!!e))],s=a.find(e=>mr(e)===t);if(!s)return{state:`tracker-wrong-id`,foundCodes:o};if(!hr(s))return{state:`tracker-correct`};let c=s.match(dr)?.[1]?.replace(/&/gi,`&`);if(!c)return{state:`proxy-broken`,scriptUrl:e,detail:`The first-party tracker tag has no readable script URL.`};let l=new URL(c,r.url||e).toString(),u;try{u=await n(l,{headers:{"User-Agent":`zenovay-cli/preflight`},signal:AbortSignal.timeout(8e3),redirect:`follow`})}catch(e){return{state:`proxy-broken`,scriptUrl:l,detail:`The first-party script could not be reached: ${e instanceof Error?e.message:`network error`}`}}if(!u.ok)return{state:`proxy-broken`,scriptUrl:l,httpStatus:u.status,detail:`The first-party script returned HTTP ${u.status}.`};let d=u.headers.get(`content-type`)??``;if(!/(?:java|ecma)script/i.test(d))return{state:`proxy-broken`,scriptUrl:l,detail:`The first-party route returned ${d||`an unknown content type`} instead of JavaScript.`};if(u.headers.get(`x-zenovay-proxied`)?.toLowerCase()!==`true`)return{state:`proxy-broken`,scriptUrl:l,detail:`The route did not identify itself as a Zenovay first-party proxy.`};let f=await u.text();return f.includes(t)?{state:`tracker-correct`}:{state:`proxy-broken`,scriptUrl:l,detail:`The proxy script was served with a different tracking code.`}}catch(e){return{state:`tracker-missing`,networkError:e instanceof Error?e.message:`network error`}}}async function _r(e){if(e.undo)return vr(e);if(c(e))return yr(e);let t=`quit`,n=null,r=null,i=Promise.resolve(),a=await new Promise(a=>{let{unmount:o,waitUntilExit:s}=te(M.createElement(br,{opts:e,onExit:(e,i,s,c)=>{t=i??`quit`,n=s??null,r=c??null,o(),a(e)}}),{exitOnCtrlC:!0});i=s(),i.then(()=>a(130),()=>a(1))});if(await i.catch(()=>{}),a===0&&r)return await l(r),0;let o=a===0&&t!==`quit`&&!!n;if(a===0&&!o&&await m().catch(()=>void 0),a!==0||t===`quit`||!n)return a;let s=n.id,u=t===`watch`?[`overview`,`--site-id`,s]:[`events`,`tail`,`--site-id`,s],{spawnSync:d}=await import(`node:child_process`),{realpathSync:f}=await import(`node:fs`),{buildPostInstallReexec:p}=await import(`./ensure-latest-BfsWmA1w.js`),{cmd:h,args:g}=p({execPath:process.execPath,argv1:process.argv[1]??``,sub:u,resolveSymlink:f});await new Promise(e=>setImmediate(e));let _=d(h,g,{stdio:`inherit`});if(_.error){let e=t===`watch`?`overview`:`events tail`;return process.stderr.write(`Run \`zenovay ${e} --site-id ${s}\` to continue.\n`),0}return _.status??0}async function vr(e){let t=C.join(E.homedir(),`.zenovay`,`undo`),n;try{let e=await w.readdir(t,{withFileTypes:!0}),r=e.filter(e=>e.isDirectory()).map(e=>e.name),i=await Promise.all(r.map(async e=>({name:e,mtime:await w.stat(C.join(t,e)).then(e=>e.mtimeMs,()=>0)})));n=i.sort((e,t)=>t.mtime-e.mtime).map(e=>e.name)}catch{n=[]}if(n.length===0)return c(e)?(s({type:`info`,message:`Nothing to undo — no init session has modified project files on this machine.`}),s({type:`done`,command:`init`,exitCode:0})):process.stdout.write(`Nothing to undo — no init session has modified project files on this machine.
|
|
348
|
+
`),0;let r;for(let t of n)if(await ge(t,e.cwd).catch(()=>!1)){r=t;break}if(!r){let t=`Nothing to undo — no init session belongs to this project.`;return c(e)?(s({type:`info`,message:t}),s({type:`done`,command:`init`,exitCode:0})):process.stdout.write(`${t}\n`),0}try{let{restored:t}=await _e(r,{cwd:e.cwd}),n=t>0?`Reverted ${t} file(s) from the last install (session ${r}).`:`Nothing to revert in the last session (${r}).`;return c(e)?(s({type:`info`,message:n}),s({type:`done`,command:`init`,exitCode:0})):process.stdout.write(`${n}\n`),0}catch(n){let i=`Undo failed: ${n.message}. The backups are under ${C.join(t,r)} if you need to restore by hand.`;return c(e)?(s({type:`error`,code:`undo_failed`,message:i}),s({type:`done`,command:`init`,exitCode:1})):process.stderr.write(`${i}\n`),1}}async function yr(t){let r=await import(`./telemetry-DIAzAYko.js`).catch(()=>null);r?.emit(`install.start`,{properties:{mode:`headless`}});try{let i=await e(),c=await gt(t.cwd);if(!c)return s({type:`error`,code:`no_framework`,message:`Could not detect framework (headless mode has no picker).`}),r?.emit(`install.error`,{error_code:`no_framework`,properties:{mode:`headless`}}),2;s({type:`framework.detected`,framework:c.id,confidence:1}),r?.emit(`install.framework_detected`,{properties:{framework:c.id}});let l=await a({strict:!1});if(!l&&!process.env.ZENOVAY_API_TOKEN)return s({type:`error`,code:`not_logged_in`,message:"Run `zenovay login` first (or set ZENOVAY_API_TOKEN)."}),2;let u=new n({config:i,cliVersion:t.cliVersion,token:l}),[d,f]=await Promise.all([u.getSites(),o(t.cwd,``).catch(()=>null)]),p;if(t.siteId){if(p=d.find(e=>e.id===t.siteId),!p)return s({type:`error`,code:`site_not_found`,message:`Site ${t.siteId} not found.`}),2}else if(f?.foundTrackingCodes.length){for(let e of f.foundTrackingCodes){let t=d.find(t=>t.trackingCode===e);if(t){p=t;break}}!p&&d.length===1&&(p=d[0])}else p=d.length===1?d[0]:void 0;if(!p)return s({type:`error`,code:d.length===0?`no_site`:`site_required`,message:d.length===0?`No sites exist; create one at app.zenovay.com or re-run interactively.`:`More than one site exists and none matches this project. Pass --site-id <ID> so Zenovay cannot install the wrong tracker.`}),2;let m=p.trackingCode??p.id;if(f&&(f.recommendation===`no-op`||f.foundTrackingCodes.includes(m)))return s({type:`info`,message:`Zenovay already installed correctly for ${p.name} (${m})`}),s({type:`done`,command:`init`,exitCode:0}),0;s({type:`info`,message:`Using site ${p.id} (${p.name}) trackingCode=${p.trackingCode??p.id}`});let h=p.trackingCode??p.id;if(!J(h))return s({type:`error`,code:`invalid_tracking_code`,message:`tracking code "${h}" has an unexpected format; aborting to avoid broken markup`}),1;let g=new V({cwd:t.cwd}),_=e=>g.journalTrustedWrite(e);if(c.id===`plain-html`){let e=await Jt({cwd:t.cwd,trackingCode:h,updateOnly:f?.recommendation===`update-tracking-code`,beforeWrite:_});if(e.installed.length===0&&e.skipped.length===0)return s({type:`error`,code:`install_failed`,message:`No .html files with a <head> block found to inject the tracker into (errors: ${e.errors.length}).`}),r?.emit(`install.error`,{error_code:`install_failed`,properties:{mode:`headless`,framework:c.id}}),s({type:`done`,command:`init`,exitCode:1}),1;s({type:`info`,message:`tracker injected into ${e.installed.length} file(s); ${e.skipped.length} already current; ${e.errors.length} error(s)`})}else if(c.id===`next-app-router`){let e=await on({cwd:t.cwd,trackingCode:h,beforeWrite:_});if(e.fellThrough||e.errors.length>0)return s({type:`error`,code:`headless_framework_unsupported`,message:"This Next.js project has a structure the headless installer can't edit safely (no standard document-shell layout found). Run `zenovay init` interactively — the wizard places the tracker in the correct file. Nothing was modified."}),r?.emit(`install.error`,{error_code:`headless_framework_unsupported`,properties:{mode:`headless`,framework:c.id}}),s({type:`done`,command:`init`,exitCode:1}),1;s({type:`info`,message:`tracker inserted: ${e.installed[0]??`already installed — nothing to change`}`})}else{let e=await un({cwd:t.cwd,trackingCode:h,siteId:p.id,adapter:c,beforeWrite:_}),n=e.skipped.some(e=>/already installed|tracker present/i.test(e.reason));if(e.fellThrough||e.errors.length>0||e.installed.length===0&&!n)return s({type:`error`,code:`headless_framework_unsupported`,message:`${c.displayName}'s tracker insert isn't a mechanical edit the headless mode can apply safely for this project shape. Run \`zenovay init\` interactively — the wizard uses a deterministic fast path and falls back to the AI installer only where judgement is needed. Nothing was modified.`}),r?.emit(`install.error`,{error_code:`headless_framework_unsupported`,properties:{mode:`headless`,framework:c.id}}),s({type:`done`,command:`init`,exitCode:1}),1;s({type:`info`,message:`tracker inserted: ${e.installed[0]??`already installed — nothing to change`}`})}let v=await q(t.cwd,{[c.envVarName]:h},{beforeWrite:_});if(v.addedKeys.length>0&&s({type:`info`,message:`env vars added: ${v.addedKeys.join(`,`)}`}),t.firstParty!==!1){let e=await Ln(t.cwd,{trackingCode:h,forceHost:yn(t.host),beforeWrite:_});e.proxyFile&&e.proxyAction!==`manual`&&e.proxyAction!==`skipped`?s({type:`info`,message:`first-party tracking enabled — analytics now load from your own domain (${Cr(t.cwd,e.proxyFile)}), so visitors on Safari/Brave and other strict-privacy browsers are counted too`}):e.manual&&s({type:`info`,message:e.manual})}else s({type:`info`,message:"first-party tracking skipped (--no-first-party) — enable it later with `zenovay init --host <cloudflare-pages|vercel|netlify|nextjs>`"});return s({type:`done`,command:`init`,exitCode:0}),r?.emit(`install.success`,{properties:{framework:c.id,mode:`headless`,env_keys_added:v.addedKeys.length}}),0}catch(e){return s({type:`error`,code:`init_failed`,message:e.message}),r?.emit(`install.error`,{error_code:`init_failed`,properties:{mode:`headless`,error:(e.message??`unknown`).slice(0,128)}}),1}}const br=({opts:t,onExit:i})=>{let{exit:s}=ne(),{theme:c}=_(),[l,u]=F(`intro`),[d,f]=F(null),[m,v]=F([]),[y,b]=F(null),[x,S]=F(null),[C,w]=F(null),[T,E]=F([]),[D,O]=F(void 0),[te,j]=F(null),[ie,ae]=F(null),[oe,se]=F(null),[ce,L]=F(0),[le,R]=F(`skipped`),[ue,z]=F(null),[B,de]=F(null),[V,fe]=F(null),H=P(new Set),[pe,me]=F(0),he=P(!1),ge=P(null),U=P(!0),_e=M.useCallback(e=>{let t=H.current.size;for(let t of e)t&&H.current.add(t);H.current.size!==t&&me(H.current.size)},[]),[ve,ye]=F(null),W=P(null),be=P(!1),[xe,Se]=F(!1),[Ce,we]=F(void 0),G=P(null),Te=M.useCallback(e=>new Promise(t=>{G.current=t,we(e),Se(!0)}),[]),Ee=M.useCallback(e=>{Se(!1);let t=G.current;G.current=null,t?.(e)},[]),K=M.useCallback((e,t,n,r)=>{U.current&&(U.current=!1,s(),i(e,t,n,r))},[s,i]);re((e,t)=>{let n=e.toLowerCase()===`q`||t.escape;n&&(l===`error`?K(1):l===`create-site`&&K(0))}),N(()=>{let e=process.env.TERM_PROGRAM===`vscode`,t=!!process.stdout.isTTY&&!e;return t&&process.stdout.write(`\x1B[?1049h\x1B[H`),()=>{U.current=!1,W.current?.abort(),G.current?.(null),G.current=null,t&&process.stdout.write(`\x1B[?1049l`)}},[]),N(()=>{be.current||(be.current=!0,(async()=>{try{de(await or(t.cwd));let r=!!process.stdout.isTTY&&!t.yes&&!t.json;r&&await new Promise(e=>setTimeout(e,1400)),u(`detecting`);let i=await gt(t.cwd);if(!i){w(`Could not detect your framework. Supported: Next.js, Nuxt, SvelteKit, Astro, Remix, plain HTML.`),u(`error`);return}f(i);let s=await a({strict:!1});!process.env.ZENOVAY_API_TOKEN&&!s&&(u(`login`),await p({cliVersion:t.cliVersion,offerCompletions:!1})),u(`loading-sites`);let c=await e(),l=await a({strict:!1}),d=new n({config:c,cliVersion:t.cliVersion,token:l}),[m,h]=await Promise.all([d.getSites(),o(t.cwd,``).catch(()=>null)]),g=await Wr(t.cwd);if(v(m),b(g),m.length===0){u(`create-site`);return}if(t.siteId){let e=m.find(e=>e.id===t.siteId);if(!e){w(`Site ${t.siteId} not found in your account.`),u(`error`);return}let n=e.trackingCode??e.id;if(h?.foundTrackingCodes.includes(n)){S(e),u(`already-installed`);return}S(e),Dr(e,i,t,{setPhase:u,setErrorMsg:w,setTasks:E,setLiveLine:O,setSandboxStats:j,setVerifyResult:ae,setFirstParty:se,setPendingApproval:ye,askHostChoice:Te,recordChangedPaths:_e,registerBridge:e=>{W.current=e}});return}if(h?.foundTrackingCodes.length)for(let e of h.foundTrackingCodes){let t=m.find(t=>t.trackingCode===e);if(t){S(t),u(`already-installed`);return}}let _=tr(m,g);if(t.yes&&_){S(_),Dr(_,i,t,{setPhase:u,setErrorMsg:w,setTasks:E,setLiveLine:O,setSandboxStats:j,setVerifyResult:ae,setFirstParty:se,setPendingApproval:ye,askHostChoice:Te,recordChangedPaths:_e,registerBridge:e=>{W.current=e}});return}u(`site-picker`)}catch(e){w(e.message),u(`error`)}})())},[]),N(()=>{l===`error`&&(W.current?.abort(),setTimeout(()=>K(1),8e3))},[l]);let De=async()=>{if(!he.current){if(he.current=!0,R(`verified`),!x){u(`success`);return}try{let i=await e();if(!U.current)return;let o=await a({strict:!1});if(!U.current)return;let s=new n({config:i,cliVersion:t.cliVersion,token:o}),c=await s.getSetupDestination(x.id);if(!U.current)return;z(c);let l=r(x.id,c);if(l){K(0,`quit`,x,l);return}}catch{U.current&&K(0,`quit`,x,r(x.id,null));return}U.current&&u(`success`)}};return M.createElement(k,{flexDirection:`column`},M.createElement(h,{version:t.cliVersion,subtitle:`AI install wizard`}),l===`intro`&&M.createElement(Or,null),l===`detecting`&&M.createElement(g,{title:`Scanning`,state:`busy`},M.createElement(k,null,M.createElement(A,{color:c.accent},M.createElement(I,{type:`dots`})),M.createElement(A,null,` Detecting framework…`))),l===`login`&&M.createElement(g,{title:`Authenticating`,state:`busy`},M.createElement(A,null,`Opening browser for login… (paste ZENOVAY_API_TOKEN env var to skip)`)),l===`loading-sites`&&M.createElement(g,{title:`Loading your sites`,state:`busy`},M.createElement(k,null,M.createElement(A,{color:c.accent},M.createElement(I,{type:`dots`})),M.createElement(A,null,` Fetching your Zenovay sites…`))),l===`already-installed`&&x&&M.createElement(jr,{site:x,onContinueSetup:()=>{if(t.skipVerify){R(`skipped`),u(`success`);return}ge.current=Date.now(),L(0),u(`visit-prompt`)},onReinstall:()=>{u(`site-picker`)},onExit:()=>K(0,`quit`,x)}),l===`site-picker`&&d&&M.createElement(Mr,{sites:m,preselectHint:y,onPick:e=>{if(e===`create-new`){u(`create-site`);return}S(e),Dr(e,d,t,{setPhase:u,setErrorMsg:w,setTasks:E,setLiveLine:O,setSandboxStats:j,setVerifyResult:ae,setFirstParty:se,setPendingApproval:ye,askHostChoice:Te,recordChangedPaths:_e,registerBridge:e=>{W.current=e}})}}),l===`create-site`&&M.createElement(g,{title:`Add a site first`,state:`warn`},M.createElement(A,{color:c.warn},`You don't have a Zenovay site yet. Create one at https://app.zenovay.com/websites (takes ~30 seconds), then re-run `,M.createElement(A,{color:c.accent},`zenovay init`),` here.`),M.createElement(k,{marginTop:1},M.createElement(A,{color:c.muted},`Press `),M.createElement(A,{color:c.accent},`q`),M.createElement(A,{color:c.muted},` to exit.`))),l===`agent`&&d&&x&&M.createElement(Ar,{adapter:d,site:x,tasks:T,liveLine:D,pendingApproval:ve,onApprove:e=>{ve&&W.current?.resolve(ve.id,e)},pendingHostChoice:xe,hostChoiceNote:Ce,onHostChoice:Ee}),l===`install-complete`&&d&&x&&M.createElement(Ir,{cwd:t.cwd,adapter:d,site:x,stats:te,modifiedFileCount:pe,verify:ie,firstParty:oe,onCommit:()=>u(`commit-prompt`),onSkipCommit:()=>u(`deploy-prompt`),onQuit:()=>K(0,`quit`,x)}),l===`commit-prompt`&&x&&M.createElement(Rr,{cwd:t.cwd,baseline:B??{isRepository:!1,root:null,dirtyPaths:[]},changedPaths:[...H.current],onDone:e=>{fe(e.message),e.pushed&&O(`Pushed ${e.shortSha} to ${e.branch}`),u(`deploy-prompt`)},onError:e=>{w(e),u(`error`)}}),l===`deploy-prompt`&&x&&M.createElement(zr,{site:x,notice:V,onDeployed:()=>{t.skipVerify?(R(`skipped`),u(`success`)):(ge.current=Date.now(),u(`visit-prompt`))},onSkip:()=>{R(`skipped`),u(`success`)},onQuit:()=>K(0,`quit`,x)}),l===`visit-prompt`&&x&&M.createElement(Br,{site:x,onContinue:()=>u(`verify`),onQuit:()=>K(0,`quit`,x)}),l===`verify`&&x&&M.createElement(Vr,{site:x,since:ge.current??Date.now(),elapsed:ce,onTick:e=>L(e),onArrived:()=>{De()},onTimeout:()=>{R(`unverified`),u(`success`)},onSkip:()=>{R(`skipped`),u(`success`)},onQuit:()=>K(0,`quit`,x)}),l===`success`&&d&&x&&M.createElement(Fr,{adapter:d,site:x,stats:te,modifiedFileCount:pe,outcome:le,dashboardUrl:ue?.kind===`dashboard`?ue.url:void 0,firstParty:oe,onPick:e=>K(0,e,x)}),l===`error`&&M.createElement(g,{title:`Install failed`,state:`err`},M.createElement(A,{color:c.error},C??`Unknown error`)),M.createElement(ee,{items:l===`already-installed`?[{key:`enter`,label:`verify and continue`},{key:`r`,label:`reinstall or change site`},{key:`q`,label:`quit`},{key:`ctrl-c`,label:`abort`}]:[{key:`q`,label:`quit`},{key:`ctrl-c`,label:`abort`}]}))};async function $(e,t,n,r){if(e.firstParty===!1){let e={host:`unknown`,proxyFile:null,proxyAction:`skipped`,snippetSwapped:!1,manual:"First-party tracking skipped (--no-first-party). Safari/Brave and other strict-privacy setups block third-party analytics — add all-browser coverage any time with `zenovay init --host <cloudflare-pages|vercel|netlify|nextjs>`.",changedFiles:[]};return n.setFirstParty?.(e),e}if(!n.setFirstParty)return null;n.setTasks(e=>e.some(e=>e.id===`first-party`)?e.map(e=>e.id===`first-party`?{...e,status:`active`}:e):[...e,{id:`first-party`,label:`Set up first-party tracking (all browsers)`,status:`active`}]),n.setLiveLine(`Setting up first-party tracking (all browsers)…`);let i=yn(e.host),a=null;try{if(a=await Ln(e.cwd,{trackingCode:t,forceHost:i,beforeWrite:r}),n.setFirstParty(a),n.recordChangedPaths?.(a.changedFiles),a.host===`unknown`&&!i&&n.askHostChoice){n.setLiveLine(`Where do you deploy this site? (enables all-browser tracking)`);let i=e.host?`Unrecognized --host "${e.host}" — pick your host below.`:void 0,o=await n.askHostChoice(i);o&&(n.setLiveLine(`Setting up first-party tracking…`),a=await Ln(e.cwd,{trackingCode:t,forceHost:o,beforeWrite:r}),n.setFirstParty(a),n.recordChangedPaths?.(a.changedFiles))}}catch{a={host:`unknown`,proxyFile:null,proxyAction:`skipped`,snippetSwapped:!1,manual:"First-party setup hit an error — your standard tracker is active; add all-browser coverage later with `zenovay init --host <cloudflare-pages|vercel|netlify|nextjs>`.",changedFiles:[]},n.setFirstParty(a)}let o=wr(a,e.cwd);return n.setTasks(e=>e.map(e=>e.id===`first-party`?{...e,status:`done`,detail:o}:e)),n.setLiveLine(void 0),a}function xr(e){return!e||e.changedFiles.length===0?`Already installed correctly`:e.proxyAction===`updated`?`Tracker already present; first-party proxy upgraded`:e.proxyAction===`created`?`Tracker already present; first-party proxy added`:`Tracker already present; first-party tracking updated`}function Sr(e){return`${e} ${e===1?`file`:`files`}`}function Cr(e,t){let n=C.resolve(e),r=C.isAbsolute(t)?C.normalize(t):C.resolve(n,t),i=C.relative(n,r);return i&&i!==`..`&&!i.startsWith(`..${C.sep}`)&&!C.isAbsolute(i)?i:C.basename(t)}function wr(e,t){return e?e.proxyFile&&e.proxyAction!==`manual`&&e.proxyAction!==`skipped`?`now loads from your domain (${Cr(t,e.proxyFile)})`:e.manual?`standard tracking active — see note below for all-browser coverage`:`standard tracking active`:`standard tracking active`}function Tr(e){return e&&e.installed.length>0?e.installed.join(`, `):e&&e.errors.length>0?`failed: ${e.errors[0]?.message??`unknown error`}`:`none detected`}async function Er(e,t,n){n.setLiveLine(`Verifying the tracker is in your source…`);try{let r=await o(e,t),i=r.recommendation===`no-op`&&r.foundTrackingCodes.includes(t);n.setVerifyResult?.({ok:i,detail:i?`Tracker confirmed in your source files`:`Couldn't auto-confirm the tracker (diagnosis: ${r.recommendation}) — please double-check`})}catch{n.setVerifyResult?.({ok:!1,detail:`Verification check could not run`})}n.setLiveLine(void 0)}async function Dr(r,i,s,c){try{c.setPhase(`agent`);let l=await e(),u=await a({strict:!1}),d=new n({config:l,cliVersion:s.cliVersion,token:u}),f=new V({cwd:s.cwd}),p=e=>f.journalTrustedWrite(e),m=r.trackingCode??r.id;if(!J(m)){c.setErrorMsg(`The resolved tracking code "${m}" has an unexpected format (expected letters, digits, "_" or "-"). Aborting to avoid writing broken markup — re-check the site in your dashboard.`),c.setPhase(`error`);return}await t({defaultSiteId:r.id,defaultSiteName:r.name}).catch(()=>void 0);let h=await o(s.cwd,m);if(h.recommendation===`no-op`){c.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:`done`,detail:`already installed correctly`}:e)),c.setLiveLine(h.summary),c.setSandboxStats?.({reads:0,writes:0,rounds:0}),!s.skipMcp&&u&&await kt({accessToken:u.accessToken}).catch(()=>void 0);let e=await $(s,m,c,p);c.setVerifyResult?.({ok:!0,detail:xr(e)}),c.setPhase(`install-complete`);return}if(h.competitors.length>0&&c.setLiveLine(`Detected ${h.competitors.map(e=>e.name).join(`, `)} — will install Zenovay alongside (won't touch their tags).`),i.id===`next-app-router`){c.setTasks([{id:`detect`,label:`Detect framework`,status:`done`,detail:`Next.js (App Router)`},{id:`read`,label:`Find the document shell layout`,status:`active`},{id:`write`,label:`Insert tracker <Script>`,status:`pending`},{id:`env`,label:`Write env vars (.env.local)`,status:`pending`},{id:`mcp`,label:`Install MCP clients (Claude Code/Cursor/VS Code)`,status:`pending`},{id:`verify`,label:`Verify the tracker in your source`,status:`pending`}]),c.setLiveLine(`Next.js — locating the document shell layout…`);let e=await on({cwd:s.cwd,trackingCode:m,beforeWrite:p});if(c.recordChangedPaths?.(e.installed),!e.fellThrough&&e.errors.length===0){let t=e.installed[0]??`already installed`;c.setTasks(e=>e.map(e=>e.id===`read`||e.id===`write`?{...e,status:`done`,detail:t}:e));let n=await q(s.cwd,{[i.envVarName]:m},{beforeWrite:p});if((n.addedKeys.length>0||n.updatedKeys.length>0)&&c.recordChangedPaths?.([n.file]),c.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${n.addedKeys.length} key(s) added`}:e)),!s.skipMcp&&u){let e=await kt({accessToken:u.accessToken}).catch(e=>({installed:[],skipped:[],errors:[{client:`mcp`,message:e.message}]}));c.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:Tr(e)}:t))}else c.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await Er(s.cwd,m,c),c.setTasks(e=>e.map(e=>e.id===`verify`?{...e,status:`done`}:e)),c.setSandboxStats?.({reads:1,writes:e.installed.length,rounds:0}),await $(s,m,c,p),c.setPhase(`install-complete`);return}c.setLiveLine(`Custom Next.js structure — handing off to the AI agent…`)}let g=i.id===`plain-html`;if(g){c.setTasks([{id:`detect`,label:`Detect framework`,status:`done`,detail:`Plain HTML`},{id:`read`,label:`Scan .html pages`,status:`active`},{id:`write`,label:`Insert tracker <script>`,status:`pending`},{id:`env`,label:`Write env vars`,status:`pending`},{id:`mcp`,label:`Install MCP clients (Claude Code/Cursor/VS Code)`,status:`pending`},{id:`verify`,label:`Verify the tracker in your source`,status:`pending`}]),c.setLiveLine(`Plain HTML — using fast install path (no AI needed)…`);let e=await Jt({cwd:s.cwd,trackingCode:m,updateOnly:h.recommendation===`update-tracking-code`,beforeWrite:p});if(c.recordChangedPaths?.(e.installed),e.installed.length===0&&e.errors.length===0&&e.skipped.length===0)throw Error(`No .html files with a <head>...</head> block were found to inject the tracker into.`);if(e.installed.length===0&&e.errors.length>0)throw Error(`Programmatic install failed for all ${e.errors.length} file(s). First error: ${e.errors[0].file}: ${e.errors[0].error}`);c.setTasks(t=>t.map(t=>t.id===`read`||t.id===`write`?{...t,status:`done`,detail:`${e.installed.length} file(s)`}:t)),c.setLiveLine(`Tracker added to ${e.installed.length} file(s). Skipped ${e.skipped.length}, errored ${e.errors.length}.`);let t=await q(s.cwd,{[i.envVarName]:m},{beforeWrite:p});if((t.addedKeys.length>0||t.updatedKeys.length>0)&&c.recordChangedPaths?.([t.file]),c.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${t.addedKeys.length} key(s) added`}:e)),!s.skipMcp&&u){let e=await kt({accessToken:u.accessToken}).catch(e=>({installed:[],skipped:[],errors:[{client:`mcp`,message:e.message}]}));c.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:Tr(e)}:t))}else c.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await Er(s.cwd,m,c),c.setSandboxStats?.({reads:e.installed.length,writes:e.installed.length,rounds:0}),await $(s,m,c,p),c.setPhase(`install-complete`);return}{let e=await un({cwd:s.cwd,trackingCode:m,siteId:r.id,adapter:i,beforeWrite:p});c.recordChangedPaths?.(e.installed);let t=e.skipped.some(e=>/already installed|tracker present/i.test(e.reason));if(!e.fellThrough&&e.errors.length===0&&(e.installed.length>0||t)){c.setTasks([{id:`detect`,label:`Detect framework`,status:`done`,detail:i.displayName},{id:`write`,label:`Insert tracker snippet`,status:`done`,detail:e.installed[0]??`already installed`},{id:`env`,label:`Write env vars (.env.local)`,status:`active`},{id:`mcp`,label:`Install MCP clients (Claude Code/Cursor/VS Code)`,status:`pending`},{id:`verify`,label:`Verify the tracker in your source`,status:`pending`}]),c.setLiveLine(`${i.displayName} — using fast install path (no AI needed)…`);let t=await q(s.cwd,{[i.envVarName]:m},{beforeWrite:p});if((t.addedKeys.length>0||t.updatedKeys.length>0)&&c.recordChangedPaths?.([t.file]),c.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${t.addedKeys.length} key(s) added`}:e)),!s.skipMcp&&u){let e=await kt({accessToken:u.accessToken}).catch(e=>({installed:[],skipped:[],errors:[{client:`mcp`,message:e.message}]}));c.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:Tr(e)}:t))}else c.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await Er(s.cwd,m,c),c.setTasks(e=>e.map(e=>e.id===`verify`?{...e,status:`done`}:e)),c.setSandboxStats?.({reads:1,writes:e.installed.length,rounds:0}),await $(s,m,c,p),c.setPhase(`install-complete`);return}c.setLiveLine(`${i.displayName} needs a closer look — using the AI installer (a bit slower than the fast path)…`)}let _=i.buildSnippets({trackingCode:m,siteId:r.id}),v=`Install Zenovay tracking into this ${i.displayName} project.\nSite: ${r.name} (trackingCode: ${m}).\n1. Call detect_framework to confirm the framework.\n2. Read the entry file(s) for this framework:\n`+i.files.map(e=>` - ${e.path}`).join(`
|
|
349
|
+
`)+`
|
|
350
|
+
3. Insert the tracker using the snippet below.
|
|
351
|
+
4. Confirm the change with a diff before writing.
|
|
352
|
+
|
|
353
|
+
Snippet reference (anchored by anchorKind — adapt to the actual file):
|
|
354
|
+
`+_.map(e=>` ${e.anchorKind} @ ${e.targetPath}:\n ${e.code.replace(/\n/g,`
|
|
355
|
+
`)}`).join(`
|
|
356
|
+
|
|
357
|
+
`);c.setTasks([{id:`detect`,label:`Detect framework`,status:`active`},{id:`read`,label:`Read project entry files`,status:`pending`},{id:`write`,label:`Insert tracker snippet`,status:`pending`},{id:`env`,label:`Write env vars (.env.local)`,status:`pending`},{id:`mcp`,label:`Install MCP clients (Claude Code/Cursor/VS Code)`,status:`pending`},{id:`verify`,label:`Wait for first event`,status:`pending`}]);let y=(e,t,n)=>{c.setTasks(r=>r.map(r=>r.id===e?{...r,status:t,detail:n??r.detail}:r))},b=Un({mode:Hn(s)});c.registerBridge(b);let ee=b.subscribe(e=>c.setPendingApproval(e)),x=null,S=``,C=0;try{await Ut({api:d,sandbox:f,approval:b,prompter:{async ask({question:e}){return e}},handlers:{onToolStart:({name:e})=>{e===`detect_framework`?(y(`detect`,`active`),c.setLiveLine(`Inspecting package.json + config files…`)):e===`read_file`?(y(`detect`,`done`),y(`read`,`active`)):(e===`write_file`||e===`patch_file`)&&(y(`read`,`done`),y(`write`,`active`))},onToolResult:({name:e,result:t})=>{let n=t?.ok!==!1,r=t?.content??{};e===`detect_framework`&&n&&(y(`detect`,`done`,i.displayName),c.setLiveLine(`Detected ${i.displayName}`)),e===`read_file`&&n&&r.path&&c.setLiveLine(`Read ${r.path}`),(e===`write_file`||e===`patch_file`)&&n&&r.path&&(y(`read`,`done`),y(`write`,`done`,`wrote ${r.path}`),c.setLiveLine(`Wrote ${r.path}`))},onDelta:e=>{S=(S+e).slice(-600);let t=Date.now();if(t-C<280)return;C=t;let n=S.replace(/\s+/g,` `).trim().slice(-80);n.length>4&&c.setLiveLine(n)}},initialMessages:[{role:`user`,content:v}],diagnosis:h,targetTrackingCode:m})}catch(e){x=e}finally{ee(),c.setPendingApproval(null)}let w=f.stats();c.recordChangedPaths?.(w.writtenPaths);let T=w.writes>0?await o(s.cwd,m).catch(()=>null):null,E=Kt(w,T?.foundTrackingCodes??[],m,x);if(!E.ok)throw Error(E.error);y(`write`,`done`),y(`env`,`active`),c.setLiveLine(`Adding env var to .env.local`);let D=await q(s.cwd,{[i.envVarName]:m},{beforeWrite:p});if((D.addedKeys.length>0||D.updatedKeys.length>0)&&c.recordChangedPaths?.([D.file]),y(`env`,`done`,`${D.addedKeys.length} key(s) added`),!s.skipMcp&&u){y(`mcp`,`active`),c.setLiveLine(`Detecting Cursor / Claude Desktop / VS Code…`);let e=await kt({accessToken:u.accessToken}).catch(e=>({installed:[],skipped:[],errors:[{client:`mcp`,message:e.message}]}));y(`mcp`,`done`,Tr(e))}else y(`mcp`,`done`,`skipped`);c.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:e.status===`pending`?`done`:e.status}:e)),await Er(s.cwd,m,c),c.setSandboxStats?.(w),await $(s,m,c,p),c.setPhase(`install-complete`)}catch(e){c.setErrorMsg(e.message),c.setPhase(`error`)}}const Or=()=>{let{theme:e}=_();return M.createElement(g,{title:`Zenovay wants to set up your project`,state:`idle`},M.createElement(A,null,`We'll use AI to analyze your codebase and add the Zenovay tracker.`),M.createElement(A,{color:e.muted},`.env* contents stay on your machine. Only framework metadata reaches api.zenovay.com.`))},kr=({siteName:e,note:t,onChoose:n})=>{let{theme:r}=_(),i=[{label:`Cloudflare Pages`,value:`cloudflare-pages`,description:`writes functions/api/_z/[[path]].ts`},{label:`Vercel`,value:`vercel`,description:`adds a vercel.json rewrite`},{label:`Netlify`,value:`netlify`,description:`adds a _redirects rule`},{label:`Next.js (self-hosted)`,value:`nextjs-server`,description:`adds a next.config rewrite`},{label:`Skip — standard tracking only`,value:`skip`,description:`already works in Chrome, Firefox and most browsers`}];return M.createElement(k,{flexDirection:`column`,paddingX:2,paddingTop:1},M.createElement(A,{bold:!0},`Count visitors in every browser?`),t?M.createElement(A,{color:r.warn},t):null,M.createElement(A,{color:r.muted},`Your tracker already works. Safari, Edge and Brave block analytics loaded from another domain — serving Zenovay from your own domain fixes that. Where is `,e,` deployed?`),M.createElement(k,{marginTop:1},M.createElement(b,{items:i,onSelect:e=>n(e===`skip`?null:e)})))},Ar=({adapter:e,site:t,tasks:n,liveLine:r,pendingApproval:i,onApprove:a,pendingHostChoice:o,hostChoiceNote:s,onHostChoice:c})=>{let{theme:l}=_(),u=process.stdout.columns??100,d=(process.stdout.rows??30)-8,f=Math.floor(u/2)-1,p=Math.max(14,d);return M.createElement(k,{flexDirection:`column`},M.createElement(k,{flexDirection:`row`,minHeight:p,borderStyle:`round`,borderColor:l.border},M.createElement(k,{width:f,flexDirection:`column`},M.createElement(Zn,{width:f,height:p})),M.createElement(k,{width:1,flexDirection:`column`},M.createElement(A,{color:l.border},`│`)),M.createElement(k,{width:f,flexDirection:`column`},i?M.createElement(k,{flexDirection:`column`,paddingX:2,paddingTop:1},M.createElement(A,{color:l.warn},`The agent wants to write `,i.path),i.reason?M.createElement(A,{color:l.muted},i.reason):null,M.createElement(v,{key:i.id,filePath:i.path,oldContent:i.oldContent,newContent:i.newContent,onApprove:a})):o&&c?M.createElement(kr,{siteName:t.name,note:s,onChoose:c}):M.createElement(M.Fragment,null,M.createElement(k,{paddingX:2,paddingTop:1},M.createElement(y,{done:n.filter(e=>e.status===`done`).length,total:n.length,label:n.find(e=>e.status===`active`)?.label})),M.createElement(er,{tasks:n,liveLine:r,width:f,height:p})))),M.createElement(k,{marginTop:1},M.createElement(A,{color:l.muted},`Site: `,t.name,` · code: `,t.trackingCode??t.id,` · Framework: `,e.displayName)))},jr=({site:e,onContinueSetup:t,onReinstall:n,onExit:r})=>{let{theme:i}=_();re((e,i)=>{let a=e.toLowerCase();if(a===`q`||i.escape){r();return}if(a===`r`){n();return}if(a===`c`||i.return){t();return}});let a=e.url.replace(/^https?:\/\//,``).replace(/\/$/,``);return M.createElement(g,{title:`Already installed`,state:`ok`},M.createElement(k,{flexDirection:`column`,gap:1},M.createElement(k,{flexDirection:`row`,gap:1},M.createElement(A,{color:i.success},`✓`),M.createElement(A,{bold:!0},e.name),M.createElement(A,{color:i.muted},`(`,a,`)`)),M.createElement(A,{color:i.muted},`Zenovay is installed in this project. Verify the live site to continue setup.`),e.trackingCode?M.createElement(A,{color:i.dim},`tracking code: `,e.trackingCode):null,M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(A,null,M.createElement(A,{color:i.accent},`[Enter]`),` Verify the live site and continue setup`),M.createElement(A,null,M.createElement(A,{color:i.accent},`[R]`),` Reinstall or choose a different site`))))},Mr=({sites:e,preselectHint:t,onPick:n})=>{let r=tr(e,t),i=e.filter(e=>e.id!==r?.id),a=r?[r,...i]:i,o=[...a.map(e=>({label:Ur(e,e.id===r?.id),value:e,description:e.trackingCode?`trackingCode: ${e.trackingCode}`:void 0})),{label:`+ Create new site on app.zenovay.com`,value:`create-new`,description:`Open the dashboard to add a new website`}];return M.createElement(g,{title:t?`Pick a site (best match: ${t})`:`Pick a site`,state:`idle`},M.createElement(b,{items:o,onSelect:n}))};function Nr(){let e=process.argv[1]??``;return e.includes(`/_npx/`)||e.includes(`\\_npx\\`)||process.env.npm_execpath?.includes(`npx`)?`npx`:`global`}const Pr=({k:e,primary:t})=>{let{theme:n}=_();return M.createElement(A,null,M.createElement(A,{color:n.muted},`[`),M.createElement(A,{bold:!0,color:t?n.accent:n.fg},e),M.createElement(A,{color:n.muted},`] `))},Fr=({adapter:e,site:t,stats:n,modifiedFileCount:r,outcome:a,dashboardUrl:o,firstParty:s,onPick:c})=>{let{theme:u}=_(),d=Nr(),f=d===`npx`?`npx @zenovay/cli`:`zenovay`,p=o??i(t),m=a===`verified`,h=m?`You’re live on Zenovay`:a===`unverified`?`Tracker installed — not yet verified`:`Tracker installed — verification skipped`,v=m?`✓ First event received from ${t.name}`:a===`unverified`?`Installation finished, but no new event was confirmed.`:`Installation finished without checking for a new event.`,y=n&&n.rounds>0?`${Sr(r)} · ${n.rounds} agent round(s)`:r>0?`${Sr(r)} · programmatic (no AI calls)`:null;return re((e,t)=>{let n=e.toLowerCase();n===`o`?l(p):n===`q`||t.escape||n===`s`?c(`quit`):m&&(n===`w`||t.return)?c(`watch`):m&&n===`e`?c(`events`):!m&&t.return&&c(`quit`)},{isActive:!0}),M.createElement(g,{title:h,state:m?`ok`:`warn`},M.createElement(A,{bold:!0,color:m?u.success:u.warn},v),M.createElement(A,{color:u.accent},`─`.repeat(18)),M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(X,{label:`Framework`,value:e.displayName}),M.createElement(X,{label:`Site`,value:M.createElement(Vn,{url:t.url,label:t.name})}),t.trackingCode?M.createElement(X,{label:`Tracker`,value:M.createElement(A,{color:u.muted},t.trackingCode)}):M.createElement(X,{label:`Tracker`,value:M.createElement(A,{color:u.warn},t.id,` (using site ID — verify in dashboard)`)}),y?M.createElement(X,{label:`Changes`,value:M.createElement(A,{color:u.muted},y)}):null,m?null:M.createElement(X,{label:`Verification`,value:M.createElement(A,{color:u.warn},a===`unverified`?`No event confirmed`:`Skipped`)}),M.createElement(X,{label:`Dashboard`,value:M.createElement(Vn,{url:p})})),s&&s.proxyFile&&s.proxyAction!==`manual`&&s.proxyAction!==`skipped`?M.createElement(k,{marginTop:1},M.createElement(A,{color:u.success},`✓ `),M.createElement(A,{color:u.muted},`Analytics now load from your own domain — after you deploy, Safari, Edge and Brave visitors are counted too.`)):s?.manual?M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(A,{color:u.muted},`Counting visitors in every browser (optional):`),M.createElement(A,{color:u.muted},` `,s.manual)):null,M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(A,{color:u.dim},`Next steps`),m?M.createElement(k,{marginTop:1},M.createElement(A,null,` `),M.createElement(Pr,{k:`W`,primary:!0}),M.createElement(A,null,`Watch live in this terminal `),M.createElement(A,{color:u.muted},`— visitors, pages, sources, vitals`)):null,M.createElement(k,null,M.createElement(A,null,` `),M.createElement(Pr,{k:`O`}),M.createElement(A,null,`Open the dashboard in your browser`)),m?M.createElement(k,null,M.createElement(A,null,` `),M.createElement(Pr,{k:`E`}),M.createElement(A,null,`Stream events as they fire `),M.createElement(A,{color:u.muted},`— page views, custom events, live`)):null,M.createElement(k,null,M.createElement(A,null,` `),M.createElement(Pr,{k:`S`}),M.createElement(A,null,`Exit to shell`))),d===`npx`?M.createElement(k,{marginTop:1,flexDirection:`column`,borderStyle:`single`,borderColor:u.warn,paddingX:1},M.createElement(A,{color:u.warn,bold:!0},`Heads up — you ran via npx`),M.createElement(A,{color:u.muted},"The `zenovay` command isn’t on your PATH yet. After you exit, run:"),M.createElement(k,{marginTop:1},M.createElement(A,{color:u.fg},` npm i -g @zenovay/cli `),M.createElement(A,{color:u.muted},"→ then `zenovay overview` works directly"))):M.createElement(k,{marginTop:1},M.createElement(A,{color:u.muted},`From your shell: `),M.createElement(A,{color:u.fg},f,` overview`),M.createElement(A,{color:u.muted},` · `),M.createElement(A,{color:u.fg},f,` --help`)))},Ir=({cwd:e,adapter:t,site:n,stats:r,modifiedFileCount:i,verify:a,firstParty:o,onCommit:s,onSkipCommit:c,onQuit:l})=>{let{theme:u}=_();return Hr((e,t)=>{e===`q`||e===`Q`||t.escape?l():e===`y`||e===`Y`||t.return?s():(e===`n`||e===`N`||e===`s`||e===`S`)&&c()}),M.createElement(g,{title:`Tracker installed`,state:a&&!a.ok?`warn`:`ok`},a?M.createElement(A,null,M.createElement(A,{color:a.ok?u.success:u.warn},a.ok?`✔ Verified — `:`⚠ `),a.detail):M.createElement(A,null,M.createElement(A,{color:u.success},`✔ `),`The Zenovay tracker is in your project.`),M.createElement(k,{marginTop:1},M.createElement(A,{color:u.muted},`Framework: `),M.createElement(A,null,t.displayName)),M.createElement(k,null,M.createElement(A,{color:u.muted},`Site: `),M.createElement(A,null,n.name,` (`,n.url,`)`)),r&&M.createElement(k,null,M.createElement(A,{color:u.muted},`Modified: `),M.createElement(A,null,Sr(i))),M.createElement(Lr,{cwd:e,firstParty:o}),M.createElement(k,{marginTop:1},M.createElement(A,null,`Commit + push these changes to git? `),M.createElement(A,{color:u.accent},`[Y/n]`)))},Lr=({cwd:e,firstParty:t})=>{let{theme:n}=_();if(!t)return null;let r=t.proxyFile&&t.proxyAction!==`manual`&&t.proxyAction!==`skipped`?t.proxyFile:null;return r?M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(k,null,M.createElement(A,{color:n.success},`✔ `),M.createElement(A,null,`Analytics now load from your own domain `),M.createElement(A,{color:n.muted},`(`,Cr(e,r),`)`)),M.createElement(A,{color:n.muted},`After you deploy, Safari, Edge and Brave visitors are counted too.`)):t.manual?M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(k,null,M.createElement(A,{color:n.muted},`Counting visitors in every browser (optional):`)),M.createElement(A,{color:n.muted},t.manual)):null},Rr=({cwd:e,baseline:t,changedPaths:n,onDone:r,onError:i})=>{let{theme:a}=_(),[o,s]=F(`committing`),[c,l]=F(`Checking the Zenovay file journal…`),u=P(!1);return N(()=>{u.current||(u.current=!0,(async()=>{try{let i=await lr({cwd:e,baseline:t,changedPaths:n,onDetail:e=>l(e),onPhase:e=>s(e)});s(`done`),l(i.message),setTimeout(()=>r(i),800)}catch(e){i(e.message)}})())},[t,n,e,r,i]),M.createElement(g,{title:`Committing to git`,state:`busy`},M.createElement(k,null,o===`done`?M.createElement(A,{color:a.success},`✓`):M.createElement(A,{color:a.accent},M.createElement(I,{type:`dots`})),M.createElement(A,null,` `,o===`pushing`?`Pushing to origin…`:o===`done`?`Git step finished`:`Committing…`)),M.createElement(k,{marginTop:1},M.createElement(A,{color:a.muted},c)))},zr=({site:e,notice:t,onDeployed:n,onSkip:r,onQuit:i})=>{let{theme:a}=_();return Hr((e,t)=>{e===`q`||e===`Q`||t.escape?i():e===`y`||e===`Y`||t.return||e===`d`||e===`D`?n():(e===`n`||e===`N`||e===`s`||e===`S`)&&r()}),M.createElement(g,{title:`Ready to deploy?`,state:`idle`},M.createElement(A,null,`The tracker is installed locally. To capture events you need it on the live site:`),M.createElement(A,null,` `),M.createElement(k,null,M.createElement(A,{color:a.muted},` → `),M.createElement(Vn,{url:e.url})),M.createElement(A,null,` `),M.createElement(A,{color:a.muted},`Push the change through your normal deploy pipeline (Vercel auto-deploy, CI/CD, etc.).`),t?M.createElement(k,{marginTop:1},M.createElement(A,{color:a.warn},t)):null,M.createElement(k,{marginTop:1},M.createElement(A,null,`Once it’s deployed, press `),M.createElement(A,{color:a.accent},`[Y]`),M.createElement(A,null,` to verify the tracker is firing. `),M.createElement(A,{color:a.muted},`[s] skip verification`)))},Br=({site:e,onContinue:t,onQuit:n})=>{let{theme:r}=_();return Hr((e,r)=>{e===`q`||e===`Q`||r.escape?n():t()}),M.createElement(g,{title:`Visit your site`,state:`idle`},M.createElement(A,null,`To send a test event, open any page on your site:`),M.createElement(A,null,` `),M.createElement(k,null,M.createElement(A,{color:r.muted},` → `),M.createElement(Vn,{url:e.url})),M.createElement(A,null,` `),M.createElement(A,{color:r.muted},`The tracker fires automatically on page load. We’ll verify the next event arrives.`),M.createElement(k,{marginTop:1},M.createElement(A,null,`Press `),M.createElement(A,{color:r.accent},`[any key]`),M.createElement(A,null,` when you’ve visited the page.`)))},Vr=({site:t,since:r,elapsed:i,onTick:o,onArrived:s,onTimeout:c,onSkip:l,onQuit:u})=>{let{theme:d}=_(),[f,p]=F(`preflight`),[m,h]=F(``),[v,y]=F([]),b=P(!1),ee=t.trackingCode??t.id,x=async()=>{p(`preflight`),h(`Fetching ${t.url}…`);let e=await gr(t.url,ee);if(b.current)return;if(e.state===`tracker-correct`){p(`polling`),h(`Tracker detected on live site — waiting for first hit…`),S();return}if(e.state===`tracker-wrong-id`){p(`wrong-id-on-live`),y(e.foundCodes),h(`Live site has Zenovay but with id(s): ${e.foundCodes.join(`, `)}`);return}if(e.state===`proxy-broken`){p(`proxy-broken`),h(`${e.detail} Route: ${e.scriptUrl}`);return}p(`awaiting-deploy`);let n=e.networkError?/enotfound|getaddrinfo|dns/i.test(e.networkError)?` (DNS lookup failed — check the site URL is correct + deployed)`:/timeout|etimedout|abort|econnrefused|network/i.test(e.networkError)?` (check your internet connection, then retry with [r])`:``:``;h(e.networkError?`Couldn’t reach ${t.url}: ${e.networkError}${n}`:e.httpStatus?`${t.url} returned HTTP ${e.httpStatus}`:`No Zenovay tracker found on ${t.url}.`)},S=async()=>{try{let i=await e(),c=await a({strict:!1}),l=new n({config:i,cliVersion:`0`,token:c}),u=await At(t.id,r,{api:l,timeoutMs:6e4,pollIntervalMs:2500,onTick:e=>{b.current||o(e)}});if(b.current)return;u.received?(p(`success`),s()):p(`timeout`)}catch{b.current||p(`timeout`)}};N(()=>(b.current=!1,x(),()=>{b.current=!0}),[]),re((e,t)=>{if(e===`q`||e===`Q`||t.escape){u();return}if(e===`s`||e===`S`){f===`timeout`?c():f!==`success`&&l();return}(f===`awaiting-deploy`||f===`wrong-id-on-live`||f===`proxy-broken`||f===`timeout`)&&(e===`r`||e===`R`)&&x()},{isActive:!0});let C=Math.floor(i/1e3);return f===`preflight`?M.createElement(g,{title:`Verifying`,state:`busy`},M.createElement(k,null,M.createElement(A,{color:d.accent},M.createElement(I,{type:`dots`})),M.createElement(A,null,` Checking your live site for the tracker…`)),M.createElement(k,{marginTop:1},M.createElement(A,{color:d.muted},m))):f===`awaiting-deploy`?M.createElement(g,{title:`Tracker not yet on your live site`,state:`warn`},M.createElement(A,{color:d.warn},m),M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(A,null,`The tracker is in your local repo but hasn’t been deployed yet.`),M.createElement(A,{color:d.muted},`Push your changes and wait for your deploy to finish (Vercel / Cloudflare Pages / CI), then retry.`)),M.createElement(k,{marginTop:1},M.createElement(A,null,`Press `),M.createElement(A,{color:d.accent},`[r]`),M.createElement(A,null,` to re-check, `),M.createElement(A,{color:d.accent},`[s]`),M.createElement(A,null,` to skip verification.`))):f===`wrong-id-on-live`?M.createElement(g,{title:`Live site has a different tracking code`,state:`warn`},M.createElement(A,{color:d.warn},`Expected: `,M.createElement(A,{color:d.accent},ee),` `,`Found on live: `,M.createElement(A,{color:d.accent},v.join(`, `))),M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(A,null,`Your local install uses a different ID than what’s on `,t.url,`.`),M.createElement(A,{color:d.muted},`Deploy the new local version, then retry — or skip if the existing ID is intentional.`)),M.createElement(k,{marginTop:1},M.createElement(A,null,`Press `),M.createElement(A,{color:d.accent},`[r]`),M.createElement(A,null,` to re-check, `),M.createElement(A,{color:d.accent},`[s]`),M.createElement(A,null,` to skip.`))):f===`proxy-broken`?M.createElement(g,{title:`First-party proxy is not working`,state:`warn`},M.createElement(A,{color:d.warn},m),M.createElement(k,{marginTop:1,flexDirection:`column`},M.createElement(A,null,`The tracker tag is deployed, but its same-origin script route did not return the Zenovay JavaScript.`),M.createElement(A,{color:d.muted},`Check the host rewrite or function route, deploy the fix, then retry.`)),M.createElement(k,{marginTop:1},M.createElement(A,null,`Press `),M.createElement(A,{color:d.accent},`[r]`),M.createElement(A,null,` to re-check, `),M.createElement(A,{color:d.accent},`[s]`),M.createElement(A,null,` to skip.`))):f===`timeout`?M.createElement(g,{title:`No event arrived in 1 minute`,state:`warn`},M.createElement(A,{color:d.warn},`The tracker is on your live site but no hits reached api.zenovay.com.`),M.createElement(k,{marginTop:1},M.createElement(A,{color:d.muted},`Try opening `,t.url,` in a fresh browser tab (no ad-blocker), then retry.`)),M.createElement(k,{marginTop:1},M.createElement(A,null,`Press `),M.createElement(A,{color:d.accent},`[r]`),M.createElement(A,null,` to re-check, `),M.createElement(A,{color:d.accent},`[s]`),M.createElement(A,null,` to finish without verification.`))):f===`success`?M.createElement(g,{title:`First event received`,state:`busy`},M.createElement(k,null,M.createElement(A,{color:d.success},`✓`),M.createElement(A,null,` Resolving your next setup step…`))):M.createElement(g,{title:`Waiting for first event`,state:`busy`},M.createElement(k,null,M.createElement(A,{color:d.accent},M.createElement(I,{type:`dots`})),M.createElement(A,null,` Polling api.zenovay.com for the first hit on `),M.createElement(A,{color:d.accent},t.url),M.createElement(A,null,` (`,C,`s elapsed)`)),M.createElement(k,{marginTop:1},M.createElement(A,{color:d.muted},`Reload the page if nothing arrives within ~30 seconds.`)))};function Hr(e){re((t,n)=>{e(t,{return:n.return,escape:n.escape})},{isActive:!0})}function Ur(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 Wr(e){try{let t=await w.readFile(C.join(e,`package.json`),`utf8`),n=JSON.parse(t);if(n.name)return String(n.name).replace(/^@[^/]+\//,``)}catch{}try{let t=await w.readFile(C.join(e,`.git`,`config`),`utf8`),n=t.match(/url\s*=\s*.*[/:]([^/]+?)(?:\.git)?\s*$/m);if(n&&n[1])return n[1]}catch{}return C.basename(e)}export{jr as AlreadyInstalledPanel,kr as HostChoicePanel,Ir as InstallCompletePanel,Sr as formatFileCount,_r as initCommand,xr as noOpInstallVerificationDetail};
|
package/dist/wizard-bin.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import(`./init-
|
|
2
|
+
import(`./init-B9onI_od.js`).then(async({initCommand:e})=>{let{readFileSync:t}=await import(`node:fs`),n=await import(`node:path`),{fileURLToPath:r}=await import(`node:url`),i=n.dirname(r(import.meta.url)),a=JSON.parse(t(n.join(i,`..`,`package.json`),`utf8`)),o=process.argv.slice(2),s=o.includes(`--json`),c=o.includes(`--yes`),l=o.includes(`--skip-mcp`),u=o.includes(`--skip-verify`),d=await e({cliVersion:a.version,cwd:process.cwd(),json:s,yes:c,skipMcp:l,skipVerify:u});process.exit(d)});
|