@kizenapps/cli 1.1.2-590a1f4 → 1.4.0-fcc7387

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.
Files changed (46) hide show
  1. package/dist/index.js +1 -1
  2. package/dist/index.js.map +1 -1
  3. package/dist/viewer/assets/{AppDetailPage-BorvgFPN.js → AppDetailPage-bXSN_SkL.js} +1 -1
  4. package/dist/viewer/assets/{BootstrapContext-D5ZnMrOp.js → BootstrapContext-BJMPPV2t.js} +1 -1
  5. package/dist/viewer/assets/Card-DRaOqhzt.js +1 -0
  6. package/dist/viewer/assets/{CodeStepsPage-DnL8JwSJ.js → CodeStepsPage-BzLWCjg6.js} +1 -1
  7. package/dist/viewer/assets/{CodeViewer-C9aVhzG7.js → CodeViewer-sTHrPWAx.js} +1 -1
  8. package/dist/viewer/assets/{ConfigurationPage-CAdaFi9y.js → ConfigurationPage-DHbuiVlX.js} +1 -1
  9. package/dist/viewer/assets/{DevSidebar-DS8UU-G8.js → DevSidebar-C8F2KFXY.js} +1 -1
  10. package/dist/viewer/assets/{IconReferencePage-bTBpdJEd.js → IconReferencePage-BDKMGmeG.js} +1 -1
  11. package/dist/viewer/assets/{SandboxPage-CU6fvI8A.js → SandboxPage-CMq8Xrjk.js} +1 -1
  12. package/dist/viewer/assets/SidebarContext-CENlTk-2.js +1 -0
  13. package/dist/viewer/assets/{SourceBrowserPage-BBZcr3MI.js → SourceBrowserPage-Clg_fH0I.js} +1 -1
  14. package/dist/viewer/assets/{Tooltip-tpqNw0op.js → Tooltip-9-UcK9bz.js} +1 -1
  15. package/dist/viewer/assets/{VersionsPage-D6QScnTb.js → VersionsPage-BRfN-13x.js} +1 -1
  16. package/dist/viewer/assets/{WhenBadge-DZrl6k94.js → WhenBadge-DY21YMpA.js} +1 -1
  17. package/dist/viewer/assets/api-DJcHZP2k.js +10 -0
  18. package/dist/viewer/assets/{bundleQuery-CjbA01rb.js → bundleQuery-Bjqi6ox2.js} +1 -1
  19. package/dist/viewer/assets/{calendarSource.worker-DGRTJYHs.js → calendarSource.worker-2UhvqVzo.js} +4 -4
  20. package/dist/viewer/assets/{configStorage-aLI-65re.js → configStorage-fNlYS08a.js} +1 -1
  21. package/dist/viewer/assets/{fa-core-BoBqCOD3.js → fa-core-B7dAyAZA.js} +1 -1
  22. package/dist/viewer/assets/{fa-pro-icons-j8-_MCQ7.js → fa-pro-icons-DtrKpGj8.js} +1 -1
  23. package/dist/viewer/assets/floatingFrame.worker-BPvRqAU5.js +23 -0
  24. package/dist/viewer/assets/{generic.worker-Bzr3c9PO.js → generic.worker-CaEdS_L8.js} +4 -4
  25. package/dist/viewer/assets/index-BqEAhAQ_.css +2 -0
  26. package/dist/viewer/assets/index-ZdHVsbQr.js +5 -0
  27. package/dist/viewer/assets/{react-csXWLXSE.js → react-j0eBFjQW.js} +1 -1
  28. package/dist/viewer/assets/{recordDetail.worker-B-1qFS5m.js → recordDetail.worker-DIZ1eFYu.js} +6 -6
  29. package/dist/viewer/assets/rolldown-runtime-Dw2cE7zH.js +1 -0
  30. package/dist/viewer/assets/storageKeys-CSWy3aiP.js +1 -0
  31. package/dist/viewer/assets/useCriticalExceptionDialog-4AtgdUhp.js +40 -0
  32. package/dist/viewer/assets/{useLocalStorage-CyZiO78q.js → useLocalStorage-BTxXC7un.js} +1 -1
  33. package/dist/viewer/assets/{useNavigate-BblEmQ3O.js → useNavigate-AMIImip9.js} +1 -1
  34. package/dist/viewer/assets/{useQuery-5OkVbV1s.js → useQuery-CHCkzQbK.js} +1 -1
  35. package/dist/viewer/assets/{validIcons-BzGQ4tWD.js → validIcons-LvIGHq2c.js} +1 -1
  36. package/dist/viewer/index.html +13 -13
  37. package/package.json +12 -2
  38. package/dist/viewer/assets/Card-BpDJPrPZ.js +0 -1
  39. package/dist/viewer/assets/SidebarContext-Cn8QRb77.js +0 -1
  40. package/dist/viewer/assets/api-DtXiAEKW.js +0 -10
  41. package/dist/viewer/assets/floatingFrame.worker-CKAMagoG.js +0 -23
  42. package/dist/viewer/assets/index-Cp0A29vq.js +0 -5
  43. package/dist/viewer/assets/index-DtzraybB.css +0 -2
  44. package/dist/viewer/assets/rolldown-runtime-DF2fYuay.js +0 -1
  45. package/dist/viewer/assets/storageKeys-C6c8YF5Y.js +0 -1
  46. package/dist/viewer/assets/useCriticalExceptionDialog-C8PL9Dxt.js +0 -5
package/dist/index.js CHANGED
@@ -168,7 +168,7 @@ sys.stdout.flush()
168
168
  `.trim(),Hn=3e4,wt=Re(process.cwd(),".kizenapp","venv"),Un=["awslambdaric","bcrypt","fpdf2","lxml","msgpack","numpy","paramiko","pyjwt","pypdf","pytz","requests","tzdata"],Ke=null;function qn(e){let t=/^python-(\d+\.\d+)$/.exec(e);return t?.[1]?`python${t[1]}`:"python3"}function tr(e,t,o){return new Promise((r,n)=>{let s=rr(e,t,{stdio:["ignore","pipe","pipe"]}),g=(C,b)=>{let x=[],h="";return C.on("data",y=>{h+=y.toString("utf-8");let c=h.indexOf(`
169
169
  `);for(;c>=0;){let v=h.slice(0,c).replace(/\r$/,"");h=h.slice(c+1),x.push(v),o?.(v,b),c=h.indexOf(`
170
170
  `)}}),C.on("end",()=>{if(h.length>0){let y=h.replace(/\r$/,"");x.push(y),o?.(y,b)}}),x},u=g(s.stderr,"stderr");g(s.stdout,"stdout"),s.on("error",n),s.on("close",C=>{if(C===0)r();else{let b=u.slice(-10).join(`
171
- `).trim(),x=b.length>0?`: ${b}`:"";n(new Error(`${e} exited with code ${String(C)}${x}`))}})})}var Ct=new Set;function Xe(e){for(let t of Ct)t(e)}function Vn(e,t){return t&&Ct.add(t),Ke||(Ke=(async()=>{let o=Re(wt,"bin","python");try{await On(o)}catch{let r=qn(e);await tr(r,["-m","venv",wt])}Xe({kind:"start"});try{await tr(o,["-m","pip","install","--disable-pip-version-check",...Un],(r,n)=>{Xe({kind:"log",line:r,stream:n})}),Xe({kind:"complete"})}catch(r){let n=r instanceof Error?r.message:String(r);throw Xe({kind:"error",message:n}),Ke=null,await nr(wt,{recursive:!0,force:!0}).catch(()=>{}),r}finally{Ct.clear()}return o})()),Ke}function Jn(e){let t="__KIZEN_RESULT_START__",o="__KIZEN_RESULT_END__",r=e.indexOf(t),n=e.indexOf(o);if(r===-1||n===-1)return{userStdout:e,result:null};let s=e.slice(0,r).trimEnd(),g=e.slice(r+t.length,n).trim();try{let u=JSON.parse(g);return{userStdout:s,result:u}}catch{return{userStdout:e,result:null}}}async function or(e){let t=e.timeout??Hn,o=await Vn(e.scriptRuntime,e.onInstallProgress),r=Date.now(),n;try{n=await An(Re(zn(),"kizen-step-"));let s=Re(n,"wrapper.py"),g=Re(n,"script.py");await Promise.all([er(s,Mn,"utf-8"),er(g,e.script,"utf-8")]);let u={...process.env,__KIZEN_INPUTS__:JSON.stringify(e.inputs),__KIZEN_SECRETS__:JSON.stringify(e.secrets),__KIZEN_SCRIPT_PATH__:g},{exitCode:C,stdout:b,stderr:x}=await new Promise(E=>{let R=[],S=[],m=!1,p=rr(o,[s],{env:u,cwd:n,stdio:["ignore","pipe","pipe"]}),P=setTimeout(()=>{p.kill("SIGKILL")},t);p.stdout.on("data",i=>{R.push(i)}),p.stderr.on("data",i=>{S.push(i)});let a=i=>{m||(m=!0,clearTimeout(P),E({exitCode:i??1,stdout:Buffer.concat(R).toString("utf-8"),stderr:Buffer.concat(S).toString("utf-8")}))};p.on("close",a),p.on("error",i=>{m||(m=!0,clearTimeout(P),E({exitCode:1,stdout:"",stderr:i.message}))})}),h=Date.now()-r,{userStdout:y,result:c}=Jn(b);if(c){let E={success:c.success,outputValues:c.outputValues,logs:c.logs,stdout:y,stderr:x,exitCode:C,durationMs:h};return c.error!==null&&(E.error=c.error),c.httpRequests&&(E.httpRequests=c.httpRequests),E}let v={success:!1,outputValues:{},logs:[],stdout:y,stderr:x,exitCode:C,durationMs:h};return C!==0&&(v.error=`Process exited with code ${String(C)}`),v}finally{n&&nr(n,{recursive:!0,force:!0})}}var ir=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".json",".md",".mdx",".yml",".yaml",".toml",".css",".scss",".html",".htm",".xml",".svg",".txt",".sh",".py",".env",".gitignore",".prettierrc",".eslintrc"]);function St(e){if(e.kind==="info")return e.message;let t=e.fromCache?" [cache]":"";return`${e.method} ${e.url} \u2192 ${String(e.status)}${t}`}var to=2*1024*1024,ro=new Set([".DS_Store",".gitignore"]);function no(e){if(e===void 0||e==="")return!1;let t=e.startsWith("[")?e.slice(0,e.indexOf("]")+1):e.split(":")[0]??"";return t==="localhost"||t==="127.0.0.1"||t==="[::1]"}var oo=["kizen.com","kizen.dev"];function io(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let o=t.hostname.toLowerCase();return oo.some(r=>o===r||o.endsWith("."+r))}function so(e){if(e===void 0||e==="")return!1;try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"}catch{return!1}}async function cr(e,t){if(t.includes("\0"))return null;let o=t.replace(/^\/+/,""),r=Qn(e,o);if(r!==e&&!r.startsWith(e+Pt))return null;try{let n=await Yn(r);return n!==e&&!n.startsWith(e+Pt)?null:n}catch{return null}}function dr(e,t){let o=t===e?"":t.slice(e.length+1);return o===""?!1:o.split(Pt).some(n=>ze.has(n))}function ur(){let e=eo(import.meta.url);return Ne(Zn(e),"viewer")}async function Tt(e){try{return await Gn(e),!0}catch{return!1}}function pr(e,t,o,r,n,s,g,u,C,b){let x=Zt({onChange:u}),h=Wn(b);return(y,c)=>{(async()=>{let v=y.url??"/";try{if(!no(y.headers.host)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Forbidden"}));return}if((y.method==="POST"||y.method==="PATCH"||y.method==="DELETE")&&!so(y.headers.origin)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Forbidden"}));return}if(t(`Received request: ${v}`),v==="/api/credentials"){c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(r.current!==null?JSON.stringify(r.current):"{}");return}if(v==="/api/credential-profiles"&&y.method==="GET"){let a=await Ie();c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({profiles:a,active:n.current}));return}if(v==="/api/credentials/switch"&&y.method==="POST"){let a=[];for await(let f of y)a.push(f);let l=JSON.parse(Buffer.concat(a).toString("utf-8")||"{}").profile,d=l===void 0||l===""?await Y():await we(l);if(d!==null){r.current=d,n.current=l??void 0;let f=n.current;await me(s,{credentialMode:"global",...f!==void 0&&{activeCredentialProfile:f}}),g({type:"credentials-updated",credentials:d})}c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({ok:d!==null}));return}if(v==="/api/bundle"){let a=Ne(process.cwd(),".kizenapp","bundle.json");try{let i=await Xn(a,"utf-8");c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(i)}catch{c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end("{}")}return}if(v==="/api/last-path"&&y.method==="POST"){let a=[];for await(let l of y)a.push(l);let i=JSON.parse(Buffer.concat(a).toString("utf-8")||"{}");if(typeof i.path=="string"){C.current=i.path;let l=await De(s);await me(s,{...l,lastPath:i.path})}c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end('{"ok":true}');return}if(v==="/api/execute-step"&&y.method==="POST"){let a=[];for await(let f of y)a.push(f);let i=JSON.parse(Buffer.concat(a).toString("utf-8")||"{}");if(typeof i.script!="string"){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Missing required field: script"}));return}let l={script:i.script,scriptRuntime:i.scriptRuntime??"python-3.9",inputs:i.inputs??{},secrets:i.secrets??{},onInstallProgress:f=>{f.kind==="start"?g({type:"venv-install-start"}):f.kind==="log"?g({type:"venv-install-log",line:f.line,stream:f.stream}):f.kind==="complete"?g({type:"venv-install-complete"}):g({type:"venv-install-error",message:f.message})}};typeof i.timeout=="number"&&i.timeout>0&&(l.timeout=Math.min(i.timeout,300*1e3));let d=await or(l);c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify(d));return}if(v==="/api/proxy-cache/clear"){x.clear(),o({kind:"info",message:"Proxy cache cleared"}),c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end('{"ok":true}');return}if(v.startsWith("/api/proxy")){let a=y.headers["x-proxy-target"];if(typeof a!="string"){c.writeHead(400),c.end("Missing x-proxy-target header");return}if(!io(a)){c.writeHead(400),c.end("Invalid proxy target");return}let i=v.slice(10)||"/",l=`${a}${i}`,d=y.method??"GET",f=[];for await(let Pe of y)f.push(Pe);let{host:F,"x-proxy-target":k,...N}=y.headers;if(d==="GET"){let Pe=`GET::${l}`,{response:se,fromCache:ot}=await x.get(Pe,()=>fetch(l,{method:"GET",headers:N}));o({kind:"request",method:"GET",status:se.status,fromCache:ot,url:i}),c.writeHead(se.status,se.headers),c.end(se.body);return}let A=f.length>0?Buffer.concat(f):void 0,H=A&&A.length>0?A:void 0,W=await fetch(l,{method:d,headers:N,...H!==void 0&&{body:H}}),ee=ht(Object.fromEntries(W.headers)),ge=await bt(W,xt);o({kind:"request",method:d,status:W.status,fromCache:!1,url:i}),c.writeHead(W.status,ee),c.end(ge);return}if(v.startsWith("/api/source/tree")&&y.method==="GET"){let i=new URL(v,"http://localhost").searchParams.get("path")??"",l=await cr(h,i);if(l===null){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Invalid path"}));return}if(dr(h,l)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Path is excluded"}));return}try{let d=await Kn(l,{withFileTypes:!0}),f=await Promise.all(d.filter(k=>k.isDirectory()?!ze.has(k.name):k.isFile()?!ro.has(k.name):!1).map(async k=>{let N=k.isDirectory()?"dir":"file",A={name:k.name,kind:N};if(N==="file")try{let H=await ar(Ne(l,k.name));A.size=H.size}catch{}return A}));f.sort((k,N)=>k.kind!==N.kind?k.kind==="dir"?-1:1:k.name.localeCompare(N.name));let F=l===h?"":l.slice(h.length+1);c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({path:F,entries:f}))}catch(d){let f=d instanceof Error?d.message:String(d);t(`source/tree failed (${i}): ${f}`),c.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not found"}))}return}if(v.startsWith("/api/source/file")&&y.method==="GET"){let i=new URL(v,"http://localhost").searchParams.get("path")??"";if(i===""){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Missing path"}));return}let l=await cr(h,i);if(l===null){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Invalid path"}));return}if(dr(h,l)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Path is excluded"}));return}try{let d=await ar(l);if(!d.isFile()){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not a file"}));return}if(d.size>to){c.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"File too large",size:d.size}));return}let f=lr(l).toLowerCase(),F=vt[f],k=ir.has(f),N=F??(k?"text/plain; charset=utf-8":"application/octet-stream");c.writeHead(200,{"Content-Type":N,"Content-Length":String(d.size)}),sr(l).pipe(c)}catch(d){let f=d instanceof Error?d.message:String(d);t(`source/file failed (${i}): ${f}`),c.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not found"}))}return}let S=Ne(e,v==="/"?"/index.html":v),m=await Tt(S)?S:Ne(e,"index.html"),p=lr(m),P=vt[p]??"application/octet-stream";c.writeHead(200,{"Content-Type":P}),sr(m).pipe(c)}catch(E){if(v.startsWith("/api/proxy")){let R=v.slice(10)||"/",S=y.method??"GET";E instanceof Be?o({kind:"info",message:`${S} ${R} \u2192 502 (response exceeded ${String(E.limit)} bytes)`}):o({kind:"request",method:S,status:502,fromCache:!1,url:R})}else o({kind:"info",message:`Error handling ${v}: ${E instanceof Error?E.message:String(E)}`});c.headersSent||(c.writeHead(502),c.end("Bad Gateway"))}})()}}import{launch as ao}from"chrome-launcher";import{createRequire as lo}from"module";import{mkdirSync as co}from"fs";import{readFile as uo}from"fs/promises";import{dirname as po,join as fo}from"path";import{fileURLToPath as mo}from"url";var fr=lo(import.meta.url)("chrome-remote-interface"),go=new Set(["content-security-policy","content-security-policy-report-only","x-frame-options"]),gr=["kizen.dev","kizen.com"];function mr(e){try{let{hostname:t}=new URL(e);return gr.some(o=>t===o||t.endsWith("."+o))}catch{return!1}}function Ye(e){if(e.type==="number")return Number(e.value);if(e.type==="boolean")return e.value==="true";if(e.type!=="undefined"){if(e.type==="object"&&e.value==="null")return null;if(e.type==="object"&&e.valuePreview){let{valuePreview:t}=e;if(t.subtype==="array")return t.properties.filter(r=>/^\d+$/.test(r.name)).sort((r,n)=>parseInt(r.name)-parseInt(n.name)).map(Ye);let o={};for(let r of t.properties)o[r.name]=Ye(r);return o}return e.value??`[${e.type}]`}}function yo(e){if(e.value!==void 0)return e.value;if(e.preview){let{preview:t}=e;if(t.subtype==="array")return t.properties.filter(r=>/^\d+$/.test(r.name)).sort((r,n)=>parseInt(r.name)-parseInt(n.name)).map(Ye);let o={};for(let r of t.properties)o[r.name]=Ye(r);return o}return e.description??`[${e.type}]`}async function ho(e,t){if(t.type==="object"&&t.objectId)try{let r=(await e.Runtime.callFunctionOn({objectId:t.objectId,functionDeclaration:'function() { try { const seen = new WeakSet(); return JSON.stringify(this, function(k,v) { if (typeof v === "bigint") { return String(v) + "n"; } if (typeof v === "object" && v !== null) { if (seen.has(v)) return "[Circular]"; seen.add(v); } return v; }); } catch { return undefined; } }',returnByValue:!0})).result.value;if(typeof r=="string")return JSON.parse(r)}catch{}return yo(t)}async function xo(e){try{let t=fo(po(mo(import.meta.url)),"viewer","icon.png"),o=await uo(t);await e.Browser.setDockTile({image:o.toString("base64")})}catch{}}async function yr(e){co(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,o=await ao({startingUrl:t,chromeFlags:[`--app=${t}`,"--no-first-run","--no-default-browser-check","--disable-extensions"],userDataDir:e.userDataDir,handleSIGINT:!1,logLevel:"silent"}),r=o.port,n=null,s=null,g=null,u=null,C=0,b=!1,x=p=>{e.debugLog?.(p)},h=p=>{e.verbose&&e.debugLog?.(p)},y=()=>{s!==null&&(clearInterval(s),s=null)},c=p=>p==="chrome://new-tab-page/"||p==="chrome://newtab/",v=async p=>{y(),g=null,await xo(p),await p.Fetch.enable({patterns:gr.flatMap(a=>[{urlPattern:`*://${a}/*`,requestStage:"Response"},{urlPattern:`*://*.${a}/*`,requestStage:"Response"}])}),p.on("Fetch.requestPaused",a=>{(async()=>{let i=a,{requestId:l,request:d,responseHeaders:f,responseStatusCode:F}=i,k=d.url;h(`Fetch ${String(F??"?")} ${k}`);let N=[],A=!1;for(let H of f??[])if(!go.has(H.name.toLowerCase()))if(H.name.toLowerCase()==="set-cookie"&&mr(k)){let W=H.value.split(`
171
+ `).trim(),x=b.length>0?`: ${b}`:"";n(new Error(`${e} exited with code ${String(C)}${x}`))}})})}var Ct=new Set;function Xe(e){for(let t of Ct)t(e)}function Vn(e,t){return t&&Ct.add(t),Ke||(Ke=(async()=>{let o=Re(wt,"bin","python");try{await On(o)}catch{let r=qn(e);await tr(r,["-m","venv",wt])}Xe({kind:"start"});try{await tr(o,["-m","pip","install","--disable-pip-version-check",...Un],(r,n)=>{Xe({kind:"log",line:r,stream:n})}),Xe({kind:"complete"})}catch(r){let n=r instanceof Error?r.message:String(r);throw Xe({kind:"error",message:n}),Ke=null,await nr(wt,{recursive:!0,force:!0}).catch(()=>{}),r}finally{Ct.clear()}return o})()),Ke}function Jn(e){let t="__KIZEN_RESULT_START__",o="__KIZEN_RESULT_END__",r=e.indexOf(t),n=e.indexOf(o);if(r===-1||n===-1)return{userStdout:e,result:null};let s=e.slice(0,r).trimEnd(),g=e.slice(r+t.length,n).trim();try{let u=JSON.parse(g);return{userStdout:s,result:u}}catch{return{userStdout:e,result:null}}}async function or(e){let t=e.timeout??Hn,o=await Vn(e.scriptRuntime,e.onInstallProgress),r=Date.now(),n;try{n=await An(Re(zn(),"kizen-step-"));let s=Re(n,"wrapper.py"),g=Re(n,"script.py");await Promise.all([er(s,Mn,"utf-8"),er(g,e.script,"utf-8")]);let u={...process.env,__KIZEN_INPUTS__:JSON.stringify(e.inputs),__KIZEN_SECRETS__:JSON.stringify(e.secrets),__KIZEN_SCRIPT_PATH__:g},{exitCode:C,stdout:b,stderr:x}=await new Promise(E=>{let R=[],S=[],m=!1,p=rr(o,[s],{env:u,cwd:n,stdio:["ignore","pipe","pipe"]}),P=setTimeout(()=>{p.kill("SIGKILL")},t);p.stdout.on("data",i=>{R.push(i)}),p.stderr.on("data",i=>{S.push(i)});let a=i=>{m||(m=!0,clearTimeout(P),E({exitCode:i??1,stdout:Buffer.concat(R).toString("utf-8"),stderr:Buffer.concat(S).toString("utf-8")}))};p.on("close",a),p.on("error",i=>{m||(m=!0,clearTimeout(P),E({exitCode:1,stdout:"",stderr:i.message}))})}),h=Date.now()-r,{userStdout:y,result:c}=Jn(b);if(c){let E={success:c.success,outputValues:c.outputValues,logs:c.logs,stdout:y,stderr:x,exitCode:C,durationMs:h};return c.error!==null&&(E.error=c.error),c.httpRequests&&(E.httpRequests=c.httpRequests),E}let v={success:!1,outputValues:{},logs:[],stdout:y,stderr:x,exitCode:C,durationMs:h};return C!==0&&(v.error=`Process exited with code ${String(C)}`),v}finally{n&&nr(n,{recursive:!0,force:!0})}}var ir=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".json",".md",".mdx",".yml",".yaml",".toml",".css",".scss",".html",".htm",".xml",".svg",".txt",".sh",".py",".env",".gitignore",".prettierrc",".eslintrc"]);function St(e){if(e.kind==="info")return e.message;let t=e.fromCache?" [cache]":"";return`${e.method} ${e.url} \u2192 ${String(e.status)}${t}`}var to=2*1024*1024,ro=new Set([".DS_Store",".gitignore"]);function no(e){if(e===void 0||e==="")return!1;let t=e.startsWith("[")?e.slice(0,e.indexOf("]")+1):e.split(":")[0]??"";return t==="localhost"||t==="127.0.0.1"||t==="[::1]"}var oo=["kizen.com","kizen.dev"];function io(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let o=t.hostname.toLowerCase();return oo.some(r=>o===r||o.endsWith("."+r))}function so(e){if(e===void 0||e==="")return!1;try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"}catch{return!1}}async function cr(e,t){if(t.includes("\0"))return null;let o=t.replace(/^\/+/,""),r=Qn(e,o);if(r!==e&&!r.startsWith(e+Pt))return null;try{let n=await Yn(r);return n!==e&&!n.startsWith(e+Pt)?null:n}catch{return null}}function dr(e,t){let o=t===e?"":t.slice(e.length+1);return o===""?!1:o.split(Pt).some(n=>ze.has(n))}function ur(){let e=eo(import.meta.url);return Ne(Zn(e),"viewer")}async function Tt(e){try{return await Gn(e),!0}catch{return!1}}function pr(e,t,o,r,n,s,g,u,C,b){let x=Zt({onChange:u}),h=Wn(b);return(y,c)=>{(async()=>{let v=y.url??"/";try{if(!no(y.headers.host)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Forbidden"}));return}if((y.method==="POST"||y.method==="PATCH"||y.method==="DELETE")&&!so(y.headers.origin)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Forbidden"}));return}if(t(`Received request: ${v}`),v==="/api/credentials"){c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({credentials:r.current??null,activeProfile:n.current??null}));return}if(v==="/api/credential-profiles"&&y.method==="GET"){let a=await Ie();c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({profiles:a,active:n.current}));return}if(v==="/api/credentials/switch"&&y.method==="POST"){let a=[];for await(let f of y)a.push(f);let l=JSON.parse(Buffer.concat(a).toString("utf-8")||"{}").profile,d=l===void 0||l===""?await Y():await we(l);if(d!==null){r.current=d,n.current=l??void 0;let f=n.current;await me(s,{credentialMode:"global",...f!==void 0&&{activeCredentialProfile:f}}),g({type:"credentials-updated",credentials:d,activeProfile:n.current??null})}c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({ok:d!==null}));return}if(v==="/api/bundle"){let a=Ne(process.cwd(),".kizenapp","bundle.json");try{let i=await Xn(a,"utf-8");c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(i)}catch{c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end("{}")}return}if(v==="/api/last-path"&&y.method==="POST"){let a=[];for await(let l of y)a.push(l);let i=JSON.parse(Buffer.concat(a).toString("utf-8")||"{}");if(typeof i.path=="string"){C.current=i.path;let l=await De(s);await me(s,{...l,lastPath:i.path})}c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end('{"ok":true}');return}if(v==="/api/execute-step"&&y.method==="POST"){let a=[];for await(let f of y)a.push(f);let i=JSON.parse(Buffer.concat(a).toString("utf-8")||"{}");if(typeof i.script!="string"){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Missing required field: script"}));return}let l={script:i.script,scriptRuntime:i.scriptRuntime??"python-3.9",inputs:i.inputs??{},secrets:i.secrets??{},onInstallProgress:f=>{f.kind==="start"?g({type:"venv-install-start"}):f.kind==="log"?g({type:"venv-install-log",line:f.line,stream:f.stream}):f.kind==="complete"?g({type:"venv-install-complete"}):g({type:"venv-install-error",message:f.message})}};typeof i.timeout=="number"&&i.timeout>0&&(l.timeout=Math.min(i.timeout,300*1e3));let d=await or(l);c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify(d));return}if(v==="/api/proxy-cache/clear"){x.clear(),o({kind:"info",message:"Proxy cache cleared"}),c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end('{"ok":true}');return}if(v.startsWith("/api/proxy")){let a=y.headers["x-proxy-target"];if(typeof a!="string"){c.writeHead(400),c.end("Missing x-proxy-target header");return}if(!io(a)){c.writeHead(400),c.end("Invalid proxy target");return}let i=v.slice(10)||"/",l=`${a}${i}`,d=y.method??"GET",f=[];for await(let Pe of y)f.push(Pe);let{host:F,"x-proxy-target":k,...N}=y.headers;if(d==="GET"){let Pe=`GET::${l}`,{response:se,fromCache:ot}=await x.get(Pe,()=>fetch(l,{method:"GET",headers:N}));o({kind:"request",method:"GET",status:se.status,fromCache:ot,url:i}),c.writeHead(se.status,se.headers),c.end(se.body);return}let A=f.length>0?Buffer.concat(f):void 0,H=A&&A.length>0?A:void 0,W=await fetch(l,{method:d,headers:N,...H!==void 0&&{body:H}}),ee=ht(Object.fromEntries(W.headers)),ge=await bt(W,xt);o({kind:"request",method:d,status:W.status,fromCache:!1,url:i}),c.writeHead(W.status,ee),c.end(ge);return}if(v.startsWith("/api/source/tree")&&y.method==="GET"){let i=new URL(v,"http://localhost").searchParams.get("path")??"",l=await cr(h,i);if(l===null){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Invalid path"}));return}if(dr(h,l)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Path is excluded"}));return}try{let d=await Kn(l,{withFileTypes:!0}),f=await Promise.all(d.filter(k=>k.isDirectory()?!ze.has(k.name):k.isFile()?!ro.has(k.name):!1).map(async k=>{let N=k.isDirectory()?"dir":"file",A={name:k.name,kind:N};if(N==="file")try{let H=await ar(Ne(l,k.name));A.size=H.size}catch{}return A}));f.sort((k,N)=>k.kind!==N.kind?k.kind==="dir"?-1:1:k.name.localeCompare(N.name));let F=l===h?"":l.slice(h.length+1);c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({path:F,entries:f}))}catch(d){let f=d instanceof Error?d.message:String(d);t(`source/tree failed (${i}): ${f}`),c.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not found"}))}return}if(v.startsWith("/api/source/file")&&y.method==="GET"){let i=new URL(v,"http://localhost").searchParams.get("path")??"";if(i===""){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Missing path"}));return}let l=await cr(h,i);if(l===null){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Invalid path"}));return}if(dr(h,l)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Path is excluded"}));return}try{let d=await ar(l);if(!d.isFile()){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not a file"}));return}if(d.size>to){c.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"File too large",size:d.size}));return}let f=lr(l).toLowerCase(),F=vt[f],k=ir.has(f),N=F??(k?"text/plain; charset=utf-8":"application/octet-stream");c.writeHead(200,{"Content-Type":N,"Content-Length":String(d.size)}),sr(l).pipe(c)}catch(d){let f=d instanceof Error?d.message:String(d);t(`source/file failed (${i}): ${f}`),c.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not found"}))}return}let S=Ne(e,v==="/"?"/index.html":v),m=await Tt(S)?S:Ne(e,"index.html"),p=lr(m),P=vt[p]??"application/octet-stream";c.writeHead(200,{"Content-Type":P}),sr(m).pipe(c)}catch(E){if(v.startsWith("/api/proxy")){let R=v.slice(10)||"/",S=y.method??"GET";E instanceof Be?o({kind:"info",message:`${S} ${R} \u2192 502 (response exceeded ${String(E.limit)} bytes)`}):o({kind:"request",method:S,status:502,fromCache:!1,url:R})}else o({kind:"info",message:`Error handling ${v}: ${E instanceof Error?E.message:String(E)}`});c.headersSent||(c.writeHead(502),c.end("Bad Gateway"))}})()}}import{launch as ao}from"chrome-launcher";import{createRequire as lo}from"module";import{mkdirSync as co}from"fs";import{readFile as uo}from"fs/promises";import{dirname as po,join as fo}from"path";import{fileURLToPath as mo}from"url";var fr=lo(import.meta.url)("chrome-remote-interface"),go=new Set(["content-security-policy","content-security-policy-report-only","x-frame-options"]),gr=["kizen.dev","kizen.com"];function mr(e){try{let{hostname:t}=new URL(e);return gr.some(o=>t===o||t.endsWith("."+o))}catch{return!1}}function Ye(e){if(e.type==="number")return Number(e.value);if(e.type==="boolean")return e.value==="true";if(e.type!=="undefined"){if(e.type==="object"&&e.value==="null")return null;if(e.type==="object"&&e.valuePreview){let{valuePreview:t}=e;if(t.subtype==="array")return t.properties.filter(r=>/^\d+$/.test(r.name)).sort((r,n)=>parseInt(r.name)-parseInt(n.name)).map(Ye);let o={};for(let r of t.properties)o[r.name]=Ye(r);return o}return e.value??`[${e.type}]`}}function yo(e){if(e.value!==void 0)return e.value;if(e.preview){let{preview:t}=e;if(t.subtype==="array")return t.properties.filter(r=>/^\d+$/.test(r.name)).sort((r,n)=>parseInt(r.name)-parseInt(n.name)).map(Ye);let o={};for(let r of t.properties)o[r.name]=Ye(r);return o}return e.description??`[${e.type}]`}async function ho(e,t){if(t.type==="object"&&t.objectId)try{let r=(await e.Runtime.callFunctionOn({objectId:t.objectId,functionDeclaration:'function() { try { const seen = new WeakSet(); return JSON.stringify(this, function(k,v) { if (typeof v === "bigint") { return String(v) + "n"; } if (typeof v === "object" && v !== null) { if (seen.has(v)) return "[Circular]"; seen.add(v); } return v; }); } catch { return undefined; } }',returnByValue:!0})).result.value;if(typeof r=="string")return JSON.parse(r)}catch{}return yo(t)}async function xo(e){try{let t=fo(po(mo(import.meta.url)),"viewer","icon.png"),o=await uo(t);await e.Browser.setDockTile({image:o.toString("base64")})}catch{}}async function yr(e){co(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,o=await ao({startingUrl:t,chromeFlags:[`--app=${t}`,"--no-first-run","--no-default-browser-check","--disable-extensions"],userDataDir:e.userDataDir,handleSIGINT:!1,logLevel:"silent"}),r=o.port,n=null,s=null,g=null,u=null,C=0,b=!1,x=p=>{e.debugLog?.(p)},h=p=>{e.verbose&&e.debugLog?.(p)},y=()=>{s!==null&&(clearInterval(s),s=null)},c=p=>p==="chrome://new-tab-page/"||p==="chrome://newtab/",v=async p=>{y(),g=null,await xo(p),await p.Fetch.enable({patterns:gr.flatMap(a=>[{urlPattern:`*://${a}/*`,requestStage:"Response"},{urlPattern:`*://*.${a}/*`,requestStage:"Response"}])}),p.on("Fetch.requestPaused",a=>{(async()=>{let i=a,{requestId:l,request:d,responseHeaders:f,responseStatusCode:F}=i,k=d.url;h(`Fetch ${String(F??"?")} ${k}`);let N=[],A=!1;for(let H of f??[])if(!go.has(H.name.toLowerCase()))if(H.name.toLowerCase()==="set-cookie"&&mr(k)){let W=H.value.split(`
172
172
  `).map(ee=>/SameSite=/i.test(ee)?ee.replace(/SameSite=\w+/i,"SameSite=None"):ee+"; SameSite=None; Secure").join(`
173
173
  `);N.push({name:H.name,value:W}),A=!0}else N.push(H);A&&h(` rewrote Set-Cookie SameSite on ${k}`);try{let{body:H,base64Encoded:W}=await p.Fetch.getResponseBody({requestId:l});await p.Fetch.fulfillRequest({requestId:l,responseCode:F??200,responseHeaders:N,body:H,...W&&{base64Encoded:!0}})}catch(H){h(` fulfillRequest failed (${H.message}), falling through`);try{await p.Fetch.continueRequest({requestId:l})}catch(W){h(` continueRequest also failed (${W.message})`)}}})()}),s=setInterval(()=>{(async()=>{try{let{cookies:a}=await p.Network.getAllCookies(),i=0;for(let l of a){if(!mr(`https://${l.domain??""}`)||l.sameSite==="None")continue;let d=l.domain??"",f=d.startsWith(".")?d.slice(1):d;await p.Network.setCookie({url:`https://${f}`,name:l.name,value:l.value,domain:d,path:l.path??"/",secure:!0,...l.httpOnly!==void 0&&{httpOnly:l.httpOnly},...l.expirationDate!==void 0&&{expires:l.expirationDate},sameSite:"None"}),i++}i>0&&h(`cookie-patch cycle: updated ${String(i)} cookie(s) to SameSite=None`)}catch(a){h(`cookie-patch cycle failed: ${a.message}`)}})()},2e3),await p.send("Runtime.enable",{generatePreview:!0}),p.on("Target.attachedToTarget",a=>{let i=a,{sessionId:l,targetInfo:d}=i;h(`attached session ${l} (${d.type} ${d.url})`),p.send("Runtime.enable",{generatePreview:!0},l).catch(f=>{h(` Runtime.enable on session ${l} failed: ${f.message}`)})}),await p.Target.setAutoAttach({autoAttach:!0,waitForDebuggerOnStart:!1,flatten:!0}),await p.Target.setDiscoverTargets({discover:!0});let P=a=>{if(a.type==="page"){if(c(a.url)){x(`closed stray new-tab-page target ${a.targetId}`),g!==null&&p.Target.activateTarget({targetId:g}).catch(()=>{}),p.Target.closeTarget({targetId:a.targetId}).catch(()=>{});return}g===null&&(g=a.targetId,x(`captured main target ${a.targetId} (${a.url})`))}};p.on("Target.targetCreated",a=>{let{targetInfo:i}=a;h(`target +${i.type} ${i.targetId} ${i.url}`),P(i)}),p.on("Target.targetInfoChanged",a=>{let{targetInfo:i}=a;h(`target ~${i.type} ${i.targetId} ${i.url}`),P(i)}),p.on("Runtime.consoleAPICalled",a=>{(async()=>{let{type:i,args:l}=a;if(l[0]?.type==="string"&&String(l[0].value).includes("Chrome Security"))return;let d=i==="warning"?"warn":["log","warn","error","info"].includes(i)?i:"log";h(`console.${d} (${String(l.length)} arg(s))`);let f=await Promise.all(l.map(F=>ho(p,F)));e.broadcast({type:"console-message",level:d,args:f})})().catch(i=>{h(`console serialization failed: ${i.message}`)})}),p.on("disconnect",()=>{b||n!==p||(x("CDP disconnected"),n=null,y(),E())})},E=()=>{if(b||u!==null)return;let p=Math.min(1e3*2**C,1e4),P=C+1;C++,x(`CDP reconnect scheduled in ${String(p)}ms (attempt #${String(P)})`),u=setTimeout(()=>{u=null,(async()=>{let a;try{a=await fr({port:r})}catch{x(`CDP reconnect attempt #${String(P)} failed`),E();return}if(b){try{await a.close()}catch{}return}n=a;try{await v(a),x(`CDP reconnected after ${String(P)} attempt(s)`),C=0}catch{n===a&&(n=null);try{await a.close()}catch{}x(`CDP reconnect attempt #${String(P)} failed during setup`),E()}})()},p)},R=30,S=300;for(let p=0;p<R;p++){await new Promise(P=>setTimeout(P,S)),x(`CDP connect attempt ${String(p+1)}/${String(R)}`);try{let P=await fr({port:r});n=P,e.path&&P.send("Page.navigate",{url:`${t}${e.path}`});try{await v(P),x("CDP connected")}catch{n===P&&(n=null);try{await P.close()}catch{}x("CDP setup failed after connect")}break}catch{if(p===R-1){let P=`CDP unavailable after ${String(R)} attempts \u2014 viewer running without interception (CSP/cookie rewrites disabled)`;return x(P),e.onWarn?.(P),{kill:()=>{o.kill()}}}}}return n?{kill:()=>{if(x("CDP kill requested \u2014 tearing down"),b=!0,u!==null&&(clearTimeout(u),u=null),y(),n!==null){try{n.close()}catch{}n=null}o.kill()}}:{kill:()=>{o.kill()}}}import{useCallback as bo,useState as vo}from"react";function Ze(e){let[t,o]=vo([]),r=bo(n=>{o(s=>[...s,`${new Date().toLocaleTimeString()}: ${n}`].slice(-e))},[e]);return[t,r]}import{useCallback as Qe,useEffect as _t,useState as et}from"react";import{Box as z,Text as B,useInput as wo}from"ink";import{jsx as T,jsxs as U}from"react/jsx-runtime";var oe=["apiKey","userId","businessId"],Co={apiKey:"API Key",userId:"User ID",businessId:"Business ID"},je=({text:e})=>T(B,{dimColor:!0,children:e}),tt=({initialMode:e,showProfileManager:t,onComplete:o,onCancel:r})=>{let[n,s]=et(e==="global"&&!t?{type:"loading"}:e==="global"&&t?{type:"profile-loading"}:{type:"mode-select",cursor:0}),[g,u]=et(""),[C,b]=et(null),[x,h]=et(void 0),y=Qe(a=>{if(a==="local"){o({mode:"local",credentials:null});return}s({type:"profile-loading"})},[o]),c=Qe(async a=>{if(a===null){s({type:"profile-loading"});let d=await Ie();s({type:"name-entry",nameBuffer:"",existingProfiles:d});return}h(a.isDefault?void 0:a.name),s({type:"loading"});let i=a.isDefault?await Y():await we(a.name),l=i?Math.max(0,K.indexOf(i.environment)):0;s({type:"creds-entry",field:0,values:i??{},envCursor:l})},[]),v=Qe(async(a,i)=>{let l=K[i]??"go",d={apiKey:a.apiKey??"",userId:a.userId??"",businessId:a.businessId??"",environment:l};s({type:"saving"});try{await Xt(x??ne,d),o({mode:"global",credentials:d,...x!==void 0&&{profileName:x}})}catch(f){b(f instanceof Error?f.message:String(f)),s({type:"creds-entry",field:0,values:a,envCursor:i})}},[o,x]);wo((a,i)=>{if(i.ctrl&&a==="c"&&process.exit(0),i.escape){if((n.type==="creds-entry"||n.type==="name-entry")&&e==="global"&&t){s({type:"profile-loading"}),E();return}r?.();return}if(n.type==="mode-select"){if(i.upArrow)s({type:"mode-select",cursor:0});else if(i.downArrow)s({type:"mode-select",cursor:1});else if(i.return){let l=n.cursor===0?"global":"local";y(l)}return}if(n.type==="profile-select"){let{profiles:l,cursor:d}=n,f=l.length,F=l.length+1;if(i.upArrow)s({...n,cursor:(d-1+F)%F});else if(i.downArrow)s({...n,cursor:(d+1)%F});else if(i.return)if(d===f)s({type:"name-entry",nameBuffer:"",existingProfiles:l});else{let k=l[d]??l[0];k&&c(k)}return}if(n.type==="name-entry"){let{nameBuffer:l,existingProfiles:d}=n;if(i.backspace||i.delete)s({type:"name-entry",nameBuffer:l.slice(0,-1),existingProfiles:d});else if(i.return){let f=l.trim();if(!f){s({...n,nameError:"Name cannot be empty"});return}if(f===ne){s({...n,nameError:`"${ne}" is reserved`});return}if(d.some(F=>F.name===f)){s({...n,nameError:`Profile "${f}" already exists`});return}h(f),s({type:"creds-entry",field:0,values:{},envCursor:0}),u("")}else a&&!i.ctrl&&!i.meta&&s({type:"name-entry",nameBuffer:l+a,existingProfiles:d});return}if(n.type==="creds-entry"){let{field:l,values:d,envCursor:f}=n;if(l===oe.length){i.leftArrow?s({...n,envCursor:(f-1+K.length)%K.length}):i.rightArrow?s({...n,envCursor:(f+1)%K.length}):i.upArrow?(s({...n,field:l-1}),u(d[oe[l-1]]??"")):i.return&&v(d,f);return}let k=oe[l];if(!k)return;if(i.backspace||i.delete)u(N=>N.slice(0,-1));else if(i.upArrow&&l>0){let N={...d,[k]:g},A=l-1;s({...n,field:A,values:N}),u(N[oe[A]]??"")}else if(i.return||i.tab||i.downArrow){let N={...d,[k]:g},A=l+1;s({...n,field:A,values:N}),A<oe.length?u(N[oe[A]]??""):u("")}else a&&!i.ctrl&&!i.meta&&u(N=>N+a)}});let E=Qe(async()=>{let a=await Ie();s({type:"profile-select",profiles:a,cursor:0})},[]);if(_t(()=>{n.type==="profile-loading"&&E()},[n.type,E]),_t(()=>{e==="global"&&!t&&(async()=>{let a=await Y(),i=a?Math.max(0,K.indexOf(a.environment)):0;s({type:"creds-entry",field:0,values:a??{},envCursor:i})})()},[]),_t(()=>{n.type==="creds-entry"&&n.field===0&&u(n.values.apiKey??"")},[n.type]),n.type==="loading"||n.type==="saving"||n.type==="profile-loading"){let a=n.type==="saving"?"Saving credentials\u2026":n.type==="profile-loading"?"Loading profiles\u2026":"Loading credentials\u2026";return T(z,{paddingY:1,paddingX:2,children:T(B,{dimColor:!0,children:a})})}if(n.type==="done")return null;if(n.type==="mode-select")return U(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),U(z,{flexDirection:"column",gap:0,children:[T(B,{bold:!0,children:"Credential mode"}),[{label:"Global",desc:"~/.kizenappbuilder/credentials.json",mode:"global"},{label:"Local",desc:"Enter credentials in the browser dev tools",mode:"local"}].map((i,l)=>{let d=n.cursor===l;return U(z,{gap:2,children:[T(B,{...d&&{color:"cyan"},children:d?"\u276F":" "}),T(B,{bold:d,...d&&{color:"cyan"},children:i.label}),T(B,{dimColor:!0,children:i.desc})]},i.mode)})]}),T(je,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]});if(n.type==="profile-select"){let{profiles:a,cursor:i}=n,l=a.length;return U(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),U(z,{flexDirection:"column",gap:0,children:[T(B,{bold:!0,children:"Credential profiles"}),a.map((d,f)=>{let F=i===f;return U(z,{gap:2,children:[T(B,{...F&&{color:"cyan"},children:F?"\u276F":" "}),T(B,{bold:F,...F&&{color:"cyan"},children:d.isDefault?"Default":d.name}),T(B,{dimColor:!0,children:d.path})]},d.name)}),U(z,{gap:2,children:[T(B,{...i===l&&{color:"cyan"},children:i===l?"\u276F":" "}),T(B,{bold:i===l,...i===l&&{color:"cyan"},children:"+ Add new profile"})]})]}),T(je,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(n.type==="name-entry"){let{nameBuffer:a,nameError:i}=n;return U(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),T(z,{flexDirection:"column",gap:0,children:T(B,{bold:!0,children:"New credential profile"})}),i&&U(B,{color:"red",children:["Error: ",i]}),U(z,{gap:2,children:[T(z,{width:12,children:T(B,{bold:!0,color:"cyan",children:"Profile name"})}),T(B,{color:"cyan",children:">"}),T(B,{children:a}),T(B,{color:"cyan",children:"\u2588"})]}),T(je,{text:"Type a name \xB7 Enter to confirm \xB7 Esc to go back"})]})}let{field:R,values:S,envCursor:m}=n,p=R===oe.length,P=x??ne;return U(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),U(z,{flexDirection:"column",gap:0,children:[T(B,{bold:!0,children:x!==void 0?`Profile: ${x}`:"Global credentials"}),U(B,{dimColor:!0,children:["Saved to:"," ",x!==void 0?`~/.kizenappbuilder/${x}.json`:ve]})]}),C&&U(B,{color:"red",children:["Error: ",C]}),U(z,{flexDirection:"column",gap:0,children:[oe.map((a,i)=>{let l=R===i,d=l?g:S[a]??"";return U(z,{gap:2,children:[T(z,{width:12,children:T(B,{bold:l,...l&&{color:"cyan"},children:Co[a]})}),T(B,{...l&&{color:"cyan"},children:">"}),T(B,{children:d}),l&&T(B,{color:"cyan",children:"\u2588"})]},a)}),U(z,{gap:2,children:[T(z,{width:12,children:T(B,{bold:p,...p&&{color:"cyan"},children:"Environment"})}),T(B,{...p&&{color:"cyan"},children:">"}),T(z,{gap:1,children:K.map((a,i)=>{let l=i===m;return p?T(B,{bold:l,...l&&{color:"cyan"},children:l?`[${a}]`:a},a):T(B,{dimColor:!l,bold:l,children:a},a)})})]})]}),p?T(je,{text:"\u2190\u2192 to select \xB7 \u2191\u2193 to move \xB7 Enter to save \xB7 Esc to cancel"}):T(je,{text:"\u2191\u2193 to move \xB7 Backspace to delete \xB7 Esc to cancel"}),U(B,{dimColor:!0,children:["Profile: ",P]})]})};import{jsx as j,jsxs as O}from"react/jsx-runtime";var ko=[".kizenapp",".git"],xr=({port:e,pluginDir:t,outputDir:o,credentials:r,credentialMode:n,activeCredentialProfile:s,lastPath:g,debug:u=!1,verbose:C=!1,autoViewer:b=!0})=>{let x=Q(r),h=Q(s),y=Q(g),[c,v]=J("main"),[E,R]=J(n),[S,m]=J("starting"),[p,P]=J(null),[a,i]=Ze(50),[l,d]=Ze(50),[f,F]=Ze(50),[k,N]=J([]),[A,H]=J("pending"),[W,ee]=J(null),[ge,Pe]=J(null),[se,ot]=J(null),[it,st]=J(0),[kt,Rr]=J(0),[Nr,jr]=J(0),[Fr,$r]=J(0),at=Q(!1),It=Q(!1),$e=Q(null),Te=Q(null),te=Q(new Set),Le=Q([]),G=Ce(w=>{let $=JSON.stringify(w);if(te.current.size===0){Le.current=[...Le.current,$].slice(-50);return}let re=!1;for(let X of te.current)if(X.readyState===1)try{X.send($)}catch{te.current.delete(X),re=!0}re&&st(te.current.size)},[]),Ae=i,lt=Ce(()=>{$e.current?.kill(),$e.current=null,yr({port:e,userDataDir:hr(o,".chrome"),broadcast:G,onWarn:w=>{i(`\u26A0 ${w}`)},...y.current!==void 0&&{path:y.current},...u&&{debugLog:F},...C&&{verbose:!0}}).then(w=>{$e.current=w})},[e,o,G,u,C,F,i]);rt(()=>{let w=()=>{$e.current?.kill()};return process.on("exit",w),()=>{process.off("exit",w)}},[]),Po((w,$)=>{(w==="q"||$.ctrl&&w==="c")&&process.exit(0),w==="c"&&v("editing"),w==="v"&&lt()},{isActive:c==="main"}),rt(()=>{S!=="running"||It.current||!b||(It.current=!0,lt())},[S,b,lt]);let Lr=Ce(w=>{x.current=w.credentials,h.current=w.profileName,v("main"),R(w.mode);let $=w.profileName;me(o,{credentialMode:w.mode,...$!==void 0&&{activeCredentialProfile:$}}),G({type:"credentials-updated",credentials:w.credentials})},[o,G]),Bt=Ce(w=>{N($=>[...$,`${new Date().toLocaleTimeString()}: ${St(w)}`].slice(-50)),w.kind==="request"&&(w.fromCache?jr($=>$+1):$r($=>$+1)),G({type:"proxy-log",entry:w})},[G]),ae=Ce(w=>{d(w),G({type:"log",message:w})},[d,G]),ct=Ce(()=>{at.current||(at.current=!0,H("building"),ee(null),ae("Build started"),He(t,o).then(({bundleSize:w})=>{ae(`Build finished \u2014 bundle: ${_e(w)}`),H("done"),Pe(new Date),ot(w),ae("Notifying viewers to reload"),G({type:"rebuild"})}).catch(w=>{let $=w instanceof Error?w.message:String(w);ee($),H("error")}).finally(()=>{at.current=!1}))},[t,o,ae,G]);if(rt(()=>{ct();let w=To(t,{recursive:!0},($,re)=>{if(!re)return;let X=re.replace(/\\/g,"/");ko.some(Oe=>X.startsWith(Oe))||(ae(`File change detected: ${re}`),Te.current!==null&&clearTimeout(Te.current),Te.current=setTimeout(ct,150))});return w.on("error",$=>{ae(`File watcher error \u2014 rebuilds have stopped: ${$.message}`)}),()=>{w.close(),Te.current!==null&&clearTimeout(Te.current)}},[t,ct,ae]),rt(()=>{let w=ur();Tt(hr(w,"index.html")).then($=>{if(!$){P("Viewer not built. Run 'pnpm build:viewer' first."),m("error");return}let re=pr(w,Ae,Bt,x,h,o,G,Rr,y,t),X=_o(re),Oe=new Eo({server:X});return Oe.on("connection",le=>{for(let Or of Le.current)le.readyState===1&&le.send(Or);Le.current=[],Ae("Viewer connected for live reload"),te.current.add(le),st(te.current.size),le.on("close",()=>{te.current.delete(le),st(te.current.size)})}),X.listen(e,"127.0.0.1",()=>{m("running"),Ae(`Server started on 127.0.0.1:${String(e)}`)}),X.on("error",le=>{P(le.message),m("error")}),()=>{Oe.close(),X.close()}})},[e,Ae,Bt,G,o,t]),c==="editing")return j(tt,{...E!==void 0&&{initialMode:E},showProfileManager:E==="global",onComplete:Lr,onCancel:()=>{v("main")}});let dt=ge!==null?Math.round((Date.now()-ge.getTime())/1e3):null,Ar=dt===null?"":dt<5?" (just now)":` (${String(dt)}s ago)`;return O(q,{flexDirection:"column",paddingY:1,paddingX:2,children:[j(V,{marginBottom:1}),O(q,{flexDirection:"column",children:[O(q,{gap:2,marginBottom:0,children:[j(D,{bold:!0,dimColor:!0,children:"App Build"}),A==="pending"&&j(D,{dimColor:!0,children:"waiting\u2026"}),A==="building"&&O(q,{gap:1,children:[j(Ue,{}),j(D,{children:"Building plugin package\u2026"})]}),A==="done"&&O(q,{gap:1,children:[j(D,{color:"green",children:"\u2713 Built"}),ge!==null&&O(D,{dimColor:!0,children:["at ",ge.toLocaleTimeString(),Ar]}),se!==null&&O(D,{dimColor:!0,children:["\xB7 bundle: ",_e(se)]})]}),A==="error"&&O(D,{color:"red",children:["\u2717 ",W??"unknown error"]})]}),j(q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:l.slice(-8).map((w,$)=>j(D,{dimColor:!0,wrap:"truncate",children:w},$))})]}),O(q,{marginTop:1,flexDirection:"column",children:[O(q,{gap:2,children:[j(D,{bold:!0,dimColor:!0,children:"Web Server"}),S==="starting"&&j(D,{dimColor:!0,children:"starting\u2026"}),S==="running"&&O(q,{gap:2,children:[j(D,{color:"green",children:"\u2713 Running"}),O(D,{dimColor:!0,children:["\u25CF ",it," viewer",it!==1?"s":""]})]}),S==="error"&&O(D,{color:"red",children:["\u2717 ",p??"Server error"]})]}),j(q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:a.slice(-8).map((w,$)=>j(D,{dimColor:!0,wrap:"truncate",children:w},$))})]}),O(q,{marginTop:1,flexDirection:"column",children:[O(q,{gap:2,children:[j(D,{bold:!0,dimColor:!0,children:"Network Proxy"}),j(D,{color:"green",children:"\u2713 Active"}),O(D,{dimColor:!0,children:["\u25CF ",kt," key",kt!==1?"s":""," in the network cache \xB7"," ",Nr," hit \xB7 ",Fr," miss"]})]}),j(q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:k.length===0?j(D,{dimColor:!0,children:" No requests yet."}):k.slice(-8).map((w,$)=>j(D,{dimColor:!0,wrap:"truncate",children:w},$))})]}),u&&O(q,{marginTop:1,flexDirection:"column",children:[O(q,{gap:2,children:[j(D,{bold:!0,dimColor:!0,children:"CDP Debug"}),O(D,{dimColor:!0,children:["\u25CF ",f.length," event(s)"]})]}),j(q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:f.length===0?j(D,{dimColor:!0,children:" No CDP events yet."}):f.slice(-8).map((w,$)=>j(D,{dimColor:!0,wrap:"truncate",children:w},$))})]}),O(q,{marginTop:1,gap:1,children:[j(D,{dimColor:!0,children:"["}),j(D,{children:"q"}),j(D,{dimColor:!0,children:"] quit ["}),j(D,{children:"c"}),j(D,{dimColor:!0,children:"] credentials ["}),j(D,{children:"v"}),O(D,{dimColor:!0,children:["] ",it===0?"open viewer":"relaunch viewer"]})]})]})};async function br(e){return new Promise(t=>{let o=null,r=s=>{o?.(),t(s)},{unmount:n}=wr(vr(tt,{...e!==void 0&&{initialMode:e},onComplete:r}),{exitOnCtrlC:!1});o=n})}function Cr(e){e.command("dev").description("Start the plugin viewer dev server").option("-p, --port <port>","port to listen on","3121").option("-c, --credentials <path>","path to a credentials JSON file").option("-d, --debug","Enable CDP lifecycle logs in the TUI").option("-v, --verbose","Log every CDP event and handled error (implies --debug)").option("--no-viewer","Don't auto-launch the viewer on startup (press [v] to launch manually)").action(async t=>{let o=parseInt(t.port,10),r=process.cwd(),n=`${r}/.kizenapp`;xe(r);let s=null,g,u,{lastPath:C}=await De(n);if(t.credentials)s=await Ge(t.credentials);else{let c=await De(n);if(c.credentialMode==="local")g="local";else if(c.credentialMode==="global"){if(g="global",u=c.activeCredentialProfile,u?(s=await we(u),s||(s=await Y(),u=void 0)):s=await Y(),!s){let v=await br("global");s=v.credentials,u=v.profileName}}else{let v=await br();s=v.credentials,g=v.mode,u=v.profileName;let E=v.profileName;await me(n,{credentialMode:v.mode,...E!==void 0&&{activeCredentialProfile:E}})}}let b=t.verbose===!0,x=b||t.debug===!0,h=t.viewer!==!1,{waitUntilExit:y}=wr(vr(xr,{port:o,pluginDir:r,outputDir:n,credentials:s,...g!==void 0&&{credentialMode:g},...u!==void 0&&{activeCredentialProfile:u},...C!==void 0&&{lastPath:C},debug:x,verbose:b,autoViewer:h}),{exitOnCtrlC:!1});await y()})}import{mkdir as Io,writeFile as Sr,readFile as Bo}from"fs/promises";import{join as nt}from"path";var Do=new Set(["developer_business_id"]);function Ro(e){return Array.isArray(e)?e.map(t=>{if(typeof t!="object"||t===null)return t;let o=t;if(typeof o.auth_credentials!="object"||o.auth_credentials===null)return o;let r=Object.fromEntries(Object.keys(o.auth_credentials).map(n=>[n,"*****"]));return{...o,auth_credentials:r}}):e}var No={".png":"image/png",".svg":"image/svg+xml",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function Tr(e){let t={name:"",children:new Map,isFile:!1,filePath:""};for(let o of e){let r=o.path.split("/"),n=t;r.forEach((s,g)=>{n.children.has(s)||n.children.set(s,{name:s,children:new Map,isFile:g===r.length-1,filePath:r.slice(0,g+1).join("/")});let u=n.children.get(s);u&&(n=u)})}return t}function Et(e){return"file-"+e.replace(/[^a-zA-Z0-9]/g,"-")}function Z(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function _r(e){return`<ul>${[...e.children.values()].sort((r,n)=>r.isFile!==n.isFile?r.isFile?1:-1:r.name.localeCompare(n.name)).map(r=>r.isFile?`<li class="tf"><a href="#${Et(r.filePath)}" data-id="${Et(r.filePath)}">${Z(r.name)}</a></li>`:`<li class="td"><span class="dn">${Z(r.name)}/</span>${_r(r)}</li>`).join("")}</ul>`}function Er(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t).toLowerCase():""}function jo(e){let t;return e.base64Image!==void 0?t=`<img src="data:${No[Er(e.path)]??"image/png"};base64,${e.base64Image}" alt="${Z(e.path)}" style="max-width:100%">`:e.binaryData!==void 0?t=`<p class="bin">[Binary file: ${String(e.binaryData.length)} bytes]</p>`:t=`<pre><code>${Z(e.content)}</code></pre>`,`<section id="${Et(e.path)}"><h2 class="fp">${Z(e.path)}</h2><div class="fb">${t}</div></section>`}var Fo={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".json":"json",".css":"css",".scss":"scss",".html":"html",".htm":"html",".md":"markdown",".mdx":"markdown",".py":"python",".sh":"bash",".yml":"yaml",".yaml":"yaml",".xml":"xml",".toml":"toml"};function $o(e){return Fo[Er(e)]??""}function kr(e,t=""){let o=[...e.children.values()].sort((r,n)=>r.isFile!==n.isFile?r.isFile?1:-1:r.name.localeCompare(n.name));return o.map((r,n)=>{let s=n===o.length-1,g=s?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",u=s?" ":"\u2502 ";return r.isFile?`${t}${g}${r.name}`:`${t}${g}${r.name}/
174
174
  ${kr(r,t+u)}`}).join(`