@kizenapps/cli 0.18.0 → 0.19.0
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/index.js +19 -13
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{readFileSync as
|
|
3
|
-
`).map(
|
|
2
|
+
import{readFileSync as Oo}from"fs";import{dirname as zo,join as Mo}from"path";import{fileURLToPath as Ho}from"url";import{program as Se}from"commander";import{createElement as gn}from"react";import{render as yn}from"ink";import{useEffect as pn,useState as ft}from"react";import{Box as Ee,Text as ye,useApp as fn}from"ink";import{mkdir as Vr,writeFile as Jr}from"fs/promises";import{join as Wr}from"path";import{minifyFiles as Gr,packagePlugin as Kr,transformDeployablePlugin as Xr}from"@kizenapps/packager";import{readdir as zr,readFile as ut}from"fs/promises";import{join as Dt,relative as Mr}from"path";var Hr=new Set([".png",".svg"]),Ur=new Set([".kzn"]),qr=new Set([".DS_Store"]),ze=new Set(["node_modules",".git",".kizenapp",".github"]);async function Rt(e,t){let o=await zr(e,{withFileTypes:!0}),r=[];for(let n of o)if(n.isDirectory()){if(ze.has(n.name))continue;r.push(...await Rt(Dt(e,n.name),t))}else n.isFile()&&(qr.has(n.name)||r.push(Dt(e,n.name)));return r}async function Me(e){let t=await Rt(e,e);return Promise.all(t.map(async o=>{let r=Mr(e,o).split("\\").join("/"),n=r.lastIndexOf("."),s=n>=0?r.slice(n).toLowerCase():"";if(Hr.has(s)){let u=await ut(o);return{path:r,content:"",base64Image:u.toString("base64")}}if(Ur.has(s)){let u=await ut(o);return{path:r,content:"",binaryData:u}}let g=await ut(o,"utf-8");return{path:r,content:g}}))}var Yr=["name","api_name","version","entry"];function Nt(e,t){let o=t===void 0?"kizen.json":`kizen.json entry #${String(t+1)}`;for(let r of Yr){let n=e[r];if(typeof n!="string"||n==="")throw new Error(`${o} is missing required field "${r}" (expected a non-empty string).`)}}function Zr(e){let t;try{t=JSON.parse(e)}catch(o){let r=o instanceof Error?o.message:String(o);throw new Error(`kizen.json is not valid JSON: ${r}`)}if(Array.isArray(t))return t.forEach((o,r)=>{if(typeof o!="object"||o===null)throw new Error(`kizen.json entry #${String(r+1)} is not a JSON object.`);Nt(o,r)}),t;if(typeof t!="object"||t===null)throw new Error("kizen.json must be a JSON object (or array of objects).");return Nt(t),t}var Qr=(e,t)=>({...e,thumbnail:e.thumbnail?Buffer.from(e.thumbnail).toString("base64"):null,kznFile:e.kznFile?Buffer.from(e.kznFile).toString("base64"):null,allReleaseNotes:t});async function He(e,t,o){await Vr(t,{recursive:!0}),o?.("reading-files");let r=await Me(e);o?.("minifying");let n=await Gr(r);o?.("packaging");let s=n.find(c=>c.path==="kizen.json");if(!s)throw new Error("kizen.json not found in plugin directory.");let g=Zr(s.content),u=Kr(n,g),C=Object.values(u).map(Xr);o?.("writing-bundle");let b=C.map(c=>{let v=c.release_notes_directory?.replace(/\/$/,""),E=v?r.filter(R=>R.path.startsWith(v+"/")&&R.path.endsWith(".md")&&R.content).map(R=>({version:R.path.slice(R.path.lastIndexOf("/")+1,-3),notes:R.content})).sort((R,S)=>S.version.localeCompare(R.version,void 0,{numeric:!0})):[];return Qr(c,E)}),x=JSON.stringify(b,null,2),h=(c,v)=>c==="allReleaseNotes"?void 0:v,y=Buffer.byteLength(JSON.stringify(b,h,2),"utf-8");return await Jr(Wr(t,"bundle.json"),x,"utf-8"),{bundleSize:y}}function _e(e){return e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}import{Box as nn,Text as on}from"ink";import{Box as en,Text as tn}from"ink";import{jsx as jt}from"react/jsx-runtime";var rn=[" :::::::: "," :::::: ::::::::::: "," :::::: :::::::::: "," :::::: :::::: ::::::: "," ::::: :::::: ::::::::::::::::: "," ::::: ::::: ::::::::::::::::::: "," ::::: ::::: :::::: ::::: ",":::: ::::: ::: ::::: :: ","::::: :::::: :::::::::: ","::::: :::::: ::::::::::: "," ::::: ::: ::::::: "," ::::::: ::: ::::: "," ::::::::::: :::::: :::::"," :::::::::: :::::: :::::"," :: ::::: ::: ::::: ::::"," ::::: :::::: ::::: ::::: ::: "," ::::::::::::::::::: ::::: ::::: "," ::::::::::::::::: ::::: ::::: "," ::::::::: :::::: :::::: "," :::::::::: :::::: "," ::::::::::: :::::: "," :::::::: "],Ft=()=>jt(en,{flexDirection:"column",children:rn.map((e,t)=>jt(tn,{color:"cyan",children:e},t))});import{Fragment as sn,jsx as pt,jsxs as an}from"react/jsx-runtime";var V=({marginBottom:e=0})=>an(sn,{children:[pt(Ft,{}),pt(nn,{flexDirection:"column",marginTop:1,marginBottom:e,children:pt(on,{bold:!0,color:"cyan",children:"Kizen App Development Toolkit"})})]});import{useEffect as ln,useState as cn}from"react";import{Text as dn}from"ink";import{jsx as un}from"react/jsx-runtime";var $t=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ue=()=>{let[e,t]=cn(0);return ln(()=>{let o=setInterval(()=>{t(r=>(r+1)%$t.length)},80);return()=>{clearInterval(o)}},[]),un(dn,{color:"cyan",children:$t[e]??"\u280B"})};import{Fragment as mn,jsx as ce,jsxs as de}from"react/jsx-runtime";var Lt=["creating-dir","reading-files","minifying","packaging","writing-bundle"],qe={"creating-dir":"Creating .kizenapp directory","reading-files":"Reading plugin files",minifying:"Minifying scripts",packaging:"Packaging plugin","writing-bundle":"Writing bundle.json"},At=({outputDir:e,pluginDir:t})=>{let o=fn(),[r,n]=ft("creating-dir"),[s,g]=ft(null),[u,C]=ft(null);pn(()=>{He(t,e,n).then(({bundleSize:y})=>{C(y),n("done"),o.exit()}).catch(y=>{let c=y instanceof Error?y.message:String(y);g(c),n("error"),o.exit()})},[e,t,o]);let b=Lt.indexOf(r),x=r==="error",h=r==="done";return de(Ee,{flexDirection:"column",paddingY:1,paddingX:2,children:[ce(V,{marginBottom:1}),de(Ee,{flexDirection:"column",gap:0,children:[Lt.map((y,c)=>{let v=r===y,E=h||b>c;return ce(Ee,{gap:1,children:x&&c===b?de(ye,{color:"red",children:["\u2717 ",qe[y]]}):E?de(ye,{color:"green",children:["\u2713 ",qe[y]]}):v?de(mn,{children:[ce(Ue,{}),ce(ye,{children:qe[y]})]}):de(ye,{dimColor:!0,children:[" ",qe[y]]})},y)}),h&&u!==null&&ce(Ee,{marginTop:1,gap:1,children:de(ye,{color:"green",children:["\u2713 bundle \u2014 ",_e(u)]})}),s!==null&&ce(Ee,{marginTop:1,borderStyle:"single",borderColor:"red",paddingX:1,children:ce(ye,{color:"red",children:s})})]})]})};import*as he from"fs";import*as Ot from"path";function xe(e){let t=Ot.join(e,".gitignore"),o=".kizenapp/",r="";if(he.existsSync(t)){r=he.readFileSync(t,"utf8");let s=r.split(`
|
|
3
|
+
`).map(g=>g.trim());if(s.includes(o)||s.includes(".kizenapp"))return}let n=r.endsWith(`
|
|
4
4
|
`)?o+`
|
|
5
5
|
`:`
|
|
6
6
|
`+o+`
|
|
7
|
-
`;he.writeFileSync(t,r+n)}function zt(e){e.command("build").description("Bundle the plugin app into .kizenapp directory").action(async()=>{let t=process.cwd(),o=`${t}/.kizenapp`;xe(t);let{waitUntilExit:r}=
|
|
8
|
-
`,"utf-8"),await mt(ue(e.targetDir,"src"),{recursive:!0}),await mt(ue(e.targetDir,"releaseNotes"),{recursive:!0}),xe(e.targetDir)}import{jsx as _,jsxs as A}from"react/jsx-runtime";var pe=["name","apiName","externalLink","description","developerBusinessId"],qt={name:"Name",apiName:"API name",externalLink:"External link",description:"Description",developerBusinessId:"Business ID"},Vt=["name","apiName"];function gn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}var be=({text:e})=>_(I,{dimColor:!0,children:e});function yn(e){return{name:"",apiName:"",externalLink:"",description:"",developerBusinessId:e}}var Jt=({parentDir:e,defaultBusinessId:t})=>{let o=fn(),[r,n]=ke({type:"target-select",cursor:0}),[l,v]=ke("in-place"),[f,T]=ke(()=>yn(t)),[m,h]=ke(""),[x,y]=ke(e),c=Je((C,g)=>{v(C),h(g.name),n({type:"field-entry",field:0,values:g})},[]),b=Je(async C=>{let g=await Mt(C);if(g!=="ok"){n({type:"precheck-error",targetDir:C,reason:g});return}y(C),c("in-place",f)},[f,c]),E=Je(async C=>{try{let g=await Ht(e,C.apiName);y(g),n({type:"confirm",values:C})}catch(g){n({type:"error",message:g instanceof Error?g.message:String(g)})}},[e]),R=Je(async(C,g)=>{try{await Ut({targetDir:g,name:C.name,apiName:C.apiName,externalLink:C.externalLink,description:C.description,developerBusinessId:C.developerBusinessId}),n({type:"done",targetDir:g})}catch(u){n({type:"error",message:u instanceof Error?u.message:String(u)})}},[]);if(mn((C,g)=>{if(g.ctrl&&C==="c"){o.exit();return}if(r.type==="target-select"){g.upArrow?n({type:"target-select",cursor:0}):g.downArrow?n({type:"target-select",cursor:1}):g.return?r.cursor===0?b(e):c("sub-dir",f):g.escape&&o.exit();return}if(r.type==="precheck-error"){(g.return||g.escape)&&o.exit();return}if(r.type==="field-entry"){let{field:u,values:S}=r,s=pe[u];if(!s)return;if(g.escape){o.exit();return}if(g.backspace||g.delete){h(i=>i.slice(0,-1));return}if(g.upArrow&&u>0){let i={...S,[s]:m},a=u-1,d=pe[a];n({type:"field-entry",field:a,values:i}),T(i),h(d?i[d]:"");return}if(g.return||g.tab||g.downArrow){let i=m.trim();if(Vt.includes(s)&&!i){n({type:"field-entry",field:u,values:S,fieldError:`${qt[s]} is required`});return}let d=s==="description"?m:i,p={...S,[s]:d};T(p);let F=u+1;if(F>=pe.length)h(""),l==="sub-dir"?(n({type:"resolving-target"}),E(p)):n({type:"confirm",values:p});else{let k=pe[F],N=k?p[k]:"",$=k==="apiName"&&!N?gn(p.name):N;n({type:"field-entry",field:F,values:p}),h($)}return}C&&!g.ctrl&&!g.meta&&h(i=>i+C);return}if(r.type==="confirm"){if(g.escape){let u=pe.length-1,S=pe[u];n({type:"field-entry",field:u,values:r.values}),h(S?r.values[S]:"");return}g.return&&(n({type:"writing"}),R(r.values,x));return}(r.type==="done"||r.type==="error")&&(g.return||g.escape)&&o.exit()}),r.type==="target-select"){let C=[{label:"Use current directory",desc:e},{label:"Create new sub-directory",desc:`${e}/<inferred from API name>`}];return A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),A(M,{flexDirection:"column",gap:0,children:[_(I,{bold:!0,children:"Where should the new plugin live?"}),C.map((g,u)=>{let S=r.cursor===u;return A(M,{gap:2,children:[_(I,{...S&&{color:"cyan"},children:S?"\u276F":" "}),_(I,{bold:S,...S&&{color:"cyan"},children:g.label}),_(I,{dimColor:!0,children:g.desc})]},g.label)})]}),_(be,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(r.type==="precheck-error"){let{targetDir:C,reason:g}=r;return A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),_(I,{color:"red",bold:!0,children:"Cannot create plugin"}),A(M,{flexDirection:"column",gap:0,children:[A(I,{children:[C," already contains ",_(I,{bold:!0,children:g==="has-manifest"?"kizen.json":".kizenapp/"}),"."]}),_(I,{dimColor:!0,children:"Remove the conflicting file/directory or choose a different target to avoid overwriting an existing plugin."})]}),_(be,{text:"Enter or Esc to exit"})]})}if(r.type==="field-entry"){let{field:C,fieldError:g}=r,u=l==="sub-dir"?`Target: sub-directory of ${e} (inferred from API name)`:`Target: ${x}`;return A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),A(M,{flexDirection:"column",gap:0,children:[_(I,{bold:!0,children:"Plugin details"}),_(I,{dimColor:!0,children:u})]}),g!==void 0&&A(I,{color:"red",children:["Error: ",g]}),_(M,{flexDirection:"column",gap:0,children:pe.map((S,s)=>{let i=C===s,a=i?m:f[S],d=Vt.includes(S),p=`${qt[S]}${d?"":" (optional)"}`;return A(M,{gap:2,children:[_(M,{width:24,children:_(I,{bold:i,...i&&{color:"cyan"},children:p})}),_(I,{...i&&{color:"cyan"},children:">"}),_(I,{children:a}),i&&_(I,{color:"cyan",children:"\u2588"})]},S)})}),_(be,{text:"Enter/Tab/\u2193 next \xB7 \u2191 previous \xB7 Backspace delete \xB7 Esc cancel"})]})}if(r.type==="confirm"){let C=gt({targetDir:x,name:r.values.name,apiName:r.values.apiName,externalLink:r.values.externalLink,description:r.values.description,developerBusinessId:r.values.developerBusinessId});return A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),A(M,{flexDirection:"column",gap:0,children:[_(I,{bold:!0,children:"Ready to create"}),A(I,{dimColor:!0,children:["Target: ",x]})]}),A(M,{flexDirection:"column",gap:0,children:[_(I,{bold:!0,children:"kizen.json preview"}),_(I,{children:JSON.stringify(C,null,2)})]}),A(M,{flexDirection:"column",gap:0,children:[_(I,{dimColor:!0,children:"Also creates:"}),A(I,{dimColor:!0,children:[" ",yt(x,"src/")]}),A(I,{dimColor:!0,children:[" ",yt(x,"releaseNotes/")]}),A(I,{dimColor:!0,children:[" ",yt(x,".gitignore")," (adds .kizenapp/)"]})]}),_(be,{text:"Enter to create \xB7 Esc to go back"})]})}return r.type==="resolving-target"?_(M,{paddingY:1,paddingX:2,children:_(I,{dimColor:!0,children:"Finding available sub-directory\u2026"})}):r.type==="writing"?_(M,{paddingY:1,paddingX:2,children:_(I,{dimColor:!0,children:"Creating plugin\u2026"})}):r.type==="done"?A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),A(I,{color:"green",bold:!0,children:["Plugin created at ",r.targetDir]}),A(M,{flexDirection:"column",gap:0,children:[_(I,{dimColor:!0,children:"Next steps:"}),A(I,{children:[" ","cd ",r.targetDir]}),A(I,{children:[" ","appbuilder dev"]})]}),_(be,{text:"Enter or Esc to exit"})]}):A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),_(I,{color:"red",bold:!0,children:"Failed to create plugin"}),_(I,{children:r.message}),_(be,{text:"Enter or Esc to exit"})]})};import{mkdir as Wt,readFile as hn,readdir as xn,writeFile as Gt}from"fs/promises";import{homedir as bn}from"os";import{dirname as vn,join as We}from"path";var K=["go","fmo","staging","integration","test1"];var fe=We(bn(),".kizenappbuilder"),ve=We(fe,"credentials.json"),ne="credentials";function wn(e){return K.includes(e)}function Cn(e){if(typeof e!="object"||e===null)throw new Error("Credentials must be a JSON object");let t=e,o=t.environment;return{apiKey:typeof t.apiKey=="string"?t.apiKey:"",userId:typeof t.userId=="string"?t.userId:"",businessId:typeof t.businessId=="string"?t.businessId:"",environment:wn(o)?o:"go"}}async function Ge(e){let t=await hn(e,"utf-8");return Cn(JSON.parse(t))}async function Y(){try{return await Ge(ve)}catch{return null}}async function Sn(e){await Wt(vn(ve),{recursive:!0,mode:448}),await Gt(ve,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function Kt(e){return We(fe,`${e}.json`)}async function Ie(){let e=[{name:ne,path:ve,isDefault:!0}];try{let t=await xn(fe);for(let o of t){if(!o.endsWith(".json"))continue;let r=o.slice(0,-5);r!==ne&&e.push({name:r,path:We(fe,o),isDefault:!1})}}catch{}return e}async function Xt(e,t){if(e===ne){await Sn(t);return}await Wt(fe,{recursive:!0,mode:448}),await Gt(Kt(e),JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}async function we(e){try{return await Ge(Kt(e))}catch{return null}}function Yt(e){e.command("create").description("Scaffold a new Kizen plugin project").action(async()=>{let t=process.cwd(),r=(await Y())?.businessId??"",{waitUntilExit:n}=Tn(Pn(Jt,{parentDir:t,defaultBusinessId:r}),{exitOnCtrlC:!1});await n()})}import{createElement as vr}from"react";import{render as wr}from"ink";import{useCallback as Ce,useEffect as rt,useRef as Q,useState as J}from"react";import{Box as q,Text as D,useInput as xo}from"ink";import{watch as bo}from"fs";import{createServer as vo}from"http";import{join as hr}from"path";import{WebSocketServer as wo}from"ws";import{createReadStream as sr,realpathSync as Mn}from"fs";import{access as Hn,readdir as Un,readFile as qn,realpath as Vn,stat as ar}from"fs/promises";import{dirname as Jn,extname as lr,join as Ne,resolve as Wn,sep as Pt}from"path";import{fileURLToPath as Gn}from"url";var _n=new Set(["set-cookie","strict-transport-security","content-security-policy","content-security-policy-report-only","x-frame-options","content-encoding","content-length"]);function ht(e){let t={};for(let[o,r]of Object.entries(e)){let n=o.toLowerCase();_n.has(n)||n.startsWith("access-control-")||(t[o]=r)}return t}var xt=10*1024*1024,En=6e4,kn=200,Be=class extends Error{bytesRead;limit;constructor(t,o){super(`Upstream response exceeded ${String(o)} bytes (read ${String(t)}).`),this.name="ProxyResponseTooLargeError",this.bytesRead=t,this.limit=o}};async function bt(e,t){let o=e.body;if(o===null)return Buffer.alloc(0);let r=[],n=0;for await(let l of o){if(n+=l.length,n>t)throw new Be(n,t);r.push(l)}return Buffer.concat(r)}function Zt(e={}){let t=new Map,{onChange:o}=e,r=()=>{o?.(t.size)},n=l=>{t.delete(l)&&r()};return{get(l,v){let f=t.get(l);if(f!==void 0){if(Date.now()-f.insertedAt<En)return f.promise.then(m=>({response:m,fromCache:!0}));n(l)}if(t.size>=kn){let m=t.keys().next().value;m!==void 0&&n(m)}let T=v().then(async m=>{let h=ht(Object.fromEntries(m.headers)),x=await bt(m,xt);return{status:m.status,headers:h,body:x}}).catch(m=>{throw n(l),m});return t.set(l,{insertedAt:Date.now(),promise:T}),r(),T.then(m=>((m.status<200||m.status>=300)&&n(l),{response:m,fromCache:!1}))},clear(){t.clear(),r()}}}var vt={".html":"text/html; charset=utf-8",".js":"application/javascript; charset=utf-8",".mjs":"application/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".svg":"image/svg+xml",".ico":"image/x-icon",".json":"application/json; charset=utf-8",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".map":"application/json"};import{mkdir as In,readFile as Bn,writeFile as Dn}from"fs/promises";import{join as Qt}from"path";async function De(e){try{let t=await Bn(Qt(e,"config.json"),"utf-8");return JSON.parse(t)}catch{return{}}}async function me(e,t){await In(e,{recursive:!0}),await Dn(Qt(e,"config.json"),JSON.stringify(t,null,2),"utf-8")}import{spawn as rr}from"child_process";import{writeFile as er,rm as nr,mkdtemp as Rn,access as Nn}from"fs/promises";import{join as Re}from"path";import{tmpdir as jn}from"os";var Fn=`
|
|
7
|
+
`;he.writeFileSync(t,r+n)}function zt(e){e.command("build").description("Bundle the plugin app into .kizenapp directory").action(async()=>{let t=process.cwd(),o=`${t}/.kizenapp`;xe(t);let{waitUntilExit:r}=yn(gn(At,{outputDir:o,pluginDir:t}));await r()})}import{createElement as Bn}from"react";import{render as Dn}from"ink";import{useCallback as Je,useState as ke}from"react";import{Box as M,Text as I,useApp as bn,useInput as vn}from"ink";import{join as yt}from"path";import{access as hn,mkdir as mt,writeFile as xn}from"fs/promises";import{join as ue}from"path";async function Ve(e){try{return await hn(e),!0}catch{return!1}}async function Mt(e){return await Ve(ue(e,"kizen.json"))?"has-manifest":await Ve(ue(e,".kizenapp"))?"has-kizenapp":"ok"}async function Ht(e,t){let o=ue(e,t);if(!await Ve(o))return o;for(let r=1;r<1e3;r++){let n=ue(e,`${t}-${String(r)}`);if(!await Ve(n))return n}throw new Error(`Could not find an available directory name for "${t}"`)}function gt(e){return{name:e.name,version:"1.0.0",published:!0,api_name:e.apiName,external_link:e.externalLink,description:e.description,entry:"src/",engine:"1.0.0",release_notes_directory:"releaseNotes/",release_environments:["prod"],config_template:{},base_config:{},developer_business_id:e.developerBusinessId}}async function Ut(e){await mt(e.targetDir,{recursive:!0});let t=gt(e);await xn(ue(e.targetDir,"kizen.json"),JSON.stringify(t,null,2)+`
|
|
8
|
+
`,"utf-8"),await mt(ue(e.targetDir,"src"),{recursive:!0}),await mt(ue(e.targetDir,"releaseNotes"),{recursive:!0}),xe(e.targetDir)}import{jsx as _,jsxs as L}from"react/jsx-runtime";var pe=["name","apiName","externalLink","description","developerBusinessId"],qt={name:"Name",apiName:"API name",externalLink:"External link",description:"Description",developerBusinessId:"Business ID"},Vt=["name","apiName"];function wn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}var be=({text:e})=>_(I,{dimColor:!0,children:e});function Cn(e){return{name:"",apiName:"",externalLink:"",description:"",developerBusinessId:e}}var Jt=({parentDir:e,defaultBusinessId:t})=>{let o=bn(),[r,n]=ke({type:"target-select",cursor:0}),[s,g]=ke("in-place"),[u,C]=ke(()=>Cn(t)),[b,x]=ke(""),[h,y]=ke(e),c=Je((S,m)=>{g(S),x(m.name),n({type:"field-entry",field:0,values:m})},[]),v=Je(async S=>{let m=await Mt(S);if(m!=="ok"){n({type:"precheck-error",targetDir:S,reason:m});return}y(S),c("in-place",u)},[u,c]),E=Je(async S=>{try{let m=await Ht(e,S.apiName);y(m),n({type:"confirm",values:S})}catch(m){n({type:"error",message:m instanceof Error?m.message:String(m)})}},[e]),R=Je(async(S,m)=>{try{await Ut({targetDir:m,name:S.name,apiName:S.apiName,externalLink:S.externalLink,description:S.description,developerBusinessId:S.developerBusinessId}),n({type:"done",targetDir:m})}catch(p){n({type:"error",message:p instanceof Error?p.message:String(p)})}},[]);if(vn((S,m)=>{if(m.ctrl&&S==="c"){o.exit();return}if(r.type==="target-select"){m.upArrow?n({type:"target-select",cursor:0}):m.downArrow?n({type:"target-select",cursor:1}):m.return?r.cursor===0?v(e):c("sub-dir",u):m.escape&&o.exit();return}if(r.type==="precheck-error"){(m.return||m.escape)&&o.exit();return}if(r.type==="field-entry"){let{field:p,values:P}=r,a=pe[p];if(!a)return;if(m.escape){o.exit();return}if(m.backspace||m.delete){x(i=>i.slice(0,-1));return}if(m.upArrow&&p>0){let i={...P,[a]:b},l=p-1,d=pe[l];n({type:"field-entry",field:l,values:i}),C(i),x(d?i[d]:"");return}if(m.return||m.tab||m.downArrow){let i=b.trim();if(Vt.includes(a)&&!i){n({type:"field-entry",field:p,values:P,fieldError:`${qt[a]} is required`});return}let d=a==="description"?b:i,f={...P,[a]:d};C(f);let F=p+1;if(F>=pe.length)x(""),s==="sub-dir"?(n({type:"resolving-target"}),E(f)):n({type:"confirm",values:f});else{let k=pe[F],N=k?f[k]:"",A=k==="apiName"&&!N?wn(f.name):N;n({type:"field-entry",field:F,values:f}),x(A)}return}S&&!m.ctrl&&!m.meta&&x(i=>i+S);return}if(r.type==="confirm"){if(m.escape){let p=pe.length-1,P=pe[p];n({type:"field-entry",field:p,values:r.values}),x(P?r.values[P]:"");return}m.return&&(n({type:"writing"}),R(r.values,h));return}(r.type==="done"||r.type==="error")&&(m.return||m.escape)&&o.exit()}),r.type==="target-select"){let S=[{label:"Use current directory",desc:e},{label:"Create new sub-directory",desc:`${e}/<inferred from API name>`}];return L(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),L(M,{flexDirection:"column",gap:0,children:[_(I,{bold:!0,children:"Where should the new plugin live?"}),S.map((m,p)=>{let P=r.cursor===p;return L(M,{gap:2,children:[_(I,{...P&&{color:"cyan"},children:P?"\u276F":" "}),_(I,{bold:P,...P&&{color:"cyan"},children:m.label}),_(I,{dimColor:!0,children:m.desc})]},m.label)})]}),_(be,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(r.type==="precheck-error"){let{targetDir:S,reason:m}=r;return L(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),_(I,{color:"red",bold:!0,children:"Cannot create plugin"}),L(M,{flexDirection:"column",gap:0,children:[L(I,{children:[S," already contains ",_(I,{bold:!0,children:m==="has-manifest"?"kizen.json":".kizenapp/"}),"."]}),_(I,{dimColor:!0,children:"Remove the conflicting file/directory or choose a different target to avoid overwriting an existing plugin."})]}),_(be,{text:"Enter or Esc to exit"})]})}if(r.type==="field-entry"){let{field:S,fieldError:m}=r,p=s==="sub-dir"?`Target: sub-directory of ${e} (inferred from API name)`:`Target: ${h}`;return L(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),L(M,{flexDirection:"column",gap:0,children:[_(I,{bold:!0,children:"Plugin details"}),_(I,{dimColor:!0,children:p})]}),m!==void 0&&L(I,{color:"red",children:["Error: ",m]}),_(M,{flexDirection:"column",gap:0,children:pe.map((P,a)=>{let i=S===a,l=i?b:u[P],d=Vt.includes(P),f=`${qt[P]}${d?"":" (optional)"}`;return L(M,{gap:2,children:[_(M,{width:24,children:_(I,{bold:i,...i&&{color:"cyan"},children:f})}),_(I,{...i&&{color:"cyan"},children:">"}),_(I,{children:l}),i&&_(I,{color:"cyan",children:"\u2588"})]},P)})}),_(be,{text:"Enter/Tab/\u2193 next \xB7 \u2191 previous \xB7 Backspace delete \xB7 Esc cancel"})]})}if(r.type==="confirm"){let S=gt({targetDir:h,name:r.values.name,apiName:r.values.apiName,externalLink:r.values.externalLink,description:r.values.description,developerBusinessId:r.values.developerBusinessId});return L(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),L(M,{flexDirection:"column",gap:0,children:[_(I,{bold:!0,children:"Ready to create"}),L(I,{dimColor:!0,children:["Target: ",h]})]}),L(M,{flexDirection:"column",gap:0,children:[_(I,{bold:!0,children:"kizen.json preview"}),_(I,{children:JSON.stringify(S,null,2)})]}),L(M,{flexDirection:"column",gap:0,children:[_(I,{dimColor:!0,children:"Also creates:"}),L(I,{dimColor:!0,children:[" ",yt(h,"src/")]}),L(I,{dimColor:!0,children:[" ",yt(h,"releaseNotes/")]}),L(I,{dimColor:!0,children:[" ",yt(h,".gitignore")," (adds .kizenapp/)"]})]}),_(be,{text:"Enter to create \xB7 Esc to go back"})]})}return r.type==="resolving-target"?_(M,{paddingY:1,paddingX:2,children:_(I,{dimColor:!0,children:"Finding available sub-directory\u2026"})}):r.type==="writing"?_(M,{paddingY:1,paddingX:2,children:_(I,{dimColor:!0,children:"Creating plugin\u2026"})}):r.type==="done"?L(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),L(I,{color:"green",bold:!0,children:["Plugin created at ",r.targetDir]}),L(M,{flexDirection:"column",gap:0,children:[_(I,{dimColor:!0,children:"Next steps:"}),L(I,{children:[" ","cd ",r.targetDir]}),L(I,{children:[" ","appbuilder dev"]})]}),_(be,{text:"Enter or Esc to exit"})]}):L(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),_(I,{color:"red",bold:!0,children:"Failed to create plugin"}),_(I,{children:r.message}),_(be,{text:"Enter or Esc to exit"})]})};import{mkdir as Wt,readFile as Sn,readdir as Pn,writeFile as Gt}from"fs/promises";import{homedir as Tn}from"os";import{dirname as _n,join as We}from"path";var K=["go","fmo","staging","integration","test1"];var fe=We(Tn(),".kizenappbuilder"),ve=We(fe,"credentials.json"),ne="credentials";function En(e){return K.includes(e)}function kn(e){if(typeof e!="object"||e===null)throw new Error("Credentials must be a JSON object");let t=e,o=t.environment;return{apiKey:typeof t.apiKey=="string"?t.apiKey:"",userId:typeof t.userId=="string"?t.userId:"",businessId:typeof t.businessId=="string"?t.businessId:"",environment:En(o)?o:"go"}}async function Ge(e){let t=await Sn(e,"utf-8");return kn(JSON.parse(t))}async function Y(){try{return await Ge(ve)}catch{return null}}async function In(e){await Wt(_n(ve),{recursive:!0,mode:448}),await Gt(ve,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function Kt(e){return We(fe,`${e}.json`)}async function Ie(){let e=[{name:ne,path:ve,isDefault:!0}];try{let t=await Pn(fe);for(let o of t){if(!o.endsWith(".json"))continue;let r=o.slice(0,-5);r!==ne&&e.push({name:r,path:We(fe,o),isDefault:!1})}}catch{}return e}async function Xt(e,t){if(e===ne){await In(t);return}await Wt(fe,{recursive:!0,mode:448}),await Gt(Kt(e),JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}async function we(e){try{return await Ge(Kt(e))}catch{return null}}function Yt(e){e.command("create").description("Scaffold a new Kizen plugin project").action(async()=>{let t=process.cwd(),r=(await Y())?.businessId??"",{waitUntilExit:n}=Dn(Bn(Jt,{parentDir:t,defaultBusinessId:r}),{exitOnCtrlC:!1});await n()})}import{createElement as vr}from"react";import{render as wr}from"ink";import{useCallback as Ce,useEffect as rt,useRef as Q,useState as J}from"react";import{Box as q,Text as D,useInput as Po}from"ink";import{watch as To}from"fs";import{createServer as _o}from"http";import{join as hr}from"path";import{WebSocketServer as Eo}from"ws";import{createReadStream as sr,realpathSync as Wn}from"fs";import{access as Gn,readdir as Kn,readFile as Xn,realpath as Yn,stat as ar}from"fs/promises";import{dirname as Zn,extname as lr,join as Ne,resolve as Qn,sep as Pt}from"path";import{fileURLToPath as eo}from"url";var Rn=new Set(["set-cookie","strict-transport-security","content-security-policy","content-security-policy-report-only","x-frame-options","content-encoding","content-length"]);function ht(e){let t={};for(let[o,r]of Object.entries(e)){let n=o.toLowerCase();Rn.has(n)||n.startsWith("access-control-")||(t[o]=r)}return t}var xt=10*1024*1024,Nn=6e4,jn=200,Be=class extends Error{bytesRead;limit;constructor(t,o){super(`Upstream response exceeded ${String(o)} bytes (read ${String(t)}).`),this.name="ProxyResponseTooLargeError",this.bytesRead=t,this.limit=o}};async function bt(e,t){let o=e.body;if(o===null)return Buffer.alloc(0);let r=[],n=0;for await(let s of o){if(n+=s.length,n>t)throw new Be(n,t);r.push(s)}return Buffer.concat(r)}function Zt(e={}){let t=new Map,{onChange:o}=e,r=()=>{o?.(t.size)},n=s=>{t.delete(s)&&r()};return{get(s,g){let u=t.get(s);if(u!==void 0){if(Date.now()-u.insertedAt<Nn)return u.promise.then(b=>({response:b,fromCache:!0}));n(s)}if(t.size>=jn){let b=t.keys().next().value;b!==void 0&&n(b)}let C=g().then(async b=>{let x=ht(Object.fromEntries(b.headers)),h=await bt(b,xt);return{status:b.status,headers:x,body:h}}).catch(b=>{throw n(s),b});return t.set(s,{insertedAt:Date.now(),promise:C}),r(),C.then(b=>((b.status<200||b.status>=300)&&n(s),{response:b,fromCache:!1}))},clear(){t.clear(),r()}}}var vt={".html":"text/html; charset=utf-8",".js":"application/javascript; charset=utf-8",".mjs":"application/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".svg":"image/svg+xml",".ico":"image/x-icon",".json":"application/json; charset=utf-8",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".map":"application/json"};import{mkdir as Fn,readFile as $n,writeFile as Ln}from"fs/promises";import{join as Qt}from"path";async function De(e){try{let t=await $n(Qt(e,"config.json"),"utf-8");return JSON.parse(t)}catch{return{}}}async function me(e,t){await Fn(e,{recursive:!0}),await Ln(Qt(e,"config.json"),JSON.stringify(t,null,2),"utf-8")}import{spawn as rr}from"child_process";import{writeFile as er,rm as nr,mkdtemp as An,access as On}from"fs/promises";import{join as Re}from"path";import{tmpdir as zn}from"os";var Mn=`
|
|
9
9
|
import sys, json, os, traceback
|
|
10
10
|
|
|
11
11
|
# --- Inputs proxy (attribute access) ---
|
|
@@ -165,12 +165,16 @@ sys.stdout.write('\\n__KIZEN_RESULT_START__\\n')
|
|
|
165
165
|
sys.stdout.write(json.dumps(result, ensure_ascii=False))
|
|
166
166
|
sys.stdout.write('\\n__KIZEN_RESULT_END__\\n')
|
|
167
167
|
sys.stdout.flush()
|
|
168
|
-
`.trim(),
|
|
169
|
-
`);for(;c>=0;){let
|
|
170
|
-
`)}}),
|
|
171
|
-
`).trim(),h=m.length>0?`: ${m}`:"";n(new Error(`${e} exited with code ${String(T)}${h}`))}})})}var Ct=new Set;function Xe(e){for(let t of Ct)t(e)}function On(e,t){return t&&Ct.add(t),Ke||(Ke=(async()=>{let o=Re(wt,"bin","python");try{await Nn(o)}catch{let r=$n(e);await tr(r,["-m","venv",wt])}Xe({kind:"start"});try{await tr(o,["-m","pip","install","--disable-pip-version-check",...An],(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 zn(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 l=e.slice(0,r).trimEnd(),v=e.slice(r+t.length,n).trim();try{let f=JSON.parse(v);return{userStdout:l,result:f}}catch{return{userStdout:e,result:null}}}async function or(e){let t=e.timeout??Ln,o=await On(e.scriptRuntime,e.onInstallProgress),r=Date.now(),n;try{n=await Rn(Re(jn(),"kizen-step-"));let l=Re(n,"wrapper.py"),v=Re(n,"script.py");await Promise.all([er(l,Fn,"utf-8"),er(v,e.script,"utf-8")]);let f={...process.env,__KIZEN_INPUTS__:JSON.stringify(e.inputs),__KIZEN_SECRETS__:JSON.stringify(e.secrets),__KIZEN_SCRIPT_PATH__:v},{exitCode:T,stdout:m,stderr:h}=await new Promise(E=>{let R=[],C=[],g=!1,u=rr(o,[l],{env:f,cwd:n,stdio:["ignore","pipe","pipe"]}),S=setTimeout(()=>{u.kill("SIGKILL")},t);u.stdout.on("data",i=>{R.push(i)}),u.stderr.on("data",i=>{C.push(i)});let s=i=>{g||(g=!0,clearTimeout(S),E({exitCode:i??1,stdout:Buffer.concat(R).toString("utf-8"),stderr:Buffer.concat(C).toString("utf-8")}))};u.on("close",s),u.on("error",i=>{g||(g=!0,clearTimeout(S),E({exitCode:1,stdout:"",stderr:i.message}))})}),x=Date.now()-r,{userStdout:y,result:c}=zn(m);if(c){let E={success:c.success,outputValues:c.outputValues,logs:c.logs,stdout:y,stderr:h,exitCode:T,durationMs:x};return c.error!==null&&(E.error=c.error),c.httpRequests&&(E.httpRequests=c.httpRequests),E}let b={success:!1,outputValues:{},logs:[],stdout:y,stderr:h,exitCode:T,durationMs:x};return T!==0&&(b.error=`Process exited with code ${String(T)}`),b}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 Kn=2*1024*1024,Xn=new Set([".DS_Store",".gitignore"]);function Yn(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 Zn=["kizen.com","kizen.dev"];function Qn(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let o=t.hostname.toLowerCase();return Zn.some(r=>o===r||o.endsWith("."+r))}function eo(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=Wn(e,o);if(r!==e&&!r.startsWith(e+Pt))return null;try{let n=await Vn(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=Gn(import.meta.url);return Ne(Jn(e),"viewer")}async function Tt(e){try{return await Hn(e),!0}catch{return!1}}function pr(e,t,o,r,n,l,v,f,T,m){let h=Zt({onChange:f}),x=Mn(m);return(y,c)=>{(async()=>{let b=y.url??"/";try{if(!Yn(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")&&!eo(y.headers.origin)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Forbidden"}));return}if(t(`Received request: ${b}`),b==="/api/credentials"){c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(r.current!==null?JSON.stringify(r.current):"{}");return}if(b==="/api/credential-profiles"&&y.method==="GET"){let s=await Ie();c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({profiles:s,active:n.current}));return}if(b==="/api/credentials/switch"&&y.method==="POST"){let s=[];for await(let p of y)s.push(p);let a=JSON.parse(Buffer.concat(s).toString("utf-8")||"{}").profile,d=a===void 0||a===""?await Y():await we(a);if(d!==null){r.current=d,n.current=a??void 0;let p=n.current;await me(l,{credentialMode:"global",...p!==void 0&&{activeCredentialProfile:p}}),v({type:"credentials-updated",credentials:d})}c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({ok:d!==null}));return}if(b==="/api/bundle"){let s=Ne(process.cwd(),".kizenapp","bundle.json");try{let i=await qn(s,"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(b==="/api/last-path"&&y.method==="POST"){let s=[];for await(let a of y)s.push(a);let i=JSON.parse(Buffer.concat(s).toString("utf-8")||"{}");if(typeof i.path=="string"){T.current=i.path;let a=await De(l);await me(l,{...a,lastPath:i.path})}c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end('{"ok":true}');return}if(b==="/api/execute-step"&&y.method==="POST"){let s=[];for await(let p of y)s.push(p);let i=JSON.parse(Buffer.concat(s).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 a={script:i.script,scriptRuntime:i.scriptRuntime??"python-3.9",inputs:i.inputs??{},secrets:i.secrets??{},onInstallProgress:p=>{p.kind==="start"?v({type:"venv-install-start"}):p.kind==="log"?v({type:"venv-install-log",line:p.line,stream:p.stream}):p.kind==="complete"?v({type:"venv-install-complete"}):v({type:"venv-install-error",message:p.message})}};typeof i.timeout=="number"&&i.timeout>0&&(a.timeout=Math.min(i.timeout,300*1e3));let d=await or(a);c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify(d));return}if(b==="/api/proxy-cache/clear"){h.clear(),o({kind:"info",message:"Proxy cache cleared"}),c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end('{"ok":true}');return}if(b.startsWith("/api/proxy")){let s=y.headers["x-proxy-target"];if(typeof s!="string"){c.writeHead(400),c.end("Missing x-proxy-target header");return}if(!Qn(s)){c.writeHead(400),c.end("Invalid proxy target");return}let i=b.slice(10)||"/",a=`${s}${i}`,d=y.method??"GET",p=[];for await(let Pe of y)p.push(Pe);let{host:F,"x-proxy-target":k,...N}=y.headers;if(d==="GET"){let Pe=`GET::${a}`,{response:se,fromCache:ot}=await h.get(Pe,()=>fetch(a,{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 $=p.length>0?Buffer.concat(p):void 0,H=$&&$.length>0?$:void 0,W=await fetch(a,{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(b.startsWith("/api/source/tree")&&y.method==="GET"){let i=new URL(b,"http://localhost").searchParams.get("path")??"",a=await cr(x,i);if(a===null){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Invalid path"}));return}if(dr(x,a)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Path is excluded"}));return}try{let d=await Un(a,{withFileTypes:!0}),p=await Promise.all(d.filter(k=>k.isDirectory()?!ze.has(k.name):k.isFile()?!Xn.has(k.name):!1).map(async k=>{let N=k.isDirectory()?"dir":"file",$={name:k.name,kind:N};if(N==="file")try{let H=await ar(Ne(a,k.name));$.size=H.size}catch{}return $}));p.sort((k,N)=>k.kind!==N.kind?k.kind==="dir"?-1:1:k.name.localeCompare(N.name));let F=a===x?"":a.slice(x.length+1);c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({path:F,entries:p}))}catch(d){let p=d instanceof Error?d.message:String(d);t(`source/tree failed (${i}): ${p}`),c.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not found"}))}return}if(b.startsWith("/api/source/file")&&y.method==="GET"){let i=new URL(b,"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 a=await cr(x,i);if(a===null){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Invalid path"}));return}if(dr(x,a)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Path is excluded"}));return}try{let d=await ar(a);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>Kn){c.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"File too large",size:d.size}));return}let p=lr(a).toLowerCase(),F=vt[p],k=ir.has(p),N=F??(k?"text/plain; charset=utf-8":"application/octet-stream");c.writeHead(200,{"Content-Type":N,"Content-Length":String(d.size)}),sr(a).pipe(c)}catch(d){let p=d instanceof Error?d.message:String(d);t(`source/file failed (${i}): ${p}`),c.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not found"}))}return}let C=Ne(e,b==="/"?"/index.html":b),g=await Tt(C)?C:Ne(e,"index.html"),u=lr(g),S=vt[u]??"application/octet-stream";c.writeHead(200,{"Content-Type":S}),sr(g).pipe(c)}catch(E){if(b.startsWith("/api/proxy")){let R=b.slice(10)||"/",C=y.method??"GET";E instanceof Be?o({kind:"info",message:`${C} ${R} \u2192 502 (response exceeded ${String(E.limit)} bytes)`}):o({kind:"request",method:C,status:502,fromCache:!1,url:R})}else o({kind:"info",message:`Error handling ${b}: ${E instanceof Error?E.message:String(E)}`});c.headersSent||(c.writeHead(502),c.end("Bad Gateway"))}})()}}import{launch as to}from"chrome-launcher";import{createRequire as ro}from"module";import{mkdirSync as no}from"fs";import{readFile as oo}from"fs/promises";import{dirname as io,join as so}from"path";import{fileURLToPath as ao}from"url";var fr=ro(import.meta.url)("chrome-remote-interface"),lo=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 co(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 uo(e,t){if(t.type==="object"&&t.objectId)try{let r=(await e.Runtime.callFunctionOn({objectId:t.objectId,functionDeclaration:'function() { const seen = new WeakSet(); return JSON.stringify(this, function(k,v) { if (typeof v === "object" && v !== null) { if (seen.has(v)) return "[Circular]"; seen.add(v); } return v; }); }',returnByValue:!0})).result.value;if(typeof r=="string")return JSON.parse(r)}catch{}return co(t)}async function po(e){try{let t=so(io(ao(import.meta.url)),"viewer","icon.png"),o=await oo(t);await e.Browser.setDockTile({image:o.toString("base64")})}catch{}}async function yr(e){no(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,o=await to({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,l=null,v=null,f=null,T=0,m=!1,h=u=>{e.debugLog?.(u)},x=u=>{e.verbose&&e.debugLog?.(u)},y=()=>{l!==null&&(clearInterval(l),l=null)},c=u=>u==="chrome://new-tab-page/"||u==="chrome://newtab/",b=async u=>{y(),v=null,await po(u),await u.Fetch.enable({patterns:gr.flatMap(s=>[{urlPattern:`*://${s}/*`,requestStage:"Response"},{urlPattern:`*://*.${s}/*`,requestStage:"Response"}])}),u.on("Fetch.requestPaused",s=>{(async()=>{let i=s,{requestId:a,request:d,responseHeaders:p,responseStatusCode:F}=i,k=d.url;x(`Fetch ${String(F??"?")} ${k}`);let N=[],$=!1;for(let H of p??[])if(!lo.has(H.name.toLowerCase()))if(H.name.toLowerCase()==="set-cookie"&&mr(k)){let W=H.value.split(`
|
|
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
|
+
`);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
|
+
`)}}),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() { const seen = new WeakSet(); return JSON.stringify(this, function(k,v) { if (typeof v === "object" && v !== null) { if (seen.has(v)) return "[Circular]"; seen.add(v); } return v; }); }',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
|
-
`);N.push({name:H.name,value:W}),$=!0}else N.push(H);$&&x(` rewrote Set-Cookie SameSite on ${k}`);try{let{body:H,base64Encoded:W}=await u.Fetch.getResponseBody({requestId:a});await u.Fetch.fulfillRequest({requestId:a,responseCode:F??200,responseHeaders:N,body:H,...W&&{base64Encoded:!0}})}catch(H){x(` fulfillRequest failed (${H.message}), falling through`);try{await u.Fetch.continueRequest({requestId:a})}catch(W){x(` continueRequest also failed (${W.message})`)}}})()}),l=setInterval(()=>{(async()=>{try{let{cookies:s}=await u.Network.getAllCookies(),i=0;for(let a of s){if(!mr(`https://${a.domain??""}`)||a.sameSite==="None")continue;let d=a.domain??"",p=d.startsWith(".")?d.slice(1):d;await u.Network.setCookie({url:`https://${p}`,name:a.name,value:a.value,domain:d,path:a.path??"/",secure:!0,...a.httpOnly!==void 0&&{httpOnly:a.httpOnly},...a.expirationDate!==void 0&&{expires:a.expirationDate},sameSite:"None"}),i++}i>0&&x(`cookie-patch cycle: updated ${String(i)} cookie(s) to SameSite=None`)}catch(s){x(`cookie-patch cycle failed: ${s.message}`)}})()},2e3),await u.send("Runtime.enable",{generatePreview:!0}),u.on("Target.attachedToTarget",s=>{let i=s,{sessionId:a,targetInfo:d}=i;x(`attached session ${a} (${d.type} ${d.url})`),u.send("Runtime.enable",{generatePreview:!0},a).catch(p=>{x(` Runtime.enable on session ${a} failed: ${p.message}`)})}),await u.Target.setAutoAttach({autoAttach:!0,waitForDebuggerOnStart:!1,flatten:!0}),await u.Target.setDiscoverTargets({discover:!0});let S=s=>{if(s.type==="page"){if(c(s.url)){h(`closed stray new-tab-page target ${s.targetId}`),v!==null&&u.Target.activateTarget({targetId:v}).catch(()=>{}),u.Target.closeTarget({targetId:s.targetId}).catch(()=>{});return}v===null&&(v=s.targetId,h(`captured main target ${s.targetId} (${s.url})`))}};u.on("Target.targetCreated",s=>{let{targetInfo:i}=s;x(`target +${i.type} ${i.targetId} ${i.url}`),S(i)}),u.on("Target.targetInfoChanged",s=>{let{targetInfo:i}=s;x(`target ~${i.type} ${i.targetId} ${i.url}`),S(i)}),u.on("Runtime.consoleAPICalled",s=>{(async()=>{let{type:i,args:a}=s;if(a[0]?.type==="string"&&String(a[0].value).includes("Chrome Security"))return;let d=i==="warning"?"warn":["log","warn","error","info"].includes(i)?i:"log";x(`console.${d} (${String(a.length)} arg(s))`);let p=await Promise.all(a.map(F=>uo(u,F)));e.broadcast({type:"console-message",level:d,args:p})})().catch(i=>{x(`console serialization failed: ${i.message}`)})}),u.on("disconnect",()=>{m||n!==u||(h("CDP disconnected"),n=null,y(),E())})},E=()=>{if(m||f!==null)return;let u=Math.min(1e3*2**T,1e4),S=T+1;T++,h(`CDP reconnect scheduled in ${String(u)}ms (attempt #${String(S)})`),f=setTimeout(()=>{f=null,(async()=>{let s;try{s=await fr({port:r})}catch{h(`CDP reconnect attempt #${String(S)} failed`),E();return}if(m){try{await s.close()}catch{}return}n=s;try{await b(s),h(`CDP reconnected after ${String(S)} attempt(s)`),T=0}catch{n===s&&(n=null);try{await s.close()}catch{}h(`CDP reconnect attempt #${String(S)} failed during setup`),E()}})()},u)},R=30,C=300;for(let u=0;u<R;u++){await new Promise(S=>setTimeout(S,C)),h(`CDP connect attempt ${String(u+1)}/${String(R)}`);try{let S=await fr({port:r});n=S,e.path&&S.send("Page.navigate",{url:`${t}${e.path}`});try{await b(S),h("CDP connected")}catch{n===S&&(n=null);try{await S.close()}catch{}h("CDP setup failed after connect")}break}catch{if(u===R-1){let S=`CDP unavailable after ${String(R)} attempts \u2014 viewer running without interception (CSP/cookie rewrites disabled)`;return h(S),e.onWarn?.(S),{kill:()=>{o.kill()}}}}}return n?{kill:()=>{if(h("CDP kill requested \u2014 tearing down"),m=!0,f!==null&&(clearTimeout(f),f=null),y(),n!==null){try{n.close()}catch{}n=null}o.kill()}}:{kill:()=>{o.kill()}}}import{useCallback as fo,useState as mo}from"react";function Ze(e){let[t,o]=mo([]),r=fo(n=>{o(l=>[...l,`${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 go}from"ink";import{jsx as P,jsxs as U}from"react/jsx-runtime";var oe=["apiKey","userId","businessId"],yo={apiKey:"API Key",userId:"User ID",businessId:"Business ID"},je=({text:e})=>P(B,{dimColor:!0,children:e}),tt=({initialMode:e,showProfileManager:t,onComplete:o,onCancel:r})=>{let[n,l]=et(e==="global"&&!t?{type:"loading"}:e==="global"&&t?{type:"profile-loading"}:{type:"mode-select",cursor:0}),[v,f]=et(""),[T,m]=et(null),[h,x]=et(void 0),y=Qe(s=>{if(s==="local"){o({mode:"local",credentials:null});return}l({type:"profile-loading"})},[o]),c=Qe(async s=>{if(s===null){l({type:"profile-loading"});let d=await Ie();l({type:"name-entry",nameBuffer:"",existingProfiles:d});return}x(s.isDefault?void 0:s.name),l({type:"loading"});let i=s.isDefault?await Y():await we(s.name),a=i?Math.max(0,K.indexOf(i.environment)):0;l({type:"creds-entry",field:0,values:i??{},envCursor:a})},[]),b=Qe(async(s,i)=>{let a=K[i]??"go",d={apiKey:s.apiKey??"",userId:s.userId??"",businessId:s.businessId??"",environment:a};l({type:"saving"});try{await Xt(h??ne,d),o({mode:"global",credentials:d,...h!==void 0&&{profileName:h}})}catch(p){m(p instanceof Error?p.message:String(p)),l({type:"creds-entry",field:0,values:s,envCursor:i})}},[o,h]);go((s,i)=>{if(i.ctrl&&s==="c"&&process.exit(0),i.escape){if((n.type==="creds-entry"||n.type==="name-entry")&&e==="global"&&t){l({type:"profile-loading"}),E();return}r?.();return}if(n.type==="mode-select"){if(i.upArrow)l({type:"mode-select",cursor:0});else if(i.downArrow)l({type:"mode-select",cursor:1});else if(i.return){let a=n.cursor===0?"global":"local";y(a)}return}if(n.type==="profile-select"){let{profiles:a,cursor:d}=n,p=a.length,F=a.length+1;if(i.upArrow)l({...n,cursor:(d-1+F)%F});else if(i.downArrow)l({...n,cursor:(d+1)%F});else if(i.return)if(d===p)l({type:"name-entry",nameBuffer:"",existingProfiles:a});else{let k=a[d]??a[0];k&&c(k)}return}if(n.type==="name-entry"){let{nameBuffer:a,existingProfiles:d}=n;if(i.backspace||i.delete)l({type:"name-entry",nameBuffer:a.slice(0,-1),existingProfiles:d});else if(i.return){let p=a.trim();if(!p){l({...n,nameError:"Name cannot be empty"});return}if(p===ne){l({...n,nameError:`"${ne}" is reserved`});return}if(d.some(F=>F.name===p)){l({...n,nameError:`Profile "${p}" already exists`});return}x(p),l({type:"creds-entry",field:0,values:{},envCursor:0}),f("")}else s&&!i.ctrl&&!i.meta&&l({type:"name-entry",nameBuffer:a+s,existingProfiles:d});return}if(n.type==="creds-entry"){let{field:a,values:d,envCursor:p}=n;if(a===oe.length){i.leftArrow?l({...n,envCursor:(p-1+K.length)%K.length}):i.rightArrow?l({...n,envCursor:(p+1)%K.length}):i.upArrow?(l({...n,field:a-1}),f(d[oe[a-1]]??"")):i.return&&b(d,p);return}let k=oe[a];if(!k)return;if(i.backspace||i.delete)f(N=>N.slice(0,-1));else if(i.upArrow&&a>0){let N={...d,[k]:v},$=a-1;l({...n,field:$,values:N}),f(N[oe[$]]??"")}else if(i.return||i.tab||i.downArrow){let N={...d,[k]:v},$=a+1;l({...n,field:$,values:N}),$<oe.length?f(N[oe[$]]??""):f("")}else s&&!i.ctrl&&!i.meta&&f(N=>N+s)}});let E=Qe(async()=>{let s=await Ie();l({type:"profile-select",profiles:s,cursor:0})},[]);if(_t(()=>{n.type==="profile-loading"&&E()},[n.type,E]),_t(()=>{e==="global"&&!t&&(async()=>{let s=await Y(),i=s?Math.max(0,K.indexOf(s.environment)):0;l({type:"creds-entry",field:0,values:s??{},envCursor:i})})()},[]),_t(()=>{n.type==="creds-entry"&&n.field===0&&f(n.values.apiKey??"")},[n.type]),n.type==="loading"||n.type==="saving"||n.type==="profile-loading"){let s=n.type==="saving"?"Saving credentials\u2026":n.type==="profile-loading"?"Loading profiles\u2026":"Loading credentials\u2026";return P(z,{paddingY:1,paddingX:2,children:P(B,{dimColor:!0,children:s})})}if(n.type==="done")return null;if(n.type==="mode-select")return U(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),U(z,{flexDirection:"column",gap:0,children:[P(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,a)=>{let d=n.cursor===a;return U(z,{gap:2,children:[P(B,{...d&&{color:"cyan"},children:d?"\u276F":" "}),P(B,{bold:d,...d&&{color:"cyan"},children:i.label}),P(B,{dimColor:!0,children:i.desc})]},i.mode)})]}),P(je,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]});if(n.type==="profile-select"){let{profiles:s,cursor:i}=n,a=s.length;return U(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),U(z,{flexDirection:"column",gap:0,children:[P(B,{bold:!0,children:"Credential profiles"}),s.map((d,p)=>{let F=i===p;return U(z,{gap:2,children:[P(B,{...F&&{color:"cyan"},children:F?"\u276F":" "}),P(B,{bold:F,...F&&{color:"cyan"},children:d.isDefault?"Default":d.name}),P(B,{dimColor:!0,children:d.path})]},d.name)}),U(z,{gap:2,children:[P(B,{...i===a&&{color:"cyan"},children:i===a?"\u276F":" "}),P(B,{bold:i===a,...i===a&&{color:"cyan"},children:"+ Add new profile"})]})]}),P(je,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(n.type==="name-entry"){let{nameBuffer:s,nameError:i}=n;return U(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),P(z,{flexDirection:"column",gap:0,children:P(B,{bold:!0,children:"New credential profile"})}),i&&U(B,{color:"red",children:["Error: ",i]}),U(z,{gap:2,children:[P(z,{width:12,children:P(B,{bold:!0,color:"cyan",children:"Profile name"})}),P(B,{color:"cyan",children:">"}),P(B,{children:s}),P(B,{color:"cyan",children:"\u2588"})]}),P(je,{text:"Type a name \xB7 Enter to confirm \xB7 Esc to go back"})]})}let{field:R,values:C,envCursor:g}=n,u=R===oe.length,S=h??ne;return U(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),U(z,{flexDirection:"column",gap:0,children:[P(B,{bold:!0,children:h!==void 0?`Profile: ${h}`:"Global credentials"}),U(B,{dimColor:!0,children:["Saved to:"," ",h!==void 0?`~/.kizenappbuilder/${h}.json`:ve]})]}),T&&U(B,{color:"red",children:["Error: ",T]}),U(z,{flexDirection:"column",gap:0,children:[oe.map((s,i)=>{let a=R===i,d=a?v:C[s]??"";return U(z,{gap:2,children:[P(z,{width:12,children:P(B,{bold:a,...a&&{color:"cyan"},children:yo[s]})}),P(B,{...a&&{color:"cyan"},children:">"}),P(B,{children:d}),a&&P(B,{color:"cyan",children:"\u2588"})]},s)}),U(z,{gap:2,children:[P(z,{width:12,children:P(B,{bold:u,...u&&{color:"cyan"},children:"Environment"})}),P(B,{...u&&{color:"cyan"},children:">"}),P(z,{gap:1,children:K.map((s,i)=>{let a=i===g;return u?P(B,{bold:a,...a&&{color:"cyan"},children:a?`[${s}]`:s},s):P(B,{dimColor:!a,bold:a,children:s},s)})})]})]}),u?P(je,{text:"\u2190\u2192 to select \xB7 \u2191\u2193 to move \xB7 Enter to save \xB7 Esc to cancel"}):P(je,{text:"\u2191\u2193 to move \xB7 Backspace to delete \xB7 Esc to cancel"}),U(B,{dimColor:!0,children:["Profile: ",S]})]})};import{jsx as j,jsxs as O}from"react/jsx-runtime";var Co=[".kizenapp",".git"],xr=({port:e,pluginDir:t,outputDir:o,credentials:r,credentialMode:n,activeCredentialProfile:l,lastPath:v,debug:f=!1,verbose:T=!1,autoViewer:m=!0})=>{let h=Q(r),x=Q(l),y=Q(v),[c,b]=J("main"),[E,R]=J(n),[C,g]=J("starting"),[u,S]=J(null),[s,i]=Ze(50),[a,d]=Ze(50),[p,F]=Ze(50),[k,N]=J([]),[$,H]=J("pending"),[W,ee]=J(null),[ge,Pe]=J(null),[se,ot]=J(null),[it,st]=J(0),[kt,_r]=J(0),[Er,kr]=J(0),[Ir,Br]=J(0),at=Q(!1),It=Q(!1),Le=Q(null),Te=Q(null),te=Q(new Set),Ae=Q([]),G=Ce(w=>{let L=JSON.stringify(w);if(te.current.size===0){Ae.current=[...Ae.current,L].slice(-50);return}let re=!1;for(let X of te.current)if(X.readyState===1)try{X.send(L)}catch{te.current.delete(X),re=!0}re&&st(te.current.size)},[]),$e=i,lt=Ce(()=>{Le.current?.kill(),Le.current=null,yr({port:e,userDataDir:hr(o,".chrome"),broadcast:G,onWarn:w=>{i(`\u26A0 ${w}`)},...y.current!==void 0&&{path:y.current},...f&&{debugLog:F},...T&&{verbose:!0}}).then(w=>{Le.current=w})},[e,o,G,f,T,F,i]);rt(()=>{let w=()=>{Le.current?.kill()};return process.on("exit",w),()=>{process.off("exit",w)}},[]),xo((w,L)=>{(w==="q"||L.ctrl&&w==="c")&&process.exit(0),w==="c"&&b("editing"),w==="v"&<()},{isActive:c==="main"}),rt(()=>{C!=="running"||It.current||!m||(It.current=!0,lt())},[C,m,lt]);let Dr=Ce(w=>{h.current=w.credentials,x.current=w.profileName,b("main"),R(w.mode);let L=w.profileName;me(o,{credentialMode:w.mode,...L!==void 0&&{activeCredentialProfile:L}}),G({type:"credentials-updated",credentials:w.credentials})},[o,G]),Bt=Ce(w=>{N(L=>[...L,`${new Date().toLocaleTimeString()}: ${St(w)}`].slice(-50)),w.kind==="request"&&(w.fromCache?kr(L=>L+1):Br(L=>L+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 L=w instanceof Error?w.message:String(w);ee(L),H("error")}).finally(()=>{at.current=!1}))},[t,o,ae,G]);if(rt(()=>{ct();let w=bo(t,{recursive:!0},(L,re)=>{if(!re)return;let X=re.replace(/\\/g,"/");Co.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",L=>{ae(`File watcher error \u2014 rebuilds have stopped: ${L.message}`)}),()=>{w.close(),Te.current!==null&&clearTimeout(Te.current)}},[t,ct,ae]),rt(()=>{let w=ur();Tt(hr(w,"index.html")).then(L=>{if(!L){S("Viewer not built. Run 'pnpm build:viewer' first."),g("error");return}let re=pr(w,$e,Bt,h,x,o,G,_r,y,t),X=vo(re),Oe=new wo({server:X});return Oe.on("connection",le=>{for(let Nr of Ae.current)le.readyState===1&&le.send(Nr);Ae.current=[],$e("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",()=>{g("running"),$e(`Server started on 127.0.0.1:${String(e)}`)}),X.on("error",le=>{S(le.message),g("error")}),()=>{Oe.close(),X.close()}})},[e,$e,Bt,G,o,t]),c==="editing")return j(tt,{...E!==void 0&&{initialMode:E},showProfileManager:E==="global",onComplete:Dr,onCancel:()=>{b("main")}});let dt=ge!==null?Math.round((Date.now()-ge.getTime())/1e3):null,Rr=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"}),$==="pending"&&j(D,{dimColor:!0,children:"waiting\u2026"}),$==="building"&&O(q,{gap:1,children:[j(Ue,{}),j(D,{children:"Building plugin package\u2026"})]}),$==="done"&&O(q,{gap:1,children:[j(D,{color:"green",children:"\u2713 Built"}),ge!==null&&O(D,{dimColor:!0,children:["at ",ge.toLocaleTimeString(),Rr]}),se!==null&&O(D,{dimColor:!0,children:["\xB7 bundle: ",_e(se)]})]}),$==="error"&&O(D,{color:"red",children:["\u2717 ",W??"unknown error"]})]}),j(q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:a.slice(-8).map((w,L)=>j(D,{dimColor:!0,wrap:"truncate",children:w},L))})]}),O(q,{marginTop:1,flexDirection:"column",children:[O(q,{gap:2,children:[j(D,{bold:!0,dimColor:!0,children:"Web Server"}),C==="starting"&&j(D,{dimColor:!0,children:"starting\u2026"}),C==="running"&&O(q,{gap:2,children:[j(D,{color:"green",children:"\u2713 Running"}),O(D,{dimColor:!0,children:["\u25CF ",it," viewer",it!==1?"s":""]})]}),C==="error"&&O(D,{color:"red",children:["\u2717 ",u??"Server error"]})]}),j(q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:s.slice(-8).map((w,L)=>j(D,{dimColor:!0,wrap:"truncate",children:w},L))})]}),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"," ",Er," hit \xB7 ",Ir," 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,L)=>j(D,{dimColor:!0,wrap:"truncate",children:w},L))})]}),f&&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 ",p.length," event(s)"]})]}),j(q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:p.length===0?j(D,{dimColor:!0,children:" No CDP events yet."}):p.slice(-8).map((w,L)=>j(D,{dimColor:!0,wrap:"truncate",children:w},L))})]}),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=l=>{o?.(),t(l)},{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 l=null,v,f,{lastPath:T}=await De(n);if(t.credentials)l=await Ge(t.credentials);else{let c=await De(n);if(c.credentialMode==="local")v="local";else if(c.credentialMode==="global"){if(v="global",f=c.activeCredentialProfile,f?(l=await we(f),l||(l=await Y(),f=void 0)):l=await Y(),!l){let b=await br("global");l=b.credentials,f=b.profileName}}else{let b=await br();l=b.credentials,v=b.mode,f=b.profileName;let E=b.profileName;await me(n,{credentialMode:b.mode,...E!==void 0&&{activeCredentialProfile:E}})}}let m=t.verbose===!0,h=m||t.debug===!0,x=t.viewer!==!1,{waitUntilExit:y}=wr(vr(xr,{port:o,pluginDir:r,outputDir:n,credentials:l,...v!==void 0&&{credentialMode:v},...f!==void 0&&{activeCredentialProfile:f},...T!==void 0&&{lastPath:T},debug:h,verbose:m,autoViewer:x}),{exitOnCtrlC:!1});await y()})}import{mkdir as So,writeFile as Po,readFile as To}from"fs/promises";import{join as nt}from"path";var _o=new Set(["developer_business_id"]);function Eo(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 ko={".png":"image/png",".svg":"image/svg+xml",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function Io(e){let t={name:"",children:new Map,isFile:!1,filePath:""};for(let o of e){let r=o.path.split("/"),n=t;r.forEach((l,v)=>{n.children.has(l)||n.children.set(l,{name:l,children:new Map,isFile:v===r.length-1,filePath:r.slice(0,v+1).join("/")});let f=n.children.get(l);f&&(n=f)})}return t}function Et(e){return"file-"+e.replace(/[^a-zA-Z0-9]/g,"-")}function Z(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Pr(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>${Pr(r)}</li>`).join("")}</ul>`}function Bo(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t).toLowerCase():""}function Do(e){let t;return e.base64Image!==void 0?t=`<img src="data:${ko[Bo(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>`}function Ro(e,t){let o=Object.fromEntries(Object.entries(e).filter(([m])=>!_o.has(m)).map(([m,h])=>[m,m==="services"?Eo(h):h])),r=typeof e.name=="string"?e.name:"Plugin",n=typeof e.version=="string"?e.version:"",l=typeof e.description=="string"?e.description:"",v=t.filter(m=>m.path!=="kizen.json"&&m.path!=="plugin-report.html"),f=Pr(Io(v)),T=v.map(Do).join(`
|
|
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"&<()},{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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}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
|
+
${kr(r,t+u)}`}).join(`
|
|
175
|
+
`)}function Ir(e){return e.filter(t=>t.path!=="kizen.json"&&t.path!=="plugin-report.html")}function Br(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!Do.has(t)).map(([t,o])=>[t,t==="services"?Ro(o):o]))}function Lo(e,t){let o=Br(e),r=typeof e.name=="string"?e.name:"Plugin",n=typeof e.version=="string"?e.version:"",s=typeof e.description=="string"?e.description:"",g=Ir(t),u=[];u.push(`# ${r}${n?` v${n}`:""}`),s&&u.push("",s),u.push("","## Configuration (`kizen.json`)","","```json",JSON.stringify(o,null,2),"```"),u.push("","## File Tree","","```",kr(Tr(g)),"```"),u.push("","## Files");for(let C of g)u.push("",`### \`${C.path}\``,""),C.base64Image!==void 0?u.push(`[Image file: ${C.path}]`):C.binaryData!==void 0?u.push(`[Binary file: ${String(C.binaryData.length)} bytes]`):u.push(`\`\`\`${$o(C.path)}`,C.content,"```");return u.join(`
|
|
176
|
+
`)+`
|
|
177
|
+
`}function Ao(e,t){let o=Br(e),r=typeof e.name=="string"?e.name:"Plugin",n=typeof e.version=="string"?e.version:"",s=typeof e.description=="string"?e.description:"",g=Ir(t),u=_r(Tr(g)),C=g.map(jo).join(`
|
|
174
178
|
`);return`<!DOCTYPE html>
|
|
175
179
|
<html lang="en">
|
|
176
180
|
<head>
|
|
@@ -214,16 +218,16 @@ img{border:1px solid var(--bd);border-radius:4px}
|
|
|
214
218
|
<body>
|
|
215
219
|
<header>
|
|
216
220
|
<h1>${Z(r)}${n?` <span style="color:var(--mu);font-size:.8em">v${Z(n)}</span>`:""}</h1>
|
|
217
|
-
${
|
|
221
|
+
${s?`<p>${Z(s)}</p>`:""}
|
|
218
222
|
</header>
|
|
219
223
|
<div class="layout">
|
|
220
224
|
<nav>
|
|
221
225
|
<a href="#config" class="cfg" data-id="config">kizen.json (config)</a>
|
|
222
|
-
${
|
|
226
|
+
${u}
|
|
223
227
|
</nav>
|
|
224
228
|
<main>
|
|
225
229
|
<section id="config"><h2 class="fp">kizen.json \u2014 Plugin Configuration</h2><div class="fb"><pre><code>${Z(JSON.stringify(o,null,2))}</code></pre></div></section>
|
|
226
|
-
${
|
|
230
|
+
${C}
|
|
227
231
|
</main>
|
|
228
232
|
</div>
|
|
229
233
|
<script>
|
|
@@ -236,5 +240,7 @@ ${T}
|
|
|
236
240
|
})();
|
|
237
241
|
</script>
|
|
238
242
|
</body>
|
|
239
|
-
</html>`}var
|
|
243
|
+
</html>`}var Pr=nt(fe,"examples");function Dr(e){e.command("report").description("Generate a self-contained HTML report of the plugin").option("-o, --output <path>",`output file path (default: ${Pr}/<api_name>.html)`).action(async t=>{let o=process.cwd(),r;try{let C=await Bo(nt(o,"kizen.json"),"utf-8"),b=JSON.parse(C);r=Array.isArray(b)?b[0]:b}catch{console.error("Error: kizen.json not found. Run this command from a plugin directory."),process.exit(1)}let n=typeof r.api_name=="string"?r.api_name:"plugin",s=t.output??nt(Pr,`${n}.html`),g=s.replace(/\.html$/,".md"),u=await Me(o);await Io(nt(s,".."),{recursive:!0}),await Promise.all([Sr(s,Ao(r,u),"utf-8"),Sr(g,Lo(r,u),"utf-8")]),console.log(`Plugin report written to:
|
|
244
|
+
${s}
|
|
245
|
+
${g}`)})}var Uo=Mo(zo(Ho(import.meta.url)),"..","package.json"),qo=JSON.parse(Oo(Uo,"utf-8"));Se.name("appbuilder").description("Kizen plugin app builder").version(qo.version);Yt(Se);zt(Se);Cr(Se);Dr(Se);Se.parse();
|
|
240
246
|
//# sourceMappingURL=index.js.map
|