@kizenapps/cli 1.14.0 → 1.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/README.md +251 -1
- package/dist/index.js +772 -161
- package/dist/index.js.map +1 -1
- package/dist/viewer/assets/{CodeStepsPage-Cu9UiRy9.js → CodeStepsPage-D_a3dij6.js} +1 -1
- package/dist/viewer/assets/{ConfigurationPage-CI0pRNJ0.js → ConfigurationPage-DUiOAiMK.js} +1 -1
- package/dist/viewer/assets/CredentialsContext-p3i8s7a6.js +1 -0
- package/dist/viewer/assets/{DevSidebar-BFsoIbMt.js → DevSidebar-CkLpkWSy.js} +1 -1
- package/dist/viewer/assets/{SandboxPage-Dyb8i7vf.js → SandboxPage-D3Qdh_0M.js} +1 -1
- package/dist/viewer/assets/{SecretsPage-g2FF7d-B.js → SecretsPage-CQVPedWl.js} +1 -1
- package/dist/viewer/assets/{WhenBadge-DKz8ukwo.js → WhenBadge-CV5t88Iv.js} +1 -1
- package/dist/viewer/assets/api-C4R44YCL.js +11 -0
- package/dist/viewer/assets/{bootstrapQuery-DTAPKOf-.js → bootstrapQuery-WnoB2iya.js} +1 -1
- package/dist/viewer/assets/index-w3fkjFhR.js +5 -0
- package/dist/viewer/assets/{useCompleteSetup-QS3W9RRO.js → useCompleteSetup-BgC9V-FN.js} +4 -4
- package/dist/viewer/assets/{usePluginConfig--4sAyik4.js → usePluginConfig-mg5WevIz.js} +1 -1
- package/dist/viewer/index.html +4 -4
- package/package.json +1 -1
- package/dist/viewer/assets/CredentialsContext-Cwl_xyt_.js +0 -1
- package/dist/viewer/assets/api--pW2v3sH.js +0 -11
- package/dist/viewer/assets/index-GvAPdgKb.js +0 -5
package/dist/index.js
CHANGED
|
@@ -1,10 +1,726 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`).map(f=>f.
|
|
2
|
+
import*as uf from"http";var It="If you're behind a proxy, upgrade Node to 24.14+ or set NODE_USE_ENV_PROXY=1 on a Node version that supports it.",Oa=["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy"],La=e=>e!==void 0&&e!=="",Ee="not-configured";function Zn({env:e,http:t}){return Ee==="applied"||(Oa.some(r=>La(e[r]))?e.NODE_USE_ENV_PROXY==="1"?Ee="already-set":typeof t.setGlobalProxyFromEnv!="function"?Ee="unavailable":(t.setGlobalProxyFromEnv(e),Ee="applied"):Ee="not-configured"),Ee}var Dt=()=>Ee;import{readFileSync as of}from"fs";import{dirname as sf,join as af}from"path";import{fileURLToPath as lf}from"url";import{Command as cf}from"commander";import{createElement as Pd}from"react";import{render as Ed}from"ink";import{PluginValidationError as Td}from"@kizenapps/packager";import{spawn as za}from"child_process";import{platform as Qn}from"process";function Ma(){return Qn==="darwin"?[{cmd:"pbcopy",args:[]}]:Qn==="win32"?[{cmd:"clip",args:[]}]:[{cmd:"wl-copy",args:[]},{cmd:"xclip",args:["-selection","clipboard"]},{cmd:"xsel",args:["--clipboard","--input"]}]}var Ua=2e3;function Ha(e,{cmd:t,args:r}){return new Promise(o=>{let n;try{n=za(t,r,{stdio:["pipe","ignore","ignore"]})}catch{o(!1);return}let i=n,s=!1;function a(p){s||(s=!0,clearTimeout(l),o(p))}let l=setTimeout(()=>{i.kill(),a(!1)},Ua);l.unref(),i.on("error",()=>{a(!1)}),i.on("close",p=>{a(p===0)}),i.stdin.on("error",()=>{a(!1)});try{i.stdin.end(e)}catch{a(!1)}})}async function At(e){for(let t of Ma())if(await Ha(e,t))return!0;return!1}import{BLOCKS_DIRECTORY_NAME as Sl,CONFIG_FILE_NAME as _l,MANIFEST_FILE_NAME as Pl,sanitizeToAPIName as El}from"@kizenapps/packager";import{posix as Va}from"path";var H=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Nt=e=>e instanceof Error&&e.code==="ENOENT",Bt=e=>{let t=Va.normalize(e.trim().replaceAll("\\","/")).replace(/\/+$/,"");return t==="."?"":t};var Rt=["min_w","max_w","min_h","max_h","default_w","default_h"];import{createHash as Wa}from"crypto";import{mkdir as Ka,readFile as Ja,writeFile as qa}from"fs/promises";import{dirname as Ga,join as ro}from"path";var Z=["go","fmo","staging","integration","test1"];function it(e){return typeof e=="string"?e.trim():""}function st(e){return{apiKey:it(e.apiKey),userId:it(e.userId),businessId:it(e.businessId)}}var $r="appbuilder:",Me=".kizenapp/pushes.json",Ya=["environment","businessId","pluginApiName","blockApiName","dashboardId","dashletId","contentHash","pushedAt"];function Fr(e){return typeof e=="number"&&Number.isFinite(e)}function $t(e,t,r){return Math.min(Math.max(e,t),r)}function Xa(e){let t={...e};return delete t.custom_object,t}function no(e,t){return`${$r}${e}/${t}`}function oo(e){if(!e.startsWith($r))return null;let t=e.slice($r.length).split("/");if(t.length!==2)return null;let[r,o]=t;return!r||!o?null:{pluginApiName:r,blockApiName:o}}function io(e){let t={};for(let r of Rt){let o=e[r];Fr(o)&&(t[r]=o)}return t}function so(e){return typeof e.host_chrome=="boolean"?{host_chrome:e.host_chrome}:{}}var ao=e=>Object.entries(e).map(([t,r])=>({name:t,script:r}));function Za(e){return{api_name:e.api_name,name:e.name,type:e.type,...e.script!==""&&{script:e.script},...e.html!==""&&{html:e.html},...e.css!==""&&{css:e.css},event_scripts:ao(e.event_scripts)}}function Or(e){return e.length>0?{views:e.map(Za)}:{}}function lo(e,t=[]){return{kind:"custom_code",version:1,name:e.name,script:e.script,styles:e.styles,event_scripts:ao(e.event_scripts),...io(e),...so(e),...Or(t)}}function Qa(e){return{object_id:e.objectId,entity_type:"static_content",report_type:"html",chart_type:"html",content:e.content,fe_extra_info:{}}}function el(e){let t=0;for(let r of e){let o=r.layout;if(!H(o))continue;let{y:n,h:i}=o;!Fr(n)||!Fr(i)||(t=Math.max(t,n+i))}return t}function tl(e,t,r){let o=$t(t.default_w??t.min_w??6,t.min_w??1,t.max_w??12),n=$t(t.default_h??t.min_h??3,t.min_h??1,t.max_h??99);return{i:r,x:0,y:el(e),w:$t(o,2,12),h:$t(n,1,99)}}function co(e){return{name:no(e.pluginApiName,e.blockApiName),layout:tl(e.dashlets,e.content,e.layoutId),config:Qa({content:e.content,objectId:e.objectId})}}function uo(e,t){let r=e.config;return{config:{...Xa(H(r)?r:{}),content:t}}}function po(e){let t=e.config;return H(t)?t.content:void 0}function Ye(e){let t=e.config;if(!H(t)||t.chart_type!=="html")return!1;let r=t.content;return H(r)&&r.kind==="custom_code"}function fo(e){return e.dashlets.filter(Ye)}function Ft(e){let t=po(e);return H(t)&&typeof t.name=="string"?t.name:e.name}var Te=e=>typeof e=="string"?e:"";function mo(e){return Array.isArray(e)?e.filter(H).map(t=>({name:Te(t.name),script:Te(t.script)})):H(e)?Object.entries(e).map(([t,r])=>({name:t,script:Te(r)})):[]}function jr(e){if(Array.isArray(e))return e.map(jr);if(H(e)){let t={};for(let r of Object.keys(e).sort())t[r]=jr(e[r]);return t}return e}function ho(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e).trim():""}function rl(e){return Array.isArray(e)?e.filter(H).map(t=>({api_name:Te(t.api_name),name:ho(t.name),type:Te(t.type),script:Te(t.script),html:Te(t.html),css:Te(t.css),event_scripts:mo(t.event_scripts)})):[]}function Lr(e){let t=H(e)?e:{},r=rl(t.views),o={name:ho(t.name),script:typeof t.script=="string"?t.script:"",styles:typeof t.styles=="string"?t.styles:"",event_scripts:mo(t.event_scripts),...io(t),...so(t),...r.length>0&&{views:r}};return Wa("sha256").update(JSON.stringify(jr(o))).digest("hex")}function go(e){let{entry:t}=e;if(t?.dashboardId===e.dashboardId){let i=e.dashlets.find(s=>s.id===t.dashletId);if(i&&Ye(i))return{kind:"map",dashlet:i,entry:t}}let r=no(e.pluginApiName,e.blockApiName),o=e.dashlets.filter(i=>i.name===r&&Ye(i)),[n]=o;return o.length===1&&n?{kind:"name",dashlet:n}:o.length>1?{kind:"ambiguous",dashlets:o}:{kind:"none"}}function yo(e,t){return t?.dashletId!==e.id?!1:Lr(po(e))!==t.contentHash}function zr(e,t){return e.environment===t.environment&&e.businessId===t.businessId&&e.pluginApiName===t.pluginApiName&&e.blockApiName===t.blockApiName}function Mr(e,t){return e.find(r=>zr(r,t))}function bo(e,t){let r=e.findIndex(o=>zr(o,t));return r===-1?[...e,t]:e.map((o,n)=>n===r?t:o)}function wo(e,t){return e.filter(r=>!zr(r,t))}function nl(e){if(!H(e))return null;for(let r of Ya)if(typeof e[r]!="string")return null;let t=e;return{environment:t.environment,businessId:it(t.businessId),pluginApiName:t.pluginApiName,blockApiName:t.blockApiName,dashboardId:t.dashboardId,dashletId:t.dashletId,contentHash:t.contentHash,pushedAt:t.pushedAt}}var eo=e=>Date.parse(e.pushedAt)||0;function ol(e){let t=new Map;for(let r of e){let o=[r.environment,r.businessId,r.pluginApiName,r.blockApiName].join("\0"),n=t.get(o);(n===void 0||eo(r)>eo(n))&&t.set(o,r)}return[...t.values()]}var to=e=>e instanceof Error?e.message:String(e);async function xo(e){let t;try{t=await Ja(ro(e,Me),"utf8")}catch(o){if(Nt(o))return[];throw new Error(`Couldn't read ${Me}: ${to(o)}. Fix its permissions, or delete it to start a fresh push map.`)}let r;try{r=JSON.parse(t)}catch(o){throw new Error(`${Me} is not valid JSON (${to(o)}). Fix it, or delete it to start a fresh push map.`)}if(!Array.isArray(r))throw new Error(`${Me} must contain a JSON array of push entries. Fix it, or delete it to start a fresh push map.`);return ol(r.map(nl).filter(o=>o!==null))}async function vo(e,t){let r=ro(e,Me);await Ka(Ga(r),{recursive:!0}),await qa(r,`${JSON.stringify(t,null,2)}
|
|
3
|
+
`,"utf8")}var il={generic_dashboard:"dashboard",homepage:"homepage",chart_group:"chart_group"},sl={dashboard:"generic_dashboard",homepage:"homepage",chart_group:"chart_group"};function Ur(e){return il[e]}function ko(e){return sl[e]}function Co(e){let t=e.appBaseUrl.replace(/\/+$/,""),r=e.dashboardId;return e.surface==="homepage"?`${t}/home/${r}`:e.surface==="chart_group"&&e.customObject?e.customObject.fetchUrl==="client"?`${t}/clients/charts/${r}`:`${t}/custom-objects/${e.customObject.id}/charts/${r}`:`${t}/dashboard/${r}`}import{mkdir as ml,writeFile as hl}from"fs/promises";import{join as gl}from"path";import{PluginValidationError as yl,packagePlugin as bl,parseManifestFromFiles as wl,transformDeployablePlugin as xl,transformFiles as vl,validatePluginApp as kl}from"@kizenapps/packager";import{readdir as al,readFile as So}from"fs/promises";import{join as _o,relative as ll}from"path";var cl=new Set([".png",".svg"]),dl=new Set([".kzn"]),ul=new Set([".DS_Store"]),jt=new Set(["node_modules",".git",".kizenapp",".copilot-docs",".github",".claude","__pycache__"]),pl=8e3;function fl(e){return e.subarray(0,pl).includes(0)}async function Po(e,t){let r=await al(e,{withFileTypes:!0}),o=[];for(let n of r)if(n.isDirectory()){if(jt.has(n.name))continue;o.push(...await Po(_o(e,n.name),t))}else n.isFile()&&(ul.has(n.name)||o.push(_o(e,n.name)));return o}async function Ot(e,{detectBinaryByContent:t=!1}={}){let r=await Po(e,e);return Promise.all(r.map(async o=>{let n=ll(e,o).split("\\").join("/"),i=n.lastIndexOf("."),s=i>=0?n.slice(i).toLowerCase():"";if(cl.has(s)){let l=await So(o);return{path:n,content:"",base64Image:l.toString("base64")}}let a=await So(o);return dl.has(s)||t&&fl(a)?{path:n,content:"",binaryData:a}:{path:n,content:a.toString("utf-8")}}))}var Cl=(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 Hr(e,t){t?.("reading-files");let r=await Ot(e);t?.("validating");let o=kl(r);if(o.some(l=>l.severity==="error"))throw new yl(o);t?.("minifying");let n=await vl(r);t?.("packaging");let i=wl(n),s=bl(n,i),a=Object.values(s).map(xl);return{files:r,deployable:a,issues:o}}async function Lt(e,t,r){await ml(t,{recursive:!0});let{files:o,deployable:n}=await Hr(e,r);r?.("writing-bundle");let i=n.map(p=>{let g=p.release_notes_directory?.replace(/\/$/,""),v=g?o.filter(k=>k.path.startsWith(g+"/")&&k.path.endsWith(".md")&&k.content).map(k=>({version:k.path.slice(k.path.lastIndexOf("/")+1,-3),notes:k.content})).sort((k,f)=>f.version.localeCompare(k.version,void 0,{numeric:!0})):[];return Cl(p,v)}),s=JSON.stringify(i,null,2),a=(p,g)=>p==="allReleaseNotes"?void 0:g,l=Buffer.byteLength(JSON.stringify(i,a,2),"utf-8");return await hl(gl(t,"bundle.json"),s,"utf-8"),{bundleSize:l}}var Io=["min_w","max_w","min_h","max_h"],Do=[["min_w","max_w"],["min_h","max_h"]],zt={default_w:["min_w","max_w"],default_h:["min_h","max_h"]},Tl=Object.keys(zt),Ao=[...Rt,"host_chrome"],Il=["\0","{__ref:"],Vr="views",Wr=class extends Error{reason;available;field;constructor(t,r,o={}){super(r),this.name="BlockExportError",this.reason=t,this.available=o.available??[],this.field=o.field}};function Dl(e){let t=new Set(e.map(r=>r.pluginApiName)).size>1;return e.map(r=>t?`${r.pluginApiName}/${r.apiName}`:r.apiName).join(", ")}function Al(e,t){let r=e.flatMap(s=>s.artifacts.custom_blocks.map(a=>({block:a,pluginApiName:s.api_name}))),o=r.map(({block:s,pluginApiName:a})=>({pluginApiName:a,apiName:s.api_name}));if(r.length===0)return{ok:!1,reason:"no_blocks",available:o};if(t===void 0){let[s]=r;return r.length===1&&s?{ok:!0,...s}:{ok:!1,reason:"ambiguous",available:o}}let n=r.filter(({block:s})=>s.api_name===t),[i]=n;return i?n.length>1?{ok:!1,reason:"ambiguous",available:n.map(({block:s,pluginApiName:a})=>({pluginApiName:a,apiName:s.api_name}))}:{ok:!0,...i}:{ok:!1,reason:"not_found",available:o}}var Eo=e=>typeof e=="number"&&Number.isInteger(e)&&e>0,at=e=>Il.some(t=>e.includes(t));function Nl(e){let t=e,{name:r,script:o,styles:n,event_scripts:i}=t;if(typeof o!="string"||!o.trim())return"script";if(r!==void 0&&typeof r!="string")return"name";if(n!==void 0&&typeof n!="string")return"styles";if(i!==void 0){if(!H(i))return"event_scripts";let g=Object.entries(i).find(([v,k])=>typeof k!="string"||at(v)||at(k));if(g)return`event_scripts.${g[0]}`}let s=[["name",r],["script",o],["styles",n]].find(([,g])=>typeof g=="string"&&at(g));if(s)return s[0];let a=Io.find(g=>t[g]!==void 0&&!Eo(t[g]));if(a)return a;let l=Do.find(([g,v])=>{let k=t[g],f=t[v];return typeof k=="number"&&typeof f=="number"&&k>f});if(l)return l[0];let p=Tl.find(g=>{let v=t[g];if(v===void 0)return!1;if(typeof v!="number"||!Eo(v))return!0;let[k,f]=zt[g],c=t[k],h=t[f];return typeof c=="number"&&v<c||typeof h=="number"&&v>h});if(p)return p;if(t.host_chrome!==void 0&&typeof t.host_chrome!="boolean")return"host_chrome"}var Bl=["api_name","name","script","html","css"],To=e=>typeof e!="string"||at(e);function Rl(e){for(let t of e){let r=t,o=typeof r.api_name=="string"?r.api_name:String(r.api_name),n=Bl.find(a=>To(r[a]));if(n)return{view:o,field:n};let i=r.event_scripts;if(!H(i))return{view:o,field:"event_scripts"};let s=Object.entries(i).find(([a,l])=>at(a)||To(l));if(s)return{view:o,field:`event_scripts.${s[0]}`}}}var $l=({view:e,field:t})=>`views.${e}.${t}`,Fl=(e,t)=>`Block "${e}" can't carry view ${JSON.stringify(t.view)}: its ${t.field} must be a string without NUL characters or "{__ref:".`,jl=(e,t)=>{if(t==="script")return`Block "${e}" has no script. Add a non-empty script.js to the block directory.`;if(t==="host_chrome")return`Block "${e}" has an invalid host_chrome: it must be true or false.`;let r=Do.find(([o])=>o===t);if(r)return`Block "${e}" has an invalid ${t}: it must be a positive integer no greater than ${r[1]}.`;if(Io.includes(t))return`Block "${e}" has an invalid ${t}: it must be a positive integer.`;if(t in zt){let[o,n]=zt[t];return`Block "${e}" has an invalid ${t}: it must be a positive integer between ${o} and ${n}.`}return`Block "${e}" has an invalid ${t}: it must be a string without NUL characters or "{__ref:".`},Ol=({reason:e,available:t},r,o)=>{let n=Dl(t);return e==="no_blocks"?"This plugin has no blocks. Scaffold one with `appbuilder create --artifacts block`.":e==="not_found"?`No block with api_name "${r??""}". Available blocks: ${n}`:r===void 0?`This plugin has several blocks; pass the api_name of the one to ${o}: ${n}`:`More than one plugin has a block with api_name "${r}": ${n}`},Ll=e=>{try{let t=JSON.parse(e);return H(t)?t:void 0}catch{return}},No=e=>{let t=e.find(i=>i.path===Pl),r=t?JSON.parse(t.content):[],o=Array.isArray(r)?r:[r],n=new Map;for(let i of o)H(i)&&typeof i.api_name=="string"&&typeof i.entry=="string"&&n.set(i.api_name,i.entry);return n},Bo=(e,t)=>{let r=Bt(e);return r===""?t:`${r}/${t}`},Ro=(e,t,r)=>{let o=`${Bo(t,r)}/`,n=new Set,i=[];for(let s of e){if(!s.path.startsWith(o)||s.path.endsWith(".DS_Store"))continue;let[a,l,...p]=s.path.slice(o.length).split("/");if(a&&(n.add(a),l===_l&&p.length===0)){let g=Ll(s.content);g&&i.push([a,g])}}return{directories:n,configs:i}},$o=(e,t)=>typeof e.api_name=="string"&&e.api_name!==""?e.api_name:El(t),zl=(e,t)=>{let r=new Map;for(let[o,n]of Ro(e,t,Sl).configs){let i=$o(n,o),s={};for(let a of Ao)n[a]!==void 0&&(s[a]=n[a]);r.set(i,s)}return r},Ml=(e,t={})=>({...Object.fromEntries(Object.entries(e).filter(([o])=>!Ao.includes(o))),...t});function Ul(e,t){let r=No(t);return e.map(o=>{let n=r.get(o.api_name),i=n===void 0?new Map:zl(t,n);return{...o,artifacts:{...o.artifacts,custom_blocks:o.artifacts.custom_blocks.map(s=>Ml(s,i.get(s.api_name)))}}})}var Fo=(e,t)=>JSON.stringify([String(e),String(t)]),Hl=(e,t)=>{let{directories:r,configs:o}=Ro(e,t,Vr),n=new Map(o),i=new Set;for(let s of r){let a=n.get(s)??{};i.add(Fo($o(a,s),a.name||s))}return i},Vl=(e,t)=>e.api_name.localeCompare(t.api_name)||String(e.name).localeCompare(String(t.name)),Wl="appbuilder/views-unmatched";function Kl(e,t){let r=No(t),o={},n=[];for(let i of e){let s=r.get(i.api_name),a=s===void 0?new Set:Hl(t,s),l=i.artifacts.routable_pages.filter(p=>a.has(Fo(p.api_name,p.name))).sort(Vl);l.length!==a.size&&s!==void 0&&n.push({rule:Wl,severity:"warning",message:`Found ${String(a.size)} ${Vr}/ components but matched ${String(l.length)} packaged views; the pushed block carries only the matched ones.`,path:Bo(s,Vr),pluginApiName:i.api_name}),o[i.api_name]=l}return{views:o,warnings:n}}function Jl(e,t){return Object.hasOwn(e,t)?e[t]??[]:[]}function jo(e){return{...e.block,...Or(e.views)}}async function Kr(e){let{files:t,deployable:r,issues:o}=await Hr(e),n=Kl(r,t);return{deployable:Ul(r,t),views:n.views,warnings:[...o.filter(i=>i.severity==="warning"),...n.warnings]}}function Jr({deployable:e,views:t,warnings:r},o,n){let i=Al(e,o);if(!i.ok)return{ok:!1,reason:i.reason,message:Ol(i,o,n),available:i.available};let s=Nl(i.block);if(s!==void 0)return{ok:!1,reason:"invalid_block",message:jl(i.block.api_name,s),available:[],field:s};let a=Jl(t,i.pluginApiName),l=Rl(a);return l!==void 0?{ok:!1,reason:"invalid_block",message:Fl(i.block.api_name,l),available:[],field:$l(l)}:{ok:!0,value:{block:i.block,pluginApiName:i.pluginApiName,views:a,warnings:r}}}async function Oo(e,t){let r=Jr(await Kr(e),t,"export");if(!r.ok)throw new Wr(r.reason,r.message,r);return r.value}var qr=(e,t,r)=>`${String(e)} ${e===1?t:r}`,Gr=e=>{let t=new Map;for(let r of e){let o=r.path??r.pluginApiName??"general",n=t.get(o)??[];n.push(r),t.set(o,n)}return t},ql=e=>{let t=e.filter(n=>n.severity==="error").length,r=e.length-t;if(t===0)return`\u26A0 ${qr(r,"validation warning","validation warnings")}`;let o=`\u2717 ${qr(t,"validation error","validation errors")}`;return r===0?o:`${o}, ${qr(r,"warning","warnings")}`};function xe(e){if(e.length===0)return"";let t=[...Gr(e)].map(([r,o])=>[r,...o.map(n=>` ${n.severity==="error"?"\u2717":"\u26A0"} ${n.message} (${n.rule})`)].join(`
|
|
4
|
+
`));return[ql(e),...t].join(`
|
|
5
|
+
|
|
6
|
+
`)}import{randomUUID as Nc}from"crypto";import{join as Bc}from"path";import{PluginValidationError as Rc}from"@kizenapps/packager";var Lo={go:"https://app.go.kizen.com/api",fmo:"https://app.fmo.kizen.com/api",staging:"https://staging.kizen.com/api",integration:"https://integration.kizen.dev/api",test1:"https://test1.kizen.dev/api"},zo={go:"https://go.kizen.com",fmo:"https://fmo.kizen.com",staging:"https://v2.staging.kizen.com",integration:"https://v2.integration.kizen.dev",test1:"https://test1.kizen.dev"},Gl=["go","fmo"];function Yr(e){return Gl.includes(e)}import{mkdir as Yl,readFile as Xl,writeFile as Zl}from"fs/promises";import{join as Mo}from"path";async function he(e){try{let t=await Xl(Mo(e,"config.json"),"utf-8");return JSON.parse(t)}catch{return{}}}async function Ie(e,t){await Yl(e,{recursive:!0}),await Zl(Mo(e,"config.json"),JSON.stringify(t,null,2),"utf-8")}import{mkdir as Uo,readFile as Ql,readdir as ec,writeFile as Ho}from"fs/promises";import{homedir as tc}from"os";import{dirname as rc,join as Mt}from"path";var Ue=Mt(tc(),".kizenappbuilder"),ve=Mt(Ue,"credentials.json"),De="credentials";function Vo(e){return Z.includes(e)}function nc(e){return typeof e=="string"?e.trim():e}function oc(e){return Vo(e)?"explicit":e==null||e===""?"missing":"invalid"}function ic(e){if(typeof e!="object"||e===null)throw new Error("Credentials must be a JSON object");let t=e,r=nc(t.environment);return{credentials:{...st(t),environment:Vo(r)?r:"go"},environmentSource:oc(r)}}async function Ut(e){let t=await Ql(e,"utf-8");return ic(JSON.parse(t))}async function Ae(e){return(await Ut(e)).credentials}async function re(){try{return await Ae(ve)}catch{return null}}async function sc(e){await Uo(rc(ve),{recursive:!0,mode:448}),await Ho(ve,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function Wo(e){return Mt(Ue,`${e}.json`)}async function Ne(){let e=[{name:De,path:ve,isDefault:!0}];try{let t=await ec(Ue);for(let r of t){if(!r.endsWith(".json"))continue;let o=r.slice(0,-5);o!==De&&e.push({name:o,path:Mt(Ue,r),isDefault:!1})}}catch{}return e}async function Ko(e,t){if(e===De){await sc(t);return}await Uo(Ue,{recursive:!0,mode:448}),await Ho(Wo(e),JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}async function ke(e){try{return await Ae(Wo(e))}catch{return null}}async function Jo(){let e=await Ne(),t=await Promise.all(e.map(r=>Ut(r.path).then(()=>!0,()=>!1)));return e.filter((r,o)=>t[o]===!0)}import*as Xe from"fs";import*as qo from"path";var ac=[".kizenapp/",".copilot-docs/"];function ge(e){let t=qo.join(e,".gitignore"),r="";Xe.existsSync(t)&&(r=Xe.readFileSync(t,"utf8"));let o=new Set(r.split(`
|
|
7
|
+
`).map(a=>a.trim())),n=ac.filter(a=>!o.has(a)&&!o.has(a.replace(/\/$/,"")));if(n.length===0)return;let i=n.join(`
|
|
4
8
|
`)+`
|
|
5
|
-
`,
|
|
9
|
+
`,s=r===""||r.endsWith(`
|
|
6
10
|
`)?i:`
|
|
7
|
-
`+i;Ae.writeFileSync(t,n+p)}function Er(e){e.command("build").description("Bundle the plugin app into .kizenapp directory").action(async()=>{let t=process.cwd(),n=`${t}/.kizenapp`;he(t);let{waitUntilExit:o}=yi(hi(Sr,{outputDir:n,pluginDir:t}));await o()})}import{createElement as ws}from"react";import{render as Cs}from"ink";import{useCallback as gt,useState as De}from"react";import{Box as M,Text as I,useApp as as,useInput as ls}from"ink";import{join as ht}from"path";import{access as ns,mkdir as dt,writeFile as Vt}from"fs/promises";import{dirname as os,join as ce}from"path";var _r=`{
|
|
11
|
+
`+i;Xe.writeFileSync(t,r+s)}var lc="The API key is invalid for this business, or the user id doesn't match. Check the credentials file's apiKey, userId and businessId.",cc="The API key's user needs the Standard API Keys permission and edit access to this dashboard. Homepages also need the Customize Homepages permission.",dc=100,uc=new Set(["detail","non_field_errors"]),ne=class extends Error{kind;status;hint;constructor(t,r,o={}){super(r),this.name="KizenApiError",this.kind=t,this.status=o.status,this.hint=o.hint}},lt=encodeURIComponent,ct=(e,t)=>t===void 0?`/dashboards/${lt(e)}/dashlet`:`/dashboards/${lt(e)}/dashlet/${lt(t)}`;function Xr(e,t,r){let o=n=>{r.push(t===""?n:`${t}: ${n}`)};if(typeof e=="string"){e.trim()!==""&&o(e);return}if(typeof e=="number"||typeof e=="boolean"){o(String(e));return}if(Array.isArray(e)){let n=e.filter(i=>typeof i=="string"&&i.trim()!==""||typeof i=="number"||typeof i=="boolean");n.length>0&&o(n.map(String).join(" "));for(let i of e)typeof i=="object"&&i!==null&&Xr(i,t,r);return}if(H(e))for(let[n,i]of Object.entries(e)){let s=t===""&&uc.has(n)?"":t===""?n:`${t}.${n}`;Xr(i,s,r)}}function pc(e){if(typeof e!="object"||e===null)return;let t=[];return Xr(e,"",t),t.length>0?t.join("; "):void 0}function Go(e){let t=e;return t.cause?.code??t.code??t.cause?.message??t.message??String(e)}async function fc(e){let t=await e.text();if(t==="")return{text:t,json:void 0};try{return{text:t,json:JSON.parse(t)}}catch{return{text:t,json:void 0}}}function mc(e,t,r,o){let n=pc(o),i=`${e} ${t} failed with ${String(r)}${n===void 0?"":`: ${n}`}`;return r===401?new ne("auth_failed",i,{status:r,hint:lc}):r===403?new ne("forbidden",i,{status:r,hint:cc}):r===404?new ne("not_found",i,{status:r}):new ne("api_error",i,{status:r})}function Yo(e,t,r){if(Array.isArray(r))return{results:r,next:null};if(H(r)&&Array.isArray(r.results))return{results:r.results,next:r.next};throw new ne("api_error",`${e} ${t} returned an unexpected response shape`)}function Xo(e){let{credentials:t}=e,r=e.fetch??fetch,o=e.baseUrl??Lo[t.environment],n=async(s,a,l)=>{let p=/^https?:\/\//.test(a)?a:`${o}${a}`,g=p.startsWith(o)?p.slice(o.length):p,v={"X-API-KEY":t.apiKey,"X-USER-ID":t.userId,"X-BUSINESS-ID":t.businessId,Accept:"application/json"},k={method:s,headers:v};l!==void 0&&(v["Content-Type"]="application/json",k.body=JSON.stringify(l));let f;try{f=await r(p,k)}catch(x){throw new ne("network_error",`Couldn't reach Kizen at ${o}: ${Go(x)}${Dt()==="unavailable"?` ${It}`:""}`)}let c,h;try{({text:c,json:h}=await fc(f))}catch(x){throw new ne("network_error",`${s} ${g}: couldn't read the response: ${Go(x)}. The request may have been applied; check Kizen before retrying.`,{status:f.status})}if(!f.ok)throw mc(s,g,f.status,h);if(h===void 0&&c!=="")throw new ne("api_error",`${s} ${g} returned a response that is not JSON`,{status:f.status});return h},i=s=>{let a=new URL(o),l=new URL(s,a.origin);if(l.hostname!==a.hostname)throw new ne("api_error",`GET /custom-objects pagination pointed at an unexpected host ${l.hostname}`);return new URL(`${l.pathname}${l.search}`,a.origin).toString()};return{async listDashboards(s,a){let l=new URLSearchParams({size:"10000",include_sharing:"true",dashboard_type:s});a!==void 0&&l.set("custom_object_id",a);let p=`/dashboards/mine?${l.toString()}`;return Yo("GET",p,await n("GET",p)).results},async listCustomObjects(){let s=[],a=new Set,l="/custom-objects?page_size=200";for(;l!==void 0&&!a.has(l)&&a.size<dc;){a.add(l);let p=Yo("GET",l,await n("GET",l));s.push(...p.results),l=typeof p.next=="string"&&p.next!==""?i(p.next):void 0}return s},async getCustomObject(s){let a=`/custom-objects/${lt(s)}`,l=await n("GET",a);if(!H(l)||typeof l.id!="string"||typeof l.fetch_url!="string")throw new ne("api_error",`GET ${a} returned an unexpected response shape`);return l},async getClientObjectId(){let s=await n("GET","/auth/bootstrap"),a=H(s)?s.business:void 0,l=H(a)?a.client_object:void 0,p=H(l)?l.id:void 0;return typeof p=="string"&&p!==""?p:null},async getDashboard(s){return await n("GET",`/dashboards/${lt(s)}`)},async createDashlet(s,a){return await n("POST",ct(s),a)},async updateDashlet(s,a,l){return await n("PATCH",ct(s,a),l)}}}import{join as qt}from"path";var Zo="---\nname: kizen-custom-block\ndescription: Use this skill when the user asks to build, change or publish a Kizen content block, custom block, chart, or dashboard/homepage visualization in this plugin. It covers the block file layout, the plugin engine runtime rules, and the appbuilder validate, preview and push loop.\n---\n\n# Kizen custom blocks\n\nFollow these rules exactly. The runtime is strict, and a push changes a live Kizen dashlet.\n\n## Keep this skill current\n\nAt the start of any block task, run `appbuilder setup-claude --include-lib` in the plugin directory.\n\n- If it reports `updated` for `.claude/skills/kizen-custom-block/SKILL.md`, your loaded copy of this skill is stale. Re-read `.claude/skills/kizen-custom-block/SKILL.md` before doing anything else, and follow the new copy.\n- If it reports `created` for any file, or `updated` for `.claude/skills/kizen-custom-block/design.md`, read that file before writing any markup or styles.\n- If it reports `created` or `updated` for `lib/kizenData.js` (under the plugin's entry directory, usually `src/`), re-read its exports before using them.\n- If every file line reports `unchanged`, continue.\n- If the command doesn't exist (an older CLI), skip it and continue.\n- If it fails (for example, you aren't in the plugin directory that holds `kizen.json`), switch to that directory and run it once more. If it still fails, continue without it.\n\n`setup-claude` only rewrites the CLI-managed files: the ones in this skill directory and `src/lib/kizenData.js`. It never touches block code, so it's always safe to run.\n\n## What a block is\n\nA block is a directory under `src/blocks/<dir>/`:\n\n- `config.json` (required): `name`, `api_name` (always set it explicitly), `types` (any of `homepages`, `dashboards`, `charts` for chart groups, and `records`; a block only appears on the surfaces it lists), and the optional sizes `min_w`, `max_w`, `min_h`, `max_h`, `default_w` and `default_h`. Widths are grid columns (1 to 12) and heights are grid rows. Each size you set is a positive integer, each `min_*` is no greater than its `max_*`, and each `default_*` falls within whichever of its `min_*` and `max_*` you set. `default_w` and `default_h` are the starting size when `block push` creates a new dashlet; updates never resize an existing dashlet. Only the sizes you write are exported and pushed.\n - `host_chrome` (optional boolean, default `true`): whether the host paints the dashlet card around the block. Omit it unless you are turning chrome off. Only a value you write is exported and pushed, and any value other than `true` or `false` fails validation.\n- `script.js` (required): the render script.\n- `styles.css` (optional).\n- `eventScripts/<name>.js` (optional): one file per interactive handler.\n\nShared helpers live in `src/lib/*.js`. Import them with relative named imports only, for example `import { formatMoney } from '../../lib/format.js';`. No default imports, no bare package names.\n\n`src/lib/kizenData.js` is managed by appbuilder: `setup-claude` and CLI updates replace it. Never edit it. Put your own helpers in another file under `src/lib/`.\n\n### Host chrome\n\nDecide the mode yourself from the request. Ask the user only if they already raised it and their choice is unclear.\n\n- Keep host chrome (omit `host_chrome`) for standard data dashlets such as charts, KPIs, tables and lists that should match native cards.\n- Set `\"host_chrome\": false` for full-bleed heroes, imagery, custom-shaped cards, or any design whose background is part of the visual.\n\nChrome off, in `config.json`:\n\n```json\n{\n \"name\": \"Welcome hero\",\n \"api_name\": \"welcome_hero\",\n \"types\": [\"homepages\", \"dashboards\"],\n \"host_chrome\": false\n}\n```\n\nFollow \"Chrome off\" in `design.md` for the layout rules. In your summary to the user, state which mode you chose and why in one line. `block push --dry-run --json` shows the value as `body.config.content.host_chrome` (absent when chrome is on by default), so check it there. Changing `host_chrome` on a block you already pushed is an ordinary update: validate, then `block push <api_name> --yes --json`.\n\n## Runtime rules\n\nBlocks run in the plugin engine web worker.\n\n- `script.js` is the body of an async function, and `this` is the worker context. Use `await` at the top level.\n- There is no DOM: no `document` or `window`. There are no npm packages. Don't use `eval` or `Function`.\n- Render with `this.outputUI(htmlString)`. The output is sanitized with DOMPurify, so `<script>` tags and `on*` attributes are stripped. Don't rely on them.\n- Charts are hand-built inline SVG strings. There are no chart libraries.\n- Interactivity: put `data-script=\"<eventScriptName>\"` on a `<button>` whose content is text only. Clicking it runs `eventScripts/<eventScriptName>.js` in a fresh worker, so no state carries over from `script.js`.\n- Args:\n - `this.args.dateFilter`: `{ start, end }`, or `undefined`.\n - `this.args.teamFilter`.\n - `this.args.objectId`: set on chart groups.\n - Homepages have no date or team filter. Handle both being absent.\n- Data: read records with the `kizenData.js` helpers (see \"Reading Kizen data\"). They call `this.getWithErrors` and `this.postWithErrors`, which use relative URLs and run as the viewing user.\n- Toasts: `this.showToast(message, options)`. `message` MUST be a string. Passing an object crashes the host app.\n- Styling:\n - The host applies `* { font-size: 10px }`. Set explicit px font sizes on everything.\n - With host chrome (the default), the host paints the card (background, border, border radius and shadow) from the dashboard's style settings, like native dashlets. The block root is transparent, fills the card, and paints no card of its own.\n - With `\"host_chrome\": false`, the host paints nothing: no background, border, radius or shadow. The block root fills the card edge to edge and owns its whole look (see \"Chrome off\" in `design.md`).\n - Put chart labels inside the SVG as `<text>` so they scale with the `viewBox`.\n- The code is stored in a Kizen dashlet. Never include a NUL character or the literal text `{__ref:` anywhere in any file.\n\n## Reading Kizen data\n\nRead records through `src/lib/kizenData.js`. Always import it from `../../lib/kizenData.js`. Its helpers take the worker context as their first argument, so pass `this`.\n\n- `getFields(this, object)` loads an object's fields. `object` is the object's id or name, and Contacts is `client_client`. Match fields by `name`.\n- `blockFilters(this.args, fields)` returns `{ filters, unapplied }`. Always apply `filters`, so the block reacts to the dashboard's date and team filters the way native dashlets do (date on `created`, team on `owner`). When `unapplied` contains `'teamFilter'`, the team filter couldn't be applied (a roles-only selection, or an object with no owner field). Show \"(team filter not applied)\".\n- `dropdownFilter(field, 'Name')` or `dropdownFilter(field, ['A', 'B'])` filters a dropdown by option names.\n- `searchRecords(this, { object, fieldNames, filters })` returns `{ records, count, truncated }`. When `truncated` is true, show \"Showing first N\" with N = `records.length`.\n- `fieldValue(record, name)`, `fieldLabel(record, name)`, `countBy(records, name, field?)`, `sumBy(records, name, valueOf?)` and `formatNumber(n, prefix)` read and summarize the results. `countBy` groups empty values under `key: ''`. Filter that group out, or give it a label.\n- Every record value or label you put into markup goes through `escapeHtml(value)`, including option names, owner names and text fields. `this.outputUI` sanitizes scripts, but it keeps images, links, forms and styles, and the block renders for every viewer. `escapeHtml` is the only escaping helper; never write your own.\n- Never hand-build filter or search JSON when a helper exists. Every helper throws a readable `Error`, so wrap the fetch in `try` and render the error state from `design.md`.\n\nCount Contacts by a dropdown field named `status` for the current dashboard filters. Use a field name from `getFields`:\n\n```js\nimport {\n blockFilters,\n countBy,\n escapeHtml,\n getFields,\n searchRecords,\n} from '../../lib/kizenData.js';\n\ntry {\n const fields = await getFields(this, 'client_client');\n const { filters, unapplied } = blockFilters(this.args, fields);\n const search = { object: 'client_client', fieldNames: ['status'], filters };\n const { records, count, truncated } = await searchRecords(this, search);\n const rows = countBy(records, 'status').filter((row) => row.key !== '');\n const items = rows.map((row) => `<li>${escapeHtml(row.label)}: ${row.count}</li>`).join('');\n const note = truncated ? `Showing first ${records.length} of ${count}. ` : '';\n const team = unapplied.includes('teamFilter') ? '(team filter not applied)' : '';\n this.outputUI(`<ul>${items}</ul><p>${note}${team}</p>`);\n} catch {\n this.outputUI('<div class=\"kz-state kz-state--error\">Couldn\\'t load data.</div>');\n}\n```\n\n## Design\n\nBefore writing any markup or styles, read `design.md` in this skill directory and follow it exactly.\n\n## The loop\n\nRun these exact commands. The flags and JSON keys are the contract. `<api_name>` is the block's `config.json` `api_name`. `block targets` and `block push` both accept `-c/--credentials <path>` and `--profile <name>` to pick the credential.\n\n1. **Validate.** Run `appbuilder block export <api_name>`. Fix every validation error it prints, then run it again until it passes.\n2. **Choose the target with the user (first publish only).**\n - `appbuilder block targets --json` returns `{ surfaces: { dashboard: [...], homepage: [...] }, customObjects: [{ id, objectName, fetchUrl }] }`. Contacts appears in `customObjects` when available.\n - `appbuilder block targets --object <id> --json` returns `{ surfaces: { chart_group: [...] } }` for that object.\n - Only offer rows where `canEdit !== false`. Ask the user which surface and which specific one. Don't pick for them.\n - Optionally run `appbuilder block push <api_name> --dashboard <id> --json` to get a `needs_choice` result listing the existing custom blocks and \"new\".\n3. **Preview.** Run `appbuilder block push <api_name> --dashboard <id> [--dashlet <id> | --create] --dry-run --json`. Show the user the `environment`, `businessId`, `dashboard.name`, `action` and any `warnings`.\n4. **Apply** once the user agrees: run the same command with `--yes` in place of `--dry-run`. Treat the push as done only when `applied === true`. Give the user the returned `url`, then refresh the browser (below).\n5. **Change requests.** Edit the files, validate again (step 1), then run `appbuilder block push <api_name> --yes --json`. With no target flags it updates the remembered dashlet. Refresh the browser (below) after each push. Repeat for each change.\n\nA headless run without `--yes` is always a dry run.\n\n### Refresh the browser after a push\n\nDo this after every applied push, only when Claude-in-Chrome tools are available. Dashlets don't poll, so the user's open tab keeps the old block until it's refreshed. Don't reload the page.\n\n1. List the open tabs (`tabs_context_mcp`) and find the one whose URL has the same origin and path as the result's `url`.\n2. If there is no such tab, open `url` in a new tab (`tabs_create_mcp`) and go to step 5.\n3. If the result has a `refresh` field, run `refresh.script` exactly as given in that tab with the page JavaScript tool (`javascript_tool`). If it has no `refresh` field, navigate that tab to `url` (`navigate`) and go to step 5.\n4. Check what the script returned:\n - `{ refreshed: true, ... }`: the dashboard refetched in place.\n - `undefined`: the refresh hook isn't available on this page (an older Kizen build, or a page without the hook). Navigate the tab to `url` instead.\n5. Wait a couple of seconds, take a screenshot (`computer`), and check that the block rendered: not blank, and no visible error. Report what you saw to the user. If the block is blank or shows an error, read the console and fix the block before pushing again.\n\nNever run any other injected code in the user's tabs. `refresh.script` is the only script you may run.\n\n### JSON results\n\n- Dry run: `{ ok: true, applied: false, dryRun: true, action: 'create' | 'update', environment, businessId, dashboard: { id, name, type }, dashletId | null, url, method, path, body, warnings }`.\n- Applied: `{ ok: true, applied: true, dryRun: false, action: 'created' | 'updated', ..., dashletId, url, refresh?: { dashboardId, script }, remembered }`. `refresh` is absent when the dashboard id isn't a uuid.\n- If a `block push` result's `warnings` contains `Claude files managed by appbuilder are out of date; run appbuilder setup-claude`, run `appbuilder setup-claude --include-lib`, re-read `.claude/skills/kizen-custom-block/SKILL.md`, then continue.\n- Error: `{ ok: false, code, message, choice?, choices? }`. `code` is one of `needs_choice`, `validation_failed`, `invalid_block`, `auth_failed`, `forbidden`, `remembered_target_missing`, `drift_detected`, `network_error`, `credentials_invalid`, `production_requires_flag`, `not_found`, `usage_error`, `api_error` or `local_error`.\n\n### `needs_choice`\n\n`choice` is `'profile'`, `'block'`, `'dashboard'` or `'target'`. `choices` is a list of `{ value, label, args, surface?, canEdit?, pushKey?, isFromThisPlugin? }`, where `args` is a string array. Ask the user using each option's `label`, then re-run the same command with the chosen option's `args` appended exactly. Never construct these flags by hand. The \"new\" option is `{ value: 'new', args: ['--dashboard', <id>, '--create'] }`.\n\n## Guardrails\n\n- Never pass `--allow-production` unless the user explicitly asked, in this conversation, to publish to production (`go` or `fmo`).\n- On `drift_detected`, stop and ask the user. Someone edited the block in Kizen since your last push, and `--force` overwrites their changes. Pass `--force` only when the user says to discard them.\n- On `needs_choice`, ask the user using the returned `choices` as described above. Never guess.\n- On `remembered_target_missing`, the remembered dashboard or dashlet is gone. Ask the user where to publish instead, then push with `--dashboard <id>` plus `--create` or a `--dashlet` choice, or use `--forget` to clear the memory. `--create` alone won't work.\n- On `credentials_invalid`, tell the user to fix the credential file named in `message`, or to pass `--profile` or `-c`.\n- On `production_requires_flag`, the target is `go` or `fmo`. Apply the production rule above.\n- Never push to a new target without first showing the user a dry run.\n- Blocks run with the viewing user's permissions for every viewer. Don't write code that creates, updates or deletes data unless the user asked for it.\n";var Qo=`# Designing a Kizen custom block
|
|
12
|
+
|
|
13
|
+
With host chrome (the default), a block must look like a native Kizen dashlet. Follow every rule here exactly. Where a rule says "use judgment", pick the option that looks most native. A block whose \`config.json\` sets \`"host_chrome": false\` follows section M for its card and outer box, and skips every rule marked "with host chrome".
|
|
14
|
+
|
|
15
|
+
## A. Card and outer box (with host chrome)
|
|
16
|
+
|
|
17
|
+
The host paints the card. Background, border, border radius and drop shadow all come from the dashboard's style settings, the same as native dashlets.
|
|
18
|
+
|
|
19
|
+
- Never paint a card. The block root has no background (it stays transparent), no border, no \`border-radius\`, no \`box-shadow\` and no outer margin.
|
|
20
|
+
- The block's content box starts at the card's top-left corner (0,0) and fills the whole card. The host body padding is 0. The root is always \`width: 100%; height: 100%; box-sizing: border-box;\`.
|
|
21
|
+
- The host draws a 46px header overlay (\`position: absolute\`, padding \`11px 15px 15px\`) over the block's top edge. The dashlet menu appears at its top right on hover. The top-right strip, 60px wide and 46px tall from the card's top edge, must hold no interactive controls and no text. Non-interactive chart marks may pass under it.
|
|
22
|
+
- The native grid has a 10px gap between cards and around the grid. Row height is 105px (100px at the mobile, 2-column breakpoint), so a card is \`rows * 105 + (rows - 1) * 10\` px tall. Width depends on the breakpoint's column count.
|
|
23
|
+
- Blocks are fluid. Never assume a pixel size. Use percentages, flex or grid, and an SVG \`viewBox\`.
|
|
24
|
+
- Set \`default_w\` (columns) and \`default_h\` (rows) in \`config.json\` so the content fits comfortably at its starting size: roughly 3\xD72 for a KPI tile, 6\xD74 for a chart, and 6\xD75 for a table or list. A card \`rows\` tall is \`rows * 105 + (rows - 1) * 10\` px, so 2 rows is 220px, 4 rows is 440px and 5 rows is 565px. Keep each default within any \`min_*\` and \`max_*\` the block sets.
|
|
25
|
+
|
|
26
|
+
## B. Inner spacing
|
|
27
|
+
|
|
28
|
+
With host chrome, measure these insets from the card's edge. With chrome off, measure them from the edge of the block-owned card, or follow section M for full bleed.
|
|
29
|
+
|
|
30
|
+
- Horizontal inset: 15px left and right, matching the native body padding \`0 15px\`.
|
|
31
|
+
- With a header, use the native header band (section C). Content under a header starts at 35px from the top. The header overlay still covers the card down to 46px, so the top-right strip 60px wide from 35px to 46px must hold no interactive controls or text.
|
|
32
|
+
- Without a header, use 15px top padding. The same top-right strip, 60px wide down to 46px, stays free of controls and text.
|
|
33
|
+
- Bottom padding: 15px.
|
|
34
|
+
- Major gaps use 15px: between a KPI value and its comparison row, and between sections.
|
|
35
|
+
- Minor gaps use 10px: legend rows, list-row vertical padding, and the padding above a legend.
|
|
36
|
+
|
|
37
|
+
\`\`\`css
|
|
38
|
+
.kz-block {
|
|
39
|
+
box-sizing: border-box;
|
|
40
|
+
width: 100%;
|
|
41
|
+
height: 100%;
|
|
42
|
+
padding: 15px;
|
|
43
|
+
display: flex;
|
|
44
|
+
flex-direction: column;
|
|
45
|
+
font-family: var(--font-family-sans-serif);
|
|
46
|
+
color: var(--color-font-primary);
|
|
47
|
+
}
|
|
48
|
+
.kz-block--with-header {
|
|
49
|
+
padding-top: 0;
|
|
50
|
+
}
|
|
51
|
+
\`\`\`
|
|
52
|
+
|
|
53
|
+
## C. Header (optional; use judgment)
|
|
54
|
+
|
|
55
|
+
A block doesn't need a header, and it may use a different kind of header when the content calls for one. When it shows a native-style title, match native exactly:
|
|
56
|
+
|
|
57
|
+
- A band 35px tall with padding \`7.5px 60px 7.5px 15px\`. The 60px right padding keeps long titles out from under the hover menu.
|
|
58
|
+
- Title text 12px, weight 100 (Proxima Nova Light), \`text-transform: uppercase\`, \`color: var(--color-font-primary)\`, \`line-height: 20px\`, left-aligned at 15px.
|
|
59
|
+
- Blocks can't read per-dashboard title-style settings, so always use these defaults.
|
|
60
|
+
- Copy \`.kz-header\` from the example below. Its \`margin: 0 -15px\` cancels the root's side padding so the title lands at 15px.
|
|
61
|
+
|
|
62
|
+
## D. Typography
|
|
63
|
+
|
|
64
|
+
- Font: Proxima Nova through \`font-family: var(--font-family-sans-serif)\`. The host already loads it.
|
|
65
|
+
- The host applies \`* { font-size: 10px; line-height: 1 }\`. Set an explicit px \`font-size\` on every text element.
|
|
66
|
+
- Scale (px): hero 32, header 24, subheader 18, body 14, button 13, label 12, small 11, micro 10.
|
|
67
|
+
- Weights: 100 light, 400 regular, 600 bold, 900 black.
|
|
68
|
+
- Text colors: \`var(--color-font-primary)\` (#4A5660) for primary text, \`var(--color-font-secondary)\` (#7E8C98) for secondary text, \`var(--color-font-placeholder)\` (#A8B3BC) for muted text and captions.
|
|
69
|
+
- Header titles and category or axis labels are uppercase. Legend labels use sentence case.
|
|
70
|
+
|
|
71
|
+
## E. Color tokens
|
|
72
|
+
|
|
73
|
+
Always use CSS custom properties. Never write raw hex, because themes can change the values. The hex values below are reference only.
|
|
74
|
+
|
|
75
|
+
| Use | Token | Default |
|
|
76
|
+
| ------------------------ | -------------------------------------------- | ------- |
|
|
77
|
+
| Surface | \`--color-background-white\` | #FFFFFF |
|
|
78
|
+
| Surface | \`--color-background-light\` | #F5F6F7 |
|
|
79
|
+
| Surface | \`--color-background-lighter\` | #F9FAFB |
|
|
80
|
+
| Surface | \`--color-background-medium\` | #D8DDE1 |
|
|
81
|
+
| Surface | \`--color-background-dark\` | #A8B3BC |
|
|
82
|
+
| Surface | \`--color-background-darker\` | #4A5660 |
|
|
83
|
+
| Surface | \`--color-background-hover\` | #D8EAFD |
|
|
84
|
+
| Border, divider | \`--color-border-medium\` | #D8DDE1 |
|
|
85
|
+
| Border, divider | \`--color-border-medium-light\` | #ECEEF0 |
|
|
86
|
+
| Border, divider | \`--color-border-light\` | #F5F6F7 |
|
|
87
|
+
| Links, secondary actions | \`--color-button-secondary-default\`, \`-hover\` | #4090F7 |
|
|
88
|
+
| Primary actions | \`--color-button-primary-default\`, \`-hover\` | #4BC7B4 |
|
|
89
|
+
| Status good | \`--color-viz-cat-1-primary\` | #32C055 |
|
|
90
|
+
| Status bad | \`--color-viz-cat-7-primary\` | #EB272B |
|
|
91
|
+
|
|
92
|
+
Color SVG through CSS classes in \`styles.css\`, for example \`.bar-1 { fill: var(--color-viz-cat-1-primary); }\`. Never use \`fill="var(...)"\` attributes; they aren't reliable.
|
|
93
|
+
|
|
94
|
+
## F. Charts
|
|
95
|
+
|
|
96
|
+
Native dashlets use amCharts 5. Blocks hand-build SVG that mimics it.
|
|
97
|
+
|
|
98
|
+
- Series palette, in order: \`--color-viz-cat-N-primary\` for N = 1 to 10 (the tokens native charts read). The paired light shade \`--color-viz-cat-N-secondary\` is for backgrounds, tracks and comparison series.
|
|
99
|
+
- Defaults (primary / secondary): 1 #32C055 / #ADE6BB, 2 #285DE4 / #6FB2F9, 3 #F3A800 / #FADC99, 4 #4926CC / #B7A6EA, 5 #38B3B9 / #9BD9DB, 6 #F26C56 / #F4A63A, 7 #EB272B / #FF8A8A, 8 #D100A0 / #FF85E2, 9 #AE764A / #D6BAA4, 10 #7A7A7A / #BCBCBC.
|
|
100
|
+
- Axis labels: \`fill: var(--color-background-dark)\`, 10 to 11 user units, small and muted.
|
|
101
|
+
- Gridlines: \`stroke: var(--color-border-medium-light)\`, 1px.
|
|
102
|
+
- Tooltip, if you draw one: background \`var(--color-background-darker)\`, text \`var(--color-background-white)\`.
|
|
103
|
+
- Donut: 2px white gaps between segments (\`stroke: var(--color-background-white); stroke-width: 2;\`).
|
|
104
|
+
- Dashed forecast or incomplete segments: \`stroke-dasharray: 4 4;\`.
|
|
105
|
+
- Legend: 8px circular dots, 10px gap to a 10px label, 20px column gap between items, 10px row gap when wrapping, 10px padding above the legend.
|
|
106
|
+
- Put chart labels inside the SVG as \`<text>\` so they scale with the \`viewBox\`.
|
|
107
|
+
|
|
108
|
+
## G. KPI tiles
|
|
109
|
+
|
|
110
|
+
The value is hero 32px, weight 400, \`var(--color-font-primary)\`, centered when it stands alone. A comparison or delta row sits 15px below it, \`var(--color-viz-cat-1-primary)\` when good and \`var(--color-viz-cat-7-primary)\` when bad.
|
|
111
|
+
|
|
112
|
+
## H. Number formatting
|
|
113
|
+
|
|
114
|
+
Match the native \`collapseNumber\` rules:
|
|
115
|
+
|
|
116
|
+
- Not a number: \`0\`.
|
|
117
|
+
- |n| < 1: up to 4 decimals, trailing zeros removed.
|
|
118
|
+
- |n| < 1,000: up to 5 significant digits, trailing zeros removed.
|
|
119
|
+
- 1,000 to 9,999: an integer with a thousands separator.
|
|
120
|
+
- 10,000 and up: round to 4 significant digits first, then show K, M or B.
|
|
121
|
+
- 1 trillion and up: \`999B+\`, with no sign.
|
|
122
|
+
- Currency: prefix the symbol, for example \`$\`.
|
|
123
|
+
|
|
124
|
+
Never copy or rewrite this helper. Import it from the CLI-managed data lib:
|
|
125
|
+
|
|
126
|
+
\`\`\`js
|
|
127
|
+
import { formatNumber } from '../../lib/kizenData.js';
|
|
128
|
+
\`\`\`
|
|
129
|
+
|
|
130
|
+
## I. States
|
|
131
|
+
|
|
132
|
+
- Loading: a centered, subtle "Loading\u2026" line on a transparent background (with chrome off, on whatever background the block paints). Render it with \`this.outputUI\` first, before any data fetch.
|
|
133
|
+
- Empty: centered "No Data", 32px, \`color: var(--color-background-medium)\`.
|
|
134
|
+
- Error: a centered 14px message in \`var(--color-font-secondary)\`, for example "Couldn't load data." Never show raw error objects.
|
|
135
|
+
|
|
136
|
+
## J. Icons
|
|
137
|
+
|
|
138
|
+
Inline SVG only, with \`fill: currentColor\` or a token applied through a class. Icon fonts and host icon classes aren't available.
|
|
139
|
+
|
|
140
|
+
## K. Scrollbars
|
|
141
|
+
|
|
142
|
+
Every scroll container uses the app's expanding scrollbar. Add the \`kds-expanding-scrollbar\` class to the element that scrolls, for example \`<div class="kz-list kds-expanding-scrollbar">\`. The host finds these containers on its own, including ones that render later, and attaches the native thin bar that widens on hover.
|
|
143
|
+
|
|
144
|
+
- Put the class on the element that has \`overflow: auto\`, not on its parent. Give that element a bounded height, usually a flex child with \`flex: 1; min-height: 0\`.
|
|
145
|
+
- Never style scrollbars yourself: no \`::-webkit-scrollbar\` rules, \`scrollbar-width\` or \`scrollbar-color\`.
|
|
146
|
+
- Only scroll when the content really is a list. Otherwise fit the content to the card.
|
|
147
|
+
|
|
148
|
+
## L. Don'ts
|
|
149
|
+
|
|
150
|
+
- With host chrome, don't paint an outer card, shadow or border.
|
|
151
|
+
- Don't use fixed pixel widths.
|
|
152
|
+
- Don't use raw hex colors.
|
|
153
|
+
- Don't use \`em\` or \`rem\` units. The base is 10px, so they surprise.
|
|
154
|
+
- Don't load custom web fonts.
|
|
155
|
+
- Don't put content under the top-right menu area.
|
|
156
|
+
- Don't add a scroll container without \`kds-expanding-scrollbar\` (section K).
|
|
157
|
+
|
|
158
|
+
## M. Chrome off (\`"host_chrome": false\`)
|
|
159
|
+
|
|
160
|
+
The host paints no background, border, radius or shadow. The block root is still \`width: 100%; height: 100%; box-sizing: border-box;\` and starts at the card's top-left corner (0,0) with no host padding. Pick one of these layouts:
|
|
161
|
+
|
|
162
|
+
- Transparent full bleed: the root fills the card edge to edge and the dashboard background shows through wherever the block paints nothing. Use it for heroes and imagery, for example a \`background-image\` with \`background-size: cover\` on the root.
|
|
163
|
+
- Block-owned card: the block paints its own card with its own background, \`border-radius\`, border and \`box-shadow\`, using tokens. The host card still clips at its edges (\`overflow: hidden\`), so inset the card from the root by at least its shadow's blur plus offset, usually 8 to 12px (for example \`padding: 10px\` on the root with the card inside). A card with no inset loses its shadow.
|
|
164
|
+
|
|
165
|
+
The host adds no backdrop behind its controls, so keep two areas visually quiet, with no dark or busy art directly under them:
|
|
166
|
+
|
|
167
|
+
- The top-right menu strip, 60px wide and 46px tall. It still holds no interactive controls and no text.
|
|
168
|
+
- The top-left drag-handle area in edit mode, about 30px square. The handle icon sits 5px from the left and 10px from the top and is 15px tall.
|
|
169
|
+
|
|
170
|
+
Section A's grid, fluid-size and default-size rules, section C (when you show a native-style header), sections D to K and the rest of section L still apply. Inside a block-owned card, use section B's spacing.
|
|
171
|
+
|
|
172
|
+
## Example: header, bar chart and legend
|
|
173
|
+
|
|
174
|
+
The block counts Contacts by their \`status\` dropdown for the current dashboard filters, with the helpers from \`src/lib/kizenData.js\` (see "Reading Kizen data" in \`SKILL.md\`). Swap \`OBJECT\` and \`FIELD\` for the object and field the user asked about. The chart's only text is the y-axis labels at the left edge and the category labels along the bottom, so nothing lands in the top-right strip under the menu.
|
|
175
|
+
|
|
176
|
+
\`script.js\`:
|
|
177
|
+
|
|
178
|
+
\`\`\`js
|
|
179
|
+
import {
|
|
180
|
+
blockFilters,
|
|
181
|
+
countBy,
|
|
182
|
+
escapeHtml,
|
|
183
|
+
fieldByName,
|
|
184
|
+
formatNumber,
|
|
185
|
+
getFields,
|
|
186
|
+
searchRecords,
|
|
187
|
+
} from '../../lib/kizenData.js';
|
|
188
|
+
|
|
189
|
+
const OBJECT = 'client_client';
|
|
190
|
+
const FIELD = 'status';
|
|
191
|
+
|
|
192
|
+
const render = (body) =>
|
|
193
|
+
this.outputUI(
|
|
194
|
+
\`<div class="kz-block kz-block--with-header"><div class="kz-header">Contacts by status</div>\${body}</div>\`,
|
|
195
|
+
);
|
|
196
|
+
|
|
197
|
+
render('<div class="kz-state">Loading\u2026</div>');
|
|
198
|
+
|
|
199
|
+
let rows;
|
|
200
|
+
let notes;
|
|
201
|
+
try {
|
|
202
|
+
const fields = await getFields(this, OBJECT);
|
|
203
|
+
const field = fieldByName(fields, FIELD);
|
|
204
|
+
if (!field) throw new Error(\`\${OBJECT} has no \${FIELD} field\`);
|
|
205
|
+
const { filters, unapplied } = blockFilters(this.args, fields);
|
|
206
|
+
const { records, count, truncated } = await searchRecords(this, {
|
|
207
|
+
object: OBJECT,
|
|
208
|
+
fieldNames: [FIELD],
|
|
209
|
+
filters,
|
|
210
|
+
});
|
|
211
|
+
rows = countBy(records, FIELD, field).filter((row) => row.key !== '');
|
|
212
|
+
notes = [
|
|
213
|
+
truncated ? \`Showing first \${formatNumber(records.length)} of \${formatNumber(count)}\` : '',
|
|
214
|
+
unapplied.includes('teamFilter') ? '(team filter not applied)' : '',
|
|
215
|
+
].filter(Boolean);
|
|
216
|
+
} catch {
|
|
217
|
+
render('<div class="kz-state kz-state--error">Couldn\\'t load data.</div>');
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
if (rows.length === 0) {
|
|
222
|
+
render('<div class="kz-state kz-state--empty">No Data</div>');
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const W = 300,
|
|
227
|
+
H = 150,
|
|
228
|
+
left = 36,
|
|
229
|
+
top = 6,
|
|
230
|
+
bottom = 18;
|
|
231
|
+
const plot = H - top - bottom;
|
|
232
|
+
const max = Math.max(...rows.map((r) => r.count)) || 1;
|
|
233
|
+
const y = (v) => top + plot - (v / max) * plot;
|
|
234
|
+
const step = (W - left) / rows.length;
|
|
235
|
+
const barW = Math.min(20, step / 2);
|
|
236
|
+
|
|
237
|
+
const grid = [0, 0.5, 1]
|
|
238
|
+
.map((f) => f * max)
|
|
239
|
+
.map(
|
|
240
|
+
(t) =>
|
|
241
|
+
\`<line class="grid" x1="\${left}" x2="\${W}" y1="\${y(t)}" y2="\${y(t)}"/>\` +
|
|
242
|
+
\`<text class="axis" x="\${left - 6}" y="\${y(t) + 3}" text-anchor="end">\${formatNumber(t)}</text>\`,
|
|
243
|
+
)
|
|
244
|
+
.join('');
|
|
245
|
+
|
|
246
|
+
const bars = rows
|
|
247
|
+
.map((r, i) => {
|
|
248
|
+
const cx = left + i * step + step / 2;
|
|
249
|
+
return (
|
|
250
|
+
\`<rect class="bar" x="\${cx - barW / 2}" y="\${y(r.count)}" width="\${barW}" height="\${top + plot - y(r.count)}"/>\` +
|
|
251
|
+
\`<text class="axis" x="\${cx}" y="\${H - 4}" text-anchor="middle">\${escapeHtml(r.label)}</text>\`
|
|
252
|
+
);
|
|
253
|
+
})
|
|
254
|
+
.join('');
|
|
255
|
+
|
|
256
|
+
render(
|
|
257
|
+
\`<div class="kz-chart"><svg viewBox="0 0 \${W} \${H}">\${grid}\${bars}</svg></div>\` +
|
|
258
|
+
'<div class="kz-legend">' +
|
|
259
|
+
'<span class="kz-legend__item"><span class="kz-dot"></span>Contacts</span>' +
|
|
260
|
+
notes.map((note) => \`<span class="kz-note">\${escapeHtml(note)}</span>\`).join('') +
|
|
261
|
+
'</div>',
|
|
262
|
+
);
|
|
263
|
+
\`\`\`
|
|
264
|
+
|
|
265
|
+
\`styles.css\`:
|
|
266
|
+
|
|
267
|
+
\`\`\`css
|
|
268
|
+
.kz-block {
|
|
269
|
+
box-sizing: border-box;
|
|
270
|
+
width: 100%;
|
|
271
|
+
height: 100%;
|
|
272
|
+
padding: 15px;
|
|
273
|
+
display: flex;
|
|
274
|
+
flex-direction: column;
|
|
275
|
+
font-family: var(--font-family-sans-serif);
|
|
276
|
+
color: var(--color-font-primary);
|
|
277
|
+
}
|
|
278
|
+
.kz-block--with-header {
|
|
279
|
+
padding-top: 0;
|
|
280
|
+
}
|
|
281
|
+
.kz-header {
|
|
282
|
+
flex: none;
|
|
283
|
+
box-sizing: border-box;
|
|
284
|
+
height: 35px;
|
|
285
|
+
margin: 0 -15px;
|
|
286
|
+
padding: 7.5px 60px 7.5px 15px;
|
|
287
|
+
font-size: 12px;
|
|
288
|
+
font-weight: 100;
|
|
289
|
+
line-height: 20px;
|
|
290
|
+
text-transform: uppercase;
|
|
291
|
+
color: var(--color-font-primary);
|
|
292
|
+
white-space: nowrap;
|
|
293
|
+
overflow: hidden;
|
|
294
|
+
text-overflow: ellipsis;
|
|
295
|
+
}
|
|
296
|
+
.kz-state {
|
|
297
|
+
flex: 1;
|
|
298
|
+
display: flex;
|
|
299
|
+
align-items: center;
|
|
300
|
+
justify-content: center;
|
|
301
|
+
text-align: center;
|
|
302
|
+
font-size: 14px;
|
|
303
|
+
color: var(--color-font-placeholder);
|
|
304
|
+
}
|
|
305
|
+
.kz-state--empty {
|
|
306
|
+
font-size: 32px;
|
|
307
|
+
color: var(--color-background-medium);
|
|
308
|
+
}
|
|
309
|
+
.kz-state--error {
|
|
310
|
+
font-size: 14px;
|
|
311
|
+
color: var(--color-font-secondary);
|
|
312
|
+
}
|
|
313
|
+
.kz-chart {
|
|
314
|
+
flex: 1;
|
|
315
|
+
min-height: 0;
|
|
316
|
+
}
|
|
317
|
+
.kz-chart svg {
|
|
318
|
+
display: block;
|
|
319
|
+
width: 100%;
|
|
320
|
+
height: 100%;
|
|
321
|
+
}
|
|
322
|
+
.grid {
|
|
323
|
+
stroke: var(--color-border-medium-light);
|
|
324
|
+
stroke-width: 1;
|
|
325
|
+
}
|
|
326
|
+
.axis {
|
|
327
|
+
fill: var(--color-background-dark);
|
|
328
|
+
font-size: 10px;
|
|
329
|
+
}
|
|
330
|
+
.bar {
|
|
331
|
+
fill: var(--color-viz-cat-1-primary);
|
|
332
|
+
}
|
|
333
|
+
.kz-legend {
|
|
334
|
+
flex: none;
|
|
335
|
+
display: flex;
|
|
336
|
+
flex-wrap: wrap;
|
|
337
|
+
column-gap: 20px;
|
|
338
|
+
row-gap: 10px;
|
|
339
|
+
padding-top: 10px;
|
|
340
|
+
}
|
|
341
|
+
.kz-legend__item {
|
|
342
|
+
display: flex;
|
|
343
|
+
align-items: center;
|
|
344
|
+
gap: 10px;
|
|
345
|
+
font-size: 10px;
|
|
346
|
+
color: var(--color-font-primary);
|
|
347
|
+
}
|
|
348
|
+
.kz-dot {
|
|
349
|
+
flex: none;
|
|
350
|
+
width: 8px;
|
|
351
|
+
height: 8px;
|
|
352
|
+
border-radius: 50%;
|
|
353
|
+
background: var(--color-viz-cat-1-primary);
|
|
354
|
+
}
|
|
355
|
+
.kz-note {
|
|
356
|
+
font-size: 10px;
|
|
357
|
+
color: var(--color-font-placeholder);
|
|
358
|
+
}
|
|
359
|
+
\`\`\`
|
|
360
|
+
`;var ei=`# Copilot review instructions for this Kizen plugin
|
|
361
|
+
|
|
362
|
+
This repo is a Kizen plugin app: a \`kizen.json\` manifest plus the artifacts
|
|
363
|
+
that \`@kizenapps/packager\` finds by walking the directory tree under the
|
|
364
|
+
manifest's \`entry\` (default \`src/\`). No manifest key lists artifacts. The
|
|
365
|
+
directory layout decides what gets packaged.
|
|
366
|
+
|
|
367
|
+
## The full Kizen plugin documentation is available at \`.copilot-docs/\`
|
|
368
|
+
|
|
369
|
+
Before this review started, the complete Kizen plugin developer documentation
|
|
370
|
+
was fetched into \`.copilot-docs/\` by \`.github/workflows/copilot-code-review.yml\`.
|
|
371
|
+
It is not committed to this repo \u2014 it is cloned from \`kizen/app-engine\` at review
|
|
372
|
+
time, so it is always current. It is the authoritative reference for every plugin
|
|
373
|
+
API, manifest field and runtime contract. Deliberately, no plugin rules are
|
|
374
|
+
copied into this repo: read them from \`.copilot-docs/\` instead.
|
|
375
|
+
|
|
376
|
+
Use it. Start from:
|
|
377
|
+
|
|
378
|
+
- \`.copilot-docs/17-gotchas.md\` \u2014 the consolidated list of traps and silent
|
|
379
|
+
failure modes, grouped by topic. Scan the sections relevant to the changed
|
|
380
|
+
files.
|
|
381
|
+
- \`.copilot-docs/method-index.md\` \u2014 A\u2013Z lookup from any method, manifest field,
|
|
382
|
+
endpoint or identifier to the doc that owns it.
|
|
383
|
+
- \`.copilot-docs/03-manifest-reference.md\` \u2014 every \`kizen.json\` and \`config.json\`
|
|
384
|
+
field, the component directory names, \`api_name\` rules, and the build/publish
|
|
385
|
+
validation rules.
|
|
386
|
+
- The other numbered docs (\`.copilot-docs/04-worker-runtime-api.md\`,
|
|
387
|
+
\`.copilot-docs/07-automation-steps.md\`, \`.copilot-docs/08-actions.md\`, and so
|
|
388
|
+
on) for complete contracts.
|
|
389
|
+
|
|
390
|
+
**Many Kizen plugin APIs fail silently when misused** \u2014 the call succeeds,
|
|
391
|
+
nothing throws, and the behavior is quietly wrong. These defects are not
|
|
392
|
+
detectable from the calling code alone, and they are the single most valuable
|
|
393
|
+
thing to catch in review. When a changed file calls a \`this.*\` worker method,
|
|
394
|
+
look that method up in \`method-index.md\` and read its contract before concluding
|
|
395
|
+
the call is correct.
|
|
396
|
+
|
|
397
|
+
The same applies to artifact config: check each \`config.json\` against
|
|
398
|
+
\`03-manifest-reference.md\`, and each automation step against
|
|
399
|
+
\`07-automation-steps.md\`.
|
|
400
|
+
|
|
401
|
+
When a review comment is based on the documentation, name the file it came from.
|
|
402
|
+
|
|
403
|
+
If \`.copilot-docs/\` is not present, the setup workflow did not run \u2014 it only
|
|
404
|
+
takes effect once it is on the repository's default branch \u2014 so say that in
|
|
405
|
+
the review instead of guessing at the rules from memory.
|
|
406
|
+
|
|
407
|
+
## Scope
|
|
408
|
+
|
|
409
|
+
This file covers repo structure and general review. Two path-scoped files cover
|
|
410
|
+
the rest: \`.github/instructions/security.instructions.md\` for security-sensitive
|
|
411
|
+
patterns and \`.github/instructions/version-discipline.instructions.md\` for
|
|
412
|
+
manifest version bumps.
|
|
413
|
+
`;var ti='---\napplyTo: "src/**/*.js,kizen.json"\n---\n\n# Security review rules for plugin scripts\n\nThe rules themselves live in the docs corpus that\n`.github/workflows/copilot-code-review.yml` fetches into `.copilot-docs/`, so\nthey cannot drift out of date here. Read them there rather than reviewing from\nmemory.\n\nWhen a change touches a service, `auth_credentials`, a `{{secret.KEY}}`\nreference, `base_config.secrets`, or dynamic code (`eval`, `new Function`, or a\nstring argument to `setTimeout` or `setInterval`), read\n`.copilot-docs/06-auth-secrets-services.md` together with the "Services, auth &\nsecrets" and "Release & publish" sections of `.copilot-docs/17-gotchas.md`, and\nreview the change against what they say.\n\nWhen a change uses `__dangerouslySkipProxy`, also read\n`.copilot-docs/11-output-ui-iframes-frames.md`.\n';var ri=`---
|
|
414
|
+
applyTo: "kizen.json"
|
|
415
|
+
---
|
|
416
|
+
|
|
417
|
+
# Version-bump discipline for \`kizen.json\`
|
|
418
|
+
|
|
419
|
+
The bump matrix lives in the docs corpus that
|
|
420
|
+
\`.github/workflows/copilot-code-review.yml\` fetches into \`.copilot-docs/\`, so it
|
|
421
|
+
cannot drift out of date here.
|
|
422
|
+
|
|
423
|
+
Check every \`kizen.json\` diff against the "How big a bump?" matrix in
|
|
424
|
+
\`.copilot-docs/16-release-and-publish.md\` and the "Release & publish" section of
|
|
425
|
+
\`.copilot-docs/17-gotchas.md\`, and name the change that sets the required level.
|
|
426
|
+
`;var ni=`# Copilot only reads this file from the default branch, and only if the job is named copilot-setup-steps.
|
|
427
|
+
name: Copilot code review setup
|
|
428
|
+
|
|
429
|
+
on:
|
|
430
|
+
workflow_dispatch:
|
|
431
|
+
|
|
432
|
+
jobs:
|
|
433
|
+
copilot-setup-steps:
|
|
434
|
+
runs-on: ubuntu-latest
|
|
435
|
+
timeout-minutes: 10
|
|
436
|
+
permissions:
|
|
437
|
+
contents: read
|
|
438
|
+
steps:
|
|
439
|
+
- name: Check out this plugin repo
|
|
440
|
+
uses: actions/checkout@v4
|
|
441
|
+
|
|
442
|
+
- name: Fetch the Kizen plugin docs corpus into .copilot-docs/
|
|
443
|
+
run: |
|
|
444
|
+
set -euo pipefail
|
|
445
|
+
git clone --depth 1 --filter=blob:none --sparse \\
|
|
446
|
+
https://github.com/kizen/app-engine.git .docs-src
|
|
447
|
+
git -C .docs-src sparse-checkout set --no-cone '/docs/**/*.md' '!/docs/site/**'
|
|
448
|
+
mv .docs-src/docs .copilot-docs
|
|
449
|
+
rm -rf .docs-src
|
|
450
|
+
|
|
451
|
+
- name: Verify the corpus landed
|
|
452
|
+
run: |
|
|
453
|
+
set -euo pipefail
|
|
454
|
+
test -f .copilot-docs/17-gotchas.md
|
|
455
|
+
test -f .copilot-docs/method-index.md
|
|
456
|
+
|
|
457
|
+
numbered=$(find .copilot-docs -maxdepth 1 -name '[0-9][0-9]-*.md' | wc -l | tr -d ' ')
|
|
458
|
+
test "$numbered" -ge 18
|
|
459
|
+
test -f .copilot-docs/examples/kitchen_sink.md
|
|
460
|
+
|
|
461
|
+
count=$(find .copilot-docs -name '*.md' | wc -l | tr -d ' ')
|
|
462
|
+
echo "Fetched $count markdown files into .copilot-docs/ ($numbered numbered docs)"
|
|
463
|
+
test "$count" -ge 24
|
|
464
|
+
du -sh .copilot-docs
|
|
465
|
+
`;var oi=`const MAX_PAGE_SIZE = 1000;
|
|
466
|
+
const DEFAULT_MAX_PAGES = 10;
|
|
467
|
+
|
|
468
|
+
const fieldCache = new Map();
|
|
469
|
+
|
|
470
|
+
export const formatNumber = (input, prefix = '') => {
|
|
471
|
+
const n = Number.isNaN(Number(input)) ? 0 : Number(input);
|
|
472
|
+
const abs = Math.abs(n);
|
|
473
|
+
const sign = n < 0 ? '-' : '';
|
|
474
|
+
if (abs < 1) return \`\${sign}\${prefix}\${Number(abs.toFixed(4))}\`;
|
|
475
|
+
if (abs < 1000) return \`\${sign}\${prefix}\${Number(abs.toPrecision(5))}\`;
|
|
476
|
+
if (abs < 10000) return \`\${sign}\${prefix}\${Math.round(abs).toLocaleString()}\`;
|
|
477
|
+
const rounded = Number(abs.toPrecision(4));
|
|
478
|
+
if (rounded >= 1e12) return \`\${prefix}999B+\`;
|
|
479
|
+
const [unit, suffix] = rounded >= 1e9 ? [1e9, 'B'] : rounded >= 1e6 ? [1e6, 'M'] : [1e3, 'K'];
|
|
480
|
+
return \`\${sign}\${prefix}\${Number((rounded / unit).toPrecision(4))}\${suffix}\`;
|
|
481
|
+
};
|
|
482
|
+
|
|
483
|
+
const HTML_ESCAPES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
|
484
|
+
|
|
485
|
+
export const escapeHtml = (value) =>
|
|
486
|
+
value === null || value === undefined
|
|
487
|
+
? ''
|
|
488
|
+
: String(value).replace(/[&<>"']/g, (char) => HTML_ESCAPES[char]);
|
|
489
|
+
|
|
490
|
+
const describeError = (error) => {
|
|
491
|
+
if (typeof error === 'string') return error;
|
|
492
|
+
if (error instanceof Error) return error.message;
|
|
493
|
+
if (error && typeof error === 'object') {
|
|
494
|
+
if (typeof error.message === 'string') return error.message;
|
|
495
|
+
try {
|
|
496
|
+
return JSON.stringify(error);
|
|
497
|
+
} catch {
|
|
498
|
+
return String(error);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
return String(error);
|
|
502
|
+
};
|
|
503
|
+
|
|
504
|
+
const loadFields = async (ctx, object) => {
|
|
505
|
+
const [data, error] = await ctx.getWithErrors(
|
|
506
|
+
\`/custom-objects/\${encodeURIComponent(object)}/fields\`,
|
|
507
|
+
);
|
|
508
|
+
if (error) {
|
|
509
|
+
throw new Error(\`Couldn't load fields for \${object}: \${describeError(error)}\`);
|
|
510
|
+
}
|
|
511
|
+
if (!Array.isArray(data)) {
|
|
512
|
+
throw new Error(\`Couldn't load fields for \${object}: the response was not a list of fields\`);
|
|
513
|
+
}
|
|
514
|
+
return data;
|
|
515
|
+
};
|
|
516
|
+
|
|
517
|
+
export const getFields = (ctx, object) => {
|
|
518
|
+
if (!fieldCache.has(object)) {
|
|
519
|
+
const pending = loadFields(ctx, object);
|
|
520
|
+
fieldCache.set(object, pending);
|
|
521
|
+
pending.catch(() => {
|
|
522
|
+
if (fieldCache.get(object) === pending) fieldCache.delete(object);
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
return fieldCache.get(object);
|
|
526
|
+
};
|
|
527
|
+
|
|
528
|
+
export const fieldByName = (fields, name) => fields.find((field) => field.name === name);
|
|
529
|
+
|
|
530
|
+
const nonCustomFilter = (field, condition, value) => ({
|
|
531
|
+
type: 'fields_v2',
|
|
532
|
+
subtype: 'non_custom',
|
|
533
|
+
field,
|
|
534
|
+
condition,
|
|
535
|
+
value,
|
|
536
|
+
});
|
|
537
|
+
|
|
538
|
+
export const blockFilters = (args, fields) => {
|
|
539
|
+
const filters = [];
|
|
540
|
+
const unapplied = [];
|
|
541
|
+
const dateFilter = args?.dateFilter;
|
|
542
|
+
const teamFilter = args?.teamFilter;
|
|
543
|
+
|
|
544
|
+
if (dateFilter) {
|
|
545
|
+
if (dateFilter.start && dateFilter.end) {
|
|
546
|
+
filters.push(nonCustomFilter('created', 'between', [dateFilter.start, dateFilter.end]));
|
|
547
|
+
} else {
|
|
548
|
+
unapplied.push('dateFilter');
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
const teamMembers = teamFilter?.teamMembers ?? [];
|
|
553
|
+
const roles = teamFilter?.roles ?? [];
|
|
554
|
+
|
|
555
|
+
if (teamMembers.length > 0) {
|
|
556
|
+
if (fieldByName(fields, 'owner')) {
|
|
557
|
+
filters.push(nonCustomFilter('owner', 'is_any_of', [...teamMembers]));
|
|
558
|
+
} else {
|
|
559
|
+
unapplied.push('teamFilter');
|
|
560
|
+
}
|
|
561
|
+
} else if (roles.length > 0) {
|
|
562
|
+
unapplied.push('teamFilter');
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
return { filters, unapplied };
|
|
566
|
+
};
|
|
567
|
+
|
|
568
|
+
export const dropdownFilter = (field, optionNameOrNames) => {
|
|
569
|
+
const names = Array.isArray(optionNameOrNames) ? optionNameOrNames : [optionNameOrNames];
|
|
570
|
+
const ids = names.map((name) => {
|
|
571
|
+
const option = (field.options ?? []).find((candidate) => candidate.name === name);
|
|
572
|
+
if (!option) {
|
|
573
|
+
throw new Error(\`\${field.display_name ?? field.name} has no option named "\${name}"\`);
|
|
574
|
+
}
|
|
575
|
+
return option.id;
|
|
576
|
+
});
|
|
577
|
+
const multiple = Array.isArray(optionNameOrNames);
|
|
578
|
+
return {
|
|
579
|
+
type: 'fields_v2',
|
|
580
|
+
subtype: 'custom',
|
|
581
|
+
field: \`custom::\${field.id}\`,
|
|
582
|
+
condition: multiple ? 'is_any_of' : '=',
|
|
583
|
+
value: multiple ? ids : ids[0],
|
|
584
|
+
};
|
|
585
|
+
};
|
|
586
|
+
|
|
587
|
+
export const searchRecords = async (
|
|
588
|
+
ctx,
|
|
589
|
+
{
|
|
590
|
+
object,
|
|
591
|
+
fieldNames,
|
|
592
|
+
filters = [],
|
|
593
|
+
pageSize = MAX_PAGE_SIZE,
|
|
594
|
+
maxPages = DEFAULT_MAX_PAGES,
|
|
595
|
+
ordering,
|
|
596
|
+
},
|
|
597
|
+
) => {
|
|
598
|
+
const size = Number.isFinite(Number(pageSize))
|
|
599
|
+
? Math.max(1, Math.min(MAX_PAGE_SIZE, Math.floor(Number(pageSize))))
|
|
600
|
+
: MAX_PAGE_SIZE;
|
|
601
|
+
const pages = Number.isFinite(Number(maxPages))
|
|
602
|
+
? Math.max(1, Math.floor(Number(maxPages)))
|
|
603
|
+
: DEFAULT_MAX_PAGES;
|
|
604
|
+
const body = {
|
|
605
|
+
field_names: fieldNames,
|
|
606
|
+
query: Array.isArray(filters) && filters.length > 0 ? [{ and: true, filters }] : [],
|
|
607
|
+
};
|
|
608
|
+
const orderingParam = ordering ? \`&ordering=\${encodeURIComponent(ordering)}\` : '';
|
|
609
|
+
const records = [];
|
|
610
|
+
let count = 0;
|
|
611
|
+
let hasMore = false;
|
|
612
|
+
|
|
613
|
+
for (let page = 1; page <= pages; page += 1) {
|
|
614
|
+
const [data, error] = await ctx.postWithErrors(
|
|
615
|
+
\`/records/\${encodeURIComponent(object)}/search?page_size=\${size}&page=\${page}\${orderingParam}\`,
|
|
616
|
+
body,
|
|
617
|
+
);
|
|
618
|
+
if (error) {
|
|
619
|
+
throw new Error(\`Couldn't search \${object}: \${describeError(error)}\`);
|
|
620
|
+
}
|
|
621
|
+
const results = Array.isArray(data?.results) ? data.results : [];
|
|
622
|
+
records.push(...results);
|
|
623
|
+
count = typeof data?.count === 'number' ? data.count : records.length;
|
|
624
|
+
hasMore = Boolean(data?.next) && results.length > 0;
|
|
625
|
+
if (!hasMore) break;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
return { records, count, truncated: hasMore || count > records.length };
|
|
629
|
+
};
|
|
630
|
+
|
|
631
|
+
const fieldEntry = (record, name) =>
|
|
632
|
+
Object.values(record?.fields ?? {}).find((entry) => entry?.name === name);
|
|
633
|
+
|
|
634
|
+
export const fieldValue = (record, name) => fieldEntry(record, name)?.value;
|
|
635
|
+
|
|
636
|
+
const labelOf = (value) => {
|
|
637
|
+
if (value === null || value === undefined || value === '') return '';
|
|
638
|
+
if (Array.isArray(value)) return value.map(labelOf).filter(Boolean).join(', ');
|
|
639
|
+
if (typeof value === 'object') {
|
|
640
|
+
if ('amount' in value) {
|
|
641
|
+
if (value.amount === null || value.amount === undefined || value.amount === '') return '';
|
|
642
|
+
return formatNumber(Number(value.amount), value.symbol ?? '');
|
|
643
|
+
}
|
|
644
|
+
if ('first_name' in value || 'last_name' in value) {
|
|
645
|
+
const fullName = [value.first_name, value.last_name].filter(Boolean).join(' ');
|
|
646
|
+
return fullName || value.email || '';
|
|
647
|
+
}
|
|
648
|
+
return String(value.name ?? value.display_name ?? '');
|
|
649
|
+
}
|
|
650
|
+
return String(value);
|
|
651
|
+
};
|
|
652
|
+
|
|
653
|
+
export const fieldLabel = (record, name) => labelOf(fieldValue(record, name));
|
|
654
|
+
|
|
655
|
+
const keyOf = (value) => {
|
|
656
|
+
if (value === null || value === undefined) return '';
|
|
657
|
+
if (typeof value === 'object') return String(value.id ?? labelOf(value));
|
|
658
|
+
return String(value);
|
|
659
|
+
};
|
|
660
|
+
|
|
661
|
+
const valuesOf = (value) => {
|
|
662
|
+
if (Array.isArray(value)) return value.length > 0 ? value : [null];
|
|
663
|
+
return [value];
|
|
664
|
+
};
|
|
665
|
+
|
|
666
|
+
export const countBy = (records, name, field) => {
|
|
667
|
+
const groups = new Map();
|
|
668
|
+
|
|
669
|
+
for (const record of records) {
|
|
670
|
+
for (const value of valuesOf(fieldValue(record, name))) {
|
|
671
|
+
const key = keyOf(value);
|
|
672
|
+
const group = groups.get(key);
|
|
673
|
+
if (group) {
|
|
674
|
+
group.count += 1;
|
|
675
|
+
} else {
|
|
676
|
+
groups.set(key, { key, label: labelOf(value), count: 1 });
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
const order = new Map(
|
|
682
|
+
(field?.options ?? [])
|
|
683
|
+
.filter((option) => typeof option.order === 'number' && Number.isFinite(option.order))
|
|
684
|
+
.map((option) => [String(option.id), option.order]),
|
|
685
|
+
);
|
|
686
|
+
const rank = (key) => (order.has(key) ? order.get(key) : Number.POSITIVE_INFINITY);
|
|
687
|
+
|
|
688
|
+
return [...groups.values()].sort((a, b) => {
|
|
689
|
+
if (b.count !== a.count) return b.count - a.count;
|
|
690
|
+
const ra = rank(a.key);
|
|
691
|
+
const rb = rank(b.key);
|
|
692
|
+
return ra === rb ? 0 : ra < rb ? -1 : 1;
|
|
693
|
+
});
|
|
694
|
+
};
|
|
695
|
+
|
|
696
|
+
const numberOf = (value) => {
|
|
697
|
+
if (value === null || value === undefined || value === '') return 0;
|
|
698
|
+
const raw = typeof value === 'object' ? value.amount : value;
|
|
699
|
+
if (raw === null || raw === undefined || raw === '') return 0;
|
|
700
|
+
const n = Number(raw);
|
|
701
|
+
return Number.isFinite(n) ? n : 0;
|
|
702
|
+
};
|
|
703
|
+
|
|
704
|
+
export const sumBy = (records, name, valueOf) =>
|
|
705
|
+
records.reduce(
|
|
706
|
+
(total, record) =>
|
|
707
|
+
total + (valueOf ? numberOf(valueOf(record)) : numberOf(fieldValue(record, name))),
|
|
708
|
+
0,
|
|
709
|
+
);
|
|
710
|
+
`;function Ht(){return[{path:".github/copilot-instructions.md",content:ei},{path:".github/instructions/security.instructions.md",content:ti},{path:".github/instructions/version-discipline.instructions.md",content:ri},{path:".github/workflows/copilot-code-review.yml",content:ni}]}var ii="lib/kizenData.js",Zr=(e="src")=>e===""?ii:`${e}/${ii}`;function Vt(e=[]){return[{path:".claude/skills/kizen-custom-block/SKILL.md",content:Zo},{path:".claude/skills/kizen-custom-block/design.md",content:Qo},...[...new Set(e)].map(t=>({path:Zr(t),content:oi}))]}import{access as kc,mkdir as Cc,readFile as Sc,writeFile as _c}from"fs/promises";import{dirname as Pc,join as si}from"path";var Wt={readFile:async e=>{try{return await Sc(e,"utf-8")}catch(t){if(Nt(t))return;throw t}},writeFile:async(e,t)=>{await Cc(Pc(e),{recursive:!0}),await _c(e,t,"utf-8")},exists:async e=>{try{return await kc(e),!0}catch{return!1}}},Ec=(e,t)=>e===void 0?"created":e===t?"unchanged":"updated";async function Qr(e,t,r=Wt){return Promise.all(t.map(async o=>({path:o.path,status:Ec(await r.readFile(si(e,o.path)),o.content)})))}async function Kt(e,t,r={},o=Wt){let n=await Qr(e,t,o);return r.dryRun===!0||await Promise.all(t.filter((i,s)=>n[s]?.status!=="unchanged").map(i=>o.writeFile(si(e,i.path),i.content))),n}var Jt=e=>`${e.status.padEnd(9)} ${e.path}`;var ai=".claude/skills/kizen-custom-block/SKILL.md",li="Claude files managed by appbuilder are out of date; run appbuilder setup-claude",tn=Wt,Tc=e=>{if(typeof e!="string"||e.trim()==="")return;let t=Bt(e);if(!(t===".."||t.startsWith("../")||t.startsWith("/")))return t};function Ic(e){let r=(Array.isArray(e)?e:[e]).map(o=>typeof o=="object"&&o!==null&&"entry"in o?Tc(o.entry):void 0).filter(o=>o!==void 0);return r.length>0?[...new Set(r)]:["src"]}var Dc=async(e,t)=>{try{let r=await t.readFile(qt(e,"kizen.json"));return r===void 0?["src"]:Ic(JSON.parse(r))}catch{return["src"]}};async function ci(e,t=tn,r={}){let o=await Dc(e,t),n=r.includeLib===!0?o:(await Promise.all(o.map(async i=>await t.exists(qt(e,Zr(i)))?i:void 0))).filter(i=>i!==void 0);return Vt(n)}async function di(e,t=tn){try{let r=await ci(e,t);return!r.some(n=>n.path===ai)||await t.readFile(qt(e,ai))===void 0?!1:(await Qr(e,r,t)).some(n=>n.status!=="unchanged")}catch{return!1}}var Ac={fs:tn,log:e=>{console.log(e)},error:e=>{console.error(e)},setExitCode:e=>{process.exitCode=e}},en=(e,t)=>`${String(e.filter(r=>r.status===t).length)} ${t}`;async function ui(e,t,r=Ac){if(!await r.fs.exists(qt(e,"kizen.json"))){r.error("Error: kizen.json not found. Run this command from a plugin directory."),r.setExitCode(1);return}let o=t.dryRun===!0,n;try{n=await Kt(e,await ci(e,r.fs,{includeLib:t.includeLib===!0}),{dryRun:o},r.fs)}catch(a){r.error(`Error: ${a instanceof Error?a.message:String(a)}`),r.setExitCode(1);return}for(let a of n)r.log(Jt(a));let i=`${en(n,"created")}, ${en(n,"updated")}, ${en(n,"unchanged")}`,s="these files are managed by appbuilder, so local edits to them are replaced";r.log(o?`Dry run: ${i}; nothing written (${s}).`:`Claude files: ${i} (${s}).`)}function Xt(e){return{cwd:e,loadCredentialsDetailed:Ut,listLoadableCredentialProfiles:Jo,loadConfig:he,packageBlocks:Kr,createClient:t=>Xo({credentials:t}),readPushMap:xo,writePushMap:vo,ensureGitignore:ge,isClaudeSkillStale:t=>di(t),randomUUID:Nc,now:()=>new Date,writeStdout:t=>{process.stdout.write(t)},writeStderr:t=>{process.stderr.write(t)},setExitCode:t=>{process.exitCode=t}}}var $c=new Set(["owner","admin","edit"]),Fc="Chart groups are not listed here; find them with `appbuilder block targets --object <id> --json` and pass --dashboard <id>.",nn=e=>e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";function W(e,t,r={}){return{ok:!1,code:e,message:t,...r}}var ue=e=>({ok:!0,value:e});function Ve(e){return e instanceof ne?W(e.kind,e.message,e.hint===void 0?{}:{hint:e.hint}):e instanceof Rc?W("validation_failed",xe(e.issues),{issues:e.issues}):W("local_error",nn(e))}var jc=()=>Z.join(", ");async function Gt(e,t){let r;try{r=await t.loadCredentialsDetailed(e)}catch(i){return W("credentials_invalid",`Couldn't read credentials from ${e}: ${nn(i)}`)}if(r.environmentSource!=="explicit"){let i=r.environmentSource==="missing"?'has no "environment"':'has an invalid "environment"';return W("credentials_invalid",`${e} ${i}. Set it to one of: ${jc()}. The CLI won't default to production.`)}let{credentials:o}=r,n=["apiKey","userId","businessId"].filter(i=>o[i].trim()==="");return n.length>0?W("credentials_invalid",`${e} is missing ${n.map(i=>`"${i}"`).join(", ")}.`):ue({credentials:o})}async function Zt(e,t){if(e.credentials!==void 0)return Gt(e.credentials,t);let r=await t.listLoadableCredentialProfiles(),o=r.map(a=>a.name);if(e.profile!==void 0){let a=r.find(l=>l.name===e.profile);return a?Gt(a.path,t):W("credentials_invalid",o.length===0?`No loadable credential profile named "${e.profile}". No profiles are loadable; create ${ve} or pass -c <path>.`:`No loadable credential profile named "${e.profile}". Loadable profiles: ${o.join(", ")}`)}let n=await t.loadConfig(Bc(t.cwd,".kizenapp"));if(n.credentialMode==="local")return W("credentials_invalid","This plugin is set to use local browser-only credentials the CLI can't read. Pass -c <path> or --profile <name>.");let i=n.activeCredentialProfile===void 0?void 0:r.find(a=>a.name===n.activeCredentialProfile);if(i)return Gt(i.path,t);let[s]=r;return r.length===1&&s?Gt(s.path,t):r.length===0?W("credentials_invalid",`No credentials found. Create ${ve} or pass -c <path>.`):W("needs_choice",`Several credential profiles are available; pass --profile <name>: ${o.join(", ")}`,{choice:"profile",choices:r.map(a=>({value:a.name,label:a.isDefault?`${a.name} (default)`:a.name,args:["--profile",a.name]}))})}function Oc(e,t){let r=new Set(t.map(o=>o.pluginApiName)).size>1;return t.map(({pluginApiName:o,apiName:n})=>{let i=e.find(a=>a.api_name===o)?.artifacts.custom_blocks.find(a=>a.api_name===n),s=r?`${o}/${n}`:n;return{value:n,label:`${i?.name??n} (${s})`,args:[n]}})}async function on(e,t){let r=await t.packageBlocks(t.cwd),o=Jr(r,e,"push");if(!o.ok){let{reason:p,message:g,field:v}=o;return p==="no_blocks"||p==="invalid_block"?W("invalid_block",g,v===void 0?{}:{field:v}):W("needs_choice",g,{choice:"block",choices:Oc(r.deployable,o.available)})}let{block:n,pluginApiName:i,views:s,warnings:a}=o.value,l=lo(n,s);return ue({block:n,pluginApiName:i,content:l,contentHash:Lr(l),warnings:a})}var mi=e=>e==null?null:$c.has(e.toLowerCase());function dt(e,t){return{id:e.id,name:e.name,type:t,dashletsCount:e.dashlets_count??null,employeeAccess:e.employee_access??null,hidden:e.hidden??!1,canEdit:mi(e.employee_access)}}var hi=e=>({id:e.id,objectName:e.object_name,fetchUrl:e.fetch_url}),Lc="Contacts";async function sn(e){let[t,r]=await Promise.all([e.listCustomObjects(),e.getClientObjectId().catch(()=>null)]),o=t.map(hi).sort((n,i)=>n.objectName.localeCompare(i.objectName));return r!==null&&r!==""&&!o.some(n=>n.id===r)&&o.push({id:r,objectName:Lc,fetchUrl:"client"}),o}async function zc(e,t,r){let{environment:o,businessId:n}=t;try{if(r.object!==void 0){let l=r.object,[p,g]=await Promise.all([e.getCustomObject(l).catch(()=>null),e.listDashboards("chart_group",l)]);return ue({ok:!0,environment:o,businessId:n,object:p?hi(p):null,surfaces:{chart_group:g.map(v=>dt(v,"chart_group"))}})}let[i,s,a]=await Promise.all([e.listDashboards("generic_dashboard"),e.listDashboards("homepage"),sn(e)]);return ue({ok:!0,environment:o,businessId:n,surfaces:{dashboard:i.map(l=>dt(l,"dashboard")),homepage:s.map(l=>dt(l,"homepage"))},customObjects:a})}catch(i){return Ve(i)}}var an=(e,t)=>t.dashboard===e.id;function Qt(e,t){return[...fo(e).filter(o=>an(e,o)).map(o=>{let n=oo(o.name);return{value:o.id,label:Ft(o),args:["--dashboard",e.id,"--dashlet",o.id],pushKey:n?o.name:null,isFromThisPlugin:n?.pluginApiName===t.pluginApiName}}),{value:"new",label:"Create a new block",args:["--dashboard",e.id,"--create"]}]}var ln=(e,t)=>go({dashboardId:t.id,dashlets:t.dashlets,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name,entry:e.entry}),gi=(e,t)=>ue({dashboard:e,surface:Ur(e.type),action:"create",dashlet:void 0,resolvedBy:t}),Yt=(e,t,r)=>ue({dashboard:e,surface:Ur(e.type),action:"update",dashlet:t,resolvedBy:r});async function Mc(e){let[t,r]=await Promise.all([e.client.listDashboards("generic_dashboard"),e.client.listDashboards("homepage")]),o=n=>i=>({value:i.id,label:i.name,args:["--dashboard",i.id],surface:n,canEdit:mi(i.employee_access)});return W("needs_choice",`Choose where to push; pass --dashboard <id>. ${Fc}`,{choice:"dashboard",choices:[...t.map(o("dashboard")),...r.map(o("homepage"))]})}async function Uc(e,t,r){let o=await e.client.getDashboard(t);if(r.create)return gi(o,"flag");let n=()=>Qt(o,e.block);if(r.dashlet!==void 0){let s=r.dashlet,a=o.dashlets.find(l=>l.id===s&&an(o,l));return a?Ye(a)?Yt(o,a,"flag"):W("usage_error",`Dashlet ${s} is not a custom code block, so it can't be updated with a pushed block. Pass --create to add a new one.`):W("not_found",`Dashlet ${s} is not on dashboard "${o.name}" (${o.id}).`,{choice:"target",choices:n()})}let i=ln(e,o);return i.kind==="map"?Yt(o,i.dashlet,"push_map"):i.kind==="name"?Yt(o,i.dashlet,"name"):W("needs_choice",i.kind==="ambiguous"?`Dashboard "${o.name}" has ${String(i.dashlets.length)} blocks pushed from this block; pass --dashlet <id> to pick one, or --create.`:`Choose a block to update on "${o.name}", or create a new one; pass --dashlet <id> or --create.`,{choice:"target",choices:n()})}async function Hc(e,t,r){let o;try{o=await e.client.getDashboard(t.dashboardId)}catch(i){if(i instanceof ne&&i.kind==="not_found")return W("remembered_target_missing",`The remembered dashboard ${t.dashboardId} no longer exists. Pass --dashboard <id> to choose another, or --forget to clear it.`);throw i}if(r.create)return gi(o,"remembered");let n=o.dashlets.find(i=>i.id===t.dashletId&&an(o,i));return n&&Ye(n)?Yt(o,n,"remembered"):W("remembered_target_missing",`The remembered block (dashlet ${t.dashletId}) is no longer on "${o.name}". Choose a block to update, or create a new one.`,{choice:"target",choices:Qt(o,e.block)})}async function cn(e,t){if(t.dashlet!==void 0&&t.create)return W("usage_error","Pass either --dashlet <id> or --create, not both.");if(t.dashlet!==void 0&&t.dashboard===void 0)return W("usage_error","--dashlet <id> needs --dashboard <id>.");try{return t.dashboard!==void 0?await Uc(e,t.dashboard,t):e.entry?await Hc(e,e.entry,t):await Mc(e)}catch(r){return Ve(r)}}async function Vc(e,t,r){let o=t.custom_object;if(o==null||o==="")return null;if(typeof o!="string"){if(typeof o!="object"||typeof o.id!="string")return null;let{id:n,fetch_url:i}=o;return typeof i=="string"?{id:n,fetchUrl:i}:{id:n}}if(r!=="chart_group")return{id:o};try{let n=await e.getCustomObject(o);return{id:o,fetchUrl:n.fetch_url}}catch{return{id:o}}}async function dn(e,t,r,o){let{credentials:n,block:i}=e,{dashboard:s,surface:a}=t,l=[],p,g;if(t.action==="update"){let{dashlet:k}=t;if(yo(k,e.entry)){let f=`"${Ft(k)}" (dashlet ${k.id}) was changed in Kizen since the last push.`;if(!r.force)return W("drift_detected",`${f} Pushing would overwrite those changes; pass --force to overwrite them.`);l.push(`${f} Overwriting it because of --force.`)}p={action:"update",method:"PATCH",path:ct(s.id,k.id),body:uo(k,i.content),dashletId:k.id},g=`Update "${Ft(k)}" (dashlet ${k.id})`}else p={action:"create",method:"POST",path:ct(s.id),body:co({pluginApiName:i.pluginApiName,blockApiName:i.block.api_name,content:i.content,dashlets:s.dashlets,objectId:o.randomUUID(),layoutId:o.randomUUID()}),dashletId:null},g=`Create a new block on "${s.name}"`;let v=Co({appBaseUrl:zo[n.environment],surface:a,dashboardId:s.id,customObject:await Vc(e.client,s,a)});return ue({...p,dashboard:{id:s.id,name:s.name,type:a},url:v,resolvedBy:t.resolvedBy,warnings:l,summary:{environment:n.environment,businessId:n.businessId,isProduction:Yr(n.environment),surface:a,dashboardId:s.id,dashboardName:s.name,action:t.action,actionLine:g,dashletId:p.dashletId,blockName:i.block.name,blockApiName:i.block.api_name,pluginApiName:i.pluginApiName,scriptBytes:Buffer.byteLength(i.content.script,"utf8"),stylesBytes:Buffer.byteLength(i.content.styles,"utf8"),...i.content.views&&{viewsBytes:Buffer.byteLength(JSON.stringify(i.content.views),"utf8")}}})}var un=e=>({environment:e.credentials.environment,businessId:e.credentials.businessId,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name});async function pn(e,t,r){let o;try{if(t.action==="create"){let l=(await e.client.createDashlet(t.dashboard.id,t.body)).id;if(typeof l!="string"||l==="")return W("api_error",`POST ${t.path} succeeded but the response had no dashlet id; check "${t.dashboard.name}" before pushing again.`);o=l}else await e.client.updateDashlet(t.dashboard.id,t.dashletId,t.body),o=t.dashletId}catch(a){return Ve(a)}let n=[...t.warnings],i={...un(e),dashboardId:t.dashboard.id,dashletId:o,contentHash:e.block.contentHash,pushedAt:r.now().toISOString()},s=!1;try{r.ensureGitignore(r.cwd),await r.writePushMap(r.cwd,bo(e.pushMap,i)),s=!0}catch(a){n.push(`The push succeeded, but ${Me} couldn't be written, so this target isn't remembered: ${nn(a)}`)}return ue({dashletId:o,remembered:s,warnings:n})}var Wc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function fn(e){return Wc.test(e)?{dashboardId:e,script:`await window.__kizenCustomBlocks?.refresh('${e}')`}:null}async function Kc(e,t){let r=un(e);if(!Mr(e.pushMap,r))return null;let o=wo(e.pushMap,r);return await t.writePushMap(t.cwd,o),o}async function mn(e,t){let{client:r,credentials:o,block:n}=e,i=await t.readPushMap(t.cwd),s=!1;if(e.forget){let a=await Kc({credentials:o,block:n,pushMap:i},t);a&&(i=a,s=!0)}return{context:{client:r,credentials:o,block:n,pushMap:i,entry:Mr(i,un({credentials:o,block:n}))},forgotten:s}}function hn(e,t){return e.dryRun?ue({kind:"dry-run",reason:"flag"}):e.yes?Yr(t)&&!e.allowProduction?W("production_requires_flag",`${t} is a production environment. Pass --allow-production with --yes to write to it.`):ue({kind:"apply"}):ue({kind:"dry-run",reason:"no_yes"})}var Jc="Dry run only: pass --yes to write.",He=e=>e.map(t=>`Warning: ${t}`);function ut(e){return[`Environment: ${e.environment}${e.isProduction?" (production)":""}`,`Business: ${e.businessId}`,`Surface: ${e.surface}`,`Dashboard: "${e.dashboardName}" (${e.dashboardId})`,`Action: ${e.actionLine}`,`Block: ${e.blockName} (${e.pluginApiName}/${e.blockApiName})`,`Size: script ${String(e.scriptBytes)} bytes, styles ${String(e.stylesBytes)} bytes${e.viewsBytes===void 0?"":`, views ${String(e.viewsBytes)} bytes`}`]}var qc=e=>`${e.path===void 0?"":`${e.path}: `}${e.message} (${e.rule})`,Gc=e=>/^[\w./:@=-]+$/.test(e)?e:JSON.stringify(e);function Yc(e,t,r){let o=[`Error: ${e.message}`];if(e.hint!==void 0&&o.push(`Hint: ${e.hint}`),e.choices&&e.choices.length>0){o.push("Choices:");for(let n of e.choices){let i=r(n,e.choice).map(Gc).join(" ");o.push(` ${n.label} \u2192 ${t} ${i}`)}}return`${o.join(`
|
|
711
|
+
`)}
|
|
712
|
+
`}function yi(e,t,r,o){e.json?e.deps.writeStdout(`${JSON.stringify(t,null,2)}
|
|
713
|
+
`):e.deps.writeStderr(Yc(t,r,o)),e.deps.setExitCode(1)}function pi(e,t,r,o=r){e.json?(e.deps.writeStdout(`${JSON.stringify(t,null,2)}
|
|
714
|
+
`),e.deps.writeStderr(o)):e.deps.writeStdout(r)}var fi=e=>e.credentials!==void 0?["-c",e.credentials]:e.profile===void 0?[]:["--profile",e.profile];async function Xc(e){try{return await e.isClaudeSkillStale(e.cwd)?[li]:[]}catch{return[]}}async function bi(e,t,r){let o={json:t.json===!0,deps:r},n="appbuilder block push",i=e===void 0?[]:[e],s=(l,p)=>p==="profile"?[...i,...l.args]:p==="block"?[...l.args,...fi(t)]:[...i,...fi(t),...l.args],a=l=>{yi(o,l,n,s)};try{let l=await Zt(t,r);if(!l.ok){a(l);return}let{credentials:p}=l.value,g=r.createClient(p),v=await on(e,r);if(!v.ok){a(v);return}let k=v.value;i=[k.block.api_name],k.warnings.length>0&&r.writeStderr(`${xe(k.warnings)}
|
|
715
|
+
`);let{context:f,forgotten:c}=await mn({client:g,credentials:p,block:k,forget:t.forget===!0},r);c&&r.writeStderr(`Forgot the remembered target for ${k.block.api_name}.
|
|
716
|
+
`);let h=await cn(f,t);if(!h.ok){a(h);return}let x=hn(t,p.environment);if(!x.ok){a(x);return}let I=await dn(f,h.value,t,r);if(!I.ok){a(I);return}let C=I.value,S={pluginApiName:k.pluginApiName,apiName:k.block.api_name,name:k.block.name},N={environment:p.environment,businessId:p.businessId,dashboard:C.dashboard},b=[...k.warnings.map(qc),...await Xc(r)],u=x.value;if(u.kind==="dry-run"){let _=[...b,...C.warnings],R={ok:!0,applied:!1,dryRun:!0,reason:u.reason,action:C.action,...N,dashletId:C.dashletId,url:C.url,resolvedBy:C.resolvedBy,block:S,method:C.method,path:C.path,body:C.body,warnings:_,...c?{forgotten:!0}:{}};pi(o,R,[...ut(C.summary),`URL: ${C.url}`,...He(_),"",`${C.method} ${C.path}`,JSON.stringify(C.body,null,2),""].join(`
|
|
717
|
+
`),[...ut(C.summary),...He(_),""].join(`
|
|
718
|
+
`)),u.reason==="no_yes"&&r.writeStderr(`${Jc}
|
|
719
|
+
`);return}let d=await pn(f,C,r);if(!d.ok){a(d);return}let m=d.value,y=[...b,...m.warnings],w=fn(C.dashboard.id),E={ok:!0,applied:!0,dryRun:!1,action:C.action==="create"?"created":"updated",...N,dashletId:m.dashletId,url:C.url,...w?{refresh:w}:{},resolvedBy:C.resolvedBy,block:S,remembered:m.remembered,warnings:y,...c?{forgotten:!0}:{}};pi(o,E,[`\u2713 ${E.action==="created"?"Created":"Updated"} ${k.block.name} on "${C.dashboard.name}" (dashlet ${m.dashletId})`,...ut(C.summary),`URL: ${C.url}`,...w?[`Refresh an open tab: ${w.script}`]:[],...He(y),""].join(`
|
|
720
|
+
`))}catch(l){a(Ve(l))}}var Zc=(e,t)=>e.padEnd(t);function rn(e,t){if(t.length===0)return[e," (none)"];let r=["NAME","ID","DASHLETS","ACCESS"],o=t.map(s=>[`${s.name}${s.hidden?" (hidden)":""}`,s.id,s.dashletsCount===null?"-":String(s.dashletsCount),`${s.employeeAccess??"-"}${s.canEdit===!1?" (no edit access)":""}`]),n=r.map((s,a)=>Math.max(s.length,...o.map(l=>(l[a]??"").length))),i=s=>` ${s.map((a,l)=>Zc(a,n[l]??0)).join(" ")}`.trimEnd();return[e,i(r),...o.map(i)]}function Qc(e){let t=[`Environment: ${e.environment}`,`Business: ${e.businessId}`,""];return"object"in e?t.push(e.object===null?"Custom object: not found in /custom-objects":`Custom object: ${e.object.objectName} (${e.object.id})`,"",...rn("Chart groups",e.surfaces.chart_group)):t.push(...rn("Dashboards",e.surfaces.dashboard),"",...rn("Homepages",e.surfaces.homepage),"","Custom objects",...e.customObjects.length===0?[" (none)"]:e.customObjects.map(r=>` ${r.objectName} ${r.id}`),"","List an object\u2019s chart groups with `appbuilder block targets --object <id>`."),`${t.join(`
|
|
721
|
+
`)}
|
|
722
|
+
`}async function wi(e,t){let r={json:e.json===!0,deps:t},o="appbuilder block targets",n=e.object===void 0?[]:["--object",e.object],i=a=>[...a.args,...n],s=a=>{yi(r,a,o,i)};try{let a=await Zt(e,t);if(!a.ok){s(a);return}let{credentials:l}=a.value,p=await zc(t.createClient(l),l,e.object===void 0?{}:{object:e.object});if(!p.ok){s(p);return}t.writeStdout(r.json?`${JSON.stringify(p.value,null,2)}
|
|
723
|
+
`:Qc(p.value))}catch(a){s(Ve(a))}}import{useEffect as Si,useState as rr}from"react";import{Box as se,Text as q,useApp as gd,useInput as Ti}from"ink";import"@kizenapps/packager";import{Box as nd,Text as od}from"ink";import{Box as ed,Text as td}from"ink";import{jsx as xi}from"react/jsx-runtime";var rd=[" :::::::: "," :::::: ::::::::::: "," :::::: :::::::::: "," :::::: :::::: ::::::: "," ::::: :::::: ::::::::::::::::: "," ::::: ::::: ::::::::::::::::::: "," ::::: ::::: :::::: ::::: ",":::: ::::: ::: ::::: :: ","::::: :::::: :::::::::: ","::::: :::::: ::::::::::: "," ::::: ::: ::::::: "," ::::::: ::: ::::: "," ::::::::::: :::::: :::::"," :::::::::: :::::: :::::"," :: ::::: ::: ::::: ::::"," ::::: :::::: ::::: ::::: ::: "," ::::::::::::::::::: ::::: ::::: "," ::::::::::::::::: ::::: ::::: "," ::::::::: :::::: :::::: "," :::::::::: :::::: "," ::::::::::: :::::: "," :::::::: "],vi=()=>xi(ed,{flexDirection:"column",children:rd.map((e,t)=>xi(td,{color:"cyan",children:e},t))});import{Fragment as id,jsx as gn,jsxs as sd}from"react/jsx-runtime";var K=({marginBottom:e=0})=>sd(id,{children:[gn(vi,{}),gn(nd,{flexDirection:"column",marginTop:1,marginBottom:e,children:gn(od,{bold:!0,color:"cyan",children:"Kizen App Development Toolkit"})})]});import{useMemo as ad,useState as ld}from"react";import{Box as yn,Text as We,useInput as cd}from"ink";var er=(e,t,r)=>Math.min(Math.max(e,t),r);function tr(e,t,r,o={}){if(t<=0)return 0;let n=er(Math.trunc(e)||0,0,t-1),i=l=>o.disabled?.[l]!==!0;if(r===0)return n;let s=r>0?1:-1;if(Math.abs(r)===1){for(let l=1;l<=t;l++){let p=((n+s*l)%t+t)%t;if(i(p))return p}return n}let a=er(n+Math.trunc(r),0,t-1);for(let l=a;l>=0&&l<t;l+=s)if(i(l))return l;for(let l=a-s;l>=0&&l<t;l-=s)if(i(l))return l;return n}function ki(e,t,r=10){if(t<=0)return{start:0,end:0};let o=Math.max(1,Math.floor(r));if(t<=o)return{start:0,end:t};let n=er(Math.trunc(e)||0,0,t-1),i=er(n-Math.floor(o/2),0,t-o);return{start:i,end:i+o}}import{jsx as Ke,jsxs as wn}from"react/jsx-runtime";var dd="\u2191/\u2193 to move, Enter to select, Esc to cancel",bn=10,ud=e=>{let t=tr(0,e.length,0);if(e[t]?.disabled!==!0)return t;let r=e.findIndex(o=>o.disabled!==!0);return r===-1?t:r},Je=({title:e,items:t,onSelect:r,onCancel:o,hint:n=dd})=>{let[i,s]=ld(()=>ud(t)),a=ad(()=>t.map(f=>f.disabled===!0),[t]),l=tr(i,t.length,0);cd((f,c)=>{let h=x=>{s(tr(l,t.length,x,{disabled:a}))};if(c.upArrow||f==="k")h(-1);else if(c.downArrow||f==="j")h(1);else if(c.pageUp)h(-bn);else if(c.pageDown)h(bn);else if(c.return){let x=t[l];x!==void 0&&x.disabled!==!0&&r(x,l)}else c.escape&&o?.()});let{start:p,end:g}=ki(l,t.length,bn),v=p,k=t.length-g;return wn(yn,{flexDirection:"column",gap:1,children:[Ke(We,{bold:!0,children:e}),wn(yn,{flexDirection:"column",children:[v>0&&Ke(We,{dimColor:!0,children:` \u2191 ${String(v)} more`}),t.slice(p,g).map((f,c)=>{let x=p+c===l,I=f.disabled===!0,C=x&&!I;return wn(yn,{gap:2,children:[Ke(We,{...C&&{color:"cyan"},dimColor:I,children:x?"\u276F":" "}),Ke(We,{bold:C,dimColor:I,...C&&{color:"cyan"},children:f.label}),f.description!==void 0&&Ke(We,{dimColor:!0,children:f.description})]},f.key)}),k>0&&Ke(We,{dimColor:!0,children:` \u2193 ${String(k)} more`})]}),Ke(We,{dimColor:!0,children:n})]})};import{useEffect as pd,useState as fd}from"react";import{Text as md}from"ink";import{jsx as hd}from"react/jsx-runtime";var Ci=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],ye=()=>{let[e,t]=fd(0);return pd(()=>{let r=setInterval(()=>{t(o=>(o+1)%Ci.length)},80);return()=>{clearInterval(r)}},[]),hd(md,{color:"cyan",children:Ci[e]??"\u280B"})};import{Fragment as _d,jsx as B,jsxs as J}from"react/jsx-runtime";var _i=[{key:"dashboard",label:"Dashboard"},{key:"homepage",label:"Homepage"},{key:"chart_group",label:"Chart group"}],yd={dashboard:"dashboard",homepage:"homepage",chart_group:"chart group"},xn="\u2191/\u2193 to move, Enter to select, Esc to go back",bd="The block was edited in Kizen since your last push. Overwriting discards those edits.",nr=e=>e.args.includes("--create");function Pi(e,t){let r=e.filter(i=>i.value===t),o=e.filter(nr),n=e.filter(i=>i.value!==t&&!nr(i));return r.length>0?[...r,...n,...o]:[...o,...n]}function Ze(e,t){return(r,o)=>{let n=e[o];n!==void 0&&t(n)}}function wd(e,t){if(nr(e))return{key:e.value,label:e.label};if(e.value===t)return{key:e.value,label:`Update "${e.label}" (last pushed here)`};let r=e.isFromThisPlugin?"pushed from this plugin":e.pushKey;return{key:e.value,label:`Update "${e.label}"`,...r?{description:r}:{}}}function xd(e){let t=e.dashletsCount===null?e.name:`${e.name} (${String(e.dashletsCount)} dashlets)`;if(e.canEdit===!1)return{key:e.id,label:t,description:"no edit access",disabled:!0};let r=[e.employeeAccess,e.hidden?"hidden":null].filter(o=>o!==null&&o!=="").join(" \xB7 ");return{key:e.id,label:t,...r===""?{}:{description:r}}}function vd(e,t,r){let o={...e,dashboard:t};return delete o.dashlet,delete o.create,nr(r)?{...o,create:!0}:{...o,dashlet:r.value}}function kd(e,t,r,o){let n=f=>{t.setExitCode(1),r({type:"error",view:f})},i=f=>{f().catch(c=>{n(Ve(c))})},s=async(f,c)=>{r({type:"applying",plan:c});let h=await pn(f,c,t);if(!h.ok){n(h);return}r({type:"done",plan:c,applied:h.value})},a=async(f,c,h)=>{r({type:"loading",label:"Preparing the push\u2026"});let x=await dn(f,c,h,t);if(!x.ok){if(x.code==="drift_detected"){r({type:"confirm",kind:"drift",message:x.message,target:c,options:h,context:f});return}n(x);return}if(h.dryRun){r({type:"done",plan:x.value,applied:null});return}if(h.yes){let I=hn(h,f.credentials.environment);if(I.ok&&I.value.kind==="apply"){await s(f,x.value);return}}r({type:"confirm",kind:"push",plan:x.value,options:h,context:f})},l=async(f,c,h)=>{r({type:"loading",label:"Resolving the target\u2026"});let x=await cn(f,c);if(x.ok){await a(f,x.value,c);return}let I=c.dashboard??f.entry?.dashboardId;if((x.code==="needs_choice"&&x.choice==="target"||x.code==="remembered_target_missing")&&x.choices&&x.choices.length>0&&I!==void 0){r({type:"target-select",dashboardId:I,title:"Choose a block to update, or create a new one",message:x.message,choices:Pi(x.choices,null),matchedId:null,back:h,options:c,context:f});return}n(x)},p=async(f,c,h)=>{let{context:x,forgotten:I}=await mn({client:t.createClient(c),credentials:c,block:h,forget:f.forget===!0},t);if(I&&o(C=>({...C,notices:[...C.notices,`Forgot the remembered target for ${h.block.api_name}.`]})),f.dashboard!==void 0||x.entry){await l(x,f,null);return}r({type:"surface-select",options:f,context:x})},g=async(f,c,h)=>{r({type:"packaging"});let x=await on(h,t);if(!x.ok){if(x.choice==="block"&&x.choices){r({type:"block-select",options:f,credentials:c,choices:x.choices});return}n(x);return}o(I=>({...I,warnings:x.value.warnings})),await p(f,c,x.value)},v=async f=>{r({type:"loading",label:"Loading credentials\u2026"});let c=await Zt(f,t);if(!c.ok){if(c.choice==="profile"&&c.choices){r({type:"profile-select",options:f,choices:c.choices});return}n(c);return}let{credentials:h}=c.value;o(x=>({...x,credentials:h})),await g(f,h,e)},k=async({options:f,context:c},h,x,I)=>{let C=yd[h];r({type:"loading",label:`Loading ${C}s\u2026`});let N=(await c.client.listDashboards(ko(h),x?.id)).map(d=>dt(d,h)),{environment:b,businessId:u}=c.credentials;if(N.length===0){n({message:`No ${C}s found${x?` on ${x.objectName}`:""} for business ${u} (${b}).`});return}r({type:"dashboard-select",surface:h,objectId:x?.id??null,title:x?`Choose a chart group on ${x.objectName}`:`Choose a ${C}`,rows:N,back:I,options:f,context:c})};return{start:f=>{i(()=>v(f))},pickProfile:(f,c)=>{i(()=>v({...f.options,profile:c.value}))},pickBlock:(f,c)=>{i(()=>g(f.options,f.credentials,c.value))},pickSurface:(f,c)=>{i(async()=>{if(c!=="chart_group"){await k(f,c,null,f);return}r({type:"loading",label:"Loading custom objects\u2026"});let h=await sn(f.context.client);if(h.length===0){n({message:"No custom objects found, so there are no chart groups to push to."});return}r({type:"object-select",objects:h,back:f,options:f.options,context:f.context})})},pickObject:(f,c)=>{i(()=>k(f,"chart_group",c,f))},pickDashboard:(f,c)=>{i(async()=>{let{context:h}=f,x={...f.options,dashboard:c.id};if(x.dashlet!==void 0||x.create){await l(h,x,f);return}r({type:"loading",label:`Loading "${c.name}"\u2026`});let I=await h.client.getDashboard(c.id),C=ln(h,I),S=C.kind==="map"||C.kind==="name"?C.dashlet.id:null;r({type:"target-select",dashboardId:I.id,title:`Choose what to push to on "${I.name}"`,message:null,choices:Pi(Qt(I,h.block),S),matchedId:S,back:f,options:x,context:h})})},pickTarget:(f,c)=>{i(()=>l(f.context,vd(f.options,f.dashboardId,c),f))},acceptDrift:f=>{i(()=>a(f.context,f.target,{...f.options,force:!0}))},acceptPush:f=>{i(()=>s(f.context,f.plan))},cancel:()=>{n({message:"Cancelled."})}}}var Ei=({prompt:e,strict:t,onAccept:r,onCancel:o})=>(Ti((n,i)=>{if(i.ctrl)return;let s=n.toLowerCase();s==="y"||!t&&i.return?r():(t||s==="n"||i.escape)&&o()}),B(q,{bold:!0,children:e})),Qe=({lines:e,color:t})=>B(se,{flexDirection:"column",children:e.map((r,o)=>B(q,{...t&&{color:t},children:r},`${String(o)}-${r}`))}),Ii=({plan:e})=>J(se,{flexDirection:"column",children:[B(Qe,{lines:ut(e.summary)}),J(q,{children:["URL: ",e.url]})]}),vn=({label:e})=>J(se,{gap:1,children:[B(ye,{}),B(q,{dimColor:!0,children:e})]}),Cd=({view:e})=>J(se,{flexDirection:"column",gap:1,children:[J(se,{gap:1,children:[B(q,{color:"red",children:"\u2717"}),B(q,{color:"red",children:e.issues&&e.issues.length>0?xe(e.issues):e.message})]}),e.hint!==void 0&&J(q,{dimColor:!0,children:["Hint: ",e.hint]}),e.choices&&e.choices.length>0&&J(se,{flexDirection:"column",children:[B(q,{children:"Choices:"}),B(Qe,{lines:e.choices.map(t=>` ${t.label}`)})]})]}),Sd=({plan:e,applied:t})=>{let r=fn(e.dashboard.id);return t===null?J(se,{flexDirection:"column",gap:1,children:[B(q,{color:"yellow",children:"Dry run: nothing was written."}),B(Ii,{plan:e}),e.warnings.length>0&&B(Qe,{lines:He(e.warnings),color:"yellow"}),J(se,{flexDirection:"column",children:[J(q,{bold:!0,children:[e.method," ",e.path]}),B(q,{children:JSON.stringify(e.body,null,2)})]})]}):J(se,{flexDirection:"column",gap:1,children:[J(se,{gap:1,children:[B(q,{color:"green",children:"\u2713"}),J(q,{bold:!0,children:[e.action==="create"?"Created":"Updated"," ",e.summary.blockName,' on "',e.dashboard.name,'"']})]}),J(se,{flexDirection:"column",children:[J(q,{children:["URL: ",e.url]}),r&&J(q,{dimColor:!0,children:["Refresh an open tab: ",r.script]})]}),t.warnings.length>0&&B(Qe,{lines:He(t.warnings),color:"yellow"})]})},Di=({apiName:e,options:t,deps:r})=>{let o=gd(),[n,i]=rr({type:"loading",label:"Loading credentials\u2026"}),[s,a]=rr({credentials:null,warnings:[],notices:[]}),[l]=rr(()=>kd(e,r,i,a)),[p]=rr(t);Si(()=>{l.start(p)},[l,p]),Si(()=>{(n.type==="done"||n.type==="error")&&o.exit()},[n,o]),Ti((v,k)=>{k.ctrl&&v==="c"&&n.type!=="done"&&n.type!=="error"&&(r.setExitCode(130),o.exit())});let g=v=>J(se,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[B(K,{}),s.credentials&&J(q,{dimColor:!0,children:["Environment: ",s.credentials.environment," \xB7 Business:"," ",s.credentials.businessId]}),s.warnings.length>0&&B(q,{dimColor:!0,children:xe(s.warnings)}),s.notices.length>0&&B(Qe,{lines:s.notices}),v]});switch(n.type){case"loading":return g(B(vn,{label:n.label}));case"packaging":return g(B(vn,{label:"Packaging blocks\u2026"}));case"applying":return g(B(vn,{label:`Pushing ${n.plan.summary.blockName} to "${n.plan.dashboard.name}"\u2026`}));case"profile-select":return g(B(Je,{title:"Credential profile",items:n.choices.map(v=>({key:v.value,label:v.label})),onSelect:Ze(n.choices,v=>{l.pickProfile(n,v)}),onCancel:l.cancel},"profile"));case"block-select":return g(B(Je,{title:"Block to push",items:n.choices.map(v=>({key:v.value,label:v.label})),onSelect:Ze(n.choices,v=>{l.pickBlock(n,v)}),onCancel:l.cancel},"block"));case"surface-select":return g(B(Je,{title:"Where should the block go?",items:_i,onSelect:Ze(_i,v=>{l.pickSurface(n,v.key)}),onCancel:l.cancel},"surface"));case"object-select":return g(B(Je,{title:"Custom object",items:n.objects.map(v=>({key:v.id,label:v.objectName})),onSelect:Ze(n.objects,v=>{l.pickObject(n,v)}),onCancel:()=>{i(n.back)},hint:xn},"object"));case"dashboard-select":return g(B(Je,{title:n.title,items:n.rows.map(xd),onSelect:Ze(n.rows,v=>{l.pickDashboard(n,v)}),onCancel:()=>{i(n.back)},hint:xn},`dashboards-${n.surface}-${n.objectId??""}`));case"target-select":{let{back:v}=n;return g(J(_d,{children:[n.message!==null&&B(q,{color:"yellow",children:n.message}),B(Je,{title:n.title,items:n.choices.map(k=>wd(k,n.matchedId)),onSelect:Ze(n.choices,k=>{l.pickTarget(n,k)}),onCancel:v?()=>{i(v)}:l.cancel,...v&&{hint:xn}},`targets-${n.dashboardId}`)]}))}case"confirm":return n.kind==="drift"?g(J(se,{flexDirection:"column",gap:1,children:[B(q,{color:"yellow",children:bd}),B(q,{dimColor:!0,children:n.message}),B(Ei,{prompt:"Type y to overwrite (y/N)",strict:!0,onAccept:()=>{l.acceptDrift(n)},onCancel:l.cancel},"drift")]})):g(J(se,{flexDirection:"column",gap:1,children:[B(Ii,{plan:n.plan}),n.plan.warnings.length>0&&B(Qe,{lines:He(n.plan.warnings),color:"yellow"}),n.plan.summary.isProduction&&B(q,{color:"red",bold:!0,children:"PRODUCTION"}),B(Ei,{prompt:n.plan.summary.isProduction?"Type y to push to production (y/N)":"Push? (Y/n)",strict:n.plan.summary.isProduction,onAccept:()=>{l.acceptPush(n)},onCancel:l.cancel},"push")]}));case"done":return g(B(Sd,{plan:n.plan,applied:n.applied}));case"error":return g(B(Cd,{view:n.view}))}};var Ni=e=>`Error: ${e instanceof Error?e.message:String(e)}`,Id=e=>e instanceof Td?xe(e.issues):Ni(e),Ai=e=>{console.error(Ni(e)),process.exitCode=1};function Bi(e){let t=e.command("block").description("Work with plugin content blocks");t.command("export").description("Print one packaged block as JSON for the Custom Block (AI Coded) paste editor").argument("[api_name]","api_name of the block to export (optional when there is only one)").option("--copy","also copy the JSON to the clipboard").action(async(r,o)=>{try{let n=await Oo(process.cwd(),r),{block:i,warnings:s}=n;s.length>0&&console.error(xe(s));let a=JSON.stringify(jo(n),null,2);console.log(a),o.copy&&console.error(await At(a)?`Copied block "${i.api_name}" to the clipboard.`:"Couldn't copy to the clipboard; use the JSON printed to stdout instead.")}catch(n){console.error(Id(n)),process.exitCode=1}}),t.command("push").description("Push a block to a Kizen dashboard, homepage or chart group dashlet").argument("[api_name]","api_name of the block to push (optional when there is only one)").option("-c, --credentials <path>","path to a credentials JSON file").option("--profile <name>","stored credential profile to use").option("--dashboard <id>","dashboard, homepage or chart group to push to").option("--dashlet <id>","existing custom code dashlet to update (needs --dashboard)").option("--create","create a new dashlet instead of updating one").option("--dry-run","show the request without writing anything").option("--yes","write without asking (headless runs are dry runs without it)").option("--allow-production","allow headless writes to go/fmo").option("--force","overwrite even if the block was edited in Kizen since the last push").option("--forget","clear the remembered target for this block first").option("--json","print a JSON result to stdout (always headless)").action(async(r,o)=>{try{if(!process.stdin.isTTY||!process.stdout.isTTY||o.json===!0){await bi(r,o,Xt(process.cwd()));return}let{waitUntilExit:n}=Ed(Pd(Di,{...r!==void 0&&{apiName:r},options:o,deps:Xt(process.cwd())}),{exitOnCtrlC:!1});await n()}catch(n){Ai(n)}}),t.command("targets").description("List the dashboards, homepages and chart groups a block can be pushed to").option("-c, --credentials <path>","path to a credentials JSON file").option("--profile <name>","stored credential profile to use").option("--object <id>","list the chart groups of this custom object").option("--json","print a JSON result to stdout").action(async r=>{try{await wi(r,Xt(process.cwd()))}catch(o){Ai(o)}})}import{createElement as Bd}from"react";import{render as Rd}from"ink";import{useEffect as $i,useState as mt}from"react";import{Box as ht,Text as et,useApp as Dd}from"ink";import{PluginValidationError as Ad}from"@kizenapps/packager";function pt(e){return e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}import{Box as kn,Text as or}from"ink";import{jsx as Ri,jsxs as ft}from"react/jsx-runtime";var ir=({issues:e})=>{let t=e.filter(r=>r.severity==="error").length;return ft(kn,{flexDirection:"column",marginTop:1,children:[ft(or,{color:"red",children:["\u2717 ",t," validation ",t===1?"error":"errors"]}),[...Gr(e)].map(([r,o])=>ft(kn,{flexDirection:"column",marginTop:1,children:[Ri(or,{bold:!0,children:r}),o.map((n,i)=>Ri(kn,{paddingLeft:2,children:ft(or,{color:n.severity==="error"?"red":"yellow",children:[n.severity==="error"?"\u2717":"\u26A0"," ",n.message," ",ft(or,{dimColor:!0,children:["(",n.rule,")"]})]})},`${n.rule}-${String(i)}`))]},r))]})};import{Fragment as Nd,jsx as Be,jsxs as qe}from"react/jsx-runtime";var Fi=["creating-dir","reading-files","validating","minifying","packaging","writing-bundle"],sr={"creating-dir":"Creating .kizenapp directory","reading-files":"Reading plugin files",validating:"Validating plugin app",minifying:"Minifying scripts",packaging:"Packaging plugin","writing-bundle":"Writing bundle.json"},ji=({outputDir:e,pluginDir:t})=>{let r=Dd(),[o,n]=mt("creating-dir"),[i,s]=mt(!1),[a,l]=mt(null),[p,g]=mt(null),[v,k]=mt(null);$i(()=>{Lt(t,e,n).then(({bundleSize:h})=>{k(h),n("done")}).catch(h=>{h instanceof Ad?l(h.issues):g(h instanceof Error?h.message:String(h)),s(!0),process.exitCode=1})},[e,t]),$i(()=>{(o==="done"||i)&&r.exit()},[o,i,r]);let f=Fi.indexOf(o),c=o==="done";return qe(ht,{flexDirection:"column",paddingY:1,paddingX:2,children:[Be(K,{marginBottom:1}),qe(ht,{flexDirection:"column",gap:0,children:[Fi.map((h,x)=>{let I=o===h,C=c||f>x;return Be(ht,{gap:1,children:i&&x===f?qe(et,{color:"red",children:["\u2717 ",sr[h]]}):C?qe(et,{color:"green",children:["\u2713 ",sr[h]]}):I?qe(Nd,{children:[Be(ye,{}),Be(et,{children:sr[h]})]}):qe(et,{dimColor:!0,children:[" ",sr[h]]})},h)}),c&&v!==null&&Be(ht,{marginTop:1,gap:1,children:qe(et,{color:"green",children:["\u2713 bundle \u2014 ",pt(v)]})}),a!==null&&Be(ir,{issues:a}),p!==null&&Be(ht,{marginTop:1,borderStyle:"single",borderColor:"red",paddingX:1,children:Be(et,{color:"red",children:p})})]})]})};function Oi(e){e.command("build").description("Bundle the plugin app into .kizenapp directory").action(async()=>{let t=process.cwd(),r=`${t}/.kizenapp`;ge(t);let{waitUntilExit:o}=Rd(Bd(ji,{outputDir:r,pluginDir:t}));await o()})}import{createElement as Eu}from"react";import{render as Tu}from"ink";import{useCallback as fr,useState as tt}from"react";import{Box as V,Text as D,useApp as xu,useInput as vu}from"ink";import{join as mr}from"path";import{access as gu,mkdir as lr,writeFile as Tn}from"fs/promises";import{dirname as yu,join as Ce}from"path";var Li=`{
|
|
8
724
|
"name": "Hello Frame",
|
|
9
725
|
"api_name": "hello_frame",
|
|
10
726
|
"title": "Hello Frame",
|
|
@@ -13,13 +729,13 @@ import{readFileSync as ul}from"fs";import{dirname as fl,join as ml}from"path";im
|
|
|
13
729
|
"height": 320,
|
|
14
730
|
"width": 280
|
|
15
731
|
}
|
|
16
|
-
`;var
|
|
732
|
+
`;var zi=`this.outputUI(\`
|
|
17
733
|
<div class="hello-frame">
|
|
18
734
|
<h2 class="hello-frame__title">Hello from a floating frame</h2>
|
|
19
735
|
<p class="hello-frame__body">Edit src/floatingFrames/helloFrame/script.js to change this.</p>
|
|
20
736
|
</div>
|
|
21
737
|
\`);
|
|
22
|
-
`;var
|
|
738
|
+
`;var Mi=`.hello-frame {
|
|
23
739
|
padding: 16px;
|
|
24
740
|
font-family: system-ui, sans-serif;
|
|
25
741
|
}
|
|
@@ -33,18 +749,18 @@ import{readFileSync as ul}from"fs";import{dirname as fl,join as ml}from"path";im
|
|
|
33
749
|
margin: 0;
|
|
34
750
|
color: #555;
|
|
35
751
|
}
|
|
36
|
-
`;var
|
|
752
|
+
`;var Ui=`{
|
|
37
753
|
"name": "Hello Block",
|
|
38
754
|
"api_name": "hello_block",
|
|
39
755
|
"types": ["dashboards"]
|
|
40
756
|
}
|
|
41
|
-
`;var
|
|
757
|
+
`;var Hi=`this.outputUI(\`
|
|
42
758
|
<div class="hello-block">
|
|
43
759
|
<h2 class="hello-block__title">Hello from a block</h2>
|
|
44
760
|
<p class="hello-block__body">Edit src/blocks/helloBlock/script.js to change this.</p>
|
|
45
761
|
</div>
|
|
46
762
|
\`);
|
|
47
|
-
`;var
|
|
763
|
+
`;var Vi=`.hello-block {
|
|
48
764
|
padding: 16px;
|
|
49
765
|
font-family: system-ui, sans-serif;
|
|
50
766
|
background: #f8fafc;
|
|
@@ -60,25 +776,25 @@ import{readFileSync as ul}from"fs";import{dirname as fl,join as ml}from"path";im
|
|
|
60
776
|
margin: 0;
|
|
61
777
|
color: #555;
|
|
62
778
|
}
|
|
63
|
-
`;var
|
|
779
|
+
`;var Wi=`{
|
|
64
780
|
"icon": "phone",
|
|
65
781
|
"color": "#0ea5e9",
|
|
66
782
|
"tooltip": "Hello adornment",
|
|
67
783
|
"field_type": "phonenumber"
|
|
68
784
|
}
|
|
69
|
-
`;var
|
|
70
|
-
`;var
|
|
785
|
+
`;var Ki=`this.showToast('Hello from a data adornment.', { variant: 'success' });
|
|
786
|
+
`;var Ji=`{
|
|
71
787
|
"name": "Hello Page",
|
|
72
788
|
"api_name": "hello_page"
|
|
73
789
|
}
|
|
74
|
-
`;var
|
|
790
|
+
`;var qi=`this.outputUI(\`
|
|
75
791
|
<div class="hello-page">
|
|
76
792
|
<p class="hello-page__loading">Loading\u2026</p>
|
|
77
793
|
</div>
|
|
78
794
|
\`);
|
|
79
795
|
|
|
80
796
|
this.runEventScript('greet');
|
|
81
|
-
`;var
|
|
797
|
+
`;var Gi=`.hello-page {
|
|
82
798
|
padding: 24px;
|
|
83
799
|
font-family: system-ui, sans-serif;
|
|
84
800
|
}
|
|
@@ -116,7 +832,7 @@ this.runEventScript('greet');
|
|
|
116
832
|
.hello-page__button:hover {
|
|
117
833
|
background: #cbd5e1;
|
|
118
834
|
}
|
|
119
|
-
`;var
|
|
835
|
+
`;var Yi=`const tone = this.args?.formData?.tone?.[0] ?? 'plain';
|
|
120
836
|
|
|
121
837
|
const greeting = tone === 'cheer' ? 'Hello, and good to see you!' : 'Hello from a routable page.';
|
|
122
838
|
|
|
@@ -139,138 +855,33 @@ this.outputUI(\`
|
|
|
139
855
|
</div>
|
|
140
856
|
</div>
|
|
141
857
|
\`);
|
|
142
|
-
`;var
|
|
858
|
+
`;var Xi=`{
|
|
143
859
|
"api_name": "hello_toolbar_item",
|
|
144
860
|
"label": "Hello Toolbar Item",
|
|
145
861
|
"icon": "star",
|
|
146
862
|
"color": "#0ea5e9"
|
|
147
863
|
}
|
|
148
|
-
`;var
|
|
149
|
-
`;var
|
|
864
|
+
`;var Zi=`this.showToast('Hello from a toolbar item.', { variant: 'success' });
|
|
865
|
+
`;var Qi=`{
|
|
150
866
|
"api_name": "hello_object_settings_item",
|
|
151
867
|
"label": "Hello Object Settings"
|
|
152
868
|
}
|
|
153
|
-
`;var
|
|
154
|
-
`;var
|
|
869
|
+
`;var es=`this.showToast('Hello from an object settings item.', { variant: 'success' });
|
|
870
|
+
`;var ts=`{
|
|
155
871
|
"name": "Hello Action",
|
|
156
872
|
"api_name": "hello_action",
|
|
157
873
|
"hint_object_name": "client_client"
|
|
158
874
|
}
|
|
159
|
-
`;var
|
|
160
|
-
`;var
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
## The full Kizen plugin documentation is available at \`.copilot-docs/\`
|
|
168
|
-
|
|
169
|
-
Before this review started, the complete Kizen plugin developer documentation
|
|
170
|
-
was fetched into \`.copilot-docs/\` by \`.github/workflows/copilot-code-review.yml\`.
|
|
171
|
-
It is not committed to this repo \u2014 it is cloned from \`kizen/app-engine\` at review
|
|
172
|
-
time, so it is always current. It is the authoritative reference for every plugin
|
|
173
|
-
API, manifest field and runtime contract. Deliberately, no plugin rules are
|
|
174
|
-
copied into this repo: read them from \`.copilot-docs/\` instead.
|
|
175
|
-
|
|
176
|
-
Use it. Start from:
|
|
177
|
-
|
|
178
|
-
- \`.copilot-docs/17-gotchas.md\` \u2014 the consolidated list of traps and silent
|
|
179
|
-
failure modes, grouped by topic. Scan the sections relevant to the changed
|
|
180
|
-
files.
|
|
181
|
-
- \`.copilot-docs/method-index.md\` \u2014 A\u2013Z lookup from any method, manifest field,
|
|
182
|
-
endpoint or identifier to the doc that owns it.
|
|
183
|
-
- \`.copilot-docs/03-manifest-reference.md\` \u2014 every \`kizen.json\` and \`config.json\`
|
|
184
|
-
field, the component directory names, \`api_name\` rules, and the build/publish
|
|
185
|
-
validation rules.
|
|
186
|
-
- The other numbered docs (\`.copilot-docs/04-worker-runtime-api.md\`,
|
|
187
|
-
\`.copilot-docs/07-automation-steps.md\`, \`.copilot-docs/08-actions.md\`, and so
|
|
188
|
-
on) for complete contracts.
|
|
189
|
-
|
|
190
|
-
**Many Kizen plugin APIs fail silently when misused** \u2014 the call succeeds,
|
|
191
|
-
nothing throws, and the behavior is quietly wrong. These defects are not
|
|
192
|
-
detectable from the calling code alone, and they are the single most valuable
|
|
193
|
-
thing to catch in review. When a changed file calls a \`this.*\` worker method,
|
|
194
|
-
look that method up in \`method-index.md\` and read its contract before concluding
|
|
195
|
-
the call is correct.
|
|
196
|
-
|
|
197
|
-
The same applies to artifact config: check each \`config.json\` against
|
|
198
|
-
\`03-manifest-reference.md\`, and each automation step against
|
|
199
|
-
\`07-automation-steps.md\`.
|
|
200
|
-
|
|
201
|
-
When a review comment is based on the documentation, name the file it came from.
|
|
202
|
-
|
|
203
|
-
If \`.copilot-docs/\` is not present, the setup workflow did not run \u2014 it only
|
|
204
|
-
takes effect once it is on the repository's default branch \u2014 so say that in
|
|
205
|
-
the review instead of guessing at the rules from memory.
|
|
206
|
-
|
|
207
|
-
## Scope
|
|
208
|
-
|
|
209
|
-
This file covers repo structure and general review. Two path-scoped files cover
|
|
210
|
-
the rest: \`.github/instructions/security.instructions.md\` for security-sensitive
|
|
211
|
-
patterns and \`.github/instructions/version-discipline.instructions.md\` for
|
|
212
|
-
manifest version bumps.
|
|
213
|
-
`;var Jr='---\napplyTo: "src/**/*.js,kizen.json"\n---\n\n# Security review rules for plugin scripts\n\nThe rules themselves live in the docs corpus that\n`.github/workflows/copilot-code-review.yml` fetches into `.copilot-docs/`, so\nthey cannot drift out of date here. Read them there rather than reviewing from\nmemory.\n\nWhen a change touches a service, `auth_credentials`, a `{{secret.KEY}}`\nreference, `base_config.secrets`, or dynamic code (`eval`, `new Function`, or a\nstring argument to `setTimeout` or `setInterval`), read\n`.copilot-docs/06-auth-secrets-services.md` together with the "Services, auth &\nsecrets" and "Release & publish" sections of `.copilot-docs/17-gotchas.md`, and\nreview the change against what they say.\n\nWhen a change uses `__dangerouslySkipProxy`, also read\n`.copilot-docs/11-output-ui-iframes-frames.md`.\n';var Wr=`---
|
|
214
|
-
applyTo: "kizen.json"
|
|
215
|
-
---
|
|
216
|
-
|
|
217
|
-
# Version-bump discipline for \`kizen.json\`
|
|
218
|
-
|
|
219
|
-
The bump matrix lives in the docs corpus that
|
|
220
|
-
\`.github/workflows/copilot-code-review.yml\` fetches into \`.copilot-docs/\`, so it
|
|
221
|
-
cannot drift out of date here.
|
|
222
|
-
|
|
223
|
-
Check every \`kizen.json\` diff against the "How big a bump?" matrix in
|
|
224
|
-
\`.copilot-docs/16-release-and-publish.md\` and the "Release & publish" section of
|
|
225
|
-
\`.copilot-docs/17-gotchas.md\`, and name the change that sets the required level.
|
|
226
|
-
`;var Gr=`# Copilot only reads this file from the default branch, and only if the job is named copilot-setup-steps.
|
|
227
|
-
name: Copilot code review setup
|
|
228
|
-
|
|
229
|
-
on:
|
|
230
|
-
workflow_dispatch:
|
|
231
|
-
|
|
232
|
-
jobs:
|
|
233
|
-
copilot-setup-steps:
|
|
234
|
-
runs-on: ubuntu-latest
|
|
235
|
-
timeout-minutes: 10
|
|
236
|
-
permissions:
|
|
237
|
-
contents: read
|
|
238
|
-
steps:
|
|
239
|
-
- name: Check out this plugin repo
|
|
240
|
-
uses: actions/checkout@v4
|
|
241
|
-
|
|
242
|
-
- name: Fetch the Kizen plugin docs corpus into .copilot-docs/
|
|
243
|
-
run: |
|
|
244
|
-
set -euo pipefail
|
|
245
|
-
git clone --depth 1 --filter=blob:none --sparse \\
|
|
246
|
-
https://github.com/kizen/app-engine.git .docs-src
|
|
247
|
-
git -C .docs-src sparse-checkout set --no-cone '/docs/**/*.md' '!/docs/site/**'
|
|
248
|
-
mv .docs-src/docs .copilot-docs
|
|
249
|
-
rm -rf .docs-src
|
|
250
|
-
|
|
251
|
-
- name: Verify the corpus landed
|
|
252
|
-
run: |
|
|
253
|
-
set -euo pipefail
|
|
254
|
-
test -f .copilot-docs/17-gotchas.md
|
|
255
|
-
test -f .copilot-docs/method-index.md
|
|
256
|
-
|
|
257
|
-
numbered=$(find .copilot-docs -maxdepth 1 -name '[0-9][0-9]-*.md' | wc -l | tr -d ' ')
|
|
258
|
-
test "$numbered" -ge 18
|
|
259
|
-
test -f .copilot-docs/examples/kitchen_sink.md
|
|
260
|
-
|
|
261
|
-
count=$(find .copilot-docs -name '*.md' | wc -l | tr -d ' ')
|
|
262
|
-
echo "Fetched $count markdown files into .copilot-docs/ ($numbered numbered docs)"
|
|
263
|
-
test "$count" -ge 24
|
|
264
|
-
du -sh .copilot-docs
|
|
265
|
-
`;function lt(){return[{path:".github/copilot-instructions.md",content:qr},{path:".github/instructions/security.instructions.md",content:Jr},{path:".github/instructions/version-discipline.instructions.md",content:Wr},{path:".github/workflows/copilot-code-review.yml",content:Gr}]}import{deflateSync as Hi}from"zlib";var Ht=512,Ui=150,Vi=26,Ut=46,Kr=.6,qi=Ut*.55,Ji=.55,Wi=.47;function Gi(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=t+((t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24))>>>0;return t}function Ki(e){let t=Gi(e);return{hue:t%360,quarterTurns:(t>>>16)%4}}function Yi(e,t,n){let o=(1-Math.abs(2*n-1))*t,r=e/60,i=o*(1-Math.abs(r%2-1)),p=n-o/2,[f,g,m]=r<1?[o,i,0]:r<2?[i,o,0]:r<3?[0,o,i]:r<4?[0,i,o]:r<5?[i,0,o]:[o,0,i];return[Math.round((f+p)*255),Math.round((g+p)*255),Math.round((m+p)*255)]}function Ue(e,t,n,o,r){let i=Math.abs(e)-n+r,p=Math.abs(t)-o+r;return Math.hypot(Math.max(i,0),Math.max(p,0))+Math.min(Math.max(i,p),0)-r}function ct(e,t,n,o,r){return Math.hypot(e-n,t-o)-r}function Xi(e,t){let n=Ui,o=Ut,r=o*Kr,i=qi,p=Ue(e,t,n,n,Vi),f=Math.min(ct(e,t,0,-n-r,o),Ue(e,t+n+r/2,i,r/2+1,0)),g=Math.min(ct(e,t,n+r,0,o),Ue(e-n-r/2,t,r/2+1,i,0));p=Math.min(p,f,g);let m=Math.min(ct(e,t,0,n-r,o),Ue(e,t-n+r/2,i,r/2+1,0)),y=Math.min(ct(e,t,-n+r,0,o),Ue(e+n-r/2,t,r/2+1,i,0));return Math.max(p,-m,-y)}function Zi(e){let t=Ht,n=new Uint8Array(t*t*4),[o,r,i]=Yi(e.hue,Ji,Wi),p=Ut*(1+Kr),f=(t-1)/2,g=p/2;for(let m=0;m<t;m+=1)for(let y=0;y<t;y+=1){let T=y-f,P=m-f;for(let w=0;w<e.quarterTurns;w+=1)[T,P]=[-P,T];let x=Xi(T+g,P-g),c=Math.min(1,Math.max(0,.5-x));if(c<=0)continue;let b=(m*t+y)*4;n[b]=o,n[b+1]=r,n[b+2]=i,n[b+3]=Math.round(c*255)}return n}var Qi=new Uint32Array(256).map((e,t)=>{let n=t;for(let o=0;o<8;o+=1)n=n&1?3988292384^n>>>1:n>>>1;return n>>>0});function es(e){let t=4294967295;for(let n of e)t=(Qi[(t^n)&255]??0)^t>>>8;return(t^4294967295)>>>0}function Mt(e,t){let n=Buffer.from(e,"latin1"),o=Buffer.alloc(4);o.writeUInt32BE(t.length);let r=Buffer.alloc(4);return r.writeUInt32BE(es(Buffer.concat([n,t]))),Buffer.concat([o,n,t,r])}var ts=Buffer.from([137,80,78,71,13,10,26,10]);function rs(e,t,n){if(n.length!==e*t*4)throw new Error(`encodePng: expected ${String(e*t*4)} bytes of RGBA for ${String(e)}x${String(t)}, got ${String(n.length)}`);let o=Buffer.alloc(13);o.writeUInt32BE(e,0),o.writeUInt32BE(t,4),o[8]=8,o[9]=6;let r=e*4,i=Buffer.alloc((r+1)*t);for(let p=0;p<t;p+=1)i.set(n.subarray(p*r,(p+1)*r),p*(r+1)+1);return Buffer.concat([ts,Mt("IHDR",o),Mt("IDAT",Hi(i,{level:9})),Mt("IEND",new Uint8Array(0))])}function Yr(e){return rs(Ht,Ht,Zi(Ki(e)))}var is="src/thumbnail.png",ss=["go","fmo"];async function pt(e){try{return await ns(e),!0}catch{return!1}}async function ye(e){return await pt(ce(e,"kizen.json"))?"has-manifest":await pt(ce(e,".kizenapp"))?"has-kizenapp":"ok"}async function Zr(e,t){let n=ce(e,t);if(!await pt(n))return n;for(let o=1;o<1e3;o++){let r=ce(e,`${t}-${String(o)}`);if(!await pt(r))return r}throw new Error(`Could not find an available directory name for "${t}"`)}function qt(e){let t=e.developerBusinessId.trim(),n=t!==""&&!ss.includes(e.developerEnvironment)?[e.developerEnvironment]:["prod"];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:n,config_template:{},base_config:{},...t?{developer_business_id:{[e.developerEnvironment]:t}}:{}}}async function Xr(e,t){let n=t.map(r=>({fullPath:ce(e,...r.path.split("/")),content:r.content})),o=new Set(n.map(r=>os(r.fullPath)));await Promise.all([...o].map(r=>dt(r,{recursive:!0}))),await Promise.all(n.map(r=>Vt(r.fullPath,r.content,"utf-8")))}async function ut(e){await dt(e.targetDir,{recursive:!0});let t=qt(e);await Vt(ce(e.targetDir,"kizen.json"),JSON.stringify(t,null,2)+`
|
|
266
|
-
`,"utf-8"),await dt(ce(e.targetDir,"src"),{recursive:!0}),await dt(ce(e.targetDir,"releaseNotes"),{recursive:!0}),await Promise.all([Xr(e.targetDir,Vr(e.artifacts??[])),Xr(e.targetDir,lt()),Vt(ce(e.targetDir,...is.split("/")),Yr(e.apiName))]),he(e.targetDir)}var be=["name","apiName","externalLink","description","developerBusinessId"],ft={name:"Name",apiName:"API name",externalLink:"External link",description:"Description",developerBusinessId:"Business ID"},Jt=["name","apiName","description"],Wt=/^[a-z_][a-z0-9_]+$/,Gt="must start with a letter or underscore and contain only lowercase letters, numbers, or underscores (minimum 2 characters)";function mt(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}function Qr(e){return{name:"",apiName:"",externalLink:"",description:"",developerBusinessId:e}}function en(e,t){let n=t.trim();if(Jt.includes(e)&&!n)return`${ft[e]} is required`;if(e==="apiName"&&!Wt.test(n))return`${ft[e]} ${Gt}`}function tn(e,t){return e==="description"?t:t.trim()}function rn(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),X.filter(o=>n.has(o))}import{jsx as _,jsxs as B}from"react/jsx-runtime";var Ie=({text:e})=>_(I,{dimColor:!0,children:e}),nn=({parentDir:e,defaultBusinessId:t,defaultEnvironment:n})=>{let o=as(),[r,i]=De({type:"target-select",cursor:0}),[p,f]=De("in-place"),[g,m]=De(()=>Qr(t)),[y,T]=De(()=>[...X]),[P,x]=De(""),[c,b]=De(e),w=gt((v,d)=>{f(v),x(d.name),i({type:"field-entry",field:0,values:d})},[]),H=gt(async v=>{let d=await ye(v);if(d!=="ok"){i({type:"precheck-error",targetDir:v,reason:d});return}b(v),w("in-place",g)},[g,w]),j=gt(async(v,d)=>{try{let l=await Zr(e,v.apiName);b(l),i({type:"confirm",values:v,artifacts:d})}catch(l){i({type:"error",message:l instanceof Error?l.message:String(l)})}},[e]),C=gt(async(v,d,l)=>{try{await ut({targetDir:d,name:v.name,apiName:v.apiName,externalLink:v.externalLink,description:v.description,developerBusinessId:v.developerBusinessId,developerEnvironment:n,artifacts:l}),i({type:"done",targetDir:d})}catch(s){i({type:"error",message:s instanceof Error?s.message:String(s)})}},[n]);if(ls((v,d)=>{if(d.ctrl&&v==="c"){o.exit();return}if(r.type==="target-select"){d.upArrow?i({type:"target-select",cursor:0}):d.downArrow?i({type:"target-select",cursor:1}):d.return?r.cursor===0?H(e):w("sub-dir",g):d.escape&&o.exit();return}if(r.type==="precheck-error"){(d.return||d.escape)&&o.exit();return}if(r.type==="field-entry"){let{field:l,values:s}=r,a=be[l];if(!a)return;if(d.escape){o.exit();return}if(d.backspace||d.delete){x(u=>u.slice(0,-1));return}if(d.upArrow&&l>0){let u={...s,[a]:P},h=l-1,k=be[h];i({type:"field-entry",field:h,values:u}),m(u),x(k?u[k]:"");return}if(d.return||d.tab||d.downArrow){let u=en(a,P);if(u!==void 0){i({type:"field-entry",field:l,values:s,fieldError:u});return}let h=tn(a,P),k={...s,[a]:h};m(k);let E=l+1;if(E>=be.length)x(""),i({type:"artifact-select",values:k,cursor:0,selected:y});else{let R=be[E],z=R?k[R]:"",W=R==="apiName"&&!z?mt(k.name):z;i({type:"field-entry",field:E,values:k}),x(W)}return}v&&!d.ctrl&&!d.meta&&x(u=>u+v);return}if(r.type==="artifact-select"){let{cursor:l,selected:s,values:a}=r;if(d.escape){let u=be.length-1,h=be[u];i({type:"field-entry",field:u,values:a}),x(h?a[h]:"");return}if(d.upArrow){i({...r,cursor:Math.max(0,l-1)});return}if(d.downArrow){i({...r,cursor:Math.min(X.length-1,l+1)});return}if(v===" "){let u=X[l];if(u){let h=rn(s,u);T(h),i({...r,selected:h})}return}if(v==="a"){T([...X]),i({...r,selected:[...X]});return}if(v==="n"){T([]),i({...r,selected:[]});return}d.return&&(p==="sub-dir"?(i({type:"resolving-target"}),j(a,s)):i({type:"confirm",values:a,artifacts:s}));return}if(r.type==="confirm"){if(d.escape){i({type:"artifact-select",values:r.values,cursor:0,selected:r.artifacts});return}d.return&&(i({type:"writing"}),C(r.values,c,r.artifacts));return}(r.type==="done"||r.type==="error")&&(d.return||d.escape)&&o.exit()}),r.type==="target-select"){let v=[{label:"Use current directory",desc:e},{label:"Create new sub-directory",desc:`${e}/<inferred from API name>`}];return B(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(q,{}),B(M,{flexDirection:"column",gap:0,children:[_(I,{bold:!0,children:"Where should the new plugin live?"}),v.map((d,l)=>{let s=r.cursor===l;return B(M,{gap:2,children:[_(I,{...s&&{color:"cyan"},children:s?"\u276F":" "}),_(I,{bold:s,...s&&{color:"cyan"},children:d.label}),_(I,{dimColor:!0,children:d.desc})]},d.label)})]}),_(Ie,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(r.type==="precheck-error"){let{targetDir:v,reason:d}=r;return B(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(q,{}),_(I,{color:"red",bold:!0,children:"Cannot create plugin"}),B(M,{flexDirection:"column",gap:0,children:[B(I,{children:[v," already contains ",_(I,{bold:!0,children:d==="has-manifest"?"kizen.json":".kizenapp/"}),"."]}),_(I,{dimColor:!0,children:"Remove the conflicting file/directory or choose a different target to avoid overwriting an existing plugin."})]}),_(Ie,{text:"Enter or Esc to exit"})]})}if(r.type==="field-entry"){let{field:v,fieldError:d}=r,l=p==="sub-dir"?`Target: sub-directory of ${e} (inferred from API name)`:`Target: ${c}`;return B(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(q,{}),B(M,{flexDirection:"column",gap:0,children:[_(I,{bold:!0,children:"Plugin details"}),_(I,{dimColor:!0,children:l})]}),d!==void 0&&B(I,{color:"red",children:["Error: ",d]}),_(M,{flexDirection:"column",gap:0,children:be.map((s,a)=>{let u=v===a,h=u?P:g[s],k=Jt.includes(s),E=`${ft[s]}${k?"":" (optional)"}`;return B(M,{gap:2,children:[_(M,{width:24,children:_(I,{bold:u,...u&&{color:"cyan"},children:E})}),_(I,{...u&&{color:"cyan"},children:">"}),_(I,{children:h}),u&&_(I,{color:"cyan",children:"\u2588"})]},s)})}),_(Ie,{text:"Enter/Tab/\u2193 next \xB7 \u2191 previous \xB7 Backspace delete \xB7 Esc cancel"})]})}if(r.type==="artifact-select"){let{cursor:v,selected:d}=r;return B(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(q,{}),B(M,{flexDirection:"column",gap:0,children:[_(I,{bold:!0,children:"Which artifacts should we scaffold?"}),_(I,{dimColor:!0,children:"Each one gets a directory with a config.json and a script that runs."})]}),_(M,{flexDirection:"column",gap:0,children:X.map((l,s)=>{let a=v===s,u=d.includes(l);return B(M,{gap:1,children:[_(I,{...a&&{color:"cyan"},children:a?"\u276F":" "}),_(I,{...u&&{color:"green"},children:u?"\u25C9":"\u25EF"}),_(I,{bold:a,...a&&{color:"cyan"},children:zt[l]})]},l)})}),_(Ie,{text:"\u2191\u2193 move \xB7 Space toggle \xB7 a all \xB7 n none \xB7 Enter continue \xB7 Esc back"})]})}if(r.type==="confirm"){let v=qt({targetDir:c,name:r.values.name,apiName:r.values.apiName,externalLink:r.values.externalLink,description:r.values.description,developerBusinessId:r.values.developerBusinessId,developerEnvironment:n});return B(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(q,{}),B(M,{flexDirection:"column",gap:0,children:[_(I,{bold:!0,children:"Ready to create"}),B(I,{dimColor:!0,children:["Target: ",c]})]}),B(M,{flexDirection:"column",gap:0,children:[_(I,{bold:!0,children:"kizen.json preview"}),_(I,{children:JSON.stringify(v,null,2)})]}),B(M,{flexDirection:"column",gap:0,children:[_(I,{bold:!0,children:"Artifacts"}),r.artifacts.length===0?B(I,{dimColor:!0,children:[" ","none (src/ will hold only thumbnail.png)"]}):r.artifacts.map(d=>B(I,{dimColor:!0,children:[" ",zt[d]]},d))]}),B(M,{flexDirection:"column",gap:0,children:[_(I,{dimColor:!0,children:"Also creates:"}),B(I,{dimColor:!0,children:[" ",ht(c,"src/")]}),B(I,{dimColor:!0,children:[" ",ht(c,"src/thumbnail.png")," (generated placeholder)"]}),B(I,{dimColor:!0,children:[" ",ht(c,"releaseNotes/")]}),B(I,{dimColor:!0,children:[" ",ht(c,".gitignore")," (adds .kizenapp/)"]})]}),_(Ie,{text:"Enter to create \xB7 Esc to go back"})]})}return r.type==="resolving-target"?_(M,{paddingY:1,paddingX:2,children:_(I,{dimColor:!0,children:"Finding available sub-directory\u2026"})}):r.type==="writing"?_(M,{paddingY:1,paddingX:2,children:_(I,{dimColor:!0,children:"Creating plugin\u2026"})}):r.type==="done"?B(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(q,{}),B(I,{color:"green",bold:!0,children:["Plugin created at ",r.targetDir]}),B(M,{flexDirection:"column",gap:0,children:[_(I,{dimColor:!0,children:"Next steps:"}),B(I,{children:[" ","cd ",r.targetDir]}),B(I,{children:[" ","npx --yes @kizenapps/cli dev"]}),B(I,{dimColor:!0,children:[" ","Replace src/thumbnail.png with real artwork before publishing."]})]}),_(Ie,{text:"Enter or Esc to exit"})]}):B(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(q,{}),_(I,{color:"red",bold:!0,children:"Failed to create plugin"}),_(I,{children:r.message}),_(Ie,{text:"Enter or Esc to exit"})]})};import{mkdir as on,readFile as cs,readdir as ds,writeFile as sn}from"fs/promises";import{homedir as ps}from"os";import{dirname as us,join as yt}from"path";var Y=["go","fmo","staging","integration","test1"];var Ne=yt(ps(),".kizenappbuilder"),Fe=yt(Ne,"credentials.json"),xe="credentials";function fs(e){return Y.includes(e)}function ms(e){if(typeof e!="object"||e===null)throw new Error("Credentials must be a JSON object");let t=e,n=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:fs(n)?n:"go"}}async function ve(e){let t=await cs(e,"utf-8");return ms(JSON.parse(t))}async function Z(){try{return await ve(Fe)}catch{return null}}async function gs(e){await on(us(Fe),{recursive:!0,mode:448}),await sn(Fe,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function an(e){return yt(Ne,`${e}.json`)}async function Re(){let e=[{name:xe,path:Fe,isDefault:!0}];try{let t=await ds(Ne);for(let n of t){if(!n.endsWith(".json"))continue;let o=n.slice(0,-5);o!==xe&&e.push({name:o,path:yt(Ne,n),isDefault:!1})}}catch{}return e}async function ln(e,t){if(e===xe){await gs(t);return}await on(Ne,{recursive:!0,mode:448}),await sn(an(e),JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}async function de(e){try{return await ve(an(e))}catch{return null}}var hs="A hello-world Kizen plugin.";function ys(e){if(e===void 0||e.trim()===""||e.trim()==="all")return[...X];if(e.trim()==="none")return[];let t=e.split(",").map(o=>o.trim()).filter(o=>o!==""),n=t.filter(o=>!X.includes(o));if(n.length>0)throw new Error(`Unknown artifact type(s): ${n.join(", ")}. Valid types: ${X.join(", ")}, or "all" / "none".`);return[...new Set(t)]}function bs(e,t,n){let o=e.name?.trim()??"";if(o==="")throw new Error("--name is required for a non-interactive run.");let r=(e.apiName?.trim()??"")||mt(o);if(!Wt.test(r))throw new Error(`api_name "${r}" is invalid: ${Gt}. Pass --api-name.`);let i=e.description?.trim(),p=e.businessId?.trim()??t.businessId,f=vs(e,t);return{targetDir:n,name:o,apiName:r,externalLink:e.externalLink?.trim()??"",description:i===void 0||i===""?hs:i,developerBusinessId:p,developerEnvironment:f,artifacts:ys(e.artifacts)}}function xs(e){return Y.includes(e)}function vs(e,t){let n=e.environment?.trim();if(n!==void 0&&n!==""){if(!xs(n))throw new Error(`Unknown environment "${n}". Valid environments: ${Y.join(", ")}.`);return n}if(e.businessId!==void 0&&t.businessId==="")throw new Error("--environment is required alongside --business-id when no credentials are saved, so the id is keyed to the environment that issued it.");return t.environment}async function cn(e,t,n,o){let r;try{r=bs(e,t,n)}catch(f){o.writeStderr(`Error: ${f instanceof Error?f.message:String(f)}
|
|
267
|
-
`),o.setExitCode(1);return}let i=await o.precheckTargetDir(n);if(i!=="ok"){let f=i==="has-manifest"?"kizen.json":".kizenapp/";o.writeStderr(`Error: ${n} already contains ${f}. Refusing to overwrite an existing plugin.
|
|
268
|
-
`),o.setExitCode(1);return}try{await o.createPlugin(r)}catch(f){o.writeStderr(`Error: ${f instanceof Error?f.message:String(f)}
|
|
269
|
-
`),o.setExitCode(1);return}let p=r.artifacts&&r.artifacts.length>0?r.artifacts.join(", "):"none";o.writeStdout(`Created plugin ${r.apiName} at ${n}
|
|
270
|
-
`),o.writeStdout(`Artifacts: ${p}
|
|
875
|
+
`;var rs=`this.showToast('Hello from a JS action.', { variant: 'success' });
|
|
876
|
+
`;var oe=["floatingFrame","block","dataAdornment","page","toolbarItem","objectSettingsItem","jsAction"],Cn={floatingFrame:"Floating frame",block:"Block",dataAdornment:"Data adornment",page:"Routable page",toolbarItem:"Toolbar item",objectSettingsItem:"Object settings item",jsAction:"JS action"},Qd={floatingFrame:{directory:"floatingFrames",component:"helloFrame",files:{"config.json":Li,"script.js":zi,"styles.css":Mi}},block:{directory:"blocks",component:"helloBlock",files:{"config.json":Ui,"script.js":Hi,"styles.css":Vi}},dataAdornment:{directory:"dataAdornments",component:"helloAdornment",files:{"config.json":Wi,"script.js":Ki}},page:{directory:"pages",component:"helloPage",files:{"config.json":Ji,"script.js":qi,"styles.css":Gi,"eventScripts/greet.js":Yi}},toolbarItem:{directory:"toolbarItems",component:"helloToolbarItem",files:{"config.json":Xi,"script.js":Zi}},objectSettingsItem:{directory:"objectSettingsItems",component:"helloObjectSettingsItem",files:{"config.json":Qi,"script.js":es}},jsAction:{directory:"actions",component:"helloAction",files:{"config.json":ts,"script.js":rs}}};function eu(e,t="src"){let{directory:r,component:o,files:n}=Qd[e];return Object.entries(n).map(([i,s])=>({path:`${t}/${r}/${o}/${i}`,content:s}))}function ns(e,t="src"){return[...new Set(e)].flatMap(r=>eu(r,t))}import{deflateSync as tu}from"zlib";var _n=512,ru=150,nu=26,Pn=46,os=.6,ou=Pn*.55,iu=.55,su=.47;function au(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=t+((t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24))>>>0;return t}function lu(e){let t=au(e);return{hue:t%360,quarterTurns:(t>>>16)%4}}function cu(e,t,r){let o=(1-Math.abs(2*r-1))*t,n=e/60,i=o*(1-Math.abs(n%2-1)),s=r-o/2,[a,l,p]=n<1?[o,i,0]:n<2?[i,o,0]:n<3?[0,o,i]:n<4?[0,i,o]:n<5?[i,0,o]:[o,0,i];return[Math.round((a+s)*255),Math.round((l+s)*255),Math.round((p+s)*255)]}function gt(e,t,r,o,n){let i=Math.abs(e)-r+n,s=Math.abs(t)-o+n;return Math.hypot(Math.max(i,0),Math.max(s,0))+Math.min(Math.max(i,s),0)-n}function ar(e,t,r,o,n){return Math.hypot(e-r,t-o)-n}function du(e,t){let r=ru,o=Pn,n=o*os,i=ou,s=gt(e,t,r,r,nu),a=Math.min(ar(e,t,0,-r-n,o),gt(e,t+r+n/2,i,n/2+1,0)),l=Math.min(ar(e,t,r+n,0,o),gt(e-r-n/2,t,n/2+1,i,0));s=Math.min(s,a,l);let p=Math.min(ar(e,t,0,r-n,o),gt(e,t-r+n/2,i,n/2+1,0)),g=Math.min(ar(e,t,-r+n,0,o),gt(e+r-n/2,t,n/2+1,i,0));return Math.max(s,-p,-g)}function uu(e){let t=_n,r=new Uint8Array(t*t*4),[o,n,i]=cu(e.hue,iu,su),s=Pn*(1+os),a=(t-1)/2,l=s/2;for(let p=0;p<t;p+=1)for(let g=0;g<t;g+=1){let v=g-a,k=p-a;for(let x=0;x<e.quarterTurns;x+=1)[v,k]=[-k,v];let f=du(v+l,k-l),c=Math.min(1,Math.max(0,.5-f));if(c<=0)continue;let h=(p*t+g)*4;r[h]=o,r[h+1]=n,r[h+2]=i,r[h+3]=Math.round(c*255)}return r}var pu=new Uint32Array(256).map((e,t)=>{let r=t;for(let o=0;o<8;o+=1)r=r&1?3988292384^r>>>1:r>>>1;return r>>>0});function fu(e){let t=4294967295;for(let r of e)t=(pu[(t^r)&255]??0)^t>>>8;return(t^4294967295)>>>0}function Sn(e,t){let r=Buffer.from(e,"latin1"),o=Buffer.alloc(4);o.writeUInt32BE(t.length);let n=Buffer.alloc(4);return n.writeUInt32BE(fu(Buffer.concat([r,t]))),Buffer.concat([o,r,t,n])}var mu=Buffer.from([137,80,78,71,13,10,26,10]);function hu(e,t,r){if(r.length!==e*t*4)throw new Error(`encodePng: expected ${String(e*t*4)} bytes of RGBA for ${String(e)}x${String(t)}, got ${String(r.length)}`);let o=Buffer.alloc(13);o.writeUInt32BE(e,0),o.writeUInt32BE(t,4),o[8]=8,o[9]=6;let n=e*4,i=Buffer.alloc((n+1)*t);for(let s=0;s<t;s+=1)i.set(r.subarray(s*n,(s+1)*n),s*(n+1)+1);return Buffer.concat([mu,Sn("IHDR",o),Sn("IDAT",tu(i,{level:9})),Sn("IEND",new Uint8Array(0))])}function is(e){return hu(_n,_n,uu(lu(e)))}var bu="src/thumbnail.png",wu=["go","fmo"];async function cr(e){try{return await gu(e),!0}catch{return!1}}async function Re(e){return await cr(Ce(e,"kizen.json"))?"has-manifest":await cr(Ce(e,".kizenapp"))?"has-kizenapp":"ok"}async function ss(e,t){let r=Ce(e,t);if(!await cr(r))return r;for(let o=1;o<1e3;o++){let n=Ce(e,`${t}-${String(o)}`);if(!await cr(n))return n}throw new Error(`Could not find an available directory name for "${t}"`)}function In(e){let t=e.developerBusinessId.trim(),r=t!==""&&!wu.includes(e.developerEnvironment)?[e.developerEnvironment]:["prod"];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:r,config_template:{},base_config:{},...t?{developer_business_id:{[e.developerEnvironment]:t}}:{}}}async function En(e,t){let r=t.map(n=>({fullPath:Ce(e,...n.path.split("/")),content:n.content})),o=new Set(r.map(n=>yu(n.fullPath)));await Promise.all([...o].map(n=>lr(n,{recursive:!0}))),await Promise.all(r.map(n=>Tn(n.fullPath,n.content,"utf-8")))}async function dr(e){await lr(e.targetDir,{recursive:!0});let t=In(e);await Tn(Ce(e.targetDir,"kizen.json"),JSON.stringify(t,null,2)+`
|
|
877
|
+
`,"utf-8"),await lr(Ce(e.targetDir,"src"),{recursive:!0}),await lr(Ce(e.targetDir,"releaseNotes"),{recursive:!0}),await Promise.all([En(e.targetDir,ns(e.artifacts??[])),En(e.targetDir,Ht()),En(e.targetDir,Vt(e.includeLib===!0?["src"]:[])),Tn(Ce(e.targetDir,...bu.split("/")),is(e.apiName))]),ge(e.targetDir)}var $e=["name","apiName","externalLink","description","developerBusinessId"],ur={name:"Name",apiName:"API name",externalLink:"External link",description:"Description",developerBusinessId:"Business ID"},Dn=["name","apiName","description"],An=/^[a-z_][a-z0-9_]+$/,Nn="must start with a letter or underscore and contain only lowercase letters, numbers, or underscores (minimum 2 characters)";function pr(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}function as(e){return{name:"",apiName:"",externalLink:"",description:"",developerBusinessId:e}}function ls(e,t){let r=t.trim();if(Dn.includes(e)&&!r)return`${ur[e]} is required`;if(e==="apiName"&&!An.test(r))return`${ur[e]} ${Nn}`}function cs(e,t){return e==="description"?t:t.trim()}function ds(e,t){let r=new Set(e);return r.has(t)?r.delete(t):r.add(t),oe.filter(o=>r.has(o))}import{jsx as T,jsxs as $}from"react/jsx-runtime";var Ge=({text:e})=>T(D,{dimColor:!0,children:e}),us=({parentDir:e,defaultBusinessId:t,defaultEnvironment:r,includeLib:o=!1})=>{let n=xu(),[i,s]=tt({type:"target-select",cursor:0}),[a,l]=tt("in-place"),[p,g]=tt(()=>as(t)),[v,k]=tt(()=>[...oe]),[f,c]=tt(""),[h,x]=tt(e),I=fr((b,u)=>{l(b),c(u.name),s({type:"field-entry",field:0,values:u})},[]),C=fr(async b=>{let u=await Re(b);if(u!=="ok"){s({type:"precheck-error",targetDir:b,reason:u});return}x(b),I("in-place",p)},[p,I]),S=fr(async(b,u)=>{try{let d=await ss(e,b.apiName);x(d),s({type:"confirm",values:b,artifacts:u})}catch(d){s({type:"error",message:d instanceof Error?d.message:String(d)})}},[e]),N=fr(async(b,u,d)=>{try{await dr({targetDir:u,name:b.name,apiName:b.apiName,externalLink:b.externalLink,description:b.description,developerBusinessId:b.developerBusinessId,developerEnvironment:r,artifacts:d,includeLib:o}),s({type:"done",targetDir:u})}catch(m){s({type:"error",message:m instanceof Error?m.message:String(m)})}},[r,o]);if(vu((b,u)=>{if(u.ctrl&&b==="c"){n.exit();return}if(i.type==="target-select"){u.upArrow?s({type:"target-select",cursor:0}):u.downArrow?s({type:"target-select",cursor:1}):u.return?i.cursor===0?C(e):I("sub-dir",p):u.escape&&n.exit();return}if(i.type==="precheck-error"){(u.return||u.escape)&&n.exit();return}if(i.type==="field-entry"){let{field:d,values:m}=i,y=$e[d];if(!y)return;if(u.escape){n.exit();return}if(u.backspace||u.delete){c(w=>w.slice(0,-1));return}if(u.upArrow&&d>0){let w={...m,[y]:f},E=d-1,_=$e[E];s({type:"field-entry",field:E,values:w}),g(w),c(_?w[_]:"");return}if(u.return||u.tab||u.downArrow){let w=ls(y,f);if(w!==void 0){s({type:"field-entry",field:d,values:m,fieldError:w});return}let E=cs(y,f),_={...m,[y]:E};g(_);let R=d+1;if(R>=$e.length)c(""),s({type:"artifact-select",values:_,cursor:0,selected:v});else{let M=$e[R],X=M?_[M]:"",ie=M==="apiName"&&!X?pr(_.name):X;s({type:"field-entry",field:R,values:_}),c(ie)}return}b&&!u.ctrl&&!u.meta&&c(w=>w+b);return}if(i.type==="artifact-select"){let{cursor:d,selected:m,values:y}=i;if(u.escape){let w=$e.length-1,E=$e[w];s({type:"field-entry",field:w,values:y}),c(E?y[E]:"");return}if(u.upArrow){s({...i,cursor:Math.max(0,d-1)});return}if(u.downArrow){s({...i,cursor:Math.min(oe.length-1,d+1)});return}if(b===" "){let w=oe[d];if(w){let E=ds(m,w);k(E),s({...i,selected:E})}return}if(b==="a"){k([...oe]),s({...i,selected:[...oe]});return}if(b==="n"){k([]),s({...i,selected:[]});return}u.return&&(a==="sub-dir"?(s({type:"resolving-target"}),S(y,m)):s({type:"confirm",values:y,artifacts:m}));return}if(i.type==="confirm"){if(u.escape){s({type:"artifact-select",values:i.values,cursor:0,selected:i.artifacts});return}u.return&&(s({type:"writing"}),N(i.values,h,i.artifacts));return}(i.type==="done"||i.type==="error")&&(u.return||u.escape)&&n.exit()}),i.type==="target-select"){let b=[{label:"Use current directory",desc:e},{label:"Create new sub-directory",desc:`${e}/<inferred from API name>`}];return $(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(K,{}),$(V,{flexDirection:"column",gap:0,children:[T(D,{bold:!0,children:"Where should the new plugin live?"}),b.map((u,d)=>{let m=i.cursor===d;return $(V,{gap:2,children:[T(D,{...m&&{color:"cyan"},children:m?"\u276F":" "}),T(D,{bold:m,...m&&{color:"cyan"},children:u.label}),T(D,{dimColor:!0,children:u.desc})]},u.label)})]}),T(Ge,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(i.type==="precheck-error"){let{targetDir:b,reason:u}=i;return $(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(K,{}),T(D,{color:"red",bold:!0,children:"Cannot create plugin"}),$(V,{flexDirection:"column",gap:0,children:[$(D,{children:[b," already contains ",T(D,{bold:!0,children:u==="has-manifest"?"kizen.json":".kizenapp/"}),"."]}),T(D,{dimColor:!0,children:"Remove the conflicting file/directory or choose a different target to avoid overwriting an existing plugin."})]}),T(Ge,{text:"Enter or Esc to exit"})]})}if(i.type==="field-entry"){let{field:b,fieldError:u}=i,d=a==="sub-dir"?`Target: sub-directory of ${e} (inferred from API name)`:`Target: ${h}`;return $(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(K,{}),$(V,{flexDirection:"column",gap:0,children:[T(D,{bold:!0,children:"Plugin details"}),T(D,{dimColor:!0,children:d})]}),u!==void 0&&$(D,{color:"red",children:["Error: ",u]}),T(V,{flexDirection:"column",gap:0,children:$e.map((m,y)=>{let w=b===y,E=w?f:p[m],_=Dn.includes(m),R=`${ur[m]}${_?"":" (optional)"}`;return $(V,{gap:2,children:[T(V,{width:24,children:T(D,{bold:w,...w&&{color:"cyan"},children:R})}),T(D,{...w&&{color:"cyan"},children:">"}),T(D,{children:E}),w&&T(D,{color:"cyan",children:"\u2588"})]},m)})}),T(Ge,{text:"Enter/Tab/\u2193 next \xB7 \u2191 previous \xB7 Backspace delete \xB7 Esc cancel"})]})}if(i.type==="artifact-select"){let{cursor:b,selected:u}=i;return $(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(K,{}),$(V,{flexDirection:"column",gap:0,children:[T(D,{bold:!0,children:"Which artifacts should we scaffold?"}),T(D,{dimColor:!0,children:"Each one gets a directory with a config.json and a script that runs."})]}),T(V,{flexDirection:"column",gap:0,children:oe.map((d,m)=>{let y=b===m,w=u.includes(d);return $(V,{gap:1,children:[T(D,{...y&&{color:"cyan"},children:y?"\u276F":" "}),T(D,{...w&&{color:"green"},children:w?"\u25C9":"\u25EF"}),T(D,{bold:y,...y&&{color:"cyan"},children:Cn[d]})]},d)})}),T(Ge,{text:"\u2191\u2193 move \xB7 Space toggle \xB7 a all \xB7 n none \xB7 Enter continue \xB7 Esc back"})]})}if(i.type==="confirm"){let b=In({targetDir:h,name:i.values.name,apiName:i.values.apiName,externalLink:i.values.externalLink,description:i.values.description,developerBusinessId:i.values.developerBusinessId,developerEnvironment:r});return $(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(K,{}),$(V,{flexDirection:"column",gap:0,children:[T(D,{bold:!0,children:"Ready to create"}),$(D,{dimColor:!0,children:["Target: ",h]})]}),$(V,{flexDirection:"column",gap:0,children:[T(D,{bold:!0,children:"kizen.json preview"}),T(D,{children:JSON.stringify(b,null,2)})]}),$(V,{flexDirection:"column",gap:0,children:[T(D,{bold:!0,children:"Artifacts"}),i.artifacts.length===0?$(D,{dimColor:!0,children:[" ","none (src/ will hold only thumbnail.png)"]}):i.artifacts.map(u=>$(D,{dimColor:!0,children:[" ",Cn[u]]},u))]}),$(V,{flexDirection:"column",gap:0,children:[T(D,{dimColor:!0,children:"Also creates:"}),$(D,{dimColor:!0,children:[" ",mr(h,"src/")]}),$(D,{dimColor:!0,children:[" ",mr(h,"src/thumbnail.png")," (generated placeholder)"]}),$(D,{dimColor:!0,children:[" ",mr(h,"releaseNotes/")]}),$(D,{dimColor:!0,children:[" ",mr(h,".gitignore")," (adds .kizenapp/)"]})]}),T(Ge,{text:"Enter to create \xB7 Esc to go back"})]})}return i.type==="resolving-target"?T(V,{paddingY:1,paddingX:2,children:T(D,{dimColor:!0,children:"Finding available sub-directory\u2026"})}):i.type==="writing"?T(V,{paddingY:1,paddingX:2,children:T(D,{dimColor:!0,children:"Creating plugin\u2026"})}):i.type==="done"?$(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(K,{}),$(D,{color:"green",bold:!0,children:["Plugin created at ",i.targetDir]}),$(V,{flexDirection:"column",gap:0,children:[T(D,{dimColor:!0,children:"Next steps:"}),$(D,{children:[" ","cd ",i.targetDir]}),$(D,{children:[" ","npx --yes @kizenapps/cli dev"]}),$(D,{dimColor:!0,children:[" ","Replace src/thumbnail.png with real artwork before publishing."]})]}),T(Ge,{text:"Enter or Esc to exit"})]}):$(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(K,{}),T(D,{color:"red",bold:!0,children:"Failed to create plugin"}),T(D,{children:i.message}),T(Ge,{text:"Enter or Esc to exit"})]})};var ku="A hello-world Kizen plugin.",ps=e=>Object.entries(e).some(([t,r])=>t!=="includeLib"&&r!==void 0);function Cu(e){if(e===void 0||e.trim()===""||e.trim()==="all")return[...oe];if(e.trim()==="none")return[];let t=e.split(",").map(o=>o.trim()).filter(o=>o!==""),r=t.filter(o=>!oe.includes(o));if(r.length>0)throw new Error(`Unknown artifact type(s): ${r.join(", ")}. Valid types: ${oe.join(", ")}, or "all" / "none".`);return[...new Set(t)]}function Su(e,t,r){let o=e.name?.trim()??"";if(o==="")throw new Error("--name is required for a non-interactive run.");let n=(e.apiName?.trim()??"")||pr(o);if(!An.test(n))throw new Error(`api_name "${n}" is invalid: ${Nn}. Pass --api-name.`);let i=e.description?.trim(),s=e.businessId?.trim()??t.businessId,a=Pu(e,t);return{targetDir:r,name:o,apiName:n,externalLink:e.externalLink?.trim()??"",description:i===void 0||i===""?ku:i,developerBusinessId:s,developerEnvironment:a,artifacts:Cu(e.artifacts),includeLib:e.includeLib===!0}}function _u(e){return Z.includes(e)}function Pu(e,t){let r=e.environment?.trim();if(r!==void 0&&r!==""){if(!_u(r))throw new Error(`Unknown environment "${r}". Valid environments: ${Z.join(", ")}.`);return r}if(e.businessId!==void 0&&t.businessId==="")throw new Error("--environment is required alongside --business-id when no credentials are saved, so the id is keyed to the environment that issued it.");return t.environment}async function fs(e,t,r,o){let n;try{n=Su(e,t,r)}catch(a){o.writeStderr(`Error: ${a instanceof Error?a.message:String(a)}
|
|
878
|
+
`),o.setExitCode(1);return}let i=await o.precheckTargetDir(r);if(i!=="ok"){let a=i==="has-manifest"?"kizen.json":".kizenapp/";o.writeStderr(`Error: ${r} already contains ${a}. Refusing to overwrite an existing plugin.
|
|
879
|
+
`),o.setExitCode(1);return}try{await o.createPlugin(n)}catch(a){o.writeStderr(`Error: ${a instanceof Error?a.message:String(a)}
|
|
880
|
+
`),o.setExitCode(1);return}let s=n.artifacts&&n.artifacts.length>0?n.artifacts.join(", "):"none";o.writeStdout(`Created plugin ${n.apiName} at ${r}
|
|
881
|
+
`),o.writeStdout(`Artifacts: ${s}
|
|
271
882
|
`),o.writeStdout(`Thumbnail: src/thumbnail.png (generated placeholder; replace it before publishing)
|
|
272
|
-
`),
|
|
273
|
-
`)}function
|
|
883
|
+
`),n.developerBusinessId.trim()===""&&o.writeStderr(`Warning: no developer_business_id configured, so this plugin cannot be preview-published yet.
|
|
884
|
+
`)}function ms(e){e.command("create").description("Scaffold a new Kizen plugin project").option("-n, --name <name>","plugin display name (implies a non-interactive run)").option("-a, --api-name <name>","plugin api_name (inferred from --name when omitted)").option("-d, --description <text>","plugin description").option("-l, --external-link <url>","external link shown on the plugin listing").option("-b, --business-id <id>","developer business id (defaults to saved credentials)").option("-e, --environment <env>",`environment the business id belongs to: ${Z.join(", ")} (defaults to saved credentials)`).option("--artifacts <list>",`comma-separated artifact types, or "all" / "none" (default: all). Types: ${oe.join(", ")}`).option("--include-lib","also install the Kizen data helper library (src/lib/kizenData.js)").action(async t=>{let r=process.cwd(),o=await re(),n=o?.businessId??"",i=o?.environment??"go";if(!process.stdin.isTTY||!process.stdout.isTTY||ps(t)){await fs(t,{businessId:n,environment:i},r,{precheckTargetDir:Re,createPlugin:dr,writeStdout:l=>{process.stdout.write(l)},writeStderr:l=>{process.stderr.write(l)},setExitCode:l=>{process.exitCode=l}});return}let{waitUntilExit:a}=Tu(Eu(us,{parentDir:r,defaultBusinessId:n,defaultEnvironment:i,includeLib:t.includeLib===!0}),{exitOnCtrlC:!1});await a()})}import{createElement as Js}from"react";import{render as qs}from"ink";import{useCallback as rt,useEffect as vr,useRef as Se,useState as ae}from"react";import{Box as ee,Text as F,useInput as Pp}from"ink";import{PluginValidationError as Ep}from"@kizenapps/packager";import{watch as Tp}from"fs";import{createServer as Ip}from"http";import{join as Vs}from"path";import{WebSocketServer as Dp}from"ws";import{createReadStream as Is,realpathSync as Ju}from"fs";import{access as qu,readdir as Gu,readFile as Yu,realpath as Xu,stat as Ds}from"fs/promises";import{dirname as Zu,extname as As,join as kt,resolve as Qu,sep as Un}from"path";import{fileURLToPath as ep}from"url";var Iu=new Set(["set-cookie","strict-transport-security","content-security-policy","content-security-policy-report-only","x-frame-options","content-encoding","content-length"]);function hr(e){let t={};for(let[r,o]of Object.entries(e)){let n=r.toLowerCase();Iu.has(n)||n.startsWith("access-control-")||(t[r]=o)}return t}var Bn=10*1024*1024,Du=6e4,Au=200,yt=class extends Error{bytesRead;limit;constructor(t,r){super(`Upstream response exceeded ${String(r)} bytes (read ${String(t)}).`),this.name="ProxyResponseTooLargeError",this.bytesRead=t,this.limit=r}};async function Rn(e,t){let r=e.body;if(r===null)return Buffer.alloc(0);let o=[],n=0;for await(let i of r){if(n+=i.length,n>t)throw new yt(n,t);o.push(i)}return Buffer.concat(o)}async function hs(e){let t=hr(Object.fromEntries(e.headers)),r=await Rn(e,Bn);return{status:e.status,headers:t,body:r}}function gs(e={}){let{onChange:t,enabled:r=!0}=e;if(!r)return{async get(s,a){return{response:await hs(await a()),fromCache:!1}},clear(){}};let o=new Map,n=()=>{t?.(o.size)},i=s=>{o.delete(s)&&n()};return{get(s,a){let l=o.get(s);if(l!==void 0){if(Date.now()-l.insertedAt<Du)return l.promise.then(g=>({response:g,fromCache:!0}));i(s)}if(o.size>=Au){let g=o.keys().next().value;g!==void 0&&i(g)}let p=a().then(hs).catch(g=>{throw i(s),g});return o.set(s,{insertedAt:Date.now(),promise:p}),n(),p.then(g=>((g.status<200||g.status>=300)&&i(s),{response:g,fromCache:!1}))},clear(){o.clear(),n()}}}var $n={".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"};var Fn={prod:"https://plugin-wizard.kizen.com",dev:"https://plugin-wizard.kizen.dev",localDev:"http://localhost:9823"};function bt(e){let t=process.env.PLUGIN_WIZARD_URL;return t!==void 0&&t!==""?t:e==="prod"?process.env.PLUGIN_WIZARD_URL_PROD||Fn.prod:process.env.PLUGIN_WIZARD_URL_DEV!==void 0&&process.env.PLUGIN_WIZARD_URL_DEV!==""?process.env.PLUGIN_WIZARD_URL_DEV:process.env.APPBUILDER_LOCAL_DEV!==void 0&&process.env.APPBUILDER_LOCAL_DEV!==""?Fn.localDev:Fn.dev}import{spawn as zn}from"child_process";import{writeFile as vs,rm as Ln,mkdtemp as $u,access as Fu}from"fs/promises";import{join as xt}from"path";import{tmpdir as ju}from"os";var ys=`awslambdaric
|
|
274
885
|
bcrypt
|
|
275
886
|
boto3
|
|
276
887
|
fpdf2
|
|
@@ -288,8 +899,8 @@ pytz
|
|
|
288
899
|
requests
|
|
289
900
|
sqlalchemy>=2.0,<2.1
|
|
290
901
|
tzdata
|
|
291
|
-
`;import{AUTOMATION_SCRIPT_RUNTIMES as
|
|
292
|
-
`).map(t=>t.trim().replace(/\s+#.*$/,"")).filter(t=>t.length>0&&!t.startsWith("#"))}function
|
|
902
|
+
`;import{AUTOMATION_SCRIPT_RUNTIMES as Ou,isSupportedScriptRuntime as Lu,scriptRuntimeToApiName as Cs}from"@kizenapps/packager";function bs(e){return e.split(`
|
|
903
|
+
`).map(t=>t.trim().replace(/\s+#.*$/,"")).filter(t=>t.length>0&&!t.startsWith("#"))}function ws(e){let t=/^python-(\d+)[.-](\d+)$/.exec(e),r=t?.[1],o=t?.[2];return r!==void 0&&o!==void 0?`python${r}.${o}`:"python3"}function Bu(e){return e==null||e.trim()===""?null:e}function Ru(e){return e==null?null:typeof e=="string"?Bu(e):typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):typeof e=="function"||typeof e=="symbol"?null:JSON.stringify(e)}function xs(e){return e?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Ru(r)])):{}}var zu=`
|
|
293
904
|
import sys, json, os, traceback
|
|
294
905
|
|
|
295
906
|
# --- Inputs proxy (attribute access) ---
|
|
@@ -449,29 +1060,29 @@ sys.stdout.write('\\n__KIZEN_RESULT_START__\\n')
|
|
|
449
1060
|
sys.stdout.write(json.dumps(result, ensure_ascii=False))
|
|
450
1061
|
sys.stdout.write('\\n__KIZEN_RESULT_END__\\n')
|
|
451
1062
|
sys.stdout.flush()
|
|
452
|
-
`.trim(),
|
|
453
|
-
`);for(;
|
|
454
|
-
`)}}),
|
|
455
|
-
`).trim(),y=m.length>0?`: ${m}`:"";r(new Error(`${e} exited with code ${String(g)}${y}`))}})})}var er=null;function Ms(e,t){if(Je)return t&&er?.add(t),Je;let n=new Set;t&&n.add(t),er=n;let o=i=>{for(let p of n)p(i)},r=We(xt,"bin","python");return Je=(async()=>{try{let i=!1;try{await As(r);let p=await Sn(r);i=p!==null&&Cn(p)}catch{i=!1}if(!i){await tr(xt,{recursive:!0,force:!0}).catch(()=>{});let p=await zs(e);await xn(p,["-m","venv",xt])}return o({kind:"start"}),await xn(r,["-m","pip","install","--disable-pip-version-check",...wn],(p,f)=>{o({kind:"log",line:p,stream:f})}),o({kind:"complete"}),r}catch(i){let p=i instanceof Error?i.message:String(i);throw o({kind:"error",message:p}),Je=null,await tr(xt,{recursive:!0,force:!0}).catch(()=>{}),i}finally{er=null}})(),Je}function Hs(e){let t="__KIZEN_RESULT_START__",n="__KIZEN_RESULT_END__",o=e.indexOf(t),r=e.indexOf(n);if(o===-1||r===-1)return{userStdout:e,result:null};let i=e.slice(0,o).trimEnd(),p=e.slice(o+t.length,r).trim();try{let f=JSON.parse(p);return{userStdout:i,result:f}}catch{return{userStdout:e,result:null}}}function Us(e){return{success:!1,outputValues:{},logs:[],stdout:"",stderr:"",error:e,exitCode:1,durationMs:0}}async function Tn(e){let t=e.timeout??Ls;if(!$s(e.scriptRuntime))return Us(`Unsupported runtime "${e.scriptRuntime}". Supported runtimes: ${Os.join(", ")}. Update the step's config.json "runtime" field (e.g. "python 3.13").`);let o=await Ms(vn(e.scriptRuntime),e.onInstallProgress),r=Date.now(),i;try{i=await Bs(We(Ds(),"kizen-step-"));let p=We(i,"wrapper.py"),f=We(i,"script.py");await Promise.all([bn(p,js,"utf-8"),bn(f,e.script,"utf-8")]);let g={...process.env,__KIZEN_INPUTS__:JSON.stringify(e.inputs),__KIZEN_SECRETS__:JSON.stringify(e.secrets),__KIZEN_SCRIPT_PATH__:f},{exitCode:m,stdout:y,stderr:T}=await new Promise(w=>{let H=[],j=[],C=!1,v=rr(o,[p],{env:g,cwd:i,stdio:["ignore","pipe","pipe"]}),d=setTimeout(()=>{v.kill("SIGKILL")},t);v.stdout.on("data",s=>{H.push(s)}),v.stderr.on("data",s=>{j.push(s)});let l=s=>{C||(C=!0,clearTimeout(d),w({exitCode:s??1,stdout:Buffer.concat(H).toString("utf-8"),stderr:Buffer.concat(j).toString("utf-8")}))};v.on("close",l),v.on("error",s=>{C||(C=!0,clearTimeout(d),w({exitCode:1,stdout:"",stderr:s.message}))})}),P=Date.now()-r,{userStdout:x,result:c}=Hs(y);if(c){let w={success:c.success,outputValues:c.outputValues,logs:c.logs,stdout:x,stderr:T,exitCode:m,durationMs:P};return c.error!==null&&(w.error=c.error),c.httpRequests&&(w.httpRequests=c.httpRequests),w}let b={success:!1,outputValues:{},logs:[],stdout:x,stderr:T,exitCode:m,durationMs:P};return m!==0&&(b.error=`Process exited with code ${String(m)}`),b}finally{i&&tr(i,{recursive:!0,force:!0})}}var En=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"]);import{CRYPTO_ALG as In,CRYPTO_VERSION as Nn,DEFAULT_AUTOMATION_RUNTIME as Zs,deserializeEnvelope as Qs,encrypt as ea,scriptRuntimeToApiName as ta,serializeEnvelope as ra}from"@kizenapps/packager";function nr(e){if(e.kind==="info")return e.message;let t=e.fromCache?" [cache]":"",n=e.upstreamStatus!==void 0?` (upstream ${String(e.upstreamStatus)})`:"";return`${e.method} ${e.url} \u2192 ${String(e.status)}${n}${t}`}var na=2*1024*1024,oa=new Set([".DS_Store",".gitignore"]);function ia(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 Dn=["kizen.com","kizen.dev"];function sa(e){let t;try{t=new URL(e)}catch{return!1}let n=t.hostname.toLowerCase();return n==="localhost"||n==="127.0.0.1"||n==="[::1]"?!0:t.protocol!=="https:"?!1:Dn.some(o=>n===o||n.endsWith("."+o))}function aa(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let n=t.hostname.toLowerCase();return Dn.some(o=>n===o||n.endsWith("."+o))}function la(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 Rn(e,t){if(t.includes("\0"))return null;let n=t.replace(/^\/+/,""),o=Ys(e,n);if(o!==e&&!o.startsWith(e+or))return null;try{let r=await Gs(o);return r!==e&&!r.startsWith(e+or)?null:r}catch{return null}}function Bn(e,t){let n=t===e?"":t.slice(e.length+1);return n===""?!1:n.split(or).some(r=>rt.has(r))}function Fn(){let e=Xs(import.meta.url);return Ke(Ks(e),"viewer")}function An(e,t,n){if(e.includes("/external-integrations/proxy")&&t["content-type"]?.includes("application/json"))try{let o=JSON.parse(n.toString("utf8"));return typeof o.status_code=="number"?o.status_code:void 0}catch{return}}async function ir(e){try{return await qs(e),!0}catch{return!1}}function $n(e,t,n,o,r,i,p,f,g,m,y){let T=un({onChange:f,enabled:y}),P=Vs(m);return(x,c)=>{(async()=>{let b=x.url??"/";try{if(!ia(x.headers.host)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Forbidden"}));return}if((x.method==="POST"||x.method==="PATCH"||x.method==="DELETE")&&!la(x.headers.origin)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Forbidden"}));return}if(t(`Received request: ${b}`),b==="/api/credentials"){c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({credentials:o.current??null,activeProfile:r.current??null}));return}if(b==="/api/credential-profiles"&&x.method==="GET"){let l=await Re();c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({profiles:l,active:r.current}));return}if(b==="/api/credentials/switch"&&x.method==="POST"){let l=[];for await(let h of x)l.push(h);let a=JSON.parse(Buffer.concat(l).toString("utf-8")||"{}").profile,u=a===void 0||a===""?await Z():await de(a);if(u!==null){o.current=u,r.current=a??void 0;let h=r.current,k=await we(i);await Ce(i,{...k,credentialMode:"global",...h!==void 0&&{activeCredentialProfile:h}}),p({type:"credentials-updated",credentials:u,activeProfile:r.current??null})}c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({ok:u!==null}));return}if(b==="/api/bundle"){let l=Ke(process.cwd(),".kizenapp","bundle.json");try{let s=await Ws(l,"utf-8");c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(s)}catch{c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end("{}")}return}if(b==="/api/last-path"&&x.method==="POST"){let l=[];for await(let a of x)l.push(a);let s=JSON.parse(Buffer.concat(l).toString("utf-8")||"{}");if(typeof s.path=="string"){g.current=s.path;let a=await we(i);await Ce(i,{...a,lastPath:s.path})}c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end('{"ok":true}');return}if(b==="/api/encryption-target"&&x.method==="GET"){let s=(await we(i)).encryptionTarget==="dev"?"dev":"prod";c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({target:s}));return}if(b==="/api/encryption-target"&&x.method==="POST"){let l=[];for await(let h of x)l.push(h);let s=JSON.parse(Buffer.concat(l).toString("utf-8")||"{}"),a=s!==null&&typeof s=="object"?s:{};if(a.target!=="dev"&&a.target!=="prod"){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"target must be one of: 'dev', 'prod'"}));return}let u=await we(i);await Ce(i,{...u,encryptionTarget:a.target}),c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end('{"ok":true}');return}if(b==="/api/execute-step"&&x.method==="POST"){let l=[];for await(let h of x)l.push(h);let s=JSON.parse(Buffer.concat(l).toString("utf-8")||"{}");if(typeof s.script!="string"){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Missing required field: script"}));return}let a={script:s.script,scriptRuntime:s.scriptRuntime??ta(Zs),inputs:yn(s.inputs),secrets:s.secrets??{},onInstallProgress:h=>{h.kind==="start"?p({type:"venv-install-start"}):h.kind==="log"?p({type:"venv-install-log",line:h.line,stream:h.stream}):h.kind==="complete"?p({type:"venv-install-complete"}):p({type:"venv-install-error",message:h.message})}};typeof s.timeout=="number"&&s.timeout>0&&(a.timeout=Math.min(s.timeout,300*1e3));let u=await Tn(a);c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify(u));return}if(b==="/api/proxy-cache/clear"){T.clear(),n({kind:"info",message:"Proxy cache cleared"}),c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end('{"ok":true}');return}if(b==="/api/local/encrypt"&&x.method==="POST"){let l=[];for await(let a of x)l.push(a);let s=JSON.parse(Buffer.concat(l).toString("utf-8")||"{}");if(typeof s.publicKeyPem!="string"||typeof s.value!="string"){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Missing required fields: publicKeyPem, value"}));return}try{let a=ea(s.value,s.publicKeyPem),u=ra(a);c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify(u))}catch(a){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:a.message}))}return}if(b==="/api/local/validate"&&x.method==="POST"){let l=[];for await(let E of x)l.push(E);let s=JSON.parse(Buffer.concat(l).toString("utf-8")||"{}");if(typeof s.value!="string"){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Missing required field: value"}));return}let a,u;try{a=Qs(s.value)}catch(E){u=E.message}if(u!==void 0||a===void 0){c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({valid:!1,checks:[],error:u}));return}let h=E=>Buffer.from(E,"base64").length,k=[{label:"Version",expected:String(Nn),actual:String(a.v),pass:a.v===Nn},{label:"Algorithm",expected:In,actual:a.alg,pass:a.alg===In},{label:"Wrapped key",expected:"384 bytes (RSA-3072)",actual:`${String(h(a.k))} bytes`,pass:h(a.k)===384},{label:"IV",expected:"12 bytes",actual:`${String(h(a.iv))} bytes`,pass:h(a.iv)===12},{label:"Auth tag",expected:"16 bytes",actual:`${String(h(a.tag))} bytes`,pass:h(a.tag)===16},{label:"Ciphertext",expected:"\u2265 1 byte",actual:`${String(h(a.ct))} bytes`,pass:h(a.ct)>=1}];c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({valid:k.every(E=>E.pass),checks:k}));return}if(b.startsWith("/api/wizard")){let l=x.headers["x-encryption-target"],a=(Array.isArray(l)?l[0]:l)==="dev"?"dev":"prod",u=qe(a);if(!sa(u)){c.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:`Encryption API host is not allowed: ${u}`}));return}let h=b.slice(11)||"/",k=`${u}${h}`,E=x.method??"GET",R=[];for await(let Ee of x)R.push(Ee);let{host:z,"x-encryption-target":W,...te}=x.headers,oe=R.length>0?Buffer.concat(R):void 0,ie=oe&&oe.length>0?oe:void 0,re;try{re=await fetch(k,{method:E,headers:te,...ie!==void 0&&{body:ie}})}catch(Ee){let Nt=Ee.code==="ECONNREFUSED"?`plugin-wizard is not running at ${u}`:`Failed to reach plugin-wizard: ${Ee.message}`;c.writeHead(503,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:Nt}));return}let ee=bt(Object.fromEntries(re.headers)),je=await re.arrayBuffer();c.writeHead(re.status,ee),c.end(Buffer.from(je));return}if(b.startsWith("/api/proxy")){let l=x.headers["x-proxy-target"];if(typeof l!="string"){c.writeHead(400),c.end("Missing x-proxy-target header");return}if(!aa(l)){c.writeHead(400),c.end("Invalid proxy target");return}let s=b.slice(10)||"/",a=`${l}${s}`,u=x.method??"GET",h=[];for await(let re of x)h.push(re);let{host:k,"x-proxy-target":E,...R}=x.headers;if(u==="GET"){let re=`GET::${a}`,{response:ee,fromCache:je}=await T.get(re,()=>fetch(a,{method:"GET",headers:R}));n({kind:"request",method:"GET",status:ee.status,upstreamStatus:An(s,ee.headers,ee.body),fromCache:je,url:s}),c.writeHead(ee.status,ee.headers),c.end(ee.body);return}let z=h.length>0?Buffer.concat(h):void 0,W=z&&z.length>0?z:void 0,te=await fetch(a,{method:u,headers:R,...W!==void 0&&{body:W}}),oe=bt(Object.fromEntries(te.headers)),ie=await Yt(te,Kt);n({kind:"request",method:u,status:te.status,upstreamStatus:An(s,oe,ie),fromCache:!1,url:s}),c.writeHead(te.status,oe),c.end(ie);return}if(b.startsWith("/api/source/tree")&&x.method==="GET"){let s=new URL(b,"http://localhost").searchParams.get("path")??"",a=await Rn(P,s);if(a===null){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Invalid path"}));return}if(Bn(P,a)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Path is excluded"}));return}try{let u=await Js(a,{withFileTypes:!0}),h=await Promise.all(u.filter(E=>E.isDirectory()?!rt.has(E.name):E.isFile()?!oa.has(E.name):!1).map(async E=>{let R=E.isDirectory()?"dir":"file",z={name:E.name,kind:R};if(R==="file")try{let W=await kn(Ke(a,E.name));z.size=W.size}catch{}return z}));h.sort((E,R)=>E.kind!==R.kind?E.kind==="dir"?-1:1:E.name.localeCompare(R.name));let k=a===P?"":a.slice(P.length+1);c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({path:k,entries:h}))}catch(u){let h=u instanceof Error?u.message:String(u);t(`source/tree failed (${s}): ${h}`),c.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not found"}))}return}if(b.startsWith("/api/source/file")&&x.method==="GET"){let s=new URL(b,"http://localhost").searchParams.get("path")??"";if(s===""){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Missing path"}));return}let a=await Rn(P,s);if(a===null){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Invalid path"}));return}if(Bn(P,a)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Path is excluded"}));return}try{let u=await kn(a);if(!u.isFile()){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not a file"}));return}if(u.size>na){c.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"File too large",size:u.size}));return}let h=Pn(a).toLowerCase(),k=Xt[h],E=En.has(h),R=k??(E?"text/plain; charset=utf-8":"application/octet-stream");c.writeHead(200,{"Content-Type":R,"Content-Length":String(u.size)}),_n(a).pipe(c)}catch(u){let h=u instanceof Error?u.message:String(u);t(`source/file failed (${s}): ${h}`),c.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not found"}))}return}let j=Ke(e,b==="/"?"/index.html":b),C=await ir(j)?j:Ke(e,"index.html"),v=Pn(C),d=Xt[v]??"application/octet-stream";c.writeHead(200,{"Content-Type":d}),_n(C).pipe(c)}catch(w){if(b.startsWith("/api/proxy")){let H=b.slice(10)||"/",j=x.method??"GET";w instanceof Ve?n({kind:"info",message:`${j} ${H} \u2192 502 (response exceeded ${String(w.limit)} bytes)`}):n({kind:"request",method:j,status:502,fromCache:!1,url:H})}else n({kind:"info",message:`Error handling ${b}: ${w instanceof Error?w.message:String(w)}`});c.headersSent||(c.writeHead(502),c.end("Bad Gateway"))}})()}}import{launch as ca}from"chrome-launcher";import{createRequire as da}from"module";import{mkdirSync as pa}from"fs";import{readFile as ua}from"fs/promises";import{dirname as fa,join as ma}from"path";import{fileURLToPath as ga}from"url";var jn=da(import.meta.url)("chrome-remote-interface"),ha=new Set(["content-security-policy","content-security-policy-report-only","x-frame-options"]),On=["kizen.dev","kizen.com"];function Ln(e){try{let{hostname:t}=new URL(e);return On.some(n=>t===n||t.endsWith("."+n))}catch{return!1}}async function ya(e){try{let t=ma(fa(ga(import.meta.url)),"viewer","icon.png"),n=await ua(t);await e.Browser.setDockTile({image:n.toString("base64")})}catch{}}async function zn(e){pa(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,n=await ca({startingUrl:t,chromeFlags:[`--app=${t}`,"--no-first-run","--no-default-browser-check","--disable-extensions","--disable-features=DeviceBoundSessions"],userDataDir:e.userDataDir,handleSIGINT:!1,logLevel:"silent"}),o=n.port,r=null,i=null,p=null,f=null,g=0,m=!1,y=C=>{e.debugLog?.(C)},T=C=>{e.verbose&&e.debugLog?.(C)},P=()=>{i!==null&&(clearInterval(i),i=null)},x=C=>C==="chrome://new-tab-page/"||C==="chrome://newtab/",c=async C=>{P(),p=null,await ya(C),await C.Fetch.enable({patterns:On.flatMap(d=>[{urlPattern:`*://${d}/*`,requestStage:"Response"},{urlPattern:`*://*.${d}/*`,requestStage:"Response"}])}),C.on("Fetch.requestPaused",d=>{(async()=>{let l=d,{requestId:s,request:a,responseHeaders:u,responseStatusCode:h}=l,k=a.url;T(`Fetch ${String(h??"?")} ${k}`);let E=[],R=!1;for(let z of u??[])if(!ha.has(z.name.toLowerCase()))if(z.name.toLowerCase()==="set-cookie"&&Ln(k)){let W=z.value.split(`
|
|
456
|
-
`).map(
|
|
457
|
-
`);E.push({name:z.name,value:W}),R=!0}else E.push(z);R&&T(` rewrote Set-Cookie SameSite on ${k}`);try{let{body:z,base64Encoded:W}=await C.Fetch.getResponseBody({requestId:s});await C.Fetch.fulfillRequest({requestId:s,responseCode:h??200,responseHeaders:E,body:z,...W&&{base64Encoded:!0}})}catch(z){T(` fulfillRequest failed (${z.message}), falling through`);try{await C.Fetch.continueRequest({requestId:s})}catch(W){T(` continueRequest also failed (${W.message})`)}}})()}),i=setInterval(()=>{(async()=>{try{let{cookies:d}=await C.Network.getAllCookies(),l=0;for(let s of d){if(!Ln(`https://${s.domain??""}`)||s.sameSite==="None")continue;let a=s.domain??"",u=a.startsWith(".")?a.slice(1):a;await C.Network.setCookie({url:`https://${u}`,name:s.name,value:s.value,domain:a,path:s.path??"/",secure:!0,...s.httpOnly!==void 0&&{httpOnly:s.httpOnly},...s.expirationDate!==void 0&&{expires:s.expirationDate},sameSite:"None"}),l++}l>0&&T(`cookie-patch cycle: updated ${String(l)} cookie(s) to SameSite=None`)}catch(d){T(`cookie-patch cycle failed: ${d.message}`)}})()},2e3),await C.Target.setDiscoverTargets({discover:!0});let v=d=>{if(d.type==="page"){if(x(d.url)){y(`closed stray new-tab-page target ${d.targetId}`),p!==null&&C.Target.activateTarget({targetId:p}).catch(()=>{}),C.Target.closeTarget({targetId:d.targetId}).catch(()=>{});return}p===null&&(p=d.targetId,y(`captured main target ${d.targetId} (${d.url})`))}};C.on("Target.targetCreated",d=>{let{targetInfo:l}=d;T(`target +${l.type} ${l.targetId} ${l.url}`),v(l)}),C.on("Target.targetInfoChanged",d=>{let{targetInfo:l}=d;T(`target ~${l.type} ${l.targetId} ${l.url}`),v(l)}),C.on("disconnect",()=>{m||r!==C||(y("CDP disconnected"),r=null,P(),b())})},b=()=>{if(m||f!==null)return;let C=Math.min(1e3*2**g,1e4),v=g+1;g++,y(`CDP reconnect scheduled in ${String(C)}ms (attempt #${String(v)})`),f=setTimeout(()=>{f=null,(async()=>{let d;try{d=await jn({port:o})}catch{y(`CDP reconnect attempt #${String(v)} failed`),b();return}if(m){try{await d.close()}catch{}return}r=d;try{await c(d),y(`CDP reconnected after ${String(v)} attempt(s)`),g=0}catch{r===d&&(r=null);try{await d.close()}catch{}y(`CDP reconnect attempt #${String(v)} failed during setup`),b()}})()},C)},w=30,H=300;for(let C=0;C<w;C++){await new Promise(v=>setTimeout(v,H)),y(`CDP connect attempt ${String(C+1)}/${String(w)}`);try{let v=await jn({port:o});r=v,e.path&&v.send("Page.navigate",{url:`${t}${e.path}`});try{await c(v),y("CDP connected")}catch{r===v&&(r=null);try{await v.close()}catch{}y("CDP setup failed after connect")}break}catch{if(C===w-1){let v=`CDP unavailable after ${String(w)} attempts \u2014 viewer running without interception (CSP/cookie rewrites disabled)`;return y(v),e.onWarn?.(v),{kill:()=>{n.kill()}}}}}return r?{kill:()=>{if(y("CDP kill requested \u2014 tearing down"),m=!0,f!==null&&(clearTimeout(f),f=null),P(),r!==null){try{r.close()}catch{}r=null}n.kill()}}:{kill:()=>{n.kill()}}}import{useCallback as ba,useState as xa}from"react";function vt(e){let[t,n]=xa([]),o=ba(r=>{n(i=>[...i,`${new Date().toLocaleTimeString()}: ${r}`].slice(-e))},[e]);return[t,o]}import{useCallback as wt,useEffect as sr,useState as Ct}from"react";import{Box as V,Text as $,useInput as va}from"ink";import{jsx as N,jsxs as J}from"react/jsx-runtime";var Se=["apiKey","userId","businessId"],wa={apiKey:"API Key",userId:"User ID",businessId:"Business ID"},Ye=({text:e})=>N($,{dimColor:!0,children:e}),St=({initialMode:e,showProfileManager:t,onComplete:n,onCancel:o})=>{let[r,i]=Ct(e==="global"&&!t?{type:"loading"}:e==="global"&&t?{type:"profile-loading"}:{type:"mode-select",cursor:0}),[p,f]=Ct(""),[g,m]=Ct(null),[y,T]=Ct(void 0),P=wt(d=>{if(d==="local"){n({mode:"local",credentials:null});return}i({type:"profile-loading"})},[n]),x=wt(async d=>{if(d===null){i({type:"profile-loading"});let a=await Re();i({type:"name-entry",nameBuffer:"",existingProfiles:a});return}T(d.isDefault?void 0:d.name),i({type:"loading"});let l=d.isDefault?await Z():await de(d.name),s=l?Math.max(0,Y.indexOf(l.environment)):0;i({type:"creds-entry",field:0,values:l??{},envCursor:s})},[]),c=wt(async(d,l)=>{let s=Y[l]??"go",a={apiKey:d.apiKey??"",userId:d.userId??"",businessId:d.businessId??"",environment:s};i({type:"saving"});try{await ln(y??xe,a),n({mode:"global",credentials:a,...y!==void 0&&{profileName:y}})}catch(u){m(u instanceof Error?u.message:String(u)),i({type:"creds-entry",field:0,values:d,envCursor:l})}},[n,y]);va((d,l)=>{if(l.ctrl&&d==="c"&&process.exit(0),l.escape){if((r.type==="creds-entry"||r.type==="name-entry")&&e==="global"&&t){i({type:"profile-loading"}),b();return}o?.();return}if(r.type==="mode-select"){if(l.upArrow)i({type:"mode-select",cursor:0});else if(l.downArrow)i({type:"mode-select",cursor:1});else if(l.return){let s=r.cursor===0?"global":"local";P(s)}return}if(r.type==="profile-select"){let{profiles:s,cursor:a}=r,u=s.length,h=s.length+1;if(l.upArrow)i({...r,cursor:(a-1+h)%h});else if(l.downArrow)i({...r,cursor:(a+1)%h});else if(l.return)if(a===u)i({type:"name-entry",nameBuffer:"",existingProfiles:s});else{let k=s[a]??s[0];k&&x(k)}return}if(r.type==="name-entry"){let{nameBuffer:s,existingProfiles:a}=r;if(l.backspace||l.delete)i({type:"name-entry",nameBuffer:s.slice(0,-1),existingProfiles:a});else if(l.return){let u=s.trim();if(!u){i({...r,nameError:"Name cannot be empty"});return}if(u===xe){i({...r,nameError:`"${xe}" is reserved`});return}if(a.some(h=>h.name===u)){i({...r,nameError:`Profile "${u}" already exists`});return}T(u),i({type:"creds-entry",field:0,values:{},envCursor:0}),f("")}else d&&!l.ctrl&&!l.meta&&i({type:"name-entry",nameBuffer:s+d,existingProfiles:a});return}if(r.type==="creds-entry"){let{field:s,values:a,envCursor:u}=r;if(s===Se.length){l.leftArrow?i({...r,envCursor:(u-1+Y.length)%Y.length}):l.rightArrow?i({...r,envCursor:(u+1)%Y.length}):l.upArrow?(i({...r,field:s-1}),f(a[Se[s-1]]??"")):l.return&&c(a,u);return}let k=Se[s];if(!k)return;if(l.backspace||l.delete)f(E=>E.slice(0,-1));else if(l.upArrow&&s>0){let E={...a,[k]:p},R=s-1;i({...r,field:R,values:E}),f(E[Se[R]]??"")}else if(l.return||l.tab||l.downArrow){let E={...a,[k]:p},R=s+1;i({...r,field:R,values:E}),R<Se.length?f(E[Se[R]]??""):f("")}else d&&!l.ctrl&&!l.meta&&f(E=>E+d)}});let b=wt(async()=>{let d=await Re();i({type:"profile-select",profiles:d,cursor:0})},[]);if(sr(()=>{r.type==="profile-loading"&&b()},[r.type,b]),sr(()=>{e==="global"&&!t&&(async()=>{let d=await Z(),l=d?Math.max(0,Y.indexOf(d.environment)):0;i({type:"creds-entry",field:0,values:d??{},envCursor:l})})()},[]),sr(()=>{r.type==="creds-entry"&&r.field===0&&f(r.values.apiKey??"")},[r.type]),r.type==="loading"||r.type==="saving"||r.type==="profile-loading"){let d=r.type==="saving"?"Saving credentials\u2026":r.type==="profile-loading"?"Loading profiles\u2026":"Loading credentials\u2026";return N(V,{paddingY:1,paddingX:2,children:N($,{dimColor:!0,children:d})})}if(r.type==="done")return null;if(r.type==="mode-select")return J(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[N(q,{}),J(V,{flexDirection:"column",gap:0,children:[N($,{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((l,s)=>{let a=r.cursor===s;return J(V,{gap:2,children:[N($,{...a&&{color:"cyan"},children:a?"\u276F":" "}),N($,{bold:a,...a&&{color:"cyan"},children:l.label}),N($,{dimColor:!0,children:l.desc})]},l.mode)})]}),N(Ye,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]});if(r.type==="profile-select"){let{profiles:d,cursor:l}=r,s=d.length;return J(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[N(q,{}),J(V,{flexDirection:"column",gap:0,children:[N($,{bold:!0,children:"Credential profiles"}),d.map((a,u)=>{let h=l===u;return J(V,{gap:2,children:[N($,{...h&&{color:"cyan"},children:h?"\u276F":" "}),N($,{bold:h,...h&&{color:"cyan"},children:a.isDefault?"Default":a.name}),N($,{dimColor:!0,children:a.path})]},a.name)}),J(V,{gap:2,children:[N($,{...l===s&&{color:"cyan"},children:l===s?"\u276F":" "}),N($,{bold:l===s,...l===s&&{color:"cyan"},children:"+ Add new profile"})]})]}),N(Ye,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(r.type==="name-entry"){let{nameBuffer:d,nameError:l}=r;return J(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[N(q,{}),N(V,{flexDirection:"column",gap:0,children:N($,{bold:!0,children:"New credential profile"})}),l&&J($,{color:"red",children:["Error: ",l]}),J(V,{gap:2,children:[N(V,{width:12,children:N($,{bold:!0,color:"cyan",children:"Profile name"})}),N($,{color:"cyan",children:">"}),N($,{children:d}),N($,{color:"cyan",children:"\u2588"})]}),N(Ye,{text:"Type a name \xB7 Enter to confirm \xB7 Esc to go back"})]})}let{field:w,values:H,envCursor:j}=r,C=w===Se.length,v=y??xe;return J(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[N(q,{}),J(V,{flexDirection:"column",gap:0,children:[N($,{bold:!0,children:y!==void 0?`Profile: ${y}`:"Global credentials"}),J($,{dimColor:!0,children:["Saved to:"," ",y!==void 0?`~/.kizenappbuilder/${y}.json`:Fe]})]}),g&&J($,{color:"red",children:["Error: ",g]}),J(V,{flexDirection:"column",gap:0,children:[Se.map((d,l)=>{let s=w===l,a=s?p:H[d]??"";return J(V,{gap:2,children:[N(V,{width:12,children:N($,{bold:s,...s&&{color:"cyan"},children:wa[d]})}),N($,{...s&&{color:"cyan"},children:">"}),N($,{children:a}),s&&N($,{color:"cyan",children:"\u2588"})]},d)}),J(V,{gap:2,children:[N(V,{width:12,children:N($,{bold:C,...C&&{color:"cyan"},children:"Environment"})}),N($,{...C&&{color:"cyan"},children:">"}),N(V,{gap:1,children:Y.map((d,l)=>{let s=l===j;return C?N($,{bold:s,...s&&{color:"cyan"},children:s?`[${d}]`:d},d):N($,{dimColor:!s,bold:s,children:d},d)})})]})]}),C?N(Ye,{text:"\u2190\u2192 to select \xB7 \u2191\u2193 to move \xB7 Enter to save \xB7 Esc to cancel"}):N(Ye,{text:"\u2191\u2193 to move \xB7 Backspace to delete \xB7 Esc to cancel"}),J($,{dimColor:!0,children:["Profile: ",v]})]})};import{jsx as D,jsxs as U}from"react/jsx-runtime";var Pa=[".kizenapp",".git"],Hn=({port:e,pluginDir:t,outputDir:n,credentials:o,credentialMode:r,activeCredentialProfile:i,lastPath:p,debug:f=!1,verbose:g=!1,autoViewer:m=!0,cacheEnabled:y=!0})=>{let T=pe(o),P=pe(i),x=pe(p),[c,b]=Q("main"),[w,H]=Q(r),[j,C]=Q("starting"),[v,d]=Q(null),[l,s]=vt(50),[a,u]=vt(50),[h,k]=vt(50),[E,R]=Q([]),[z,W]=Q("pending"),[te,oe]=Q(null),[ie,re]=Q(null),[ee,je]=Q(null),[Ee,Nt]=Q(null),[Rt,Bt]=Q(0),[dr,No]=Q(0),[Ro,Bo]=Q(0),[At,Ao]=Q(0),Dt=pe(!1),pr=pe(!1),Ze=pe(null),Le=pe(null),ue=pe(new Set),Qe=pe([]),ne=$e(S=>{let O=JSON.stringify(S);if(ue.current.size===0){Qe.current=[...Qe.current,O].slice(-50);return}let fe=!1;for(let se of ue.current)if(se.readyState===1)try{se.send(O)}catch{ue.current.delete(se),fe=!0}fe&&Bt(ue.current.size)},[]),et=s,Ft=$e(()=>{Ze.current?.kill(),Ze.current=null,zn({port:e,userDataDir:Mn(n,".chrome"),broadcast:ne,onWarn:S=>{s(`\u26A0 ${S}`)},...x.current!==void 0&&{path:x.current},...f&&{debugLog:k},...g&&{verbose:!0}}).then(S=>{Ze.current=S})},[e,n,ne,f,g,k,s]);Tt(()=>{let S=()=>{Ze.current?.kill()};return process.on("exit",S),()=>{process.off("exit",S)}},[]),Sa((S,O)=>{(S==="q"||O.ctrl&&S==="c")&&process.exit(0),S==="c"&&b("editing"),S==="v"&&Ft()},{isActive:c==="main"}),Tt(()=>{j!=="running"||pr.current||!m||(pr.current=!0,Ft())},[j,m,Ft]);let Do=$e(S=>{T.current=S.credentials,P.current=S.profileName,b("main"),H(S.mode);let O=S.profileName;Ce(n,{credentialMode:S.mode,...O!==void 0&&{activeCredentialProfile:O}}),ne({type:"credentials-updated",credentials:S.credentials})},[n,ne]),ur=$e(S=>{R(O=>[...O,`${new Date().toLocaleTimeString()}: ${nr(S)}`].slice(-50)),S.kind==="request"&&(S.fromCache?Bo(O=>O+1):Ao(O=>O+1)),ne({type:"proxy-log",entry:S})},[ne]),_e=$e(S=>{u(S),ne({type:"log",message:S})},[u,ne]),$t=$e(()=>{Dt.current||(Dt.current=!0,W("building"),oe(null),re(null),_e("Build started"),ot(t,n).then(({bundleSize:S})=>{_e(`Build finished \u2014 bundle: ${Oe(S)}`),W("done"),je(new Date),Nt(S),_e("Notifying viewers to reload"),ne({type:"rebuild"})}).catch(S=>{S instanceof Ta?(re(S.issues),oe(null)):(oe(S instanceof Error?S.message:String(S)),re(null)),W("error")}).finally(()=>{Dt.current=!1}))},[t,n,_e,ne]);if(Tt(()=>{$t();let S=Ea(t,{recursive:!0},(O,fe)=>{if(!fe)return;let se=fe.replace(/\\/g,"/");Pa.some(tt=>se.startsWith(tt))||(_e(`File change detected: ${fe}`),Le.current!==null&&clearTimeout(Le.current),Le.current=setTimeout($t,150))});return S.on("error",O=>{_e(`File watcher error \u2014 rebuilds have stopped: ${O.message}`)}),()=>{S.close(),Le.current!==null&&clearTimeout(Le.current)}},[t,$t,_e]),Tt(()=>{let S=Fn();ir(Mn(S,"index.html")).then(O=>{if(!O){d("Viewer not built. Run 'pnpm build:viewer' first."),C("error");return}let fe=$n(S,et,ur,T,P,n,ne,No,x,t,y),se=_a(fe),tt=new ka({server:se});return tt.on("connection",ke=>{for(let $o of Qe.current)ke.readyState===1&&ke.send($o);Qe.current=[],et("Viewer connected for live reload"),ue.current.add(ke),Bt(ue.current.size),ke.on("close",()=>{ue.current.delete(ke),Bt(ue.current.size)})}),se.listen(e,"127.0.0.1",()=>{C("running"),et(`Server started on 127.0.0.1:${String(e)}`)}),se.on("error",ke=>{d(ke.message),C("error")}),()=>{tt.close(),se.close()}})},[e,et,ur,ne,n,t,y]),c==="editing")return D(St,{...w!==void 0&&{initialMode:w},showProfileManager:w==="global",onComplete:Do,onCancel:()=>{b("main")}});let jt=ee!==null?Math.round((Date.now()-ee.getTime())/1e3):null,Fo=jt===null?"":jt<5?" (just now)":` (${String(jt)}s ago)`,fr=ie?.filter(S=>S.severity==="error").length??0;return U(G,{flexDirection:"column",paddingY:1,paddingX:2,children:[D(q,{marginBottom:1}),U(G,{flexDirection:"column",children:[U(G,{gap:2,marginBottom:0,children:[D(A,{bold:!0,dimColor:!0,children:"App Build"}),z==="pending"&&D(A,{dimColor:!0,children:"waiting\u2026"}),z==="building"&&U(G,{gap:1,children:[D(me,{}),D(A,{children:"Building plugin package\u2026"})]}),z==="done"&&U(G,{gap:1,children:[D(A,{color:"green",children:"\u2713 Built"}),ee!==null&&U(A,{dimColor:!0,children:["at ",ee.toLocaleTimeString(),Fo]}),Ee!==null&&U(A,{dimColor:!0,children:["\xB7 bundle: ",Oe(Ee)]})]}),z==="error"&&(ie!==null?U(A,{color:"red",children:["\u2717 ",fr," validation ",fr===1?"error":"errors"]}):U(A,{color:"red",children:["\u2717 ",te??"unknown error"]}))]}),ie!==null&&D(st,{issues:ie}),D(G,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:a.slice(-8).map((S,O)=>D(A,{dimColor:!0,wrap:"truncate",children:S},O))})]}),U(G,{marginTop:1,flexDirection:"column",children:[U(G,{gap:2,children:[D(A,{bold:!0,dimColor:!0,children:"Web Server"}),j==="starting"&&D(A,{dimColor:!0,children:"starting\u2026"}),j==="running"&&U(G,{gap:2,children:[D(A,{color:"green",children:"\u2713 Running"}),U(A,{dimColor:!0,children:["\u25CF ",Rt," viewer",Rt!==1?"s":""]})]}),j==="error"&&U(A,{color:"red",children:["\u2717 ",v??"Server error"]})]}),D(G,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:l.slice(-8).map((S,O)=>D(A,{dimColor:!0,wrap:"truncate",children:S},O))})]}),U(G,{marginTop:1,flexDirection:"column",children:[U(G,{gap:2,children:[D(A,{bold:!0,dimColor:!0,children:"Network Proxy"}),D(A,{color:"green",children:"\u2713 Active"}),D(A,{dimColor:!0,children:y?`\u25CF ${String(dr)} key${dr!==1?"s":""} in the network cache \xB7 ${String(Ro)} hit \xB7 ${String(At)} miss`:`\u25CF network cache disabled \xB7 ${String(At)} request${At!==1?"s":""}`})]}),D(G,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:E.length===0?D(A,{dimColor:!0,children:" No requests yet."}):E.slice(-8).map((S,O)=>D(A,{dimColor:!0,wrap:"truncate",children:S},O))})]}),f&&U(G,{marginTop:1,flexDirection:"column",children:[U(G,{gap:2,children:[D(A,{bold:!0,dimColor:!0,children:"CDP Debug"}),U(A,{dimColor:!0,children:["\u25CF ",h.length," event(s)"]})]}),D(G,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:h.length===0?D(A,{dimColor:!0,children:" No CDP events yet."}):h.slice(-8).map((S,O)=>D(A,{dimColor:!0,wrap:"truncate",children:S},O))})]}),U(G,{marginTop:1,gap:1,children:[D(A,{dimColor:!0,children:"["}),D(A,{children:"q"}),D(A,{dimColor:!0,children:"] quit ["}),D(A,{children:"c"}),D(A,{dimColor:!0,children:"] credentials ["}),D(A,{children:"v"}),U(A,{dimColor:!0,children:["] ",Rt===0?"open viewer":"relaunch viewer"]})]})]})};async function Un(e){return new Promise(t=>{let n=null,o=i=>{n?.(),t(i)},{unmount:r}=qn(Vn(St,{...e!==void 0&&{initialMode:e},onComplete:o}),{exitOnCtrlC:!1});n=r})}function Jn(e){e.command("dev").description("Start the plugin viewer dev server").option("-p, --port <port>","port to listen on","3121").option("-c, --credentials <path>","path to a credentials JSON file").option("-d, --debug","Enable CDP lifecycle logs in the TUI").option("-v, --verbose","Log every CDP event and handled error (implies --debug)").option("--no-viewer","Don't auto-launch the viewer on startup (press [v] to launch manually)").option("--no-cache","Disable the network proxy cache (always fetch upstream)").action(async t=>{let n=parseInt(t.port,10),o=process.cwd(),r=`${o}/.kizenapp`;he(o);let i=null,p,f,{lastPath:g}=await we(r);if(t.credentials)i=await ve(t.credentials);else{let c=await we(r);if(c.credentialMode==="local")p="local";else if(c.credentialMode==="global"){if(p="global",f=c.activeCredentialProfile,f?(i=await de(f),i||(i=await Z(),f=void 0)):i=await Z(),!i){let b=await Un("global");i=b.credentials,f=b.profileName}}else{let b=await Un();i=b.credentials,p=b.mode,f=b.profileName;let w=b.profileName;await Ce(r,{credentialMode:b.mode,...w!==void 0&&{activeCredentialProfile:w}})}}let m=t.verbose===!0,y=m||t.debug===!0,T=t.viewer!==!1,P=t.cache!==!1,{waitUntilExit:x}=qn(Vn(Hn,{port:n,pluginDir:o,outputDir:r,credentials:i,...p!==void 0&&{credentialMode:p},...f!==void 0&&{activeCredentialProfile:f},...g!==void 0&&{lastPath:g},debug:y,verbose:m,autoViewer:T,cacheEnabled:P}),{exitOnCtrlC:!1});await x()})}import{createElement as qa}from"react";import{render as Ja}from"ink";import{useCallback as _t,useEffect as Zn,useState as kt}from"react";import{Box as ae,Text as L,useApp as Oa,useInput as za}from"ink";import{encrypt as Ia,serializeEnvelope as Na}from"@kizenapps/packager";function Ra(e){let t=e;return t.code==="ECONNREFUSED"||t.cause?.code==="ECONNREFUSED"}function Wn(e){return{"Content-Type":"application/json","x-api-key":e.apiKey,"x-user-id":e.userId,"x-business-id":e.businessId,"x-auth-environment":e.environment}}async function Gn(e,t,n){try{return await fetch(`${e}${t}`,n)}catch(o){throw new Error(Ra(o)?`Plugin-wizard is not running at ${e}`:`Failed to reach plugin-wizard: ${o.message}`)}}async function Kn(e){let t=await e.text();if(t==="")return{};try{let n=JSON.parse(t);return typeof n=="object"&&n!==null?n:{}}catch{return{}}}async function Ba(e,t,n){let o=qe(e.stage),r=await Gn(o,"/get-public-key",{method:"POST",headers:Wn(t),body:JSON.stringify({api_name:n})}),i=await Kn(r);if(!r.ok||typeof i.public_key!="string"){let p=typeof i.error=="string"?i.error:`HTTP ${String(r.status)}`;throw new Error(`Failed to fetch public key: ${p}`)}return i.public_key}function Aa(e,t){let n=Ia(t,e),o=Na(n);if(typeof o.value!="string")throw new Error("Unexpected serialized envelope shape from @kizenapps/packager");return o.value}async function Da(e,t,n,o){let r=qe(e.stage),i=await Gn(r,"/encrypt",{method:"POST",headers:Wn(t),body:JSON.stringify({api_name:n,value:o})}),p=await Kn(i);if(!i.ok||p.encrypted!==!0||typeof p.value!="string"){let f=typeof p.error=="string"?p.error:`HTTP ${String(i.status)}`;throw new Error(`Encryption via plugin-wizard failed: ${f}`)}return p.value}async function Et(e,t,n,o,r){if(e.isRemote)return r?.("encrypting"),Da(e,t,n,o);r?.("fetching-key");let i=await Ba(e,t,n);return r?.("encrypting"),Aa(i,o)}import{spawn as Fa}from"child_process";import{platform as Yn}from"process";function $a(){return Yn==="darwin"?[{cmd:"pbcopy",args:[]}]:Yn==="win32"?[{cmd:"clip",args:[]}]:[{cmd:"wl-copy",args:[]},{cmd:"xclip",args:["-selection","clipboard"]},{cmd:"xsel",args:["--clipboard","--input"]}]}var ja=2e3;function La(e,{cmd:t,args:n}){return new Promise(o=>{let r;try{r=Fa(t,n,{stdio:["pipe","ignore","ignore"]})}catch{o(!1);return}let i=r,p=!1;function f(m){p||(p=!0,clearTimeout(g),o(m))}let g=setTimeout(()=>{i.kill(),f(!1)},ja);g.unref(),i.on("error",()=>{f(!1)}),i.on("close",m=>{f(m===0)}),i.stdin.on("error",()=>{f(!1)});try{i.stdin.end(e)}catch{f(!1)}})}async function Xn(e){for(let t of $a())if(await La(e,t))return!0;return!1}import{Fragment as Pt,jsx as F,jsxs as K}from"react/jsx-runtime";var ar=({text:e})=>F(L,{dimColor:!0,children:e}),Qn=({ctx:e,stageDefaulted:t,credentialsPath:n,initialApiName:o,defaultApiName:r,initialValue:i,onDone:p})=>{let f=Oa(),[g,m]=kt({type:"loading"}),[y,T]=kt(null),[P,x]=kt(o??""),[c,b]=kt(i??""),w=_t(s=>{process.exitCode=1,m({type:"error",message:s instanceof Error?s.message:String(s)})},[]),H=_t(async(s,a,u)=>{try{let h=await Et(e,s,a,u,R=>{m(R==="fetching-key"?{type:"fetching-key"}:{type:"encrypting"})}),k=JSON.stringify({encrypted:!0,value:h},null,2);p?.(h);let E=await Xn(k);m({type:"done",envelope:k,copied:E})}catch(h){w(h)}},[e,w,p]),j=_t((s,a,u)=>{if(a.trim()===""){m({type:"api-name-entry",buffer:r??""});return}if(u===""){m({type:"value-entry",buffer:""});return}H(s,a.trim(),u)},[r,H]),C=_t(async s=>{try{m({type:"loading"});let a=s.isDefault?await Z():await de(s.name);if(a===null)throw new Error(`Could not load credential profile: ${s.name}`);T(a),j(a,P,c)}catch(a){w(a)}},[P,c,j,w]);Zn(()=>{(async()=>{try{if(n!==void 0){let u;try{u=await ve(n)}catch(h){throw new Error(`Could not load credentials from ${n}: ${h instanceof Error?h.message:String(h)}`)}T(u),j(u,P,c);return}let s=await Re();if(s.length===0)throw new Error("No credential profiles found. Create ~/.kizenappbuilder/credentials.json first.");let[a]=s;if(s.length===1&&a!==void 0){let u=a.isDefault?await Z():await de(a.name);if(u===null)throw new Error(`Could not load credential profile: ${a.name}`);T(u),j(u,P,c);return}m({type:"profile-select",profiles:s,cursor:0})}catch(s){w(s)}})()},[]),Zn(()=>{(g.type==="done"||g.type==="error")&&f.exit()},[g,f]),za((s,a)=>{if(a.ctrl&&s==="c"){process.exitCode=130,f.exit();return}if(g.type==="profile-select"){let{profiles:u,cursor:h}=g;if(a.upArrow)m({...g,cursor:(h-1+u.length)%u.length});else if(a.downArrow)m({...g,cursor:(h+1)%u.length});else if(a.return){let k=u[h];k!==void 0&&C(k)}return}if(g.type==="api-name-entry"){let{buffer:u}=g;if(a.backspace||a.delete)m({type:"api-name-entry",buffer:u.slice(0,-1)});else if(a.return){let h=u.trim();if(h===""){m({type:"api-name-entry",buffer:u,error:"api_name cannot be empty"});return}x(h),y?j(y,h,c):w(new Error("Internal error: credentials were not loaded"))}else s&&!a.ctrl&&!a.meta&&m({type:"api-name-entry",buffer:u+s});return}if(g.type==="value-entry"){let{buffer:u}=g;if(a.backspace||a.delete)m({type:"value-entry",buffer:u.slice(0,-1)});else if(a.return){if(u===""){m({type:"value-entry",buffer:u,error:"secret cannot be empty"});return}b(u),y?j(y,P,u):w(new Error("Internal error: credentials were not loaded"))}else s&&!a.ctrl&&!a.meta&&m({type:"value-entry",buffer:u+s});return}});let v=e.isRemote?"remote Kizen API":"on-machine",d=t===!0?`${e.stage} (default)`:e.stage,l=s=>K(ae,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[F(q,{}),K(L,{dimColor:!0,children:["Mode: ",v," Stage: ",d]}),s]});if(g.type==="loading")return l(K(ae,{gap:1,children:[F(me,{}),F(L,{dimColor:!0,children:"Loading credentials\u2026"})]}));if(g.type==="profile-select"){let{profiles:s,cursor:a}=g;return l(K(Pt,{children:[F(L,{bold:!0,children:"Credential profile"}),F(ae,{flexDirection:"column",children:s.map((u,h)=>{let k=a===h;return K(ae,{gap:2,children:[F(L,{...k&&{color:"cyan"},children:k?"\u276F":" "}),F(L,{bold:k,...k&&{color:"cyan"},children:u.isDefault?"Default":u.name}),F(L,{dimColor:!0,children:u.path})]},u.name)})}),F(ar,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]}))}return g.type==="api-name-entry"?l(K(Pt,{children:[F(L,{bold:!0,children:"Plugin api_name"}),g.error!==void 0&&K(L,{color:"red",children:["Error: ",g.error]}),K(ae,{gap:1,children:[F(L,{color:"cyan",children:">"}),F(L,{children:g.buffer}),F(L,{color:"cyan",children:"\u2588"})]}),F(ar,{text:"Type the api_name \xB7 Enter to confirm \xB7 Ctrl+C to quit"})]})):g.type==="value-entry"?l(K(Pt,{children:[F(L,{bold:!0,children:"Secret value"}),g.error!==void 0&&K(L,{color:"red",children:["Error: ",g.error]}),K(ae,{gap:1,children:[F(L,{color:"cyan",children:">"}),F(L,{children:"\u2022".repeat(g.buffer.length)}),F(L,{color:"cyan",children:"\u2588"})]}),F(ar,{text:"Input hidden \xB7 Enter to encrypt \xB7 Ctrl+C to quit"})]})):g.type==="fetching-key"?l(K(ae,{gap:1,children:[F(me,{}),K(L,{children:["Fetching ",e.stage," public key for ",F(L,{bold:!0,children:P}),"\u2026"]})]})):g.type==="encrypting"?l(K(ae,{gap:1,children:[F(me,{}),F(L,{children:"Encrypting\u2026"})]})):g.type==="error"?l(K(ae,{gap:1,children:[F(L,{color:"red",children:"\u2717"}),F(L,{color:"red",children:g.message})]})):l(K(Pt,{children:[K(ae,{gap:1,children:[F(L,{color:"green",children:"\u2713"}),F(L,{bold:!0,children:"Encrypted secret ready"})]}),g.copied?F(L,{color:"green",children:"\u2713 Copied to clipboard \u2014 paste it into the secret value in your kizen.json."}):F(L,{dimColor:!0,children:"Paste this into the secret value in your kizen.json (re-run with --out <path> to save it to a file; selecting it here may capture line wraps):"}),F(L,{children:g.envelope})]}))};import{readFile as Ma,writeFile as Ha}from"fs/promises";import{join as Ua}from"path";function eo(e){return{encrypted:!0,value:e}}function to(e){return JSON.stringify(eo(e))}async function lr(e,t){await Ha(e,`${JSON.stringify(eo(t),null,2)}
|
|
458
|
-
`,"utf-8")}var
|
|
459
|
-
`}async function
|
|
460
|
-
`),
|
|
461
|
-
`),t.out!==void 0)try{await
|
|
462
|
-
`)}catch(
|
|
463
|
-
`),
|
|
464
|
-
`)}catch(
|
|
465
|
-
${
|
|
466
|
-
`)}var
|
|
1063
|
+
`.trim(),Mu=3e4,gr=xt(process.cwd(),".kizenapp","venv"),Uu=Ou.map(Cs),Ss=bs(ys);if(Ss.length===0)throw new Error("python-requirements.txt bundled no packages \u2014 check the build output");var wt=null,vt=[3,10];function _s([e,t]){return e>vt[0]||e===vt[0]&&t>=vt[1]}function jn(e){return`${String(e[0])}.${String(e[1])}`}function Ps(e){return new Promise(t=>{let r=zn(e,["-c","import sys; print('%d.%d' % sys.version_info[:2])"],{stdio:["ignore","pipe","ignore"]}),o="";r.stdout.on("data",n=>{o+=n.toString("utf-8")}),r.on("error",()=>{t(null)}),r.on("close",n=>{let i=/(\d+)\.(\d+)/.exec(o);if(n!==0||!i){t(null);return}t([Number(i[1]),Number(i[2])])})})}async function Hu(e){let t=ws(e),r=t==="python3"?["python3"]:[t,"python3"],o=[];for(let n of r){let i=await Ps(n);if(!i){o.push(`${n}: not found`);continue}if(_s(i))return n;o.push(`${n}: ${jn(i)} (too old)`)}throw new Error(`No Python >= ${jn(vt)} found for runtime "${e}". The local runner needs Python ${jn(vt)}+ to install the bundled packages (e.g. psycopg 3.3), matching the remote code-runner (3.12 / 3.13). Tried ${o.join(", ")}. Install Python 3.12 or 3.13 and retry.`)}function ks(e,t,r){return new Promise((o,n)=>{let i=zn(e,t,{stdio:["ignore","pipe","pipe"]}),s=(l,p)=>{let g=[],v="";return l.on("data",k=>{v+=k.toString("utf-8");let f=v.indexOf(`
|
|
1064
|
+
`);for(;f>=0;){let c=v.slice(0,f).replace(/\r$/,"");v=v.slice(f+1),g.push(c),r?.(c,p),f=v.indexOf(`
|
|
1065
|
+
`)}}),l.on("end",()=>{if(v.length>0){let k=v.replace(/\r$/,"");g.push(k),r?.(k,p)}}),g},a=s(i.stderr,"stderr");s(i.stdout,"stdout"),i.on("error",n),i.on("close",l=>{if(l===0)o();else{let p=a.slice(-10).join(`
|
|
1066
|
+
`).trim(),g=p.length>0?`: ${p}`:"";n(new Error(`${e} exited with code ${String(l)}${g}`))}})})}var On=null;function Vu(e,t){if(wt)return t&&On?.add(t),wt;let r=new Set;t&&r.add(t),On=r;let o=i=>{for(let s of r)s(i)},n=xt(gr,"bin","python");return wt=(async()=>{try{let i=!1;try{await Fu(n);let s=await Ps(n);i=s!==null&&_s(s)}catch{i=!1}if(!i){await Ln(gr,{recursive:!0,force:!0}).catch(()=>{});let s=await Hu(e);await ks(s,["-m","venv",gr])}return o({kind:"start"}),await ks(n,["-m","pip","install","--disable-pip-version-check",...Ss],(s,a)=>{o({kind:"log",line:s,stream:a})}),o({kind:"complete"}),n}catch(i){let s=i instanceof Error?i.message:String(i);throw o({kind:"error",message:s}),wt=null,await Ln(gr,{recursive:!0,force:!0}).catch(()=>{}),i}finally{On=null}})(),wt}function Wu(e){let t="__KIZEN_RESULT_START__",r="__KIZEN_RESULT_END__",o=e.indexOf(t),n=e.indexOf(r);if(o===-1||n===-1)return{userStdout:e,result:null};let i=e.slice(0,o).trimEnd(),s=e.slice(o+t.length,n).trim();try{let a=JSON.parse(s);return{userStdout:i,result:a}}catch{return{userStdout:e,result:null}}}function Ku(e){return{success:!1,outputValues:{},logs:[],stdout:"",stderr:"",error:e,exitCode:1,durationMs:0}}async function Es(e){let t=e.timeout??Mu;if(!Lu(e.scriptRuntime))return Ku(`Unsupported runtime "${e.scriptRuntime}". Supported runtimes: ${Uu.join(", ")}. Update the step's config.json "runtime" field (e.g. "python 3.13").`);let o=await Vu(Cs(e.scriptRuntime),e.onInstallProgress),n=Date.now(),i;try{i=await $u(xt(ju(),"kizen-step-"));let s=xt(i,"wrapper.py"),a=xt(i,"script.py");await Promise.all([vs(s,zu,"utf-8"),vs(a,e.script,"utf-8")]);let l={...process.env,__KIZEN_INPUTS__:JSON.stringify(e.inputs),__KIZEN_SECRETS__:JSON.stringify(e.secrets),__KIZEN_SCRIPT_PATH__:a},{exitCode:p,stdout:g,stderr:v}=await new Promise(x=>{let I=[],C=[],S=!1,N=zn(o,[s],{env:l,cwd:i,stdio:["ignore","pipe","pipe"]}),b=setTimeout(()=>{N.kill("SIGKILL")},t);N.stdout.on("data",d=>{I.push(d)}),N.stderr.on("data",d=>{C.push(d)});let u=d=>{S||(S=!0,clearTimeout(b),x({exitCode:d??1,stdout:Buffer.concat(I).toString("utf-8"),stderr:Buffer.concat(C).toString("utf-8")}))};N.on("close",u),N.on("error",d=>{S||(S=!0,clearTimeout(b),x({exitCode:1,stdout:"",stderr:d.message}))})}),k=Date.now()-n,{userStdout:f,result:c}=Wu(g);if(c){let x={success:c.success,outputValues:c.outputValues,logs:c.logs,stdout:f,stderr:v,exitCode:p,durationMs:k};return c.error!==null&&(x.error=c.error),c.httpRequests&&(x.httpRequests=c.httpRequests),x}let h={success:!1,outputValues:{},logs:[],stdout:f,stderr:v,exitCode:p,durationMs:k};return p!==0&&(h.error=`Process exited with code ${String(p)}`),h}finally{i&&Ln(i,{recursive:!0,force:!0})}}var Ts=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"]);import{CRYPTO_ALG as Ns,CRYPTO_VERSION as Bs,DEFAULT_AUTOMATION_RUNTIME as tp,deserializeEnvelope as rp,encrypt as np,scriptRuntimeToApiName as op,serializeEnvelope as ip}from"@kizenapps/packager";function Mn(e){if(e.kind==="info")return e.message;let t=e.fromCache?" [cache]":"",r=e.upstreamStatus!==void 0?` (upstream ${String(e.upstreamStatus)})`:"";return`${e.method} ${e.url} \u2192 ${String(e.status)}${r}${t}`}var sp=2*1024*1024,ap=new Set([".DS_Store",".gitignore"]);function lp(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 js=["kizen.com","kizen.dev"];function cp(e){let t;try{t=new URL(e)}catch{return!1}let r=t.hostname.toLowerCase();return r==="localhost"||r==="127.0.0.1"||r==="[::1]"?!0:t.protocol!=="https:"?!1:js.some(o=>r===o||r.endsWith("."+o))}function dp(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let r=t.hostname.toLowerCase();return js.some(o=>r===o||r.endsWith("."+o))}function up(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 Rs(e,t){if(t.includes("\0"))return null;let r=t.replace(/^\/+/,""),o=Qu(e,r);if(o!==e&&!o.startsWith(e+Un))return null;try{let n=await Xu(o);return n!==e&&!n.startsWith(e+Un)?null:n}catch{return null}}function $s(e,t){let r=t===e?"":t.slice(e.length+1);return r===""?!1:r.split(Un).some(n=>jt.has(n))}function Os(){let e=ep(import.meta.url);return kt(Zu(e),"viewer")}function Fs(e,t,r){if(e.includes("/external-integrations/proxy")&&t["content-type"]?.includes("application/json"))try{let o=JSON.parse(r.toString("utf8"));return typeof o.status_code=="number"?o.status_code:void 0}catch{return}}async function Hn(e){try{return await qu(e),!0}catch{return!1}}function Ls(e,t,r,o,n,i,s,a,l,p,g){let v=gs({onChange:a,enabled:g}),k=Ju(p);return(f,c)=>{(async()=>{let h=f.url??"/";try{if(!lp(f.headers.host)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Forbidden"}));return}if((f.method==="POST"||f.method==="PATCH"||f.method==="DELETE")&&!up(f.headers.origin)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Forbidden"}));return}if(t(`Received request: ${h}`),h==="/api/credentials"){c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({credentials:o.current??null,activeProfile:n.current??null}));return}if(h==="/api/credential-profiles"&&f.method==="GET"){let u=await Ne();c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({profiles:u,active:n.current}));return}if(h==="/api/credentials/switch"&&f.method==="POST"){let u=[];for await(let w of f)u.push(w);let m=JSON.parse(Buffer.concat(u).toString("utf-8")||"{}").profile,y=m===void 0||m===""?await re():await ke(m);if(y!==null){o.current=y,n.current=m??void 0;let w=n.current,E=await he(i);await Ie(i,{...E,credentialMode:"global",...w!==void 0&&{activeCredentialProfile:w}}),s({type:"credentials-updated",credentials:y,activeProfile:n.current??null})}c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({ok:y!==null}));return}if(h==="/api/bundle"){let u=kt(process.cwd(),".kizenapp","bundle.json");try{let d=await Yu(u,"utf-8");c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(d)}catch{c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end("{}")}return}if(h==="/api/last-path"&&f.method==="POST"){let u=[];for await(let m of f)u.push(m);let d=JSON.parse(Buffer.concat(u).toString("utf-8")||"{}");if(typeof d.path=="string"){l.current=d.path;let m=await he(i);await Ie(i,{...m,lastPath:d.path})}c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end('{"ok":true}');return}if(h==="/api/encryption-target"&&f.method==="GET"){let d=(await he(i)).encryptionTarget==="dev"?"dev":"prod";c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({target:d}));return}if(h==="/api/encryption-target"&&f.method==="POST"){let u=[];for await(let w of f)u.push(w);let d=JSON.parse(Buffer.concat(u).toString("utf-8")||"{}"),m=d!==null&&typeof d=="object"?d:{};if(m.target!=="dev"&&m.target!=="prod"){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"target must be one of: 'dev', 'prod'"}));return}let y=await he(i);await Ie(i,{...y,encryptionTarget:m.target}),c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end('{"ok":true}');return}if(h==="/api/execute-step"&&f.method==="POST"){let u=[];for await(let w of f)u.push(w);let d=JSON.parse(Buffer.concat(u).toString("utf-8")||"{}");if(typeof d.script!="string"){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Missing required field: script"}));return}let m={script:d.script,scriptRuntime:d.scriptRuntime??op(tp),inputs:xs(d.inputs),secrets:d.secrets??{},onInstallProgress:w=>{w.kind==="start"?s({type:"venv-install-start"}):w.kind==="log"?s({type:"venv-install-log",line:w.line,stream:w.stream}):w.kind==="complete"?s({type:"venv-install-complete"}):s({type:"venv-install-error",message:w.message})}};typeof d.timeout=="number"&&d.timeout>0&&(m.timeout=Math.min(d.timeout,300*1e3));let y=await Es(m);c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify(y));return}if(h==="/api/proxy-cache/clear"){v.clear(),r({kind:"info",message:"Proxy cache cleared"}),c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end('{"ok":true}');return}if(h==="/api/local/encrypt"&&f.method==="POST"){let u=[];for await(let m of f)u.push(m);let d=JSON.parse(Buffer.concat(u).toString("utf-8")||"{}");if(typeof d.publicKeyPem!="string"||typeof d.value!="string"){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Missing required fields: publicKeyPem, value"}));return}try{let m=np(d.value,d.publicKeyPem),y=ip(m);c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify(y))}catch(m){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:m.message}))}return}if(h==="/api/local/validate"&&f.method==="POST"){let u=[];for await(let _ of f)u.push(_);let d=JSON.parse(Buffer.concat(u).toString("utf-8")||"{}");if(typeof d.value!="string"){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Missing required field: value"}));return}let m,y;try{m=rp(d.value)}catch(_){y=_.message}if(y!==void 0||m===void 0){c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({valid:!1,checks:[],error:y}));return}let w=_=>Buffer.from(_,"base64").length,E=[{label:"Version",expected:String(Bs),actual:String(m.v),pass:m.v===Bs},{label:"Algorithm",expected:Ns,actual:m.alg,pass:m.alg===Ns},{label:"Wrapped key",expected:"384 bytes (RSA-3072)",actual:`${String(w(m.k))} bytes`,pass:w(m.k)===384},{label:"IV",expected:"12 bytes",actual:`${String(w(m.iv))} bytes`,pass:w(m.iv)===12},{label:"Auth tag",expected:"16 bytes",actual:`${String(w(m.tag))} bytes`,pass:w(m.tag)===16},{label:"Ciphertext",expected:"\u2265 1 byte",actual:`${String(w(m.ct))} bytes`,pass:w(m.ct)>=1}];c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({valid:E.every(_=>_.pass),checks:E}));return}if(h.startsWith("/api/wizard")){let u=f.headers["x-encryption-target"],m=(Array.isArray(u)?u[0]:u)==="dev"?"dev":"prod",y=bt(m);if(!cp(y)){c.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:`Encryption API host is not allowed: ${y}`}));return}let w=h.slice(11)||"/",E=`${y}${w}`,_=f.method??"GET",R=[];for await(let Oe of f)R.push(Oe);let{host:M,"x-encryption-target":X,...ie}=f.headers,pe=R.length>0?Buffer.concat(R):void 0,fe=pe&&pe.length>0?pe:void 0,ce;try{ce=await fetch(E,{method:_,headers:ie,...fe!==void 0&&{body:fe}})}catch(Oe){let Er=Oe.code==="ECONNREFUSED"?`plugin-wizard is not running at ${y}`:`Failed to reach plugin-wizard: ${Oe.message}`;c.writeHead(503,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:Er}));return}let le=hr(Object.fromEntries(ce.headers)),nt=await ce.arrayBuffer();c.writeHead(ce.status,le),c.end(Buffer.from(nt));return}if(h.startsWith("/api/proxy")){let u=f.headers["x-proxy-target"];if(typeof u!="string"){c.writeHead(400),c.end("Missing x-proxy-target header");return}if(!dp(u)){c.writeHead(400),c.end("Invalid proxy target");return}let d=h.slice(10)||"/",m=`${u}${d}`,y=f.method??"GET",w=[];for await(let ce of f)w.push(ce);let{host:E,"x-proxy-target":_,...R}=f.headers;if(y==="GET"){let ce=`GET::${m}`,{response:le,fromCache:nt}=await v.get(ce,()=>fetch(m,{method:"GET",headers:R}));r({kind:"request",method:"GET",status:le.status,upstreamStatus:Fs(d,le.headers,le.body),fromCache:nt,url:d}),c.writeHead(le.status,le.headers),c.end(le.body);return}let M=w.length>0?Buffer.concat(w):void 0,X=M&&M.length>0?M:void 0,ie=await fetch(m,{method:y,headers:R,...X!==void 0&&{body:X}}),pe=hr(Object.fromEntries(ie.headers)),fe=await Rn(ie,Bn);r({kind:"request",method:y,status:ie.status,upstreamStatus:Fs(d,pe,fe),fromCache:!1,url:d}),c.writeHead(ie.status,pe),c.end(fe);return}if(h.startsWith("/api/source/tree")&&f.method==="GET"){let d=new URL(h,"http://localhost").searchParams.get("path")??"",m=await Rs(k,d);if(m===null){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Invalid path"}));return}if($s(k,m)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Path is excluded"}));return}try{let y=await Gu(m,{withFileTypes:!0}),w=await Promise.all(y.filter(_=>_.isDirectory()?!jt.has(_.name):_.isFile()?!ap.has(_.name):!1).map(async _=>{let R=_.isDirectory()?"dir":"file",M={name:_.name,kind:R};if(R==="file")try{let X=await Ds(kt(m,_.name));M.size=X.size}catch{}return M}));w.sort((_,R)=>_.kind!==R.kind?_.kind==="dir"?-1:1:_.name.localeCompare(R.name));let E=m===k?"":m.slice(k.length+1);c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({path:E,entries:w}))}catch(y){let w=y instanceof Error?y.message:String(y);t(`source/tree failed (${d}): ${w}`),c.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not found"}))}return}if(h.startsWith("/api/source/file")&&f.method==="GET"){let d=new URL(h,"http://localhost").searchParams.get("path")??"";if(d===""){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Missing path"}));return}let m=await Rs(k,d);if(m===null){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Invalid path"}));return}if($s(k,m)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Path is excluded"}));return}try{let y=await Ds(m);if(!y.isFile()){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not a file"}));return}if(y.size>sp){c.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"File too large",size:y.size}));return}let w=As(m).toLowerCase(),E=$n[w],_=Ts.has(w),R=E??(_?"text/plain; charset=utf-8":"application/octet-stream");c.writeHead(200,{"Content-Type":R,"Content-Length":String(y.size)}),Is(m).pipe(c)}catch(y){let w=y instanceof Error?y.message:String(y);t(`source/file failed (${d}): ${w}`),c.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not found"}))}return}let C=kt(e,h==="/"?"/index.html":h),S=await Hn(C)?C:kt(e,"index.html"),N=As(S),b=$n[N]??"application/octet-stream";c.writeHead(200,{"Content-Type":b}),Is(S).pipe(c)}catch(x){if(h.startsWith("/api/proxy")){let I=h.slice(10)||"/",C=f.method??"GET";x instanceof yt?r({kind:"info",message:`${C} ${I} \u2192 502 (response exceeded ${String(x.limit)} bytes)`}):r({kind:"request",method:C,status:502,fromCache:!1,url:I})}else r({kind:"info",message:`Error handling ${h}: ${x instanceof Error?x.message:String(x)}`});c.headersSent||(c.writeHead(502),c.end("Bad Gateway"))}})()}}import{launch as pp}from"chrome-launcher";import{createRequire as fp}from"module";import{mkdirSync as mp}from"fs";import{readFile as hp}from"fs/promises";import{dirname as gp,join as yp}from"path";import{fileURLToPath as bp}from"url";var zs=fp(import.meta.url)("chrome-remote-interface"),wp=new Set(["content-security-policy","content-security-policy-report-only","x-frame-options"]),Us=["kizen.dev","kizen.com"];function Ms(e){try{let{hostname:t}=new URL(e);return Us.some(r=>t===r||t.endsWith("."+r))}catch{return!1}}async function xp(e){try{let t=yp(gp(bp(import.meta.url)),"viewer","icon.png"),r=await hp(t);await e.Browser.setDockTile({image:r.toString("base64")})}catch{}}async function Hs(e){mp(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,r=await pp({startingUrl:t,chromeFlags:[`--app=${t}`,"--no-first-run","--no-default-browser-check","--disable-extensions","--disable-features=DeviceBoundSessions"],userDataDir:e.userDataDir,handleSIGINT:!1,logLevel:"silent"}),o=r.port,n=null,i=null,s=null,a=null,l=0,p=!1,g=S=>{e.debugLog?.(S)},v=S=>{e.verbose&&e.debugLog?.(S)},k=()=>{i!==null&&(clearInterval(i),i=null)},f=S=>S==="chrome://new-tab-page/"||S==="chrome://newtab/",c=async S=>{k(),s=null,await xp(S),await S.Fetch.enable({patterns:Us.flatMap(b=>[{urlPattern:`*://${b}/*`,requestStage:"Response"},{urlPattern:`*://*.${b}/*`,requestStage:"Response"}])}),S.on("Fetch.requestPaused",b=>{(async()=>{let u=b,{requestId:d,request:m,responseHeaders:y,responseStatusCode:w}=u,E=m.url;v(`Fetch ${String(w??"?")} ${E}`);let _=[],R=!1;for(let M of y??[])if(!wp.has(M.name.toLowerCase()))if(M.name.toLowerCase()==="set-cookie"&&Ms(E)){let X=M.value.split(`
|
|
1067
|
+
`).map(ie=>/SameSite=/i.test(ie)?ie.replace(/SameSite=\w+/i,"SameSite=None"):ie+"; SameSite=None; Secure").join(`
|
|
1068
|
+
`);_.push({name:M.name,value:X}),R=!0}else _.push(M);R&&v(` rewrote Set-Cookie SameSite on ${E}`);try{let{body:M,base64Encoded:X}=await S.Fetch.getResponseBody({requestId:d});await S.Fetch.fulfillRequest({requestId:d,responseCode:w??200,responseHeaders:_,body:M,...X&&{base64Encoded:!0}})}catch(M){v(` fulfillRequest failed (${M.message}), falling through`);try{await S.Fetch.continueRequest({requestId:d})}catch(X){v(` continueRequest also failed (${X.message})`)}}})()}),i=setInterval(()=>{(async()=>{try{let{cookies:b}=await S.Network.getAllCookies(),u=0;for(let d of b){if(!Ms(`https://${d.domain??""}`)||d.sameSite==="None")continue;let m=d.domain??"",y=m.startsWith(".")?m.slice(1):m;await S.Network.setCookie({url:`https://${y}`,name:d.name,value:d.value,domain:m,path:d.path??"/",secure:!0,...d.httpOnly!==void 0&&{httpOnly:d.httpOnly},...d.expirationDate!==void 0&&{expires:d.expirationDate},sameSite:"None"}),u++}u>0&&v(`cookie-patch cycle: updated ${String(u)} cookie(s) to SameSite=None`)}catch(b){v(`cookie-patch cycle failed: ${b.message}`)}})()},2e3),await S.Target.setDiscoverTargets({discover:!0});let N=b=>{if(b.type==="page"){if(f(b.url)){g(`closed stray new-tab-page target ${b.targetId}`),s!==null&&S.Target.activateTarget({targetId:s}).catch(()=>{}),S.Target.closeTarget({targetId:b.targetId}).catch(()=>{});return}s===null&&(s=b.targetId,g(`captured main target ${b.targetId} (${b.url})`))}};S.on("Target.targetCreated",b=>{let{targetInfo:u}=b;v(`target +${u.type} ${u.targetId} ${u.url}`),N(u)}),S.on("Target.targetInfoChanged",b=>{let{targetInfo:u}=b;v(`target ~${u.type} ${u.targetId} ${u.url}`),N(u)}),S.on("disconnect",()=>{p||n!==S||(g("CDP disconnected"),n=null,k(),h())})},h=()=>{if(p||a!==null)return;let S=Math.min(1e3*2**l,1e4),N=l+1;l++,g(`CDP reconnect scheduled in ${String(S)}ms (attempt #${String(N)})`),a=setTimeout(()=>{a=null,(async()=>{let b;try{b=await zs({port:o})}catch{g(`CDP reconnect attempt #${String(N)} failed`),h();return}if(p){try{await b.close()}catch{}return}n=b;try{await c(b),g(`CDP reconnected after ${String(N)} attempt(s)`),l=0}catch{n===b&&(n=null);try{await b.close()}catch{}g(`CDP reconnect attempt #${String(N)} failed during setup`),h()}})()},S)},x=30,I=300;for(let S=0;S<x;S++){await new Promise(N=>setTimeout(N,I)),g(`CDP connect attempt ${String(S+1)}/${String(x)}`);try{let N=await zs({port:o});n=N,e.path&&N.send("Page.navigate",{url:`${t}${e.path}`});try{await c(N),g("CDP connected")}catch{n===N&&(n=null);try{await N.close()}catch{}g("CDP setup failed after connect")}break}catch{if(S===x-1){let N=`CDP unavailable after ${String(x)} attempts \u2014 viewer running without interception (CSP/cookie rewrites disabled)`;return g(N),e.onWarn?.(N),{kill:()=>{r.kill()}}}}}return n?{kill:()=>{if(g("CDP kill requested \u2014 tearing down"),p=!0,a!==null&&(clearTimeout(a),a=null),k(),n!==null){try{n.close()}catch{}n=null}r.kill()}}:{kill:()=>{r.kill()}}}import{useCallback as vp,useState as kp}from"react";function yr(e){let[t,r]=kp([]),o=vp(n=>{r(i=>[...i,`${new Date().toLocaleTimeString()}: ${n}`].slice(-e))},[e]);return[t,o]}import{useCallback as br,useEffect as Vn,useState as wr}from"react";import{Box as Y,Text as L,useInput as Cp}from"ink";import{jsx as A,jsxs as Q}from"react/jsx-runtime";var Fe=["apiKey","userId","businessId"],Sp={apiKey:"API Key",userId:"User ID",businessId:"Business ID"},Ct=({text:e})=>A(L,{dimColor:!0,children:e}),xr=({initialMode:e,showProfileManager:t,onComplete:r,onCancel:o})=>{let[n,i]=wr(e==="global"&&!t?{type:"loading"}:e==="global"&&t?{type:"profile-loading"}:{type:"mode-select",cursor:0}),[s,a]=wr(""),[l,p]=wr(null),[g,v]=wr(void 0),k=br(b=>{if(b==="local"){r({mode:"local",credentials:null});return}i({type:"profile-loading"})},[r]),f=br(async b=>{if(b===null){i({type:"profile-loading"});let m=await Ne();i({type:"name-entry",nameBuffer:"",existingProfiles:m});return}v(b.isDefault?void 0:b.name),i({type:"loading"});let u=b.isDefault?await re():await ke(b.name),d=u?Math.max(0,Z.indexOf(u.environment)):0;i({type:"creds-entry",field:0,values:u??{},envCursor:d})},[]),c=br(async(b,u)=>{let d=Z[u]??"go",m={...st(b),environment:d};i({type:"saving"});try{await Ko(g??De,m),r({mode:"global",credentials:m,...g!==void 0&&{profileName:g}})}catch(y){p(y instanceof Error?y.message:String(y)),i({type:"creds-entry",field:0,values:b,envCursor:u})}},[r,g]);Cp((b,u)=>{if(u.ctrl&&b==="c"&&process.exit(0),u.escape){if((n.type==="creds-entry"||n.type==="name-entry")&&e==="global"&&t){i({type:"profile-loading"}),h();return}o?.();return}if(n.type==="mode-select"){if(u.upArrow)i({type:"mode-select",cursor:0});else if(u.downArrow)i({type:"mode-select",cursor:1});else if(u.return){let d=n.cursor===0?"global":"local";k(d)}return}if(n.type==="profile-select"){let{profiles:d,cursor:m}=n,y=d.length,w=d.length+1;if(u.upArrow)i({...n,cursor:(m-1+w)%w});else if(u.downArrow)i({...n,cursor:(m+1)%w});else if(u.return)if(m===y)i({type:"name-entry",nameBuffer:"",existingProfiles:d});else{let E=d[m]??d[0];E&&f(E)}return}if(n.type==="name-entry"){let{nameBuffer:d,existingProfiles:m}=n;if(u.backspace||u.delete)i({type:"name-entry",nameBuffer:d.slice(0,-1),existingProfiles:m});else if(u.return){let y=d.trim();if(!y){i({...n,nameError:"Name cannot be empty"});return}if(y===De){i({...n,nameError:`"${De}" is reserved`});return}if(m.some(w=>w.name===y)){i({...n,nameError:`Profile "${y}" already exists`});return}v(y),i({type:"creds-entry",field:0,values:{},envCursor:0}),a("")}else b&&!u.ctrl&&!u.meta&&i({type:"name-entry",nameBuffer:d+b,existingProfiles:m});return}if(n.type==="creds-entry"){let{field:d,values:m,envCursor:y}=n;if(d===Fe.length){u.leftArrow?i({...n,envCursor:(y-1+Z.length)%Z.length}):u.rightArrow?i({...n,envCursor:(y+1)%Z.length}):u.upArrow?(i({...n,field:d-1}),a(m[Fe[d-1]]??"")):u.return&&c(m,y);return}let E=Fe[d];if(!E)return;if(u.backspace||u.delete)a(_=>_.slice(0,-1));else if(u.upArrow&&d>0){let _={...m,[E]:s},R=d-1;i({...n,field:R,values:_}),a(_[Fe[R]]??"")}else if(u.return||u.tab||u.downArrow){let _={...m,[E]:s},R=d+1;i({...n,field:R,values:_}),R<Fe.length?a(_[Fe[R]]??""):a("")}else b&&!u.ctrl&&!u.meta&&a(_=>_+b)}});let h=br(async()=>{let b=await Ne();i({type:"profile-select",profiles:b,cursor:0})},[]);if(Vn(()=>{n.type==="profile-loading"&&h()},[n.type,h]),Vn(()=>{e==="global"&&!t&&(async()=>{let b=await re(),u=b?Math.max(0,Z.indexOf(b.environment)):0;i({type:"creds-entry",field:0,values:b??{},envCursor:u})})()},[]),Vn(()=>{n.type==="creds-entry"&&n.field===0&&a(n.values.apiKey??"")},[n.type]),n.type==="loading"||n.type==="saving"||n.type==="profile-loading"){let b=n.type==="saving"?"Saving credentials\u2026":n.type==="profile-loading"?"Loading profiles\u2026":"Loading credentials\u2026";return A(Y,{paddingY:1,paddingX:2,children:A(L,{dimColor:!0,children:b})})}if(n.type==="done")return null;if(n.type==="mode-select")return Q(Y,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[A(K,{}),Q(Y,{flexDirection:"column",gap:0,children:[A(L,{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((u,d)=>{let m=n.cursor===d;return Q(Y,{gap:2,children:[A(L,{...m&&{color:"cyan"},children:m?"\u276F":" "}),A(L,{bold:m,...m&&{color:"cyan"},children:u.label}),A(L,{dimColor:!0,children:u.desc})]},u.mode)})]}),A(Ct,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]});if(n.type==="profile-select"){let{profiles:b,cursor:u}=n,d=b.length;return Q(Y,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[A(K,{}),Q(Y,{flexDirection:"column",gap:0,children:[A(L,{bold:!0,children:"Credential profiles"}),b.map((m,y)=>{let w=u===y;return Q(Y,{gap:2,children:[A(L,{...w&&{color:"cyan"},children:w?"\u276F":" "}),A(L,{bold:w,...w&&{color:"cyan"},children:m.isDefault?"Default":m.name}),A(L,{dimColor:!0,children:m.path})]},m.name)}),Q(Y,{gap:2,children:[A(L,{...u===d&&{color:"cyan"},children:u===d?"\u276F":" "}),A(L,{bold:u===d,...u===d&&{color:"cyan"},children:"+ Add new profile"})]})]}),A(Ct,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(n.type==="name-entry"){let{nameBuffer:b,nameError:u}=n;return Q(Y,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[A(K,{}),A(Y,{flexDirection:"column",gap:0,children:A(L,{bold:!0,children:"New credential profile"})}),u&&Q(L,{color:"red",children:["Error: ",u]}),Q(Y,{gap:2,children:[A(Y,{width:12,children:A(L,{bold:!0,color:"cyan",children:"Profile name"})}),A(L,{color:"cyan",children:">"}),A(L,{children:b}),A(L,{color:"cyan",children:"\u2588"})]}),A(Ct,{text:"Type a name \xB7 Enter to confirm \xB7 Esc to go back"})]})}let{field:x,values:I,envCursor:C}=n,S=x===Fe.length,N=g??De;return Q(Y,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[A(K,{}),Q(Y,{flexDirection:"column",gap:0,children:[A(L,{bold:!0,children:g!==void 0?`Profile: ${g}`:"Global credentials"}),Q(L,{dimColor:!0,children:["Saved to:"," ",g!==void 0?`~/.kizenappbuilder/${g}.json`:ve]})]}),l&&Q(L,{color:"red",children:["Error: ",l]}),Q(Y,{flexDirection:"column",gap:0,children:[Fe.map((b,u)=>{let d=x===u,m=d?s:I[b]??"";return Q(Y,{gap:2,children:[A(Y,{width:12,children:A(L,{bold:d,...d&&{color:"cyan"},children:Sp[b]})}),A(L,{...d&&{color:"cyan"},children:">"}),A(L,{children:m}),d&&A(L,{color:"cyan",children:"\u2588"})]},b)}),Q(Y,{gap:2,children:[A(Y,{width:12,children:A(L,{bold:S,...S&&{color:"cyan"},children:"Environment"})}),A(L,{...S&&{color:"cyan"},children:">"}),A(Y,{gap:1,children:Z.map((b,u)=>{let d=u===C;return S?A(L,{bold:d,...d&&{color:"cyan"},children:d?`[${b}]`:b},b):A(L,{dimColor:!d,bold:d,children:b},b)})})]})]}),S?A(Ct,{text:"\u2190\u2192 to select \xB7 \u2191\u2193 to move \xB7 Enter to save \xB7 Esc to cancel"}):A(Ct,{text:"\u2191\u2193 to move \xB7 Backspace to delete \xB7 Esc to cancel"}),Q(L,{dimColor:!0,children:["Profile: ",N]})]})};import{jsx as j,jsxs as G}from"react/jsx-runtime";var Ap=[".kizenapp",".git"],Ws=({port:e,pluginDir:t,outputDir:r,credentials:o,credentialMode:n,activeCredentialProfile:i,lastPath:s,debug:a=!1,verbose:l=!1,autoViewer:p=!0,cacheEnabled:g=!0})=>{let v=Se(o),k=Se(i),f=Se(s),[c,h]=ae("main"),[x,I]=ae(n),[C,S]=ae("starting"),[N,b]=ae(null),[u,d]=yr(50),[m,y]=yr(50),[w,E]=yr(50),[_,R]=ae([]),[M,X]=ae("pending"),[ie,pe]=ae(null),[fe,ce]=ae(null),[le,nt]=ae(null),[Oe,Er]=ae(null),[Tr,Ir]=ae(0),[qn,Aa]=ae(0),[Na,Ba]=ae(0),[Dr,Ra]=ae(0),Ar=Se(!1),Gn=Se(!1),_t=Se(null),ot=Se(null),_e=Se(new Set),Pt=Se([]),de=rt(P=>{let U=JSON.stringify(P);if(_e.current.size===0){Pt.current=[...Pt.current,U].slice(-50);return}let Pe=!1;for(let me of _e.current)if(me.readyState===1)try{me.send(U)}catch{_e.current.delete(me),Pe=!0}Pe&&Ir(_e.current.size)},[]),Et=d,Nr=rt(()=>{_t.current?.kill(),_t.current=null,Hs({port:e,userDataDir:Vs(r,".chrome"),broadcast:de,onWarn:P=>{d(`\u26A0 ${P}`)},...f.current!==void 0&&{path:f.current},...a&&{debugLog:E},...l&&{verbose:!0}}).then(P=>{_t.current=P})},[e,r,de,a,l,E,d]);vr(()=>{let P=()=>{_t.current?.kill()};return process.on("exit",P),()=>{process.off("exit",P)}},[]),Pp((P,U)=>{(P==="q"||U.ctrl&&P==="c")&&process.exit(0),P==="c"&&h("editing"),P==="v"&&Nr()},{isActive:c==="main"}),vr(()=>{C!=="running"||Gn.current||!p||(Gn.current=!0,Nr())},[C,p,Nr]);let $a=rt(P=>{v.current=P.credentials,k.current=P.profileName,h("main"),I(P.mode);let U=P.profileName;Ie(r,{credentialMode:P.mode,...U!==void 0&&{activeCredentialProfile:U}}),de({type:"credentials-updated",credentials:P.credentials})},[r,de]),Yn=rt(P=>{R(U=>[...U,`${new Date().toLocaleTimeString()}: ${Mn(P)}`].slice(-50)),P.kind==="request"&&(P.fromCache?Ba(U=>U+1):Ra(U=>U+1)),de({type:"proxy-log",entry:P})},[de]),Le=rt(P=>{y(P),de({type:"log",message:P})},[y,de]),Br=rt(()=>{Ar.current||(Ar.current=!0,X("building"),pe(null),ce(null),Le("Build started"),Lt(t,r).then(({bundleSize:P})=>{Le(`Build finished \u2014 bundle: ${pt(P)}`),X("done"),nt(new Date),Er(P),Le("Notifying viewers to reload"),de({type:"rebuild"})}).catch(P=>{P instanceof Ep?(ce(P.issues),pe(null)):(pe(P instanceof Error?P.message:String(P)),ce(null)),X("error")}).finally(()=>{Ar.current=!1}))},[t,r,Le,de]);if(vr(()=>{Br();let P=Tp(t,{recursive:!0},(U,Pe)=>{if(!Pe)return;let me=Pe.replace(/\\/g,"/");Ap.some(Tt=>me.startsWith(Tt))||(Le(`File change detected: ${Pe}`),ot.current!==null&&clearTimeout(ot.current),ot.current=setTimeout(Br,150))});return P.on("error",U=>{Le(`File watcher error \u2014 rebuilds have stopped: ${U.message}`)}),()=>{P.close(),ot.current!==null&&clearTimeout(ot.current)}},[t,Br,Le]),vr(()=>{let P=Os();Hn(Vs(P,"index.html")).then(U=>{if(!U){b("Viewer not built. Run 'pnpm build:viewer' first."),S("error");return}let Pe=Ls(P,Et,Yn,v,k,r,de,Aa,f,t,g),me=Ip(Pe),Tt=new Dp({server:me});return Tt.on("connection",ze=>{for(let ja of Pt.current)ze.readyState===1&&ze.send(ja);Pt.current=[],Et("Viewer connected for live reload"),_e.current.add(ze),Ir(_e.current.size),ze.on("close",()=>{_e.current.delete(ze),Ir(_e.current.size)})}),me.listen(e,"127.0.0.1",()=>{S("running"),Et(`Server started on 127.0.0.1:${String(e)}`)}),me.on("error",ze=>{b(ze.message),S("error")}),()=>{Tt.close(),me.close()}})},[e,Et,Yn,de,r,t,g]),c==="editing")return j(xr,{...x!==void 0&&{initialMode:x},showProfileManager:x==="global",onComplete:$a,onCancel:()=>{h("main")}});let Rr=le!==null?Math.round((Date.now()-le.getTime())/1e3):null,Fa=Rr===null?"":Rr<5?" (just now)":` (${String(Rr)}s ago)`,Xn=fe?.filter(P=>P.severity==="error").length??0;return G(ee,{flexDirection:"column",paddingY:1,paddingX:2,children:[j(K,{marginBottom:1}),G(ee,{flexDirection:"column",children:[G(ee,{gap:2,marginBottom:0,children:[j(F,{bold:!0,dimColor:!0,children:"App Build"}),M==="pending"&&j(F,{dimColor:!0,children:"waiting\u2026"}),M==="building"&&G(ee,{gap:1,children:[j(ye,{}),j(F,{children:"Building plugin package\u2026"})]}),M==="done"&&G(ee,{gap:1,children:[j(F,{color:"green",children:"\u2713 Built"}),le!==null&&G(F,{dimColor:!0,children:["at ",le.toLocaleTimeString(),Fa]}),Oe!==null&&G(F,{dimColor:!0,children:["\xB7 bundle: ",pt(Oe)]})]}),M==="error"&&(fe!==null?G(F,{color:"red",children:["\u2717 ",Xn," validation ",Xn===1?"error":"errors"]}):G(F,{color:"red",children:["\u2717 ",ie??"unknown error"]}))]}),fe!==null&&j(ir,{issues:fe}),j(ee,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:m.slice(-8).map((P,U)=>j(F,{dimColor:!0,wrap:"truncate",children:P},U))})]}),G(ee,{marginTop:1,flexDirection:"column",children:[G(ee,{gap:2,children:[j(F,{bold:!0,dimColor:!0,children:"Web Server"}),C==="starting"&&j(F,{dimColor:!0,children:"starting\u2026"}),C==="running"&&G(ee,{gap:2,children:[j(F,{color:"green",children:"\u2713 Running"}),G(F,{dimColor:!0,children:["\u25CF ",Tr," viewer",Tr!==1?"s":""]})]}),C==="error"&&G(F,{color:"red",children:["\u2717 ",N??"Server error"]})]}),j(ee,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:u.slice(-8).map((P,U)=>j(F,{dimColor:!0,wrap:"truncate",children:P},U))})]}),G(ee,{marginTop:1,flexDirection:"column",children:[G(ee,{gap:2,children:[j(F,{bold:!0,dimColor:!0,children:"Network Proxy"}),j(F,{color:"green",children:"\u2713 Active"}),j(F,{dimColor:!0,children:g?`\u25CF ${String(qn)} key${qn!==1?"s":""} in the network cache \xB7 ${String(Na)} hit \xB7 ${String(Dr)} miss`:`\u25CF network cache disabled \xB7 ${String(Dr)} request${Dr!==1?"s":""}`})]}),j(ee,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:_.length===0?j(F,{dimColor:!0,children:" No requests yet."}):_.slice(-8).map((P,U)=>j(F,{dimColor:!0,wrap:"truncate",children:P},U))})]}),a&&G(ee,{marginTop:1,flexDirection:"column",children:[G(ee,{gap:2,children:[j(F,{bold:!0,dimColor:!0,children:"CDP Debug"}),G(F,{dimColor:!0,children:["\u25CF ",w.length," event(s)"]})]}),j(ee,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:w.length===0?j(F,{dimColor:!0,children:" No CDP events yet."}):w.slice(-8).map((P,U)=>j(F,{dimColor:!0,wrap:"truncate",children:P},U))})]}),G(ee,{marginTop:1,gap:1,children:[j(F,{dimColor:!0,children:"["}),j(F,{children:"q"}),j(F,{dimColor:!0,children:"] quit ["}),j(F,{children:"c"}),j(F,{dimColor:!0,children:"] credentials ["}),j(F,{children:"v"}),G(F,{dimColor:!0,children:["] ",Tr===0?"open viewer":"relaunch viewer"]})]})]})};async function Ks(e){return new Promise(t=>{let r=null,o=i=>{r?.(),t(i)},{unmount:n}=qs(Js(xr,{...e!==void 0&&{initialMode:e},onComplete:o}),{exitOnCtrlC:!1});r=n})}function Gs(e){e.command("dev").description("Start the plugin viewer dev server").option("-p, --port <port>","port to listen on","3121").option("-c, --credentials <path>","path to a credentials JSON file").option("-d, --debug","Enable CDP lifecycle logs in the TUI").option("-v, --verbose","Log every CDP event and handled error (implies --debug)").option("--no-viewer","Don't auto-launch the viewer on startup (press [v] to launch manually)").option("--no-cache","Disable the network proxy cache (always fetch upstream)").action(async t=>{let r=parseInt(t.port,10),o=process.cwd(),n=`${o}/.kizenapp`;ge(o);let i=null,s,a,{lastPath:l}=await he(n);if(t.credentials)i=await Ae(t.credentials);else{let c=await he(n);if(c.credentialMode==="local")s="local";else if(c.credentialMode==="global"){if(s="global",a=c.activeCredentialProfile,a?(i=await ke(a),i||(i=await re(),a=void 0)):i=await re(),!i){let h=await Ks("global");i=h.credentials,a=h.profileName}}else{let h=await Ks();i=h.credentials,s=h.mode,a=h.profileName;let x=h.profileName;await Ie(n,{credentialMode:h.mode,...x!==void 0&&{activeCredentialProfile:x}})}}let p=t.verbose===!0,g=p||t.debug===!0,v=t.viewer!==!1,k=t.cache!==!1,{waitUntilExit:f}=qs(Js(Ws,{port:r,pluginDir:o,outputDir:n,credentials:i,...s!==void 0&&{credentialMode:s},...a!==void 0&&{activeCredentialProfile:a},...l!==void 0&&{lastPath:l},debug:g,verbose:p,autoViewer:v,cacheEnabled:k}),{exitOnCtrlC:!1});await f()})}import{createElement as Vp}from"react";import{render as Wp}from"ink";import{useCallback as Cr,useEffect as Qs,useState as Sr}from"react";import{Box as be,Text as z,useApp as Op,useInput as Lp}from"ink";import{encrypt as Np,serializeEnvelope as Bp}from"@kizenapps/packager";function Rp(e){let t=e;return t.code==="ECONNREFUSED"||t.cause?.code==="ECONNREFUSED"}function Ys(e){return{"Content-Type":"application/json","x-api-key":e.apiKey,"x-user-id":e.userId,"x-business-id":e.businessId,"x-auth-environment":e.environment}}async function Xs(e,t,r){try{return await fetch(`${e}${t}`,r)}catch(o){throw new Error(Rp(o)?`Plugin-wizard is not running at ${e}`:`Failed to reach plugin-wizard: ${o.message}${Dt()==="unavailable"?` ${It}`:""}`)}}async function Zs(e){let t=await e.text();if(t==="")return{};try{let r=JSON.parse(t);return typeof r=="object"&&r!==null?r:{}}catch{return{}}}async function $p(e,t,r){let o=bt(e.stage),n=await Xs(o,"/get-public-key",{method:"POST",headers:Ys(t),body:JSON.stringify({api_name:r})}),i=await Zs(n);if(!n.ok||typeof i.public_key!="string"){let s=typeof i.error=="string"?i.error:`HTTP ${String(n.status)}`;throw new Error(`Failed to fetch public key: ${s}`)}return i.public_key}function Fp(e,t){let r=Np(t,e),o=Bp(r);if(typeof o.value!="string")throw new Error("Unexpected serialized envelope shape from @kizenapps/packager");return o.value}async function jp(e,t,r,o){let n=bt(e.stage),i=await Xs(n,"/encrypt",{method:"POST",headers:Ys(t),body:JSON.stringify({api_name:r,value:o})}),s=await Zs(i);if(!i.ok||s.encrypted!==!0||typeof s.value!="string"){let a=typeof s.error=="string"?s.error:`HTTP ${String(i.status)}`;throw new Error(`Encryption via plugin-wizard failed: ${a}`)}return s.value}async function kr(e,t,r,o,n){if(e.isRemote)return n?.("encrypting"),jp(e,t,r,o);n?.("fetching-key");let i=await $p(e,t,r);return n?.("encrypting"),Fp(i,o)}import{Fragment as _r,jsx as O,jsxs as te}from"react/jsx-runtime";var Wn=({text:e})=>O(z,{dimColor:!0,children:e}),ea=({ctx:e,stageDefaulted:t,credentialsPath:r,initialApiName:o,defaultApiName:n,initialValue:i,onDone:s})=>{let a=Op(),[l,p]=Sr({type:"loading"}),[g,v]=Sr(null),[k,f]=Sr(o??""),[c,h]=Sr(i??""),x=Cr(d=>{process.exitCode=1,p({type:"error",message:d instanceof Error?d.message:String(d)})},[]),I=Cr(async(d,m,y)=>{try{let w=await kr(e,d,m,y,R=>{p(R==="fetching-key"?{type:"fetching-key"}:{type:"encrypting"})}),E=JSON.stringify({encrypted:!0,value:w},null,2);s?.(w);let _=await At(E);p({type:"done",envelope:E,copied:_})}catch(w){x(w)}},[e,x,s]),C=Cr((d,m,y)=>{if(m.trim()===""){p({type:"api-name-entry",buffer:n??""});return}if(y===""){p({type:"value-entry",buffer:""});return}I(d,m.trim(),y)},[n,I]),S=Cr(async d=>{try{p({type:"loading"});let m=d.isDefault?await re():await ke(d.name);if(m===null)throw new Error(`Could not load credential profile: ${d.name}`);v(m),C(m,k,c)}catch(m){x(m)}},[k,c,C,x]);Qs(()=>{(async()=>{try{if(r!==void 0){let y;try{y=await Ae(r)}catch(w){throw new Error(`Could not load credentials from ${r}: ${w instanceof Error?w.message:String(w)}`)}v(y),C(y,k,c);return}let d=await Ne();if(d.length===0)throw new Error("No credential profiles found. Create ~/.kizenappbuilder/credentials.json first.");let[m]=d;if(d.length===1&&m!==void 0){let y=m.isDefault?await re():await ke(m.name);if(y===null)throw new Error(`Could not load credential profile: ${m.name}`);v(y),C(y,k,c);return}p({type:"profile-select",profiles:d,cursor:0})}catch(d){x(d)}})()},[]),Qs(()=>{(l.type==="done"||l.type==="error")&&a.exit()},[l,a]),Lp((d,m)=>{if(m.ctrl&&d==="c"){process.exitCode=130,a.exit();return}if(l.type==="profile-select"){let{profiles:y,cursor:w}=l;if(m.upArrow)p({...l,cursor:(w-1+y.length)%y.length});else if(m.downArrow)p({...l,cursor:(w+1)%y.length});else if(m.return){let E=y[w];E!==void 0&&S(E)}return}if(l.type==="api-name-entry"){let{buffer:y}=l;if(m.backspace||m.delete)p({type:"api-name-entry",buffer:y.slice(0,-1)});else if(m.return){let w=y.trim();if(w===""){p({type:"api-name-entry",buffer:y,error:"api_name cannot be empty"});return}f(w),g?C(g,w,c):x(new Error("Internal error: credentials were not loaded"))}else d&&!m.ctrl&&!m.meta&&p({type:"api-name-entry",buffer:y+d});return}if(l.type==="value-entry"){let{buffer:y}=l;if(m.backspace||m.delete)p({type:"value-entry",buffer:y.slice(0,-1)});else if(m.return){if(y===""){p({type:"value-entry",buffer:y,error:"secret cannot be empty"});return}h(y),g?C(g,k,y):x(new Error("Internal error: credentials were not loaded"))}else d&&!m.ctrl&&!m.meta&&p({type:"value-entry",buffer:y+d});return}});let N=e.isRemote?"remote Kizen API":"on-machine",b=t===!0?`${e.stage} (default)`:e.stage,u=d=>te(be,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[O(K,{}),te(z,{dimColor:!0,children:["Mode: ",N," Stage: ",b]}),d]});if(l.type==="loading")return u(te(be,{gap:1,children:[O(ye,{}),O(z,{dimColor:!0,children:"Loading credentials\u2026"})]}));if(l.type==="profile-select"){let{profiles:d,cursor:m}=l;return u(te(_r,{children:[O(z,{bold:!0,children:"Credential profile"}),O(be,{flexDirection:"column",children:d.map((y,w)=>{let E=m===w;return te(be,{gap:2,children:[O(z,{...E&&{color:"cyan"},children:E?"\u276F":" "}),O(z,{bold:E,...E&&{color:"cyan"},children:y.isDefault?"Default":y.name}),O(z,{dimColor:!0,children:y.path})]},y.name)})}),O(Wn,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]}))}return l.type==="api-name-entry"?u(te(_r,{children:[O(z,{bold:!0,children:"Plugin api_name"}),l.error!==void 0&&te(z,{color:"red",children:["Error: ",l.error]}),te(be,{gap:1,children:[O(z,{color:"cyan",children:">"}),O(z,{children:l.buffer}),O(z,{color:"cyan",children:"\u2588"})]}),O(Wn,{text:"Type the api_name \xB7 Enter to confirm \xB7 Ctrl+C to quit"})]})):l.type==="value-entry"?u(te(_r,{children:[O(z,{bold:!0,children:"Secret value"}),l.error!==void 0&&te(z,{color:"red",children:["Error: ",l.error]}),te(be,{gap:1,children:[O(z,{color:"cyan",children:">"}),O(z,{children:"\u2022".repeat(l.buffer.length)}),O(z,{color:"cyan",children:"\u2588"})]}),O(Wn,{text:"Input hidden \xB7 Enter to encrypt \xB7 Ctrl+C to quit"})]})):l.type==="fetching-key"?u(te(be,{gap:1,children:[O(ye,{}),te(z,{children:["Fetching ",e.stage," public key for ",O(z,{bold:!0,children:k}),"\u2026"]})]})):l.type==="encrypting"?u(te(be,{gap:1,children:[O(ye,{}),O(z,{children:"Encrypting\u2026"})]})):l.type==="error"?u(te(be,{gap:1,children:[O(z,{color:"red",children:"\u2717"}),O(z,{color:"red",children:l.message})]})):u(te(_r,{children:[te(be,{gap:1,children:[O(z,{color:"green",children:"\u2713"}),O(z,{bold:!0,children:"Encrypted secret ready"})]}),l.copied?O(z,{color:"green",children:"\u2713 Copied to clipboard \u2014 paste it into the secret value in your kizen.json."}):O(z,{dimColor:!0,children:"Paste this into the secret value in your kizen.json (re-run with --out <path> to save it to a file; selecting it here may capture line wraps):"}),O(z,{children:l.envelope})]}))};import{readFile as zp,writeFile as Mp}from"fs/promises";import{join as Up}from"path";function ta(e){return{encrypted:!0,value:e}}function ra(e){return JSON.stringify(ta(e))}async function Kn(e,t){await Mp(e,`${JSON.stringify(ta(t),null,2)}
|
|
1069
|
+
`,"utf-8")}var Hp="prod";function na(e){return e==="dev"||e==="prod"}function oa(e){return`Error: --stage must be "dev" or "prod" (got: "${e}")`}function ia(e){return{stage:e==="dev"||e==="prod"?e:Hp,wasDefaulted:e===void 0}}function sa(e){return`No --stage given; defaulting to ${e} encryption keys (pass --stage dev to override)
|
|
1070
|
+
`}async function aa(e=process.cwd()){try{let t=await zp(Up(e,"kizen.json"),"utf-8"),r=JSON.parse(t),o=Array.isArray(r)?r[0]:r,n=typeof o.api_name=="string"&&o.api_name!==""?o.api_name:void 0;return{...n!==void 0&&{apiName:n}}}catch{}return{}}function la(e){return e.replace(/[\r\n]+$/,"")}async function ca(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}async function da(e,t,r,o,n){let i=t.credentials!==void 0?await n.loadCredentialsFromFile(t.credentials):await n.loadGlobalCredentials();if(i===null)throw new Error("No credentials found. Pass --credentials or create ~/.kizenappbuilder/credentials.json.");let s=t.apiName??r.apiName;if(s===void 0||s.trim()==="")throw new Error("api_name is required in non-interactive mode. Pass --api-name or run inside a plugin directory.");o&&n.writeStderr(sa(e.stage));let a=t.value;if(a===void 0){if(n.stdinIsTTY())throw new Error('No secret provided and stdin is a terminal. Pass --value, or pipe the secret in (e.g. `printf %s "$SECRET" | npx --yes @kizenapps/cli encrypt \u2026`).');n.writeStderr(`Reading secret from stdin (pass --value to skip)\u2026
|
|
1071
|
+
`),a=la(await n.readStdin())}if(a==="")throw new Error("A secret value is required. Pass --value or pipe it via stdin.");let l=await n.encryptSecret(e,i,s.trim(),a);if(n.writeStdout(`${ra(l)}
|
|
1072
|
+
`),t.out!==void 0)try{await n.writeEnvelopeFile(t.out,l),n.writeStderr(`Wrote encrypted envelope to ${t.out}
|
|
1073
|
+
`)}catch(p){n.writeStderr(`Error writing ${t.out}: ${p instanceof Error?p.message:String(p)}
|
|
1074
|
+
`),n.setExitCode(1)}}function ua(e){e.command("encrypt").description("Encrypt a secret for a plugin against its encryption keys").option("--remote","encrypt via the plugin-wizard's remote API instead of on-machine").option("-c, --credentials <path>","path to a credentials JSON file").option("-a, --api-name <name>","plugin api_name the secret belongs to").option("-v, --value <value>","plaintext secret value to encrypt").option("-s, --stage <stage>","which encryption API to use: dev or prod (default: prod)").option("-o, --out <path>","also write the encrypted envelope to a file").action(async t=>{t.stage!==void 0&&!na(t.stage)&&(console.error(oa(t.stage)),process.exit(1));let o=t.apiName===void 0?await aa():{},{stage:n,wasDefaulted:i}=ia(t.stage),s={isRemote:t.remote===!0,stage:n};if(!process.stdin.isTTY||!process.stdout.isTTY){try{await da(s,t,o,i,{loadCredentialsFromFile:Ae,loadGlobalCredentials:re,encryptSecret:kr,readStdin:ca,stdinIsTTY:()=>process.stdin.isTTY,writeStdout:p=>{process.stdout.write(p)},writeStderr:p=>{process.stderr.write(p)},writeEnvelopeFile:Kn,setExitCode:p=>{process.exitCode=p}})}catch(p){console.error(`Error: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}return}let a,{waitUntilExit:l}=Wp(Vp(ea,{ctx:s,stageDefaulted:i,onDone:p=>{a=p},...t.credentials!==void 0&&{credentialsPath:t.credentials},...t.apiName!==void 0&&{initialApiName:t.apiName},...o.apiName!==void 0&&{defaultApiName:o.apiName},...t.value!==void 0&&{initialValue:t.value}}),{exitOnCtrlC:!1});if(await l(),a!==void 0&&t.out!==void 0)try{await Kn(t.out,a),process.stderr.write(`Wrote encrypted envelope to ${t.out}
|
|
1075
|
+
`)}catch(p){console.error(`Error writing ${t.out}: ${p instanceof Error?p.message:String(p)}`),process.exitCode=1}})}var Kp=new Set(["phone","envelope","pen-nib","calendar-days","paperclip","file","clipboard","pen","tag","book","print","pen-to-square","folder","folder-open","thumbtack","globe","city","briefcase","compass","address-book","business-time","computer-classic","pen-fancy","badge-check","mug-saucer","landmark","chart-simple","envelopes","diagram-venn","calendar","pencil","phone-volume","copy","table","building","network-wired","address-card","tags","registered","signature","phone-office","projector","sitemap","marker","badge","wallet","copyright","bullseye","calculator","certificate","percent","eraser","file-spreadsheet","glasses","industry","vault","user-tie-hair-long","user-tie-hair","user-hair-mullet","trademark","timeline-arrow","timeline","table-tree","table-rows","table-pivot","table-layout","table-columns","stapler","square-poll-vertical","square-poll-horizontal","square-phone-flip","square-phone","square-pen","square-kanban","square-envelope","socks","slot-machine","signature-slash","signature-lock","shredder","scissors","scanner-image","scale-unbalanced-flip","scale-unbalanced","scale-balanced","router","rectangle-pro","print-slash","print-magnifying-glass","presentation-screen","podium","phone-slash","phone-intercom","phone-flip","person-chalkboard","pen-nib-slash","pen-clip","paste","paperclip-vertical","notebook","note-sticky","money-check-pen","money-check-dollar-pen","magnifying-glass-chart","magnifying-glass-arrow-right","list-tree","list-timeline","list-radio","list-dropdown","list-check","laptop-file","lamp-desk","keynote","industry-windows","inboxes","inbox-full","house-laptop","highlighter","folders","folder-xmark","folder-tree","folder-plus","folder-minus","folder-arrow-up","folder-arrow-down","floppy-disk-circle-xmark","floppy-disk-circle-arrow-right","floppy-disk","file-user","file-lines","file-circle-plus","file-circle-info","file-chart-pie","file-chart-column","fax","envelope-open","envelope-dot","envelope-circle-check","coffee-pot","cloud-word","clipboard-question","chart-user","chart-tree-map","chart-simple-horizontal","chart-pyramid","chart-pie-simple","chart-pie","chart-line-up","chart-line-down","chart-line","cake-candles","cabinet-filing","bullhorn","briefcase-blank","briefcase-arrow-right","brain-arrow-curved-right","boxes-packing","box-archive","book-section","bars-staggered","bars-progress","badge-percent","badge-dollar","arrows-to-eye","arrows-to-dot","arrows-spin","sparkles","megaphone","block-question","lightbulb-slash","comments-dollar","comments","bullseye-pointer","lightbulb","user-group-crown","user-crown","signal-stream-slash","signal-stream","rectangle-ad","ranking-star","person-rays","people-group","messages-dollar","message-dollar","magnifying-glass-location","magnifying-glass-dollar","lightbulb-on","lightbulb-exclamation","lightbulb-dollar","lightbulb-cfl-on","lightbulb-cfl","hundred-points","group-arrows-rotate","gift-card","filter-circle-dollar","envelopes-bulk","envelope-open-text","envelope-open-dollar","comment-dollar","chart-mixed","bullseye-arrow","star","heart","camera-retro","truck-fast","bell","cart-shopping","gift","barcode","bookmark","camera","thumbs-up","thumbs-down","key","truck","balloons","handshake","shop","shirt","bag-shopping","moped","cart-plus","credit-card","store","cash-register","booth-curtain","trophy","receipt","truck-container","truck-clock","truck-bolt","trophy-star","store-slash","store-lock","star-exclamation","shop-slash","shop-lock","rectangle-barcode","person-booth","nfc-trash","nfc-symbol","nfc-slash","nfc-signal","nfc-pen","nfc-magnifying-glass","nfc-lock","nfc","money-check-dollar","money-check","mobile-signal-out","mobile-signal","hexagon-vertical-nft-slanted","hexagon-vertical-nft","hexagon-image","hand-holding-box","gifts","gem","credit-card-front","credit-card-blank","cart-xmark","cart-shopping-fast","cart-minus","cart-circle-xmark","cart-circle-plus","cart-circle-exclamation","cart-circle-check","cart-circle-arrow-up","cart-circle-arrow-down","cart-arrow-up","cart-arrow-down","box-open-full","basket-shopping-simple","basket-shopping","barcode-scan","barcode-read","balloon","bags-shopping","bars","browser","chart-bar","cog","database","calendar-alt","play","kizen-k","add","book-alt","form-entity","arrows-to-circle","question-circle","chevron-down","chevron-up","window-restore","forward"]),Jp=[...Kp].sort(),qp=new Set(["kizen-k","form-entity"]),pa=[...Jp,...[...qp].sort()];function fa(e){e.command("icons").description("List all valid icon names accepted by toolbar items, pages, and adornments").action(()=>{for(let t of pa)console.log(t)})}import{mkdir as rf,writeFile as Sa,readFile as nf}from"fs/promises";import{join as Pr}from"path";var Gp=new Set(["developer_business_id"]);function Yp(e){return Array.isArray(e)?e.map(t=>{if(typeof t!="object"||t===null)return t;let r=t;if(typeof r.auth_credentials!="object"||r.auth_credentials===null)return r;let o=Object.fromEntries(Object.keys(r.auth_credentials).map(n=>[n,"*****"]));return{...r,auth_credentials:o}}):e}function ha(e){let t={name:"",children:new Map,isFile:!1,filePath:""};for(let r of e){let o=r.path.split("/"),n=t;o.forEach((i,s)=>{n.children.has(i)||n.children.set(i,{name:i,children:new Map,isFile:s===o.length-1,filePath:o.slice(0,s+1).join("/")});let a=n.children.get(i);a&&(n=a)})}return t}function ga(e){return[...e.children.values()].sort((t,r)=>t.isFile!==r.isFile?t.isFile?1:-1:t.name.localeCompare(r.name))}function Jn(e){return"file-"+e.replace(/[^a-zA-Z0-9]/g,"-")}function we(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function ya(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t).toLowerCase():""}var Xp={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".json":"json",".css":"css",".scss":"scss",".html":"html",".htm":"html",".md":"markdown",".mdx":"markdown",".py":"python",".sh":"bash",".yml":"yaml",".yaml":"yaml",".xml":"xml",".toml":"toml"};function Zp(e){return Xp[ya(e)]??""}function ma(e){let t=[...e.matchAll(/`+/g)].reduce((r,o)=>Math.max(r,o[0].length),0);return"`".repeat(Math.max(3,t+1))}function ba(e,t=""){let r=ga(e);return r.map((o,n)=>{let i=n===r.length-1,s=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",a=i?" ":"\u2502 ";return o.isFile?`${t}${s}${o.name}`:`${t}${s}${o.name}/
|
|
1076
|
+
${ba(o,t+a)}`}).join(`
|
|
1077
|
+
`)}var Qp=/(^|\/)licen[cs]e(\.md|\.txt)?$/i;function wa(e){return e.filter(t=>t.path!=="kizen.json"&&t.path!=="plugin-report.html"&&!Qp.test(t.path))}function xa(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!Gp.has(t)).map(([t,r])=>[t,t==="services"?Yp(r):r]))}var ef={".png":"image/png",".svg":"image/svg+xml",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function va(e){return`<ul>${ga(e).map(o=>o.isFile?`<li class="tf"><a href="#${Jn(o.filePath)}" data-id="${Jn(o.filePath)}">${we(o.name)}</a></li>`:`<li class="td"><span class="dn">${we(o.name)}/</span>${va(o)}</li>`).join("")}</ul>`}function tf(e){let t;return e.base64Image!==void 0?t=`<img src="data:${ef[ya(e.path)]??"image/png"};base64,${e.base64Image}" alt="${we(e.path)}" style="max-width:100%">`:e.binaryData!==void 0?t=`<p class="bin">[Binary file: ${String(e.binaryData.length)} bytes]</p>`:t=`<pre><code>${we(e.content)}</code></pre>`,`<section id="${Jn(e.path)}"><h2 class="fp">${we(e.path)}</h2><div class="fb">${t}</div></section>`}function ka(e,t){let r=xa(e),o=typeof e.name=="string"?e.name:"Plugin",n=typeof e.version=="string"?e.version:"",i=typeof e.description=="string"?e.description:"",s=wa(t),a=[];a.push(`# ${o}${n?` v${n}`:""}`),i&&a.push("",i);let l=JSON.stringify(r,null,2),p=ma(l);a.push("","## Configuration (`kizen.json`)","",`${p}json`,l,p),a.push("","## File Tree","","```",ba(ha(s)),"```"),a.push("","## Files");for(let g of s)if(a.push("",`### \`${g.path}\``,""),g.base64Image!==void 0)a.push(`[Image file: ${g.path}]`);else if(g.binaryData!==void 0)a.push(`[Binary file: ${String(g.binaryData.length)} bytes]`);else{let v=ma(g.content);a.push(`${v}${Zp(g.path)}`,g.content,v)}return a.join(`
|
|
467
1078
|
`)+`
|
|
468
|
-
`}function
|
|
1079
|
+
`}function Ca(e,t){let r=xa(e),o=typeof e.name=="string"?e.name:"Plugin",n=typeof e.version=="string"?e.version:"",i=typeof e.description=="string"?e.description:"",s=wa(t),a=va(ha(s)),l=s.map(tf).join(`
|
|
469
1080
|
`);return`<!DOCTYPE html>
|
|
470
1081
|
<html lang="en">
|
|
471
1082
|
<head>
|
|
472
1083
|
<meta charset="UTF-8">
|
|
473
1084
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
474
|
-
<title>${
|
|
1085
|
+
<title>${we(o)} \u2014 Plugin Report</title>
|
|
475
1086
|
<style>
|
|
476
1087
|
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
|
|
477
1088
|
:root{
|
|
@@ -508,17 +1119,17 @@ img{border:1px solid var(--bd);border-radius:4px}
|
|
|
508
1119
|
</head>
|
|
509
1120
|
<body>
|
|
510
1121
|
<header>
|
|
511
|
-
<h1>${
|
|
512
|
-
${i?`<p>${
|
|
1122
|
+
<h1>${we(o)}${n?` <span style="color:var(--mu);font-size:.8em">v${we(n)}</span>`:""}</h1>
|
|
1123
|
+
${i?`<p>${we(i)}</p>`:""}
|
|
513
1124
|
</header>
|
|
514
1125
|
<div class="layout">
|
|
515
1126
|
<nav>
|
|
516
1127
|
<a href="#config" class="cfg" data-id="config">kizen.json (config)</a>
|
|
517
|
-
${
|
|
1128
|
+
${a}
|
|
518
1129
|
</nav>
|
|
519
1130
|
<main>
|
|
520
|
-
<section id="config"><h2 class="fp">kizen.json \u2014 Plugin Configuration</h2><div class="fb"><pre><code>${
|
|
521
|
-
${
|
|
1131
|
+
<section id="config"><h2 class="fp">kizen.json \u2014 Plugin Configuration</h2><div class="fb"><pre><code>${we(JSON.stringify(r,null,2))}</code></pre></div></section>
|
|
1132
|
+
${l}
|
|
522
1133
|
</main>
|
|
523
1134
|
</div>
|
|
524
1135
|
<script>
|
|
@@ -531,9 +1142,9 @@ ${g}
|
|
|
531
1142
|
})();
|
|
532
1143
|
</script>
|
|
533
1144
|
</body>
|
|
534
|
-
</html>`}var
|
|
1145
|
+
</html>`}var _a=Pr(Ue,"examples");function Pa(e){e.command("report").description("Generate a self-contained HTML report of the plugin").option("-o, --output <path>",`output file path (default: ${_a}/<api_name>.html)`).action(async t=>{let r=process.cwd(),o;try{let l=await nf(Pr(r,"kizen.json"),"utf-8"),p=JSON.parse(l);o=Array.isArray(p)?p[0]:p}catch{console.error("Error: kizen.json not found. Run this command from a plugin directory."),process.exit(1)}let n=typeof o.api_name=="string"?o.api_name:"plugin",i=t.output??Pr(_a,`${n}.html`),s=i.replace(/\.html$/,".md"),a=await Ot(r,{detectBinaryByContent:!0});await rf(Pr(i,".."),{recursive:!0}),await Promise.all([Sa(i,Ca(o,a),"utf-8"),Sa(s,ka(o,a),"utf-8")]),console.log(`Plugin report written to:
|
|
535
1146
|
${i}
|
|
536
|
-
${
|
|
1147
|
+
${s}`)})}function Ea(e){e.command("setup-claude").description("Install or refresh the Claude Code skill for building custom blocks").option("--dry-run","report what would change without writing files").option("--include-lib","also install the Kizen data helper library (<entry>/lib/kizenData.js)").action(async t=>{await ui(process.cwd(),t)})}async function Ta(e,t={}){if(await Re(e)!=="has-manifest")throw new Error(`No kizen.json found in ${e}`);let r=t.dryRun===!0,o=await Kt(e,Ht(),{dryRun:r});return r||ge(e),{files:o}}function Ia(e){e.command("setup-copilot").description("Add or refresh the Copilot code-review setup in an existing plugin repo").option("--dry-run","report what would change without writing anything").action(async t=>{let r=process.cwd();if(await Re(r)!=="has-manifest"){console.error(`No kizen.json found in ${r} \u2014 run "appbuilder setup-copilot" from the root of a plugin repo.`),process.exitCode=1;return}let o=t.dryRun===!0;try{let n=await Ta(r,{dryRun:o});for(let i of n.files)console.log(Jt(i));if(o){console.log(`
|
|
537
1148
|
Dry run \u2014 no files and no .gitignore entries were written.`);return}console.log(`
|
|
538
|
-
Ensured .gitignore ignores .kizenapp/ and .copilot-docs/.`),console.log("The code review workflow only takes effect once it is on the repository default branch \u2014 merge it before expecting reviews to cite .copilot-docs/.")}catch(
|
|
1149
|
+
Ensured .gitignore ignores .kizenapp/ and .copilot-docs/.`),console.log("The code review workflow only takes effect once it is on the repository default branch \u2014 merge it before expecting reviews to cite .copilot-docs/.")}catch(n){console.error(`Error: ${n instanceof Error?n.message:String(n)}`),process.exitCode=1}})}function df(){let e=af(sf(lf(import.meta.url)),"..","package.json");return JSON.parse(of(e,"utf-8")).version}function Da(){let e=new cf;return e.name("appbuilder").description("Kizen plugin app builder").version(df()),ms(e),Ea(e),Ia(e),Oi(e),Gs(e),ua(e),Pa(e),fa(e),Bi(e),e}Zn({env:process.env,http:uf});Da().parse();
|
|
539
1150
|
//# sourceMappingURL=index.js.map
|