@kizenapps/cli 0.14.0 → 0.15.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 +7 -7
- package/dist/index.js.map +1 -1
- package/dist/viewer/assets/AppDetailPage-BorvgFPN.js +1 -0
- package/dist/viewer/assets/{CodeStepsPage-BzaaN9Kb.js → CodeStepsPage-BZ2IGkjP.js} +1 -1
- package/dist/viewer/assets/{ConfigurationPage-DyGQQTe-.js → ConfigurationPage-n8Uo_HL7.js} +1 -1
- package/dist/viewer/assets/{DevSidebar-h9gYdctz.js → DevSidebar-DS8UU-G8.js} +1 -1
- package/dist/viewer/assets/{SandboxPage-IYn-KIbv.js → SandboxPage-CB4FgqI3.js} +1 -1
- package/dist/viewer/assets/SourceBrowserPage-BBZcr3MI.js +1 -0
- package/dist/viewer/assets/{WhenBadge-GxhTQKsq.js → WhenBadge-y4k1WgBK.js} +1 -1
- package/dist/viewer/assets/{api-C5Iu-4AS.js → api-CT-MKz2h.js} +1 -1
- package/dist/viewer/assets/{configStorage-BnMh081m.js → configStorage-CNoQ0cy5.js} +1 -1
- package/dist/viewer/assets/formatBytes-C9lOTtsO.js +1 -0
- package/dist/viewer/assets/{index-CjU7OUke.js → index-BMMO15ja.js} +3 -3
- package/dist/viewer/assets/{storageKeys-ClzdCxlg.js → storageKeys-C6c8YF5Y.js} +1 -1
- package/dist/viewer/assets/{useCriticalExceptionDialog-DK8ufamu.js → useCriticalExceptionDialog-C3m9pLEk.js} +1 -1
- package/dist/viewer/index.html +3 -5
- package/package.json +5 -3
- package/dist/viewer/assets/AppDetailPage-D4r3W5v5.js +0 -1
- package/dist/viewer/assets/SourceBrowserPage-BOlm36Dg.js +0 -1
- package/dist/viewer/manifest.json +0 -10
- /package/dist/viewer/assets/{CodeViewer-Ce2qKSWi.js → CodeViewer-C9aVhzG7.js} +0 -0
- /package/dist/viewer/assets/{IconReferencePage-BLciUKH9.js → IconReferencePage-bTBpdJEd.js} +0 -0
- /package/dist/viewer/assets/{VersionsPage-C02dpN3Y.js → VersionsPage-D6QScnTb.js} +0 -0
- /package/dist/viewer/assets/{useLocalStorage-B73GyZbK.js → useLocalStorage-CyZiO78q.js} +0 -0
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{readFileSync as go}from"fs";import{dirname as yo,join as ho}from"path";import{fileURLToPath as xo}from"url";import{program as Le}from"commander";import{createElement as
|
|
2
|
+
import{readFileSync as go}from"fs";import{dirname as yo,join as ho}from"path";import{fileURLToPath as xo}from"url";import{program as Le}from"commander";import{createElement as en}from"react";import{render as tn}from"ink";import{useEffect as Yr,useState as ct}from"react";import{Box as Pe,Text as me,useApp as Zr}from"ink";import{mkdir as Dr,writeFile as Rr}from"fs/promises";import{join as Nr}from"path";import{minifyFiles as Lr,packagePlugin as jr,transformDeployablePlugin as Fr}from"@kizenapps/packager";import{readdir as Er,readFile as at}from"fs/promises";import{join as _t,relative as kr}from"path";var Ir=new Set([".png",".svg"]),Br=new Set([".kzn"]),$e=new Set(["node_modules",".git",".kizenapp",".github"]);async function Et(e,t){let i=await Er(e,{withFileTypes:!0}),n=[];for(let r of i)if(r.isDirectory()){if($e.has(r.name))continue;n.push(...await Et(_t(e,r.name),t))}else r.isFile()&&n.push(_t(e,r.name));return n}async function kt(e){let t=await Et(e,e);return Promise.all(t.map(async i=>{let n=kr(e,i).split("\\").join("/"),r=n.lastIndexOf("."),c=r>=0?n.slice(r).toLowerCase():"";if(Ir.has(c)){let y=await at(i);return{path:n,content:"",base64Image:y.toString("base64")}}if(Br.has(c)){let y=await at(i);return{path:n,content:"",binaryData:y}}let S=await at(i,"utf-8");return{path:n,content:S}}))}var Ar=["name","api_name","version","entry"];function It(e,t){let i=t===void 0?"kizen.json":`kizen.json entry #${String(t+1)}`;for(let n of Ar){let r=e[n];if(typeof r!="string"||r==="")throw new Error(`${i} is missing required field "${n}" (expected a non-empty string).`)}}function Or(e){let t;try{t=JSON.parse(e)}catch(i){let n=i instanceof Error?i.message:String(i);throw new Error(`kizen.json is not valid JSON: ${n}`)}if(Array.isArray(t))return t.forEach((i,n)=>{if(typeof i!="object"||i===null)throw new Error(`kizen.json entry #${String(n+1)} is not a JSON object.`);It(i,n)}),t;if(typeof t!="object"||t===null)throw new Error("kizen.json must be a JSON object (or array of objects).");return It(t),t}var $r=(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 ze(e,t,i){await Dr(t,{recursive:!0}),i?.("reading-files");let n=await kt(e);i?.("minifying");let r=await Lr(n);i?.("packaging");let c=r.find(a=>a.path==="kizen.json");if(!c)throw new Error("kizen.json not found in plugin directory.");let S=Or(c.content),y=jr(r,S),_=Object.values(y).map(Fr);i?.("writing-bundle");let b=_.map(a=>{let v=a.release_notes_directory?.replace(/\/$/,""),N=v?n.filter(E=>E.path.startsWith(v+"/")&&E.path.endsWith(".md")&&E.content).map(E=>({version:E.path.slice(E.path.lastIndexOf("/")+1,-3),notes:E.content})).sort((E,C)=>C.version.localeCompare(E.version,void 0,{numeric:!0})):[];return $r(a,N)}),h=JSON.stringify(b,null,2),g=(a,v)=>a==="allReleaseNotes"?void 0:v,f=Buffer.byteLength(JSON.stringify(b,g,2),"utf-8");return await Rr(Nr(t,"bundle.json"),h,"utf-8"),{bundleSize:f}}function Se(e){return e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}import{Box as Ur,Text as qr}from"ink";import{Box as zr,Text as Mr}from"ink";import{jsx as Bt}from"react/jsx-runtime";var Hr=[" :::::::: "," :::::: ::::::::::: "," :::::: :::::::::: "," :::::: :::::: ::::::: "," ::::: :::::: ::::::::::::::::: "," ::::: ::::: ::::::::::::::::::: "," ::::: ::::: :::::: ::::: ",":::: ::::: ::: ::::: :: ","::::: :::::: :::::::::: ","::::: :::::: ::::::::::: "," ::::: ::: ::::::: "," ::::::: ::: ::::: "," ::::::::::: :::::: :::::"," :::::::::: :::::: :::::"," :: ::::: ::: ::::: ::::"," ::::: :::::: ::::: ::::: ::: "," ::::::::::::::::::: ::::: ::::: "," ::::::::::::::::: ::::: ::::: "," ::::::::: :::::: :::::: "," :::::::::: :::::: "," ::::::::::: :::::: "," :::::::: "],Dt=()=>Bt(zr,{flexDirection:"column",children:Hr.map((e,t)=>Bt(Mr,{color:"cyan",children:e},t))});import{Fragment as Vr,jsx as lt,jsxs as Jr}from"react/jsx-runtime";var V=({marginBottom:e=0})=>Jr(Vr,{children:[lt(Dt,{}),lt(Ur,{flexDirection:"column",marginTop:1,marginBottom:e,children:lt(qr,{bold:!0,color:"cyan",children:"Kizen App Development Toolkit"})})]});import{useEffect as Wr,useState as Kr}from"react";import{Text as Gr}from"ink";import{jsx as Xr}from"react/jsx-runtime";var Rt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Me=()=>{let[e,t]=Kr(0);return Wr(()=>{let i=setInterval(()=>{t(n=>(n+1)%Rt.length)},80);return()=>{clearInterval(i)}},[]),Xr(Gr,{color:"cyan",children:Rt[e]??"\u280B"})};import{Fragment as Qr,jsx as ae,jsxs as le}from"react/jsx-runtime";var Nt=["creating-dir","reading-files","minifying","packaging","writing-bundle"],He={"creating-dir":"Creating .kizenapp directory","reading-files":"Reading plugin files",minifying:"Minifying scripts",packaging:"Packaging plugin","writing-bundle":"Writing bundle.json"},Lt=({outputDir:e,pluginDir:t})=>{let i=Zr(),[n,r]=ct("creating-dir"),[c,S]=ct(null),[y,_]=ct(null);Yr(()=>{ze(t,e,r).then(({bundleSize:f})=>{_(f),r("done"),i.exit()}).catch(f=>{let a=f instanceof Error?f.message:String(f);S(a),r("error"),i.exit()})},[e,t,i]);let b=Nt.indexOf(n),h=n==="error",g=n==="done";return le(Pe,{flexDirection:"column",paddingY:1,paddingX:2,children:[ae(V,{marginBottom:1}),le(Pe,{flexDirection:"column",gap:0,children:[Nt.map((f,a)=>{let v=n===f,N=g||b>a;return ae(Pe,{gap:1,children:h&&a===b?le(me,{color:"red",children:["\u2717 ",He[f]]}):N?le(me,{color:"green",children:["\u2713 ",He[f]]}):v?le(Qr,{children:[ae(Me,{}),ae(me,{children:He[f]})]}):le(me,{dimColor:!0,children:[" ",He[f]]})},f)}),g&&y!==null&&ae(Pe,{marginTop:1,gap:1,children:le(me,{color:"green",children:["\u2713 bundle \u2014 ",Se(y)]})}),c!==null&&ae(Pe,{marginTop:1,borderStyle:"single",borderColor:"red",paddingX:1,children:ae(me,{color:"red",children:c})})]})]})};import*as ge from"fs";import*as jt from"path";function ye(e){let t=jt.join(e,".gitignore"),i=".kizenapp/",n="";if(ge.existsSync(t)){n=ge.readFileSync(t,"utf8");let c=n.split(`
|
|
3
3
|
`).map(S=>S.trim());if(c.includes(i)||c.includes(".kizenapp"))return}let r=n.endsWith(`
|
|
4
4
|
`)?i+`
|
|
5
5
|
`:`
|
|
6
6
|
`+i+`
|
|
7
|
-
`;ge.writeFileSync(t,n+r)}function Ft(e){e.command("build").description("Bundle the plugin app into .kizenapp directory").action(async()=>{let t=process.cwd(),i=`${t}/.kizenapp`;ye(t);let{waitUntilExit:n}=en(
|
|
8
|
-
`,"utf-8"),await dt(ce(e.targetDir,"src"),{recursive:!0}),await dt(ce(e.targetDir,"releaseNotes"),{recursive:!0}),ye(e.targetDir)}import{jsx as T,jsxs as A}from"react/jsx-runtime";var de=["name","apiName","externalLink","description","developerBusinessId"],$t={name:"Name",apiName:"API name",externalLink:"External link",description:"Description",developerBusinessId:"Business ID"},zt=["name","apiName"];function sn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}var he=({text:e})=>T(B,{dimColor:!0,children:e});function an(e){return{name:"",apiName:"",externalLink:"",description:"",developerBusinessId:e}}var Mt=({parentDir:e,defaultBusinessId:t})=>{let i=nn(),[n,r]=Te({type:"target-select",cursor:0}),[c,S]=Te("in-place"),[y,_]=Te(()=>an(t)),[b,h]=Te(""),[g,f]=Te(e),a=Ue((C,m)=>{S(C),h(m.name),r({type:"field-entry",field:0,values:m})},[]),v=Ue(async C=>{let m=await jt(C);if(m!=="ok"){r({type:"precheck-error",targetDir:C,reason:m});return}f(C),a("in-place",y)},[y,a]),N=Ue(async C=>{try{let m=await At(e,C.apiName);f(m),r({type:"confirm",values:C})}catch(m){r({type:"error",message:m instanceof Error?m.message:String(m)})}},[e]),E=Ue(async(C,m)=>{try{await Ot({targetDir:m,name:C.name,apiName:C.apiName,externalLink:C.externalLink,description:C.description,developerBusinessId:C.developerBusinessId}),r({type:"done",targetDir:m})}catch(u){r({type:"error",message:u instanceof Error?u.message:String(u)})}},[]);if(on((C,m)=>{if(m.ctrl&&C==="c"){i.exit();return}if(n.type==="target-select"){m.upArrow?r({type:"target-select",cursor:0}):m.downArrow?r({type:"target-select",cursor:1}):m.return?n.cursor===0?v(e):a("sub-dir",y):m.escape&&i.exit();return}if(n.type==="precheck-error"){(m.return||m.escape)&&i.exit();return}if(n.type==="field-entry"){let{field:u,values:w}=n,s=de[u];if(!s)return;if(m.escape){i.exit();return}if(m.backspace||m.delete){h(o=>o.slice(0,-1));return}if(m.upArrow&&u>0){let o={...w,[s]:b},l=u-1,d=de[l];r({type:"field-entry",field:l,values:o}),_(o),h(d?o[d]:"");return}if(m.return||m.tab||m.downArrow){let o=b.trim();if(zt.includes(s)&&!o){r({type:"field-entry",field:u,values:w,fieldError:`${$t[s]} is required`});return}let d=s==="description"?b:o,p={...w,[s]:d};_(p);let F=u+1;if(F>=de.length)h(""),c==="sub-dir"?(r({type:"resolving-target"}),N(p)):r({type:"confirm",values:p});else{let k=de[F],I=k?p[k]:"",O=k==="apiName"&&!I?sn(p.name):I;r({type:"field-entry",field:F,values:p}),h(O)}return}C&&!m.ctrl&&!m.meta&&h(o=>o+C);return}if(n.type==="confirm"){if(m.escape){let u=de.length-1,w=de[u];r({type:"field-entry",field:u,values:n.values}),h(w?n.values[w]:"");return}m.return&&(r({type:"writing"}),E(n.values,g));return}(n.type==="done"||n.type==="error")&&(m.return||m.escape)&&i.exit()}),n.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:[T(V,{}),A(M,{flexDirection:"column",gap:0,children:[T(B,{bold:!0,children:"Where should the new plugin live?"}),C.map((m,u)=>{let w=n.cursor===u;return A(M,{gap:2,children:[T(B,{...w&&{color:"cyan"},children:w?"\u276F":" "}),T(B,{bold:w,...w&&{color:"cyan"},children:m.label}),T(B,{dimColor:!0,children:m.desc})]},m.label)})]}),T(he,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(n.type==="precheck-error"){let{targetDir:C,reason:m}=n;return A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),T(B,{color:"red",bold:!0,children:"Cannot create plugin"}),A(M,{flexDirection:"column",gap:0,children:[A(B,{children:[C," already contains ",T(B,{bold:!0,children:m==="has-manifest"?"kizen.json":".kizenapp/"}),"."]}),T(B,{dimColor:!0,children:"Remove the conflicting file/directory or choose a different target to avoid overwriting an existing plugin."})]}),T(he,{text:"Enter or Esc to exit"})]})}if(n.type==="field-entry"){let{field:C,fieldError:m}=n,u=c==="sub-dir"?`Target: sub-directory of ${e} (inferred from API name)`:`Target: ${g}`;return A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),A(M,{flexDirection:"column",gap:0,children:[T(B,{bold:!0,children:"Plugin details"}),T(B,{dimColor:!0,children:u})]}),m!==void 0&&A(B,{color:"red",children:["Error: ",m]}),T(M,{flexDirection:"column",gap:0,children:de.map((w,s)=>{let o=C===s,l=o?b:y[w],d=zt.includes(w),p=`${$t[w]}${d?"":" (optional)"}`;return A(M,{gap:2,children:[T(M,{width:24,children:T(B,{bold:o,...o&&{color:"cyan"},children:p})}),T(B,{...o&&{color:"cyan"},children:">"}),T(B,{children:l}),o&&T(B,{color:"cyan",children:"\u2588"})]},w)})}),T(he,{text:"Enter/Tab/\u2193 next \xB7 \u2191 previous \xB7 Backspace delete \xB7 Esc cancel"})]})}if(n.type==="confirm"){let C=ut({targetDir:g,name:n.values.name,apiName:n.values.apiName,externalLink:n.values.externalLink,description:n.values.description,developerBusinessId:n.values.developerBusinessId});return A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),A(M,{flexDirection:"column",gap:0,children:[T(B,{bold:!0,children:"Ready to create"}),A(B,{dimColor:!0,children:["Target: ",g]})]}),A(M,{flexDirection:"column",gap:0,children:[T(B,{bold:!0,children:"kizen.json preview"}),T(B,{children:JSON.stringify(C,null,2)})]}),A(M,{flexDirection:"column",gap:0,children:[T(B,{dimColor:!0,children:"Also creates:"}),A(B,{dimColor:!0,children:[" ",pt(g,"src/")]}),A(B,{dimColor:!0,children:[" ",pt(g,"releaseNotes/")]}),A(B,{dimColor:!0,children:[" ",pt(g,".gitignore")," (adds .kizenapp/)"]})]}),T(he,{text:"Enter to create \xB7 Esc to go back"})]})}return n.type==="resolving-target"?T(M,{paddingY:1,paddingX:2,children:T(B,{dimColor:!0,children:"Finding available sub-directory\u2026"})}):n.type==="writing"?T(M,{paddingY:1,paddingX:2,children:T(B,{dimColor:!0,children:"Creating plugin\u2026"})}):n.type==="done"?A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),A(B,{color:"green",bold:!0,children:["Plugin created at ",n.targetDir]}),A(M,{flexDirection:"column",gap:0,children:[T(B,{dimColor:!0,children:"Next steps:"}),A(B,{children:[" ","cd ",n.targetDir]}),A(B,{children:[" ","appbuilder dev"]})]}),T(he,{text:"Enter or Esc to exit"})]}):A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),T(B,{color:"red",bold:!0,children:"Failed to create plugin"}),T(B,{children:n.message}),T(he,{text:"Enter or Esc to exit"})]})};import{mkdir as Ht,readFile as ln,readdir as cn,writeFile as qt}from"fs/promises";import{homedir as dn}from"os";import{dirname as un,join as Ve}from"path";var Z=["go","fmo","staging","integration","test1"],_e=Ve(dn(),".kizenappbuilder"),xe=Ve(_e,"credentials.json"),re="credentials";function pn(e){return Z.includes(e)}function fn(e){if(typeof e!="object"||e===null)throw new Error("Credentials must be a JSON object");let t=e,i=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:pn(i)?i:"go"}}async function Je(e){let t=await ln(e,"utf-8");return fn(JSON.parse(t))}async function Y(){try{return await Je(xe)}catch{return null}}async function mn(e){await Ht(un(xe),{recursive:!0,mode:448}),await qt(xe,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function Ut(e){return Ve(_e,`${e}.json`)}async function Ee(){let e=[{name:re,path:xe,isDefault:!0}];try{let t=await cn(_e);for(let i of t){if(!i.endsWith(".json"))continue;let n=i.slice(0,-5);n!==re&&e.push({name:n,path:Ve(_e,i),isDefault:!1})}}catch{}return e}async function Vt(e,t){if(e===re){await mn(t);return}await Ht(_e,{recursive:!0,mode:448}),await qt(Ut(e),JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}async function be(e){try{return await Je(Ut(e))}catch{return null}}function Jt(e){e.command("create").description("Scaffold a new Kizen plugin project").action(async()=>{let t=process.cwd(),n=(await Y())?.businessId??"",{waitUntilExit:r}=yn(gn(Mt,{parentDir:t,defaultBusinessId:n}),{exitOnCtrlC:!1});await r()})}import{createElement as gr}from"react";import{render as yr}from"ink";import{useCallback as ve,useEffect as et,useRef as Q,useState as W}from"react";import{Box as q,Text as R,useInput as co}from"ink";import{watch as uo}from"fs";import{createServer as po}from"http";import{join as pr}from"path";import{WebSocketServer as fo}from"ws";import{createReadStream as er,realpathSync as Rn}from"fs";import{access as Nn,readdir as Ln,readFile as Fn,realpath as jn,stat as tr}from"fs/promises";import{dirname as An,extname as rr,join as De,resolve as On,sep as bt}from"path";import{fileURLToPath as $n}from"url";var hn=new Set(["set-cookie","strict-transport-security","content-security-policy","content-security-policy-report-only","x-frame-options","content-encoding","content-length"]);function ft(e){let t={};for(let[i,n]of Object.entries(e)){let r=i.toLowerCase();hn.has(r)||r.startsWith("access-control-")||(t[i]=n)}return t}var mt=10*1024*1024,xn=6e4,bn=200,ke=class extends Error{bytesRead;limit;constructor(t,i){super(`Upstream response exceeded ${String(i)} bytes (read ${String(t)}).`),this.name="ProxyResponseTooLargeError",this.bytesRead=t,this.limit=i}};async function gt(e,t){let i=e.body;if(i===null)return Buffer.alloc(0);let n=[],r=0;for await(let c of i){if(r+=c.length,r>t)throw new ke(r,t);n.push(c)}return Buffer.concat(n)}function Wt(e={}){let t=new Map,{onChange:i}=e,n=()=>{i?.(t.size)},r=c=>{t.delete(c)&&n()};return{get(c,S){let y=t.get(c);if(y!==void 0){if(Date.now()-y.insertedAt<xn)return y.promise.then(b=>({response:b,fromCache:!0}));r(c)}if(t.size>=bn){let b=t.keys().next().value;b!==void 0&&r(b)}let _=S().then(async b=>{let h=ft(Object.fromEntries(b.headers)),g=await gt(b,mt);return{status:b.status,headers:h,body:g}}).catch(b=>{throw r(c),b});return t.set(c,{insertedAt:Date.now(),promise:_}),n(),_.then(b=>((b.status<200||b.status>=300)&&r(c),{response:b,fromCache:!1}))},clear(){t.clear(),n()}}}var yt={".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 vn,readFile as Cn,writeFile as wn}from"fs/promises";import{join as Kt}from"path";async function Ie(e){try{let t=await Cn(Kt(e,"config.json"),"utf-8");return JSON.parse(t)}catch{return{}}}async function ue(e,t){await vn(e,{recursive:!0}),await wn(Kt(e,"config.json"),JSON.stringify(t,null,2),"utf-8")}import{spawn as Yt}from"child_process";import{writeFile as Gt,rm as Zt,mkdtemp as Sn,access as Pn}from"fs/promises";import{join as Be}from"path";import{tmpdir as Tn}from"os";var _n=`
|
|
7
|
+
`;ge.writeFileSync(t,n+r)}function Ft(e){e.command("build").description("Bundle the plugin app into .kizenapp directory").action(async()=>{let t=process.cwd(),i=`${t}/.kizenapp`;ye(t);let{waitUntilExit:n}=tn(en(Lt,{outputDir:i,pluginDir:t}));await n()})}import{createElement as yn}from"react";import{render as hn}from"ink";import{useCallback as qe,useState as Te}from"react";import{Box as M,Text as B,useApp as on,useInput as sn}from"ink";import{join as pt}from"path";import{access as rn,mkdir as dt,writeFile as nn}from"fs/promises";import{join as ce}from"path";async function Ue(e){try{return await rn(e),!0}catch{return!1}}async function At(e){return await Ue(ce(e,"kizen.json"))?"has-manifest":await Ue(ce(e,".kizenapp"))?"has-kizenapp":"ok"}async function Ot(e,t){let i=ce(e,t);if(!await Ue(i))return i;for(let n=1;n<1e3;n++){let r=ce(e,`${t}-${String(n)}`);if(!await Ue(r))return r}throw new Error(`Could not find an available directory name for "${t}"`)}function ut(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 $t(e){await dt(e.targetDir,{recursive:!0});let t=ut(e);await nn(ce(e.targetDir,"kizen.json"),JSON.stringify(t,null,2)+`
|
|
8
|
+
`,"utf-8"),await dt(ce(e.targetDir,"src"),{recursive:!0}),await dt(ce(e.targetDir,"releaseNotes"),{recursive:!0}),ye(e.targetDir)}import{jsx as T,jsxs as A}from"react/jsx-runtime";var de=["name","apiName","externalLink","description","developerBusinessId"],zt={name:"Name",apiName:"API name",externalLink:"External link",description:"Description",developerBusinessId:"Business ID"},Mt=["name","apiName"];function an(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}var he=({text:e})=>T(B,{dimColor:!0,children:e});function ln(e){return{name:"",apiName:"",externalLink:"",description:"",developerBusinessId:e}}var Ht=({parentDir:e,defaultBusinessId:t})=>{let i=on(),[n,r]=Te({type:"target-select",cursor:0}),[c,S]=Te("in-place"),[y,_]=Te(()=>ln(t)),[b,h]=Te(""),[g,f]=Te(e),a=qe((C,m)=>{S(C),h(m.name),r({type:"field-entry",field:0,values:m})},[]),v=qe(async C=>{let m=await At(C);if(m!=="ok"){r({type:"precheck-error",targetDir:C,reason:m});return}f(C),a("in-place",y)},[y,a]),N=qe(async C=>{try{let m=await Ot(e,C.apiName);f(m),r({type:"confirm",values:C})}catch(m){r({type:"error",message:m instanceof Error?m.message:String(m)})}},[e]),E=qe(async(C,m)=>{try{await $t({targetDir:m,name:C.name,apiName:C.apiName,externalLink:C.externalLink,description:C.description,developerBusinessId:C.developerBusinessId}),r({type:"done",targetDir:m})}catch(u){r({type:"error",message:u instanceof Error?u.message:String(u)})}},[]);if(sn((C,m)=>{if(m.ctrl&&C==="c"){i.exit();return}if(n.type==="target-select"){m.upArrow?r({type:"target-select",cursor:0}):m.downArrow?r({type:"target-select",cursor:1}):m.return?n.cursor===0?v(e):a("sub-dir",y):m.escape&&i.exit();return}if(n.type==="precheck-error"){(m.return||m.escape)&&i.exit();return}if(n.type==="field-entry"){let{field:u,values:w}=n,s=de[u];if(!s)return;if(m.escape){i.exit();return}if(m.backspace||m.delete){h(o=>o.slice(0,-1));return}if(m.upArrow&&u>0){let o={...w,[s]:b},l=u-1,d=de[l];r({type:"field-entry",field:l,values:o}),_(o),h(d?o[d]:"");return}if(m.return||m.tab||m.downArrow){let o=b.trim();if(Mt.includes(s)&&!o){r({type:"field-entry",field:u,values:w,fieldError:`${zt[s]} is required`});return}let d=s==="description"?b:o,p={...w,[s]:d};_(p);let j=u+1;if(j>=de.length)h(""),c==="sub-dir"?(r({type:"resolving-target"}),N(p)):r({type:"confirm",values:p});else{let k=de[j],I=k?p[k]:"",O=k==="apiName"&&!I?an(p.name):I;r({type:"field-entry",field:j,values:p}),h(O)}return}C&&!m.ctrl&&!m.meta&&h(o=>o+C);return}if(n.type==="confirm"){if(m.escape){let u=de.length-1,w=de[u];r({type:"field-entry",field:u,values:n.values}),h(w?n.values[w]:"");return}m.return&&(r({type:"writing"}),E(n.values,g));return}(n.type==="done"||n.type==="error")&&(m.return||m.escape)&&i.exit()}),n.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:[T(V,{}),A(M,{flexDirection:"column",gap:0,children:[T(B,{bold:!0,children:"Where should the new plugin live?"}),C.map((m,u)=>{let w=n.cursor===u;return A(M,{gap:2,children:[T(B,{...w&&{color:"cyan"},children:w?"\u276F":" "}),T(B,{bold:w,...w&&{color:"cyan"},children:m.label}),T(B,{dimColor:!0,children:m.desc})]},m.label)})]}),T(he,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(n.type==="precheck-error"){let{targetDir:C,reason:m}=n;return A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),T(B,{color:"red",bold:!0,children:"Cannot create plugin"}),A(M,{flexDirection:"column",gap:0,children:[A(B,{children:[C," already contains ",T(B,{bold:!0,children:m==="has-manifest"?"kizen.json":".kizenapp/"}),"."]}),T(B,{dimColor:!0,children:"Remove the conflicting file/directory or choose a different target to avoid overwriting an existing plugin."})]}),T(he,{text:"Enter or Esc to exit"})]})}if(n.type==="field-entry"){let{field:C,fieldError:m}=n,u=c==="sub-dir"?`Target: sub-directory of ${e} (inferred from API name)`:`Target: ${g}`;return A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),A(M,{flexDirection:"column",gap:0,children:[T(B,{bold:!0,children:"Plugin details"}),T(B,{dimColor:!0,children:u})]}),m!==void 0&&A(B,{color:"red",children:["Error: ",m]}),T(M,{flexDirection:"column",gap:0,children:de.map((w,s)=>{let o=C===s,l=o?b:y[w],d=Mt.includes(w),p=`${zt[w]}${d?"":" (optional)"}`;return A(M,{gap:2,children:[T(M,{width:24,children:T(B,{bold:o,...o&&{color:"cyan"},children:p})}),T(B,{...o&&{color:"cyan"},children:">"}),T(B,{children:l}),o&&T(B,{color:"cyan",children:"\u2588"})]},w)})}),T(he,{text:"Enter/Tab/\u2193 next \xB7 \u2191 previous \xB7 Backspace delete \xB7 Esc cancel"})]})}if(n.type==="confirm"){let C=ut({targetDir:g,name:n.values.name,apiName:n.values.apiName,externalLink:n.values.externalLink,description:n.values.description,developerBusinessId:n.values.developerBusinessId});return A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),A(M,{flexDirection:"column",gap:0,children:[T(B,{bold:!0,children:"Ready to create"}),A(B,{dimColor:!0,children:["Target: ",g]})]}),A(M,{flexDirection:"column",gap:0,children:[T(B,{bold:!0,children:"kizen.json preview"}),T(B,{children:JSON.stringify(C,null,2)})]}),A(M,{flexDirection:"column",gap:0,children:[T(B,{dimColor:!0,children:"Also creates:"}),A(B,{dimColor:!0,children:[" ",pt(g,"src/")]}),A(B,{dimColor:!0,children:[" ",pt(g,"releaseNotes/")]}),A(B,{dimColor:!0,children:[" ",pt(g,".gitignore")," (adds .kizenapp/)"]})]}),T(he,{text:"Enter to create \xB7 Esc to go back"})]})}return n.type==="resolving-target"?T(M,{paddingY:1,paddingX:2,children:T(B,{dimColor:!0,children:"Finding available sub-directory\u2026"})}):n.type==="writing"?T(M,{paddingY:1,paddingX:2,children:T(B,{dimColor:!0,children:"Creating plugin\u2026"})}):n.type==="done"?A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),A(B,{color:"green",bold:!0,children:["Plugin created at ",n.targetDir]}),A(M,{flexDirection:"column",gap:0,children:[T(B,{dimColor:!0,children:"Next steps:"}),A(B,{children:[" ","cd ",n.targetDir]}),A(B,{children:[" ","appbuilder dev"]})]}),T(he,{text:"Enter or Esc to exit"})]}):A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),T(B,{color:"red",bold:!0,children:"Failed to create plugin"}),T(B,{children:n.message}),T(he,{text:"Enter or Esc to exit"})]})};import{mkdir as Ut,readFile as cn,readdir as dn,writeFile as qt}from"fs/promises";import{homedir as un}from"os";import{dirname as pn,join as Ve}from"path";var G=["go","fmo","staging","integration","test1"];var _e=Ve(un(),".kizenappbuilder"),xe=Ve(_e,"credentials.json"),re="credentials";function fn(e){return G.includes(e)}function mn(e){if(typeof e!="object"||e===null)throw new Error("Credentials must be a JSON object");let t=e,i=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:fn(i)?i:"go"}}async function Je(e){let t=await cn(e,"utf-8");return mn(JSON.parse(t))}async function Z(){try{return await Je(xe)}catch{return null}}async function gn(e){await Ut(pn(xe),{recursive:!0,mode:448}),await qt(xe,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function Vt(e){return Ve(_e,`${e}.json`)}async function Ee(){let e=[{name:re,path:xe,isDefault:!0}];try{let t=await dn(_e);for(let i of t){if(!i.endsWith(".json"))continue;let n=i.slice(0,-5);n!==re&&e.push({name:n,path:Ve(_e,i),isDefault:!1})}}catch{}return e}async function Jt(e,t){if(e===re){await gn(t);return}await Ut(_e,{recursive:!0,mode:448}),await qt(Vt(e),JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}async function be(e){try{return await Je(Vt(e))}catch{return null}}function Wt(e){e.command("create").description("Scaffold a new Kizen plugin project").action(async()=>{let t=process.cwd(),n=(await Z())?.businessId??"",{waitUntilExit:r}=hn(yn(Ht,{parentDir:t,defaultBusinessId:n}),{exitOnCtrlC:!1});await r()})}import{createElement as yr}from"react";import{render as hr}from"ink";import{useCallback as ve,useEffect as et,useRef as Q,useState as W}from"react";import{Box as U,Text as R,useInput as co}from"ink";import{watch as uo}from"fs";import{createServer as po}from"http";import{join as fr}from"path";import{WebSocketServer as fo}from"ws";import{createReadStream as rr,realpathSync as Nn}from"fs";import{access as Ln,readdir as jn,readFile as Fn,realpath as An,stat as nr}from"fs/promises";import{dirname as On,extname as or,join as De,resolve as $n,sep as vt}from"path";import{fileURLToPath as zn}from"url";var xn=new Set(["set-cookie","strict-transport-security","content-security-policy","content-security-policy-report-only","x-frame-options","content-encoding","content-length"]);function ft(e){let t={};for(let[i,n]of Object.entries(e)){let r=i.toLowerCase();xn.has(r)||r.startsWith("access-control-")||(t[i]=n)}return t}var mt=10*1024*1024,bn=6e4,vn=200,ke=class extends Error{bytesRead;limit;constructor(t,i){super(`Upstream response exceeded ${String(i)} bytes (read ${String(t)}).`),this.name="ProxyResponseTooLargeError",this.bytesRead=t,this.limit=i}};async function gt(e,t){let i=e.body;if(i===null)return Buffer.alloc(0);let n=[],r=0;for await(let c of i){if(r+=c.length,r>t)throw new ke(r,t);n.push(c)}return Buffer.concat(n)}function Kt(e={}){let t=new Map,{onChange:i}=e,n=()=>{i?.(t.size)},r=c=>{t.delete(c)&&n()};return{get(c,S){let y=t.get(c);if(y!==void 0){if(Date.now()-y.insertedAt<bn)return y.promise.then(b=>({response:b,fromCache:!0}));r(c)}if(t.size>=vn){let b=t.keys().next().value;b!==void 0&&r(b)}let _=S().then(async b=>{let h=ft(Object.fromEntries(b.headers)),g=await gt(b,mt);return{status:b.status,headers:h,body:g}}).catch(b=>{throw r(c),b});return t.set(c,{insertedAt:Date.now(),promise:_}),n(),_.then(b=>((b.status<200||b.status>=300)&&r(c),{response:b,fromCache:!1}))},clear(){t.clear(),n()}}}var yt={".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 Cn,readFile as wn,writeFile as Sn}from"fs/promises";import{join as Gt}from"path";async function Ie(e){try{let t=await wn(Gt(e,"config.json"),"utf-8");return JSON.parse(t)}catch{return{}}}async function ue(e,t){await Cn(e,{recursive:!0}),await Sn(Gt(e,"config.json"),JSON.stringify(t,null,2),"utf-8")}import{spawn as Zt}from"child_process";import{writeFile as Xt,rm as Qt,mkdtemp as Pn,access as Tn}from"fs/promises";import{join as Be}from"path";import{tmpdir as _n}from"os";var En=`
|
|
9
9
|
import sys, json, os, traceback
|
|
10
10
|
|
|
11
11
|
# --- Inputs proxy (attribute access) ---
|
|
@@ -165,10 +165,10 @@ 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(),
|
|
168
|
+
`.trim(),kn=3e4,ht=Be(process.cwd(),".kizenapp","venv"),In=["awslambdaric","bcrypt","fpdf2","lxml","msgpack","numpy","paramiko","pyjwt","pypdf","pytz","requests","tzdata"],We=null;function Bn(e){let t=/^python-(\d+\.\d+)$/.exec(e);return t?.[1]?`python${t[1]}`:"python3"}function Yt(e,t,i){return new Promise((n,r)=>{let c=Zt(e,t,{stdio:["ignore","pipe","pipe"]}),S=(_,b)=>{let h=[],g="";return _.on("data",f=>{g+=f.toString("utf-8");let a=g.indexOf(`
|
|
169
169
|
`);for(;a>=0;){let v=g.slice(0,a).replace(/\r$/,"");g=g.slice(a+1),h.push(v),i?.(v,b),a=g.indexOf(`
|
|
170
170
|
`)}}),_.on("end",()=>{if(g.length>0){let f=g.replace(/\r$/,"");h.push(f),i?.(f,b)}}),h},y=S(c.stderr,"stderr");S(c.stdout,"stdout"),c.on("error",r),c.on("close",_=>{if(_===0)n();else{let b=y.slice(-10).join(`
|
|
171
|
-
`).trim(),h=b.length>0?`: ${b}`:"";r(new Error(`${e} exited with code ${String(_)}${h}`))}})})}var xt=new Set;function Ke(e){for(let t of xt)t(e)}function Bn(e,t){return t&&xt.add(t),We||(We=(async()=>{let i=Be(ht,"bin","python");try{await Pn(i)}catch{let n=In(e);await Xt(n,["-m","venv",ht])}Ke({kind:"start"});try{await Xt(i,["-m","pip","install","--disable-pip-version-check",...kn],(n,r)=>{Ke({kind:"log",line:n,stream:r})}),Ke({kind:"complete"})}catch(n){let r=n instanceof Error?n.message:String(n);throw Ke({kind:"error",message:r}),We=null,await Zt(ht,{recursive:!0,force:!0}).catch(()=>{}),n}finally{xt.clear()}return i})()),We}function Dn(e){let t="__KIZEN_RESULT_START__",i="__KIZEN_RESULT_END__",n=e.indexOf(t),r=e.indexOf(i);if(n===-1||r===-1)return{userStdout:e,result:null};let c=e.slice(0,n).trimEnd(),S=e.slice(n+t.length,r).trim();try{let y=JSON.parse(S);return{userStdout:c,result:y}}catch{return{userStdout:e,result:null}}}async function Qt(e){let t=e.timeout??En,i=await Bn(e.scriptRuntime,e.onInstallProgress),n=Date.now(),r;try{r=await Sn(Be(Tn(),"kizen-step-"));let c=Be(r,"wrapper.py"),S=Be(r,"script.py");await Promise.all([Gt(c,_n,"utf-8"),Gt(S,e.script,"utf-8")]);let y={...process.env,__KIZEN_INPUTS__:JSON.stringify(e.inputs),__KIZEN_SECRETS__:JSON.stringify(e.secrets),__KIZEN_SCRIPT_PATH__:S},{exitCode:_,stdout:b,stderr:h}=await new Promise(N=>{let E=[],C=[],m=!1,u=Yt(i,[c],{env:y,cwd:r,stdio:["ignore","pipe","pipe"]}),w=setTimeout(()=>{u.kill("SIGKILL")},t);u.stdout.on("data",o=>{E.push(o)}),u.stderr.on("data",o=>{C.push(o)});let s=o=>{m||(m=!0,clearTimeout(w),N({exitCode:o??1,stdout:Buffer.concat(E).toString("utf-8"),stderr:Buffer.concat(C).toString("utf-8")}))};u.on("close",s),u.on("error",o=>{m||(m=!0,clearTimeout(w),N({exitCode:1,stdout:"",stderr:o.message}))})}),g=Date.now()-n,{userStdout:f,result:a}=Dn(b);if(a){let N={success:a.success,outputValues:a.outputValues,logs:a.logs,stdout:f,stderr:h,exitCode:_,durationMs:g};return a.error!==null&&(N.error=a.error),a.httpRequests&&(N.httpRequests=a.httpRequests),N}let v={success:!1,outputValues:{},logs:[],stdout:f,stderr:h,exitCode:_,durationMs:g};return _!==0&&(v.error=`Process exited with code ${String(_)}`),v}finally{r&&Zt(r,{recursive:!0,force:!0})}}var zn=2*1024*1024,Mn=new Set([".DS_Store",".gitignore"]),Hn=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 qn(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 Un=["kizen.com","kizen.dev"];function Vn(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let i=t.hostname.toLowerCase();return Un.some(n=>i===n||i.endsWith("."+n))}function Jn(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 nr(e,t){if(t.includes("\0"))return null;let i=t.replace(/^\/+/,""),n=On(e,i);if(n!==e&&!n.startsWith(e+bt))return null;try{let r=await jn(n);return r!==e&&!r.startsWith(e+bt)?null:r}catch{return null}}function or(e,t){let i=t===e?"":t.slice(e.length+1);return i===""?!1:i.split(bt).some(r=>$e.has(r))}function ir(e){if(e.kind==="info")return e.message;let t=e.fromCache?" [cache]":"";return`${e.method} ${e.url} \u2192 ${String(e.status)}${t}`}function sr(){let e=$n(import.meta.url);return De(An(e),"viewer")}async function vt(e){try{return await Nn(e),!0}catch{return!1}}function ar(e,t,i,n,r,c,S,y,_,b){let h=Wt({onChange:y}),g=Rn(b);return(f,a)=>{(async()=>{let v=f.url??"/";try{if(!qn(f.headers.host)){a.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"Forbidden"}));return}if((f.method==="POST"||f.method==="PATCH"||f.method==="DELETE")&&!Jn(f.headers.origin)){a.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"Forbidden"}));return}if(t(`Received request: ${v}`),v==="/api/credentials"){a.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),a.end(n.current!==null?JSON.stringify(n.current):"{}");return}if(v==="/api/credential-profiles"&&f.method==="GET"){let s=await Ee();a.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({profiles:s,active:r.current}));return}if(v==="/api/credentials/switch"&&f.method==="POST"){let s=[];for await(let p of f)s.push(p);let l=JSON.parse(Buffer.concat(s).toString("utf-8")||"{}").profile,d=l===void 0||l===""?await Y():await be(l);if(d!==null){n.current=d,r.current=l??void 0;let p=r.current;await ue(c,{credentialMode:"global",...p!==void 0&&{activeCredentialProfile:p}}),S({type:"credentials-updated",credentials:d})}a.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({ok:d!==null}));return}if(v==="/api/bundle"){let s=De(process.cwd(),".kizenapp","bundle.json");try{let o=await Fn(s,"utf-8");a.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),a.end(o)}catch{a.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),a.end("{}")}return}if(v==="/api/last-path"&&f.method==="POST"){let s=[];for await(let l of f)s.push(l);let o=JSON.parse(Buffer.concat(s).toString("utf-8")||"{}");if(typeof o.path=="string"){_.current=o.path;let l=await Ie(c);await ue(c,{...l,lastPath:o.path})}a.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),a.end('{"ok":true}');return}if(v==="/api/execute-step"&&f.method==="POST"){let s=[];for await(let p of f)s.push(p);let o=JSON.parse(Buffer.concat(s).toString("utf-8")||"{}");if(typeof o.script!="string"){a.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"Missing required field: script"}));return}let l={script:o.script,scriptRuntime:o.scriptRuntime??"python-3.9",inputs:o.inputs??{},secrets:o.secrets??{},onInstallProgress:p=>{p.kind==="start"?S({type:"venv-install-start"}):p.kind==="log"?S({type:"venv-install-log",line:p.line,stream:p.stream}):p.kind==="complete"?S({type:"venv-install-complete"}):S({type:"venv-install-error",message:p.message})}};typeof o.timeout=="number"&&o.timeout>0&&(l.timeout=Math.min(o.timeout,300*1e3));let d=await Qt(l);a.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify(d));return}if(v==="/api/proxy-cache/clear"){h.clear(),i({kind:"info",message:"Proxy cache cleared"}),a.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),a.end('{"ok":true}');return}if(v.startsWith("/api/proxy")){let s=f.headers["x-proxy-target"];if(typeof s!="string"){a.writeHead(400),a.end("Missing x-proxy-target header");return}if(!Vn(s)){a.writeHead(400),a.end("Invalid proxy target");return}let o=v.slice(10)||"/",l=`${s}${o}`,d=f.method??"GET",p=[];for await(let pe of f)p.push(pe);let{host:F,"x-proxy-target":k,...I}=f.headers;if(d==="GET"){let pe=`GET::${l}`,{response:fe,fromCache:Ce}=await h.get(pe,()=>fetch(l,{method:"GET",headers:I}));i({kind:"request",method:"GET",status:fe.status,fromCache:Ce,url:o}),a.writeHead(fe.status,fe.headers),a.end(fe.body);return}let O=p.length>0?Buffer.concat(p):void 0,U=O&&O.length>0?O:void 0,J=await fetch(l,{method:d,headers:I,...U!==void 0&&{body:U}}),G=ft(Object.fromEntries(J.headers)),tt=await gt(J,mt);i({kind:"request",method:d,status:J.status,fromCache:!1,url:o}),a.writeHead(J.status,G),a.end(tt);return}if(v.startsWith("/api/source/tree")&&f.method==="GET"){let o=new URL(v,"http://localhost").searchParams.get("path")??"",l=await nr(g,o);if(l===null){a.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"Invalid path"}));return}if(or(g,l)){a.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"Path is excluded"}));return}try{let d=await Ln(l,{withFileTypes:!0}),p=await Promise.all(d.filter(k=>k.isDirectory()?!$e.has(k.name):k.isFile()?!Mn.has(k.name):!1).map(async k=>{let I=k.isDirectory()?"dir":"file",O={name:k.name,kind:I};if(I==="file")try{let U=await tr(De(l,k.name));O.size=U.size}catch{}return O}));p.sort((k,I)=>k.kind!==I.kind?k.kind==="dir"?-1:1:k.name.localeCompare(I.name));let F=l===g?"":l.slice(g.length+1);a.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({path:F,entries:p}))}catch(d){let p=d instanceof Error?d.message:String(d);t(`source/tree failed (${o}): ${p}`),a.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"Not found"}))}return}if(v.startsWith("/api/source/file")&&f.method==="GET"){let o=new URL(v,"http://localhost").searchParams.get("path")??"";if(o===""){a.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"Missing path"}));return}let l=await nr(g,o);if(l===null){a.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"Invalid path"}));return}if(or(g,l)){a.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"Path is excluded"}));return}try{let d=await tr(l);if(!d.isFile()){a.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"Not a file"}));return}if(d.size>zn){a.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"File too large",size:d.size}));return}let p=rr(l).toLowerCase(),F=yt[p],k=Hn.has(p),I=F??(k?"text/plain; charset=utf-8":"application/octet-stream");a.writeHead(200,{"Content-Type":I,"Content-Length":String(d.size)}),er(l).pipe(a)}catch(d){let p=d instanceof Error?d.message:String(d);t(`source/file failed (${o}): ${p}`),a.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"Not found"}))}return}let C=De(e,v==="/"?"/index.html":v),m=await vt(C)?C:De(e,"index.html"),u=rr(m),w=yt[u]??"application/octet-stream";a.writeHead(200,{"Content-Type":w}),er(m).pipe(a)}catch(N){if(v.startsWith("/api/proxy")){let E=v.slice(10)||"/",C=f.method??"GET";N instanceof ke?i({kind:"info",message:`${C} ${E} \u2192 502 (response exceeded ${String(N.limit)} bytes)`}):i({kind:"request",method:C,status:502,fromCache:!1,url:E})}else i({kind:"info",message:`Error handling ${v}: ${N instanceof Error?N.message:String(N)}`});a.headersSent||(a.writeHead(502),a.end("Bad Gateway"))}})()}}import{launch as Wn}from"chrome-launcher";import{createRequire as Kn}from"module";import{mkdirSync as Gn}from"fs";import{readFile as Xn}from"fs/promises";import{dirname as Yn,join as Zn}from"path";import{fileURLToPath as Qn}from"url";var lr=Kn(import.meta.url)("chrome-remote-interface"),eo=new Set(["content-security-policy","content-security-policy-report-only","x-frame-options"]),dr=["kizen.dev","kizen.com"];function cr(e){try{let{hostname:t}=new URL(e);return dr.some(i=>t===i||t.endsWith("."+i))}catch{return!1}}function Ge(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(n=>/^\d+$/.test(n.name)).sort((n,r)=>parseInt(n.name)-parseInt(r.name)).map(Ge);let i={};for(let n of t.properties)i[n.name]=Ge(n);return i}return e.value??`[${e.type}]`}}function to(e){if(e.value!==void 0)return e.value;if(e.preview){let{preview:t}=e;if(t.subtype==="array")return t.properties.filter(n=>/^\d+$/.test(n.name)).sort((n,r)=>parseInt(n.name)-parseInt(r.name)).map(Ge);let i={};for(let n of t.properties)i[n.name]=Ge(n);return i}return e.description??`[${e.type}]`}async function ro(e,t){if(t.type==="object"&&t.objectId)try{let n=(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 n=="string")return JSON.parse(n)}catch{}return to(t)}async function no(e){try{let t=Zn(Yn(Qn(import.meta.url)),"viewer","icon.png"),i=await Xn(t);await e.Browser.setDockTile({image:i.toString("base64")})}catch{}}async function ur(e){Gn(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,i=await Wn({startingUrl:t,chromeFlags:[`--app=${t}`,"--no-first-run","--no-default-browser-check","--disable-extensions"],userDataDir:e.userDataDir,handleSIGINT:!1,logLevel:"silent"}),n=i.port,r=null,c=null,S=null,y=null,_=0,b=!1,h=u=>{e.debugLog?.(u)},g=u=>{e.verbose&&e.debugLog?.(u)},f=()=>{c!==null&&(clearInterval(c),c=null)},a=u=>u==="chrome://new-tab-page/"||u==="chrome://newtab/",v=async u=>{f(),S=null,await no(u),await u.Fetch.enable({patterns:dr.flatMap(s=>[{urlPattern:`*://${s}/*`,requestStage:"Response"},{urlPattern:`*://*.${s}/*`,requestStage:"Response"}])}),u.on("Fetch.requestPaused",s=>{(async()=>{let o=s,{requestId:l,request:d,responseHeaders:p,responseStatusCode:F}=o,k=d.url;g(`Fetch ${String(F??"?")} ${k}`);let I=[],O=!1;for(let U of p??[])if(!eo.has(U.name.toLowerCase()))if(U.name.toLowerCase()==="set-cookie"&&cr(k)){let J=U.value.split(`
|
|
172
|
-
`).map(
|
|
173
|
-
`);I.push({name:U.name,value:J}),O=!0}else I.push(U);O&&g(` rewrote Set-Cookie SameSite on ${k}`);try{let{body:U,base64Encoded:J}=await u.Fetch.getResponseBody({requestId:l});await u.Fetch.fulfillRequest({requestId:l,responseCode:F??200,responseHeaders:I,body:U,...J&&{base64Encoded:!0}})}catch(U){g(` fulfillRequest failed (${U.message}), falling through`);try{await u.Fetch.continueRequest({requestId:l})}catch(J){g(` continueRequest also failed (${J.message})`)}}})()}),c=setInterval(()=>{(async()=>{try{let{cookies:s}=await u.Network.getAllCookies(),o=0;for(let l of s){if(!cr(`https://${l.domain??""}`)||l.sameSite==="None")continue;let d=l.domain??"",p=d.startsWith(".")?d.slice(1):d;await u.Network.setCookie({url:`https://${p}`,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"}),o++}o>0&&g(`cookie-patch cycle: updated ${String(o)} cookie(s) to SameSite=None`)}catch(s){g(`cookie-patch cycle failed: ${s.message}`)}})()},2e3),await u.send("Runtime.enable",{generatePreview:!0}),u.on("Target.attachedToTarget",s=>{let o=s,{sessionId:l,targetInfo:d}=o;g(`attached session ${l} (${d.type} ${d.url})`),u.send("Runtime.enable",{generatePreview:!0},l).catch(p=>{g(` Runtime.enable on session ${l} failed: ${p.message}`)})}),await u.Target.setAutoAttach({autoAttach:!0,waitForDebuggerOnStart:!1,flatten:!0}),await u.Target.setDiscoverTargets({discover:!0});let w=s=>{if(s.type==="page"){if(a(s.url)){h(`closed stray new-tab-page target ${s.targetId}`),S!==null&&u.Target.activateTarget({targetId:S}).catch(()=>{}),u.Target.closeTarget({targetId:s.targetId}).catch(()=>{});return}S===null&&(S=s.targetId,h(`captured main target ${s.targetId} (${s.url})`))}};u.on("Target.targetCreated",s=>{let{targetInfo:o}=s;g(`target +${o.type} ${o.targetId} ${o.url}`),w(o)}),u.on("Target.targetInfoChanged",s=>{let{targetInfo:o}=s;g(`target ~${o.type} ${o.targetId} ${o.url}`),w(o)}),u.on("Runtime.consoleAPICalled",s=>{(async()=>{let{type:o,args:l}=s;if(l[0]?.type==="string"&&String(l[0].value).includes("Chrome Security"))return;let d=o==="warning"?"warn":["log","warn","error","info"].includes(o)?o:"log";g(`console.${d} (${String(l.length)} arg(s))`);let p=await Promise.all(l.map(F=>ro(u,F)));e.broadcast({type:"console-message",level:d,args:p})})().catch(o=>{g(`console serialization failed: ${o.message}`)})}),u.on("disconnect",()=>{b||r!==u||(h("CDP disconnected"),r=null,f(),N())})},N=()=>{if(b||y!==null)return;let u=Math.min(1e3*2**_,1e4),w=_+1;_++,h(`CDP reconnect scheduled in ${String(u)}ms (attempt #${String(w)})`),y=setTimeout(()=>{y=null,(async()=>{let s;try{s=await lr({port:n})}catch{h(`CDP reconnect attempt #${String(w)} failed`),N();return}if(b){try{await s.close()}catch{}return}r=s;try{await v(s),h(`CDP reconnected after ${String(w)} attempt(s)`),_=0}catch{r===s&&(r=null);try{await s.close()}catch{}h(`CDP reconnect attempt #${String(w)} failed during setup`),N()}})()},u)},E=30,C=300;for(let u=0;u<E;u++){await new Promise(w=>setTimeout(w,C)),h(`CDP connect attempt ${String(u+1)}/${String(E)}`);try{let w=await lr({port:n});r=w,e.path&&w.send("Page.navigate",{url:`${t}${e.path}`});try{await v(w),h("CDP connected")}catch{r===w&&(r=null);try{await w.close()}catch{}h("CDP setup failed after connect")}break}catch{if(u===E-1){let w=`CDP unavailable after ${String(E)} attempts \u2014 viewer running without interception (CSP/cookie rewrites disabled)`;return h(w),e.onWarn?.(w),{kill:()=>{i.kill()}}}}}return r?{kill:()=>{if(h("CDP kill requested \u2014 tearing down"),b=!0,y!==null&&(clearTimeout(y),y=null),f(),r!==null){try{r.close()}catch{}r=null}i.kill()}}:{kill:()=>{i.kill()}}}import{useCallback as oo,useState as io}from"react";function Xe(e){let[t,i]=io([]),n=oo(r=>{i(c=>[...c,`${new Date().toLocaleTimeString()}: ${r}`].slice(-e))},[e]);return[t,n]}import{useCallback as Ye,useEffect as Ct,useState as Ze}from"react";import{Box as z,Text as D,useInput as so}from"ink";import{jsx as P,jsxs as H}from"react/jsx-runtime";var ne=["apiKey","userId","businessId"],ao={apiKey:"API Key",userId:"User ID",businessId:"Business ID"},Re=({text:e})=>P(D,{dimColor:!0,children:e}),Qe=({initialMode:e,showProfileManager:t,onComplete:i,onCancel:n})=>{let[r,c]=Ze(e==="global"&&!t?{type:"loading"}:e==="global"&&t?{type:"profile-loading"}:{type:"mode-select",cursor:0}),[S,y]=Ze(""),[_,b]=Ze(null),[h,g]=Ze(void 0),f=Ye(s=>{if(s==="local"){i({mode:"local",credentials:null});return}c({type:"profile-loading"})},[i]),a=Ye(async s=>{if(s===null){c({type:"profile-loading"});let d=await Ee();c({type:"name-entry",nameBuffer:"",existingProfiles:d});return}g(s.isDefault?void 0:s.name),c({type:"loading"});let o=s.isDefault?await Y():await be(s.name),l=o?Math.max(0,Z.indexOf(o.environment)):0;c({type:"creds-entry",field:0,values:o??{},envCursor:l})},[]),v=Ye(async(s,o)=>{let l=Z[o]??"go",d={apiKey:s.apiKey??"",userId:s.userId??"",businessId:s.businessId??"",environment:l};c({type:"saving"});try{await Vt(h??re,d),i({mode:"global",credentials:d,...h!==void 0&&{profileName:h}})}catch(p){b(p instanceof Error?p.message:String(p)),c({type:"creds-entry",field:0,values:s,envCursor:o})}},[i,h]);so((s,o)=>{if(o.ctrl&&s==="c"&&process.exit(0),o.escape){if((r.type==="creds-entry"||r.type==="name-entry")&&e==="global"&&t){c({type:"profile-loading"}),N();return}n?.();return}if(r.type==="mode-select"){if(o.upArrow)c({type:"mode-select",cursor:0});else if(o.downArrow)c({type:"mode-select",cursor:1});else if(o.return){let l=r.cursor===0?"global":"local";f(l)}return}if(r.type==="profile-select"){let{profiles:l,cursor:d}=r,p=l.length,F=l.length+1;if(o.upArrow)c({...r,cursor:(d-1+F)%F});else if(o.downArrow)c({...r,cursor:(d+1)%F});else if(o.return)if(d===p)c({type:"name-entry",nameBuffer:"",existingProfiles:l});else{let k=l[d]??l[0];k&&a(k)}return}if(r.type==="name-entry"){let{nameBuffer:l,existingProfiles:d}=r;if(o.backspace||o.delete)c({type:"name-entry",nameBuffer:l.slice(0,-1),existingProfiles:d});else if(o.return){let p=l.trim();if(!p){c({...r,nameError:"Name cannot be empty"});return}if(p===re){c({...r,nameError:`"${re}" is reserved`});return}if(d.some(F=>F.name===p)){c({...r,nameError:`Profile "${p}" already exists`});return}g(p),c({type:"creds-entry",field:0,values:{},envCursor:0}),y("")}else s&&!o.ctrl&&!o.meta&&c({type:"name-entry",nameBuffer:l+s,existingProfiles:d});return}if(r.type==="creds-entry"){let{field:l,values:d,envCursor:p}=r;if(l===ne.length){o.leftArrow?c({...r,envCursor:(p-1+Z.length)%Z.length}):o.rightArrow?c({...r,envCursor:(p+1)%Z.length}):o.upArrow?(c({...r,field:l-1}),y(d[ne[l-1]]??"")):o.return&&v(d,p);return}let k=ne[l];if(!k)return;if(o.backspace||o.delete)y(I=>I.slice(0,-1));else if(o.upArrow&&l>0){let I={...d,[k]:S},O=l-1;c({...r,field:O,values:I}),y(I[ne[O]]??"")}else if(o.return||o.tab||o.downArrow){let I={...d,[k]:S},O=l+1;c({...r,field:O,values:I}),O<ne.length?y(I[ne[O]]??""):y("")}else s&&!o.ctrl&&!o.meta&&y(I=>I+s)}});let N=Ye(async()=>{let s=await Ee();c({type:"profile-select",profiles:s,cursor:0})},[]);if(Ct(()=>{r.type==="profile-loading"&&N()},[r.type,N]),Ct(()=>{e==="global"&&!t&&(async()=>{let s=await Y(),o=s?Math.max(0,Z.indexOf(s.environment)):0;c({type:"creds-entry",field:0,values:s??{},envCursor:o})})()},[]),Ct(()=>{r.type==="creds-entry"&&r.field===0&&y(r.values.apiKey??"")},[r.type]),r.type==="loading"||r.type==="saving"||r.type==="profile-loading"){let s=r.type==="saving"?"Saving credentials\u2026":r.type==="profile-loading"?"Loading profiles\u2026":"Loading credentials\u2026";return P(z,{paddingY:1,paddingX:2,children:P(D,{dimColor:!0,children:s})})}if(r.type==="done")return null;if(r.type==="mode-select")return H(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),H(z,{flexDirection:"column",gap:0,children:[P(D,{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((o,l)=>{let d=r.cursor===l;return H(z,{gap:2,children:[P(D,{...d&&{color:"cyan"},children:d?"\u276F":" "}),P(D,{bold:d,...d&&{color:"cyan"},children:o.label}),P(D,{dimColor:!0,children:o.desc})]},o.mode)})]}),P(Re,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]});if(r.type==="profile-select"){let{profiles:s,cursor:o}=r,l=s.length;return H(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),H(z,{flexDirection:"column",gap:0,children:[P(D,{bold:!0,children:"Credential profiles"}),s.map((d,p)=>{let F=o===p;return H(z,{gap:2,children:[P(D,{...F&&{color:"cyan"},children:F?"\u276F":" "}),P(D,{bold:F,...F&&{color:"cyan"},children:d.isDefault?"Default":d.name}),P(D,{dimColor:!0,children:d.path})]},d.name)}),H(z,{gap:2,children:[P(D,{...o===l&&{color:"cyan"},children:o===l?"\u276F":" "}),P(D,{bold:o===l,...o===l&&{color:"cyan"},children:"+ Add new profile"})]})]}),P(Re,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(r.type==="name-entry"){let{nameBuffer:s,nameError:o}=r;return H(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),P(z,{flexDirection:"column",gap:0,children:P(D,{bold:!0,children:"New credential profile"})}),o&&H(D,{color:"red",children:["Error: ",o]}),H(z,{gap:2,children:[P(z,{width:12,children:P(D,{bold:!0,color:"cyan",children:"Profile name"})}),P(D,{color:"cyan",children:">"}),P(D,{children:s}),P(D,{color:"cyan",children:"\u2588"})]}),P(Re,{text:"Type a name \xB7 Enter to confirm \xB7 Esc to go back"})]})}let{field:E,values:C,envCursor:m}=r,u=E===ne.length,w=h??re;return H(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),H(z,{flexDirection:"column",gap:0,children:[P(D,{bold:!0,children:h!==void 0?`Profile: ${h}`:"Global credentials"}),H(D,{dimColor:!0,children:["Saved to:"," ",h!==void 0?`~/.kizenappbuilder/${h}.json`:xe]})]}),_&&H(D,{color:"red",children:["Error: ",_]}),H(z,{flexDirection:"column",gap:0,children:[ne.map((s,o)=>{let l=E===o,d=l?S:C[s]??"";return H(z,{gap:2,children:[P(z,{width:12,children:P(D,{bold:l,...l&&{color:"cyan"},children:ao[s]})}),P(D,{...l&&{color:"cyan"},children:">"}),P(D,{children:d}),l&&P(D,{color:"cyan",children:"\u2588"})]},s)}),H(z,{gap:2,children:[P(z,{width:12,children:P(D,{bold:u,...u&&{color:"cyan"},children:"Environment"})}),P(D,{...u&&{color:"cyan"},children:">"}),P(z,{gap:1,children:Z.map((s,o)=>{let l=o===m;return u?P(D,{bold:l,...l&&{color:"cyan"},children:l?`[${s}]`:s},s):P(D,{dimColor:!l,bold:l,children:s},s)})})]})]}),u?P(Re,{text:"\u2190\u2192 to select \xB7 \u2191\u2193 to move \xB7 Enter to save \xB7 Esc to cancel"}):P(Re,{text:"\u2191\u2193 to move \xB7 Backspace to delete \xB7 Esc to cancel"}),H(D,{dimColor:!0,children:["Profile: ",w]})]})};import{jsx as L,jsxs as $}from"react/jsx-runtime";var mo=[".kizenapp",".git"],fr=({port:e,pluginDir:t,outputDir:i,credentials:n,credentialMode:r,activeCredentialProfile:c,lastPath:S,debug:y=!1,verbose:_=!1})=>{let b=Q(n),h=Q(c),g=Q(S),[f,a]=W("main"),[v,N]=W(r),[E,C]=W("starting"),[m,u]=W(null),[w,s]=Xe(50),[o,l]=Xe(50),[d,p]=Xe(50),[F,k]=W([]),[I,O]=W("pending"),[U,J]=W(null),[G,tt]=W(null),[pe,fe]=W(null),[Ce,rt]=W(0),[wt,xr]=W(0),[br,vr]=W(0),[Cr,wr]=W(0),nt=Q(!1),St=Q(!1),Fe=Q(null),we=Q(null),ee=Q(new Set),je=Q([]),K=ve(x=>{let j=JSON.stringify(x);if(ee.current.size===0){je.current=[...je.current,j].slice(-50);return}let te=!1;for(let X of ee.current)if(X.readyState===1)try{X.send(j)}catch{ee.current.delete(X),te=!0}te&&rt(ee.current.size)},[]),Ae=s,ot=ve(()=>{Fe.current?.kill(),Fe.current=null,ur({port:e,userDataDir:pr(i,".chrome"),broadcast:K,onWarn:x=>{s(`\u26A0 ${x}`)},...g.current!==void 0&&{path:g.current},...y&&{debugLog:p},..._&&{verbose:!0}}).then(x=>{Fe.current=x})},[e,i,K,y,_,p,s]);et(()=>{let x=()=>{Fe.current?.kill()};return process.on("exit",x),()=>{process.off("exit",x)}},[]),co((x,j)=>{(x==="q"||j.ctrl&&x==="c")&&process.exit(0),x==="c"&&a("editing"),x==="v"&&ot()},{isActive:f==="main"}),et(()=>{E!=="running"||St.current||(St.current=!0,ot())},[E,ot]);let Sr=ve(x=>{b.current=x.credentials,h.current=x.profileName,a("main"),N(x.mode);let j=x.profileName;ue(i,{credentialMode:x.mode,...j!==void 0&&{activeCredentialProfile:j}}),K({type:"credentials-updated",credentials:x.credentials})},[i,K]),Pt=ve(x=>{k(j=>[...j,`${new Date().toLocaleTimeString()}: ${ir(x)}`].slice(-50)),x.kind==="request"&&(x.fromCache?vr(j=>j+1):wr(j=>j+1)),K({type:"proxy-log",entry:x})},[K]),ie=ve(x=>{l(x),K({type:"log",message:x})},[l,K]),it=ve(()=>{nt.current||(nt.current=!0,O("building"),J(null),ie("Build started"),ze(t,i).then(({bundleSize:x})=>{ie(`Build finished \u2014 bundle: ${Se(x)}`),O("done"),tt(new Date),fe(x),ie("Notifying viewers to reload"),K({type:"rebuild"})}).catch(x=>{let j=x instanceof Error?x.message:String(x);J(j),O("error")}).finally(()=>{nt.current=!1}))},[t,i,ie,K]);if(et(()=>{it();let x=uo(t,{recursive:!0},(j,te)=>{if(!te)return;let X=te.replace(/\\/g,"/");mo.some(Oe=>X.startsWith(Oe))||(ie(`File change detected: ${te}`),we.current!==null&&clearTimeout(we.current),we.current=setTimeout(it,150))});return x.on("error",j=>{ie(`File watcher error \u2014 rebuilds have stopped: ${j.message}`)}),()=>{x.close(),we.current!==null&&clearTimeout(we.current)}},[t,it,ie]),et(()=>{let x=sr();vt(pr(x,"index.html")).then(j=>{if(!j){u("Viewer not built. Run 'pnpm build:viewer' first."),C("error");return}let te=ar(x,Ae,Pt,b,h,i,K,xr,g,t),X=po(te),Oe=new fo({server:X});return Oe.on("connection",se=>{for(let Tr of je.current)se.readyState===1&&se.send(Tr);je.current=[],Ae("Viewer connected for live reload"),ee.current.add(se),rt(ee.current.size),se.on("close",()=>{ee.current.delete(se),rt(ee.current.size)})}),X.listen(e,"127.0.0.1",()=>{C("running"),Ae(`Server started on 127.0.0.1:${String(e)}`)}),X.on("error",se=>{u(se.message),C("error")}),()=>{Oe.close(),X.close()}})},[e,Ae,Pt,K,i,t]),f==="editing")return L(Qe,{...v!==void 0&&{initialMode:v},showProfileManager:v==="global",onComplete:Sr,onCancel:()=>{a("main")}});let st=G!==null?Math.round((Date.now()-G.getTime())/1e3):null,Pr=st===null?"":st<5?" (just now)":` (${String(st)}s ago)`;return $(q,{flexDirection:"column",paddingY:1,paddingX:2,children:[L(V,{marginBottom:1}),$(q,{flexDirection:"column",children:[$(q,{gap:2,marginBottom:0,children:[L(R,{bold:!0,dimColor:!0,children:"App Build"}),I==="pending"&&L(R,{dimColor:!0,children:"waiting\u2026"}),I==="building"&&$(q,{gap:1,children:[L(Me,{}),L(R,{children:"Building plugin package\u2026"})]}),I==="done"&&$(q,{gap:1,children:[L(R,{color:"green",children:"\u2713 Built"}),G!==null&&$(R,{dimColor:!0,children:["at ",G.toLocaleTimeString(),Pr]}),pe!==null&&$(R,{dimColor:!0,children:["\xB7 bundle: ",Se(pe)]})]}),I==="error"&&$(R,{color:"red",children:["\u2717 ",U??"unknown error"]})]}),L(q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:o.slice(-8).map((x,j)=>L(R,{dimColor:!0,wrap:"truncate",children:x},j))})]}),$(q,{marginTop:1,flexDirection:"column",children:[$(q,{gap:2,children:[L(R,{bold:!0,dimColor:!0,children:"Web Server"}),E==="starting"&&L(R,{dimColor:!0,children:"starting\u2026"}),E==="running"&&$(q,{gap:2,children:[L(R,{color:"green",children:"\u2713 Running"}),$(R,{dimColor:!0,children:["\u25CF ",Ce," viewer",Ce!==1?"s":""]})]}),E==="error"&&$(R,{color:"red",children:["\u2717 ",m??"Server error"]})]}),L(q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:w.slice(-8).map((x,j)=>L(R,{dimColor:!0,wrap:"truncate",children:x},j))})]}),$(q,{marginTop:1,flexDirection:"column",children:[$(q,{gap:2,children:[L(R,{bold:!0,dimColor:!0,children:"Network Proxy"}),L(R,{color:"green",children:"\u2713 Active"}),$(R,{dimColor:!0,children:["\u25CF ",wt," key",wt!==1?"s":""," in the network cache \xB7"," ",br," hit \xB7 ",Cr," miss"]})]}),L(q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:F.length===0?L(R,{dimColor:!0,children:" No requests yet."}):F.slice(-8).map((x,j)=>L(R,{dimColor:!0,wrap:"truncate",children:x},j))})]}),y&&$(q,{marginTop:1,flexDirection:"column",children:[$(q,{gap:2,children:[L(R,{bold:!0,dimColor:!0,children:"CDP Debug"}),$(R,{dimColor:!0,children:["\u25CF ",d.length," event(s)"]})]}),L(q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:d.length===0?L(R,{dimColor:!0,children:" No CDP events yet."}):d.slice(-8).map((x,j)=>L(R,{dimColor:!0,wrap:"truncate",children:x},j))})]}),$(q,{marginTop:1,gap:1,children:[L(R,{dimColor:!0,children:"["}),L(R,{children:"q"}),L(R,{dimColor:!0,children:"] quit ["}),L(R,{children:"c"}),L(R,{dimColor:!0,children:"] credentials ["}),L(R,{children:"v"}),$(R,{dimColor:!0,children:["] ",Ce===0?"open viewer":"relaunch viewer"]})]})]})};async function mr(e){return new Promise(t=>{let i=null,n=c=>{i?.(),t(c)},{unmount:r}=yr(gr(Qe,{...e!==void 0&&{initialMode:e},onComplete:n}),{exitOnCtrlC:!1});i=r})}function hr(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)").action(async t=>{let i=parseInt(t.port,10),n=process.cwd(),r=`${n}/.kizenapp`;ye(n);let c=null,S,y,{lastPath:_}=await Ie(r);if(t.credentials)c=await Je(t.credentials);else{let f=await Ie(r);if(f.credentialMode==="local")S="local";else if(f.credentialMode==="global"){if(S="global",y=f.activeCredentialProfile,y?(c=await be(y),c||(c=await Y(),y=void 0)):c=await Y(),!c){let a=await mr("global");c=a.credentials,y=a.profileName}}else{let a=await mr();c=a.credentials,S=a.mode,y=a.profileName;let v=a.profileName;await ue(r,{credentialMode:a.mode,...v!==void 0&&{activeCredentialProfile:v}})}}let b=t.verbose===!0,h=b||t.debug===!0,{waitUntilExit:g}=yr(gr(fr,{port:i,pluginDir:n,outputDir:r,credentials:c,...S!==void 0&&{credentialMode:S},...y!==void 0&&{activeCredentialProfile:y},..._!==void 0&&{lastPath:_},debug:h,verbose:b}),{exitOnCtrlC:!1});await g()})}var bo=ho(yo(xo(import.meta.url)),"..","package.json"),vo=JSON.parse(go(bo,"utf-8"));Le.name("appbuilder").description("Kizen plugin app builder").version(vo.version);Jt(Le);Ft(Le);hr(Le);Le.parse();
|
|
171
|
+
`).trim(),h=b.length>0?`: ${b}`:"";r(new Error(`${e} exited with code ${String(_)}${h}`))}})})}var xt=new Set;function Ke(e){for(let t of xt)t(e)}function Dn(e,t){return t&&xt.add(t),We||(We=(async()=>{let i=Be(ht,"bin","python");try{await Tn(i)}catch{let n=Bn(e);await Yt(n,["-m","venv",ht])}Ke({kind:"start"});try{await Yt(i,["-m","pip","install","--disable-pip-version-check",...In],(n,r)=>{Ke({kind:"log",line:n,stream:r})}),Ke({kind:"complete"})}catch(n){let r=n instanceof Error?n.message:String(n);throw Ke({kind:"error",message:r}),We=null,await Qt(ht,{recursive:!0,force:!0}).catch(()=>{}),n}finally{xt.clear()}return i})()),We}function Rn(e){let t="__KIZEN_RESULT_START__",i="__KIZEN_RESULT_END__",n=e.indexOf(t),r=e.indexOf(i);if(n===-1||r===-1)return{userStdout:e,result:null};let c=e.slice(0,n).trimEnd(),S=e.slice(n+t.length,r).trim();try{let y=JSON.parse(S);return{userStdout:c,result:y}}catch{return{userStdout:e,result:null}}}async function er(e){let t=e.timeout??kn,i=await Dn(e.scriptRuntime,e.onInstallProgress),n=Date.now(),r;try{r=await Pn(Be(_n(),"kizen-step-"));let c=Be(r,"wrapper.py"),S=Be(r,"script.py");await Promise.all([Xt(c,En,"utf-8"),Xt(S,e.script,"utf-8")]);let y={...process.env,__KIZEN_INPUTS__:JSON.stringify(e.inputs),__KIZEN_SECRETS__:JSON.stringify(e.secrets),__KIZEN_SCRIPT_PATH__:S},{exitCode:_,stdout:b,stderr:h}=await new Promise(N=>{let E=[],C=[],m=!1,u=Zt(i,[c],{env:y,cwd:r,stdio:["ignore","pipe","pipe"]}),w=setTimeout(()=>{u.kill("SIGKILL")},t);u.stdout.on("data",o=>{E.push(o)}),u.stderr.on("data",o=>{C.push(o)});let s=o=>{m||(m=!0,clearTimeout(w),N({exitCode:o??1,stdout:Buffer.concat(E).toString("utf-8"),stderr:Buffer.concat(C).toString("utf-8")}))};u.on("close",s),u.on("error",o=>{m||(m=!0,clearTimeout(w),N({exitCode:1,stdout:"",stderr:o.message}))})}),g=Date.now()-n,{userStdout:f,result:a}=Rn(b);if(a){let N={success:a.success,outputValues:a.outputValues,logs:a.logs,stdout:f,stderr:h,exitCode:_,durationMs:g};return a.error!==null&&(N.error=a.error),a.httpRequests&&(N.httpRequests=a.httpRequests),N}let v={success:!1,outputValues:{},logs:[],stdout:f,stderr:h,exitCode:_,durationMs:g};return _!==0&&(v.error=`Process exited with code ${String(_)}`),v}finally{r&&Qt(r,{recursive:!0,force:!0})}}var tr=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 bt(e){if(e.kind==="info")return e.message;let t=e.fromCache?" [cache]":"";return`${e.method} ${e.url} \u2192 ${String(e.status)}${t}`}var Mn=2*1024*1024,Hn=new Set([".DS_Store",".gitignore"]);function Un(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 qn=["kizen.com","kizen.dev"];function Vn(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let i=t.hostname.toLowerCase();return qn.some(n=>i===n||i.endsWith("."+n))}function Jn(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 ir(e,t){if(t.includes("\0"))return null;let i=t.replace(/^\/+/,""),n=$n(e,i);if(n!==e&&!n.startsWith(e+vt))return null;try{let r=await An(n);return r!==e&&!r.startsWith(e+vt)?null:r}catch{return null}}function sr(e,t){let i=t===e?"":t.slice(e.length+1);return i===""?!1:i.split(vt).some(r=>$e.has(r))}function ar(){let e=zn(import.meta.url);return De(On(e),"viewer")}async function Ct(e){try{return await Ln(e),!0}catch{return!1}}function lr(e,t,i,n,r,c,S,y,_,b){let h=Kt({onChange:y}),g=Nn(b);return(f,a)=>{(async()=>{let v=f.url??"/";try{if(!Un(f.headers.host)){a.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"Forbidden"}));return}if((f.method==="POST"||f.method==="PATCH"||f.method==="DELETE")&&!Jn(f.headers.origin)){a.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"Forbidden"}));return}if(t(`Received request: ${v}`),v==="/api/credentials"){a.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),a.end(n.current!==null?JSON.stringify(n.current):"{}");return}if(v==="/api/credential-profiles"&&f.method==="GET"){let s=await Ee();a.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({profiles:s,active:r.current}));return}if(v==="/api/credentials/switch"&&f.method==="POST"){let s=[];for await(let p of f)s.push(p);let l=JSON.parse(Buffer.concat(s).toString("utf-8")||"{}").profile,d=l===void 0||l===""?await Z():await be(l);if(d!==null){n.current=d,r.current=l??void 0;let p=r.current;await ue(c,{credentialMode:"global",...p!==void 0&&{activeCredentialProfile:p}}),S({type:"credentials-updated",credentials:d})}a.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({ok:d!==null}));return}if(v==="/api/bundle"){let s=De(process.cwd(),".kizenapp","bundle.json");try{let o=await Fn(s,"utf-8");a.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),a.end(o)}catch{a.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),a.end("{}")}return}if(v==="/api/last-path"&&f.method==="POST"){let s=[];for await(let l of f)s.push(l);let o=JSON.parse(Buffer.concat(s).toString("utf-8")||"{}");if(typeof o.path=="string"){_.current=o.path;let l=await Ie(c);await ue(c,{...l,lastPath:o.path})}a.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),a.end('{"ok":true}');return}if(v==="/api/execute-step"&&f.method==="POST"){let s=[];for await(let p of f)s.push(p);let o=JSON.parse(Buffer.concat(s).toString("utf-8")||"{}");if(typeof o.script!="string"){a.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"Missing required field: script"}));return}let l={script:o.script,scriptRuntime:o.scriptRuntime??"python-3.9",inputs:o.inputs??{},secrets:o.secrets??{},onInstallProgress:p=>{p.kind==="start"?S({type:"venv-install-start"}):p.kind==="log"?S({type:"venv-install-log",line:p.line,stream:p.stream}):p.kind==="complete"?S({type:"venv-install-complete"}):S({type:"venv-install-error",message:p.message})}};typeof o.timeout=="number"&&o.timeout>0&&(l.timeout=Math.min(o.timeout,300*1e3));let d=await er(l);a.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify(d));return}if(v==="/api/proxy-cache/clear"){h.clear(),i({kind:"info",message:"Proxy cache cleared"}),a.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),a.end('{"ok":true}');return}if(v.startsWith("/api/proxy")){let s=f.headers["x-proxy-target"];if(typeof s!="string"){a.writeHead(400),a.end("Missing x-proxy-target header");return}if(!Vn(s)){a.writeHead(400),a.end("Invalid proxy target");return}let o=v.slice(10)||"/",l=`${s}${o}`,d=f.method??"GET",p=[];for await(let pe of f)p.push(pe);let{host:j,"x-proxy-target":k,...I}=f.headers;if(d==="GET"){let pe=`GET::${l}`,{response:fe,fromCache:Ce}=await h.get(pe,()=>fetch(l,{method:"GET",headers:I}));i({kind:"request",method:"GET",status:fe.status,fromCache:Ce,url:o}),a.writeHead(fe.status,fe.headers),a.end(fe.body);return}let O=p.length>0?Buffer.concat(p):void 0,q=O&&O.length>0?O:void 0,J=await fetch(l,{method:d,headers:I,...q!==void 0&&{body:q}}),X=ft(Object.fromEntries(J.headers)),tt=await gt(J,mt);i({kind:"request",method:d,status:J.status,fromCache:!1,url:o}),a.writeHead(J.status,X),a.end(tt);return}if(v.startsWith("/api/source/tree")&&f.method==="GET"){let o=new URL(v,"http://localhost").searchParams.get("path")??"",l=await ir(g,o);if(l===null){a.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"Invalid path"}));return}if(sr(g,l)){a.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"Path is excluded"}));return}try{let d=await jn(l,{withFileTypes:!0}),p=await Promise.all(d.filter(k=>k.isDirectory()?!$e.has(k.name):k.isFile()?!Hn.has(k.name):!1).map(async k=>{let I=k.isDirectory()?"dir":"file",O={name:k.name,kind:I};if(I==="file")try{let q=await nr(De(l,k.name));O.size=q.size}catch{}return O}));p.sort((k,I)=>k.kind!==I.kind?k.kind==="dir"?-1:1:k.name.localeCompare(I.name));let j=l===g?"":l.slice(g.length+1);a.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({path:j,entries:p}))}catch(d){let p=d instanceof Error?d.message:String(d);t(`source/tree failed (${o}): ${p}`),a.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"Not found"}))}return}if(v.startsWith("/api/source/file")&&f.method==="GET"){let o=new URL(v,"http://localhost").searchParams.get("path")??"";if(o===""){a.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"Missing path"}));return}let l=await ir(g,o);if(l===null){a.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"Invalid path"}));return}if(sr(g,l)){a.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"Path is excluded"}));return}try{let d=await nr(l);if(!d.isFile()){a.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"Not a file"}));return}if(d.size>Mn){a.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"File too large",size:d.size}));return}let p=or(l).toLowerCase(),j=yt[p],k=tr.has(p),I=j??(k?"text/plain; charset=utf-8":"application/octet-stream");a.writeHead(200,{"Content-Type":I,"Content-Length":String(d.size)}),rr(l).pipe(a)}catch(d){let p=d instanceof Error?d.message:String(d);t(`source/file failed (${o}): ${p}`),a.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),a.end(JSON.stringify({error:"Not found"}))}return}let C=De(e,v==="/"?"/index.html":v),m=await Ct(C)?C:De(e,"index.html"),u=or(m),w=yt[u]??"application/octet-stream";a.writeHead(200,{"Content-Type":w}),rr(m).pipe(a)}catch(N){if(v.startsWith("/api/proxy")){let E=v.slice(10)||"/",C=f.method??"GET";N instanceof ke?i({kind:"info",message:`${C} ${E} \u2192 502 (response exceeded ${String(N.limit)} bytes)`}):i({kind:"request",method:C,status:502,fromCache:!1,url:E})}else i({kind:"info",message:`Error handling ${v}: ${N instanceof Error?N.message:String(N)}`});a.headersSent||(a.writeHead(502),a.end("Bad Gateway"))}})()}}import{launch as Wn}from"chrome-launcher";import{createRequire as Kn}from"module";import{mkdirSync as Gn}from"fs";import{readFile as Xn}from"fs/promises";import{dirname as Yn,join as Zn}from"path";import{fileURLToPath as Qn}from"url";var cr=Kn(import.meta.url)("chrome-remote-interface"),eo=new Set(["content-security-policy","content-security-policy-report-only","x-frame-options"]),ur=["kizen.dev","kizen.com"];function dr(e){try{let{hostname:t}=new URL(e);return ur.some(i=>t===i||t.endsWith("."+i))}catch{return!1}}function Ge(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(n=>/^\d+$/.test(n.name)).sort((n,r)=>parseInt(n.name)-parseInt(r.name)).map(Ge);let i={};for(let n of t.properties)i[n.name]=Ge(n);return i}return e.value??`[${e.type}]`}}function to(e){if(e.value!==void 0)return e.value;if(e.preview){let{preview:t}=e;if(t.subtype==="array")return t.properties.filter(n=>/^\d+$/.test(n.name)).sort((n,r)=>parseInt(n.name)-parseInt(r.name)).map(Ge);let i={};for(let n of t.properties)i[n.name]=Ge(n);return i}return e.description??`[${e.type}]`}async function ro(e,t){if(t.type==="object"&&t.objectId)try{let n=(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 n=="string")return JSON.parse(n)}catch{}return to(t)}async function no(e){try{let t=Zn(Yn(Qn(import.meta.url)),"viewer","icon.png"),i=await Xn(t);await e.Browser.setDockTile({image:i.toString("base64")})}catch{}}async function pr(e){Gn(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,i=await Wn({startingUrl:t,chromeFlags:[`--app=${t}`,"--no-first-run","--no-default-browser-check","--disable-extensions"],userDataDir:e.userDataDir,handleSIGINT:!1,logLevel:"silent"}),n=i.port,r=null,c=null,S=null,y=null,_=0,b=!1,h=u=>{e.debugLog?.(u)},g=u=>{e.verbose&&e.debugLog?.(u)},f=()=>{c!==null&&(clearInterval(c),c=null)},a=u=>u==="chrome://new-tab-page/"||u==="chrome://newtab/",v=async u=>{f(),S=null,await no(u),await u.Fetch.enable({patterns:ur.flatMap(s=>[{urlPattern:`*://${s}/*`,requestStage:"Response"},{urlPattern:`*://*.${s}/*`,requestStage:"Response"}])}),u.on("Fetch.requestPaused",s=>{(async()=>{let o=s,{requestId:l,request:d,responseHeaders:p,responseStatusCode:j}=o,k=d.url;g(`Fetch ${String(j??"?")} ${k}`);let I=[],O=!1;for(let q of p??[])if(!eo.has(q.name.toLowerCase()))if(q.name.toLowerCase()==="set-cookie"&&dr(k)){let J=q.value.split(`
|
|
172
|
+
`).map(X=>/SameSite=/i.test(X)?X.replace(/SameSite=\w+/i,"SameSite=None"):X+"; SameSite=None; Secure").join(`
|
|
173
|
+
`);I.push({name:q.name,value:J}),O=!0}else I.push(q);O&&g(` rewrote Set-Cookie SameSite on ${k}`);try{let{body:q,base64Encoded:J}=await u.Fetch.getResponseBody({requestId:l});await u.Fetch.fulfillRequest({requestId:l,responseCode:j??200,responseHeaders:I,body:q,...J&&{base64Encoded:!0}})}catch(q){g(` fulfillRequest failed (${q.message}), falling through`);try{await u.Fetch.continueRequest({requestId:l})}catch(J){g(` continueRequest also failed (${J.message})`)}}})()}),c=setInterval(()=>{(async()=>{try{let{cookies:s}=await u.Network.getAllCookies(),o=0;for(let l of s){if(!dr(`https://${l.domain??""}`)||l.sameSite==="None")continue;let d=l.domain??"",p=d.startsWith(".")?d.slice(1):d;await u.Network.setCookie({url:`https://${p}`,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"}),o++}o>0&&g(`cookie-patch cycle: updated ${String(o)} cookie(s) to SameSite=None`)}catch(s){g(`cookie-patch cycle failed: ${s.message}`)}})()},2e3),await u.send("Runtime.enable",{generatePreview:!0}),u.on("Target.attachedToTarget",s=>{let o=s,{sessionId:l,targetInfo:d}=o;g(`attached session ${l} (${d.type} ${d.url})`),u.send("Runtime.enable",{generatePreview:!0},l).catch(p=>{g(` Runtime.enable on session ${l} failed: ${p.message}`)})}),await u.Target.setAutoAttach({autoAttach:!0,waitForDebuggerOnStart:!1,flatten:!0}),await u.Target.setDiscoverTargets({discover:!0});let w=s=>{if(s.type==="page"){if(a(s.url)){h(`closed stray new-tab-page target ${s.targetId}`),S!==null&&u.Target.activateTarget({targetId:S}).catch(()=>{}),u.Target.closeTarget({targetId:s.targetId}).catch(()=>{});return}S===null&&(S=s.targetId,h(`captured main target ${s.targetId} (${s.url})`))}};u.on("Target.targetCreated",s=>{let{targetInfo:o}=s;g(`target +${o.type} ${o.targetId} ${o.url}`),w(o)}),u.on("Target.targetInfoChanged",s=>{let{targetInfo:o}=s;g(`target ~${o.type} ${o.targetId} ${o.url}`),w(o)}),u.on("Runtime.consoleAPICalled",s=>{(async()=>{let{type:o,args:l}=s;if(l[0]?.type==="string"&&String(l[0].value).includes("Chrome Security"))return;let d=o==="warning"?"warn":["log","warn","error","info"].includes(o)?o:"log";g(`console.${d} (${String(l.length)} arg(s))`);let p=await Promise.all(l.map(j=>ro(u,j)));e.broadcast({type:"console-message",level:d,args:p})})().catch(o=>{g(`console serialization failed: ${o.message}`)})}),u.on("disconnect",()=>{b||r!==u||(h("CDP disconnected"),r=null,f(),N())})},N=()=>{if(b||y!==null)return;let u=Math.min(1e3*2**_,1e4),w=_+1;_++,h(`CDP reconnect scheduled in ${String(u)}ms (attempt #${String(w)})`),y=setTimeout(()=>{y=null,(async()=>{let s;try{s=await cr({port:n})}catch{h(`CDP reconnect attempt #${String(w)} failed`),N();return}if(b){try{await s.close()}catch{}return}r=s;try{await v(s),h(`CDP reconnected after ${String(w)} attempt(s)`),_=0}catch{r===s&&(r=null);try{await s.close()}catch{}h(`CDP reconnect attempt #${String(w)} failed during setup`),N()}})()},u)},E=30,C=300;for(let u=0;u<E;u++){await new Promise(w=>setTimeout(w,C)),h(`CDP connect attempt ${String(u+1)}/${String(E)}`);try{let w=await cr({port:n});r=w,e.path&&w.send("Page.navigate",{url:`${t}${e.path}`});try{await v(w),h("CDP connected")}catch{r===w&&(r=null);try{await w.close()}catch{}h("CDP setup failed after connect")}break}catch{if(u===E-1){let w=`CDP unavailable after ${String(E)} attempts \u2014 viewer running without interception (CSP/cookie rewrites disabled)`;return h(w),e.onWarn?.(w),{kill:()=>{i.kill()}}}}}return r?{kill:()=>{if(h("CDP kill requested \u2014 tearing down"),b=!0,y!==null&&(clearTimeout(y),y=null),f(),r!==null){try{r.close()}catch{}r=null}i.kill()}}:{kill:()=>{i.kill()}}}import{useCallback as oo,useState as io}from"react";function Xe(e){let[t,i]=io([]),n=oo(r=>{i(c=>[...c,`${new Date().toLocaleTimeString()}: ${r}`].slice(-e))},[e]);return[t,n]}import{useCallback as Ye,useEffect as wt,useState as Ze}from"react";import{Box as z,Text as D,useInput as so}from"ink";import{jsx as P,jsxs as H}from"react/jsx-runtime";var ne=["apiKey","userId","businessId"],ao={apiKey:"API Key",userId:"User ID",businessId:"Business ID"},Re=({text:e})=>P(D,{dimColor:!0,children:e}),Qe=({initialMode:e,showProfileManager:t,onComplete:i,onCancel:n})=>{let[r,c]=Ze(e==="global"&&!t?{type:"loading"}:e==="global"&&t?{type:"profile-loading"}:{type:"mode-select",cursor:0}),[S,y]=Ze(""),[_,b]=Ze(null),[h,g]=Ze(void 0),f=Ye(s=>{if(s==="local"){i({mode:"local",credentials:null});return}c({type:"profile-loading"})},[i]),a=Ye(async s=>{if(s===null){c({type:"profile-loading"});let d=await Ee();c({type:"name-entry",nameBuffer:"",existingProfiles:d});return}g(s.isDefault?void 0:s.name),c({type:"loading"});let o=s.isDefault?await Z():await be(s.name),l=o?Math.max(0,G.indexOf(o.environment)):0;c({type:"creds-entry",field:0,values:o??{},envCursor:l})},[]),v=Ye(async(s,o)=>{let l=G[o]??"go",d={apiKey:s.apiKey??"",userId:s.userId??"",businessId:s.businessId??"",environment:l};c({type:"saving"});try{await Jt(h??re,d),i({mode:"global",credentials:d,...h!==void 0&&{profileName:h}})}catch(p){b(p instanceof Error?p.message:String(p)),c({type:"creds-entry",field:0,values:s,envCursor:o})}},[i,h]);so((s,o)=>{if(o.ctrl&&s==="c"&&process.exit(0),o.escape){if((r.type==="creds-entry"||r.type==="name-entry")&&e==="global"&&t){c({type:"profile-loading"}),N();return}n?.();return}if(r.type==="mode-select"){if(o.upArrow)c({type:"mode-select",cursor:0});else if(o.downArrow)c({type:"mode-select",cursor:1});else if(o.return){let l=r.cursor===0?"global":"local";f(l)}return}if(r.type==="profile-select"){let{profiles:l,cursor:d}=r,p=l.length,j=l.length+1;if(o.upArrow)c({...r,cursor:(d-1+j)%j});else if(o.downArrow)c({...r,cursor:(d+1)%j});else if(o.return)if(d===p)c({type:"name-entry",nameBuffer:"",existingProfiles:l});else{let k=l[d]??l[0];k&&a(k)}return}if(r.type==="name-entry"){let{nameBuffer:l,existingProfiles:d}=r;if(o.backspace||o.delete)c({type:"name-entry",nameBuffer:l.slice(0,-1),existingProfiles:d});else if(o.return){let p=l.trim();if(!p){c({...r,nameError:"Name cannot be empty"});return}if(p===re){c({...r,nameError:`"${re}" is reserved`});return}if(d.some(j=>j.name===p)){c({...r,nameError:`Profile "${p}" already exists`});return}g(p),c({type:"creds-entry",field:0,values:{},envCursor:0}),y("")}else s&&!o.ctrl&&!o.meta&&c({type:"name-entry",nameBuffer:l+s,existingProfiles:d});return}if(r.type==="creds-entry"){let{field:l,values:d,envCursor:p}=r;if(l===ne.length){o.leftArrow?c({...r,envCursor:(p-1+G.length)%G.length}):o.rightArrow?c({...r,envCursor:(p+1)%G.length}):o.upArrow?(c({...r,field:l-1}),y(d[ne[l-1]]??"")):o.return&&v(d,p);return}let k=ne[l];if(!k)return;if(o.backspace||o.delete)y(I=>I.slice(0,-1));else if(o.upArrow&&l>0){let I={...d,[k]:S},O=l-1;c({...r,field:O,values:I}),y(I[ne[O]]??"")}else if(o.return||o.tab||o.downArrow){let I={...d,[k]:S},O=l+1;c({...r,field:O,values:I}),O<ne.length?y(I[ne[O]]??""):y("")}else s&&!o.ctrl&&!o.meta&&y(I=>I+s)}});let N=Ye(async()=>{let s=await Ee();c({type:"profile-select",profiles:s,cursor:0})},[]);if(wt(()=>{r.type==="profile-loading"&&N()},[r.type,N]),wt(()=>{e==="global"&&!t&&(async()=>{let s=await Z(),o=s?Math.max(0,G.indexOf(s.environment)):0;c({type:"creds-entry",field:0,values:s??{},envCursor:o})})()},[]),wt(()=>{r.type==="creds-entry"&&r.field===0&&y(r.values.apiKey??"")},[r.type]),r.type==="loading"||r.type==="saving"||r.type==="profile-loading"){let s=r.type==="saving"?"Saving credentials\u2026":r.type==="profile-loading"?"Loading profiles\u2026":"Loading credentials\u2026";return P(z,{paddingY:1,paddingX:2,children:P(D,{dimColor:!0,children:s})})}if(r.type==="done")return null;if(r.type==="mode-select")return H(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),H(z,{flexDirection:"column",gap:0,children:[P(D,{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((o,l)=>{let d=r.cursor===l;return H(z,{gap:2,children:[P(D,{...d&&{color:"cyan"},children:d?"\u276F":" "}),P(D,{bold:d,...d&&{color:"cyan"},children:o.label}),P(D,{dimColor:!0,children:o.desc})]},o.mode)})]}),P(Re,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]});if(r.type==="profile-select"){let{profiles:s,cursor:o}=r,l=s.length;return H(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),H(z,{flexDirection:"column",gap:0,children:[P(D,{bold:!0,children:"Credential profiles"}),s.map((d,p)=>{let j=o===p;return H(z,{gap:2,children:[P(D,{...j&&{color:"cyan"},children:j?"\u276F":" "}),P(D,{bold:j,...j&&{color:"cyan"},children:d.isDefault?"Default":d.name}),P(D,{dimColor:!0,children:d.path})]},d.name)}),H(z,{gap:2,children:[P(D,{...o===l&&{color:"cyan"},children:o===l?"\u276F":" "}),P(D,{bold:o===l,...o===l&&{color:"cyan"},children:"+ Add new profile"})]})]}),P(Re,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(r.type==="name-entry"){let{nameBuffer:s,nameError:o}=r;return H(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),P(z,{flexDirection:"column",gap:0,children:P(D,{bold:!0,children:"New credential profile"})}),o&&H(D,{color:"red",children:["Error: ",o]}),H(z,{gap:2,children:[P(z,{width:12,children:P(D,{bold:!0,color:"cyan",children:"Profile name"})}),P(D,{color:"cyan",children:">"}),P(D,{children:s}),P(D,{color:"cyan",children:"\u2588"})]}),P(Re,{text:"Type a name \xB7 Enter to confirm \xB7 Esc to go back"})]})}let{field:E,values:C,envCursor:m}=r,u=E===ne.length,w=h??re;return H(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),H(z,{flexDirection:"column",gap:0,children:[P(D,{bold:!0,children:h!==void 0?`Profile: ${h}`:"Global credentials"}),H(D,{dimColor:!0,children:["Saved to:"," ",h!==void 0?`~/.kizenappbuilder/${h}.json`:xe]})]}),_&&H(D,{color:"red",children:["Error: ",_]}),H(z,{flexDirection:"column",gap:0,children:[ne.map((s,o)=>{let l=E===o,d=l?S:C[s]??"";return H(z,{gap:2,children:[P(z,{width:12,children:P(D,{bold:l,...l&&{color:"cyan"},children:ao[s]})}),P(D,{...l&&{color:"cyan"},children:">"}),P(D,{children:d}),l&&P(D,{color:"cyan",children:"\u2588"})]},s)}),H(z,{gap:2,children:[P(z,{width:12,children:P(D,{bold:u,...u&&{color:"cyan"},children:"Environment"})}),P(D,{...u&&{color:"cyan"},children:">"}),P(z,{gap:1,children:G.map((s,o)=>{let l=o===m;return u?P(D,{bold:l,...l&&{color:"cyan"},children:l?`[${s}]`:s},s):P(D,{dimColor:!l,bold:l,children:s},s)})})]})]}),u?P(Re,{text:"\u2190\u2192 to select \xB7 \u2191\u2193 to move \xB7 Enter to save \xB7 Esc to cancel"}):P(Re,{text:"\u2191\u2193 to move \xB7 Backspace to delete \xB7 Esc to cancel"}),H(D,{dimColor:!0,children:["Profile: ",w]})]})};import{jsx as L,jsxs as $}from"react/jsx-runtime";var mo=[".kizenapp",".git"],mr=({port:e,pluginDir:t,outputDir:i,credentials:n,credentialMode:r,activeCredentialProfile:c,lastPath:S,debug:y=!1,verbose:_=!1})=>{let b=Q(n),h=Q(c),g=Q(S),[f,a]=W("main"),[v,N]=W(r),[E,C]=W("starting"),[m,u]=W(null),[w,s]=Xe(50),[o,l]=Xe(50),[d,p]=Xe(50),[j,k]=W([]),[I,O]=W("pending"),[q,J]=W(null),[X,tt]=W(null),[pe,fe]=W(null),[Ce,rt]=W(0),[St,br]=W(0),[vr,Cr]=W(0),[wr,Sr]=W(0),nt=Q(!1),Pt=Q(!1),je=Q(null),we=Q(null),ee=Q(new Set),Fe=Q([]),K=ve(x=>{let F=JSON.stringify(x);if(ee.current.size===0){Fe.current=[...Fe.current,F].slice(-50);return}let te=!1;for(let Y of ee.current)if(Y.readyState===1)try{Y.send(F)}catch{ee.current.delete(Y),te=!0}te&&rt(ee.current.size)},[]),Ae=s,ot=ve(()=>{je.current?.kill(),je.current=null,pr({port:e,userDataDir:fr(i,".chrome"),broadcast:K,onWarn:x=>{s(`\u26A0 ${x}`)},...g.current!==void 0&&{path:g.current},...y&&{debugLog:p},..._&&{verbose:!0}}).then(x=>{je.current=x})},[e,i,K,y,_,p,s]);et(()=>{let x=()=>{je.current?.kill()};return process.on("exit",x),()=>{process.off("exit",x)}},[]),co((x,F)=>{(x==="q"||F.ctrl&&x==="c")&&process.exit(0),x==="c"&&a("editing"),x==="v"&&ot()},{isActive:f==="main"}),et(()=>{E!=="running"||Pt.current||(Pt.current=!0,ot())},[E,ot]);let Pr=ve(x=>{b.current=x.credentials,h.current=x.profileName,a("main"),N(x.mode);let F=x.profileName;ue(i,{credentialMode:x.mode,...F!==void 0&&{activeCredentialProfile:F}}),K({type:"credentials-updated",credentials:x.credentials})},[i,K]),Tt=ve(x=>{k(F=>[...F,`${new Date().toLocaleTimeString()}: ${bt(x)}`].slice(-50)),x.kind==="request"&&(x.fromCache?Cr(F=>F+1):Sr(F=>F+1)),K({type:"proxy-log",entry:x})},[K]),ie=ve(x=>{l(x),K({type:"log",message:x})},[l,K]),it=ve(()=>{nt.current||(nt.current=!0,O("building"),J(null),ie("Build started"),ze(t,i).then(({bundleSize:x})=>{ie(`Build finished \u2014 bundle: ${Se(x)}`),O("done"),tt(new Date),fe(x),ie("Notifying viewers to reload"),K({type:"rebuild"})}).catch(x=>{let F=x instanceof Error?x.message:String(x);J(F),O("error")}).finally(()=>{nt.current=!1}))},[t,i,ie,K]);if(et(()=>{it();let x=uo(t,{recursive:!0},(F,te)=>{if(!te)return;let Y=te.replace(/\\/g,"/");mo.some(Oe=>Y.startsWith(Oe))||(ie(`File change detected: ${te}`),we.current!==null&&clearTimeout(we.current),we.current=setTimeout(it,150))});return x.on("error",F=>{ie(`File watcher error \u2014 rebuilds have stopped: ${F.message}`)}),()=>{x.close(),we.current!==null&&clearTimeout(we.current)}},[t,it,ie]),et(()=>{let x=ar();Ct(fr(x,"index.html")).then(F=>{if(!F){u("Viewer not built. Run 'pnpm build:viewer' first."),C("error");return}let te=lr(x,Ae,Tt,b,h,i,K,br,g,t),Y=po(te),Oe=new fo({server:Y});return Oe.on("connection",se=>{for(let _r of Fe.current)se.readyState===1&&se.send(_r);Fe.current=[],Ae("Viewer connected for live reload"),ee.current.add(se),rt(ee.current.size),se.on("close",()=>{ee.current.delete(se),rt(ee.current.size)})}),Y.listen(e,"127.0.0.1",()=>{C("running"),Ae(`Server started on 127.0.0.1:${String(e)}`)}),Y.on("error",se=>{u(se.message),C("error")}),()=>{Oe.close(),Y.close()}})},[e,Ae,Tt,K,i,t]),f==="editing")return L(Qe,{...v!==void 0&&{initialMode:v},showProfileManager:v==="global",onComplete:Pr,onCancel:()=>{a("main")}});let st=X!==null?Math.round((Date.now()-X.getTime())/1e3):null,Tr=st===null?"":st<5?" (just now)":` (${String(st)}s ago)`;return $(U,{flexDirection:"column",paddingY:1,paddingX:2,children:[L(V,{marginBottom:1}),$(U,{flexDirection:"column",children:[$(U,{gap:2,marginBottom:0,children:[L(R,{bold:!0,dimColor:!0,children:"App Build"}),I==="pending"&&L(R,{dimColor:!0,children:"waiting\u2026"}),I==="building"&&$(U,{gap:1,children:[L(Me,{}),L(R,{children:"Building plugin package\u2026"})]}),I==="done"&&$(U,{gap:1,children:[L(R,{color:"green",children:"\u2713 Built"}),X!==null&&$(R,{dimColor:!0,children:["at ",X.toLocaleTimeString(),Tr]}),pe!==null&&$(R,{dimColor:!0,children:["\xB7 bundle: ",Se(pe)]})]}),I==="error"&&$(R,{color:"red",children:["\u2717 ",q??"unknown error"]})]}),L(U,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:o.slice(-8).map((x,F)=>L(R,{dimColor:!0,wrap:"truncate",children:x},F))})]}),$(U,{marginTop:1,flexDirection:"column",children:[$(U,{gap:2,children:[L(R,{bold:!0,dimColor:!0,children:"Web Server"}),E==="starting"&&L(R,{dimColor:!0,children:"starting\u2026"}),E==="running"&&$(U,{gap:2,children:[L(R,{color:"green",children:"\u2713 Running"}),$(R,{dimColor:!0,children:["\u25CF ",Ce," viewer",Ce!==1?"s":""]})]}),E==="error"&&$(R,{color:"red",children:["\u2717 ",m??"Server error"]})]}),L(U,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:w.slice(-8).map((x,F)=>L(R,{dimColor:!0,wrap:"truncate",children:x},F))})]}),$(U,{marginTop:1,flexDirection:"column",children:[$(U,{gap:2,children:[L(R,{bold:!0,dimColor:!0,children:"Network Proxy"}),L(R,{color:"green",children:"\u2713 Active"}),$(R,{dimColor:!0,children:["\u25CF ",St," key",St!==1?"s":""," in the network cache \xB7"," ",vr," hit \xB7 ",wr," miss"]})]}),L(U,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:j.length===0?L(R,{dimColor:!0,children:" No requests yet."}):j.slice(-8).map((x,F)=>L(R,{dimColor:!0,wrap:"truncate",children:x},F))})]}),y&&$(U,{marginTop:1,flexDirection:"column",children:[$(U,{gap:2,children:[L(R,{bold:!0,dimColor:!0,children:"CDP Debug"}),$(R,{dimColor:!0,children:["\u25CF ",d.length," event(s)"]})]}),L(U,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:d.length===0?L(R,{dimColor:!0,children:" No CDP events yet."}):d.slice(-8).map((x,F)=>L(R,{dimColor:!0,wrap:"truncate",children:x},F))})]}),$(U,{marginTop:1,gap:1,children:[L(R,{dimColor:!0,children:"["}),L(R,{children:"q"}),L(R,{dimColor:!0,children:"] quit ["}),L(R,{children:"c"}),L(R,{dimColor:!0,children:"] credentials ["}),L(R,{children:"v"}),$(R,{dimColor:!0,children:["] ",Ce===0?"open viewer":"relaunch viewer"]})]})]})};async function gr(e){return new Promise(t=>{let i=null,n=c=>{i?.(),t(c)},{unmount:r}=hr(yr(Qe,{...e!==void 0&&{initialMode:e},onComplete:n}),{exitOnCtrlC:!1});i=r})}function xr(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)").action(async t=>{let i=parseInt(t.port,10),n=process.cwd(),r=`${n}/.kizenapp`;ye(n);let c=null,S,y,{lastPath:_}=await Ie(r);if(t.credentials)c=await Je(t.credentials);else{let f=await Ie(r);if(f.credentialMode==="local")S="local";else if(f.credentialMode==="global"){if(S="global",y=f.activeCredentialProfile,y?(c=await be(y),c||(c=await Z(),y=void 0)):c=await Z(),!c){let a=await gr("global");c=a.credentials,y=a.profileName}}else{let a=await gr();c=a.credentials,S=a.mode,y=a.profileName;let v=a.profileName;await ue(r,{credentialMode:a.mode,...v!==void 0&&{activeCredentialProfile:v}})}}let b=t.verbose===!0,h=b||t.debug===!0,{waitUntilExit:g}=hr(yr(mr,{port:i,pluginDir:n,outputDir:r,credentials:c,...S!==void 0&&{credentialMode:S},...y!==void 0&&{activeCredentialProfile:y},..._!==void 0&&{lastPath:_},debug:h,verbose:b}),{exitOnCtrlC:!1});await g()})}var bo=ho(yo(xo(import.meta.url)),"..","package.json"),vo=JSON.parse(go(bo,"utf-8"));Le.name("appbuilder").description("Kizen plugin app builder").version(vo.version);Wt(Le);Ft(Le);xr(Le);Le.parse();
|
|
174
174
|
//# sourceMappingURL=index.js.map
|