@kizenapps/cli 1.16.0 → 1.17.0-acc599a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import*as Kh from"http";var Xt="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.",ll=["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy"],dl=e=>e!==void 0&&e!=="",Re="not-configured";function jo({env:e,http:t}){return Re==="applied"||(ll.some(n=>dl(e[n]))?e.NODE_USE_ENV_PROXY==="1"?Re="already-set":typeof t.setGlobalProxyFromEnv!="function"?Re="unavailable":(t.setGlobalProxyFromEnv(e),Re="applied"):Re="not-configured"),Re}var Zt=()=>Re;import{readFileSync as Lh}from"fs";import{dirname as Mh,join as zh}from"path";import{fileURLToPath as Uh}from"url";import{Command as Hh}from"commander";var dr={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"},ut=e=>new URL(dr[e]).origin,Lo={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"},ul=["go","fmo"];function ur(e){return ul.includes(e)}import{mkdir as Mo,readFile as pl,readdir as fl,writeFile as zo}from"fs/promises";import{homedir as ml}from"os";import{dirname as hl,join as Qt}from"path";var W=["go","fmo","staging","integration","test1"];function kt(e){return typeof e=="string"?e.trim():""}function Ct(e){return{apiKey:kt(e.apiKey),userId:kt(e.userId),businessId:kt(e.businessId)}}var Se=Qt(ml(),".kizenappbuilder"),Oe=Qt(Se,"credentials.json"),Be="credentials",St=e=>W.includes(e),gl=e=>`Unknown --env "${e}". Use one of: ${W.join(", ")}.`,et=e=>St(e)?{environment:e}:{message:gl(e)};function yl(e){return typeof e=="string"?e.trim():e}function bl(e){return St(e)?"explicit":e==null||e===""?"missing":"invalid"}function wl(e){if(typeof e!="object"||e===null)throw new Error("Credentials must be a JSON object");let t=e,n=yl(t.environment);return{credentials:{...Ct(t),environment:St(n)?n:"go"},environmentSource:bl(n)}}async function en(e){let t=await pl(e,"utf-8");return wl(JSON.parse(t))}async function Fe(e){return(await en(e)).credentials}async function oe(){try{return await Fe(Oe)}catch{return null}}async function vl(e){await Mo(hl(Oe),{recursive:!0,mode:448}),await zo(Oe,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function Uo(e){return Qt(Se,`${e}.json`)}async function je(){let e=[{name:Be,path:Oe,isDefault:!0}];try{let t=await fl(Se);for(let n of t){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);r!==Be&&e.push({name:r,path:Qt(Se,n),isDefault:!1})}}catch{}return e}async function Ho(e,t){if(e===Be){await vl(t);return}await Mo(Se,{recursive:!0,mode:448}),await zo(Uo(e),JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}async function Pe(e){try{return await Fe(Uo(e))}catch{return null}}async function Vo(){let e=await je(),t=await Promise.all(e.map(n=>en(n.path).then(()=>!0,()=>!1)));return e.filter((n,r)=>t[r]===!0)}import{posix as xl}from"path";var O=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tn=(e,t)=>e?.code===t,nn=e=>e instanceof Error&&tn(e,"ENOENT"),tt=async e=>{try{return await e}catch(t){if(tn(t,"ENOENT"))return;throw t}},ie=e=>typeof e=="string"&&e!==""?e:void 0,Le=e=>e instanceof Error?e.message:String(e),Pt=e=>{let t=e;return t.cause?.code??t.code??t.cause?.message??t.message??String(e)},rn=e=>{let t=xl.normalize(e.trim().replaceAll("\\","/")).replace(/\/+$/,"");return t==="."?"":t};import{spawn as _l}from"child_process";import{createHash as Tl,randomBytes as Al}from"crypto";import{createServer as Il}from"http";import{platform as Wo}from"process";var kl=["M22.8852 7.03547C22.8112 7.5787 22.5356 8.0447 22.1428 8.36712C21.336 7.31995 20.1615 6.55456 18.7791 6.28228C18.6674 6.2606 18.5549 6.24164 18.4404 6.22606C17.0417 6.03708 15.6939 6.37914 14.6 7.09712C14.4293 7.20955 14.2646 7.33079 14.1068 7.46084C13.9084 7.62408 13.655 7.70942 13.3997 7.68233C13.3841 7.68098 13.3686 7.67894 13.353 7.67624C12.698 7.58073 12.2245 6.98196 12.2842 6.32291C12.2855 6.3087 12.2869 6.29447 12.2889 6.28092C12.3181 6.04522 12.442 5.83117 12.6249 5.67946C12.8246 5.51418 13.0326 5.35907 13.2473 5.21412C14.8059 4.16358 16.7417 3.65828 18.7513 3.92989C19.665 4.05317 20.5212 4.32749 21.2981 4.72441C21.5392 4.84701 21.7722 4.9818 21.9978 5.12743C22.6183 5.52908 22.9712 6.24503 22.8919 6.97926C22.8899 6.99822 22.8878 7.01719 22.8852 7.03547Z","M23.2333 16.1537C22.797 16.4857 22.2721 16.6198 21.7662 16.571C21.9369 15.2604 21.6476 13.8887 20.8626 12.7197C20.7996 12.6255 20.7325 12.532 20.6628 12.4406C19.8073 11.3183 18.6125 10.6077 17.331 10.3429C17.1304 10.3016 16.9286 10.2711 16.7254 10.2515C16.4694 10.2271 16.2297 10.1078 16.0684 9.90806C16.0582 9.89587 16.0488 9.88368 16.0393 9.87082C15.6437 9.34044 15.7325 8.58183 16.2411 8.15849C16.2519 8.14969 16.2628 8.1402 16.2743 8.13208C16.462 7.98645 16.701 7.9221 16.9375 7.94446C17.1955 7.96884 17.4522 8.00609 17.7069 8.05554C19.5526 8.41385 21.2785 9.42512 22.5072 11.0372C23.0659 11.7701 23.4771 12.5693 23.746 13.399C23.8293 13.6564 23.8991 13.9165 23.9553 14.1786C24.1097 14.9006 23.853 15.6566 23.2773 16.1199C23.2624 16.1314 23.2475 16.1436 23.2326 16.1551L23.2333 16.1537Z","M16.9978 22.8858C16.4545 22.8127 15.9878 22.5363 15.6654 22.1441C16.7132 21.3381 17.4793 20.1636 17.7516 18.7825C17.7732 18.6708 17.7923 18.5583 17.8078 18.4438C17.9968 17.0458 17.6547 15.6986 16.936 14.6053C16.8236 14.4347 16.7024 14.2701 16.5724 14.113C16.4091 13.9152 16.3231 13.6612 16.3508 13.4058C16.3523 13.3903 16.3543 13.3746 16.357 13.3591C16.4525 12.7041 17.0519 12.2313 17.7109 12.2909C17.7252 12.2922 17.7394 12.2937 17.7537 12.2957C17.9893 12.3248 18.204 12.4487 18.3551 12.6316C18.5203 12.8315 18.6755 13.0387 18.8204 13.2534C19.8716 14.8113 20.377 16.7458 20.1053 18.7541C19.982 19.6671 19.7071 20.5233 19.3108 21.2994C19.1882 21.5406 19.0534 21.7736 18.9078 21.9985C18.5061 22.6183 17.7895 22.9712 17.0553 22.8919C17.0364 22.8899 17.0173 22.8878 16.9991 22.8852L16.9978 22.8858Z","M7.86115 23.2332C7.52858 22.797 7.39447 22.2728 7.44391 21.7668C8.75523 21.9375 10.1275 21.6483 11.2973 20.864C11.3915 20.801 11.4849 20.7339 11.5764 20.6641C12.6994 19.8093 13.4105 18.6145 13.6754 17.3337C13.7167 17.1339 13.7472 16.9313 13.7668 16.7281C13.7912 16.4727 13.9104 16.233 14.1103 16.0718C14.1225 16.0617 14.1353 16.0522 14.1475 16.0427C14.6785 15.6471 15.4371 15.7365 15.8605 16.2445C15.8693 16.2554 15.8788 16.2662 15.8869 16.2777C16.0332 16.4653 16.0969 16.7037 16.0745 16.9408C16.0501 17.1989 16.0129 17.4556 15.9635 17.7096C15.6044 19.554 14.5932 21.2792 12.9798 22.5072C12.2462 23.0652 11.4469 23.4771 10.6165 23.7453C10.3592 23.8286 10.0991 23.8984 9.83693 23.9546C9.11422 24.1091 8.35831 23.8524 7.89502 23.2773C7.88282 23.2624 7.87131 23.2475 7.85979 23.2326L7.86115 23.2332Z","M1.13386 17.0634C1.20769 16.5202 1.48336 16.0542 1.87621 15.7318C2.68292 16.779 3.85742 17.5443 5.23986 17.8166C5.35163 17.8382 5.46406 17.8572 5.57853 17.8728C6.97722 18.0618 8.32512 17.7198 9.41902 17.0018C9.58971 16.8894 9.75427 16.7681 9.9121 16.638C10.1105 16.4748 10.3639 16.3895 10.6192 16.4166C10.6348 16.4179 10.6504 16.4199 10.666 16.4226C11.321 16.5181 11.7945 17.1169 11.7348 17.7759C11.7335 17.7902 11.7322 17.8044 11.73 17.818C11.701 18.0537 11.577 18.2677 11.3941 18.4194C11.1943 18.5847 10.9863 18.7398 10.7717 18.8847C9.21311 19.9354 7.27728 20.4406 5.26764 20.169C4.35391 20.0458 3.49776 19.7714 2.72085 19.3745C2.47972 19.2518 2.24672 19.1171 2.02117 18.9714C1.40073 18.5699 1.04784 17.8539 1.12709 17.1197C1.12911 17.1007 1.13115 17.0817 1.13386 17.0634Z","M0.766739 7.8774C1.20294 7.5455 1.72788 7.41139 2.23385 7.46016C2.06316 8.77081 2.35238 10.1424 3.13741 11.3115C3.20041 11.4057 3.26746 11.4991 3.33722 11.5906C4.1927 12.7129 5.38752 13.4234 6.66903 13.6883C6.86953 13.7295 7.07138 13.7601 7.27457 13.7797C7.5306 13.8041 7.77038 13.9233 7.93158 14.1231C7.94175 14.1353 7.95123 14.1475 7.96071 14.1604C8.35628 14.6907 8.26755 15.4493 7.75887 15.8726C7.74803 15.8815 7.73719 15.891 7.72567 15.899C7.53805 16.0447 7.29895 16.1091 7.06256 16.0867C6.8045 16.0623 6.54779 16.0251 6.29311 15.9756C4.44738 15.6173 2.72153 14.606 1.49284 12.994C0.934041 12.2611 0.522899 11.4618 0.253997 10.6321C0.170684 10.3747 0.100919 10.1147 0.0447005 9.85248C-0.109732 9.13047 0.146978 8.37457 0.722712 7.91127C0.737614 7.89975 0.752515 7.88756 0.767417 7.87605L0.766739 7.8774Z","M7.0287 1.14538C7.57192 1.21853 8.03861 1.49487 8.36102 1.88705C7.31318 2.69308 6.54711 3.86758 6.27483 5.24867C6.25315 5.36043 6.23419 5.47286 6.21861 5.58733C6.02963 6.98535 6.37168 8.33257 7.09034 9.42579C7.20277 9.59648 7.32402 9.76109 7.45407 9.91824C7.6173 10.116 7.70333 10.37 7.67555 10.6254C7.6742 10.6409 7.67216 10.6565 7.66946 10.6721C7.57396 11.327 6.97451 11.7998 6.31546 11.7402C6.30125 11.7389 6.28702 11.7375 6.27279 11.7355C6.03708 11.7063 5.82237 11.5824 5.67132 11.3995C5.50605 11.1997 5.35094 10.9925 5.20599 10.7777C4.15477 9.21988 3.64948 7.28541 3.92109 5.27711C4.04436 4.36406 4.31936 3.50792 4.7156 2.73169C4.8382 2.49056 4.97299 2.25755 5.11861 2.03268C5.52028 1.41292 6.2369 1.06003 6.97112 1.13928C6.99009 1.14131 7.00905 1.14334 7.02734 1.14605L7.0287 1.14538Z","M16.1579 0.766744C16.4904 1.20295 16.6245 1.7272 16.5751 2.23317C15.2637 2.06248 13.8915 2.3517 12.7217 3.13606C12.6276 3.19906 12.534 3.26611 12.4427 3.33588C11.3196 4.19067 10.6084 5.38549 10.3436 6.66633C10.3022 6.86614 10.2718 7.06866 10.2521 7.27187C10.2277 7.52723 10.1085 7.767 9.90873 7.92821C9.89654 7.93837 9.88368 7.94785 9.87149 7.95733C9.34044 8.35289 8.58183 8.26349 8.15849 7.75549C8.14969 7.74465 8.1402 7.73381 8.13208 7.7223C7.98578 7.53468 7.9221 7.29625 7.94446 7.05919C7.96884 6.80112 8.00609 6.54441 8.05554 6.29041C8.41452 4.44603 9.42579 2.72085 11.0392 1.49285C11.7728 0.934723 12.572 0.522903 13.4025 0.254678C13.6598 0.171366 13.9199 0.101601 14.1821 0.0453817C14.9048 -0.109051 15.6607 0.147659 16.124 0.722716C16.1362 0.737618 16.1477 0.752519 16.1592 0.76742L16.1579 0.766744Z","M37.833 18.812L33.0705 12.364L31.0715 14.5591V18.812H28.896V5.0929H31.0715V11.5801L36.9707 5.0929H39.6949L34.5601 10.7177L40.4593 18.812H37.833ZM41.3079 18.812V8.79706H43.3658V18.812H41.3079ZM41.0531 6.36192C41.0531 5.65636 41.6411 5.088 42.3467 5.088C43.0523 5.088 43.6206 5.65636 43.6206 6.36192C43.6206 7.06747 43.0523 7.63584 42.3467 7.63584C41.6411 7.63584 41.0531 7.06747 41.0531 6.36192ZM45.1032 18.812V17.1069L50.8653 10.6197H45.1032V8.79706H53.4523V10.5022L47.6903 16.9893H53.4523V18.812H45.1032ZM54.2765 13.8143C54.2765 10.8549 56.5303 8.60107 59.4898 8.60107C62.7039 8.60107 65.0166 11.2273 64.6442 14.5003H56.3539C56.6479 16.0878 57.9218 17.2245 59.6465 17.2245C60.9596 17.2245 62.0376 16.5386 62.6059 15.441L64.3307 16.2054C63.4683 17.8517 61.7828 19.008 59.5877 19.008C56.5695 19.008 54.2765 16.7541 54.2765 13.8143ZM56.4127 12.8932H62.5668C62.2335 11.4429 61.0772 10.3846 59.4898 10.3846C57.9022 10.3846 56.7655 11.4233 56.4127 12.8932ZM66.2386 18.812V8.79706H68.2964V10.2278C69.0216 9.24783 70.1975 8.60107 71.589 8.60107C74.0193 8.60107 75.744 10.3846 75.744 12.8344V18.812H73.6861V13.148C73.6861 11.5997 72.5494 10.4825 71.0011 10.4825C69.4528 10.4825 68.2964 11.5997 68.2964 13.148V18.812H66.2386Z"],Cl=`<svg class="wordmark" role="img" aria-label="Kizen" width="76" height="24" viewBox="0 0 76 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg"><defs><clipPath id="kizen-callback-wordmark-clip"><rect width="75.648" height="24"/></clipPath></defs><g clip-path="url(#kizen-callback-wordmark-clip)">${kl.map(e=>`<path d="${e}"/>`).join("")}</g></svg>`,Sl={success:'<path d="M6 12.5l4 4 8-9"/>',error:'<path d="M8 8l8 8M16 8l-8 8"/>'},Pl=e=>`<svg class="status-icon" aria-hidden="true" focusable="false" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.25" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">${Sl[e]}</svg>`,El=`
2
+ import*as Cy from"http";var un="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.",Vl=["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy"],Wl=e=>e!==void 0&&e!=="",Le="not-configured";function ui({env:e,http:t}){return Le==="applied"||(Vl.some(n=>Wl(e[n]))?e.NODE_USE_ENV_PROXY==="1"?Le="already-set":typeof t.setGlobalProxyFromEnv!="function"?Le="unavailable":(t.setGlobalProxyFromEnv(e),Le="applied"):Le="not-configured"),Le}var pn=()=>Le;import{readFileSync as yy}from"fs";import{dirname as by,join as wy}from"path";import{fileURLToPath as vy}from"url";import{Command as xy}from"commander";import{spawn as tp}from"child_process";import{Command as np}from"commander";import{constants as pu}from"os";var _r={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"},ze=e=>new URL(_r[e]).origin,pi={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"},ql=["go","fmo"];function Ar(e){return ql.includes(e)}import{posix as Gl}from"path";var O=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Te=(e,t)=>e?.code===t,fn=e=>e instanceof Error&&Te(e,"ENOENT"),fe=async e=>{try{return await e}catch(t){if(Te(t,"ENOENT"))return;throw t}},ie=e=>typeof e=="string"&&e!==""?e:void 0,oe=e=>e instanceof Error?e.message:String(e),Me=e=>{let t=e;return t.cause?.code??t.code??t.cause?.message??t.message??String(e)},mn=e=>{let t=Gl.normalize(e.trim().replaceAll("\\","/")).replace(/\/+$/,"");return t==="."?"":t};import{spawn as ed}from"child_process";import{createHash as td,randomBytes as nd}from"crypto";import{createServer as rd}from"http";import{platform as mi}from"process";var Jl=["M22.8852 7.03547C22.8112 7.5787 22.5356 8.0447 22.1428 8.36712C21.336 7.31995 20.1615 6.55456 18.7791 6.28228C18.6674 6.2606 18.5549 6.24164 18.4404 6.22606C17.0417 6.03708 15.6939 6.37914 14.6 7.09712C14.4293 7.20955 14.2646 7.33079 14.1068 7.46084C13.9084 7.62408 13.655 7.70942 13.3997 7.68233C13.3841 7.68098 13.3686 7.67894 13.353 7.67624C12.698 7.58073 12.2245 6.98196 12.2842 6.32291C12.2855 6.3087 12.2869 6.29447 12.2889 6.28092C12.3181 6.04522 12.442 5.83117 12.6249 5.67946C12.8246 5.51418 13.0326 5.35907 13.2473 5.21412C14.8059 4.16358 16.7417 3.65828 18.7513 3.92989C19.665 4.05317 20.5212 4.32749 21.2981 4.72441C21.5392 4.84701 21.7722 4.9818 21.9978 5.12743C22.6183 5.52908 22.9712 6.24503 22.8919 6.97926C22.8899 6.99822 22.8878 7.01719 22.8852 7.03547Z","M23.2333 16.1537C22.797 16.4857 22.2721 16.6198 21.7662 16.571C21.9369 15.2604 21.6476 13.8887 20.8626 12.7197C20.7996 12.6255 20.7325 12.532 20.6628 12.4406C19.8073 11.3183 18.6125 10.6077 17.331 10.3429C17.1304 10.3016 16.9286 10.2711 16.7254 10.2515C16.4694 10.2271 16.2297 10.1078 16.0684 9.90806C16.0582 9.89587 16.0488 9.88368 16.0393 9.87082C15.6437 9.34044 15.7325 8.58183 16.2411 8.15849C16.2519 8.14969 16.2628 8.1402 16.2743 8.13208C16.462 7.98645 16.701 7.9221 16.9375 7.94446C17.1955 7.96884 17.4522 8.00609 17.7069 8.05554C19.5526 8.41385 21.2785 9.42512 22.5072 11.0372C23.0659 11.7701 23.4771 12.5693 23.746 13.399C23.8293 13.6564 23.8991 13.9165 23.9553 14.1786C24.1097 14.9006 23.853 15.6566 23.2773 16.1199C23.2624 16.1314 23.2475 16.1436 23.2326 16.1551L23.2333 16.1537Z","M16.9978 22.8858C16.4545 22.8127 15.9878 22.5363 15.6654 22.1441C16.7132 21.3381 17.4793 20.1636 17.7516 18.7825C17.7732 18.6708 17.7923 18.5583 17.8078 18.4438C17.9968 17.0458 17.6547 15.6986 16.936 14.6053C16.8236 14.4347 16.7024 14.2701 16.5724 14.113C16.4091 13.9152 16.3231 13.6612 16.3508 13.4058C16.3523 13.3903 16.3543 13.3746 16.357 13.3591C16.4525 12.7041 17.0519 12.2313 17.7109 12.2909C17.7252 12.2922 17.7394 12.2937 17.7537 12.2957C17.9893 12.3248 18.204 12.4487 18.3551 12.6316C18.5203 12.8315 18.6755 13.0387 18.8204 13.2534C19.8716 14.8113 20.377 16.7458 20.1053 18.7541C19.982 19.6671 19.7071 20.5233 19.3108 21.2994C19.1882 21.5406 19.0534 21.7736 18.9078 21.9985C18.5061 22.6183 17.7895 22.9712 17.0553 22.8919C17.0364 22.8899 17.0173 22.8878 16.9991 22.8852L16.9978 22.8858Z","M7.86115 23.2332C7.52858 22.797 7.39447 22.2728 7.44391 21.7668C8.75523 21.9375 10.1275 21.6483 11.2973 20.864C11.3915 20.801 11.4849 20.7339 11.5764 20.6641C12.6994 19.8093 13.4105 18.6145 13.6754 17.3337C13.7167 17.1339 13.7472 16.9313 13.7668 16.7281C13.7912 16.4727 13.9104 16.233 14.1103 16.0718C14.1225 16.0617 14.1353 16.0522 14.1475 16.0427C14.6785 15.6471 15.4371 15.7365 15.8605 16.2445C15.8693 16.2554 15.8788 16.2662 15.8869 16.2777C16.0332 16.4653 16.0969 16.7037 16.0745 16.9408C16.0501 17.1989 16.0129 17.4556 15.9635 17.7096C15.6044 19.554 14.5932 21.2792 12.9798 22.5072C12.2462 23.0652 11.4469 23.4771 10.6165 23.7453C10.3592 23.8286 10.0991 23.8984 9.83693 23.9546C9.11422 24.1091 8.35831 23.8524 7.89502 23.2773C7.88282 23.2624 7.87131 23.2475 7.85979 23.2326L7.86115 23.2332Z","M1.13386 17.0634C1.20769 16.5202 1.48336 16.0542 1.87621 15.7318C2.68292 16.779 3.85742 17.5443 5.23986 17.8166C5.35163 17.8382 5.46406 17.8572 5.57853 17.8728C6.97722 18.0618 8.32512 17.7198 9.41902 17.0018C9.58971 16.8894 9.75427 16.7681 9.9121 16.638C10.1105 16.4748 10.3639 16.3895 10.6192 16.4166C10.6348 16.4179 10.6504 16.4199 10.666 16.4226C11.321 16.5181 11.7945 17.1169 11.7348 17.7759C11.7335 17.7902 11.7322 17.8044 11.73 17.818C11.701 18.0537 11.577 18.2677 11.3941 18.4194C11.1943 18.5847 10.9863 18.7398 10.7717 18.8847C9.21311 19.9354 7.27728 20.4406 5.26764 20.169C4.35391 20.0458 3.49776 19.7714 2.72085 19.3745C2.47972 19.2518 2.24672 19.1171 2.02117 18.9714C1.40073 18.5699 1.04784 17.8539 1.12709 17.1197C1.12911 17.1007 1.13115 17.0817 1.13386 17.0634Z","M0.766739 7.8774C1.20294 7.5455 1.72788 7.41139 2.23385 7.46016C2.06316 8.77081 2.35238 10.1424 3.13741 11.3115C3.20041 11.4057 3.26746 11.4991 3.33722 11.5906C4.1927 12.7129 5.38752 13.4234 6.66903 13.6883C6.86953 13.7295 7.07138 13.7601 7.27457 13.7797C7.5306 13.8041 7.77038 13.9233 7.93158 14.1231C7.94175 14.1353 7.95123 14.1475 7.96071 14.1604C8.35628 14.6907 8.26755 15.4493 7.75887 15.8726C7.74803 15.8815 7.73719 15.891 7.72567 15.899C7.53805 16.0447 7.29895 16.1091 7.06256 16.0867C6.8045 16.0623 6.54779 16.0251 6.29311 15.9756C4.44738 15.6173 2.72153 14.606 1.49284 12.994C0.934041 12.2611 0.522899 11.4618 0.253997 10.6321C0.170684 10.3747 0.100919 10.1147 0.0447005 9.85248C-0.109732 9.13047 0.146978 8.37457 0.722712 7.91127C0.737614 7.89975 0.752515 7.88756 0.767417 7.87605L0.766739 7.8774Z","M7.0287 1.14538C7.57192 1.21853 8.03861 1.49487 8.36102 1.88705C7.31318 2.69308 6.54711 3.86758 6.27483 5.24867C6.25315 5.36043 6.23419 5.47286 6.21861 5.58733C6.02963 6.98535 6.37168 8.33257 7.09034 9.42579C7.20277 9.59648 7.32402 9.76109 7.45407 9.91824C7.6173 10.116 7.70333 10.37 7.67555 10.6254C7.6742 10.6409 7.67216 10.6565 7.66946 10.6721C7.57396 11.327 6.97451 11.7998 6.31546 11.7402C6.30125 11.7389 6.28702 11.7375 6.27279 11.7355C6.03708 11.7063 5.82237 11.5824 5.67132 11.3995C5.50605 11.1997 5.35094 10.9925 5.20599 10.7777C4.15477 9.21988 3.64948 7.28541 3.92109 5.27711C4.04436 4.36406 4.31936 3.50792 4.7156 2.73169C4.8382 2.49056 4.97299 2.25755 5.11861 2.03268C5.52028 1.41292 6.2369 1.06003 6.97112 1.13928C6.99009 1.14131 7.00905 1.14334 7.02734 1.14605L7.0287 1.14538Z","M16.1579 0.766744C16.4904 1.20295 16.6245 1.7272 16.5751 2.23317C15.2637 2.06248 13.8915 2.3517 12.7217 3.13606C12.6276 3.19906 12.534 3.26611 12.4427 3.33588C11.3196 4.19067 10.6084 5.38549 10.3436 6.66633C10.3022 6.86614 10.2718 7.06866 10.2521 7.27187C10.2277 7.52723 10.1085 7.767 9.90873 7.92821C9.89654 7.93837 9.88368 7.94785 9.87149 7.95733C9.34044 8.35289 8.58183 8.26349 8.15849 7.75549C8.14969 7.74465 8.1402 7.73381 8.13208 7.7223C7.98578 7.53468 7.9221 7.29625 7.94446 7.05919C7.96884 6.80112 8.00609 6.54441 8.05554 6.29041C8.41452 4.44603 9.42579 2.72085 11.0392 1.49285C11.7728 0.934723 12.572 0.522903 13.4025 0.254678C13.6598 0.171366 13.9199 0.101601 14.1821 0.0453817C14.9048 -0.109051 15.6607 0.147659 16.124 0.722716C16.1362 0.737618 16.1477 0.752519 16.1592 0.76742L16.1579 0.766744Z","M37.833 18.812L33.0705 12.364L31.0715 14.5591V18.812H28.896V5.0929H31.0715V11.5801L36.9707 5.0929H39.6949L34.5601 10.7177L40.4593 18.812H37.833ZM41.3079 18.812V8.79706H43.3658V18.812H41.3079ZM41.0531 6.36192C41.0531 5.65636 41.6411 5.088 42.3467 5.088C43.0523 5.088 43.6206 5.65636 43.6206 6.36192C43.6206 7.06747 43.0523 7.63584 42.3467 7.63584C41.6411 7.63584 41.0531 7.06747 41.0531 6.36192ZM45.1032 18.812V17.1069L50.8653 10.6197H45.1032V8.79706H53.4523V10.5022L47.6903 16.9893H53.4523V18.812H45.1032ZM54.2765 13.8143C54.2765 10.8549 56.5303 8.60107 59.4898 8.60107C62.7039 8.60107 65.0166 11.2273 64.6442 14.5003H56.3539C56.6479 16.0878 57.9218 17.2245 59.6465 17.2245C60.9596 17.2245 62.0376 16.5386 62.6059 15.441L64.3307 16.2054C63.4683 17.8517 61.7828 19.008 59.5877 19.008C56.5695 19.008 54.2765 16.7541 54.2765 13.8143ZM56.4127 12.8932H62.5668C62.2335 11.4429 61.0772 10.3846 59.4898 10.3846C57.9022 10.3846 56.7655 11.4233 56.4127 12.8932ZM66.2386 18.812V8.79706H68.2964V10.2278C69.0216 9.24783 70.1975 8.60107 71.589 8.60107C74.0193 8.60107 75.744 10.3846 75.744 12.8344V18.812H73.6861V13.148C73.6861 11.5997 72.5494 10.4825 71.0011 10.4825C69.4528 10.4825 68.2964 11.5997 68.2964 13.148V18.812H66.2386Z"],Yl=`<svg class="wordmark" role="img" aria-label="Kizen" width="76" height="24" viewBox="0 0 76 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg"><defs><clipPath id="kizen-callback-wordmark-clip"><rect width="75.648" height="24"/></clipPath></defs><g clip-path="url(#kizen-callback-wordmark-clip)">${Jl.map(e=>`<path d="${e}"/>`).join("")}</g></svg>`,Xl={success:'<path d="M6 12.5l4 4 8-9"/>',error:'<path d="M8 8l8 8M16 8l-8 8"/>'},Zl=e=>`<svg class="status-icon" aria-hidden="true" focusable="false" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.25" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">${Xl[e]}</svg>`,Ql=`
3
3
  :root {
4
4
  color-scheme: light dark;
5
5
  --page-bg: #F4F9F7;
@@ -82,47 +82,65 @@ main {
82
82
  .error { --accent: var(--error-accent); --tint: var(--error-bg); --glyph: var(--error-text); }
83
83
  h1 { margin: 0 0 10px; font-size: 22px; line-height: 1.3; font-weight: 600; }
84
84
  p { margin: 0; font-size: 15px; line-height: 1.5; color: var(--text-secondary); }
85
- `.trim().replace(/\n\s*/g,"");function Ko(e,t,n){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="color-scheme" content="light dark"><title>Kizen App Builder</title><style>${El}</style></head><body><main>${Cl}<section class="card ${e}" data-status="${e}"><div class="status">${Pl(e)}</div><h1>${t}</h1><p>${n}</p></section></main></body></html>`}var on="127.0.0.1",pr="/callback",$l=`http://${on}${pr}`,Nl="read write offline_access",Dl="Kizen App Builder CLI",Rl=300*1e3,Me="go",Et=2e4,q=class extends Error{constructor(n,r){super(r);this.code=n;this.name="OAuthError"}code},ye=e=>e===Me?"appbuilder login":`appbuilder login --env ${e}`,ze=(e,t,n={})=>new q("login_required",`${t} Run \`${ye(e)}\` to sign in${n.again===!0?" again":""}.`),Ol=e=>{try{return e===""?void 0:JSON.parse(e)}catch{return}};async function fr(e,t,n,r){let o=AbortSignal.timeout(r);try{let i=await e(t,{...n,headers:{Accept:"application/json",...n.headers},signal:o});return{res:i,body:Ol(await i.text())}}catch(i){let s=o.aborted?`timed out after ${String(Math.round(r/1e3))}s`:Pt(i);throw new q("network_error",`Couldn't reach ${new URL(t).origin}: ${s}`)}}function Jo(e,t,n){let r=O(n)?n:{},o=ie(r.error);if(o!==void 0){let i=ie(r.error_description);return new q(o,`${e} failed (${o}${i===void 0?"":`: ${i}`})`)}return new q("server_error",`${e} failed with HTTP ${String(t)}`)}async function Go(e,t,n=Et){let r=`${e}/.well-known/oauth-authorization-server`,o=a=>new q("server_error",`OAuth discovery at ${r} ${a}`),{res:i,body:s}=await fr(t,r,{},n);if(!i.ok)throw o(`failed with HTTP ${String(i.status)}`);if(!O(s))throw o("didn't return valid JSON");if(s.issuer!==e)throw o(`returned issuer ${typeof s.issuer=="string"?JSON.stringify(s.issuer):"none"}, expected ${e}`);return{issuer:e,authorizationEndpoint:s.authorization_endpoint,tokenEndpoint:s.token_endpoint,registrationEndpoint:s.registration_endpoint}}async function Yo(e,t,n=Et){let{res:r,body:o}=await fr(t,e.registrationEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:Dl,redirect_uris:[$l],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"})},n);if(!r.ok)throw Jo("App registration",r.status,o);let i=O(o)?ie(o.client_id):void 0;if(i===void 0)throw new q("server_error","App registration returned no client_id");return i}var Bl=e=>Tl("sha256").update(e,"ascii").digest("base64url"),mr=()=>Al(32).toString("base64url");function Xo(){let e=mr();return{verifier:e,challenge:Bl(e)}}function Zo(e,t){let n=new URL(e.authorizationEndpoint);return n.searchParams.set("response_type","code"),n.searchParams.set("client_id",t.clientId),n.searchParams.set("redirect_uri",t.redirectUri),n.searchParams.set("scope",Nl),n.searchParams.set("state",t.state),n.searchParams.set("code_challenge",t.codeChallenge),n.searchParams.set("code_challenge_method","S256"),n.toString()}async function hr(e,t,n,r=Et){let{res:o,body:i}=await fr(n,e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()},r);if(!o.ok)throw Jo("The token request",o.status,i);let s=O(i)?ie(i.access_token):void 0,a=O(i)?ie(i.refresh_token):void 0;if(!O(i)||s===void 0||a===void 0)throw new q("server_error","The token endpoint returned an unexpected response");return{accessToken:s,refreshToken:a,expiresIn:i.expires_in}}var qo=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store",Connection:"close"}).end(Ko(n.kind,n.heading,n.text))},Fl={kind:"success",heading:"You\u2019re signed in",text:"Sign-in complete. You can close this window."},jl={kind:"error",heading:"Sign-in failed",text:"Sign-in failed. Return to the terminal for details. You can close this window."},Ll={kind:"error",heading:"Outdated link",text:"This sign-in link is out of date. Use the latest link from the terminal."},Ml=e=>{try{return new URL(e??"/",`http://${on}`)}catch{return}};async function Qo(e){let t=e.timeoutMs??Rl,n,r=new Promise((h,v)=>{n={resolve:h,reject:v}});r.catch(()=>{});let o=!1,i,s=Il((h,v)=>{let p=Ml(h.url);if(o||h.method!=="GET"||p?.pathname!==pr){v.writeHead(404,{"Content-Type":"text/plain",Connection:"close"}).end("Not found");return}let l=p.searchParams;if(l.get("state")!==e.state){qo(v,400,Ll);return}let w=l.get("error"),C=l.get("error_description"),E=l.get("code")??"",x=w!==null?new q(w,`Kizen denied the sign-in (${w}${C?`: ${C}`:""})`):E?void 0:new q("invalid_callback","The sign-in callback had no authorization code");qo(v,x?400:200,x?jl:Fl),c(x,E)}),a=()=>(i??=new Promise(h=>{clearTimeout(g),s.close(()=>{h()}),s.closeAllConnections()}),i);function c(h,v=""){o||(o=!0,h?n.reject(h):n.resolve({code:v}),a())}await new Promise((h,v)=>{s.once("error",v),s.listen(0,on,()=>{s.off("error",v),h()})});let g=setTimeout(()=>{c(new q("timeout",`Timed out after ${String(Math.round(t/1e3))}s waiting for the browser sign-in`))},t),u=s.address();return{port:u.port,redirectUri:`http://${on}:${String(u.port)}${pr}`,result:r,close:a}}function ei(e){let[t,n]=Wo==="darwin"?["open",[e]]:Wo==="win32"?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{let r=_l(t,n,{stdio:"ignore",detached:!0});r.on("error",()=>{}),r.unref()}catch{}}var zl="The API key is invalid for this business, or the user id doesn't match. Check the credentials file's apiKey, userId and businessId.",Ul="The API key's user needs the Standard API Keys permission and edit access to this dashboard. Homepages also need the Customize Homepages permission.",Hl=e=>ze(e,"Kizen rejected the signed-in session.",{again:!0}).message,Vl="The signed-in user needs edit access to this dashboard. Homepages also need the Customize Homepages permission.",Kl={authFailed:zl,forbidden:Ul},Wl=100,ql=new Set(["detail","non_field_errors"]),Z=class extends Error{kind;status;hint;constructor(t,n,r={}){super(n),this.name="KizenApiError",this.kind=t,this.status=r.status,this.hint=r.hint}},_t=encodeURIComponent,Tt=(e,t)=>t===void 0?`/dashboards/${_t(e)}/dashlet`:`/dashboards/${_t(e)}/dashlet/${_t(t)}`;function gr(e,t,n){let r=o=>{n.push(t===""?o:`${t}: ${o}`)};if(typeof e=="string"){e.trim()!==""&&r(e);return}if(typeof e=="number"||typeof e=="boolean"){r(String(e));return}if(Array.isArray(e)){let o=e.filter(i=>typeof i=="string"&&i.trim()!==""||typeof i=="number"||typeof i=="boolean");o.length>0&&r(o.map(String).join(" "));for(let i of e)typeof i=="object"&&i!==null&&gr(i,t,n);return}if(O(e))for(let[o,i]of Object.entries(e)){let s=t===""&&ql.has(o)?"":t===""?o:`${t}.${o}`;gr(i,s,n)}}function Jl(e){if(typeof e!="object"||e===null)return;let t=[];return gr(e,"",t),t.length>0?t.join("; "):void 0}async function Gl(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 Yl(e,t,n,r,o){let i=Jl(r),s=`${e} ${t} failed with ${String(n)}${i===void 0?"":`: ${i}`}`;return n===401?new Z("auth_failed",s,{status:n,hint:o.authFailed}):n===403?new Z("forbidden",s,{status:n,hint:o.forbidden}):n===404?new Z("not_found",s,{status:n}):new Z("api_error",s,{status:n})}function ti(e,t,n){if(Array.isArray(n))return{results:n,next:null};if(O(n)&&Array.isArray(n.results))return{results:n.results,next:n.next};throw new Z("api_error",`${e} ${t} returned an unexpected response shape`)}var sn=e=>O(e)?e:{};function ni(e){let t=sn(e);return{business:sn(t.business),team:sn(t.team)}}var Xl=new Map([["login_required","auth_failed"],["network_error","network_error"]]);function Zl(e,t){let n=Le(e),r=e instanceof q?Xl.get(e.code):void 0;return r===void 0?new Z("api_error",`Couldn't refresh the ${t} session: ${n}`):new Z(r,n)}function At(e){let t=e.fetch??fetch,n=e.bearer?e.bearer.environment:e.credentials.environment,r=e.baseUrl??dr[n],o=e.bearer?{authFailed:Hl(n),forbidden:Vl}:Kl,i=u=>{throw Zl(u,n)},s=async()=>{if(!e.bearer){let{apiKey:v,userId:p,businessId:l}=e.credentials;return{headers:{"X-API-KEY":v,"X-USER-ID":p,"X-BUSINESS-ID":l}}}let{bearer:u}=e,h=await u.getAccessToken().catch(i);return{headers:{Authorization:`Bearer ${h}`},retry:async()=>({Authorization:`Bearer ${await u.refreshAccessToken(h).catch(i)}`})}},a=async(u,h,v)=>{let p=/^https?:\/\//.test(h)?h:`${r}${h}`,l=p.startsWith(r)?p.slice(r.length):p,w=async b=>{let f={...b,Accept:"application/json"},d={method:u,headers:f};v!==void 0&&(f["Content-Type"]="application/json",d.body=JSON.stringify(v));try{return await t(p,d)}catch(m){throw new Z("network_error",`Couldn't reach Kizen at ${r}: ${Pt(m)}${Zt()==="unavailable"?` ${Xt}`:""}`)}},{headers:C,retry:E}=await s(),x=await w(C);x.status===401&&E&&(await x.body?.cancel().catch(()=>{}),x=await w(await E()));let y,P;try{({text:y,json:P}=await Gl(x))}catch(b){throw new Z("network_error",`${u} ${l}: couldn't read the response: ${Pt(b)}. The request may have been applied; check Kizen before retrying.`,{status:x.status})}if(!x.ok)throw Yl(u,l,x.status,P,o);if(P===void 0&&y!=="")throw new Z("api_error",`${u} ${l} returned a response that is not JSON`,{status:x.status});return P},c=u=>{let h=new URL(r),v=new URL(u,h.origin);if(v.protocol=h.protocol,v.port=h.port,v.username="",v.password="",v.hash="",v.origin!==h.origin)throw new Z("api_error",`GET /custom-objects pagination pointed at an unexpected location ${v.origin}${v.pathname}`);return v.toString()},g;return{async listDashboards(u,h){let v=new URLSearchParams({size:"10000",include_sharing:"true",dashboard_type:u});h!==void 0&&v.set("custom_object_id",h);let p=`/dashboards/mine?${v.toString()}`;return ti("GET",p,await a("GET",p)).results},async listCustomObjects(){let u=[],h=new Set,v="/custom-objects?page_size=200";for(;v!==void 0&&!h.has(v)&&h.size<Wl;){h.add(v);let p=ti("GET",v,await a("GET",v));u.push(...p.results),v=typeof p.next=="string"&&p.next!==""?c(p.next):void 0}return u},async getCustomObject(u){let h=`/custom-objects/${_t(u)}`,v=await a("GET",h);if(!O(v)||typeof v.id!="string"||typeof v.fetch_url!="string")throw new Z("api_error",`GET ${h} returned an unexpected response shape`);return v},async getIdentity(){let u=await a("GET","/auth/bootstrap"),{business:h,team:v}=ni(u),p=ie(h.id),l=ie(v.user);if(p===void 0||l===void 0)throw new Z("api_error","GET /auth/bootstrap returned an unexpected response shape");return g=u,{userId:l,businessId:p,businessName:ie(h.name),fullName:ie(v.full_name),email:ie(v.email)}},async getClientObjectId(){let u=g??await a("GET","/auth/bootstrap"),{business:h}=ni(u);return ie(sn(h.client_object).id)??null},async getDashboard(u){return await a("GET",`/dashboards/${_t(u)}`)},async createDashlet(u,h){return await a("POST",Tt(u),h)},async updateDashlet(u,h,v){return await a("PATCH",Tt(u,h),v)}}}import{randomBytes as ri}from"crypto";import{chmod as Ql,mkdir as ed,open as td,readdir as nd,readFile as yr,rename as oi,rm as ii,unlink as si}from"fs/promises";import{join as It}from"path";var rd="clients.json",od=10*6e4,id=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ai=e=>typeof e=="string"&&id.test(e),an=e=>O(e)&&ai(e.businessId)&&ai(e.userId)?{businessId:e.businessId,userId:e.userId}:void 0,Ee=(e,t)=>e.businessId===t.businessId&&e.userId===t.userId,pt=e=>{if(an(e)===void 0)throw new Error("Refusing a session file name built from an invalid account id.");return`${e.businessId}.${e.userId}`};function ci(e){let t;try{t=JSON.parse(e)}catch{return}return an(t)}var br=e=>typeof e=="string"?e:void 0;function sd(e,t){let n=an(e);return!O(e)||n===void 0||e.environment!==t||typeof e.issuer!="string"||typeof e.clientId!="string"||typeof e.tokenEndpoint!="string"||typeof e.accessToken!="string"||typeof e.refreshToken!="string"||typeof e.expiresAt!="number"?null:{environment:t,...n,businessName:br(e.businessName),fullName:br(e.fullName),email:br(e.email),issuer:e.issuer,clientId:e.clientId,tokenEndpoint:e.tokenEndpoint,accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt}}function Ue(e=Se){let t=It(e,"oauth"),n=x=>It(t,`${x}.json`),r=(x,y)=>It(t,`${x}.${pt(y)}.json`),o=It(t,rd),i=(x,y)=>{let P=`${x}.`;if(!y.startsWith(P)||!y.endsWith(".json"))return;let b=y.slice(P.length,-5).split(".");if(b.length!==2)return;let[f,d]=b;return an({businessId:f,userId:d})},s=async()=>await tt(nd(t))??[],a=async()=>{await ed(t,{recursive:!0,mode:448}),await Ql(t,448)},c=async(x,y)=>{await a();let P=`${x}.${ri(6).toString("hex")}.tmp`;try{let b=await td(P,"wx",384);try{await b.writeFile(JSON.stringify(y,null,2),"utf-8"),await b.sync()}finally{await b.close()}await oi(P,x)}catch(b){throw await ii(P,{force:!0}),b}},g=(x,y)=>ze(x,`The saved ${x} session at ${y} can't be read.`,{again:!0}),u=async x=>{try{let y=new RegExp(`^${x}\\.json\\.([0-9]{1,16})-[0-9a-f]{12}\\.signout$`);for(let P of await s()){let b=y.exec(P)?.[1];b!==void 0&&Date.now()-Number(b)>od&&await tt(si(It(t,P)))}}catch{}},h=async()=>{let x;try{x=JSON.parse(await tt(yr(o,"utf-8"))??"{}")}catch(y){if(y instanceof SyntaxError)return{};throw y}return O(x)?x:{}},v=async(x,y)=>{try{return await tt(yr(y,"utf-8"))}catch{throw g(x,y)}},p=async(x,y)=>{let P=r(x,y),b=await v(x,P);if(b===void 0)return null;try{let f=sd(JSON.parse(b),x);if(f!==null&&Ee(f,y))return f}catch{}throw g(x,P)},l=async x=>{let y=n(x),P=await v(x,y);if(P===void 0)return;let b=ci(P);if(b===void 0)throw g(x,y);return b},w=async x=>{let y=await l(x);return y===void 0?null:p(x,y)},C=async x=>{let y=n(x),P=`${y}.${String(Date.now())}-${ri(6).toString("hex")}.signout`;if(await tt(oi(y,P).then(()=>!0))===!0)try{return{account:ci(await yr(P,"utf-8"))}}catch{return{account:void 0}}finally{await ii(P,{force:!0})}},E=async(x,y)=>await tt(si(r(x,y)).then(()=>!0))??!1;return{dir:t,sessionPath:n,accountPath:r,readSession:w,readAccount:p,async listAccounts(x){let y;try{y=await l(x)}catch{}let P=(await s()).map(d=>i(x,d)).filter(d=>d!==void 0),b=await Promise.all(P.map(async d=>{let m;try{let k=await p(x,d);if(k===null)return;m=k}catch(k){if(!(k instanceof q&&k.code==="login_required"))throw k}return{account:d,session:m,current:y!==void 0&&Ee(y,d)}})),f=d=>(d.session?.businessName??d.account.businessId).toLowerCase();return b.filter(d=>d!==void 0).sort((d,m)=>f(d).localeCompare(f(m))||pt(d.account).localeCompare(pt(m.account)))},async writeSession(x){await c(r(x.environment,x),x)},async setCurrent(x,y){let{businessId:P,userId:b}=y;await c(n(x),{businessId:P,userId:b}),await u(x)},async deleteSession(x,y){return E(x,y)},async signOut(x){let y=await C(x),P=y!==void 0;return y?.account!==void 0&&(P=await E(x,y.account)),await u(x),P},async removeAccount(x,y){let P=!1,b;try{b=await l(x)}catch{}b!==void 0&&Ee(b,y)&&(P=await C(x)!==void 0);let f=await E(x,y);return await u(x),{removed:f,current:P}},async signOutAll(x){let y=await C(x),P=y!==void 0&&y.account===void 0,b=0;for(let f of await s()){let d=i(x,f);d!==void 0&&await E(x,d)&&(b+=1,P||=y?.account!==void 0&&Ee(y.account,d))}return await u(x),{signedIn:P,removed:b}},async listSessions(){return(await Promise.all(W.map(async y=>{try{return await w(y)===null?void 0:y}catch(P){if(P instanceof q&&P.code==="login_required")return y;throw P}}))).filter(y=>y!==void 0)},async readClientId(x){let y=(await h())[x];return O(y)?ie(y.clientId):void 0},async writeClientId(x,y){await c(o,{...await h(),[x]:{clientId:y}})},async forgetClientId(x){let y=await h();x in y&&await c(o,Object.fromEntries(Object.entries(y).filter(([P])=>P!==x)))}}}var ad=6e4,cn=class extends q{},li=(e,t)=>fetch(e,t),di=()=>Date.now(),ui=(e,t,n)=>({store:e,fetch:li,now:di,print:t,openBrowser:ei,startLoopbackServer:Qo,identify:n}),cd=(e,t)=>({environment:e,getAccessToken:()=>Promise.resolve(t),refreshAccessToken:()=>Promise.reject(ze(e,`Kizen rejected the new ${e} sign-in.`))}),ln=e=>ze(e,`You're not signed in to ${e}.`),ld=e=>({businessName:e.businessName,fullName:e.fullName,email:e.email}),pi=(e,t,n)=>({...e,accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:n+t.expiresIn*1e3}),dd=(e,t)=>t?"Opening your browser to sign in to Kizen. If it does not open, visit:":`A browser window should open for the user to sign in to Kizen ${e}. If it doesn't, give them this URL:`;async function ud(e,t,n,r){let{verifier:o,challenge:i}=Xo(),s=mr(),a=await n.startLoopbackServer({state:s,...n.timeoutMs!==void 0&&{timeoutMs:n.timeoutMs}});try{let c=Zo(e,{clientId:t,redirectUri:a.redirectUri,state:s,codeChallenge:i});n.print(r),n.print(c),n.openBrowser(c);let{code:g}=await a.result;return await hr(e.tokenEndpoint,{grant_type:"authorization_code",code:g,redirect_uri:a.redirectUri,client_id:t,code_verifier:o},n.fetch)}finally{await a.close()}}async function wr(e,t,n={}){let r=dd(e,n.interactive??!0),o=await Go(ut(e),t.fetch),i=await t.store.readClientId(o.issuer),s=i??await Yo(o,t.fetch);i===void 0&&await t.store.writeClientId(o.issuer,s);let a;try{a=await ud(o,s,t,r)}catch(h){throw h instanceof q&&h.code==="timeout"&&i!==void 0?(await t.store.forgetClientId(o.issuer),new q("timeout",`${h.message}. If the browser showed an error instead of a consent page, the saved app registration was stale; it has been cleared. Run \`${ye(e)}\` again.`)):h}let c=await t.identify(cd(e,a.accessToken)),g={businessId:c.businessId,userId:c.userId},u=pi({environment:e,...g,...ld(c),issuer:o.issuer,clientId:s,tokenEndpoint:o.tokenEndpoint},a,t.now());if(await t.store.writeSession(u),n.makeCurrent!==void 0&&!n.makeCurrent(c)){if(await t.store.readAccount(e,g)===null)throw ln(e);return u}if(await t.store.setCurrent(e,g),await t.store.readSession(e)===null)throw ln(e);return u}async function fi(e,t,n){try{await n.identify(n.provider)}catch(o){if(await n.store.readAccount(e,t).then(s=>s===null,()=>!1))return;throw o}await n.store.setCurrent(e,t);let r=await n.store.readSession(e);if(r===null)throw ln(e);return r}function pd(e,t){let n,r=t.account,o=c=>c.expiresAt-t.now()>ad,i=async()=>{let c=t.account===void 0?await t.store.readSession(e):await t.store.readAccount(e,t.account);if(c===null)throw ln(e);if(r??={businessId:c.businessId,userId:c.userId},!Ee(c,r))throw new cn("login_required",`The ${e} sign-in changed while this command was running. Run it again.`);return c},s=async(c,g)=>{let u=await i();if(u.accessToken!==c&&o(u))return u.accessToken;let h=g??t.now()+(t.requestTimeoutMs??Et),v=async()=>{let E=await i();return{stored:E,rotated:E.refreshToken!==u.refreshToken}},p=h-t.now();if(p<=0)return u.accessToken;let l;try{l=await hr(u.tokenEndpoint,{grant_type:"refresh_token",refresh_token:u.refreshToken,client_id:u.clientId},t.fetch,p)}catch(E){if(E instanceof q&&(E.code==="invalid_grant"||E.code==="invalid_client")){let{stored:x,rotated:y}=await v();if(y)return o(x)||g!==void 0?x.accessToken:s(x.accessToken,h);if(await t.store.deleteSession(e,u)&&E.code==="invalid_client")try{await t.store.readClientId(u.issuer)===u.clientId&&await t.store.forgetClientId(u.issuer)}catch{}throw ze(e,`The ${e} session is no longer valid.`)}throw E}let w=pi(u,l,t.now()),C;try{({rotated:C}=await v())}catch(E){if(E instanceof cn){let x=await t.store.readAccount(e,u).catch(()=>null);x!==null&&x.refreshToken===u.refreshToken&&await t.store.writeSession(w).catch(()=>{})}throw E}return C||await t.store.writeSession(w),w.accessToken},a=c=>(n??=s(c).finally(()=>{n=void 0}),n);return{environment:e,async getAccessToken(){if(n)return n;let c=await i();return o(c)?c.accessToken:a(c.accessToken)},refreshAccessToken:a}}var dn=(e,t,n={})=>pd(e,{store:t,now:di,...n,fetch:n.fetch??li}),fd=`You're not signed in. Run \`${ye(Me)}\` (add \`--env <env>\` to sign in to an environment other than ${Me}).`;async function nt(e,t){if(e!==void 0){let{environment:o,message:i}=et(e);return o===void 0?{ok:!1,problem:"unknown_environment",message:i}:{ok:!0,environment:o}}let n=await t(),[r]=n;return n.length>1?{ok:!1,problem:"several_sessions",message:`You're signed in to several environments; pass --env <env>: ${n.join(", ")}`}:r===void 0?{ok:!1,problem:"not_signed_in",message:fd}:{ok:!0,environment:r}}var be=e=>/^[\w@%+:,./-][\w@%+=:,./-]*$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`;var md=5e3,hd=(e,t)=>e.isTTY===!0&&t.isTTY===!0;function hi(e=Ue(),t){let n=(i,s)=>dn(i,e,s),r=i=>{process.stderr.write(i)},o=i=>At({bearer:i}).getIdentity();return{store:e,loginDeps:ui(e,i=>{r(`${i}
86
- `)},o),identify:o,tokenProvider:n,isInteractive:()=>hd(process.stdin,process.stdout),...t!==void 0&&{pickAccount:t},authHeaderTimeouts:{requestTimeoutMs:md},processEnv:process.env,writeStdout:i=>{process.stdout.write(i)},writeStderr:r,setExitCode:i=>{process.exitCode=i}}}function gi(e){let{environment:t,message:n}=et(e);if(t===void 0)throw new Error(n);return t}async function yi(e,t){let n=await nt(e,()=>t.listSessions());if(!n.ok)throw new Error(n.message);return n.environment}var un=(e,t)=>e?`${e} (${t})`:t,bi=(e,t)=>{let n=[t.fullName,t.email&&`<${t.email}>`].filter(Boolean).join(" ");return`Environment: ${e}
85
+ `.trim().replace(/\n\s*/g,"");function fi(e,t,n){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="color-scheme" content="light dark"><title>Kizen App Builder</title><style>${Ql}</style></head><body><main>${Yl}<section class="card ${e}" data-status="${e}"><div class="status">${Zl(e)}</div><h1>${t}</h1><p>${n}</p></section></main></body></html>`}var hn="127.0.0.1",Tr="/callback",od=`http://${hn}${Tr}`,id="read write offline_access",sd="Kizen App Builder CLI",ad=300*1e3,Ue="go",_t=2e4,q=class extends Error{constructor(n,r){super(r);this.code=n;this.name="OAuthError"}code},xe=e=>e===Ue?"appbuilder login":`appbuilder login --env ${e}`,ke=(e,t,n={})=>new q("login_required",`${t} Run \`${xe(e)}\` to sign in${n.again===!0?" again":""}.`),cd=e=>{try{return e===""?void 0:JSON.parse(e)}catch{return}};async function Ir(e,t,n,r){let o=AbortSignal.timeout(r);try{let i=await e(t,{...n,headers:{Accept:"application/json",...n.headers},signal:o});return{res:i,body:cd(await i.text())}}catch(i){let s=o.aborted?`timed out after ${String(Math.round(r/1e3))}s`:Me(i);throw new q("network_error",`Couldn't reach ${new URL(t).origin}: ${s}`)}}function gi(e,t,n){let r=O(n)?n:{},o=ie(r.error);if(o!==void 0){let i=ie(r.error_description);return new q(o,`${e} failed (${o}${i===void 0?"":`: ${i}`})`)}return new q("server_error",`${e} failed with HTTP ${String(t)}`)}async function yi(e,t,n=_t){let r=`${e}/.well-known/oauth-authorization-server`,o=a=>new q("server_error",`OAuth discovery at ${r} ${a}`),{res:i,body:s}=await Ir(t,r,{},n);if(!i.ok)throw o(`failed with HTTP ${String(i.status)}`);if(!O(s))throw o("didn't return valid JSON");if(s.issuer!==e)throw o(`returned issuer ${typeof s.issuer=="string"?JSON.stringify(s.issuer):"none"}, expected ${e}`);return{issuer:e,authorizationEndpoint:s.authorization_endpoint,tokenEndpoint:s.token_endpoint,registrationEndpoint:s.registration_endpoint}}async function bi(e,t,n=_t){let{res:r,body:o}=await Ir(t,e.registrationEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:sd,redirect_uris:[od],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"})},n);if(!r.ok)throw gi("App registration",r.status,o);let i=O(o)?ie(o.client_id):void 0;if(i===void 0)throw new q("server_error","App registration returned no client_id");return i}var ld=e=>td("sha256").update(e,"ascii").digest("base64url"),$r=()=>nd(32).toString("base64url");function wi(){let e=$r();return{verifier:e,challenge:ld(e)}}function vi(e,t){let n=new URL(e.authorizationEndpoint);return n.searchParams.set("response_type","code"),n.searchParams.set("client_id",t.clientId),n.searchParams.set("redirect_uri",t.redirectUri),n.searchParams.set("scope",id),n.searchParams.set("state",t.state),n.searchParams.set("code_challenge",t.codeChallenge),n.searchParams.set("code_challenge_method","S256"),n.toString()}async function Nr(e,t,n,r=_t){let{res:o,body:i}=await Ir(n,e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()},r);if(!o.ok)throw gi("The token request",o.status,i);let s=O(i)?ie(i.access_token):void 0,a=O(i)?ie(i.refresh_token):void 0;if(!O(i)||s===void 0||a===void 0)throw new q("server_error","The token endpoint returned an unexpected response");return{accessToken:s,refreshToken:a,expiresIn:i.expires_in}}var hi=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store",Connection:"close"}).end(fi(n.kind,n.heading,n.text))},dd={kind:"success",heading:"You\u2019re signed in",text:"Sign-in complete. You can close this window."},ud={kind:"error",heading:"Sign-in failed",text:"Sign-in failed. Return to the terminal for details. You can close this window."},pd={kind:"error",heading:"Outdated link",text:"This sign-in link is out of date. Use the latest link from the terminal."},fd=e=>{try{return new URL(e??"/",`http://${hn}`)}catch{return}};async function xi(e){let t=e.timeoutMs??ad,n,r=new Promise((h,y)=>{n={resolve:h,reject:y}});r.catch(()=>{});let o=!1,i,s=rd((h,y)=>{let f=fd(h.url);if(o||h.method!=="GET"||f?.pathname!==Tr){y.writeHead(404,{"Content-Type":"text/plain",Connection:"close"}).end("Not found");return}let u=f.searchParams;if(u.get("state")!==e.state){hi(y,400,pd);return}let w=u.get("error"),k=u.get("error_description"),_=u.get("code")??"",P=w!==null?new q(w,`Kizen denied the sign-in (${w}${k?`: ${k}`:""})`):_?void 0:new q("invalid_callback","The sign-in callback had no authorization code");hi(y,P?400:200,P?ud:dd),c(P,_)}),a=()=>(i??=new Promise(h=>{clearTimeout(g),s.close(()=>{h()}),s.closeAllConnections()}),i);function c(h,y=""){o||(o=!0,h?n.reject(h):n.resolve({code:y}),a())}await new Promise((h,y)=>{s.once("error",y),s.listen(0,hn,()=>{s.off("error",y),h()})});let g=setTimeout(()=>{c(new q("timeout",`Timed out after ${String(Math.round(t/1e3))}s waiting for the browser sign-in`))},t),m=s.address();return{port:m.port,redirectUri:`http://${hn}:${String(m.port)}${Tr}`,result:r,close:a}}function ki(e){let[t,n]=mi==="darwin"?["open",[e]]:mi==="win32"?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{let r=ed(t,n,{stdio:"ignore",detached:!0});r.on("error",()=>{}),r.unref()}catch{}}var le=e=>/^[\w@%+:,./-][\w@%+=:,./-]*$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`;var At="APPBUILDER_BUSINESS",Tt="APPBUILDER_USER";function It(e,t){if(e.business!==void 0)return{ok:!0,request:{business:e.business,user:e.user,source:"flags"}};if(e.user!==void 0)return{ok:!1,message:"--user only applies with --business."};let n=t[At]||void 0,r=t[Tt]||void 0;return n===void 0?r===void 0?{ok:!0,request:void 0}:{ok:!1,message:`${Tt} only applies with ${At}.`}:{ok:!0,request:{business:n,user:r,source:"env"}}}var md="To use an API key instead (deprecated), pass --profile <name> or -c <path>.";function Ci(e,t){let n=e.credentials!==void 0||e.profile!==void 0;if(n&&e.env!==void 0)return{ok:!1,message:"--env selects a sign-in session, so it can't be combined with -c or --profile."};if(n&&(e.business!==void 0||e.user!==void 0))return{ok:!1,message:`${e.business===void 0?"--user":"--business"} selects a saved sign-in account, so it can't be combined with -c or --profile.`};if(e.credentials!==void 0)return{ok:!0,selection:{kind:"api-key",credentials:e.credentials}};if(e.profile!==void 0)return{ok:!0,selection:{kind:"api-key",profile:e.profile}};let r=It(e,t);return r.ok?{ok:!0,selection:{kind:"oauth",...e.env!==void 0&&{env:e.env},...r.request!==void 0&&{account:r.request}}}:r}var Si=e=>`Ignoring the API-key profile ${JSON.stringify(e)} pinned in .kizenapp/config.json and using your sign-in session.${/[\x00-\x1f\x7f]/.test(e)?"":` Pass --profile ${le(e)} to use the API key.`}`,Pi=e=>`${e} ${md}`;import{mkdir as Ei,readFile as hd,readdir as gd,writeFile as _i}from"fs/promises";import{homedir as yd}from"os";import{dirname as bd,join as gn}from"path";var W=["go","fmo","staging","integration","test1"];function $t(e){return typeof e=="string"?e.trim():""}function Nt(e){return{apiKey:$t(e.apiKey),userId:$t(e.userId),businessId:$t(e.businessId)}}var ye=gn(yd(),".kizenappbuilder"),He=gn(ye,"credentials.json"),Ke="credentials",Dt=e=>W.includes(e),wd=e=>`Unknown --env "${e}". Use one of: ${W.join(", ")}.`,ot=e=>Dt(e)?{environment:e}:{message:wd(e)};function vd(e){return typeof e=="string"?e.trim():e}function xd(e){return Dt(e)?"explicit":e==null||e===""?"missing":"invalid"}function kd(e){if(typeof e!="object"||e===null)throw new Error("Credentials must be a JSON object");let t=e,n=vd(t.environment);return{credentials:{...Nt(t),environment:Dt(n)?n:"go"},environmentSource:xd(n)}}async function yn(e){let t=await hd(e,"utf-8");return kd(JSON.parse(t))}async function Ve(e){return(await yn(e)).credentials}async function se(){try{return await Ve(He)}catch{return null}}async function Cd(e){await Ei(bd(He),{recursive:!0,mode:448}),await _i(He,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function Ai(e){return gn(ye,`${e}.json`)}async function We(){let e=[{name:Ke,path:He,isDefault:!0}];try{let t=await gd(ye);for(let n of t){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);r!==Ke&&e.push({name:r,path:gn(ye,n),isDefault:!1})}}catch{}return e}async function Ti(e,t){if(e===Ke){await Cd(t);return}await Ei(ye,{recursive:!0,mode:448}),await _i(Ai(e),JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}async function Ie(e){try{return await Ve(Ai(e))}catch{return null}}async function Ii(){let e=await We(),t=await Promise.all(e.map(n=>yn(n.path).then(()=>!0,()=>!1)));return e.filter((n,r)=>t[r]===!0)}var Sd="The API key is invalid for this business, or the user id doesn't match. Check the credentials file's apiKey, userId and businessId.",Pd="The API key's user needs the Standard API Keys permission and edit access to this dashboard. Homepages also need the Customize Homepages permission.",Ed=e=>ke(e,"Kizen rejected the signed-in session.",{again:!0}).message,_d="The signed-in user needs edit access to this dashboard. Homepages also need the Customize Homepages permission.",Ad={authFailed:Sd,forbidden:Pd},Td=100,Id=new Set(["detail","non_field_errors"]),Z=class extends Error{kind;status;hint;constructor(t,n,r={}){super(n),this.name="KizenApiError",this.kind=t,this.status=r.status,this.hint=r.hint}},Rt=encodeURIComponent,Ot=(e,t)=>t===void 0?`/dashboards/${Rt(e)}/dashlet`:`/dashboards/${Rt(e)}/dashlet/${Rt(t)}`;function Dr(e,t,n){let r=o=>{n.push(t===""?o:`${t}: ${o}`)};if(typeof e=="string"){e.trim()!==""&&r(e);return}if(typeof e=="number"||typeof e=="boolean"){r(String(e));return}if(Array.isArray(e)){let o=e.filter(i=>typeof i=="string"&&i.trim()!==""||typeof i=="number"||typeof i=="boolean");o.length>0&&r(o.map(String).join(" "));for(let i of e)typeof i=="object"&&i!==null&&Dr(i,t,n);return}if(O(e))for(let[o,i]of Object.entries(e)){let s=t===""&&Id.has(o)?"":t===""?o:`${t}.${o}`;Dr(i,s,n)}}function $d(e){if(typeof e!="object"||e===null)return;let t=[];return Dr(e,"",t),t.length>0?t.join("; "):void 0}async function Nd(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 Dd(e,t,n,r,o){let i=$d(r),s=`${e} ${t} failed with ${String(n)}${i===void 0?"":`: ${i}`}`;return n===401?new Z("auth_failed",s,{status:n,hint:o.authFailed}):n===403?new Z("forbidden",s,{status:n,hint:o.forbidden}):n===404?new Z("not_found",s,{status:n}):new Z("api_error",s,{status:n})}function $i(e,t,n){if(Array.isArray(n))return{results:n,next:null};if(O(n)&&Array.isArray(n.results))return{results:n.results,next:n.next};throw new Z("api_error",`${e} ${t} returned an unexpected response shape`)}var bn=e=>O(e)?e:{};function Ni(e){let t=bn(e);return{business:bn(t.business),team:bn(t.team)}}var Rd=new Map([["login_required","auth_failed"],["network_error","network_error"]]);function Od(e,t){let n=oe(e),r=e instanceof q?Rd.get(e.code):void 0;return r===void 0?new Z("api_error",`Couldn't refresh the ${t} session: ${n}`):new Z(r,n)}function Bt(e){let t=e.fetch??fetch,n=e.bearer?e.bearer.environment:e.credentials.environment,r=e.baseUrl??_r[n],o=e.bearer?{authFailed:Ed(n),forbidden:_d}:Ad,i=m=>{throw Od(m,n)},s=async()=>{if(!e.bearer){let{apiKey:y,userId:f,businessId:u}=e.credentials;return{headers:{"X-API-KEY":y,"X-USER-ID":f,"X-BUSINESS-ID":u}}}let{bearer:m}=e,h=await m.getAccessToken().catch(i);return{headers:{Authorization:`Bearer ${h}`},retry:async()=>({Authorization:`Bearer ${await m.refreshAccessToken(h).catch(i)}`})}},a=async(m,h,y)=>{let f=/^https?:\/\//.test(h)?h:`${r}${h}`,u=f.startsWith(r)?f.slice(r.length):f,w=async v=>{let l={...v,Accept:"application/json"},d={method:m,headers:l};y!==void 0&&(l["Content-Type"]="application/json",d.body=JSON.stringify(y));try{return await t(f,d)}catch(p){throw new Z("network_error",`Couldn't reach Kizen at ${r}: ${Me(p)}${pn()==="unavailable"?` ${un}`:""}`)}},{headers:k,retry:_}=await s(),P=await w(k);P.status===401&&_&&(await P.body?.cancel().catch(()=>{}),P=await w(await _()));let C,T;try{({text:C,json:T}=await Nd(P))}catch(v){throw new Z("network_error",`${m} ${u}: couldn't read the response: ${Me(v)}. The request may have been applied; check Kizen before retrying.`,{status:P.status})}if(!P.ok)throw Dd(m,u,P.status,T,o);if(T===void 0&&C!=="")throw new Z("api_error",`${m} ${u} returned a response that is not JSON`,{status:P.status});return T},c=m=>{let h=new URL(r),y=new URL(m,h.origin);if(y.protocol=h.protocol,y.port=h.port,y.username="",y.password="",y.hash="",y.origin!==h.origin)throw new Z("api_error",`GET /custom-objects pagination pointed at an unexpected location ${y.origin}${y.pathname}`);return y.toString()},g;return{async listDashboards(m,h){let y=new URLSearchParams({size:"10000",include_sharing:"true",dashboard_type:m});h!==void 0&&y.set("custom_object_id",h);let f=`/dashboards/mine?${y.toString()}`;return $i("GET",f,await a("GET",f)).results},async listCustomObjects(){let m=[],h=new Set,y="/custom-objects?page_size=200";for(;y!==void 0&&!h.has(y)&&h.size<Td;){h.add(y);let f=$i("GET",y,await a("GET",y));m.push(...f.results),y=typeof f.next=="string"&&f.next!==""?c(f.next):void 0}return m},async getCustomObject(m){let h=`/custom-objects/${Rt(m)}`,y=await a("GET",h);if(!O(y)||typeof y.id!="string"||typeof y.fetch_url!="string")throw new Z("api_error",`GET ${h} returned an unexpected response shape`);return y},async getIdentity(){let m=await a("GET","/auth/bootstrap"),{business:h,team:y}=Ni(m),f=ie(h.id),u=ie(y.user);if(f===void 0||u===void 0)throw new Z("api_error","GET /auth/bootstrap returned an unexpected response shape");return g=m,{userId:u,businessId:f,businessName:ie(h.name),fullName:ie(y.full_name),email:ie(y.email)}},async getClientObjectId(){let m=g??await a("GET","/auth/bootstrap"),{business:h}=Ni(m);return ie(bn(h.client_object).id)??null},async getDashboard(m){return await a("GET",`/dashboards/${Rt(m)}`)},async createDashlet(m,h){return await a("POST",Ot(m),h)},async updateDashlet(m,h,y){return await a("PATCH",Ot(m,h),y)}}}var Bd=6e4,Di=(e,t)=>fetch(e,t),Ri=()=>Date.now(),Oi=(e,t,n)=>({store:e,fetch:Di,now:Ri,print:t,openBrowser:ki,startLoopbackServer:xi,identify:n}),Fd=(e,t)=>({environment:e,getAccessToken:()=>Promise.resolve(t),refreshAccessToken:()=>Promise.reject(ke(e,`Kizen rejected the new ${e} sign-in.`))}),Ft=e=>ke(e,`You're not signed in to ${e}.`),jd=e=>({businessName:e.businessName,fullName:e.fullName,email:e.email}),Bi=(e,t,n)=>({...e,accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:n+t.expiresIn*1e3}),Ld=(e,t)=>t?"Opening your browser to sign in to Kizen. If it does not open, visit:":`A browser window should open for the user to sign in to Kizen ${e}. If it doesn't, give them this URL:`;async function zd(e,t,n,r){let{verifier:o,challenge:i}=wi(),s=$r(),a=await n.startLoopbackServer({state:s,...n.timeoutMs!==void 0&&{timeoutMs:n.timeoutMs}});try{let c=vi(e,{clientId:t,redirectUri:a.redirectUri,state:s,codeChallenge:i});n.print(r),n.print(c),n.openBrowser(c);let{code:g}=await a.result;return await Nr(e.tokenEndpoint,{grant_type:"authorization_code",code:g,redirect_uri:a.redirectUri,client_id:t,code_verifier:o},n.fetch)}finally{await a.close()}}async function Rr(e,t,n={}){let r=Ld(e,n.interactive??!0),o=await yi(ze(e),t.fetch),i=await t.store.readClientId(o.issuer),s=i??await bi(o,t.fetch);i===void 0&&await t.store.writeClientId(o.issuer,s);let a;try{a=await zd(o,s,t,r)}catch(h){throw h instanceof q&&h.code==="timeout"&&i!==void 0?(await t.store.forgetClientId(o.issuer),new q("timeout",`${h.message}. If the browser showed an error instead of a consent page, the saved app registration was stale; it has been cleared. Run \`${xe(e)}\` again.`)):h}let c=await t.identify(Fd(e,a.accessToken)),g={businessId:c.businessId,userId:c.userId},m=Bi({environment:e,...g,...jd(c),issuer:o.issuer,clientId:s,tokenEndpoint:o.tokenEndpoint},a,t.now());if(await t.store.writeSession(m),n.makeCurrent!==void 0&&!n.makeCurrent(c)){if(await t.store.readAccount(e,g)===null)throw Ft(e);return m}if(await t.store.setCurrent(e,g),await t.store.readSession(e)===null)throw Ft(e);return m}async function Fi(e,t,n){try{await n.identify(n.provider)}catch(o){if(await n.store.readAccount(e,t).then(s=>s===null,()=>!1))return;throw o}await n.store.setCurrent(e,t);let r=await n.store.readSession(e);if(r===null)throw Ft(e);return r}function Md(e,t){let n,r=t.account,o,i=m=>m.expiresAt-t.now()>Bd,s=m=>{if(m===null)throw Ft(e);return m},a=async()=>r!==void 0?s(await t.store.readAccount(e,r)):(o??=t.store.readSession(e).then(m=>{let h=s(m);return r={businessId:h.businessId,userId:h.userId},h}).finally(()=>{o=void 0}),o),c=async(m,h)=>{let y=await a();if(y.accessToken!==m&&i(y))return y.accessToken;let f=h??t.now()+(t.requestTimeoutMs??_t),u=async()=>{let P=await a();return{stored:P,rotated:P.refreshToken!==y.refreshToken}},w=f-t.now();if(w<=0)return y.accessToken;let k;try{k=await Nr(y.tokenEndpoint,{grant_type:"refresh_token",refresh_token:y.refreshToken,client_id:y.clientId},t.fetch,w)}catch(P){if(P instanceof q&&(P.code==="invalid_grant"||P.code==="invalid_client")){let{stored:C,rotated:T}=await u();if(T)return i(C)||h!==void 0?C.accessToken:c(C.accessToken,f);if(await t.store.deleteSession(e,y)&&P.code==="invalid_client")try{await t.store.readClientId(y.issuer)===y.clientId&&await t.store.forgetClientId(y.issuer)}catch{}throw ke(e,`The ${e} session is no longer valid.`)}throw P}let _=Bi(y,k,t.now());if(await t.store.commitRefresh(_,y.refreshToken)==="gone")throw Ft(e);return _.accessToken},g=m=>(n??=c(m).finally(()=>{n=void 0}),n);return{environment:e,async getAccessToken(){if(n)return n;let m=await a();return i(m)?m.accessToken:g(m.accessToken)},refreshAccessToken:g}}var wn=(e,t,n={})=>Md(e,{store:t,now:Ri,...n,fetch:n.fetch??Di}),Ud=`You're not signed in. Run \`${xe(Ue)}\` (add \`--env <env>\` to sign in to an environment other than ${Ue}).`;async function jt(e,t){if(e!==void 0){let{environment:o,message:i}=ot(e);return o===void 0?{ok:!1,problem:"unknown_environment",message:i}:{ok:!0,environment:o}}let n=await t(),[r]=n;return n.length>1?{ok:!1,problem:"several_sessions",message:`You're signed in to several environments; pass --env <env>: ${n.join(", ")}`}:r===void 0?{ok:!1,problem:"not_signed_in",message:Ud}:{ok:!0,environment:r}}import{randomBytes as Br}from"crypto";import{chmod as Hd,mkdir as Kd,open as Mi,readdir as Vd,readFile as vn,rename as ji,rm as Fr,stat as Ui,unlink as Lt}from"fs/promises";import{join as yt}from"path";import{setTimeout as Wd}from"timers/promises";var qd="clients.json",Gd=10*6e4,Jd={waitMs:2e3,staleMs:3e4,pollMs:25};async function Yd(e,{waitMs:t,staleMs:n,pollMs:r}){let o=Date.now()+t;for(;;){let i;try{i=await Mi(e,"wx",384)}catch(a){if(!Te(a,"EEXIST"))return;try{let c=await fe(Ui(e));if(c===void 0)continue;if(Date.now()-c.mtimeMs>n){await fe(Lt(e));continue}}catch{return}if(Date.now()>=o)return;await Wd(r);continue}let s=Br(16).toString("hex");try{await i.writeFile(s,"utf-8")}catch{s=void 0}try{await i.close()}catch{s=void 0}return s===void 0&&await Fr(e,{force:!0}).catch(()=>{}),s}}async function Xd(e,t,n){let r=await Yd(e,t);try{return{value:await n(),held:r!==void 0}}finally{if(r!==void 0)try{await fe(vn(e,"utf-8"))===r&&await fe(Lt(e))}catch{}}}var Zd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Li=e=>typeof e=="string"&&Zd.test(e),xn=e=>O(e)&&Li(e.businessId)&&Li(e.userId)?{businessId:e.businessId,userId:e.userId}:void 0,it=(e,t)=>e.businessId===t.businessId&&e.userId===t.userId,st=e=>{if(xn(e)===void 0)throw new Error("Refusing a session file name built from an invalid account id.");return`${e.businessId}.${e.userId}`};function zi(e){let t;try{t=JSON.parse(e)}catch{return}return xn(t)}var Or=e=>typeof e=="string"?e:void 0;function Qd(e,t){let n=xn(e);return!O(e)||n===void 0||e.environment!==t||typeof e.issuer!="string"||typeof e.clientId!="string"||typeof e.tokenEndpoint!="string"||typeof e.accessToken!="string"||typeof e.refreshToken!="string"||typeof e.expiresAt!="number"?null:{environment:t,...n,businessName:Or(e.businessName),fullName:Or(e.fullName),email:Or(e.email),issuer:e.issuer,clientId:e.clientId,tokenEndpoint:e.tokenEndpoint,accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt}}function Ce(e=ye,t={}){let n=yt(e,"oauth"),r={...Jd,...t.lock},o=l=>yt(n,`${l}.json`),i=(l,d)=>yt(n,`${l}.${st(d)}.json`),s=(l,d)=>yt(n,`${l}.${st(d)}.lock`),a=async(l,d,p)=>(await Xd(s(l,d),r,p)).value,c=yt(n,qd),g=(l,d)=>{let p=`${l}.`;if(!d.startsWith(p)||!d.endsWith(".json"))return;let b=d.slice(p.length,-5).split(".");if(b.length!==2)return;let[x,S]=b;return xn({businessId:x,userId:S})},m=async()=>await fe(Vd(n))??[],h=async()=>{await Kd(n,{recursive:!0,mode:448}),await Hd(n,448)},y=async(l,d)=>{await h();let p=`${l}.${Br(6).toString("hex")}.tmp`;try{let b=await Mi(p,"wx",384);try{await b.writeFile(JSON.stringify(d,null,2),"utf-8"),await b.sync()}finally{await b.close()}await ji(p,l)}catch(b){throw await Fr(p,{force:!0}),b}},f=(l,d)=>ke(l,`The saved ${l} session at ${d} can't be read.`,{again:!0}),u=async l=>{try{let d=new RegExp(`^${l}\\.json\\.([0-9]{1,16})-[0-9a-f]{12}\\.signout$`);for(let p of await m()){let b=d.exec(p)?.[1];b!==void 0&&Date.now()-Number(b)>Gd&&await fe(Lt(yt(n,p)));let x=p.endsWith(".lock")?g(l,`${p.slice(0,-5)}.json`):void 0;if(x!==void 0){let S=s(l,x),E=await fe(Ui(S));E!==void 0&&Date.now()-E.mtimeMs>r.staleMs&&await fe(Lt(S))}}}catch{}},w=async()=>{let l;try{l=JSON.parse(await fe(vn(c,"utf-8"))??"{}")}catch(d){if(d instanceof SyntaxError)return{};throw d}return O(l)?l:{}},k=async(l,d)=>{try{return await fe(vn(d,"utf-8"))}catch{throw f(l,d)}},_=async(l,d)=>{let p=i(l,d),b=await k(l,p);if(b===void 0)return null;try{let x=Qd(JSON.parse(b),l);if(x!==null&&it(x,d))return x}catch{}throw f(l,p)},P=async l=>{let d=o(l),p=await k(l,d);if(p===void 0)return;let b=zi(p);if(b===void 0)throw f(l,d);return b},C=async l=>{let d=await P(l);return d===void 0?null:_(l,d)},T=async l=>{let d=o(l),p=`${d}.${String(Date.now())}-${Br(6).toString("hex")}.signout`;if(await fe(ji(d,p).then(()=>!0))===!0)try{return{account:zi(await vn(p,"utf-8"))}}catch{return{account:void 0}}finally{await Fr(p,{force:!0})}},v=(l,d)=>a(l,d,async()=>await fe(Lt(i(l,d)).then(()=>!0))??!1);return{dir:n,sessionPath:o,accountPath:i,readSession:C,readAccount:_,async listAccounts(l){let d;try{d=await P(l)}catch{}let p=(await m()).map(S=>g(l,S)).filter(S=>S!==void 0),b=await Promise.all(p.map(async S=>{let E;try{let $=await _(l,S);if($===null)return;E=$}catch($){if(!($ instanceof q&&$.code==="login_required"))throw $}return{account:S,session:E,current:d!==void 0&&it(d,S)}})),x=S=>(S.session?.businessName??S.account.businessId).toLowerCase();return b.filter(S=>S!==void 0).sort((S,E)=>x(S).localeCompare(x(E))||st(S.account).localeCompare(st(E.account)))},async writeSession(l){await y(i(l.environment,l),l)},async commitRefresh(l,d){let{environment:p}=l;return a(p,l,async()=>{let b=await _(p,l);return b===null?"gone":b.refreshToken!==d?"rotated":(await y(i(p,l),l),"written")})},async setCurrent(l,d){let{businessId:p,userId:b}=d;await y(o(l),{businessId:p,userId:b}),await u(l)},async deleteSession(l,d){return v(l,d)},async signOut(l){let d=await T(l),p=d!==void 0;return d?.account!==void 0&&(p=await v(l,d.account)),await u(l),p},async removeAccount(l,d){let p=!1,b;try{b=await P(l)}catch{}b!==void 0&&it(b,d)&&(p=await T(l)!==void 0);let x=await v(l,d);return await u(l),{removed:x,current:p}},async signOutAll(l){let d=await T(l),p=d!==void 0&&d.account===void 0,b=0;for(let x of await m()){let S=g(l,x);S!==void 0&&await v(l,S)&&(b+=1,p||=d?.account!==void 0&&it(d.account,S))}return await u(l),{signedIn:p,removed:b}},async listSessions(){return(await Promise.all(W.map(async d=>{try{return await C(d)===null?void 0:d}catch(p){if(p instanceof q&&p.code==="login_required")return d;throw p}}))).filter(d=>d!==void 0)},async readClientId(l){let d=(await w())[l];return O(d)?ie(d.clientId):void 0},async writeClientId(l,d){await y(c,{...await w(),[l]:{clientId:d}})},async forgetClientId(l){let d=await w();l in d&&await y(c,Object.fromEntries(Object.entries(d).filter(([p])=>p!==l)))}}}var eu=5e3,tu=(e,t)=>e.isTTY===!0&&t.isTTY===!0;function Ki(e=Ce(),t){let n=(i,s)=>wn(i,e,s),r=i=>{process.stderr.write(i)},o=i=>Bt({bearer:i}).getIdentity();return{store:e,loginDeps:Oi(e,i=>{r(`${i}
86
+ `)},o),identify:o,tokenProvider:n,isInteractive:()=>tu(process.stdin,process.stdout),...t!==void 0&&{pickAccount:t},authHeaderTimeouts:{requestTimeoutMs:eu},processEnv:process.env,writeStdout:i=>{process.stdout.write(i)},writeStderr:r,setExitCode:i=>{process.exitCode=i}}}function Vi(e){let{environment:t,message:n}=ot(e);if(t===void 0)throw new Error(n);return t}async function Wi(e,t,n){let r=await zt(e,n,t);if(!r.ok)throw new Error(r.message);return r.environment}var kn=(e,t)=>e?`${e} (${t})`:t,qi=(e,t)=>{let n=[t.fullName,t.email&&`<${t.email}>`].filter(Boolean).join(" ");return`Environment: ${e}
87
87
  User: ${n===""?t.userId:`${n} (${t.userId})`}
88
- Business: ${un(t.businessName,t.businessId)}
89
- `};function wi(e,t,{prefix:n="Error",oneLine:r=!1}={}){let o=Le(t),i=t instanceof Z&&t.hint!==void 0?`
88
+ Business: ${kn(t.businessName,t.businessId)}
89
+ `};function Gi(e,t,{prefix:n="Error",oneLine:r=!1}={}){let o=oe(t),i=t instanceof Z&&t.hint!==void 0?`
90
90
  ${t.hint}`:"";e.writeStderr(`${n}: ${r?o.replace(/\s+/g," ").trim():`${o}${i}`}
91
- `),e.setExitCode(1)}var xr=e=>async(t,n)=>{try{await e(t,n)}catch(r){wi(n,r)}},vr=(e,t)=>{e.writeStdout(`Signed in to ${t.environment}.
92
- `),e.writeStdout(bi(t.environment,t))},rt="browser",_e=({account:e,session:t})=>`${un(t?.businessName,e.businessId)} ${t?.email??`user ${e.userId}`}${t===void 0?" (can't be read)":""}`,gd=e=>[...e.map(({account:t,session:n,current:r})=>({key:pt(t),label:un(n?.businessName,t.businessId),description:[n?.email??t.userId,n===void 0?"(can't be read)":"",r?"(current)":""].filter(Boolean).join(" ")})),{key:rt,label:"Sign in with the browser"}],yd=(e,t)=>e===rt?rt:t.find(({account:n})=>pt(n)===e),bd=(e,{business:t,user:n})=>(e.businessId===t||e.businessName?.toLowerCase()===t.toLowerCase())&&(n===void 0||e.userId===n);function vi(e,t,n){let r=e.filter(({account:a})=>a.businessId===t),o=r.length>0?r:e.filter(({session:a})=>a?.businessName?.toLowerCase()===t.toLowerCase()),i=n===void 0?o:o.filter(({account:a})=>a.userId===n),[s]=i;return i.length===1&&s!==void 0?{kind:"one",account:s}:i.length===0?{kind:"none",candidates:[...e]}:{kind:"several",candidates:i}}var mi=e=>e.map(t=>`
93
- ${_e(t)}`).join(""),ft=({business:e,user:t})=>`--business ${be(e)}${t===void 0?"":` --user ${be(t)}`}`;function xi(e,t,n,r=vi(t,n.business,n.user)){if(r.kind==="one")return r.account;let o=ft(n);if(r.kind==="none")throw new Error(`No saved ${e} account matches ${o}. Saved accounts:${mi(r.candidates)}`);let[i]=r.candidates;throw i!==void 0&&r.candidates.every(({account:a})=>a.businessId===i.account.businessId)?new Error(`${o} matches several saved ${e} users of the same business. Pass --user too, for example \`${ft({business:i.account.businessId,user:i.account.userId})}\`:${r.candidates.map(a=>`
94
- --user ${be(a.account.userId)}: ${_e(a)}`).join("")}`):new Error(`${o} matches several saved ${e} accounts. Pass one of these business ids instead:${mi(r.candidates)}`)}function wd(e,t,n,r){if(n){r.writeStdout(`${JSON.stringify(t.map(({account:o,session:i,current:s})=>({businessId:o.businessId,userId:o.userId,businessName:i?.businessName??null,fullName:i?.fullName??null,email:i?.email??null,current:s,readable:i!==void 0})))}
91
+ `),e.setExitCode(1)}var Lr=e=>async(t,n)=>{try{await e(t,n)}catch(r){Gi(n,r)}},jr=(e,t)=>{e.writeStdout(`Signed in to ${t.environment}.
92
+ `),e.writeStdout(qi(t.environment,t))},ct="browser",$e=({account:e,session:t})=>`${kn(t?.businessName,e.businessId)} ${t?.email??`user ${e.userId}`}${t===void 0?" (can't be read)":""}`,nu=e=>[...e.map(({account:t,session:n,current:r})=>({key:st(t),label:kn(n?.businessName,t.businessId),description:[n?.email??t.userId,n===void 0?"(can't be read)":"",r?"(current)":""].filter(Boolean).join(" ")})),{key:ct,label:"Sign in with the browser"}],ru=(e,t)=>e===ct?ct:t.find(({account:n})=>st(n)===e),ou=(e,{business:t,user:n})=>(e.businessId===t||e.businessName?.toLowerCase()===t.toLowerCase())&&(n===void 0||e.userId===n);function zr(e,t,n){let r=e.filter(({account:a})=>a.businessId===t),o=r.length>0?r:e.filter(({session:a})=>a?.businessName?.toLowerCase()===t.toLowerCase()),i=n===void 0?o:o.filter(({account:a})=>a.userId===n),[s]=i;return i.length===1&&s!==void 0?{kind:"one",account:s}:i.length===0?{kind:"none",candidates:[...e]}:{kind:"several",candidates:i}}var Hi=e=>e.map(t=>`
93
+ ${$e(t)}`).join(""),Ji=(e,t)=>e==="env"?`${Tt}=${le(t)}`:`--user ${le(t)}`,at=({business:e,user:t,source:n})=>`${n==="env"?`${At}=${le(e)}`:`--business ${le(e)}`}${t===void 0?"":` ${Ji(n,t)}`}`;function Mr(e,t,n,r=zr(t,n.business,n.user)){if(r.kind==="one")return r.account;let o=at(n);if(r.kind==="none")throw new Error(`No saved ${e} account matches ${o}. Saved accounts:${Hi(r.candidates)}`);let[i]=r.candidates;if(i!==void 0&&r.candidates.every(({account:a})=>a.businessId===i.account.businessId)){let{source:a}=n;throw new Error(`${o} matches several saved ${e} users of the same business. ${a==="env"?`Set ${Tt}`:"Pass --user"} too, for example \`${at({business:i.account.businessId,user:i.account.userId,source:a})}\`:${r.candidates.map(c=>`
94
+ ${Ji(a,c.account.userId)}: ${$e(c)}`).join("")}`)}throw new Error(`${o} matches several saved ${e} accounts. ${n.source==="env"?`Set ${At} to`:"Pass"} one of these business ids instead:${Hi(r.candidates)}`)}async function zt(e,t,n){let r=async a=>{let c=[],g=await jt(e,async()=>(c=await a(),c));return g.ok?g:{...g,environments:c}};if(t===void 0||e!==void 0)return r(()=>n.listSessions());let o=await Promise.all(W.map(async a=>({environment:a,accounts:await n.listAccounts(a)}))),i=o.filter(({accounts:a})=>zr(a,t.business,t.user).kind!=="none").map(({environment:a})=>a),[s]=i;return i.length===1&&s!==void 0?{ok:!0,environment:s}:i.length>1?{ok:!1,problem:"several_sessions",message:`${at(t)} matches saved accounts in several environments; pass --env <env>: ${i.join(", ")}`,environments:i}:r(()=>Promise.resolve(o.filter(({accounts:a})=>a.length>0).map(({environment:a})=>a)))}var Mt=(e,t,n)=>Mr(e,t,n).account;function Ur(e,t){let n=It(e,t);if(!n.ok)throw new Error(n.message);return n.request}function iu(e,t,n,r){if(n){r.writeStdout(`${JSON.stringify(t.map(({account:o,session:i,current:s})=>({businessId:o.businessId,userId:o.userId,businessName:i?.businessName??null,fullName:i?.fullName??null,email:i?.email??null,current:s,readable:i!==void 0})))}
95
95
  `);return}if(t.length===0){r.writeStdout(`No saved accounts for ${e}.
96
- `);return}for(let o of t)r.writeStdout(`${_e(o)}${o.current?" (current)":""}
97
- `)}async function vd(e,t,n,r){if(t.business!==void 0){let o={business:t.business,user:t.user},i=vi(n,o.business,o.user);return i.kind==="none"?{kind:"not_saved",request:o}:xi(e,n,o,i)}return n.length===0?rt:r.pickAccount===void 0||!r.isInteractive()?(r.writeStderr(`Saved accounts for ${e} exist; pass --business <id> to switch without the browser, or --list to see them.
98
- `),rt):yd(await r.pickAccount(`Sign in to ${e}`,gd(n)),n)}function xd(e,t,n){let r=t.kind==="expired"?`The saved sign-in for ${_e(t.account)} has expired and was removed.`:`There's no saved ${e} account for ${JSON.stringify(t.request.business)}${t.request.user===void 0?"":` with user ${JSON.stringify(t.request.user)}`}.`,o=t.kind==="expired"?un(t.account.session?.businessName&&JSON.stringify(t.account.session.businessName),t.account.account.businessId):JSON.stringify(t.request.business),i=t.kind==="expired"?t.account.session?.email??t.account.account.userId:t.request.user,s=`the business ${o}${i===void 0?"":`, signed in as ${i}`}`;return n?`${r}
96
+ `);return}for(let o of t)r.writeStdout(`${$e(o)}${o.current?" (current)":""}
97
+ `)}async function su(e,t,n,r){if(t.business!==void 0){let o={business:t.business,user:t.user},i=zr(n,o.business,o.user);return i.kind==="none"?{kind:"not_saved",request:o}:Mr(e,n,o,i)}return n.length===0?ct:r.pickAccount===void 0||!r.isInteractive()?(r.writeStderr(`Saved accounts for ${e} exist; pass --business <id> to switch without the browser, or --list to see them.
98
+ `),ct):ru(await r.pickAccount(`Sign in to ${e}`,nu(n)),n)}function au(e,t,n){let r=t.kind==="expired"?`The saved sign-in for ${$e(t.account)} has expired and was removed.`:`There's no saved ${e} account for ${JSON.stringify(t.request.business)}${t.request.user===void 0?"":` with user ${JSON.stringify(t.request.user)}`}.`,o=t.kind==="expired"?kn(t.account.session?.businessName&&JSON.stringify(t.account.session.businessName),t.account.account.businessId):JSON.stringify(t.request.business),i=t.kind==="expired"?t.account.session?.email??t.account.account.userId:t.request.user,s=`the business ${o}${i===void 0?"":`, signed in as ${i}`}`;return n?`${r}
99
99
  A browser window is opening to sign in to Kizen ${e}. On the consent page, choose ${s}.
100
100
  `:`${r}
101
101
  Waiting for the user to sign in to Kizen ${e} in a browser window. Ask them to choose ${s}.
102
- `}function kd(e,t){if(t.kind==="expired"){let{account:n}=t.account;return{accepts:r=>Ee(r,n),requested:_e(t.account),retry:`${ye(e)} ${ft({business:n.businessId,user:n.userId})}`}}return{accepts:n=>bd(n,t.request),requested:ft(t.request),retry:`${ye(e)} ${ft(t.request)}`}}var ki=xr(async(e,t)=>{let n=gi(e.env??Me);if(e.json===!0&&e.list!==!0)throw new Error("--json only applies with --list.");if(e.user!==void 0&&e.business===void 0)throw new Error("--user only applies with --business.");if(e.list===!0&&e.business!==void 0)throw new Error("--list can't be combined with --business.");let r=await t.store.listAccounts(n);if(e.list===!0){wd(n,r,e.json===!0,t);return}let o=await vd(n,e,r,t);if(o===void 0){t.writeStderr(`Cancelled.
103
- `),t.setExitCode(1);return}if(o!==rt&&!("kind"in o)){let w=o,{account:C}=w;t.writeStderr(`Switching to ${_e(w)} on ${n}.
104
- `);let E=await fi(n,C,{store:t.store,provider:t.tokenProvider(n,{account:C}),identify:t.identify});if(E!==void 0){vr(t,E);return}o={kind:"expired",account:w}}if(o===rt){t.writeStderr(`Signing in to ${n}.
105
- `),vr(t,await wr(n,t.loginDeps,{interactive:t.isInteractive()}));return}let i=t.isInteractive(),s=kd(n,o);t.writeStderr(xd(n,o,i));let a=await wr(n,t.loginDeps,{makeCurrent:s.accepts,interactive:i});if(s.accepts(a)){vr(t,a);return}let c=await t.store.readSession(n).catch(()=>null),g=c!==null&&Ee(c,a),u=_e({account:a,session:a,current:!1}),h=i?"You":"The user",v=g?`That's already the current ${n} account; its saved session was updated.`:`It was saved, but it isn't the current ${n} account.`,p=g?"":`To use it, run \`${ye(n)} ${ft({business:a.businessId,user:a.userId})}\`. `,l=i?"To try again":"To have them try again";t.writeStderr(`${h} signed in as ${u}, not ${s.requested}. ${v}
106
- ${p}${l}, run \`${s.retry}\`.
107
- `),t.setExitCode(1)}),Ci=xr(async(e,t)=>{if(e.all===!0&&e.business!==void 0)throw new Error("--all can't be combined with --business.");if(e.user!==void 0&&e.business===void 0)throw new Error("--user only applies with --business.");let n=await nt(e.env,()=>t.store.listSessions());if(!n.ok){if(n.problem!=="not_signed_in")throw new Error(n.message);if(e.business!==void 0)throw new Error("Pass --env <env> with --business to remove a saved account.");if(e.all===!0)throw new Error("Pass --env <env> with --all to remove every saved account.");t.writeStdout(`Not signed in.
102
+ `}function cu(e,t){if(t.kind==="expired"){let{account:n}=t.account;return{accepts:r=>it(r,n),requested:$e(t.account),retry:`${xe(e)} ${at({business:n.businessId,user:n.userId})}`}}return{accepts:n=>ou(n,t.request),requested:at(t.request),retry:`${xe(e)} ${at(t.request)}`}}var Yi=Lr(async(e,t)=>{let n=Vi(e.env??Ue);if(e.json===!0&&e.list!==!0)throw new Error("--json only applies with --list.");if(e.user!==void 0&&e.business===void 0)throw new Error("--user only applies with --business.");if(e.list===!0&&e.business!==void 0)throw new Error("--list can't be combined with --business.");let r=await t.store.listAccounts(n);if(e.list===!0){iu(n,r,e.json===!0,t);return}let o=await su(n,e,r,t);if(o===void 0){t.writeStderr(`Cancelled.
103
+ `),t.setExitCode(1);return}if(o!==ct&&!("kind"in o)){let w=o,{account:k}=w;t.writeStderr(`Switching to ${$e(w)} on ${n}.
104
+ `);let _=await Fi(n,k,{store:t.store,provider:t.tokenProvider(n,{account:k}),identify:t.identify});if(_!==void 0){jr(t,_);return}o={kind:"expired",account:w}}if(o===ct){t.writeStderr(`Signing in to ${n}.
105
+ `),jr(t,await Rr(n,t.loginDeps,{interactive:t.isInteractive()}));return}let i=t.isInteractive(),s=cu(n,o);t.writeStderr(au(n,o,i));let a=await Rr(n,t.loginDeps,{makeCurrent:s.accepts,interactive:i});if(s.accepts(a)){jr(t,a);return}let c=await t.store.readSession(n).catch(()=>null),g=c!==null&&it(c,a),m=$e({account:a,session:a,current:!1}),h=i?"You":"The user",y=g?`That's already the current ${n} account; its saved session was updated.`:`It was saved, but it isn't the current ${n} account.`,f=g?"":`To use it, run \`${xe(n)} ${at({business:a.businessId,user:a.userId})}\`. `,u=i?"To try again":"To have them try again";t.writeStderr(`${h} signed in as ${m}, not ${s.requested}. ${y}
106
+ ${f}${u}, run \`${s.retry}\`.
107
+ `),t.setExitCode(1)}),Xi=Lr(async(e,t)=>{if(e.all===!0&&e.business!==void 0)throw new Error("--all can't be combined with --business.");if(e.user!==void 0&&e.business===void 0)throw new Error("--user only applies with --business.");let n=await jt(e.env,()=>t.store.listSessions());if(!n.ok){if(n.problem!=="not_signed_in")throw new Error(n.message);if(e.business!==void 0)throw new Error("Pass --env <env> with --business to remove a saved account.");if(e.all===!0)throw new Error("Pass --env <env> with --all to remove every saved account.");t.writeStdout(`Not signed in.
108
108
  `);return}let{environment:r}=n;if(e.business!==void 0){let i=await t.store.listAccounts(r);if(i.length===0){t.writeStdout(`No saved accounts for ${r}.
109
- `);return}let s=xi(r,i,{business:e.business,user:e.user}),{removed:a,current:c}=await t.store.removeAccount(r,s.account);t.writeStdout(a||c?`Removed the saved ${r} account ${_e(s)} from this machine.${c?` You're no longer signed in to ${r}.`:""}
110
- `:`No saved ${r} account ${_e(s)}.
109
+ `);return}let s=Mr(r,i,{business:e.business,user:e.user}),{removed:a,current:c}=await t.store.removeAccount(r,s.account);t.writeStdout(a||c?`Removed the saved ${r} account ${$e(s)} from this machine.${c?` You're no longer signed in to ${r}.`:""}
110
+ `:`No saved ${r} account ${$e(s)}.
111
111
  `);return}if(e.all===!0){let{signedIn:i,removed:s}=await t.store.signOutAll(r);t.writeStdout(i||s>0?`Signed out of ${r}. Removed ${String(s)} saved ${s===1?"account":"accounts"} from this machine.
112
112
  `:`No saved accounts for ${r}.
113
113
  `);return}let o=await t.store.signOut(r);t.writeStdout(o?`Signed out of ${r}. The session was removed from this machine.
114
114
  `:`Not signed in to ${r}.
115
- `)}),Si=xr(async(e,t)=>{let n=await yi(e.env,t.store);t.writeStdout(bi(n,await t.identify(t.tokenProvider(n))))});function Cd(e){let t;try{t=new URL(e).origin}catch{throw new Error("CLAUDE_CODE_MCP_SERVER_URL is not a valid URL, so auth-header won't send a token.")}let n=W.find(r=>ut(r)===t);if(n===void 0)throw new Error(`No Kizen environment matches the MCP server ${t}, so auth-header won't send it a token.`);return{environment:n,origin:t}}async function Sd(e,t){let n=e===void 0?void 0:gi(e),r=t.processEnv.CLAUDE_CODE_MCP_SERVER_URL;if(r!==void 0&&r!==""){let o=Cd(r);if(n!==void 0&&n!==o.environment)throw new Error(`--env ${n} doesn't match the MCP server ${o.origin} (${o.environment}), so auth-header won't send it a token.`);return o.environment}return n??yi(void 0,t.store)}var Pi=async(e,t)=>{let n;try{let r=await Sd(e.env,t),{requestTimeoutMs:o}=t.authHeaderTimeouts,i=await t.tokenProvider(r,{requestTimeoutMs:o}).getAccessToken();n=`${JSON.stringify({Authorization:`Bearer ${i}`})}
116
- `}catch(r){wi(t,r,{prefix:"appbuilder auth-header",oneLine:!0});return}t.writeStdout(n)};import{render as Id}from"ink";import{useMemo as Pd,useState as Ed}from"react";import{Box as kr,Text as ot,useInput as _d}from"ink";var pn=(e,t,n)=>Math.min(Math.max(e,t),n);function fn(e,t,n,r={}){if(t<=0)return 0;let o=pn(Math.trunc(e)||0,0,t-1),i=c=>r.disabled?.[c]!==!0;if(n===0)return o;let s=n>0?1:-1;if(Math.abs(n)===1){for(let c=1;c<=t;c++){let g=((o+s*c)%t+t)%t;if(i(g))return g}return o}let a=pn(o+Math.trunc(n),0,t-1);for(let c=a;c>=0&&c<t;c+=s)if(i(c))return c;for(let c=a-s;c>=0&&c<t;c-=s)if(i(c))return c;return o}function Ei(e,t,n=10){if(t<=0)return{start:0,end:0};let r=Math.max(1,Math.floor(n));if(t<=r)return{start:0,end:t};let o=pn(Math.trunc(e)||0,0,t-1),i=pn(o-Math.floor(r/2),0,t-r);return{start:i,end:i+r}}import{jsx as it,jsxs as Sr}from"react/jsx-runtime";var Td="\u2191/\u2193 to move, Enter to select, Esc to cancel",Cr=10,Ad=e=>{let t=fn(0,e.length,0);if(e[t]?.disabled!==!0)return t;let n=e.findIndex(r=>r.disabled!==!0);return n===-1?t:n},Te=({title:e,items:t,onSelect:n,onCancel:r,hint:o=Td})=>{let[i,s]=Ed(()=>Ad(t)),a=Pd(()=>t.map(p=>p.disabled===!0),[t]),c=fn(i,t.length,0);_d((p,l)=>{let w=C=>{s(fn(c,t.length,C,{disabled:a}))};if(l.upArrow||p==="k")w(-1);else if(l.downArrow||p==="j")w(1);else if(l.pageUp)w(-Cr);else if(l.pageDown)w(Cr);else if(l.return){let C=t[c];C!==void 0&&C.disabled!==!0&&n(C,c)}else l.escape&&r?.()});let{start:g,end:u}=Ei(c,t.length,Cr),h=g,v=t.length-u;return Sr(kr,{flexDirection:"column",gap:1,children:[it(ot,{bold:!0,children:e}),Sr(kr,{flexDirection:"column",children:[h>0&&it(ot,{dimColor:!0,children:` \u2191 ${String(h)} more`}),t.slice(g,u).map((p,l)=>{let C=g+l===c,E=p.disabled===!0,x=C&&!E;return Sr(kr,{gap:2,children:[it(ot,{...x&&{color:"cyan"},dimColor:E,children:C?"\u276F":" "}),it(ot,{bold:x,dimColor:E,...x&&{color:"cyan"},children:p.label}),p.description!==void 0&&it(ot,{dimColor:!0,children:p.description})]},p.key)}),v>0&&it(ot,{dimColor:!0,children:` \u2193 ${String(v)} more`})]}),it(ot,{dimColor:!0,children:o})]})};import{jsx as $d}from"react/jsx-runtime";var _i=async(e,t)=>{let n,r=Id($d(Te,{title:e,items:t,onSelect:o=>{n=o.key,r.unmount()},onCancel:()=>{r.unmount()}}));return await r.waitUntilExit(),n};var Nd=[{name:"login",description:"Sign in to Kizen in the browser, or switch to a saved account, and store the session on this machine",env:"environment to sign in to (default: go)",options:[["--business <id-or-name>","switch to the saved account with this business id, or business name (ignoring case); signs in with the browser if none matches or it expired"],["--user <userId>","with --business, pick the saved account of this user id"],["--list","list the saved accounts for the environment and exit"],["--json","with --list, print the accounts as JSON"]],run:ki},{name:"logout",description:"Remove the stored session from this machine",env:"environment to sign out of (default: the only signed-in one)",options:[["--all","also remove every other saved account for the environment"],["--business <id-or-name>","remove only this saved account, by business id or name (ignoring case)"],["--user <userId>","with --business, remove the saved account of this user id"]],run:Ci},{name:"whoami",description:"Show the user and business of the stored session",env:"environment to check (default: the only signed-in one)",run:Si},{name:"auth-header",description:"Print an Authorization header for the stored session as JSON (for a Claude Code MCP headersHelper)",env:"environment to use; must match CLAUDE_CODE_MCP_SERVER_URL when that is set (default: the environment matching it, else the only signed-in one)",run:Pi}];function Ti(e){for(let{name:t,description:n,env:r,options:o=[],run:i}of Nd){let s=e.command(t).description(n).option("--env <env>",r);for(let[a,c]of o)s.option(a,c);s.action(async a=>{await i(a,hi(void 0,_i))})}}import{createElement as cf}from"react";import{render as lf}from"ink";import{PluginValidationError as df}from"@kizenapps/packager";import{spawn as Dd}from"child_process";import{platform as Ai}from"process";function Rd(){return Ai==="darwin"?[{cmd:"pbcopy",args:[]}]:Ai==="win32"?[{cmd:"clip",args:[]}]:[{cmd:"wl-copy",args:[]},{cmd:"xclip",args:["-selection","clipboard"]},{cmd:"xsel",args:["--clipboard","--input"]}]}var Od=2e3;function Bd(e,{cmd:t,args:n}){return new Promise(r=>{let o;try{o=Dd(t,n,{stdio:["pipe","ignore","ignore"]})}catch{r(!1);return}let i=o,s=!1;function a(g){s||(s=!0,clearTimeout(c),r(g))}let c=setTimeout(()=>{i.kill(),a(!1)},Od);c.unref(),i.on("error",()=>{a(!1)}),i.on("close",g=>{a(g===0)}),i.stdin.on("error",()=>{a(!1)});try{i.stdin.end(e)}catch{a(!1)}})}async function mn(e){for(let t of Rd())if(await Bd(e,t))return!0;return!1}import{BLOCKS_DIRECTORY_NAME as gu,CONFIG_FILE_NAME as yu,MANIFEST_FILE_NAME as bu,sanitizeToAPIName as wu}from"@kizenapps/packager";var hn=["min_w","max_w","min_h","max_h","default_w","default_h"];import{createHash as Fd}from"crypto";import{mkdir as jd,readFile as Ld,writeFile as Md}from"fs/promises";import{dirname as zd,join as Ni}from"path";var Pr="appbuilder:",st=".kizenapp/pushes.json",Ud=["environment","businessId","pluginApiName","blockApiName","dashboardId","dashletId","contentHash","pushedAt"];function Er(e){return typeof e=="number"&&Number.isFinite(e)}function gn(e,t,n){return Math.min(Math.max(e,t),n)}function Hd(e){let t={...e};return delete t.custom_object,t}function Di(e,t){return`${Pr}${e}/${t}`}function Ri(e){if(!e.startsWith(Pr))return null;let t=e.slice(Pr.length).split("/");if(t.length!==2)return null;let[n,r]=t;return!n||!r?null:{pluginApiName:n,blockApiName:r}}function Oi(e){let t={};for(let n of hn){let r=e[n];Er(r)&&(t[n]=r)}return t}function Bi(e){return typeof e.host_chrome=="boolean"?{host_chrome:e.host_chrome}:{}}var Fi=e=>Object.entries(e).map(([t,n])=>({name:t,script:n}));function Vd(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:Fi(e.event_scripts)}}function Tr(e){return e.length>0?{views:e.map(Vd)}:{}}function ji(e,t=[]){return{kind:"custom_code",version:1,name:e.name,script:e.script,styles:e.styles,event_scripts:Fi(e.event_scripts),...Oi(e),...Bi(e),...Tr(t)}}function Kd(e){return{object_id:e.objectId,entity_type:"static_content",report_type:"html",chart_type:"html",content:e.content,fe_extra_info:{}}}function Wd(e){let t=0;for(let n of e){let r=n.layout;if(!O(r))continue;let{y:o,h:i}=r;!Er(o)||!Er(i)||(t=Math.max(t,o+i))}return t}function qd(e,t,n){let r=gn(t.default_w??t.min_w??6,t.min_w??1,t.max_w??12),o=gn(t.default_h??t.min_h??3,t.min_h??1,t.max_h??99);return{i:n,x:0,y:Wd(e),w:gn(r,2,12),h:gn(o,1,99)}}function Li(e){return{name:Di(e.pluginApiName,e.blockApiName),layout:qd(e.dashlets,e.content,e.layoutId),config:Kd({content:e.content,objectId:e.objectId})}}function Mi(e,t){let n=e.config;return{config:{...Hd(O(n)?n:{}),content:t}}}function zi(e){let t=e.config;return O(t)?t.content:void 0}function mt(e){let t=e.config;if(!O(t)||t.chart_type!=="html")return!1;let n=t.content;return O(n)&&n.kind==="custom_code"}function Ui(e){return e.dashlets.filter(mt)}function yn(e){let t=zi(e);return O(t)&&typeof t.name=="string"?t.name:e.name}var He=e=>typeof e=="string"?e:"";function Hi(e){return Array.isArray(e)?e.filter(O).map(t=>({name:He(t.name),script:He(t.script)})):O(e)?Object.entries(e).map(([t,n])=>({name:t,script:He(n)})):[]}function _r(e){if(Array.isArray(e))return e.map(_r);if(O(e)){let t={};for(let n of Object.keys(e).sort())t[n]=_r(e[n]);return t}return e}function Vi(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e).trim():""}function Jd(e){return Array.isArray(e)?e.filter(O).map(t=>({api_name:He(t.api_name),name:Vi(t.name),type:He(t.type),script:He(t.script),html:He(t.html),css:He(t.css),event_scripts:Hi(t.event_scripts)})):[]}function Ar(e){let t=O(e)?e:{},n=Jd(t.views),r={name:Vi(t.name),script:typeof t.script=="string"?t.script:"",styles:typeof t.styles=="string"?t.styles:"",event_scripts:Hi(t.event_scripts),...Oi(t),...Bi(t),...n.length>0&&{views:n}};return Fd("sha256").update(JSON.stringify(_r(r))).digest("hex")}function Ki(e){let{entry:t}=e;if(t?.dashboardId===e.dashboardId){let i=e.dashlets.find(s=>s.id===t.dashletId);if(i&&mt(i))return{kind:"map",dashlet:i,entry:t}}let n=Di(e.pluginApiName,e.blockApiName),r=e.dashlets.filter(i=>i.name===n&&mt(i)),[o]=r;return r.length===1&&o?{kind:"name",dashlet:o}:r.length>1?{kind:"ambiguous",dashlets:r}:{kind:"none"}}function Wi(e,t){return t?.dashletId!==e.id?!1:Ar(zi(e))!==t.contentHash}function Ir(e,t){return e.environment===t.environment&&e.businessId===t.businessId&&e.pluginApiName===t.pluginApiName&&e.blockApiName===t.blockApiName}function $r(e,t){return e.find(n=>Ir(n,t))}function qi(e,t){let n=e.findIndex(r=>Ir(r,t));return n===-1?[...e,t]:e.map((r,o)=>o===n?t:r)}function Ji(e,t){return e.filter(n=>!Ir(n,t))}function Gd(e){if(!O(e))return null;for(let n of Ud)if(typeof e[n]!="string")return null;let t=e;return{environment:t.environment,businessId:kt(t.businessId),pluginApiName:t.pluginApiName,blockApiName:t.blockApiName,dashboardId:t.dashboardId,dashletId:t.dashletId,contentHash:t.contentHash,pushedAt:t.pushedAt}}var Ii=e=>Date.parse(e.pushedAt)||0;function Yd(e){let t=new Map;for(let n of e){let r=[n.environment,n.businessId,n.pluginApiName,n.blockApiName].join("\0"),o=t.get(r);(o===void 0||Ii(n)>Ii(o))&&t.set(r,n)}return[...t.values()]}var $i=e=>e instanceof Error?e.message:String(e);async function Gi(e){let t;try{t=await Ld(Ni(e,st),"utf8")}catch(r){if(nn(r))return[];throw new Error(`Couldn't read ${st}: ${$i(r)}. Fix its permissions, or delete it to start a fresh push map.`)}let n;try{n=JSON.parse(t)}catch(r){throw new Error(`${st} is not valid JSON (${$i(r)}). Fix it, or delete it to start a fresh push map.`)}if(!Array.isArray(n))throw new Error(`${st} must contain a JSON array of push entries. Fix it, or delete it to start a fresh push map.`);return Yd(n.map(Gd).filter(r=>r!==null))}async function Yi(e,t){let n=Ni(e,st);await jd(zd(n),{recursive:!0}),await Md(n,`${JSON.stringify(t,null,2)}
117
- `,"utf8")}var Xd={generic_dashboard:"dashboard",homepage:"homepage",chart_group:"chart_group"},Zd={dashboard:"generic_dashboard",homepage:"homepage",chart_group:"chart_group"};function Nr(e){return Xd[e]}function Xi(e){return Zd[e]}function Zi(e){let t=e.appBaseUrl.replace(/\/+$/,""),n=e.dashboardId;return e.surface==="homepage"?`${t}/home/${n}`:e.surface==="chart_group"&&e.customObject?e.customObject.fetchUrl==="client"?`${t}/clients/charts/${n}`:`${t}/custom-objects/${e.customObject.id}/charts/${n}`:`${t}/dashboard/${n}`}import{mkdir as su,writeFile as au}from"fs/promises";import{join as cu}from"path";import{PluginValidationError as lu,packagePlugin as du,parseManifestFromFiles as uu,transformDeployablePlugin as pu,transformFiles as fu,validatePluginApp as mu}from"@kizenapps/packager";import{readdir as Qd,readFile as Qi}from"fs/promises";import{join as es,relative as eu}from"path";var tu=new Set([".png",".svg"]),nu=new Set([".kzn"]),ru=new Set([".DS_Store"]),bn=new Set(["node_modules",".git",".kizenapp",".copilot-docs",".github",".claude","__pycache__"]),ou=8e3;function iu(e){return e.subarray(0,ou).includes(0)}async function ts(e,t){let n=await Qd(e,{withFileTypes:!0}),r=[];for(let o of n)if(o.isDirectory()){if(bn.has(o.name))continue;r.push(...await ts(es(e,o.name),t))}else o.isFile()&&(ru.has(o.name)||r.push(es(e,o.name)));return r}async function wn(e,{detectBinaryByContent:t=!1}={}){let n=await ts(e,e);return Promise.all(n.map(async r=>{let o=eu(e,r).split("\\").join("/"),i=o.lastIndexOf("."),s=i>=0?o.slice(i).toLowerCase():"";if(tu.has(s)){let c=await Qi(r);return{path:o,content:"",base64Image:c.toString("base64")}}let a=await Qi(r);return nu.has(s)||t&&iu(a)?{path:o,content:"",binaryData:a}:{path:o,content:a.toString("utf-8")}}))}var hu=(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 Dr(e,t){t?.("reading-files");let n=await wn(e);t?.("validating");let r=mu(n);if(r.some(c=>c.severity==="error"))throw new lu(r);t?.("minifying");let o=await fu(n);t?.("packaging");let i=uu(o),s=du(o,i),a=Object.values(s).map(pu);return{files:n,deployable:a,issues:r}}async function vn(e,t,n){await su(t,{recursive:!0});let{files:r,deployable:o}=await Dr(e,n);n?.("writing-bundle");let i=o.map(g=>{let u=g.release_notes_directory?.replace(/\/$/,""),h=u?r.filter(v=>v.path.startsWith(u+"/")&&v.path.endsWith(".md")&&v.content).map(v=>({version:v.path.slice(v.path.lastIndexOf("/")+1,-3),notes:v.content})).sort((v,p)=>p.version.localeCompare(v.version,void 0,{numeric:!0})):[];return hu(g,h)}),s=JSON.stringify(i,null,2),a=(g,u)=>g==="allReleaseNotes"?void 0:u,c=Buffer.byteLength(JSON.stringify(i,a,2),"utf-8");return await au(cu(t,"bundle.json"),s,"utf-8"),{bundleSize:c}}var os=["min_w","max_w","min_h","max_h"],is=[["min_w","max_w"],["min_h","max_h"]],xn={default_w:["min_w","max_w"],default_h:["min_h","max_h"]},vu=Object.keys(xn),ss=[...hn,"host_chrome"],xu=["\0","{__ref:"],Rr="views",Or=class extends Error{reason;available;field;constructor(t,n,r={}){super(n),this.name="BlockExportError",this.reason=t,this.available=r.available??[],this.field=r.field}};function ku(e){let t=new Set(e.map(n=>n.pluginApiName)).size>1;return e.map(n=>t?`${n.pluginApiName}/${n.apiName}`:n.apiName).join(", ")}function Cu(e,t){let n=e.flatMap(s=>s.artifacts.custom_blocks.map(a=>({block:a,pluginApiName:s.api_name}))),r=n.map(({block:s,pluginApiName:a})=>({pluginApiName:a,apiName:s.api_name}));if(n.length===0)return{ok:!1,reason:"no_blocks",available:r};if(t===void 0){let[s]=n;return n.length===1&&s?{ok:!0,...s}:{ok:!1,reason:"ambiguous",available:r}}let o=n.filter(({block:s})=>s.api_name===t),[i]=o;return i?o.length>1?{ok:!1,reason:"ambiguous",available:o.map(({block:s,pluginApiName:a})=>({pluginApiName:a,apiName:s.api_name}))}:{ok:!0,...i}:{ok:!1,reason:"not_found",available:r}}var ns=e=>typeof e=="number"&&Number.isInteger(e)&&e>0,$t=e=>xu.some(t=>e.includes(t));function Su(e){let t=e,{name:n,script:r,styles:o,event_scripts:i}=t;if(typeof r!="string"||!r.trim())return"script";if(n!==void 0&&typeof n!="string")return"name";if(o!==void 0&&typeof o!="string")return"styles";if(i!==void 0){if(!O(i))return"event_scripts";let u=Object.entries(i).find(([h,v])=>typeof v!="string"||$t(h)||$t(v));if(u)return`event_scripts.${u[0]}`}let s=[["name",n],["script",r],["styles",o]].find(([,u])=>typeof u=="string"&&$t(u));if(s)return s[0];let a=os.find(u=>t[u]!==void 0&&!ns(t[u]));if(a)return a;let c=is.find(([u,h])=>{let v=t[u],p=t[h];return typeof v=="number"&&typeof p=="number"&&v>p});if(c)return c[0];let g=vu.find(u=>{let h=t[u];if(h===void 0)return!1;if(typeof h!="number"||!ns(h))return!0;let[v,p]=xn[u],l=t[v],w=t[p];return typeof l=="number"&&h<l||typeof w=="number"&&h>w});if(g)return g;if(t.host_chrome!==void 0&&typeof t.host_chrome!="boolean")return"host_chrome"}var Pu=["api_name","name","script","html","css"],rs=e=>typeof e!="string"||$t(e);function Eu(e){for(let t of e){let n=t,r=typeof n.api_name=="string"?n.api_name:String(n.api_name),o=Pu.find(a=>rs(n[a]));if(o)return{view:r,field:o};let i=n.event_scripts;if(!O(i))return{view:r,field:"event_scripts"};let s=Object.entries(i).find(([a,c])=>$t(a)||rs(c));if(s)return{view:r,field:`event_scripts.${s[0]}`}}}var _u=({view:e,field:t})=>`views.${e}.${t}`,Tu=(e,t)=>`Block "${e}" can't carry view ${JSON.stringify(t.view)}: its ${t.field} must be a string without NUL characters or "{__ref:".`,Au=(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 n=is.find(([r])=>r===t);if(n)return`Block "${e}" has an invalid ${t}: it must be a positive integer no greater than ${n[1]}.`;if(os.includes(t))return`Block "${e}" has an invalid ${t}: it must be a positive integer.`;if(t in xn){let[r,o]=xn[t];return`Block "${e}" has an invalid ${t}: it must be a positive integer between ${r} and ${o}.`}return`Block "${e}" has an invalid ${t}: it must be a string without NUL characters or "{__ref:".`},Iu=({reason:e,available:t},n,r)=>{let o=ku(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 "${n??""}". Available blocks: ${o}`:n===void 0?`This plugin has several blocks; pass the api_name of the one to ${r}: ${o}`:`More than one plugin has a block with api_name "${n}": ${o}`},$u=e=>{try{let t=JSON.parse(e);return O(t)?t:void 0}catch{return}},as=e=>{let t=e.find(i=>i.path===bu),n=t?JSON.parse(t.content):[],r=Array.isArray(n)?n:[n],o=new Map;for(let i of r)O(i)&&typeof i.api_name=="string"&&typeof i.entry=="string"&&o.set(i.api_name,i.entry);return o},cs=(e,t)=>{let n=rn(e);return n===""?t:`${n}/${t}`},ls=(e,t,n)=>{let r=`${cs(t,n)}/`,o=new Set,i=[];for(let s of e){if(!s.path.startsWith(r)||s.path.endsWith(".DS_Store"))continue;let[a,c,...g]=s.path.slice(r.length).split("/");if(a&&(o.add(a),c===yu&&g.length===0)){let u=$u(s.content);u&&i.push([a,u])}}return{directories:o,configs:i}},ds=(e,t)=>typeof e.api_name=="string"&&e.api_name!==""?e.api_name:wu(t),Nu=(e,t)=>{let n=new Map;for(let[r,o]of ls(e,t,gu).configs){let i=ds(o,r),s={};for(let a of ss)o[a]!==void 0&&(s[a]=o[a]);n.set(i,s)}return n},Du=(e,t={})=>({...Object.fromEntries(Object.entries(e).filter(([r])=>!ss.includes(r))),...t});function Ru(e,t){let n=as(t);return e.map(r=>{let o=n.get(r.api_name),i=o===void 0?new Map:Nu(t,o);return{...r,artifacts:{...r.artifacts,custom_blocks:r.artifacts.custom_blocks.map(s=>Du(s,i.get(s.api_name)))}}})}var us=(e,t)=>JSON.stringify([String(e),String(t)]),Ou=(e,t)=>{let{directories:n,configs:r}=ls(e,t,Rr),o=new Map(r),i=new Set;for(let s of n){let a=o.get(s)??{};i.add(us(ds(a,s),a.name||s))}return i},Bu=(e,t)=>e.api_name.localeCompare(t.api_name)||String(e.name).localeCompare(String(t.name)),Fu="appbuilder/views-unmatched";function ju(e,t){let n=as(t),r={},o=[];for(let i of e){let s=n.get(i.api_name),a=s===void 0?new Set:Ou(t,s),c=i.artifacts.routable_pages.filter(g=>a.has(us(g.api_name,g.name))).sort(Bu);c.length!==a.size&&s!==void 0&&o.push({rule:Fu,severity:"warning",message:`Found ${String(a.size)} ${Rr}/ components but matched ${String(c.length)} packaged views; the pushed block carries only the matched ones.`,path:cs(s,Rr),pluginApiName:i.api_name}),r[i.api_name]=c}return{views:r,warnings:o}}function Lu(e,t){return Object.hasOwn(e,t)?e[t]??[]:[]}function ps(e){return{...e.block,...Tr(e.views)}}async function Br(e){let{files:t,deployable:n,issues:r}=await Dr(e),o=ju(n,t);return{deployable:Ru(n,t),views:o.views,warnings:[...r.filter(i=>i.severity==="warning"),...o.warnings]}}function Fr({deployable:e,views:t,warnings:n},r,o){let i=Cu(e,r);if(!i.ok)return{ok:!1,reason:i.reason,message:Iu(i,r,o),available:i.available};let s=Su(i.block);if(s!==void 0)return{ok:!1,reason:"invalid_block",message:Au(i.block.api_name,s),available:[],field:s};let a=Lu(t,i.pluginApiName),c=Eu(a);return c!==void 0?{ok:!1,reason:"invalid_block",message:Tu(i.block.api_name,c),available:[],field:_u(c)}:{ok:!0,value:{block:i.block,pluginApiName:i.pluginApiName,views:a,warnings:n}}}async function fs(e,t){let n=Fr(await Br(e),t,"export");if(!n.ok)throw new Or(n.reason,n.message,n);return n.value}var jr=(e,t,n)=>`${String(e)} ${e===1?t:n}`,Lr=e=>{let t=new Map;for(let n of e){let r=n.path??n.pluginApiName??"general",o=t.get(r)??[];o.push(n),t.set(r,o)}return t},Mu=e=>{let t=e.filter(o=>o.severity==="error").length,n=e.length-t;if(t===0)return`\u26A0 ${jr(n,"validation warning","validation warnings")}`;let r=`\u2717 ${jr(t,"validation error","validation errors")}`;return n===0?r:`${r}, ${jr(n,"warning","warnings")}`};function Ae(e){if(e.length===0)return"";let t=[...Lr(e)].map(([n,r])=>[n,...r.map(o=>` ${o.severity==="error"?"\u2717":"\u26A0"} ${o.message} (${o.rule})`)].join(`
118
- `));return[Mu(e),...t].join(`
119
-
120
- `)}import{randomUUID as gp}from"crypto";import{join as yp}from"path";import{PluginValidationError as bp}from"@kizenapps/packager";import{mkdir as zu,readFile as Uu,writeFile as Hu}from"fs/promises";import{join as ms}from"path";async function we(e){try{let t=await Uu(ms(e,"config.json"),"utf-8");return JSON.parse(t)}catch{return{}}}async function Ve(e,t){await zu(e,{recursive:!0}),await Hu(ms(e,"config.json"),JSON.stringify(t,null,2),"utf-8")}import*as ht from"fs";import*as hs from"path";var Vu=[".kizenapp/",".copilot-docs/"];function ve(e){let t=hs.join(e,".gitignore"),n="";ht.existsSync(t)&&(n=ht.readFileSync(t,"utf8"));let r=new Set(n.split(`
121
- `).map(a=>a.trim())),o=Vu.filter(a=>!r.has(a)&&!r.has(a.replace(/\/$/,"")));if(o.length===0)return;let i=o.join(`
115
+ `)}),Zi=Lr(async(e,t)=>{let n=Ur(e,t.processEnv),r=await Wi(e.env,t.store,n),o=n===void 0?void 0:Mt(r,await t.store.listAccounts(r),n);t.writeStdout(qi(r,await t.identify(t.tokenProvider(r,o===void 0?void 0:{account:o}))))});function lu(e){let t;try{t=new URL(e).origin}catch{throw new Error("CLAUDE_CODE_MCP_SERVER_URL is not a valid URL, so auth-header won't send a token.")}let n=W.find(r=>ze(r)===t);if(n===void 0)throw new Error(`No Kizen environment matches the MCP server ${t}, so auth-header won't send it a token.`);return{environment:n,origin:t}}async function du(e,t){let n=e===void 0?void 0:Vi(e),r=t.processEnv.CLAUDE_CODE_MCP_SERVER_URL;if(r!==void 0&&r!==""){let o=lu(r);if(n!==void 0&&n!==o.environment)throw new Error(`--env ${n} doesn't match the MCP server ${o.origin} (${o.environment}), so auth-header won't send it a token.`);return o.environment}return n??Wi(void 0,t.store)}function uu(e){let{business:t,user:n}=e;if(!(t===void 0&&n===void 0)){if(t===void 0||n===void 0)throw new Error("auth-header takes --business and --user together.");return{businessId:t,userId:n}}}var Qi=async(e,t)=>{let n;try{let r=uu(e),o=await du(e.env,t),{requestTimeoutMs:i}=t.authHeaderTimeouts,s=await t.tokenProvider(o,{requestTimeoutMs:i,...r!==void 0&&{account:r}}).getAccessToken();n=`${JSON.stringify({Authorization:`Bearer ${s}`})}
116
+ `}catch(r){Gi(t,r,{prefix:"appbuilder auth-header",oneLine:!0});return}t.writeStdout(n)};var Cn="appbuilder admin",fu={env:["--env","<env>"],business:["--business","<id-or-name>"],user:["--user","<userId>"]},es=["-h","--help"],mu="--force";function hu(e){let t={},n=0,r=i=>({kind:"run",env:t.env,...t.business!==void 0&&{business:t.business},...t.user!==void 0&&{user:t.user},args:i});e:for(;n<e.length;){let i=e[n]??"";if(i==="--")return r(e.slice(n+1));if(es.includes(i))return{kind:"help"};for(let[s,[a,c]]of Object.entries(fu))if(i===a||i.startsWith(`${a}=`)){let g=i===a?e[n+1]:i.slice(a.length+1);if(g===void 0||g==="")return{kind:"error",message:`option '${a} ${c}' argument missing`};t[s]=g,n+=i===a?2:1;continue e}break}let o=e.slice(n);if(o[0]==="init"){let i=o.slice(1);return i.length===0?{kind:"init",force:!1}:i.length===1&&i[0]===mu?{kind:"init",force:!0}:i.length===1&&es.includes(i[0]??"")?{kind:"init-help"}:{kind:"error",message:`admin init takes only --force, but got: ${i.map(le).join(" ")}`}}return r(o)}var gu=(e,t,n,r)=>[e,t,"auth-header","--env",n,"--business",r.businessId,"--user",r.userId].map(le).join(" "),yu=["KIZEN_PROFILE","CLAUDE_CODE_MCP_SERVER_URL"];function bu(e,t){let n={};for(let[r,o]of Object.entries(e))o!==void 0&&!yu.includes(r)&&(n[r]=o);return{...n,...t}}var ts=["SIGTERM","SIGHUP"];function wu(e,t,n,r,o,i){return new Promise((s,a)=>{let c;try{c=r(e.python,[e.kizen,...t],{stdio:"inherit",env:n})}catch(f){a(f instanceof Error?f:new Error(String(f)));return}let m=[...(i?ts:[...ts,"SIGINT"]).map(f=>[f,()=>{c.kill(f)}]),...i?[["SIGINT",()=>{}]]:[]];for(let[f,u]of m)o.on(f,u);let h=!1,y=f=>{if(!h){h=!0;for(let[u,w]of m)o.off(u,w);f()}};c.on("error",f=>{y(()=>{a(f)})}),c.on("close",(f,u)=>{y(()=>{s(f??128+(u===null?0:pu.signals[u]))})})})}var bt=(e,t)=>{e.writeStderr(`${Cn}: ${t}
117
+ `),e.setExitCode(1)};async function vu(e,t=!1){let n;try{n=await e.ensureKizen(t?{force:t}:void 0)}catch(r){bt(e,oe(r));return}e.writeStderr(`${Cn}: kizen ${n.version} is ready in ${n.dir}.
118
+ `)}async function xu(e,t){let n=Ur(e,t.processEnv),r=await zt(e.env,n,t.store);if(!r.ok)return{ok:!1,message:r.message};let{environment:o}=r,i;if(n===void 0)i=await t.store.readSession(o);else{let s=Mt(o,await t.store.listAccounts(o),n);i=await t.store.readAccount(o,s)}return i===null?{ok:!1,message:ke(o,`You're not signed in to ${o}.`).message}:t.scriptPath===void 0?{ok:!1,message:"can't tell which script is running, so kizen can't call back."}:{ok:!0,session:{KIZEN_AUTH_HELPER:gu(t.execPath,t.scriptPath,o,i),KIZEN_BASE_URL:ze(o),KIZEN_BUSINESS_ID:i.businessId,KIZEN_USER_ID:i.userId}}}async function ns(e,t){let n=hu(e);switch(n.kind){case"help":t.outputHelp();return;case"init-help":t.outputInitHelp();return;case"init":await vu(t,n.force);return;case"error":bt(t,n.message);return;case"run":break}let r;try{r=await xu(n,t)}catch(s){bt(t,oe(s));return}if(!r.ok){bt(t,r.message);return}let o;try{o=await t.ensureKizen()}catch(s){bt(t,oe(s));return}let i=bu(t.processEnv,r.session);try{t.setExitCode(await wu(o,n.args,i,t.spawn,t.signals,t.interactive))}catch(s){bt(t,`couldn't start kizen: ${oe(s)}`)}}import{spawn as Su}from"child_process";import{createHash as cs,randomBytes as Pu}from"crypto";import{createReadStream as Eu,createWriteStream as _u}from"fs";import{access as ss,mkdir as as,readdir as Au,readFile as Tu,rename as Iu,rm as Ht,stat as Pn,utimes as $u,writeFile as Nu}from"fs/promises";import{basename as Gr,join as qe}from"path";import{Readable as Du,Transform as Ru}from"stream";import{pipeline as ls}from"stream/promises";import{spawn as ku}from"child_process";function rs(e){return e.split(`
119
+ `).map(t=>t.trim().replace(/\s+#.*$/,"")).filter(t=>t.length>0&&!t.startsWith("#"))}function os(e){let t=/^python-(\d+)[.-](\d+)$/.exec(e),n=t?.[1],r=t?.[2];return n!==void 0&&r!==void 0?`python${n}.${r}`:"python3"}function Hr([e,t],n){return e>n[0]||e===n[0]&&t>=n[1]}function lt(e){return`${String(e[0])}.${String(e[1])}`}var Cu=(e,t)=>e[0]>t[0]||e[0]===t[0]&&e[1]>t[1];function Sn(e){return new Promise(t=>{let n=ku(e,["-c","import sys; print('%d.%d' % sys.version_info[:2])"],{stdio:["ignore","pipe","ignore"]}),r="";n.stdout.on("data",o=>{r+=o.toString("utf-8")}),n.on("error",()=>{t(null)}),n.on("close",o=>{let i=/(\d+)\.(\d+)/.exec(r);if(o!==0||!i){t(null);return}t([Number(i[1]),Number(i[2])])})})}async function Kr(e,t,n,r=Sn){let o=[],i;for(let s of e){let a=await r(s);if(!a){o.push(`${s}: not found`);continue}if(!Hr(a,t)){o.push(`${s}: ${lt(a)} (too old)`);continue}if((i===void 0||Cu(a,i.version))&&(i={bin:s,version:a}),n==="first")break}return{found:i,tried:o}}var Ut=[3,10];async function is(e,t=Sn){let n=os(e),r=n==="python3"?["python3"]:[n,"python3"],{found:o,tried:i}=await Kr(r,Ut,"first",t);if(o!==void 0)return o.bin;throw new Error(`No Python >= ${lt(Ut)} found for runtime "${e}". The local runner needs Python ${lt(Ut)}+ to install the bundled packages (e.g. psycopg 3.3), matching the remote code-runner (3.12 / 3.13). Tried ${i.join(", ")}. Install Python 3.12 or 3.13 and retry.`)}var Ou=e=>`https://github.com/kizen/kizen-admin-cli/releases/download/v${e}/kizen_builder-${e}-py3-none-any.whl`,Bu={version:"0.3.0",wheelUrl:Ou("0.3.0"),sha256:"9f2017dd43bdc4554b655c87e25d1b5c754b04e0b8a32f1ed7516e30b9edf2d7"},En="APPBUILDER_KIZEN_WHEEL",Fu=qe(ye,"kizen"),ju=".appbuilder-ready.json",Vr=[3,12],Lu=["python3.14","python3.13","python3.12","python3"],zu=720*60*6e4,Mu=60*6e4,Uu=5*6e4,Hu=/^[0-9][\w.+!]*-[0-9a-f]{12}$/,Ku=/^kizen_builder-([^-]+)-.*\.whl$/;async function Vu(e){let{found:t,tried:n}=await Kr(Lu,Vr,"newest",e);if(t===void 0)throw new Error(`No Python ${lt(Vr)} or newer found to run kizen. Tried ${n.join(", ")}. Install Python ${lt(Vr)} or newer and retry.`);return t}var Wu=20,qu=e=>(t,n)=>new Promise((r,o)=>{let i=Su(t,n,{stdio:["ignore","pipe","pipe"]}),s="",a=c=>{s+=c.toString("utf-8")};i.stdout.on("data",a),i.stderr.on("data",a),i.on("error",c=>{o(new Error(`couldn't run ${t}: ${c.message}`))}),i.on("close",(c,g)=>{if(c===0){r();return}let m=s.trimEnd().split(`
120
+ `).slice(-Wu).join(`
121
+ `);m!==""&&e(`${m}
122
+ `),o(new Error(`${Gr(t)} exited with ${c===null?String(g):`code ${String(c)}`}`))})});function ds(e,t,n=process.env){let r=n[En];return{baseDir:Fu,pin:Bu,localWheel:r===""?void 0:r,fetch:(...o)=>fetch(...o),findPython:()=>Vu(),run:qu(t),log:e,now:Date.now}}var Gu=async e=>{let t=cs("sha256");return await ls(Eu(e),t),t.digest("hex")},_n=e=>qe(e,ju),Kt=(e,t)=>qe(e,"bin",t);async function qr(e,t){try{let n=JSON.parse(await Tu(_n(e),"utf-8"));return!O(n)||n.sha256!==t?!1:(await ss(Kt(e,"python")),await ss(Kt(e,"kizen")),!0)}catch{return!1}}async function Wr(e,t){let n=new Date(t);await $u(_n(e),n,n).catch(()=>{})}async function Ju(e){if(e.localWheel!==void 0){let t=e.localWheel,n=Ku.exec(Gr(t))?.[1];if(n===void 0)throw new Error(`${En} must name a kizen_builder wheel (kizen_builder-<version>-\u2026.whl), not ${t}.`);let r;try{r=await Gu(t)}catch(o){throw new Error(`Couldn't read ${En} ${t}: ${Me(o)}`)}return{version:n,sha256:r,localPath:t}}return{version:e.pin.version,sha256:e.pin.sha256,localPath:void 0}}async function Yu(e,t,n){let r=cs("sha256");try{let o=await e.fetch(t,{signal:AbortSignal.timeout(Uu)});if(!o.ok||o.body===null)throw new Error(`HTTP ${String(o.status)}`);await ls(Du.fromWeb(o.body),new Ru({transform(i,s,a){r.update(i),a(null,i)}}),_u(n))}catch(o){throw new Error(`Couldn't download kizen from ${t}: ${Me(o)}`)}return r.digest("hex")}var Xu=e=>`.tmp-${e}-${String(process.pid)}-${Pu(4).toString("hex")}`;async function Zu(e,t,n){let r;try{r=await Au(e)}catch{return}await Promise.all(r.map(async o=>{if(o===t)return;let i=qe(e,o);try{if(Hu.test(o)){let{mtimeMs:s}=await Pn(_n(i)).catch(()=>Pn(i));n-s>zu&&await Ht(i,{recursive:!0,force:!0})}else if(o.startsWith(".tmp-")){let{mtimeMs:s}=await Pn(i);n-s>Mu&&await Ht(i,{recursive:!0,force:!0})}}catch{}}))}var Qu=e=>Pn(e).then(()=>!0,()=>!1),us=e=>new Error(`kizen's install at ${e} is damaged. Run \`appbuilder admin init --force\` to reinstall it.`);async function ep(e,t,n){try{return await Iu(e,t),!0}catch(r){if(!Te(r,"ENOTEMPTY")&&!Te(r,"EEXIST"))throw r}if(await qr(t,n))return!1;throw us(t)}async function ps(e,t={}){let n=await Ju(e),r=`${n.version}-${n.sha256.slice(0,12)}`,o=qe(e.baseDir,r),i=h=>({version:n.version,dir:o,python:Kt(o,"python"),kizen:Kt(o,"kizen"),built:h});if(t.force===!0)e.log(`Removing ${o}.`),await Ht(o,{recursive:!0,force:!0});else{if(await qr(o,n.sha256))return await Wr(o,e.now()),i(!1);if(await Qu(o)){if(await qr(o,n.sha256))return await Wr(o,e.now()),i(!1);throw us(o)}}e.log(`Installing kizen ${n.version} into ${o} (first run only).`);let s=await e.findPython();e.log(`Using ${s.bin} (Python ${lt(s.version)}).`),await as(e.baseDir,{recursive:!0,mode:448});let a=qe(e.baseDir,Xu(r)),c=qe(a,"venv"),g;try{await as(a);let h;if(n.localPath===void 0){h=qe(a,Gr(new URL(e.pin.wheelUrl).pathname)),e.log(`Downloading ${e.pin.wheelUrl}`);let y=await Yu(e,e.pin.wheelUrl,h);if(y!==n.sha256)throw await Ht(h,{force:!0}),new Error(`The kizen ${n.version} download doesn't match its pinned sha256 (expected ${n.sha256}, got ${y}), so nothing was installed.`)}else h=n.localPath,e.log(`Using the local wheel ${h} (${En}).`);e.log("Creating a virtual environment.");try{await e.run(s.bin,["-m","venv",c])}catch(y){throw new Error(`Couldn't create a virtual environment: ${oe(y)}`)}e.log(`Installing kizen ${n.version} from the wheel and its dependencies from PyPI.`);try{await e.run(Kt(c,"python"),["-m","pip","install","--disable-pip-version-check",h])}catch(y){throw new Error(`Couldn't install kizen: ${oe(y)}`)}await Nu(_n(c),`${JSON.stringify({version:n.version,sha256:n.sha256},null,2)}
123
+ `),g=await ep(c,o,n.sha256)}finally{await Ht(a,{recursive:!0,force:!0}).catch(()=>{})}let m=e.now();return await Wr(o,m),g&&(e.log(`kizen ${n.version} is installed.`),await Zu(e.baseDir,r,m)),i(g)}var Jr="admin",rp=`Usage: appbuilder admin init [--force]
124
+
125
+ Install kizen for appbuilder admin, or confirm it's installed. Needs Python 3.12 or newer.
126
+
127
+ Options:
128
+ --force remove kizen's install and install it again, to repair a damaged one; don't run it
129
+ while appbuilder admin is running
130
+ `,Yr=class extends np{parseOptions(t){return{operands:[...t],unknown:[]}}};function op(e){let t=o=>{process.stderr.write(o)},n=ds(o=>{t(`${Cn}: ${o}
131
+ `)},t),r=process.stdin;return{store:Ce(),ensureKizen:o=>ps(n,o),spawn:tp,signals:process,interactive:r.isTTY===!0,processEnv:process.env,execPath:process.execPath,scriptPath:process.argv[1],outputHelp:()=>{e.outputHelp()},outputInitHelp:()=>{process.stdout.write(rp)},writeStderr:t,setExitCode:o=>{process.exitCode=o}}}function fs(e){let t=new Yr(Jr).copyInheritedSettings(e).description("Run Kizen's admin CLI (kizen) with the signed-in session").usage(`[--env <env>] [--business <id-or-name> [--user <userId>]] [--] <kizen args...>
132
+ appbuilder admin init [--force]`).option("--env <env>","environment to use (default: the only signed-in one, or with --business the only one where it's saved)").option("--business <id-or-name>","use this saved account, by business id or name (ignoring case), instead of the current one (default: $APPBUILDER_BUSINESS)").option("--user <userId>","with --business, use the saved account of this user id (default: $APPBUILDER_USER)").allowExcessArguments().addHelpText("after",`
133
+ Wrapper options end at the first other argument or at --; everything after goes to kizen.
134
+ "appbuilder admin init" installs kizen ahead of time; it's otherwise installed on first use.`).action(async()=>{await ns(t.args,op(t))});e.addCommand(t);let n=e.parseOptions.bind(e);e.parseOptions=r=>r[0]===Jr?{operands:[Jr],unknown:r.slice(1)}:n(r)}import{render as dp}from"ink";import{useMemo as ip,useState as sp}from"react";import{Box as Xr,Text as dt,useInput as ap}from"ink";var An=(e,t,n)=>Math.min(Math.max(e,t),n);function Tn(e,t,n,r={}){if(t<=0)return 0;let o=An(Math.trunc(e)||0,0,t-1),i=c=>r.disabled?.[c]!==!0;if(n===0)return o;let s=n>0?1:-1;if(Math.abs(n)===1){for(let c=1;c<=t;c++){let g=((o+s*c)%t+t)%t;if(i(g))return g}return o}let a=An(o+Math.trunc(n),0,t-1);for(let c=a;c>=0&&c<t;c+=s)if(i(c))return c;for(let c=a-s;c>=0&&c<t;c-=s)if(i(c))return c;return o}function ms(e,t,n=10){if(t<=0)return{start:0,end:0};let r=Math.max(1,Math.floor(n));if(t<=r)return{start:0,end:t};let o=An(Math.trunc(e)||0,0,t-1),i=An(o-Math.floor(r/2),0,t-r);return{start:i,end:i+r}}import{jsx as ut,jsxs as Qr}from"react/jsx-runtime";var cp="\u2191/\u2193 to move, Enter to select, Esc to cancel",Zr=10,lp=e=>{let t=Tn(0,e.length,0);if(e[t]?.disabled!==!0)return t;let n=e.findIndex(r=>r.disabled!==!0);return n===-1?t:n},Ne=({title:e,items:t,onSelect:n,onCancel:r,hint:o=cp})=>{let[i,s]=sp(()=>lp(t)),a=ip(()=>t.map(f=>f.disabled===!0),[t]),c=Tn(i,t.length,0);ap((f,u)=>{let w=k=>{s(Tn(c,t.length,k,{disabled:a}))};if(u.upArrow||f==="k")w(-1);else if(u.downArrow||f==="j")w(1);else if(u.pageUp)w(-Zr);else if(u.pageDown)w(Zr);else if(u.return){let k=t[c];k!==void 0&&k.disabled!==!0&&n(k,c)}else u.escape&&r?.()});let{start:g,end:m}=ms(c,t.length,Zr),h=g,y=t.length-m;return Qr(Xr,{flexDirection:"column",gap:1,children:[ut(dt,{bold:!0,children:e}),Qr(Xr,{flexDirection:"column",children:[h>0&&ut(dt,{dimColor:!0,children:` \u2191 ${String(h)} more`}),t.slice(g,m).map((f,u)=>{let k=g+u===c,_=f.disabled===!0,P=k&&!_;return Qr(Xr,{gap:2,children:[ut(dt,{...P&&{color:"cyan"},dimColor:_,children:k?"\u276F":" "}),ut(dt,{bold:P,dimColor:_,...P&&{color:"cyan"},children:f.label}),f.description!==void 0&&ut(dt,{dimColor:!0,children:f.description})]},f.key)}),y>0&&ut(dt,{dimColor:!0,children:` \u2193 ${String(y)} more`})]}),ut(dt,{dimColor:!0,children:o})]})};import{jsx as up}from"react/jsx-runtime";var hs=async(e,t)=>{let n,r=dp(up(Ne,{title:e,items:t,onSelect:o=>{n=o.key,r.unmount()},onCancel:()=>{r.unmount()}}));return await r.waitUntilExit(),n};var pp=[{name:"login",description:"Sign in to Kizen in the browser, or switch to a saved account, and store the session on this machine",env:"environment to sign in to (default: go)",options:[["--business <id-or-name>","switch to the saved account with this business id, or business name (ignoring case); signs in with the browser if none matches or it expired"],["--user <userId>","with --business, pick the saved account of this user id"],["--list","list the saved accounts for the environment and exit"],["--json","with --list, print the accounts as JSON"]],run:Yi},{name:"logout",description:"Remove the stored session from this machine",env:"environment to sign out of (default: the only signed-in one)",options:[["--all","also remove every other saved account for the environment"],["--business <id-or-name>","remove only this saved account, by business id or name (ignoring case)"],["--user <userId>","with --business, remove the saved account of this user id"]],run:Xi},{name:"whoami",description:"Show the user and business of the stored session",env:"environment to check (default: the only signed-in one, or with --business the only one where it's saved)",options:[["--business <id-or-name>","check this saved account, by business id or name (ignoring case), instead of the current one (default: $APPBUILDER_BUSINESS)"],["--user <userId>","with --business, check the saved account of this user id (default: $APPBUILDER_USER)"]],run:Zi},{name:"auth-header",description:"Print an Authorization header for the stored session as JSON (for a Claude Code MCP headersHelper)",env:"environment to use; must match CLAUDE_CODE_MCP_SERVER_URL when that is set (default: the environment matching it, else the only signed-in one)",options:[["--business <id>","with --user, use this saved account, current or not"],["--user <userId>","with --business, the user id of that account"]],run:Qi}];function gs(e){for(let{name:t,description:n,env:r,options:o=[],run:i}of pp){let s=e.command(t).description(n).option("--env <env>",r);for(let[a,c]of o)s.option(a,c);s.action(async a=>{await i(a,Ki(void 0,hs))})}}import{createElement as Mm}from"react";import{render as Um}from"ink";import{PluginValidationError as Hm}from"@kizenapps/packager";import{spawn as fp}from"child_process";import{platform as ys}from"process";function mp(){return ys==="darwin"?[{cmd:"pbcopy",args:[]}]:ys==="win32"?[{cmd:"clip",args:[]}]:[{cmd:"wl-copy",args:[]},{cmd:"xclip",args:["-selection","clipboard"]},{cmd:"xsel",args:["--clipboard","--input"]}]}var hp=2e3;function gp(e,{cmd:t,args:n}){return new Promise(r=>{let o;try{o=fp(t,n,{stdio:["pipe","ignore","ignore"]})}catch{r(!1);return}let i=o,s=!1;function a(g){s||(s=!0,clearTimeout(c),r(g))}let c=setTimeout(()=>{i.kill(),a(!1)},hp);c.unref(),i.on("error",()=>{a(!1)}),i.on("close",g=>{a(g===0)}),i.stdin.on("error",()=>{a(!1)});try{i.stdin.end(e)}catch{a(!1)}})}async function In(e){for(let t of mp())if(await gp(e,t))return!0;return!1}import{BLOCKS_DIRECTORY_NAME as Yp,CONFIG_FILE_NAME as Xp,MANIFEST_FILE_NAME as Zp,sanitizeToAPIName as Qp}from"@kizenapps/packager";var $n=["min_w","max_w","min_h","max_h","default_w","default_h"];import{createHash as yp}from"crypto";import{mkdir as bp,readFile as wp,writeFile as vp}from"fs/promises";import{dirname as xp,join as vs}from"path";var eo="appbuilder:",pt=".kizenapp/pushes.json",kp=["environment","businessId","pluginApiName","blockApiName","dashboardId","dashletId","contentHash","pushedAt"];function to(e){return typeof e=="number"&&Number.isFinite(e)}function Nn(e,t,n){return Math.min(Math.max(e,t),n)}function Cp(e){let t={...e};return delete t.custom_object,t}function xs(e,t){return`${eo}${e}/${t}`}function ks(e){if(!e.startsWith(eo))return null;let t=e.slice(eo.length).split("/");if(t.length!==2)return null;let[n,r]=t;return!n||!r?null:{pluginApiName:n,blockApiName:r}}function Cs(e){let t={};for(let n of $n){let r=e[n];to(r)&&(t[n]=r)}return t}function Ss(e){return typeof e.host_chrome=="boolean"?{host_chrome:e.host_chrome}:{}}var Ps=e=>Object.entries(e).map(([t,n])=>({name:t,script:n}));function Sp(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:Ps(e.event_scripts)}}function ro(e){return e.length>0?{views:e.map(Sp)}:{}}function Es(e,t=[]){return{kind:"custom_code",version:1,name:e.name,script:e.script,styles:e.styles,event_scripts:Ps(e.event_scripts),...Cs(e),...Ss(e),...ro(t)}}function Pp(e){return{object_id:e.objectId,entity_type:"static_content",report_type:"html",chart_type:"html",content:e.content,fe_extra_info:{}}}function Ep(e){let t=0;for(let n of e){let r=n.layout;if(!O(r))continue;let{y:o,h:i}=r;!to(o)||!to(i)||(t=Math.max(t,o+i))}return t}function _p(e,t,n){let r=Nn(t.default_w??t.min_w??6,t.min_w??1,t.max_w??12),o=Nn(t.default_h??t.min_h??3,t.min_h??1,t.max_h??99);return{i:n,x:0,y:Ep(e),w:Nn(r,2,12),h:Nn(o,1,99)}}function _s(e){return{name:xs(e.pluginApiName,e.blockApiName),layout:_p(e.dashlets,e.content,e.layoutId),config:Pp({content:e.content,objectId:e.objectId})}}function As(e,t){let n=e.config;return{config:{...Cp(O(n)?n:{}),content:t}}}function Ts(e){let t=e.config;return O(t)?t.content:void 0}function wt(e){let t=e.config;if(!O(t)||t.chart_type!=="html")return!1;let n=t.content;return O(n)&&n.kind==="custom_code"}function Is(e){return e.dashlets.filter(wt)}function Dn(e){let t=Ts(e);return O(t)&&typeof t.name=="string"?t.name:e.name}var Ge=e=>typeof e=="string"?e:"";function $s(e){return Array.isArray(e)?e.filter(O).map(t=>({name:Ge(t.name),script:Ge(t.script)})):O(e)?Object.entries(e).map(([t,n])=>({name:t,script:Ge(n)})):[]}function no(e){if(Array.isArray(e))return e.map(no);if(O(e)){let t={};for(let n of Object.keys(e).sort())t[n]=no(e[n]);return t}return e}function Ns(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e).trim():""}function Ap(e){return Array.isArray(e)?e.filter(O).map(t=>({api_name:Ge(t.api_name),name:Ns(t.name),type:Ge(t.type),script:Ge(t.script),html:Ge(t.html),css:Ge(t.css),event_scripts:$s(t.event_scripts)})):[]}function oo(e){let t=O(e)?e:{},n=Ap(t.views),r={name:Ns(t.name),script:typeof t.script=="string"?t.script:"",styles:typeof t.styles=="string"?t.styles:"",event_scripts:$s(t.event_scripts),...Cs(t),...Ss(t),...n.length>0&&{views:n}};return yp("sha256").update(JSON.stringify(no(r))).digest("hex")}function Ds(e){let{entry:t}=e;if(t?.dashboardId===e.dashboardId){let i=e.dashlets.find(s=>s.id===t.dashletId);if(i&&wt(i))return{kind:"map",dashlet:i,entry:t}}let n=xs(e.pluginApiName,e.blockApiName),r=e.dashlets.filter(i=>i.name===n&&wt(i)),[o]=r;return r.length===1&&o?{kind:"name",dashlet:o}:r.length>1?{kind:"ambiguous",dashlets:r}:{kind:"none"}}function Rs(e,t){return t?.dashletId!==e.id?!1:oo(Ts(e))!==t.contentHash}function io(e,t){return e.environment===t.environment&&e.businessId===t.businessId&&e.pluginApiName===t.pluginApiName&&e.blockApiName===t.blockApiName}function so(e,t){return e.find(n=>io(n,t))}function Os(e,t){let n=e.findIndex(r=>io(r,t));return n===-1?[...e,t]:e.map((r,o)=>o===n?t:r)}function Bs(e,t){return e.filter(n=>!io(n,t))}function Tp(e){if(!O(e))return null;for(let n of kp)if(typeof e[n]!="string")return null;let t=e;return{environment:t.environment,businessId:$t(t.businessId),pluginApiName:t.pluginApiName,blockApiName:t.blockApiName,dashboardId:t.dashboardId,dashletId:t.dashletId,contentHash:t.contentHash,pushedAt:t.pushedAt}}var bs=e=>Date.parse(e.pushedAt)||0;function Ip(e){let t=new Map;for(let n of e){let r=[n.environment,n.businessId,n.pluginApiName,n.blockApiName].join("\0"),o=t.get(r);(o===void 0||bs(n)>bs(o))&&t.set(r,n)}return[...t.values()]}var ws=e=>e instanceof Error?e.message:String(e);async function Fs(e){let t;try{t=await wp(vs(e,pt),"utf8")}catch(r){if(fn(r))return[];throw new Error(`Couldn't read ${pt}: ${ws(r)}. Fix its permissions, or delete it to start a fresh push map.`)}let n;try{n=JSON.parse(t)}catch(r){throw new Error(`${pt} is not valid JSON (${ws(r)}). Fix it, or delete it to start a fresh push map.`)}if(!Array.isArray(n))throw new Error(`${pt} must contain a JSON array of push entries. Fix it, or delete it to start a fresh push map.`);return Ip(n.map(Tp).filter(r=>r!==null))}async function js(e,t){let n=vs(e,pt);await bp(xp(n),{recursive:!0}),await vp(n,`${JSON.stringify(t,null,2)}
135
+ `,"utf8")}var $p={generic_dashboard:"dashboard",homepage:"homepage",chart_group:"chart_group"},Np={dashboard:"generic_dashboard",homepage:"homepage",chart_group:"chart_group"};function ao(e){return $p[e]}function Ls(e){return Np[e]}function zs(e){let t=e.appBaseUrl.replace(/\/+$/,""),n=e.dashboardId;return e.surface==="homepage"?`${t}/home/${n}`:e.surface==="chart_group"&&e.customObject?e.customObject.fetchUrl==="client"?`${t}/clients/charts/${n}`:`${t}/custom-objects/${e.customObject.id}/charts/${n}`:`${t}/dashboard/${n}`}import{mkdir as zp,writeFile as Mp}from"fs/promises";import{join as Up}from"path";import{PluginValidationError as Hp,packagePlugin as Kp,parseManifestFromFiles as Vp,transformDeployablePlugin as Wp,transformFiles as qp,validatePluginApp as Gp}from"@kizenapps/packager";import{readdir as Dp,readFile as Ms}from"fs/promises";import{join as Us,relative as Rp}from"path";var Op=new Set([".png",".svg"]),Bp=new Set([".kzn"]),Fp=new Set([".DS_Store"]),Rn=new Set(["node_modules",".git",".kizenapp",".copilot-docs",".github",".claude","__pycache__"]),jp=8e3;function Lp(e){return e.subarray(0,jp).includes(0)}async function Hs(e,t){let n=await Dp(e,{withFileTypes:!0}),r=[];for(let o of n)if(o.isDirectory()){if(Rn.has(o.name))continue;r.push(...await Hs(Us(e,o.name),t))}else o.isFile()&&(Fp.has(o.name)||r.push(Us(e,o.name)));return r}async function On(e,{detectBinaryByContent:t=!1}={}){let n=await Hs(e,e);return Promise.all(n.map(async r=>{let o=Rp(e,r).split("\\").join("/"),i=o.lastIndexOf("."),s=i>=0?o.slice(i).toLowerCase():"";if(Op.has(s)){let c=await Ms(r);return{path:o,content:"",base64Image:c.toString("base64")}}let a=await Ms(r);return Bp.has(s)||t&&Lp(a)?{path:o,content:"",binaryData:a}:{path:o,content:a.toString("utf-8")}}))}var Jp=(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 co(e,t){t?.("reading-files");let n=await On(e);t?.("validating");let r=Gp(n);if(r.some(c=>c.severity==="error"))throw new Hp(r);t?.("minifying");let o=await qp(n);t?.("packaging");let i=Vp(o),s=Kp(o,i),a=Object.values(s).map(Wp);return{files:n,deployable:a,issues:r}}async function Bn(e,t,n){await zp(t,{recursive:!0});let{files:r,deployable:o}=await co(e,n);n?.("writing-bundle");let i=o.map(g=>{let m=g.release_notes_directory?.replace(/\/$/,""),h=m?r.filter(y=>y.path.startsWith(m+"/")&&y.path.endsWith(".md")&&y.content).map(y=>({version:y.path.slice(y.path.lastIndexOf("/")+1,-3),notes:y.content})).sort((y,f)=>f.version.localeCompare(y.version,void 0,{numeric:!0})):[];return Jp(g,h)}),s=JSON.stringify(i,null,2),a=(g,m)=>g==="allReleaseNotes"?void 0:m,c=Buffer.byteLength(JSON.stringify(i,a,2),"utf-8");return await Mp(Up(t,"bundle.json"),s,"utf-8"),{bundleSize:c}}var Ws=["min_w","max_w","min_h","max_h"],qs=[["min_w","max_w"],["min_h","max_h"]],Fn={default_w:["min_w","max_w"],default_h:["min_h","max_h"]},ef=Object.keys(Fn),Gs=[...$n,"host_chrome"],tf=["\0","{__ref:"],lo="views",uo=class extends Error{reason;available;field;constructor(t,n,r={}){super(n),this.name="BlockExportError",this.reason=t,this.available=r.available??[],this.field=r.field}};function nf(e){let t=new Set(e.map(n=>n.pluginApiName)).size>1;return e.map(n=>t?`${n.pluginApiName}/${n.apiName}`:n.apiName).join(", ")}function rf(e,t){let n=e.flatMap(s=>s.artifacts.custom_blocks.map(a=>({block:a,pluginApiName:s.api_name}))),r=n.map(({block:s,pluginApiName:a})=>({pluginApiName:a,apiName:s.api_name}));if(n.length===0)return{ok:!1,reason:"no_blocks",available:r};if(t===void 0){let[s]=n;return n.length===1&&s?{ok:!0,...s}:{ok:!1,reason:"ambiguous",available:r}}let o=n.filter(({block:s})=>s.api_name===t),[i]=o;return i?o.length>1?{ok:!1,reason:"ambiguous",available:o.map(({block:s,pluginApiName:a})=>({pluginApiName:a,apiName:s.api_name}))}:{ok:!0,...i}:{ok:!1,reason:"not_found",available:r}}var Ks=e=>typeof e=="number"&&Number.isInteger(e)&&e>0,Vt=e=>tf.some(t=>e.includes(t));function of(e){let t=e,{name:n,script:r,styles:o,event_scripts:i}=t;if(typeof r!="string"||!r.trim())return"script";if(n!==void 0&&typeof n!="string")return"name";if(o!==void 0&&typeof o!="string")return"styles";if(i!==void 0){if(!O(i))return"event_scripts";let m=Object.entries(i).find(([h,y])=>typeof y!="string"||Vt(h)||Vt(y));if(m)return`event_scripts.${m[0]}`}let s=[["name",n],["script",r],["styles",o]].find(([,m])=>typeof m=="string"&&Vt(m));if(s)return s[0];let a=Ws.find(m=>t[m]!==void 0&&!Ks(t[m]));if(a)return a;let c=qs.find(([m,h])=>{let y=t[m],f=t[h];return typeof y=="number"&&typeof f=="number"&&y>f});if(c)return c[0];let g=ef.find(m=>{let h=t[m];if(h===void 0)return!1;if(typeof h!="number"||!Ks(h))return!0;let[y,f]=Fn[m],u=t[y],w=t[f];return typeof u=="number"&&h<u||typeof w=="number"&&h>w});if(g)return g;if(t.host_chrome!==void 0&&typeof t.host_chrome!="boolean")return"host_chrome"}var sf=["api_name","name","script","html","css"],Vs=e=>typeof e!="string"||Vt(e);function af(e){for(let t of e){let n=t,r=typeof n.api_name=="string"?n.api_name:String(n.api_name),o=sf.find(a=>Vs(n[a]));if(o)return{view:r,field:o};let i=n.event_scripts;if(!O(i))return{view:r,field:"event_scripts"};let s=Object.entries(i).find(([a,c])=>Vt(a)||Vs(c));if(s)return{view:r,field:`event_scripts.${s[0]}`}}}var cf=({view:e,field:t})=>`views.${e}.${t}`,lf=(e,t)=>`Block "${e}" can't carry view ${JSON.stringify(t.view)}: its ${t.field} must be a string without NUL characters or "{__ref:".`,df=(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 n=qs.find(([r])=>r===t);if(n)return`Block "${e}" has an invalid ${t}: it must be a positive integer no greater than ${n[1]}.`;if(Ws.includes(t))return`Block "${e}" has an invalid ${t}: it must be a positive integer.`;if(t in Fn){let[r,o]=Fn[t];return`Block "${e}" has an invalid ${t}: it must be a positive integer between ${r} and ${o}.`}return`Block "${e}" has an invalid ${t}: it must be a string without NUL characters or "{__ref:".`},uf=({reason:e,available:t},n,r)=>{let o=nf(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 "${n??""}". Available blocks: ${o}`:n===void 0?`This plugin has several blocks; pass the api_name of the one to ${r}: ${o}`:`More than one plugin has a block with api_name "${n}": ${o}`},pf=e=>{try{let t=JSON.parse(e);return O(t)?t:void 0}catch{return}},Js=e=>{let t=e.find(i=>i.path===Zp),n=t?JSON.parse(t.content):[],r=Array.isArray(n)?n:[n],o=new Map;for(let i of r)O(i)&&typeof i.api_name=="string"&&typeof i.entry=="string"&&o.set(i.api_name,i.entry);return o},Ys=(e,t)=>{let n=mn(e);return n===""?t:`${n}/${t}`},Xs=(e,t,n)=>{let r=`${Ys(t,n)}/`,o=new Set,i=[];for(let s of e){if(!s.path.startsWith(r)||s.path.endsWith(".DS_Store"))continue;let[a,c,...g]=s.path.slice(r.length).split("/");if(a&&(o.add(a),c===Xp&&g.length===0)){let m=pf(s.content);m&&i.push([a,m])}}return{directories:o,configs:i}},Zs=(e,t)=>typeof e.api_name=="string"&&e.api_name!==""?e.api_name:Qp(t),ff=(e,t)=>{let n=new Map;for(let[r,o]of Xs(e,t,Yp).configs){let i=Zs(o,r),s={};for(let a of Gs)o[a]!==void 0&&(s[a]=o[a]);n.set(i,s)}return n},mf=(e,t={})=>({...Object.fromEntries(Object.entries(e).filter(([r])=>!Gs.includes(r))),...t});function hf(e,t){let n=Js(t);return e.map(r=>{let o=n.get(r.api_name),i=o===void 0?new Map:ff(t,o);return{...r,artifacts:{...r.artifacts,custom_blocks:r.artifacts.custom_blocks.map(s=>mf(s,i.get(s.api_name)))}}})}var Qs=(e,t)=>JSON.stringify([String(e),String(t)]),gf=(e,t)=>{let{directories:n,configs:r}=Xs(e,t,lo),o=new Map(r),i=new Set;for(let s of n){let a=o.get(s)??{};i.add(Qs(Zs(a,s),a.name||s))}return i},yf=(e,t)=>e.api_name.localeCompare(t.api_name)||String(e.name).localeCompare(String(t.name)),bf="appbuilder/views-unmatched";function wf(e,t){let n=Js(t),r={},o=[];for(let i of e){let s=n.get(i.api_name),a=s===void 0?new Set:gf(t,s),c=i.artifacts.routable_pages.filter(g=>a.has(Qs(g.api_name,g.name))).sort(yf);c.length!==a.size&&s!==void 0&&o.push({rule:bf,severity:"warning",message:`Found ${String(a.size)} ${lo}/ components but matched ${String(c.length)} packaged views; the pushed block carries only the matched ones.`,path:Ys(s,lo),pluginApiName:i.api_name}),r[i.api_name]=c}return{views:r,warnings:o}}function vf(e,t){return Object.hasOwn(e,t)?e[t]??[]:[]}function ea(e){return{...e.block,...ro(e.views)}}async function po(e){let{files:t,deployable:n,issues:r}=await co(e),o=wf(n,t);return{deployable:hf(n,t),views:o.views,warnings:[...r.filter(i=>i.severity==="warning"),...o.warnings]}}function fo({deployable:e,views:t,warnings:n},r,o){let i=rf(e,r);if(!i.ok)return{ok:!1,reason:i.reason,message:uf(i,r,o),available:i.available};let s=of(i.block);if(s!==void 0)return{ok:!1,reason:"invalid_block",message:df(i.block.api_name,s),available:[],field:s};let a=vf(t,i.pluginApiName),c=af(a);return c!==void 0?{ok:!1,reason:"invalid_block",message:lf(i.block.api_name,c),available:[],field:cf(c)}:{ok:!0,value:{block:i.block,pluginApiName:i.pluginApiName,views:a,warnings:n}}}async function ta(e,t){let n=fo(await po(e),t,"export");if(!n.ok)throw new uo(n.reason,n.message,n);return n.value}var mo=(e,t,n)=>`${String(e)} ${e===1?t:n}`,ho=e=>{let t=new Map;for(let n of e){let r=n.path??n.pluginApiName??"general",o=t.get(r)??[];o.push(n),t.set(r,o)}return t},xf=e=>{let t=e.filter(o=>o.severity==="error").length,n=e.length-t;if(t===0)return`\u26A0 ${mo(n,"validation warning","validation warnings")}`;let r=`\u2717 ${mo(t,"validation error","validation errors")}`;return n===0?r:`${r}, ${mo(n,"warning","warnings")}`};function De(e){if(e.length===0)return"";let t=[...ho(e)].map(([n,r])=>[n,...r.map(o=>` ${o.severity==="error"?"\u2717":"\u26A0"} ${o.message} (${o.rule})`)].join(`
136
+ `));return[xf(e),...t].join(`
137
+
138
+ `)}import{randomUUID as Yf}from"crypto";import{join as Xf}from"path";import{PluginValidationError as Zf}from"@kizenapps/packager";import{mkdir as kf,readFile as Cf,writeFile as Sf}from"fs/promises";import{join as na}from"path";async function Se(e){try{let t=await Cf(na(e,"config.json"),"utf-8");return JSON.parse(t)}catch{return{}}}async function Je(e,t){await kf(e,{recursive:!0}),await Sf(na(e,"config.json"),JSON.stringify(t,null,2),"utf-8")}import*as vt from"fs";import*as ra from"path";var Pf=[".kizenapp/",".copilot-docs/"];function Pe(e){let t=ra.join(e,".gitignore"),n="";vt.existsSync(t)&&(n=vt.readFileSync(t,"utf8"));let r=new Set(n.split(`
139
+ `).map(a=>a.trim())),o=Pf.filter(a=>!r.has(a)&&!r.has(a.replace(/\/$/,"")));if(o.length===0)return;let i=o.join(`
122
140
  `)+`
123
141
  `,s=n===""||n.endsWith(`
124
142
  `)?i:`
125
- `+i;ht.writeFileSync(t,n+s)}var Ku="To use an API key instead (deprecated), pass --profile <name> or -c <path>.";function gs(e){return(e.credentials!==void 0||e.profile!==void 0)&&e.env!==void 0?{ok:!1,message:"--env selects a sign-in session, so it can't be combined with -c or --profile."}:e.credentials!==void 0?{ok:!0,selection:{kind:"api-key",credentials:e.credentials}}:e.profile!==void 0?{ok:!0,selection:{kind:"api-key",profile:e.profile}}:{ok:!0,selection:e.env===void 0?{kind:"oauth"}:{kind:"oauth",env:e.env}}}var ys=e=>`Ignoring the API-key profile ${JSON.stringify(e)} pinned in .kizenapp/config.json and using your sign-in session.${/[\x00-\x1f\x7f]/.test(e)?"":` Pass --profile ${be(e)} to use the API key.`}`,bs=e=>`${e} ${Ku}`;import{spawn as ip}from"child_process";import{join as _n}from"path";var ws="---\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` use the user's `appbuilder login` session by default. `-c/--credentials <path>` and `--profile <name>` opt in to a deprecated API key; use them only when the user asks.\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 `'environment'`, `'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`, if `message` says they're not signed in, tell the user to run `appbuilder login` (add `--env <env>` for an environment other than `go`). Otherwise tell them to fix the credential file named in `message`. Don't run `--profile` or `-c` unless the user asks for an API key.\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 vs=`# Designing a Kizen custom block
143
+ `+i;vt.writeFileSync(t,n+s)}import{spawn as Lf}from"child_process";import{join as Hn}from"path";var oa="---\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` use the user's `appbuilder login` session by default. `-c/--credentials <path>` and `--profile <name>` opt in to a deprecated API key; use them only when the user asks.\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 `'environment'`, `'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`, if `message` says they're not signed in, tell the user to run `appbuilder login` (add `--env <env>` for an environment other than `go`). Otherwise tell them to fix the credential file named in `message`. Don't run `--profile` or `-c` unless the user asks for an API key.\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 ia=`# Designing a Kizen custom block
126
144
 
127
145
  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".
128
146
 
@@ -471,7 +489,7 @@ render(
471
489
  color: var(--color-font-placeholder);
472
490
  }
473
491
  \`\`\`
474
- `;var xs=`# Copilot review instructions for this Kizen plugin
492
+ `;var sa=`# Copilot review instructions for this Kizen plugin
475
493
 
476
494
  This repo is a Kizen plugin app: a \`kizen.json\` manifest plus the artifacts
477
495
  that \`@kizenapps/packager\` finds by walking the directory tree under the
@@ -524,7 +542,7 @@ This file covers repo structure and general review. Two path-scoped files cover
524
542
  the rest: \`.github/instructions/security.instructions.md\` for security-sensitive
525
543
  patterns and \`.github/instructions/version-discipline.instructions.md\` for
526
544
  manifest version bumps.
527
- `;var ks='---\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 Cs=`---
545
+ `;var aa='---\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 ca=`---
528
546
  applyTo: "kizen.json"
529
547
  ---
530
548
 
@@ -537,7 +555,7 @@ cannot drift out of date here.
537
555
  Check every \`kizen.json\` diff against the "How big a bump?" matrix in
538
556
  \`.copilot-docs/16-release-and-publish.md\` and the "Release & publish" section of
539
557
  \`.copilot-docs/17-gotchas.md\`, and name the change that sets the required level.
540
- `;var Ss=`# Copilot only reads this file from the default branch, and only if the job is named copilot-setup-steps.
558
+ `;var la=`# Copilot only reads this file from the default branch, and only if the job is named copilot-setup-steps.
541
559
  name: Copilot code review setup
542
560
 
543
561
  on:
@@ -576,7 +594,7 @@ jobs:
576
594
  echo "Fetched $count markdown files into .copilot-docs/ ($numbered numbered docs)"
577
595
  test "$count" -ge 24
578
596
  du -sh .copilot-docs
579
- `;var Ps=`const MAX_PAGE_SIZE = 1000;
597
+ `;var da=`const MAX_PAGE_SIZE = 1000;
580
598
  const DEFAULT_MAX_PAGES = 10;
581
599
 
582
600
  const fieldCache = new Map();
@@ -821,22 +839,22 @@ export const sumBy = (records, name, valueOf) =>
821
839
  total + (valueOf ? numberOf(valueOf(record)) : numberOf(fieldValue(record, name))),
822
840
  0,
823
841
  );
824
- `;function kn(){return[{path:".github/copilot-instructions.md",content:xs},{path:".github/instructions/security.instructions.md",content:ks},{path:".github/instructions/version-discipline.instructions.md",content:Cs},{path:".github/workflows/copilot-code-review.yml",content:Ss}]}var Es="lib/kizenData.js",Mr=(e="src")=>e===""?Es:`${e}/${Es}`;function Cn(e=[]){return[{path:".claude/skills/kizen-custom-block/SKILL.md",content:ws},{path:".claude/skills/kizen-custom-block/design.md",content:vs},...[...new Set(e)].map(t=>({path:Mr(t),content:Ps}))]}import{access as Qu,mkdir as ep,readFile as tp,writeFile as np}from"fs/promises";import{dirname as rp,join as _s}from"path";var Sn={readFile:async e=>{try{return await tp(e,"utf-8")}catch(t){if(nn(t))return;throw t}},writeFile:async(e,t)=>{await ep(rp(e),{recursive:!0}),await np(e,t,"utf-8")},exists:async e=>{try{return await Qu(e),!0}catch{return!1}}},op=(e,t)=>e===void 0?"created":e===t?"unchanged":"updated";async function zr(e,t,n=Sn){return Promise.all(t.map(async r=>({path:r.path,status:op(await n.readFile(_s(e,r.path)),r.content)})))}async function Pn(e,t,n={},r=Sn){let o=await zr(e,t,r);return n.dryRun===!0||await Promise.all(t.filter((i,s)=>o[s]?.status!=="unchanged").map(i=>r.writeFile(_s(e,i.path),i.content))),o}var En=e=>`${e.status.padEnd(9)} ${e.path}`;var Ts=".claude/skills/kizen-custom-block/SKILL.md",Is="Claude files managed by appbuilder are out of date; run appbuilder setup-claude",Hr=Sn,sp=e=>{if(typeof e!="string"||e.trim()==="")return;let t=rn(e);if(!(t===".."||t.startsWith("../")||t.startsWith("/")))return t};function ap(e){let n=(Array.isArray(e)?e:[e]).map(r=>typeof r=="object"&&r!==null&&"entry"in r?sp(r.entry):void 0).filter(r=>r!==void 0);return n.length>0?[...new Set(n)]:["src"]}var cp=async(e,t)=>{try{let n=await t.readFile(_n(e,"kizen.json"));return n===void 0?["src"]:ap(JSON.parse(n))}catch{return["src"]}};async function $s(e,t=Hr,n={}){let r=await cp(e,t),o=n.includeLib===!0?r:(await Promise.all(r.map(async i=>await t.exists(_n(e,Mr(i)))?i:void 0))).filter(i=>i!==void 0);return Cn(o)}async function Ns(e,t=Hr){try{let n=await $s(e,t);return!n.some(o=>o.path===Ts)||await t.readFile(_n(e,Ts))===void 0?!1:(await zr(e,n,t)).some(o=>o.status!=="unchanged")}catch{return!1}}var lp="@kizenapps/cli",dp=6e4,up=(e,t)=>new Promise((n,r)=>{let o=ip(e,[...t],{stdio:["ignore","pipe","pipe"],timeout:dp}),i="",s="";o.stdout.setEncoding("utf-8"),o.stderr.setEncoding("utf-8"),o.stdout.on("data",a=>{i+=a}),o.stderr.on("data",a=>{s+=a}),o.on("error",r),o.on("close",a=>{n({code:a,stdout:i,stderr:s})})}),Ds=e=>({run:up,hasOAuthSession:async t=>await Ue().readSession(t)!==null,cliVersion:e,fs:Hr,log:t=>{console.log(t)},error:t=>{console.error(t)},setExitCode:t=>{process.exitCode=t}}),Ur=(e,t)=>`${String(e.filter(n=>n.status===t).length)} ${t}`;function pp(e,t){let n=`kizen-${e}`,r=`${ut(e)}/api/mcp`,o=JSON.stringify({type:"http",url:r,headersHelper:`npx -y ${lp}@${t} auth-header`}),i=["mcp","add-json","--scope","user",n,o];return{environment:e,name:n,url:r,addArgs:i,addCommand:["claude",...i].map(be).join(" ")}}function fp(e){return e.mcp!==!0&&(e.env!==void 0||e.force===!0)?"--env and --force only apply with --mcp.":e.env===void 0?void 0:et(e.env).message}var mp=e=>/already\s+exists/i.test(`${e.stdout}
825
- ${e.stderr}`),As=e=>{let t=(e.stderr.trim()||e.stdout.trim()).replace(/\s+/g," "),n=e.code===null?"was stopped (timed out?)":`exited ${String(e.code)}`;return t===""?n:`${n}: ${t}`};async function hp(e,t,n){let r=pp(e,n.cliVersion),{name:o}=r,i=!1,s=a=>{n.error(`Error: couldn't register the MCP server ${o}: ${a}`),i&&(n.error(`The old ${o} registration was already removed, so Claude Code has no ${o} server now. Re-run \`appbuilder setup-claude --mcp --env ${e}\`, or run:`),n.error(` ${r.addCommand}`)),n.setExitCode(1)};if(t.dryRun){n.log(`Dry run: would register the MCP server ${r.name} with: ${r.addCommand}`);return}try{let a=await n.run("claude",r.addArgs);if(a.code!==0&&mp(a)){if(!t.force){n.log(`MCP server ${r.name} already exists in Claude Code; left unchanged. Pass --force to replace it.`);return}let c=await n.run("claude",["mcp","remove","--scope","user",r.name]);if(c.code!==0){s(`claude mcp remove --scope user ${As(c)}`);return}i=!0,a=await n.run("claude",r.addArgs)}if(a.code!==0){s(`claude mcp add-json ${As(a)}`);return}}catch(a){if(!i&&tn(a,"ENOENT")){n.log("Claude Code's `claude` command wasn't found. To register the MCP server, run (in a POSIX shell such as bash or zsh):"),n.log(` ${r.addCommand}`);return}s(Le(a));return}n.log(`Registered the MCP server ${r.name} (${r.url}) in Claude Code at user scope.`);try{await n.hasOAuthSession(e)||n.log(`You're not signed in to ${e} yet. Run \`${ye(e)}\` before using ${r.name}.`)}catch(a){n.log(Le(a))}}async function Rs(e,t,n){let r=fp(t);if(r!==void 0){n.error(`Error: ${r}`),n.setExitCode(1);return}if(!await n.fs.exists(_n(e,"kizen.json"))){n.error("Error: kizen.json not found. Run this command from a plugin directory."),n.setExitCode(1);return}let o=t.dryRun===!0,i;try{i=await Pn(e,await $s(e,n.fs,{includeLib:t.includeLib===!0}),{dryRun:o},n.fs)}catch(c){n.error(`Error: ${Le(c)}`),n.setExitCode(1);return}for(let c of i)n.log(En(c));let s=`${Ur(i,"created")}, ${Ur(i,"updated")}, ${Ur(i,"unchanged")}`,a="these files are managed by appbuilder, so local edits to them are replaced";n.log(o?`Dry run: ${s}; nothing written (${a}).`:`Claude files: ${s} (${a}).`),t.mcp===!0&&await hp((t.env===void 0?void 0:et(t.env).environment)??Me,{dryRun:o,force:t.force===!0},n)}function wp(e,t={}){let{fetch:n}=t;return{listSessions:()=>e.listSessions(),connect:async r=>{let o=dn(r,e,{...n&&{fetch:n}}),i=At({bearer:o,...n&&{fetch:n}});return{identity:await i.getIdentity(),client:i}}}}function Kr(e){return{cwd:e,loadCredentialsDetailed:en,listLoadableCredentialProfiles:Vo,loadConfig:we,packageBlocks:Br,createClient:t=>At({credentials:t}),readPushMap:Gi,writePushMap:Yi,ensureGitignore:ve,isClaudeSkillStale:t=>Ns(t),randomUUID:gp,now:()=>new Date,writeStdout:t=>{process.stdout.write(t)},writeStderr:t=>{process.stderr.write(t)},setExitCode:t=>{process.exitCode=t},oauth:wp(Ue())}}var vp=new Set(["owner","admin","edit"]),xp="Chart groups are not listed here; find them with `appbuilder block targets --object <id> --json` and pass --dashboard <id>.",Wr=e=>e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";function V(e,t,n={}){return{ok:!1,code:e,message:t,...n}}var fe=e=>({ok:!0,value:e});function Ke(e){return e instanceof Z?V(e.kind,e.message,e.hint===void 0?{}:{hint:e.hint}):e instanceof bp?V("validation_failed",Ae(e.issues),{issues:e.issues}):V("local_error",Wr(e))}async function Fs(e,t){let n;try{n=await t.loadCredentialsDetailed(e)}catch(i){return V("credentials_invalid",`Couldn't read credentials from ${e}: ${Wr(i)}`)}if(n.environmentSource!=="explicit"){let i=n.environmentSource==="missing"?'has no "environment"':'has an invalid "environment"';return V("credentials_invalid",`${e} ${i}. Set it to one of: ${W.join(", ")}. The CLI won't default to production.`)}let{credentials:r}=n,o=["apiKey","userId","businessId"].filter(i=>r[i].trim()==="");return o.length>0?V("credentials_invalid",`${e} is missing ${o.map(i=>`"${i}"`).join(", ")}.`):fe({credentials:r,client:t.createClient(r),notices:[]})}async function kp(e,t){let n=await t.listLoadableCredentialProfiles(),r=n.find(o=>o.name===e);if(!r){let o=n.map(i=>i.name);return V("credentials_invalid",o.length===0?`No loadable credential profile named "${e}". No profiles are loadable; create ${Oe} or pass -c <path>.`:`No loadable credential profile named "${e}". Loadable profiles: ${o.join(", ")}`)}return Fs(r.path,t)}async function Cp(e){let{activeCredentialProfile:t}=await e.loadConfig(yp(e.cwd,".kizenapp"));return t===void 0||t===""?[]:[ys(t)]}async function Sp(e,t){let n=[],r=await nt(e,async()=>(n=await t.oauth.listSessions(),n));if(!r.ok)switch(r.problem){case"not_signed_in":return V("credentials_invalid",bs(r.message));case"several_sessions":return V("needs_choice",r.message,{choice:"environment",choices:n.map(s=>({value:s,label:s,args:["--env",s]}))});case"unknown_environment":return V("usage_error",r.message)}let{environment:o}=r,i;try{i=await t.oauth.connect(o)}catch(s){return Ke(s)}return fe({credentials:{environment:o,businessId:i.identity.businessId},client:i.client,notices:await Cp(t)})}async function An(e,t){let n=gs(e);if(!n.ok)return V("usage_error",n.message);let{selection:r}=n;return r.kind==="oauth"?Sp(r.env,t):r.credentials===void 0?kp(r.profile,t):Fs(r.credentials,t)}function Pp(e,t){let n=new Set(t.map(r=>r.pluginApiName)).size>1;return t.map(({pluginApiName:r,apiName:o})=>{let i=e.find(a=>a.api_name===r)?.artifacts.custom_blocks.find(a=>a.api_name===o),s=n?`${r}/${o}`:o;return{value:o,label:`${i?.name??o} (${s})`,args:[o]}})}async function qr(e,t){let n=await t.packageBlocks(t.cwd),r=Fr(n,e,"push");if(!r.ok){let{reason:g,message:u,field:h}=r;return g==="no_blocks"||g==="invalid_block"?V("invalid_block",u,h===void 0?{}:{field:h}):V("needs_choice",u,{choice:"block",choices:Pp(n.deployable,r.available)})}let{block:o,pluginApiName:i,views:s,warnings:a}=r.value,c=ji(o,s);return fe({block:o,pluginApiName:i,content:c,contentHash:Ar(c),warnings:a})}var js=e=>e==null?null:vp.has(e.toLowerCase());function Nt(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:js(e.employee_access)}}var Ls=e=>({id:e.id,objectName:e.object_name,fetchUrl:e.fetch_url}),Ep="Contacts";async function Jr(e){let[t,n]=await Promise.all([e.listCustomObjects(),e.getClientObjectId().catch(()=>null)]),r=t.map(Ls).sort((o,i)=>o.objectName.localeCompare(i.objectName));return n!==null&&n!==""&&!r.some(o=>o.id===n)&&r.push({id:n,objectName:Ep,fetchUrl:"client"}),r}async function _p(e,t,n){let{environment:r,businessId:o}=t;try{if(n.object!==void 0){let c=n.object,[g,u]=await Promise.all([e.getCustomObject(c).catch(()=>null),e.listDashboards("chart_group",c)]);return fe({ok:!0,environment:r,businessId:o,object:g?Ls(g):null,surfaces:{chart_group:u.map(h=>Nt(h,"chart_group"))}})}let[i,s,a]=await Promise.all([e.listDashboards("generic_dashboard"),e.listDashboards("homepage"),Jr(e)]);return fe({ok:!0,environment:r,businessId:o,surfaces:{dashboard:i.map(c=>Nt(c,"dashboard")),homepage:s.map(c=>Nt(c,"homepage"))},customObjects:a})}catch(i){return Ke(i)}}var Gr=(e,t)=>t.dashboard===e.id;function In(e,t){return[...Ui(e).filter(r=>Gr(e,r)).map(r=>{let o=Ri(r.name);return{value:r.id,label:yn(r),args:["--dashboard",e.id,"--dashlet",r.id],pushKey:o?r.name:null,isFromThisPlugin:o?.pluginApiName===t.pluginApiName}}),{value:"new",label:"Create a new block",args:["--dashboard",e.id,"--create"]}]}var Yr=(e,t)=>Ki({dashboardId:t.id,dashlets:t.dashlets,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name,entry:e.entry}),Ms=(e,t)=>fe({dashboard:e,surface:Nr(e.type),action:"create",dashlet:void 0,resolvedBy:t}),Tn=(e,t,n)=>fe({dashboard:e,surface:Nr(e.type),action:"update",dashlet:t,resolvedBy:n});async function Tp(e){let[t,n]=await Promise.all([e.client.listDashboards("generic_dashboard"),e.client.listDashboards("homepage")]),r=o=>i=>({value:i.id,label:i.name,args:["--dashboard",i.id],surface:o,canEdit:js(i.employee_access)});return V("needs_choice",`Choose where to push; pass --dashboard <id>. ${xp}`,{choice:"dashboard",choices:[...t.map(r("dashboard")),...n.map(r("homepage"))]})}async function Ap(e,t,n){let r=await e.client.getDashboard(t);if(n.create)return Ms(r,"flag");let o=()=>In(r,e.block);if(n.dashlet!==void 0){let s=n.dashlet,a=r.dashlets.find(c=>c.id===s&&Gr(r,c));return a?mt(a)?Tn(r,a,"flag"):V("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.`):V("not_found",`Dashlet ${s} is not on dashboard "${r.name}" (${r.id}).`,{choice:"target",choices:o()})}let i=Yr(e,r);return i.kind==="map"?Tn(r,i.dashlet,"push_map"):i.kind==="name"?Tn(r,i.dashlet,"name"):V("needs_choice",i.kind==="ambiguous"?`Dashboard "${r.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 "${r.name}", or create a new one; pass --dashlet <id> or --create.`,{choice:"target",choices:o()})}async function Ip(e,t,n){let r;try{r=await e.client.getDashboard(t.dashboardId)}catch(i){if(i instanceof Z&&i.kind==="not_found")return V("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(n.create)return Ms(r,"remembered");let o=r.dashlets.find(i=>i.id===t.dashletId&&Gr(r,i));return o&&mt(o)?Tn(r,o,"remembered"):V("remembered_target_missing",`The remembered block (dashlet ${t.dashletId}) is no longer on "${r.name}". Choose a block to update, or create a new one.`,{choice:"target",choices:In(r,e.block)})}async function Xr(e,t){if(t.dashlet!==void 0&&t.create)return V("usage_error","Pass either --dashlet <id> or --create, not both.");if(t.dashlet!==void 0&&t.dashboard===void 0)return V("usage_error","--dashlet <id> needs --dashboard <id>.");try{return t.dashboard!==void 0?await Ap(e,t.dashboard,t):e.entry?await Ip(e,e.entry,t):await Tp(e)}catch(n){return Ke(n)}}async function $p(e,t,n){let r=t.custom_object;if(r==null||r==="")return null;if(typeof r!="string"){if(typeof r!="object"||typeof r.id!="string")return null;let{id:o,fetch_url:i}=r;return typeof i=="string"?{id:o,fetchUrl:i}:{id:o}}if(n!=="chart_group")return{id:r};try{let o=await e.getCustomObject(r);return{id:r,fetchUrl:o.fetch_url}}catch{return{id:r}}}async function Zr(e,t,n,r){let{credentials:o,block:i}=e,{dashboard:s,surface:a}=t,c=[],g,u;if(t.action==="update"){let{dashlet:v}=t;if(Wi(v,e.entry)){let p=`"${yn(v)}" (dashlet ${v.id}) was changed in Kizen since the last push.`;if(!n.force)return V("drift_detected",`${p} Pushing would overwrite those changes; pass --force to overwrite them.`);c.push(`${p} Overwriting it because of --force.`)}g={action:"update",method:"PATCH",path:Tt(s.id,v.id),body:Mi(v,i.content),dashletId:v.id},u=`Update "${yn(v)}" (dashlet ${v.id})`}else g={action:"create",method:"POST",path:Tt(s.id),body:Li({pluginApiName:i.pluginApiName,blockApiName:i.block.api_name,content:i.content,dashlets:s.dashlets,objectId:r.randomUUID(),layoutId:r.randomUUID()}),dashletId:null},u=`Create a new block on "${s.name}"`;let h=Zi({appBaseUrl:Lo[o.environment],surface:a,dashboardId:s.id,customObject:await $p(e.client,s,a)});return fe({...g,dashboard:{id:s.id,name:s.name,type:a},url:h,resolvedBy:t.resolvedBy,warnings:c,summary:{environment:o.environment,businessId:o.businessId,isProduction:ur(o.environment),surface:a,dashboardId:s.id,dashboardName:s.name,action:t.action,actionLine:u,dashletId:g.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 Qr=e=>({environment:e.credentials.environment,businessId:e.credentials.businessId,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name});async function eo(e,t,n){let r;try{if(t.action==="create"){let c=(await e.client.createDashlet(t.dashboard.id,t.body)).id;if(typeof c!="string"||c==="")return V("api_error",`POST ${t.path} succeeded but the response had no dashlet id; check "${t.dashboard.name}" before pushing again.`);r=c}else await e.client.updateDashlet(t.dashboard.id,t.dashletId,t.body),r=t.dashletId}catch(a){return Ke(a)}let o=[...t.warnings],i={...Qr(e),dashboardId:t.dashboard.id,dashletId:r,contentHash:e.block.contentHash,pushedAt:n.now().toISOString()},s=!1;try{n.ensureGitignore(n.cwd),await n.writePushMap(n.cwd,qi(e.pushMap,i)),s=!0}catch(a){o.push(`The push succeeded, but ${st} couldn't be written, so this target isn't remembered: ${Wr(a)}`)}return fe({dashletId:r,remembered:s,warnings:o})}var Np=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function to(e){return Np.test(e)?{dashboardId:e,script:`await window.__kizenCustomBlocks?.refresh('${e}')`}:null}async function Dp(e,t){let n=Qr(e);if(!$r(e.pushMap,n))return null;let r=Ji(e.pushMap,n);return await t.writePushMap(t.cwd,r),r}async function no(e,t){let{client:n,credentials:r,block:o}=e,i=await t.readPushMap(t.cwd),s=!1;if(e.forget){let a=await Dp({credentials:r,block:o,pushMap:i},t);a&&(i=a,s=!0)}return{context:{client:n,credentials:r,block:o,pushMap:i,entry:$r(i,Qr({credentials:r,block:o}))},forgotten:s}}function ro(e,t){return e.dryRun?fe({kind:"dry-run",reason:"flag"}):e.yes?ur(t)&&!e.allowProduction?V("production_requires_flag",`${t} is a production environment. Pass --allow-production with --yes to write to it.`):fe({kind:"apply"}):fe({kind:"dry-run",reason:"no_yes"})}var Rp="Dry run only: pass --yes to write.",at=e=>e.map(t=>`Warning: ${t}`);function Dt(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 Op=e=>`${e.path===void 0?"":`${e.path}: `}${e.message} (${e.rule})`;function Bp(e,t,n){let r=[`Error: ${e.message}`];if(e.hint!==void 0&&r.push(`Hint: ${e.hint}`),e.choices&&e.choices.length>0){r.push("Choices:");for(let o of e.choices){let i=n(o,e.choice).map(be).join(" ");r.push(` ${o.label} \u2192 ${t} ${i}`)}}return`${r.join(`
842
+ `;function jn(){return[{path:".github/copilot-instructions.md",content:sa},{path:".github/instructions/security.instructions.md",content:aa},{path:".github/instructions/version-discipline.instructions.md",content:ca},{path:".github/workflows/copilot-code-review.yml",content:la}]}var ua="lib/kizenData.js",go=(e="src")=>e===""?ua:`${e}/${ua}`;function Ln(e=[]){return[{path:".claude/skills/kizen-custom-block/SKILL.md",content:oa},{path:".claude/skills/kizen-custom-block/design.md",content:ia},...[...new Set(e)].map(t=>({path:go(t),content:da}))]}import{access as Df,mkdir as Rf,readFile as Of,writeFile as Bf}from"fs/promises";import{dirname as Ff,join as pa}from"path";var zn={readFile:async e=>{try{return await Of(e,"utf-8")}catch(t){if(fn(t))return;throw t}},writeFile:async(e,t)=>{await Rf(Ff(e),{recursive:!0}),await Bf(e,t,"utf-8")},exists:async e=>{try{return await Df(e),!0}catch{return!1}}},jf=(e,t)=>e===void 0?"created":e===t?"unchanged":"updated";async function yo(e,t,n=zn){return Promise.all(t.map(async r=>({path:r.path,status:jf(await n.readFile(pa(e,r.path)),r.content)})))}async function Mn(e,t,n={},r=zn){let o=await yo(e,t,r);return n.dryRun===!0||await Promise.all(t.filter((i,s)=>o[s]?.status!=="unchanged").map(i=>r.writeFile(pa(e,i.path),i.content))),o}var Un=e=>`${e.status.padEnd(9)} ${e.path}`;var fa=".claude/skills/kizen-custom-block/SKILL.md",ha="Claude files managed by appbuilder are out of date; run appbuilder setup-claude",wo=zn,zf=e=>{if(typeof e!="string"||e.trim()==="")return;let t=mn(e);if(!(t===".."||t.startsWith("../")||t.startsWith("/")))return t};function Mf(e){let n=(Array.isArray(e)?e:[e]).map(r=>typeof r=="object"&&r!==null&&"entry"in r?zf(r.entry):void 0).filter(r=>r!==void 0);return n.length>0?[...new Set(n)]:["src"]}var Uf=async(e,t)=>{try{let n=await t.readFile(Hn(e,"kizen.json"));return n===void 0?["src"]:Mf(JSON.parse(n))}catch{return["src"]}};async function ga(e,t=wo,n={}){let r=await Uf(e,t),o=n.includeLib===!0?r:(await Promise.all(r.map(async i=>await t.exists(Hn(e,go(i)))?i:void 0))).filter(i=>i!==void 0);return Ln(o)}async function ya(e,t=wo){try{let n=await ga(e,t);return!n.some(o=>o.path===fa)||await t.readFile(Hn(e,fa))===void 0?!1:(await yo(e,n,t)).some(o=>o.status!=="unchanged")}catch{return!1}}var Hf="@kizenapps/cli",Kf=6e4,Vf=(e,t)=>new Promise((n,r)=>{let o=Lf(e,[...t],{stdio:["ignore","pipe","pipe"],timeout:Kf}),i="",s="";o.stdout.setEncoding("utf-8"),o.stderr.setEncoding("utf-8"),o.stdout.on("data",a=>{i+=a}),o.stderr.on("data",a=>{s+=a}),o.on("error",r),o.on("close",a=>{n({code:a,stdout:i,stderr:s})})}),ba=e=>({run:Vf,hasOAuthSession:async t=>await Ce().readSession(t)!==null,cliVersion:e,fs:wo,log:t=>{console.log(t)},error:t=>{console.error(t)},setExitCode:t=>{process.exitCode=t}}),bo=(e,t)=>`${String(e.filter(n=>n.status===t).length)} ${t}`;function Wf(e,t){let n=`kizen-${e}`,r=`${ze(e)}/api/mcp`,o=JSON.stringify({type:"http",url:r,headersHelper:`npx -y ${Hf}@${t} auth-header`}),i=["mcp","add-json","--scope","user",n,o];return{environment:e,name:n,url:r,addArgs:i,addCommand:["claude",...i].map(le).join(" ")}}function qf(e){return e.mcp!==!0&&(e.env!==void 0||e.force===!0)?"--env and --force only apply with --mcp.":e.mcp===!0&&e.includeLib===!0?"--mcp and --include-lib can't be combined. Run `appbuilder setup-claude --include-lib` and `appbuilder setup-claude --mcp` separately.":e.env===void 0?void 0:ot(e.env).message}var Gf=e=>/already\s+exists/i.test(`${e.stdout}
843
+ ${e.stderr}`),ma=e=>{let t=(e.stderr.trim()||e.stdout.trim()).replace(/\s+/g," "),n=e.code===null?"was stopped (timed out?)":`exited ${String(e.code)}`;return t===""?n:`${n}: ${t}`};async function Jf(e,t,n){let r=Wf(e,n.cliVersion),{name:o}=r,i=!1,s=a=>{n.error(`Error: couldn't register the MCP server ${o}: ${a}`),i&&(n.error(`The old ${o} registration was already removed, so Claude Code has no ${o} server now. Re-run \`appbuilder setup-claude --mcp --env ${e}\`, or run:`),n.error(` ${r.addCommand}`)),n.setExitCode(1)};if(t.dryRun){n.log(`Dry run: would register the MCP server ${r.name} with: ${r.addCommand}`);return}try{let a=await n.run("claude",r.addArgs);if(a.code!==0&&Gf(a)){if(!t.force){n.log(`MCP server ${r.name} already exists in Claude Code; left unchanged. Pass --force to replace it.`);return}let c=await n.run("claude",["mcp","remove","--scope","user",r.name]);if(c.code!==0){s(`claude mcp remove --scope user ${ma(c)}`);return}i=!0,a=await n.run("claude",r.addArgs)}if(a.code!==0){s(`claude mcp add-json ${ma(a)}`);return}}catch(a){if(!i&&Te(a,"ENOENT")){n.log("Claude Code's `claude` command wasn't found. To register the MCP server, run (in a POSIX shell such as bash or zsh):"),n.log(` ${r.addCommand}`);return}s(oe(a));return}n.log(`Registered the MCP server ${r.name} (${r.url}) in Claude Code at user scope.`);try{await n.hasOAuthSession(e)||n.log(`You're not signed in to ${e} yet. Run \`${xe(e)}\` before using ${r.name}.`)}catch(a){n.log(oe(a))}}async function wa(e,t,n){let r=qf(t);if(r!==void 0){n.error(`Error: ${r}`),n.setExitCode(1);return}let o=t.dryRun===!0;if(t.mcp===!0){await Jf((t.env===void 0?void 0:ot(t.env).environment)??Ue,{dryRun:o,force:t.force===!0},n);return}if(!await n.fs.exists(Hn(e,"kizen.json"))){n.error("Error: kizen.json not found. Run this command from a plugin directory, or pass --mcp to only register the MCP server."),n.setExitCode(1);return}let i;try{i=await Mn(e,await ga(e,n.fs,{includeLib:t.includeLib===!0}),{dryRun:o},n.fs)}catch(c){n.error(`Error: ${oe(c)}`),n.setExitCode(1);return}for(let c of i)n.log(Un(c));let s=`${bo(i,"created")}, ${bo(i,"updated")}, ${bo(i,"unchanged")}`,a="these files are managed by appbuilder, so local edits to them are replaced";n.log(o?`Dry run: ${s}; nothing written (${a}).`:`Claude files: ${s} (${a}).`)}function Qf(e,t={}){let{fetch:n}=t;return{listSessions:()=>e.listSessions(),listAccounts:r=>e.listAccounts(r),connect:async(r,o)=>{let i=wn(r,e,{...n&&{fetch:n},...o!==void 0&&{account:o}}),s=Bt({bearer:i,...n&&{fetch:n}});return{identity:await s.getIdentity(),client:s}}}}function xo(e){return{cwd:e,loadCredentialsDetailed:yn,listLoadableCredentialProfiles:Ii,loadConfig:Se,packageBlocks:po,createClient:t=>Bt({credentials:t}),readPushMap:Fs,writePushMap:js,ensureGitignore:Pe,isClaudeSkillStale:t=>ya(t),randomUUID:Yf,now:()=>new Date,writeStdout:t=>{process.stdout.write(t)},writeStderr:t=>{process.stderr.write(t)},setExitCode:t=>{process.exitCode=t},processEnv:process.env,oauth:Qf(Ce())}}var em=new Set(["owner","admin","edit"]),tm="Chart groups are not listed here; find them with `appbuilder block targets --object <id> --json` and pass --dashboard <id>.",Vn=e=>e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";function K(e,t,n={}){return{ok:!1,code:e,message:t,...n}}var ge=e=>({ok:!0,value:e});function Re(e){return e instanceof Z?K(e.kind,e.message,e.hint===void 0?{}:{hint:e.hint}):e instanceof Zf?K("validation_failed",De(e.issues),{issues:e.issues}):K("local_error",Vn(e))}async function ka(e,t){let n;try{n=await t.loadCredentialsDetailed(e)}catch(i){return K("credentials_invalid",`Couldn't read credentials from ${e}: ${Vn(i)}`)}if(n.environmentSource!=="explicit"){let i=n.environmentSource==="missing"?'has no "environment"':'has an invalid "environment"';return K("credentials_invalid",`${e} ${i}. Set it to one of: ${W.join(", ")}. The CLI won't default to production.`)}let{credentials:r}=n,o=["apiKey","userId","businessId"].filter(i=>r[i].trim()==="");return o.length>0?K("credentials_invalid",`${e} is missing ${o.map(i=>`"${i}"`).join(", ")}.`):ge({credentials:r,client:t.createClient(r),notices:[]})}async function nm(e,t){let n=await t.listLoadableCredentialProfiles(),r=n.find(o=>o.name===e);if(!r){let o=n.map(i=>i.name);return K("credentials_invalid",o.length===0?`No loadable credential profile named "${e}". No profiles are loadable; create ${He} or pass -c <path>.`:`No loadable credential profile named "${e}". Loadable profiles: ${o.join(", ")}`)}return ka(r.path,t)}async function rm(e){let{activeCredentialProfile:t}=await e.loadConfig(Xf(e.cwd,".kizenapp"));return t===void 0||t===""?[]:[Si(t)]}async function om(e,t,n){let r=await zt(e,t,n.oauth);if(!r.ok)switch(r.problem){case"not_signed_in":return K("credentials_invalid",Pi(r.message));case"several_sessions":return K("needs_choice",r.message,{choice:"environment",choices:r.environments.map(a=>({value:a,label:a,args:["--env",a]}))});case"unknown_environment":return K("usage_error",r.message)}let{environment:o}=r,i;if(t!==void 0){let a;try{a=await n.oauth.listAccounts(o)}catch(c){return Re(c)}try{i=Mt(o,a,t)}catch(c){return K("usage_error",Vn(c))}}let s;try{s=await n.oauth.connect(o,i)}catch(a){return Re(a)}return ge({credentials:{environment:o,businessId:s.identity.businessId},client:s.client,notices:await rm(n)})}async function Wn(e,t){let n=Ci(e,t.processEnv);if(!n.ok)return K("usage_error",n.message);let{selection:r}=n;return r.kind==="oauth"?om(r.env,r.account,t):r.credentials===void 0?nm(r.profile,t):ka(r.credentials,t)}function im(e,t){let n=new Set(t.map(r=>r.pluginApiName)).size>1;return t.map(({pluginApiName:r,apiName:o})=>{let i=e.find(a=>a.api_name===r)?.artifacts.custom_blocks.find(a=>a.api_name===o),s=n?`${r}/${o}`:o;return{value:o,label:`${i?.name??o} (${s})`,args:[o]}})}async function ko(e,t){let n=await t.packageBlocks(t.cwd),r=fo(n,e,"push");if(!r.ok){let{reason:g,message:m,field:h}=r;return g==="no_blocks"||g==="invalid_block"?K("invalid_block",m,h===void 0?{}:{field:h}):K("needs_choice",m,{choice:"block",choices:im(n.deployable,r.available)})}let{block:o,pluginApiName:i,views:s,warnings:a}=r.value,c=Es(o,s);return ge({block:o,pluginApiName:i,content:c,contentHash:oo(c),warnings:a})}var Ca=e=>e==null?null:em.has(e.toLowerCase());function Wt(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:Ca(e.employee_access)}}var Sa=e=>({id:e.id,objectName:e.object_name,fetchUrl:e.fetch_url}),sm="Contacts";async function Co(e){let[t,n]=await Promise.all([e.listCustomObjects(),e.getClientObjectId().catch(()=>null)]),r=t.map(Sa).sort((o,i)=>o.objectName.localeCompare(i.objectName));return n!==null&&n!==""&&!r.some(o=>o.id===n)&&r.push({id:n,objectName:sm,fetchUrl:"client"}),r}async function am(e,t,n){let{environment:r,businessId:o}=t;try{if(n.object!==void 0){let c=n.object,[g,m]=await Promise.all([e.getCustomObject(c).catch(()=>null),e.listDashboards("chart_group",c)]);return ge({ok:!0,environment:r,businessId:o,object:g?Sa(g):null,surfaces:{chart_group:m.map(h=>Wt(h,"chart_group"))}})}let[i,s,a]=await Promise.all([e.listDashboards("generic_dashboard"),e.listDashboards("homepage"),Co(e)]);return ge({ok:!0,environment:r,businessId:o,surfaces:{dashboard:i.map(c=>Wt(c,"dashboard")),homepage:s.map(c=>Wt(c,"homepage"))},customObjects:a})}catch(i){return Re(i)}}var So=(e,t)=>t.dashboard===e.id;function qn(e,t){return[...Is(e).filter(r=>So(e,r)).map(r=>{let o=ks(r.name);return{value:r.id,label:Dn(r),args:["--dashboard",e.id,"--dashlet",r.id],pushKey:o?r.name:null,isFromThisPlugin:o?.pluginApiName===t.pluginApiName}}),{value:"new",label:"Create a new block",args:["--dashboard",e.id,"--create"]}]}var Po=(e,t)=>Ds({dashboardId:t.id,dashlets:t.dashlets,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name,entry:e.entry}),Pa=(e,t)=>ge({dashboard:e,surface:ao(e.type),action:"create",dashlet:void 0,resolvedBy:t}),Kn=(e,t,n)=>ge({dashboard:e,surface:ao(e.type),action:"update",dashlet:t,resolvedBy:n});async function cm(e){let[t,n]=await Promise.all([e.client.listDashboards("generic_dashboard"),e.client.listDashboards("homepage")]),r=o=>i=>({value:i.id,label:i.name,args:["--dashboard",i.id],surface:o,canEdit:Ca(i.employee_access)});return K("needs_choice",`Choose where to push; pass --dashboard <id>. ${tm}`,{choice:"dashboard",choices:[...t.map(r("dashboard")),...n.map(r("homepage"))]})}async function lm(e,t,n){let r=await e.client.getDashboard(t);if(n.create)return Pa(r,"flag");let o=()=>qn(r,e.block);if(n.dashlet!==void 0){let s=n.dashlet,a=r.dashlets.find(c=>c.id===s&&So(r,c));return a?wt(a)?Kn(r,a,"flag"):K("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.`):K("not_found",`Dashlet ${s} is not on dashboard "${r.name}" (${r.id}).`,{choice:"target",choices:o()})}let i=Po(e,r);return i.kind==="map"?Kn(r,i.dashlet,"push_map"):i.kind==="name"?Kn(r,i.dashlet,"name"):K("needs_choice",i.kind==="ambiguous"?`Dashboard "${r.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 "${r.name}", or create a new one; pass --dashlet <id> or --create.`,{choice:"target",choices:o()})}async function dm(e,t,n){let r;try{r=await e.client.getDashboard(t.dashboardId)}catch(i){if(i instanceof Z&&i.kind==="not_found")return K("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(n.create)return Pa(r,"remembered");let o=r.dashlets.find(i=>i.id===t.dashletId&&So(r,i));return o&&wt(o)?Kn(r,o,"remembered"):K("remembered_target_missing",`The remembered block (dashlet ${t.dashletId}) is no longer on "${r.name}". Choose a block to update, or create a new one.`,{choice:"target",choices:qn(r,e.block)})}async function Eo(e,t){if(t.dashlet!==void 0&&t.create)return K("usage_error","Pass either --dashlet <id> or --create, not both.");if(t.dashlet!==void 0&&t.dashboard===void 0)return K("usage_error","--dashlet <id> needs --dashboard <id>.");try{return t.dashboard!==void 0?await lm(e,t.dashboard,t):e.entry?await dm(e,e.entry,t):await cm(e)}catch(n){return Re(n)}}async function um(e,t,n){let r=t.custom_object;if(r==null||r==="")return null;if(typeof r!="string"){if(typeof r!="object"||typeof r.id!="string")return null;let{id:o,fetch_url:i}=r;return typeof i=="string"?{id:o,fetchUrl:i}:{id:o}}if(n!=="chart_group")return{id:r};try{let o=await e.getCustomObject(r);return{id:r,fetchUrl:o.fetch_url}}catch{return{id:r}}}async function _o(e,t,n,r){let{credentials:o,block:i}=e,{dashboard:s,surface:a}=t,c=[],g,m;if(t.action==="update"){let{dashlet:y}=t;if(Rs(y,e.entry)){let f=`"${Dn(y)}" (dashlet ${y.id}) was changed in Kizen since the last push.`;if(!n.force)return K("drift_detected",`${f} Pushing would overwrite those changes; pass --force to overwrite them.`);c.push(`${f} Overwriting it because of --force.`)}g={action:"update",method:"PATCH",path:Ot(s.id,y.id),body:As(y,i.content),dashletId:y.id},m=`Update "${Dn(y)}" (dashlet ${y.id})`}else g={action:"create",method:"POST",path:Ot(s.id),body:_s({pluginApiName:i.pluginApiName,blockApiName:i.block.api_name,content:i.content,dashlets:s.dashlets,objectId:r.randomUUID(),layoutId:r.randomUUID()}),dashletId:null},m=`Create a new block on "${s.name}"`;let h=zs({appBaseUrl:pi[o.environment],surface:a,dashboardId:s.id,customObject:await um(e.client,s,a)});return ge({...g,dashboard:{id:s.id,name:s.name,type:a},url:h,resolvedBy:t.resolvedBy,warnings:c,summary:{environment:o.environment,businessId:o.businessId,isProduction:Ar(o.environment),surface:a,dashboardId:s.id,dashboardName:s.name,action:t.action,actionLine:m,dashletId:g.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 Ao=e=>({environment:e.credentials.environment,businessId:e.credentials.businessId,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name});async function To(e,t,n){let r;try{if(t.action==="create"){let c=(await e.client.createDashlet(t.dashboard.id,t.body)).id;if(typeof c!="string"||c==="")return K("api_error",`POST ${t.path} succeeded but the response had no dashlet id; check "${t.dashboard.name}" before pushing again.`);r=c}else await e.client.updateDashlet(t.dashboard.id,t.dashletId,t.body),r=t.dashletId}catch(a){return Re(a)}let o=[...t.warnings],i={...Ao(e),dashboardId:t.dashboard.id,dashletId:r,contentHash:e.block.contentHash,pushedAt:n.now().toISOString()},s=!1;try{n.ensureGitignore(n.cwd),await n.writePushMap(n.cwd,Os(e.pushMap,i)),s=!0}catch(a){o.push(`The push succeeded, but ${pt} couldn't be written, so this target isn't remembered: ${Vn(a)}`)}return ge({dashletId:r,remembered:s,warnings:o})}var pm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Io(e){return pm.test(e)?{dashboardId:e,script:`await window.__kizenCustomBlocks?.refresh('${e}')`}:null}async function fm(e,t){let n=Ao(e);if(!so(e.pushMap,n))return null;let r=Bs(e.pushMap,n);return await t.writePushMap(t.cwd,r),r}async function $o(e,t){let{client:n,credentials:r,block:o}=e,i=await t.readPushMap(t.cwd),s=!1;if(e.forget){let a=await fm({credentials:r,block:o,pushMap:i},t);a&&(i=a,s=!0)}return{context:{client:n,credentials:r,block:o,pushMap:i,entry:so(i,Ao({credentials:r,block:o}))},forgotten:s}}function No(e,t){return e.dryRun?ge({kind:"dry-run",reason:"flag"}):e.yes?Ar(t)&&!e.allowProduction?K("production_requires_flag",`${t} is a production environment. Pass --allow-production with --yes to write to it.`):ge({kind:"apply"}):ge({kind:"dry-run",reason:"no_yes"})}var mm="Dry run only: pass --yes to write.",ft=e=>e.map(t=>`Warning: ${t}`);function qt(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 hm=e=>`${e.path===void 0?"":`${e.path}: `}${e.message} (${e.rule})`;function gm(e,t,n){let r=[`Error: ${e.message}`];if(e.hint!==void 0&&r.push(`Hint: ${e.hint}`),e.choices&&e.choices.length>0){r.push("Choices:");for(let o of e.choices){let i=n(o,e.choice).map(le).join(" ");r.push(` ${o.label} \u2192 ${t} ${i}`)}}return`${r.join(`
826
844
  `)}
827
- `}function zs(e,t,n,r){e.json?e.deps.writeStdout(`${JSON.stringify(t,null,2)}
828
- `):e.deps.writeStderr(Bp(t,n,r)),e.deps.setExitCode(1)}function Os(e,t,n,r=n){e.json?(e.deps.writeStdout(`${JSON.stringify(t,null,2)}
829
- `),e.deps.writeStderr(r)):e.deps.writeStdout(n)}var Bs=e=>e.credentials!==void 0?["-c",e.credentials]:e.profile!==void 0?["--profile",e.profile]:e.env===void 0?[]:["--env",e.env],Us=(e,t)=>{for(let n of t)e.writeStderr(`${n}
830
- `)};async function Fp(e){try{return await e.isClaudeSkillStale(e.cwd)?[Is]:[]}catch{return[]}}async function Hs(e,t,n){let r={json:t.json===!0,deps:n},o="appbuilder block push",i=e===void 0?[]:[e],s=(c,g)=>g==="environment"?[...i,...c.args]:g==="block"?[...c.args,...Bs(t)]:[...i,...Bs(t),...c.args],a=c=>{zs(r,c,o,s)};try{let c=await An(t,n);if(!c.ok){a(c);return}let{credentials:g,client:u,notices:h}=c.value;Us(n,h);let v=await qr(e,n);if(!v.ok){a(v);return}let p=v.value;i=[p.block.api_name],p.warnings.length>0&&n.writeStderr(`${Ae(p.warnings)}
831
- `);let{context:l,forgotten:w}=await no({client:u,credentials:g,block:p,forget:t.forget===!0},n);w&&n.writeStderr(`Forgot the remembered target for ${p.block.api_name}.
832
- `);let C=await Xr(l,t);if(!C.ok){a(C);return}let E=ro(t,g.environment);if(!E.ok){a(E);return}let x=await Zr(l,C.value,t,n);if(!x.ok){a(x);return}let y=x.value,P={pluginApiName:p.pluginApiName,apiName:p.block.api_name,name:p.block.name},b={environment:g.environment,businessId:g.businessId,dashboard:y.dashboard},f=[...p.warnings.map(Op),...await Fp(n)],d=E.value;if(d.kind==="dry-run"){let R=[...f,...y.warnings],z={ok:!0,applied:!1,dryRun:!0,reason:d.reason,action:y.action,...b,dashletId:y.dashletId,url:y.url,resolvedBy:y.resolvedBy,block:P,method:y.method,path:y.path,body:y.body,warnings:R,...w?{forgotten:!0}:{}};Os(r,z,[...Dt(y.summary),`URL: ${y.url}`,...at(R),"",`${y.method} ${y.path}`,JSON.stringify(y.body,null,2),""].join(`
833
- `),[...Dt(y.summary),...at(R),""].join(`
834
- `)),d.reason==="no_yes"&&n.writeStderr(`${Rp}
835
- `);return}let m=await eo(l,y,n);if(!m.ok){a(m);return}let k=m.value,S=[...f,...k.warnings],T=to(y.dashboard.id),_={ok:!0,applied:!0,dryRun:!1,action:y.action==="create"?"created":"updated",...b,dashletId:k.dashletId,url:y.url,...T?{refresh:T}:{},resolvedBy:y.resolvedBy,block:P,remembered:k.remembered,warnings:S,...w?{forgotten:!0}:{}};Os(r,_,[`\u2713 ${_.action==="created"?"Created":"Updated"} ${p.block.name} on "${y.dashboard.name}" (dashlet ${k.dashletId})`,...Dt(y.summary),`URL: ${y.url}`,...T?[`Refresh an open tab: ${T.script}`]:[],...at(S),""].join(`
836
- `))}catch(c){a(Ke(c))}}var jp=(e,t)=>e.padEnd(t);function Vr(e,t){if(t.length===0)return[e," (none)"];let n=["NAME","ID","DASHLETS","ACCESS"],r=t.map(s=>[`${s.name}${s.hidden?" (hidden)":""}`,s.id,s.dashletsCount===null?"-":String(s.dashletsCount),`${s.employeeAccess??"-"}${s.canEdit===!1?" (no edit access)":""}`]),o=n.map((s,a)=>Math.max(s.length,...r.map(c=>(c[a]??"").length))),i=s=>` ${s.map((a,c)=>jp(a,o[c]??0)).join(" ")}`.trimEnd();return[e,i(n),...r.map(i)]}function Lp(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})`,"",...Vr("Chart groups",e.surfaces.chart_group)):t.push(...Vr("Dashboards",e.surfaces.dashboard),"",...Vr("Homepages",e.surfaces.homepage),"","Custom objects",...e.customObjects.length===0?[" (none)"]:e.customObjects.map(n=>` ${n.objectName} ${n.id}`),"","List an object\u2019s chart groups with `appbuilder block targets --object <id>`."),`${t.join(`
845
+ `}function Ea(e,t,n,r){e.json?e.deps.writeStdout(`${JSON.stringify(t,null,2)}
846
+ `):e.deps.writeStderr(gm(t,n,r)),e.deps.setExitCode(1)}function va(e,t,n,r=n){e.json?(e.deps.writeStdout(`${JSON.stringify(t,null,2)}
847
+ `),e.deps.writeStderr(r)):e.deps.writeStdout(n)}var Do=(e,t)=>{let n=It(e,t);if(!n.ok||n.request===void 0)return[];let{business:r,user:o}=n.request;return["--business",r,...o===void 0?[]:["--user",o]]},xa=(e,t)=>e.credentials!==void 0?["-c",e.credentials]:e.profile!==void 0?["--profile",e.profile]:[...e.env===void 0?[]:["--env",e.env],...Do(e,t)],_a=(e,t)=>{for(let n of t)e.writeStderr(`${n}
848
+ `)};async function ym(e){try{return await e.isClaudeSkillStale(e.cwd)?[ha]:[]}catch{return[]}}async function Aa(e,t,n){let r={json:t.json===!0,deps:n},o="appbuilder block push",i=e===void 0?[]:[e],s=(c,g)=>g==="environment"?[...i,...c.args,...Do(t,n.processEnv)]:g==="block"?[...c.args,...xa(t,n.processEnv)]:[...i,...xa(t,n.processEnv),...c.args],a=c=>{Ea(r,c,o,s)};try{let c=await Wn(t,n);if(!c.ok){a(c);return}let{credentials:g,client:m,notices:h}=c.value;_a(n,h);let y=await ko(e,n);if(!y.ok){a(y);return}let f=y.value;i=[f.block.api_name],f.warnings.length>0&&n.writeStderr(`${De(f.warnings)}
849
+ `);let{context:u,forgotten:w}=await $o({client:m,credentials:g,block:f,forget:t.forget===!0},n);w&&n.writeStderr(`Forgot the remembered target for ${f.block.api_name}.
850
+ `);let k=await Eo(u,t);if(!k.ok){a(k);return}let _=No(t,g.environment);if(!_.ok){a(_);return}let P=await _o(u,k.value,t,n);if(!P.ok){a(P);return}let C=P.value,T={pluginApiName:f.pluginApiName,apiName:f.block.api_name,name:f.block.name},v={environment:g.environment,businessId:g.businessId,dashboard:C.dashboard},l=[...f.warnings.map(hm),...await ym(n)],d=_.value;if(d.kind==="dry-run"){let $=[...l,...C.warnings],M={ok:!0,applied:!1,dryRun:!0,reason:d.reason,action:C.action,...v,dashletId:C.dashletId,url:C.url,resolvedBy:C.resolvedBy,block:T,method:C.method,path:C.path,body:C.body,warnings:$,...w?{forgotten:!0}:{}};va(r,M,[...qt(C.summary),`URL: ${C.url}`,...ft($),"",`${C.method} ${C.path}`,JSON.stringify(C.body,null,2),""].join(`
851
+ `),[...qt(C.summary),...ft($),""].join(`
852
+ `)),d.reason==="no_yes"&&n.writeStderr(`${mm}
853
+ `);return}let p=await To(u,C,n);if(!p.ok){a(p);return}let b=p.value,x=[...l,...b.warnings],S=Io(C.dashboard.id),E={ok:!0,applied:!0,dryRun:!1,action:C.action==="create"?"created":"updated",...v,dashletId:b.dashletId,url:C.url,...S?{refresh:S}:{},resolvedBy:C.resolvedBy,block:T,remembered:b.remembered,warnings:x,...w?{forgotten:!0}:{}};va(r,E,[`\u2713 ${E.action==="created"?"Created":"Updated"} ${f.block.name} on "${C.dashboard.name}" (dashlet ${b.dashletId})`,...qt(C.summary),`URL: ${C.url}`,...S?[`Refresh an open tab: ${S.script}`]:[],...ft(x),""].join(`
854
+ `))}catch(c){a(Re(c))}}var bm=(e,t)=>e.padEnd(t);function vo(e,t){if(t.length===0)return[e," (none)"];let n=["NAME","ID","DASHLETS","ACCESS"],r=t.map(s=>[`${s.name}${s.hidden?" (hidden)":""}`,s.id,s.dashletsCount===null?"-":String(s.dashletsCount),`${s.employeeAccess??"-"}${s.canEdit===!1?" (no edit access)":""}`]),o=n.map((s,a)=>Math.max(s.length,...r.map(c=>(c[a]??"").length))),i=s=>` ${s.map((a,c)=>bm(a,o[c]??0)).join(" ")}`.trimEnd();return[e,i(n),...r.map(i)]}function wm(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})`,"",...vo("Chart groups",e.surfaces.chart_group)):t.push(...vo("Dashboards",e.surfaces.dashboard),"",...vo("Homepages",e.surfaces.homepage),"","Custom objects",...e.customObjects.length===0?[" (none)"]:e.customObjects.map(n=>` ${n.objectName} ${n.id}`),"","List an object\u2019s chart groups with `appbuilder block targets --object <id>`."),`${t.join(`
837
855
  `)}
838
- `}async function Vs(e,t){let n={json:e.json===!0,deps:t},r="appbuilder block targets",o=e.object===void 0?[]:["--object",e.object],i=a=>[...a.args,...o],s=a=>{zs(n,a,r,i)};try{let a=await An(e,t);if(!a.ok){s(a);return}let{credentials:c,client:g,notices:u}=a.value;Us(t,u);let h=await _p(g,c,e.object===void 0?{}:{object:e.object});if(!h.ok){s(h);return}t.writeStdout(n.json?`${JSON.stringify(h.value,null,2)}
839
- `:Lp(h.value))}catch(a){s(Ke(a))}}import{useEffect as Js,useState as $n}from"react";import{Box as ce,Text as Y,useApp as Xp,useInput as Zs}from"ink";import"@kizenapps/packager";import{Box as Hp,Text as Vp}from"ink";import{Box as Mp,Text as zp}from"ink";import{jsx as Ks}from"react/jsx-runtime";var Up=[" :::::::: "," :::::: ::::::::::: "," :::::: :::::::::: "," :::::: :::::: ::::::: "," ::::: :::::: ::::::::::::::::: "," ::::: ::::: ::::::::::::::::::: "," ::::: ::::: :::::: ::::: ",":::: ::::: ::: ::::: :: ","::::: :::::: :::::::::: ","::::: :::::: ::::::::::: "," ::::: ::: ::::::: "," ::::::: ::: ::::: "," ::::::::::: :::::: :::::"," :::::::::: :::::: :::::"," :: ::::: ::: ::::: ::::"," ::::: :::::: ::::: ::::: ::: "," ::::::::::::::::::: ::::: ::::: "," ::::::::::::::::: ::::: ::::: "," ::::::::: :::::: :::::: "," :::::::::: :::::: "," ::::::::::: :::::: "," :::::::: "],Ws=()=>Ks(Mp,{flexDirection:"column",children:Up.map((e,t)=>Ks(zp,{color:"cyan",children:e},t))});import{Fragment as Kp,jsx as oo,jsxs as Wp}from"react/jsx-runtime";var J=({marginBottom:e=0})=>Wp(Kp,{children:[oo(Ws,{}),oo(Hp,{flexDirection:"column",marginTop:1,marginBottom:e,children:oo(Vp,{bold:!0,color:"cyan",children:"Kizen App Development Toolkit"})})]});import{useEffect as qp,useState as Jp}from"react";import{Text as Gp}from"ink";import{jsx as Yp}from"react/jsx-runtime";var qs=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],xe=()=>{let[e,t]=Jp(0);return qp(()=>{let n=setInterval(()=>{t(r=>(r+1)%qs.length)},80);return()=>{clearInterval(n)}},[]),Yp(Gp,{color:"cyan",children:qs[e]??"\u280B"})};import{Fragment as af,jsx as D,jsxs as G}from"react/jsx-runtime";var Gs=[{key:"dashboard",label:"Dashboard"},{key:"homepage",label:"Homepage"},{key:"chart_group",label:"Chart group"}],Zp={dashboard:"dashboard",homepage:"homepage",chart_group:"chart group"},io="\u2191/\u2193 to move, Enter to select, Esc to go back",Qp="The block was edited in Kizen since your last push. Overwriting discards those edits.",Nn=e=>e.args.includes("--create");function Ys(e,t){let n=e.filter(i=>i.value===t),r=e.filter(Nn),o=e.filter(i=>i.value!==t&&!Nn(i));return n.length>0?[...n,...o,...r]:[...r,...o]}function gt(e,t){return(n,r)=>{let o=e[r];o!==void 0&&t(o)}}function ef(e,t){if(Nn(e))return{key:e.value,label:e.label};if(e.value===t)return{key:e.value,label:`Update "${e.label}" (last pushed here)`};let n=e.isFromThisPlugin?"pushed from this plugin":e.pushKey;return{key:e.value,label:`Update "${e.label}"`,...n?{description:n}:{}}}function tf(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 n=[e.employeeAccess,e.hidden?"hidden":null].filter(r=>r!==null&&r!=="").join(" \xB7 ");return{key:e.id,label:t,...n===""?{}:{description:n}}}function nf(e,t,n){let r={...e,dashboard:t};return delete r.dashlet,delete r.create,Nn(n)?{...r,create:!0}:{...r,dashlet:n.value}}function rf(e,t,n,r){let o=p=>{t.setExitCode(1),n({type:"error",view:p})},i=p=>{p().catch(l=>{o(Ke(l))})},s=async(p,l)=>{n({type:"applying",plan:l});let w=await eo(p,l,t);if(!w.ok){o(w);return}n({type:"done",plan:l,applied:w.value})},a=async(p,l,w)=>{n({type:"loading",label:"Preparing the push\u2026"});let C=await Zr(p,l,w,t);if(!C.ok){if(C.code==="drift_detected"){n({type:"confirm",kind:"drift",message:C.message,target:l,options:w,context:p});return}o(C);return}if(w.dryRun){n({type:"done",plan:C.value,applied:null});return}if(w.yes){let E=ro(w,p.credentials.environment);if(E.ok&&E.value.kind==="apply"){await s(p,C.value);return}}n({type:"confirm",kind:"push",plan:C.value,options:w,context:p})},c=async(p,l,w)=>{n({type:"loading",label:"Resolving the target\u2026"});let C=await Xr(p,l);if(C.ok){await a(p,C.value,l);return}let E=l.dashboard??p.entry?.dashboardId;if((C.code==="needs_choice"&&C.choice==="target"||C.code==="remembered_target_missing")&&C.choices&&C.choices.length>0&&E!==void 0){n({type:"target-select",dashboardId:E,title:"Choose a block to update, or create a new one",message:C.message,choices:Ys(C.choices,null),matchedId:null,back:w,options:l,context:p});return}o(C)},g=async(p,{credentials:l,client:w},C)=>{let{context:E,forgotten:x}=await no({client:w,credentials:l,block:C,forget:p.forget===!0},t);if(x&&r(y=>({...y,notices:[...y.notices,`Forgot the remembered target for ${C.block.api_name}.`]})),p.dashboard!==void 0||E.entry){await c(E,p,null);return}n({type:"surface-select",options:p,context:E})},u=async(p,l,w)=>{n({type:"packaging"});let C=await qr(w,t);if(!C.ok){if(C.choice==="block"&&C.choices){n({type:"block-select",options:p,resolved:l,choices:C.choices});return}o(C);return}r(E=>({...E,warnings:C.value.warnings})),await g(p,l,C.value)},h=async p=>{n({type:"loading",label:"Loading credentials\u2026"});let l=await An(p,t);if(!l.ok){if(l.choice==="environment"&&l.choices){n({type:"environment-select",options:p,choices:l.choices});return}o(l);return}r(w=>({...w,credentials:l.value.credentials,credentialNotices:l.value.notices})),await u(p,l.value,e)},v=async({options:p,context:l},w,C,E)=>{let x=Zp[w];n({type:"loading",label:`Loading ${x}s\u2026`});let P=(await l.client.listDashboards(Xi(w),C?.id)).map(d=>Nt(d,w)),{environment:b,businessId:f}=l.credentials;if(P.length===0){o({message:`No ${x}s found${C?` on ${C.objectName}`:""} for business ${f} (${b}).`});return}n({type:"dashboard-select",surface:w,objectId:C?.id??null,title:C?`Choose a chart group on ${C.objectName}`:`Choose a ${x}`,rows:P,back:E,options:p,context:l})};return{start:p=>{i(()=>h(p))},pickEnvironment:(p,l)=>{i(()=>h({...p.options,env:l.value}))},pickBlock:(p,l)=>{i(()=>u(p.options,p.resolved,l.value))},pickSurface:(p,l)=>{i(async()=>{if(l!=="chart_group"){await v(p,l,null,p);return}n({type:"loading",label:"Loading custom objects\u2026"});let w=await Jr(p.context.client);if(w.length===0){o({message:"No custom objects found, so there are no chart groups to push to."});return}n({type:"object-select",objects:w,back:p,options:p.options,context:p.context})})},pickObject:(p,l)=>{i(()=>v(p,"chart_group",l,p))},pickDashboard:(p,l)=>{i(async()=>{let{context:w}=p,C={...p.options,dashboard:l.id};if(C.dashlet!==void 0||C.create){await c(w,C,p);return}n({type:"loading",label:`Loading "${l.name}"\u2026`});let E=await w.client.getDashboard(l.id),x=Yr(w,E),y=x.kind==="map"||x.kind==="name"?x.dashlet.id:null;n({type:"target-select",dashboardId:E.id,title:`Choose what to push to on "${E.name}"`,message:null,choices:Ys(In(E,w.block),y),matchedId:y,back:p,options:C,context:w})})},pickTarget:(p,l)=>{i(()=>c(p.context,nf(p.options,p.dashboardId,l),p))},acceptDrift:p=>{i(()=>a(p.context,p.target,{...p.options,force:!0}))},acceptPush:p=>{i(()=>s(p.context,p.plan))},cancel:()=>{o({message:"Cancelled."})}}}var Xs=({prompt:e,strict:t,onAccept:n,onCancel:r})=>(Zs((o,i)=>{if(i.ctrl)return;let s=o.toLowerCase();s==="y"||!t&&i.return?n():(t||s==="n"||i.escape)&&r()}),D(Y,{bold:!0,children:e})),ct=({lines:e,color:t})=>D(ce,{flexDirection:"column",children:e.map((n,r)=>D(Y,{...t&&{color:t},children:n},`${String(r)}-${n}`))}),Qs=({plan:e})=>G(ce,{flexDirection:"column",children:[D(ct,{lines:Dt(e.summary)}),G(Y,{children:["URL: ",e.url]})]}),so=({label:e})=>G(ce,{gap:1,children:[D(xe,{}),D(Y,{dimColor:!0,children:e})]}),of=({view:e})=>G(ce,{flexDirection:"column",gap:1,children:[G(ce,{gap:1,children:[D(Y,{color:"red",children:"\u2717"}),D(Y,{color:"red",children:e.issues&&e.issues.length>0?Ae(e.issues):e.message})]}),e.hint!==void 0&&G(Y,{dimColor:!0,children:["Hint: ",e.hint]}),e.choices&&e.choices.length>0&&G(ce,{flexDirection:"column",children:[D(Y,{children:"Choices:"}),D(ct,{lines:e.choices.map(t=>` ${t.label}`)})]})]}),sf=({plan:e,applied:t})=>{let n=to(e.dashboard.id);return t===null?G(ce,{flexDirection:"column",gap:1,children:[D(Y,{color:"yellow",children:"Dry run: nothing was written."}),D(Qs,{plan:e}),e.warnings.length>0&&D(ct,{lines:at(e.warnings),color:"yellow"}),G(ce,{flexDirection:"column",children:[G(Y,{bold:!0,children:[e.method," ",e.path]}),D(Y,{children:JSON.stringify(e.body,null,2)})]})]}):G(ce,{flexDirection:"column",gap:1,children:[G(ce,{gap:1,children:[D(Y,{color:"green",children:"\u2713"}),G(Y,{bold:!0,children:[e.action==="create"?"Created":"Updated"," ",e.summary.blockName,' on "',e.dashboard.name,'"']})]}),G(ce,{flexDirection:"column",children:[G(Y,{children:["URL: ",e.url]}),n&&G(Y,{dimColor:!0,children:["Refresh an open tab: ",n.script]})]}),t.warnings.length>0&&D(ct,{lines:at(t.warnings),color:"yellow"})]})},ea=({apiName:e,options:t,deps:n})=>{let r=Xp(),[o,i]=$n({type:"loading",label:"Loading credentials\u2026"}),[s,a]=$n({credentials:null,credentialNotices:[],warnings:[],notices:[]}),[c]=$n(()=>rf(e,n,i,a)),[g]=$n(t);Js(()=>{c.start(g)},[c,g]),Js(()=>{(o.type==="done"||o.type==="error")&&r.exit()},[o,r]),Zs((h,v)=>{v.ctrl&&h==="c"&&o.type!=="done"&&o.type!=="error"&&(n.setExitCode(130),r.exit())});let u=h=>G(ce,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[D(J,{}),s.credentials&&G(Y,{dimColor:!0,children:["Environment: ",s.credentials.environment," \xB7 Business:"," ",s.credentials.businessId]}),s.credentialNotices.length>0&&D(ct,{lines:s.credentialNotices,color:"yellow"}),s.warnings.length>0&&D(Y,{dimColor:!0,children:Ae(s.warnings)}),s.notices.length>0&&D(ct,{lines:s.notices}),h]});switch(o.type){case"loading":return u(D(so,{label:o.label}));case"packaging":return u(D(so,{label:"Packaging blocks\u2026"}));case"applying":return u(D(so,{label:`Pushing ${o.plan.summary.blockName} to "${o.plan.dashboard.name}"\u2026`}));case"environment-select":return u(D(Te,{title:"Environment",items:o.choices.map(h=>({key:h.value,label:h.label})),onSelect:gt(o.choices,h=>{c.pickEnvironment(o,h)}),onCancel:c.cancel},"environment"));case"block-select":return u(D(Te,{title:"Block to push",items:o.choices.map(h=>({key:h.value,label:h.label})),onSelect:gt(o.choices,h=>{c.pickBlock(o,h)}),onCancel:c.cancel},"block"));case"surface-select":return u(D(Te,{title:"Where should the block go?",items:Gs,onSelect:gt(Gs,h=>{c.pickSurface(o,h.key)}),onCancel:c.cancel},"surface"));case"object-select":return u(D(Te,{title:"Custom object",items:o.objects.map(h=>({key:h.id,label:h.objectName})),onSelect:gt(o.objects,h=>{c.pickObject(o,h)}),onCancel:()=>{i(o.back)},hint:io},"object"));case"dashboard-select":return u(D(Te,{title:o.title,items:o.rows.map(tf),onSelect:gt(o.rows,h=>{c.pickDashboard(o,h)}),onCancel:()=>{i(o.back)},hint:io},`dashboards-${o.surface}-${o.objectId??""}`));case"target-select":{let{back:h}=o;return u(G(af,{children:[o.message!==null&&D(Y,{color:"yellow",children:o.message}),D(Te,{title:o.title,items:o.choices.map(v=>ef(v,o.matchedId)),onSelect:gt(o.choices,v=>{c.pickTarget(o,v)}),onCancel:h?()=>{i(h)}:c.cancel,...h&&{hint:io}},`targets-${o.dashboardId}`)]}))}case"confirm":return o.kind==="drift"?u(G(ce,{flexDirection:"column",gap:1,children:[D(Y,{color:"yellow",children:Qp}),D(Y,{dimColor:!0,children:o.message}),D(Xs,{prompt:"Type y to overwrite (y/N)",strict:!0,onAccept:()=>{c.acceptDrift(o)},onCancel:c.cancel},"drift")]})):u(G(ce,{flexDirection:"column",gap:1,children:[D(Qs,{plan:o.plan}),o.plan.warnings.length>0&&D(ct,{lines:at(o.plan.warnings),color:"yellow"}),o.plan.summary.isProduction&&D(Y,{color:"red",bold:!0,children:"PRODUCTION"}),D(Xs,{prompt:o.plan.summary.isProduction?"Type y to push to production (y/N)":"Push? (Y/n)",strict:o.plan.summary.isProduction,onAccept:()=>{c.acceptPush(o)},onCancel:c.cancel},"push")]}));case"done":return u(D(sf,{plan:o.plan,applied:o.applied}));case"error":return u(D(of,{view:o.view}))}};var na=e=>`Error: ${e instanceof Error?e.message:String(e)}`,uf=e=>e instanceof df?Ae(e.issues):na(e),ta=e=>{console.error(na(e)),process.exitCode=1};function ra(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(n,r)=>{try{let o=await fs(process.cwd(),n),{block:i,warnings:s}=o;s.length>0&&console.error(Ae(s));let a=JSON.stringify(ps(o),null,2);console.log(a),r.copy&&console.error(await mn(a)?`Copied block "${i.api_name}" to the clipboard.`:"Couldn't copy to the clipboard; use the JSON printed to stdout instead.")}catch(o){console.error(uf(o)),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 an API-key credentials JSON file (deprecated; replaces the sign-in session)").option("--profile <name>","stored API-key credential profile to use (deprecated; replaces the sign-in session)").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)").option("--env <env>","environment of the `appbuilder login` session to use").action(async(n,r)=>{try{let o=Kr(process.cwd());if(!process.stdin.isTTY||!process.stdout.isTTY||r.json===!0){await Hs(n,r,o);return}let{waitUntilExit:i}=lf(cf(ea,{...n!==void 0&&{apiName:n},options:r,deps:o}),{exitOnCtrlC:!1});await i()}catch(o){ta(o)}}),t.command("targets").description("List the dashboards, homepages and chart groups a block can be pushed to").option("-c, --credentials <path>","path to an API-key credentials JSON file (deprecated; replaces the sign-in session)").option("--profile <name>","stored API-key credential profile to use (deprecated; replaces the sign-in session)").option("--object <id>","list the chart groups of this custom object").option("--json","print a JSON result to stdout").option("--env <env>","environment of the `appbuilder login` session to use").action(async n=>{try{await Vs(n,Kr(process.cwd()))}catch(r){ta(r)}})}import{createElement as hf}from"react";import{render as gf}from"ink";import{useEffect as ia,useState as Bt}from"react";import{Box as Ft,Text as yt,useApp as pf}from"ink";import{PluginValidationError as ff}from"@kizenapps/packager";function Rt(e){return e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}import{Box as ao,Text as Dn}from"ink";import{jsx as oa,jsxs as Ot}from"react/jsx-runtime";var Rn=({issues:e})=>{let t=e.filter(n=>n.severity==="error").length;return Ot(ao,{flexDirection:"column",marginTop:1,children:[Ot(Dn,{color:"red",children:["\u2717 ",t," validation ",t===1?"error":"errors"]}),[...Lr(e)].map(([n,r])=>Ot(ao,{flexDirection:"column",marginTop:1,children:[oa(Dn,{bold:!0,children:n}),r.map((o,i)=>oa(ao,{paddingLeft:2,children:Ot(Dn,{color:o.severity==="error"?"red":"yellow",children:[o.severity==="error"?"\u2717":"\u26A0"," ",o.message," ",Ot(Dn,{dimColor:!0,children:["(",o.rule,")"]})]})},`${o.rule}-${String(i)}`))]},n))]})};import{Fragment as mf,jsx as We,jsxs as lt}from"react/jsx-runtime";var sa=["creating-dir","reading-files","validating","minifying","packaging","writing-bundle"],On={"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"},aa=({outputDir:e,pluginDir:t})=>{let n=pf(),[r,o]=Bt("creating-dir"),[i,s]=Bt(!1),[a,c]=Bt(null),[g,u]=Bt(null),[h,v]=Bt(null);ia(()=>{vn(t,e,o).then(({bundleSize:w})=>{v(w),o("done")}).catch(w=>{w instanceof ff?c(w.issues):u(w instanceof Error?w.message:String(w)),s(!0),process.exitCode=1})},[e,t]),ia(()=>{(r==="done"||i)&&n.exit()},[r,i,n]);let p=sa.indexOf(r),l=r==="done";return lt(Ft,{flexDirection:"column",paddingY:1,paddingX:2,children:[We(J,{marginBottom:1}),lt(Ft,{flexDirection:"column",gap:0,children:[sa.map((w,C)=>{let E=r===w,x=l||p>C;return We(Ft,{gap:1,children:i&&C===p?lt(yt,{color:"red",children:["\u2717 ",On[w]]}):x?lt(yt,{color:"green",children:["\u2713 ",On[w]]}):E?lt(mf,{children:[We(xe,{}),We(yt,{children:On[w]})]}):lt(yt,{dimColor:!0,children:[" ",On[w]]})},w)}),l&&h!==null&&We(Ft,{marginTop:1,gap:1,children:lt(yt,{color:"green",children:["\u2713 bundle \u2014 ",Rt(h)]})}),a!==null&&We(Rn,{issues:a}),g!==null&&We(Ft,{marginTop:1,borderStyle:"single",borderColor:"red",paddingX:1,children:We(yt,{color:"red",children:g})})]})]})};function ca(e){e.command("build").description("Bundle the plugin app into .kizenapp directory").action(async()=>{let t=process.cwd(),n=`${t}/.kizenapp`;ve(t);let{waitUntilExit:r}=gf(hf(aa,{outputDir:n,pluginDir:t}));await r()})}import{createElement as cm}from"react";import{render as lm}from"ink";import{useCallback as Un,useState as bt}from"react";import{Box as K,Text as $,useApp as nm,useInput as rm}from"ink";import{join as Hn}from"path";import{access as Zf,mkdir as Fn,writeFile as mo}from"fs/promises";import{dirname as Qf,join as Ie}from"path";var la=`{
856
+ `}async function Ta(e,t){let n={json:e.json===!0,deps:t},r="appbuilder block targets",o=e.object===void 0?[]:["--object",e.object],i=a=>[...a.args,...Do(e,t.processEnv),...o],s=a=>{Ea(n,a,r,i)};try{let a=await Wn(e,t);if(!a.ok){s(a);return}let{credentials:c,client:g,notices:m}=a.value;_a(t,m);let h=await am(g,c,e.object===void 0?{}:{object:e.object});if(!h.ok){s(h);return}t.writeStdout(n.json?`${JSON.stringify(h.value,null,2)}
857
+ `:wm(h.value))}catch(a){s(Re(a))}}import{useEffect as Da,useState as Gn}from"react";import{Box as de,Text as Y,useApp as $m,useInput as Fa}from"ink";import"@kizenapps/packager";import{Box as Cm,Text as Sm}from"ink";import{Box as vm,Text as xm}from"ink";import{jsx as Ia}from"react/jsx-runtime";var km=[" :::::::: "," :::::: ::::::::::: "," :::::: :::::::::: "," :::::: :::::: ::::::: "," ::::: :::::: ::::::::::::::::: "," ::::: ::::: ::::::::::::::::::: "," ::::: ::::: :::::: ::::: ",":::: ::::: ::: ::::: :: ","::::: :::::: :::::::::: ","::::: :::::: ::::::::::: "," ::::: ::: ::::::: "," ::::::: ::: ::::: "," ::::::::::: :::::: :::::"," :::::::::: :::::: :::::"," :: ::::: ::: ::::: ::::"," ::::: :::::: ::::: ::::: ::: "," ::::::::::::::::::: ::::: ::::: "," ::::::::::::::::: ::::: ::::: "," ::::::::: :::::: :::::: "," :::::::::: :::::: "," ::::::::::: :::::: "," :::::::: "],$a=()=>Ia(vm,{flexDirection:"column",children:km.map((e,t)=>Ia(xm,{color:"cyan",children:e},t))});import{Fragment as Pm,jsx as Ro,jsxs as Em}from"react/jsx-runtime";var G=({marginBottom:e=0})=>Em(Pm,{children:[Ro($a,{}),Ro(Cm,{flexDirection:"column",marginTop:1,marginBottom:e,children:Ro(Sm,{bold:!0,color:"cyan",children:"Kizen App Development Toolkit"})})]});import{useEffect as _m,useState as Am}from"react";import{Text as Tm}from"ink";import{jsx as Im}from"react/jsx-runtime";var Na=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ee=()=>{let[e,t]=Am(0);return _m(()=>{let n=setInterval(()=>{t(r=>(r+1)%Na.length)},80);return()=>{clearInterval(n)}},[]),Im(Tm,{color:"cyan",children:Na[e]??"\u280B"})};import{Fragment as zm,jsx as R,jsxs as J}from"react/jsx-runtime";var Ra=[{key:"dashboard",label:"Dashboard"},{key:"homepage",label:"Homepage"},{key:"chart_group",label:"Chart group"}],Nm={dashboard:"dashboard",homepage:"homepage",chart_group:"chart group"},Oo="\u2191/\u2193 to move, Enter to select, Esc to go back",Dm="The block was edited in Kizen since your last push. Overwriting discards those edits.",Jn=e=>e.args.includes("--create");function Oa(e,t){let n=e.filter(i=>i.value===t),r=e.filter(Jn),o=e.filter(i=>i.value!==t&&!Jn(i));return n.length>0?[...n,...o,...r]:[...r,...o]}function xt(e,t){return(n,r)=>{let o=e[r];o!==void 0&&t(o)}}function Rm(e,t){if(Jn(e))return{key:e.value,label:e.label};if(e.value===t)return{key:e.value,label:`Update "${e.label}" (last pushed here)`};let n=e.isFromThisPlugin?"pushed from this plugin":e.pushKey;return{key:e.value,label:`Update "${e.label}"`,...n?{description:n}:{}}}function Om(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 n=[e.employeeAccess,e.hidden?"hidden":null].filter(r=>r!==null&&r!=="").join(" \xB7 ");return{key:e.id,label:t,...n===""?{}:{description:n}}}function Bm(e,t,n){let r={...e,dashboard:t};return delete r.dashlet,delete r.create,Jn(n)?{...r,create:!0}:{...r,dashlet:n.value}}function Fm(e,t,n,r){let o=f=>{t.setExitCode(1),n({type:"error",view:f})},i=f=>{f().catch(u=>{o(Re(u))})},s=async(f,u)=>{n({type:"applying",plan:u});let w=await To(f,u,t);if(!w.ok){o(w);return}n({type:"done",plan:u,applied:w.value})},a=async(f,u,w)=>{n({type:"loading",label:"Preparing the push\u2026"});let k=await _o(f,u,w,t);if(!k.ok){if(k.code==="drift_detected"){n({type:"confirm",kind:"drift",message:k.message,target:u,options:w,context:f});return}o(k);return}if(w.dryRun){n({type:"done",plan:k.value,applied:null});return}if(w.yes){let _=No(w,f.credentials.environment);if(_.ok&&_.value.kind==="apply"){await s(f,k.value);return}}n({type:"confirm",kind:"push",plan:k.value,options:w,context:f})},c=async(f,u,w)=>{n({type:"loading",label:"Resolving the target\u2026"});let k=await Eo(f,u);if(k.ok){await a(f,k.value,u);return}let _=u.dashboard??f.entry?.dashboardId;if((k.code==="needs_choice"&&k.choice==="target"||k.code==="remembered_target_missing")&&k.choices&&k.choices.length>0&&_!==void 0){n({type:"target-select",dashboardId:_,title:"Choose a block to update, or create a new one",message:k.message,choices:Oa(k.choices,null),matchedId:null,back:w,options:u,context:f});return}o(k)},g=async(f,{credentials:u,client:w},k)=>{let{context:_,forgotten:P}=await $o({client:w,credentials:u,block:k,forget:f.forget===!0},t);if(P&&r(C=>({...C,notices:[...C.notices,`Forgot the remembered target for ${k.block.api_name}.`]})),f.dashboard!==void 0||_.entry){await c(_,f,null);return}n({type:"surface-select",options:f,context:_})},m=async(f,u,w)=>{n({type:"packaging"});let k=await ko(w,t);if(!k.ok){if(k.choice==="block"&&k.choices){n({type:"block-select",options:f,resolved:u,choices:k.choices});return}o(k);return}r(_=>({..._,warnings:k.value.warnings})),await g(f,u,k.value)},h=async f=>{n({type:"loading",label:"Loading credentials\u2026"});let u=await Wn(f,t);if(!u.ok){if(u.choice==="environment"&&u.choices){n({type:"environment-select",options:f,choices:u.choices});return}o(u);return}r(w=>({...w,credentials:u.value.credentials,credentialNotices:u.value.notices})),await m(f,u.value,e)},y=async({options:f,context:u},w,k,_)=>{let P=Nm[w];n({type:"loading",label:`Loading ${P}s\u2026`});let T=(await u.client.listDashboards(Ls(w),k?.id)).map(d=>Wt(d,w)),{environment:v,businessId:l}=u.credentials;if(T.length===0){o({message:`No ${P}s found${k?` on ${k.objectName}`:""} for business ${l} (${v}).`});return}n({type:"dashboard-select",surface:w,objectId:k?.id??null,title:k?`Choose a chart group on ${k.objectName}`:`Choose a ${P}`,rows:T,back:_,options:f,context:u})};return{start:f=>{i(()=>h(f))},pickEnvironment:(f,u)=>{i(()=>h({...f.options,env:u.value}))},pickBlock:(f,u)=>{i(()=>m(f.options,f.resolved,u.value))},pickSurface:(f,u)=>{i(async()=>{if(u!=="chart_group"){await y(f,u,null,f);return}n({type:"loading",label:"Loading custom objects\u2026"});let w=await Co(f.context.client);if(w.length===0){o({message:"No custom objects found, so there are no chart groups to push to."});return}n({type:"object-select",objects:w,back:f,options:f.options,context:f.context})})},pickObject:(f,u)=>{i(()=>y(f,"chart_group",u,f))},pickDashboard:(f,u)=>{i(async()=>{let{context:w}=f,k={...f.options,dashboard:u.id};if(k.dashlet!==void 0||k.create){await c(w,k,f);return}n({type:"loading",label:`Loading "${u.name}"\u2026`});let _=await w.client.getDashboard(u.id),P=Po(w,_),C=P.kind==="map"||P.kind==="name"?P.dashlet.id:null;n({type:"target-select",dashboardId:_.id,title:`Choose what to push to on "${_.name}"`,message:null,choices:Oa(qn(_,w.block),C),matchedId:C,back:f,options:k,context:w})})},pickTarget:(f,u)=>{i(()=>c(f.context,Bm(f.options,f.dashboardId,u),f))},acceptDrift:f=>{i(()=>a(f.context,f.target,{...f.options,force:!0}))},acceptPush:f=>{i(()=>s(f.context,f.plan))},cancel:()=>{o({message:"Cancelled."})}}}var Ba=({prompt:e,strict:t,onAccept:n,onCancel:r})=>(Fa((o,i)=>{if(i.ctrl)return;let s=o.toLowerCase();s==="y"||!t&&i.return?n():(t||s==="n"||i.escape)&&r()}),R(Y,{bold:!0,children:e})),mt=({lines:e,color:t})=>R(de,{flexDirection:"column",children:e.map((n,r)=>R(Y,{...t&&{color:t},children:n},`${String(r)}-${n}`))}),ja=({plan:e})=>J(de,{flexDirection:"column",children:[R(mt,{lines:qt(e.summary)}),J(Y,{children:["URL: ",e.url]})]}),Bo=({label:e})=>J(de,{gap:1,children:[R(Ee,{}),R(Y,{dimColor:!0,children:e})]}),jm=({view:e})=>J(de,{flexDirection:"column",gap:1,children:[J(de,{gap:1,children:[R(Y,{color:"red",children:"\u2717"}),R(Y,{color:"red",children:e.issues&&e.issues.length>0?De(e.issues):e.message})]}),e.hint!==void 0&&J(Y,{dimColor:!0,children:["Hint: ",e.hint]}),e.choices&&e.choices.length>0&&J(de,{flexDirection:"column",children:[R(Y,{children:"Choices:"}),R(mt,{lines:e.choices.map(t=>` ${t.label}`)})]})]}),Lm=({plan:e,applied:t})=>{let n=Io(e.dashboard.id);return t===null?J(de,{flexDirection:"column",gap:1,children:[R(Y,{color:"yellow",children:"Dry run: nothing was written."}),R(ja,{plan:e}),e.warnings.length>0&&R(mt,{lines:ft(e.warnings),color:"yellow"}),J(de,{flexDirection:"column",children:[J(Y,{bold:!0,children:[e.method," ",e.path]}),R(Y,{children:JSON.stringify(e.body,null,2)})]})]}):J(de,{flexDirection:"column",gap:1,children:[J(de,{gap:1,children:[R(Y,{color:"green",children:"\u2713"}),J(Y,{bold:!0,children:[e.action==="create"?"Created":"Updated"," ",e.summary.blockName,' on "',e.dashboard.name,'"']})]}),J(de,{flexDirection:"column",children:[J(Y,{children:["URL: ",e.url]}),n&&J(Y,{dimColor:!0,children:["Refresh an open tab: ",n.script]})]}),t.warnings.length>0&&R(mt,{lines:ft(t.warnings),color:"yellow"})]})},La=({apiName:e,options:t,deps:n})=>{let r=$m(),[o,i]=Gn({type:"loading",label:"Loading credentials\u2026"}),[s,a]=Gn({credentials:null,credentialNotices:[],warnings:[],notices:[]}),[c]=Gn(()=>Fm(e,n,i,a)),[g]=Gn(t);Da(()=>{c.start(g)},[c,g]),Da(()=>{(o.type==="done"||o.type==="error")&&r.exit()},[o,r]),Fa((h,y)=>{y.ctrl&&h==="c"&&o.type!=="done"&&o.type!=="error"&&(n.setExitCode(130),r.exit())});let m=h=>J(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[R(G,{}),s.credentials&&J(Y,{dimColor:!0,children:["Environment: ",s.credentials.environment," \xB7 Business:"," ",s.credentials.businessId]}),s.credentialNotices.length>0&&R(mt,{lines:s.credentialNotices,color:"yellow"}),s.warnings.length>0&&R(Y,{dimColor:!0,children:De(s.warnings)}),s.notices.length>0&&R(mt,{lines:s.notices}),h]});switch(o.type){case"loading":return m(R(Bo,{label:o.label}));case"packaging":return m(R(Bo,{label:"Packaging blocks\u2026"}));case"applying":return m(R(Bo,{label:`Pushing ${o.plan.summary.blockName} to "${o.plan.dashboard.name}"\u2026`}));case"environment-select":return m(R(Ne,{title:"Environment",items:o.choices.map(h=>({key:h.value,label:h.label})),onSelect:xt(o.choices,h=>{c.pickEnvironment(o,h)}),onCancel:c.cancel},"environment"));case"block-select":return m(R(Ne,{title:"Block to push",items:o.choices.map(h=>({key:h.value,label:h.label})),onSelect:xt(o.choices,h=>{c.pickBlock(o,h)}),onCancel:c.cancel},"block"));case"surface-select":return m(R(Ne,{title:"Where should the block go?",items:Ra,onSelect:xt(Ra,h=>{c.pickSurface(o,h.key)}),onCancel:c.cancel},"surface"));case"object-select":return m(R(Ne,{title:"Custom object",items:o.objects.map(h=>({key:h.id,label:h.objectName})),onSelect:xt(o.objects,h=>{c.pickObject(o,h)}),onCancel:()=>{i(o.back)},hint:Oo},"object"));case"dashboard-select":return m(R(Ne,{title:o.title,items:o.rows.map(Om),onSelect:xt(o.rows,h=>{c.pickDashboard(o,h)}),onCancel:()=>{i(o.back)},hint:Oo},`dashboards-${o.surface}-${o.objectId??""}`));case"target-select":{let{back:h}=o;return m(J(zm,{children:[o.message!==null&&R(Y,{color:"yellow",children:o.message}),R(Ne,{title:o.title,items:o.choices.map(y=>Rm(y,o.matchedId)),onSelect:xt(o.choices,y=>{c.pickTarget(o,y)}),onCancel:h?()=>{i(h)}:c.cancel,...h&&{hint:Oo}},`targets-${o.dashboardId}`)]}))}case"confirm":return o.kind==="drift"?m(J(de,{flexDirection:"column",gap:1,children:[R(Y,{color:"yellow",children:Dm}),R(Y,{dimColor:!0,children:o.message}),R(Ba,{prompt:"Type y to overwrite (y/N)",strict:!0,onAccept:()=>{c.acceptDrift(o)},onCancel:c.cancel},"drift")]})):m(J(de,{flexDirection:"column",gap:1,children:[R(ja,{plan:o.plan}),o.plan.warnings.length>0&&R(mt,{lines:ft(o.plan.warnings),color:"yellow"}),o.plan.summary.isProduction&&R(Y,{color:"red",bold:!0,children:"PRODUCTION"}),R(Ba,{prompt:o.plan.summary.isProduction?"Type y to push to production (y/N)":"Push? (Y/n)",strict:o.plan.summary.isProduction,onAccept:()=>{c.acceptPush(o)},onCancel:c.cancel},"push")]}));case"done":return m(R(Lm,{plan:o.plan,applied:o.applied}));case"error":return m(R(jm,{view:o.view}))}};var Ma=e=>`Error: ${e instanceof Error?e.message:String(e)}`,Km=e=>e instanceof Hm?De(e.issues):Ma(e),za=e=>{console.error(Ma(e)),process.exitCode=1};function Ua(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(n,r)=>{try{let o=await ta(process.cwd(),n),{block:i,warnings:s}=o;s.length>0&&console.error(De(s));let a=JSON.stringify(ea(o),null,2);console.log(a),r.copy&&console.error(await In(a)?`Copied block "${i.api_name}" to the clipboard.`:"Couldn't copy to the clipboard; use the JSON printed to stdout instead.")}catch(o){console.error(Km(o)),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 an API-key credentials JSON file (deprecated; replaces the sign-in session)").option("--profile <name>","stored API-key credential profile to use (deprecated; replaces the sign-in session)").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)").option("--env <env>","environment of the `appbuilder login` session to use").option("--business <id-or-name>","use this saved account, by business id or name (ignoring case), instead of the current one (default: $APPBUILDER_BUSINESS)").option("--user <userId>","with --business, use the saved account of this user id (default: $APPBUILDER_USER)").action(async(n,r)=>{try{let o=xo(process.cwd());if(!process.stdin.isTTY||!process.stdout.isTTY||r.json===!0){await Aa(n,r,o);return}let{waitUntilExit:i}=Um(Mm(La,{...n!==void 0&&{apiName:n},options:r,deps:o}),{exitOnCtrlC:!1});await i()}catch(o){za(o)}}),t.command("targets").description("List the dashboards, homepages and chart groups a block can be pushed to").option("-c, --credentials <path>","path to an API-key credentials JSON file (deprecated; replaces the sign-in session)").option("--profile <name>","stored API-key credential profile to use (deprecated; replaces the sign-in session)").option("--object <id>","list the chart groups of this custom object").option("--json","print a JSON result to stdout").option("--env <env>","environment of the `appbuilder login` session to use").option("--business <id-or-name>","use this saved account, by business id or name (ignoring case), instead of the current one (default: $APPBUILDER_BUSINESS)").option("--user <userId>","with --business, use the saved account of this user id (default: $APPBUILDER_USER)").action(async n=>{try{await Ta(n,xo(process.cwd()))}catch(r){za(r)}})}import{createElement as Gm}from"react";import{render as Jm}from"ink";import{useEffect as Ka,useState as Yt}from"react";import{Box as Xt,Text as kt,useApp as Vm}from"ink";import{PluginValidationError as Wm}from"@kizenapps/packager";function Gt(e){return e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}import{Box as Fo,Text as Yn}from"ink";import{jsx as Ha,jsxs as Jt}from"react/jsx-runtime";var Xn=({issues:e})=>{let t=e.filter(n=>n.severity==="error").length;return Jt(Fo,{flexDirection:"column",marginTop:1,children:[Jt(Yn,{color:"red",children:["\u2717 ",t," validation ",t===1?"error":"errors"]}),[...ho(e)].map(([n,r])=>Jt(Fo,{flexDirection:"column",marginTop:1,children:[Ha(Yn,{bold:!0,children:n}),r.map((o,i)=>Ha(Fo,{paddingLeft:2,children:Jt(Yn,{color:o.severity==="error"?"red":"yellow",children:[o.severity==="error"?"\u2717":"\u26A0"," ",o.message," ",Jt(Yn,{dimColor:!0,children:["(",o.rule,")"]})]})},`${o.rule}-${String(i)}`))]},n))]})};import{Fragment as qm,jsx as Ye,jsxs as ht}from"react/jsx-runtime";var Va=["creating-dir","reading-files","validating","minifying","packaging","writing-bundle"],Zn={"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"},Wa=({outputDir:e,pluginDir:t})=>{let n=Vm(),[r,o]=Yt("creating-dir"),[i,s]=Yt(!1),[a,c]=Yt(null),[g,m]=Yt(null),[h,y]=Yt(null);Ka(()=>{Bn(t,e,o).then(({bundleSize:w})=>{y(w),o("done")}).catch(w=>{w instanceof Wm?c(w.issues):m(w instanceof Error?w.message:String(w)),s(!0),process.exitCode=1})},[e,t]),Ka(()=>{(r==="done"||i)&&n.exit()},[r,i,n]);let f=Va.indexOf(r),u=r==="done";return ht(Xt,{flexDirection:"column",paddingY:1,paddingX:2,children:[Ye(G,{marginBottom:1}),ht(Xt,{flexDirection:"column",gap:0,children:[Va.map((w,k)=>{let _=r===w,P=u||f>k;return Ye(Xt,{gap:1,children:i&&k===f?ht(kt,{color:"red",children:["\u2717 ",Zn[w]]}):P?ht(kt,{color:"green",children:["\u2713 ",Zn[w]]}):_?ht(qm,{children:[Ye(Ee,{}),Ye(kt,{children:Zn[w]})]}):ht(kt,{dimColor:!0,children:[" ",Zn[w]]})},w)}),u&&h!==null&&Ye(Xt,{marginTop:1,gap:1,children:ht(kt,{color:"green",children:["\u2713 bundle \u2014 ",Gt(h)]})}),a!==null&&Ye(Xn,{issues:a}),g!==null&&Ye(Xt,{marginTop:1,borderStyle:"single",borderColor:"red",paddingX:1,children:Ye(kt,{color:"red",children:g})})]})]})};function qa(e){e.command("build").description("Bundle the plugin app into .kizenapp directory").action(async()=>{let t=process.cwd(),n=`${t}/.kizenapp`;Pe(t);let{waitUntilExit:r}=Jm(Gm(Wa,{outputDir:n,pluginDir:t}));await r()})}import{createElement as Mh}from"react";import{render as Uh}from"ink";import{useCallback as ir,useState as Ct}from"react";import{Box as V,Text as N,useApp as Oh,useInput as Bh}from"ink";import{join as sr}from"path";import{access as $h,mkdir as er,writeFile as Ho}from"fs/promises";import{dirname as Nh,join as Oe}from"path";var Ga=`{
840
858
  "name": "Hello Frame",
841
859
  "api_name": "hello_frame",
842
860
  "title": "Hello Frame",
@@ -845,13 +863,13 @@ ${e.stderr}`),As=e=>{let t=(e.stderr.trim()||e.stdout.trim()).replace(/\s+/g," "
845
863
  "height": 320,
846
864
  "width": 280
847
865
  }
848
- `;var da=`this.outputUI(\`
866
+ `;var Ja=`this.outputUI(\`
849
867
  <div class="hello-frame">
850
868
  <h2 class="hello-frame__title">Hello from a floating frame</h2>
851
869
  <p class="hello-frame__body">Edit src/floatingFrames/helloFrame/script.js to change this.</p>
852
870
  </div>
853
871
  \`);
854
- `;var ua=`.hello-frame {
872
+ `;var Ya=`.hello-frame {
855
873
  padding: 16px;
856
874
  font-family: system-ui, sans-serif;
857
875
  }
@@ -865,18 +883,18 @@ ${e.stderr}`),As=e=>{let t=(e.stderr.trim()||e.stdout.trim()).replace(/\s+/g," "
865
883
  margin: 0;
866
884
  color: #555;
867
885
  }
868
- `;var pa=`{
886
+ `;var Xa=`{
869
887
  "name": "Hello Block",
870
888
  "api_name": "hello_block",
871
889
  "types": ["dashboards"]
872
890
  }
873
- `;var fa=`this.outputUI(\`
891
+ `;var Za=`this.outputUI(\`
874
892
  <div class="hello-block">
875
893
  <h2 class="hello-block__title">Hello from a block</h2>
876
894
  <p class="hello-block__body">Edit src/blocks/helloBlock/script.js to change this.</p>
877
895
  </div>
878
896
  \`);
879
- `;var ma=`.hello-block {
897
+ `;var Qa=`.hello-block {
880
898
  padding: 16px;
881
899
  font-family: system-ui, sans-serif;
882
900
  background: #f8fafc;
@@ -892,25 +910,25 @@ ${e.stderr}`),As=e=>{let t=(e.stderr.trim()||e.stdout.trim()).replace(/\s+/g," "
892
910
  margin: 0;
893
911
  color: #555;
894
912
  }
895
- `;var ha=`{
913
+ `;var ec=`{
896
914
  "icon": "phone",
897
915
  "color": "#0ea5e9",
898
916
  "tooltip": "Hello adornment",
899
917
  "field_type": "phonenumber"
900
918
  }
901
- `;var ga=`this.showToast('Hello from a data adornment.', { variant: 'success' });
902
- `;var ya=`{
919
+ `;var tc=`this.showToast('Hello from a data adornment.', { variant: 'success' });
920
+ `;var nc=`{
903
921
  "name": "Hello Page",
904
922
  "api_name": "hello_page"
905
923
  }
906
- `;var ba=`this.outputUI(\`
924
+ `;var rc=`this.outputUI(\`
907
925
  <div class="hello-page">
908
926
  <p class="hello-page__loading">Loading\u2026</p>
909
927
  </div>
910
928
  \`);
911
929
 
912
930
  this.runEventScript('greet');
913
- `;var wa=`.hello-page {
931
+ `;var oc=`.hello-page {
914
932
  padding: 24px;
915
933
  font-family: system-ui, sans-serif;
916
934
  }
@@ -948,7 +966,7 @@ this.runEventScript('greet');
948
966
  .hello-page__button:hover {
949
967
  background: #cbd5e1;
950
968
  }
951
- `;var va=`const tone = this.args?.formData?.tone?.[0] ?? 'plain';
969
+ `;var ic=`const tone = this.args?.formData?.tone?.[0] ?? 'plain';
952
970
 
953
971
  const greeting = tone === 'cheer' ? 'Hello, and good to see you!' : 'Hello from a routable page.';
954
972
 
@@ -971,33 +989,33 @@ this.outputUI(\`
971
989
  </div>
972
990
  </div>
973
991
  \`);
974
- `;var xa=`{
992
+ `;var sc=`{
975
993
  "api_name": "hello_toolbar_item",
976
994
  "label": "Hello Toolbar Item",
977
995
  "icon": "star",
978
996
  "color": "#0ea5e9"
979
997
  }
980
- `;var ka=`this.showToast('Hello from a toolbar item.', { variant: 'success' });
981
- `;var Ca=`{
998
+ `;var ac=`this.showToast('Hello from a toolbar item.', { variant: 'success' });
999
+ `;var cc=`{
982
1000
  "api_name": "hello_object_settings_item",
983
1001
  "label": "Hello Object Settings"
984
1002
  }
985
- `;var Sa=`this.showToast('Hello from an object settings item.', { variant: 'success' });
986
- `;var Pa=`{
1003
+ `;var lc=`this.showToast('Hello from an object settings item.', { variant: 'success' });
1004
+ `;var dc=`{
987
1005
  "name": "Hello Action",
988
1006
  "api_name": "hello_action",
989
1007
  "hint_object_name": "client_client"
990
1008
  }
991
- `;var Ea=`this.showToast('Hello from a JS action.', { variant: 'success' });
992
- `;var se=["floatingFrame","block","dataAdornment","page","toolbarItem","objectSettingsItem","jsAction"],co={floatingFrame:"Floating frame",block:"Block",dataAdornment:"Data adornment",page:"Routable page",toolbarItem:"Toolbar item",objectSettingsItem:"Object settings item",jsAction:"JS action"},Of={floatingFrame:{directory:"floatingFrames",component:"helloFrame",files:{"config.json":la,"script.js":da,"styles.css":ua}},block:{directory:"blocks",component:"helloBlock",files:{"config.json":pa,"script.js":fa,"styles.css":ma}},dataAdornment:{directory:"dataAdornments",component:"helloAdornment",files:{"config.json":ha,"script.js":ga}},page:{directory:"pages",component:"helloPage",files:{"config.json":ya,"script.js":ba,"styles.css":wa,"eventScripts/greet.js":va}},toolbarItem:{directory:"toolbarItems",component:"helloToolbarItem",files:{"config.json":xa,"script.js":ka}},objectSettingsItem:{directory:"objectSettingsItems",component:"helloObjectSettingsItem",files:{"config.json":Ca,"script.js":Sa}},jsAction:{directory:"actions",component:"helloAction",files:{"config.json":Pa,"script.js":Ea}}};function Bf(e,t="src"){let{directory:n,component:r,files:o}=Of[e];return Object.entries(o).map(([i,s])=>({path:`${t}/${n}/${r}/${i}`,content:s}))}function _a(e,t="src"){return[...new Set(e)].flatMap(n=>Bf(n,t))}import{deflateSync as Ff}from"zlib";var uo=512,jf=150,Lf=26,po=46,Ta=.6,Mf=po*.55,zf=.55,Uf=.47;function Hf(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 Vf(e){let t=Hf(e);return{hue:t%360,quarterTurns:(t>>>16)%4}}function Kf(e,t,n){let r=(1-Math.abs(2*n-1))*t,o=e/60,i=r*(1-Math.abs(o%2-1)),s=n-r/2,[a,c,g]=o<1?[r,i,0]:o<2?[i,r,0]:o<3?[0,r,i]:o<4?[0,i,r]:o<5?[i,0,r]:[r,0,i];return[Math.round((a+s)*255),Math.round((c+s)*255),Math.round((g+s)*255)]}function jt(e,t,n,r,o){let i=Math.abs(e)-n+o,s=Math.abs(t)-r+o;return Math.hypot(Math.max(i,0),Math.max(s,0))+Math.min(Math.max(i,s),0)-o}function Bn(e,t,n,r,o){return Math.hypot(e-n,t-r)-o}function Wf(e,t){let n=jf,r=po,o=r*Ta,i=Mf,s=jt(e,t,n,n,Lf),a=Math.min(Bn(e,t,0,-n-o,r),jt(e,t+n+o/2,i,o/2+1,0)),c=Math.min(Bn(e,t,n+o,0,r),jt(e-n-o/2,t,o/2+1,i,0));s=Math.min(s,a,c);let g=Math.min(Bn(e,t,0,n-o,r),jt(e,t-n+o/2,i,o/2+1,0)),u=Math.min(Bn(e,t,-n+o,0,r),jt(e+n-o/2,t,o/2+1,i,0));return Math.max(s,-g,-u)}function qf(e){let t=uo,n=new Uint8Array(t*t*4),[r,o,i]=Kf(e.hue,zf,Uf),s=po*(1+Ta),a=(t-1)/2,c=s/2;for(let g=0;g<t;g+=1)for(let u=0;u<t;u+=1){let h=u-a,v=g-a;for(let C=0;C<e.quarterTurns;C+=1)[h,v]=[-v,h];let p=Wf(h+c,v-c),l=Math.min(1,Math.max(0,.5-p));if(l<=0)continue;let w=(g*t+u)*4;n[w]=r,n[w+1]=o,n[w+2]=i,n[w+3]=Math.round(l*255)}return n}var Jf=new Uint32Array(256).map((e,t)=>{let n=t;for(let r=0;r<8;r+=1)n=n&1?3988292384^n>>>1:n>>>1;return n>>>0});function Gf(e){let t=4294967295;for(let n of e)t=(Jf[(t^n)&255]??0)^t>>>8;return(t^4294967295)>>>0}function lo(e,t){let n=Buffer.from(e,"latin1"),r=Buffer.alloc(4);r.writeUInt32BE(t.length);let o=Buffer.alloc(4);return o.writeUInt32BE(Gf(Buffer.concat([n,t]))),Buffer.concat([r,n,t,o])}var Yf=Buffer.from([137,80,78,71,13,10,26,10]);function Xf(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 r=Buffer.alloc(13);r.writeUInt32BE(e,0),r.writeUInt32BE(t,4),r[8]=8,r[9]=6;let o=e*4,i=Buffer.alloc((o+1)*t);for(let s=0;s<t;s+=1)i.set(n.subarray(s*o,(s+1)*o),s*(o+1)+1);return Buffer.concat([Yf,lo("IHDR",r),lo("IDAT",Ff(i,{level:9})),lo("IEND",new Uint8Array(0))])}function Aa(e){return Xf(uo,uo,qf(Vf(e)))}var em="src/thumbnail.png",tm=["go","fmo"];async function jn(e){try{return await Zf(e),!0}catch{return!1}}async function qe(e){return await jn(Ie(e,"kizen.json"))?"has-manifest":await jn(Ie(e,".kizenapp"))?"has-kizenapp":"ok"}async function Ia(e,t){let n=Ie(e,t);if(!await jn(n))return n;for(let r=1;r<1e3;r++){let o=Ie(e,`${t}-${String(r)}`);if(!await jn(o))return o}throw new Error(`Could not find an available directory name for "${t}"`)}function ho(e){let t=e.developerBusinessId.trim(),n=t!==""&&!tm.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 fo(e,t){let n=t.map(o=>({fullPath:Ie(e,...o.path.split("/")),content:o.content})),r=new Set(n.map(o=>Qf(o.fullPath)));await Promise.all([...r].map(o=>Fn(o,{recursive:!0}))),await Promise.all(n.map(o=>mo(o.fullPath,o.content,"utf-8")))}async function Ln(e){await Fn(e.targetDir,{recursive:!0});let t=ho(e);await mo(Ie(e.targetDir,"kizen.json"),JSON.stringify(t,null,2)+`
993
- `,"utf-8"),await Fn(Ie(e.targetDir,"src"),{recursive:!0}),await Fn(Ie(e.targetDir,"releaseNotes"),{recursive:!0}),await Promise.all([fo(e.targetDir,_a(e.artifacts??[])),fo(e.targetDir,kn()),fo(e.targetDir,Cn(e.includeLib===!0?["src"]:[])),mo(Ie(e.targetDir,...em.split("/")),Aa(e.apiName))]),ve(e.targetDir)}var Je=["name","apiName","externalLink","description","developerBusinessId"],Mn={name:"Name",apiName:"API name",externalLink:"External link",description:"Description",developerBusinessId:"Business ID"},go=["name","apiName","description"],yo=/^[a-z_][a-z0-9_]+$/,bo="must start with a letter or underscore and contain only lowercase letters, numbers, or underscores (minimum 2 characters)";function zn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}function $a(e){return{name:"",apiName:"",externalLink:"",description:"",developerBusinessId:e}}function Na(e,t){let n=t.trim();if(go.includes(e)&&!n)return`${Mn[e]} is required`;if(e==="apiName"&&!yo.test(n))return`${Mn[e]} ${bo}`}function Da(e,t){return e==="description"?t:t.trim()}function Ra(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),se.filter(r=>n.has(r))}import{jsx as I,jsxs as B}from"react/jsx-runtime";var dt=({text:e})=>I($,{dimColor:!0,children:e}),Oa=({parentDir:e,defaultBusinessId:t,defaultEnvironment:n,includeLib:r=!1})=>{let o=nm(),[i,s]=bt({type:"target-select",cursor:0}),[a,c]=bt("in-place"),[g,u]=bt(()=>$a(t)),[h,v]=bt(()=>[...se]),[p,l]=bt(""),[w,C]=bt(e),E=Un((b,f)=>{c(b),l(f.name),s({type:"field-entry",field:0,values:f})},[]),x=Un(async b=>{let f=await qe(b);if(f!=="ok"){s({type:"precheck-error",targetDir:b,reason:f});return}C(b),E("in-place",g)},[g,E]),y=Un(async(b,f)=>{try{let d=await Ia(e,b.apiName);C(d),s({type:"confirm",values:b,artifacts:f})}catch(d){s({type:"error",message:d instanceof Error?d.message:String(d)})}},[e]),P=Un(async(b,f,d)=>{try{await Ln({targetDir:f,name:b.name,apiName:b.apiName,externalLink:b.externalLink,description:b.description,developerBusinessId:b.developerBusinessId,developerEnvironment:n,artifacts:d,includeLib:r}),s({type:"done",targetDir:f})}catch(m){s({type:"error",message:m instanceof Error?m.message:String(m)})}},[n,r]);if(rm((b,f)=>{if(f.ctrl&&b==="c"){o.exit();return}if(i.type==="target-select"){f.upArrow?s({type:"target-select",cursor:0}):f.downArrow?s({type:"target-select",cursor:1}):f.return?i.cursor===0?x(e):E("sub-dir",g):f.escape&&o.exit();return}if(i.type==="precheck-error"){(f.return||f.escape)&&o.exit();return}if(i.type==="field-entry"){let{field:d,values:m}=i,k=Je[d];if(!k)return;if(f.escape){o.exit();return}if(f.backspace||f.delete){l(S=>S.slice(0,-1));return}if(f.upArrow&&d>0){let S={...m,[k]:p},T=d-1,_=Je[T];s({type:"field-entry",field:T,values:S}),u(S),l(_?S[_]:"");return}if(f.return||f.tab||f.downArrow){let S=Na(k,p);if(S!==void 0){s({type:"field-entry",field:d,values:m,fieldError:S});return}let T=Da(k,p),_={...m,[k]:T};u(_);let R=d+1;if(R>=Je.length)l(""),s({type:"artifact-select",values:_,cursor:0,selected:h});else{let z=Je[R],ee=z?_[z]:"",ae=z==="apiName"&&!ee?zn(_.name):ee;s({type:"field-entry",field:R,values:_}),l(ae)}return}b&&!f.ctrl&&!f.meta&&l(S=>S+b);return}if(i.type==="artifact-select"){let{cursor:d,selected:m,values:k}=i;if(f.escape){let S=Je.length-1,T=Je[S];s({type:"field-entry",field:S,values:k}),l(T?k[T]:"");return}if(f.upArrow){s({...i,cursor:Math.max(0,d-1)});return}if(f.downArrow){s({...i,cursor:Math.min(se.length-1,d+1)});return}if(b===" "){let S=se[d];if(S){let T=Ra(m,S);v(T),s({...i,selected:T})}return}if(b==="a"){v([...se]),s({...i,selected:[...se]});return}if(b==="n"){v([]),s({...i,selected:[]});return}f.return&&(a==="sub-dir"?(s({type:"resolving-target"}),y(k,m)):s({type:"confirm",values:k,artifacts:m}));return}if(i.type==="confirm"){if(f.escape){s({type:"artifact-select",values:i.values,cursor:0,selected:i.artifacts});return}f.return&&(s({type:"writing"}),P(i.values,w,i.artifacts));return}(i.type==="done"||i.type==="error")&&(f.return||f.escape)&&o.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 B(K,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(J,{}),B(K,{flexDirection:"column",gap:0,children:[I($,{bold:!0,children:"Where should the new plugin live?"}),b.map((f,d)=>{let m=i.cursor===d;return B(K,{gap:2,children:[I($,{...m&&{color:"cyan"},children:m?"\u276F":" "}),I($,{bold:m,...m&&{color:"cyan"},children:f.label}),I($,{dimColor:!0,children:f.desc})]},f.label)})]}),I(dt,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(i.type==="precheck-error"){let{targetDir:b,reason:f}=i;return B(K,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(J,{}),I($,{color:"red",bold:!0,children:"Cannot create plugin"}),B(K,{flexDirection:"column",gap:0,children:[B($,{children:[b," already contains ",I($,{bold:!0,children:f==="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."})]}),I(dt,{text:"Enter or Esc to exit"})]})}if(i.type==="field-entry"){let{field:b,fieldError:f}=i,d=a==="sub-dir"?`Target: sub-directory of ${e} (inferred from API name)`:`Target: ${w}`;return B(K,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(J,{}),B(K,{flexDirection:"column",gap:0,children:[I($,{bold:!0,children:"Plugin details"}),I($,{dimColor:!0,children:d})]}),f!==void 0&&B($,{color:"red",children:["Error: ",f]}),I(K,{flexDirection:"column",gap:0,children:Je.map((m,k)=>{let S=b===k,T=S?p:g[m],_=go.includes(m),R=`${Mn[m]}${_?"":" (optional)"}`;return B(K,{gap:2,children:[I(K,{width:24,children:I($,{bold:S,...S&&{color:"cyan"},children:R})}),I($,{...S&&{color:"cyan"},children:">"}),I($,{children:T}),S&&I($,{color:"cyan",children:"\u2588"})]},m)})}),I(dt,{text:"Enter/Tab/\u2193 next \xB7 \u2191 previous \xB7 Backspace delete \xB7 Esc cancel"})]})}if(i.type==="artifact-select"){let{cursor:b,selected:f}=i;return B(K,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(J,{}),B(K,{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."})]}),I(K,{flexDirection:"column",gap:0,children:se.map((d,m)=>{let k=b===m,S=f.includes(d);return B(K,{gap:1,children:[I($,{...k&&{color:"cyan"},children:k?"\u276F":" "}),I($,{...S&&{color:"green"},children:S?"\u25C9":"\u25EF"}),I($,{bold:k,...k&&{color:"cyan"},children:co[d]})]},d)})}),I(dt,{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=ho({targetDir:w,name:i.values.name,apiName:i.values.apiName,externalLink:i.values.externalLink,description:i.values.description,developerBusinessId:i.values.developerBusinessId,developerEnvironment:n});return B(K,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(J,{}),B(K,{flexDirection:"column",gap:0,children:[I($,{bold:!0,children:"Ready to create"}),B($,{dimColor:!0,children:["Target: ",w]})]}),B(K,{flexDirection:"column",gap:0,children:[I($,{bold:!0,children:"kizen.json preview"}),I($,{children:JSON.stringify(b,null,2)})]}),B(K,{flexDirection:"column",gap:0,children:[I($,{bold:!0,children:"Artifacts"}),i.artifacts.length===0?B($,{dimColor:!0,children:[" ","none (src/ will hold only thumbnail.png)"]}):i.artifacts.map(f=>B($,{dimColor:!0,children:[" ",co[f]]},f))]}),B(K,{flexDirection:"column",gap:0,children:[I($,{dimColor:!0,children:"Also creates:"}),B($,{dimColor:!0,children:[" ",Hn(w,"src/")]}),B($,{dimColor:!0,children:[" ",Hn(w,"src/thumbnail.png")," (generated placeholder)"]}),B($,{dimColor:!0,children:[" ",Hn(w,"releaseNotes/")]}),B($,{dimColor:!0,children:[" ",Hn(w,".gitignore")," (adds .kizenapp/)"]})]}),I(dt,{text:"Enter to create \xB7 Esc to go back"})]})}return i.type==="resolving-target"?I(K,{paddingY:1,paddingX:2,children:I($,{dimColor:!0,children:"Finding available sub-directory\u2026"})}):i.type==="writing"?I(K,{paddingY:1,paddingX:2,children:I($,{dimColor:!0,children:"Creating plugin\u2026"})}):i.type==="done"?B(K,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(J,{}),B($,{color:"green",bold:!0,children:["Plugin created at ",i.targetDir]}),B(K,{flexDirection:"column",gap:0,children:[I($,{dimColor:!0,children:"Next steps:"}),B($,{children:[" ","cd ",i.targetDir]}),B($,{children:[" ","npx --yes @kizenapps/cli dev"]}),B($,{dimColor:!0,children:[" ","Replace src/thumbnail.png with real artwork before publishing."]})]}),I(dt,{text:"Enter or Esc to exit"})]}):B(K,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(J,{}),I($,{color:"red",bold:!0,children:"Failed to create plugin"}),I($,{children:i.message}),I(dt,{text:"Enter or Esc to exit"})]})};async function Ba(e){let t=await e.listSessions().catch(()=>[]);if(t.length===0){let i=await e.loadGlobalCredentials();return{businessId:i?.businessId??"",environment:i?.environment??"go"}}let n=await nt(e.requestedEnvironment?.trim()||void 0,()=>Promise.resolve(t)),r=n.ok?n.environment:"go";return{businessId:(await e.readSession(r).catch(()=>null))?.businessId??"",environment:r}}var om="A hello-world Kizen plugin.",Fa=e=>Object.entries(e).some(([t,n])=>t!=="includeLib"&&n!==void 0);function im(e){if(e===void 0||e.trim()===""||e.trim()==="all")return[...se];if(e.trim()==="none")return[];let t=e.split(",").map(r=>r.trim()).filter(r=>r!==""),n=t.filter(r=>!se.includes(r));if(n.length>0)throw new Error(`Unknown artifact type(s): ${n.join(", ")}. Valid types: ${se.join(", ")}, or "all" / "none".`);return[...new Set(t)]}function sm(e,t,n){let r=e.name?.trim()??"";if(r==="")throw new Error("--name is required for a non-interactive run.");let o=(e.apiName?.trim()??"")||zn(r);if(!yo.test(o))throw new Error(`api_name "${o}" is invalid: ${bo}. Pass --api-name.`);let i=e.description?.trim(),s=e.businessId?.trim()??t.businessId,a=am(e,t);return{targetDir:n,name:r,apiName:o,externalLink:e.externalLink?.trim()??"",description:i===void 0||i===""?om:i,developerBusinessId:s,developerEnvironment:a,artifacts:im(e.artifacts),includeLib:e.includeLib===!0}}function am(e,t){let n=e.environment?.trim();if(n!==void 0&&n!==""){if(!St(n))throw new Error(`Unknown environment "${n}". Valid environments: ${W.join(", ")}.`);return n}if(e.businessId!==void 0&&t.businessId==="")throw new Error("--environment is required alongside --business-id when neither a sign-in session nor saved credentials give a default business, so the id is keyed to the environment that issued it.");return t.environment}async function ja(e,t,n,r){let o;try{o=sm(e,t,n)}catch(a){r.writeStderr(`Error: ${a instanceof Error?a.message:String(a)}
1009
+ `;var uc=`this.showToast('Hello from a JS action.', { variant: 'success' });
1010
+ `;var ae=["floatingFrame","block","dataAdornment","page","toolbarItem","objectSettingsItem","jsAction"],jo={floatingFrame:"Floating frame",block:"Block",dataAdornment:"Data adornment",page:"Routable page",toolbarItem:"Toolbar item",objectSettingsItem:"Object settings item",jsAction:"JS action"},mh={floatingFrame:{directory:"floatingFrames",component:"helloFrame",files:{"config.json":Ga,"script.js":Ja,"styles.css":Ya}},block:{directory:"blocks",component:"helloBlock",files:{"config.json":Xa,"script.js":Za,"styles.css":Qa}},dataAdornment:{directory:"dataAdornments",component:"helloAdornment",files:{"config.json":ec,"script.js":tc}},page:{directory:"pages",component:"helloPage",files:{"config.json":nc,"script.js":rc,"styles.css":oc,"eventScripts/greet.js":ic}},toolbarItem:{directory:"toolbarItems",component:"helloToolbarItem",files:{"config.json":sc,"script.js":ac}},objectSettingsItem:{directory:"objectSettingsItems",component:"helloObjectSettingsItem",files:{"config.json":cc,"script.js":lc}},jsAction:{directory:"actions",component:"helloAction",files:{"config.json":dc,"script.js":uc}}};function hh(e,t="src"){let{directory:n,component:r,files:o}=mh[e];return Object.entries(o).map(([i,s])=>({path:`${t}/${n}/${r}/${i}`,content:s}))}function pc(e,t="src"){return[...new Set(e)].flatMap(n=>hh(n,t))}import{deflateSync as gh}from"zlib";var zo=512,yh=150,bh=26,Mo=46,fc=.6,wh=Mo*.55,vh=.55,xh=.47;function kh(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 Ch(e){let t=kh(e);return{hue:t%360,quarterTurns:(t>>>16)%4}}function Sh(e,t,n){let r=(1-Math.abs(2*n-1))*t,o=e/60,i=r*(1-Math.abs(o%2-1)),s=n-r/2,[a,c,g]=o<1?[r,i,0]:o<2?[i,r,0]:o<3?[0,r,i]:o<4?[0,i,r]:o<5?[i,0,r]:[r,0,i];return[Math.round((a+s)*255),Math.round((c+s)*255),Math.round((g+s)*255)]}function Zt(e,t,n,r,o){let i=Math.abs(e)-n+o,s=Math.abs(t)-r+o;return Math.hypot(Math.max(i,0),Math.max(s,0))+Math.min(Math.max(i,s),0)-o}function Qn(e,t,n,r,o){return Math.hypot(e-n,t-r)-o}function Ph(e,t){let n=yh,r=Mo,o=r*fc,i=wh,s=Zt(e,t,n,n,bh),a=Math.min(Qn(e,t,0,-n-o,r),Zt(e,t+n+o/2,i,o/2+1,0)),c=Math.min(Qn(e,t,n+o,0,r),Zt(e-n-o/2,t,o/2+1,i,0));s=Math.min(s,a,c);let g=Math.min(Qn(e,t,0,n-o,r),Zt(e,t-n+o/2,i,o/2+1,0)),m=Math.min(Qn(e,t,-n+o,0,r),Zt(e+n-o/2,t,o/2+1,i,0));return Math.max(s,-g,-m)}function Eh(e){let t=zo,n=new Uint8Array(t*t*4),[r,o,i]=Sh(e.hue,vh,xh),s=Mo*(1+fc),a=(t-1)/2,c=s/2;for(let g=0;g<t;g+=1)for(let m=0;m<t;m+=1){let h=m-a,y=g-a;for(let k=0;k<e.quarterTurns;k+=1)[h,y]=[-y,h];let f=Ph(h+c,y-c),u=Math.min(1,Math.max(0,.5-f));if(u<=0)continue;let w=(g*t+m)*4;n[w]=r,n[w+1]=o,n[w+2]=i,n[w+3]=Math.round(u*255)}return n}var _h=new Uint32Array(256).map((e,t)=>{let n=t;for(let r=0;r<8;r+=1)n=n&1?3988292384^n>>>1:n>>>1;return n>>>0});function Ah(e){let t=4294967295;for(let n of e)t=(_h[(t^n)&255]??0)^t>>>8;return(t^4294967295)>>>0}function Lo(e,t){let n=Buffer.from(e,"latin1"),r=Buffer.alloc(4);r.writeUInt32BE(t.length);let o=Buffer.alloc(4);return o.writeUInt32BE(Ah(Buffer.concat([n,t]))),Buffer.concat([r,n,t,o])}var Th=Buffer.from([137,80,78,71,13,10,26,10]);function Ih(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 r=Buffer.alloc(13);r.writeUInt32BE(e,0),r.writeUInt32BE(t,4),r[8]=8,r[9]=6;let o=e*4,i=Buffer.alloc((o+1)*t);for(let s=0;s<t;s+=1)i.set(n.subarray(s*o,(s+1)*o),s*(o+1)+1);return Buffer.concat([Th,Lo("IHDR",r),Lo("IDAT",gh(i,{level:9})),Lo("IEND",new Uint8Array(0))])}function mc(e){return Ih(zo,zo,Eh(Ch(e)))}var Dh="src/thumbnail.png",Rh=["go","fmo"];async function tr(e){try{return await $h(e),!0}catch{return!1}}async function Xe(e){return await tr(Oe(e,"kizen.json"))?"has-manifest":await tr(Oe(e,".kizenapp"))?"has-kizenapp":"ok"}async function hc(e,t){let n=Oe(e,t);if(!await tr(n))return n;for(let r=1;r<1e3;r++){let o=Oe(e,`${t}-${String(r)}`);if(!await tr(o))return o}throw new Error(`Could not find an available directory name for "${t}"`)}function Ko(e){let t=e.developerBusinessId.trim(),n=t!==""&&!Rh.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 Uo(e,t){let n=t.map(o=>({fullPath:Oe(e,...o.path.split("/")),content:o.content})),r=new Set(n.map(o=>Nh(o.fullPath)));await Promise.all([...r].map(o=>er(o,{recursive:!0}))),await Promise.all(n.map(o=>Ho(o.fullPath,o.content,"utf-8")))}async function nr(e){await er(e.targetDir,{recursive:!0});let t=Ko(e);await Ho(Oe(e.targetDir,"kizen.json"),JSON.stringify(t,null,2)+`
1011
+ `,"utf-8"),await er(Oe(e.targetDir,"src"),{recursive:!0}),await er(Oe(e.targetDir,"releaseNotes"),{recursive:!0}),await Promise.all([Uo(e.targetDir,pc(e.artifacts??[])),Uo(e.targetDir,jn()),Uo(e.targetDir,Ln(e.includeLib===!0?["src"]:[])),Ho(Oe(e.targetDir,...Dh.split("/")),mc(e.apiName))]),Pe(e.targetDir)}var Ze=["name","apiName","externalLink","description","developerBusinessId"],rr={name:"Name",apiName:"API name",externalLink:"External link",description:"Description",developerBusinessId:"Business ID"},Vo=["name","apiName","description"],Wo=/^[a-z_][a-z0-9_]+$/,qo="must start with a letter or underscore and contain only lowercase letters, numbers, or underscores (minimum 2 characters)";function or(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}function gc(e){return{name:"",apiName:"",externalLink:"",description:"",developerBusinessId:e}}function yc(e,t){let n=t.trim();if(Vo.includes(e)&&!n)return`${rr[e]} is required`;if(e==="apiName"&&!Wo.test(n))return`${rr[e]} ${qo}`}function bc(e,t){return e==="description"?t:t.trim()}function wc(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),ae.filter(r=>n.has(r))}import{jsx as I,jsxs as B}from"react/jsx-runtime";var gt=({text:e})=>I(N,{dimColor:!0,children:e}),vc=({parentDir:e,defaultBusinessId:t,defaultEnvironment:n,includeLib:r=!1})=>{let o=Oh(),[i,s]=Ct({type:"target-select",cursor:0}),[a,c]=Ct("in-place"),[g,m]=Ct(()=>gc(t)),[h,y]=Ct(()=>[...ae]),[f,u]=Ct(""),[w,k]=Ct(e),_=ir((v,l)=>{c(v),u(l.name),s({type:"field-entry",field:0,values:l})},[]),P=ir(async v=>{let l=await Xe(v);if(l!=="ok"){s({type:"precheck-error",targetDir:v,reason:l});return}k(v),_("in-place",g)},[g,_]),C=ir(async(v,l)=>{try{let d=await hc(e,v.apiName);k(d),s({type:"confirm",values:v,artifacts:l})}catch(d){s({type:"error",message:d instanceof Error?d.message:String(d)})}},[e]),T=ir(async(v,l,d)=>{try{await nr({targetDir:l,name:v.name,apiName:v.apiName,externalLink:v.externalLink,description:v.description,developerBusinessId:v.developerBusinessId,developerEnvironment:n,artifacts:d,includeLib:r}),s({type:"done",targetDir:l})}catch(p){s({type:"error",message:p instanceof Error?p.message:String(p)})}},[n,r]);if(Bh((v,l)=>{if(l.ctrl&&v==="c"){o.exit();return}if(i.type==="target-select"){l.upArrow?s({type:"target-select",cursor:0}):l.downArrow?s({type:"target-select",cursor:1}):l.return?i.cursor===0?P(e):_("sub-dir",g):l.escape&&o.exit();return}if(i.type==="precheck-error"){(l.return||l.escape)&&o.exit();return}if(i.type==="field-entry"){let{field:d,values:p}=i,b=Ze[d];if(!b)return;if(l.escape){o.exit();return}if(l.backspace||l.delete){u(x=>x.slice(0,-1));return}if(l.upArrow&&d>0){let x={...p,[b]:f},S=d-1,E=Ze[S];s({type:"field-entry",field:S,values:x}),m(x),u(E?x[E]:"");return}if(l.return||l.tab||l.downArrow){let x=yc(b,f);if(x!==void 0){s({type:"field-entry",field:d,values:p,fieldError:x});return}let S=bc(b,f),E={...p,[b]:S};m(E);let $=d+1;if($>=Ze.length)u(""),s({type:"artifact-select",values:E,cursor:0,selected:h});else{let M=Ze[$],ee=M?E[M]:"",ce=M==="apiName"&&!ee?or(E.name):ee;s({type:"field-entry",field:$,values:E}),u(ce)}return}v&&!l.ctrl&&!l.meta&&u(x=>x+v);return}if(i.type==="artifact-select"){let{cursor:d,selected:p,values:b}=i;if(l.escape){let x=Ze.length-1,S=Ze[x];s({type:"field-entry",field:x,values:b}),u(S?b[S]:"");return}if(l.upArrow){s({...i,cursor:Math.max(0,d-1)});return}if(l.downArrow){s({...i,cursor:Math.min(ae.length-1,d+1)});return}if(v===" "){let x=ae[d];if(x){let S=wc(p,x);y(S),s({...i,selected:S})}return}if(v==="a"){y([...ae]),s({...i,selected:[...ae]});return}if(v==="n"){y([]),s({...i,selected:[]});return}l.return&&(a==="sub-dir"?(s({type:"resolving-target"}),C(b,p)):s({type:"confirm",values:b,artifacts:p}));return}if(i.type==="confirm"){if(l.escape){s({type:"artifact-select",values:i.values,cursor:0,selected:i.artifacts});return}l.return&&(s({type:"writing"}),T(i.values,w,i.artifacts));return}(i.type==="done"||i.type==="error")&&(l.return||l.escape)&&o.exit()}),i.type==="target-select"){let v=[{label:"Use current directory",desc:e},{label:"Create new sub-directory",desc:`${e}/<inferred from API name>`}];return B(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(G,{}),B(V,{flexDirection:"column",gap:0,children:[I(N,{bold:!0,children:"Where should the new plugin live?"}),v.map((l,d)=>{let p=i.cursor===d;return B(V,{gap:2,children:[I(N,{...p&&{color:"cyan"},children:p?"\u276F":" "}),I(N,{bold:p,...p&&{color:"cyan"},children:l.label}),I(N,{dimColor:!0,children:l.desc})]},l.label)})]}),I(gt,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(i.type==="precheck-error"){let{targetDir:v,reason:l}=i;return B(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(G,{}),I(N,{color:"red",bold:!0,children:"Cannot create plugin"}),B(V,{flexDirection:"column",gap:0,children:[B(N,{children:[v," already contains ",I(N,{bold:!0,children:l==="has-manifest"?"kizen.json":".kizenapp/"}),"."]}),I(N,{dimColor:!0,children:"Remove the conflicting file/directory or choose a different target to avoid overwriting an existing plugin."})]}),I(gt,{text:"Enter or Esc to exit"})]})}if(i.type==="field-entry"){let{field:v,fieldError:l}=i,d=a==="sub-dir"?`Target: sub-directory of ${e} (inferred from API name)`:`Target: ${w}`;return B(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(G,{}),B(V,{flexDirection:"column",gap:0,children:[I(N,{bold:!0,children:"Plugin details"}),I(N,{dimColor:!0,children:d})]}),l!==void 0&&B(N,{color:"red",children:["Error: ",l]}),I(V,{flexDirection:"column",gap:0,children:Ze.map((p,b)=>{let x=v===b,S=x?f:g[p],E=Vo.includes(p),$=`${rr[p]}${E?"":" (optional)"}`;return B(V,{gap:2,children:[I(V,{width:24,children:I(N,{bold:x,...x&&{color:"cyan"},children:$})}),I(N,{...x&&{color:"cyan"},children:">"}),I(N,{children:S}),x&&I(N,{color:"cyan",children:"\u2588"})]},p)})}),I(gt,{text:"Enter/Tab/\u2193 next \xB7 \u2191 previous \xB7 Backspace delete \xB7 Esc cancel"})]})}if(i.type==="artifact-select"){let{cursor:v,selected:l}=i;return B(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(G,{}),B(V,{flexDirection:"column",gap:0,children:[I(N,{bold:!0,children:"Which artifacts should we scaffold?"}),I(N,{dimColor:!0,children:"Each one gets a directory with a config.json and a script that runs."})]}),I(V,{flexDirection:"column",gap:0,children:ae.map((d,p)=>{let b=v===p,x=l.includes(d);return B(V,{gap:1,children:[I(N,{...b&&{color:"cyan"},children:b?"\u276F":" "}),I(N,{...x&&{color:"green"},children:x?"\u25C9":"\u25EF"}),I(N,{bold:b,...b&&{color:"cyan"},children:jo[d]})]},d)})}),I(gt,{text:"\u2191\u2193 move \xB7 Space toggle \xB7 a all \xB7 n none \xB7 Enter continue \xB7 Esc back"})]})}if(i.type==="confirm"){let v=Ko({targetDir:w,name:i.values.name,apiName:i.values.apiName,externalLink:i.values.externalLink,description:i.values.description,developerBusinessId:i.values.developerBusinessId,developerEnvironment:n});return B(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(G,{}),B(V,{flexDirection:"column",gap:0,children:[I(N,{bold:!0,children:"Ready to create"}),B(N,{dimColor:!0,children:["Target: ",w]})]}),B(V,{flexDirection:"column",gap:0,children:[I(N,{bold:!0,children:"kizen.json preview"}),I(N,{children:JSON.stringify(v,null,2)})]}),B(V,{flexDirection:"column",gap:0,children:[I(N,{bold:!0,children:"Artifacts"}),i.artifacts.length===0?B(N,{dimColor:!0,children:[" ","none (src/ will hold only thumbnail.png)"]}):i.artifacts.map(l=>B(N,{dimColor:!0,children:[" ",jo[l]]},l))]}),B(V,{flexDirection:"column",gap:0,children:[I(N,{dimColor:!0,children:"Also creates:"}),B(N,{dimColor:!0,children:[" ",sr(w,"src/")]}),B(N,{dimColor:!0,children:[" ",sr(w,"src/thumbnail.png")," (generated placeholder)"]}),B(N,{dimColor:!0,children:[" ",sr(w,"releaseNotes/")]}),B(N,{dimColor:!0,children:[" ",sr(w,".gitignore")," (adds .kizenapp/)"]})]}),I(gt,{text:"Enter to create \xB7 Esc to go back"})]})}return i.type==="resolving-target"?I(V,{paddingY:1,paddingX:2,children:I(N,{dimColor:!0,children:"Finding available sub-directory\u2026"})}):i.type==="writing"?I(V,{paddingY:1,paddingX:2,children:I(N,{dimColor:!0,children:"Creating plugin\u2026"})}):i.type==="done"?B(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(G,{}),B(N,{color:"green",bold:!0,children:["Plugin created at ",i.targetDir]}),B(V,{flexDirection:"column",gap:0,children:[I(N,{dimColor:!0,children:"Next steps:"}),B(N,{children:[" ","cd ",i.targetDir]}),B(N,{children:[" ","npx --yes @kizenapps/cli dev"]}),B(N,{dimColor:!0,children:[" ","Replace src/thumbnail.png with real artwork before publishing."]})]}),I(gt,{text:"Enter or Esc to exit"})]}):B(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(G,{}),I(N,{color:"red",bold:!0,children:"Failed to create plugin"}),I(N,{children:i.message}),I(gt,{text:"Enter or Esc to exit"})]})};async function xc(e){let t=await e.listSessions().catch(()=>[]);if(t.length===0){let i=await e.loadGlobalCredentials();return{businessId:i?.businessId??"",environment:i?.environment??"go"}}let n=await jt(e.requestedEnvironment?.trim()||void 0,()=>Promise.resolve(t)),r=n.ok?n.environment:"go";return{businessId:(await e.readSession(r).catch(()=>null))?.businessId??"",environment:r}}var Fh="A hello-world Kizen plugin.",kc=e=>Object.entries(e).some(([t,n])=>t!=="includeLib"&&n!==void 0);function jh(e){if(e===void 0||e.trim()===""||e.trim()==="all")return[...ae];if(e.trim()==="none")return[];let t=e.split(",").map(r=>r.trim()).filter(r=>r!==""),n=t.filter(r=>!ae.includes(r));if(n.length>0)throw new Error(`Unknown artifact type(s): ${n.join(", ")}. Valid types: ${ae.join(", ")}, or "all" / "none".`);return[...new Set(t)]}function Lh(e,t,n){let r=e.name?.trim()??"";if(r==="")throw new Error("--name is required for a non-interactive run.");let o=(e.apiName?.trim()??"")||or(r);if(!Wo.test(o))throw new Error(`api_name "${o}" is invalid: ${qo}. Pass --api-name.`);let i=e.description?.trim(),s=e.businessId?.trim()??t.businessId,a=zh(e,t);return{targetDir:n,name:r,apiName:o,externalLink:e.externalLink?.trim()??"",description:i===void 0||i===""?Fh:i,developerBusinessId:s,developerEnvironment:a,artifacts:jh(e.artifacts),includeLib:e.includeLib===!0}}function zh(e,t){let n=e.environment?.trim();if(n!==void 0&&n!==""){if(!Dt(n))throw new Error(`Unknown environment "${n}". Valid environments: ${W.join(", ")}.`);return n}if(e.businessId!==void 0&&t.businessId==="")throw new Error("--environment is required alongside --business-id when neither a sign-in session nor saved credentials give a default business, so the id is keyed to the environment that issued it.");return t.environment}async function Cc(e,t,n,r){let o;try{o=Lh(e,t,n)}catch(a){r.writeStderr(`Error: ${a instanceof Error?a.message:String(a)}
994
1012
  `),r.setExitCode(1);return}let i=await r.precheckTargetDir(n);if(i!=="ok"){let a=i==="has-manifest"?"kizen.json":".kizenapp/";r.writeStderr(`Error: ${n} already contains ${a}. Refusing to overwrite an existing plugin.
995
1013
  `),r.setExitCode(1);return}try{await r.createPlugin(o)}catch(a){r.writeStderr(`Error: ${a instanceof Error?a.message:String(a)}
996
1014
  `),r.setExitCode(1);return}let s=o.artifacts&&o.artifacts.length>0?o.artifacts.join(", "):"none";r.writeStdout(`Created plugin ${o.apiName} at ${n}
997
1015
  `),r.writeStdout(`Artifacts: ${s}
998
1016
  `),r.writeStdout(`Thumbnail: src/thumbnail.png (generated placeholder; replace it before publishing)
999
1017
  `),o.developerBusinessId.trim()===""&&r.writeStderr(`Warning: no developer_business_id configured, so this plugin cannot be preview-published yet.
1000
- `)}function La(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 your sign-in session, else saved API-key credentials)").option("-e, --environment <env>",`environment the business id belongs to: ${W.join(", ")} (defaults to your sign-in session, else saved API-key credentials)`).option("--artifacts <list>",`comma-separated artifact types, or "all" / "none" (default: all). Types: ${se.join(", ")}`).option("--include-lib","also install the Kizen data helper library (src/lib/kizenData.js)").action(async t=>{let n=process.cwd(),r=Ue(),{businessId:o,environment:i}=await Ba({listSessions:r.listSessions,readSession:r.readSession,loadGlobalCredentials:oe,...t.environment!==void 0&&{requestedEnvironment:t.environment}});if(!process.stdin.isTTY||!process.stdout.isTTY||Fa(t)){await ja(t,{businessId:o,environment:i},n,{precheckTargetDir:qe,createPlugin:Ln,writeStdout:c=>{process.stdout.write(c)},writeStderr:c=>{process.stderr.write(c)},setExitCode:c=>{process.exitCode=c}});return}let{waitUntilExit:a}=lm(cm(Oa,{parentDir:n,defaultBusinessId:o,defaultEnvironment:i,includeLib:t.includeLib===!0}),{exitOnCtrlC:!1});await a()})}import{createElement as bc}from"react";import{render as wc}from"ink";import{useCallback as wt,useEffect as Yn,useRef as $e,useState as le}from"react";import{Box as ne,Text as F,useInput as ah}from"ink";import{PluginValidationError as ch}from"@kizenapps/packager";import{watch as lh}from"fs";import{createServer as dh}from"http";import{join as hc}from"path";import{WebSocketServer as uh}from"ws";import{createReadStream as ec,realpathSync as Tm}from"fs";import{access as Am,readdir as Im,readFile as $m,realpath as Nm,stat as tc}from"fs/promises";import{dirname as Dm,extname as nc,join as Vt,resolve as Rm,sep as To}from"path";import{fileURLToPath as Om}from"url";var dm=new Set(["set-cookie","strict-transport-security","content-security-policy","content-security-policy-report-only","x-frame-options","content-encoding","content-length"]);function Vn(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.toLowerCase();dm.has(o)||o.startsWith("access-control-")||(t[n]=r)}return t}var wo=10*1024*1024,um=6e4,pm=200,Lt=class extends Error{bytesRead;limit;constructor(t,n){super(`Upstream response exceeded ${String(n)} bytes (read ${String(t)}).`),this.name="ProxyResponseTooLargeError",this.bytesRead=t,this.limit=n}};async function vo(e,t){let n=e.body;if(n===null)return Buffer.alloc(0);let r=[],o=0;for await(let i of n){if(o+=i.length,o>t)throw new Lt(o,t);r.push(i)}return Buffer.concat(r)}async function Ma(e){let t=Vn(Object.fromEntries(e.headers)),n=await vo(e,wo);return{status:e.status,headers:t,body:n}}function za(e={}){let{onChange:t,enabled:n=!0}=e;if(!n)return{async get(s,a){return{response:await Ma(await a()),fromCache:!1}},clear(){}};let r=new Map,o=()=>{t?.(r.size)},i=s=>{r.delete(s)&&o()};return{get(s,a){let c=r.get(s);if(c!==void 0){if(Date.now()-c.insertedAt<um)return c.promise.then(u=>({response:u,fromCache:!0}));i(s)}if(r.size>=pm){let u=r.keys().next().value;u!==void 0&&i(u)}let g=a().then(Ma).catch(u=>{throw i(s),u});return r.set(s,{insertedAt:Date.now(),promise:g}),o(),g.then(u=>((u.status<200||u.status>=300)&&i(s),{response:u,fromCache:!1}))},clear(){r.clear(),o()}}}var xo={".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 ko={prod:"https://plugin-wizard.kizen.com",dev:"https://plugin-wizard.kizen.dev",localDev:"http://localhost:9823"};function Mt(e){let t=process.env.PLUGIN_WIZARD_URL;return t!==void 0&&t!==""?t:e==="prod"?process.env.PLUGIN_WIZARD_URL_PROD||ko.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!==""?ko.localDev:ko.dev}import{spawn as Eo}from"child_process";import{writeFile as Wa,rm as Po,mkdtemp as gm,access as ym}from"fs/promises";import{join as Ut}from"path";import{tmpdir as bm}from"os";var Ua=`awslambdaric
1018
+ `)}function Sc(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 your sign-in session, else saved API-key credentials)").option("-e, --environment <env>",`environment the business id belongs to: ${W.join(", ")} (defaults to your sign-in session, else saved API-key credentials)`).option("--artifacts <list>",`comma-separated artifact types, or "all" / "none" (default: all). Types: ${ae.join(", ")}`).option("--include-lib","also install the Kizen data helper library (src/lib/kizenData.js)").action(async t=>{let n=process.cwd(),r=Ce(),{businessId:o,environment:i}=await xc({listSessions:r.listSessions,readSession:r.readSession,loadGlobalCredentials:se,...t.environment!==void 0&&{requestedEnvironment:t.environment}});if(!process.stdin.isTTY||!process.stdout.isTTY||kc(t)){await Cc(t,{businessId:o,environment:i},n,{precheckTargetDir:Xe,createPlugin:nr,writeStdout:c=>{process.stdout.write(c)},writeStderr:c=>{process.stderr.write(c)},setExitCode:c=>{process.exitCode=c}});return}let{waitUntilExit:a}=Uh(Mh(vc,{parentDir:n,defaultBusinessId:o,defaultEnvironment:i,includeLib:t.includeLib===!0}),{exitOnCtrlC:!1});await a()})}import{createElement as el}from"react";import{render as tl}from"ink";import{useCallback as St,useEffect as fr,useRef as Be,useState as ue}from"react";import{Box as ne,Text as F,useInput as Lg}from"ink";import{PluginValidationError as zg}from"@kizenapps/packager";import{watch as Mg}from"fs";import{createServer as Ug}from"http";import{join as Xc}from"path";import{WebSocketServer as Hg}from"ws";import{createReadStream as Bc,realpathSync as sg}from"fs";import{access as ag,readdir as cg,readFile as lg,realpath as dg,stat as Fc}from"fs/promises";import{dirname as ug,extname as jc,join as rn,resolve as pg,sep as ti}from"path";import{fileURLToPath as fg}from"url";var Hh=new Set(["set-cookie","strict-transport-security","content-security-policy","content-security-policy-report-only","x-frame-options","content-encoding","content-length"]);function ar(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.toLowerCase();Hh.has(o)||o.startsWith("access-control-")||(t[n]=r)}return t}var Go=10*1024*1024,Kh=6e4,Vh=200,Qt=class extends Error{bytesRead;limit;constructor(t,n){super(`Upstream response exceeded ${String(n)} bytes (read ${String(t)}).`),this.name="ProxyResponseTooLargeError",this.bytesRead=t,this.limit=n}};async function Jo(e,t){let n=e.body;if(n===null)return Buffer.alloc(0);let r=[],o=0;for await(let i of n){if(o+=i.length,o>t)throw new Qt(o,t);r.push(i)}return Buffer.concat(r)}async function Pc(e){let t=ar(Object.fromEntries(e.headers)),n=await Jo(e,Go);return{status:e.status,headers:t,body:n}}function Ec(e={}){let{onChange:t,enabled:n=!0}=e;if(!n)return{async get(s,a){return{response:await Pc(await a()),fromCache:!1}},clear(){}};let r=new Map,o=()=>{t?.(r.size)},i=s=>{r.delete(s)&&o()};return{get(s,a){let c=r.get(s);if(c!==void 0){if(Date.now()-c.insertedAt<Kh)return c.promise.then(m=>({response:m,fromCache:!0}));i(s)}if(r.size>=Vh){let m=r.keys().next().value;m!==void 0&&i(m)}let g=a().then(Pc).catch(m=>{throw i(s),m});return r.set(s,{insertedAt:Date.now(),promise:g}),o(),g.then(m=>((m.status<200||m.status>=300)&&i(s),{response:m,fromCache:!1}))},clear(){r.clear(),o()}}}var Yo={".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 Xo={prod:"https://plugin-wizard.kizen.com",dev:"https://plugin-wizard.kizen.dev",localDev:"http://localhost:9823"};function en(e){let t=process.env.PLUGIN_WIZARD_URL;return t!==void 0&&t!==""?t:e==="prod"?process.env.PLUGIN_WIZARD_URL_PROD||Xo.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!==""?Xo.localDev:Xo.dev}import{spawn as $c}from"child_process";import{writeFile as Tc,rm as Qo,mkdtemp as Jh,access as Yh}from"fs/promises";import{join as nn}from"path";import{tmpdir as Xh}from"os";var _c=`awslambdaric
1001
1019
  bcrypt
1002
1020
  boto3
1003
1021
  fpdf2
@@ -1015,8 +1033,7 @@ pytz
1015
1033
  requests
1016
1034
  sqlalchemy>=2.0,<2.1
1017
1035
  tzdata
1018
- `;import{AUTOMATION_SCRIPT_RUNTIMES as wm,isSupportedScriptRuntime as vm,scriptRuntimeToApiName as Ja}from"@kizenapps/packager";function Ha(e){return e.split(`
1019
- `).map(t=>t.trim().replace(/\s+#.*$/,"")).filter(t=>t.length>0&&!t.startsWith("#"))}function Va(e){let t=/^python-(\d+)[.-](\d+)$/.exec(e),n=t?.[1],r=t?.[2];return n!==void 0&&r!==void 0?`python${n}.${r}`:"python3"}function mm(e){return e==null||e.trim()===""?null:e}function hm(e){return e==null?null:typeof e=="string"?mm(e):typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):typeof e=="function"||typeof e=="symbol"?null:JSON.stringify(e)}function Ka(e){return e?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,hm(n)])):{}}var xm=`
1036
+ `;import{AUTOMATION_SCRIPT_RUNTIMES as Zh,isSupportedScriptRuntime as Qh,scriptRuntimeToApiName as Nc}from"@kizenapps/packager";function qh(e){return e==null||e.trim()===""?null:e}function Gh(e){return e==null?null:typeof e=="string"?qh(e):typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):typeof e=="function"||typeof e=="symbol"?null:JSON.stringify(e)}function Ac(e){return e?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Gh(n)])):{}}var eg=`
1020
1037
  import sys, json, os, traceback
1021
1038
 
1022
1039
  # --- Inputs proxy (attribute access) ---
@@ -1176,29 +1193,29 @@ sys.stdout.write('\\n__KIZEN_RESULT_START__\\n')
1176
1193
  sys.stdout.write(json.dumps(result, ensure_ascii=False))
1177
1194
  sys.stdout.write('\\n__KIZEN_RESULT_END__\\n')
1178
1195
  sys.stdout.flush()
1179
- `.trim(),km=3e4,Kn=Ut(process.cwd(),".kizenapp","venv"),Cm=wm.map(Ja),Ga=Ha(Ua);if(Ga.length===0)throw new Error("python-requirements.txt bundled no packages \u2014 check the build output");var zt=null,Ht=[3,10];function Ya([e,t]){return e>Ht[0]||e===Ht[0]&&t>=Ht[1]}function Co(e){return`${String(e[0])}.${String(e[1])}`}function Xa(e){return new Promise(t=>{let n=Eo(e,["-c","import sys; print('%d.%d' % sys.version_info[:2])"],{stdio:["ignore","pipe","ignore"]}),r="";n.stdout.on("data",o=>{r+=o.toString("utf-8")}),n.on("error",()=>{t(null)}),n.on("close",o=>{let i=/(\d+)\.(\d+)/.exec(r);if(o!==0||!i){t(null);return}t([Number(i[1]),Number(i[2])])})})}async function Sm(e){let t=Va(e),n=t==="python3"?["python3"]:[t,"python3"],r=[];for(let o of n){let i=await Xa(o);if(!i){r.push(`${o}: not found`);continue}if(Ya(i))return o;r.push(`${o}: ${Co(i)} (too old)`)}throw new Error(`No Python >= ${Co(Ht)} found for runtime "${e}". The local runner needs Python ${Co(Ht)}+ to install the bundled packages (e.g. psycopg 3.3), matching the remote code-runner (3.12 / 3.13). Tried ${r.join(", ")}. Install Python 3.12 or 3.13 and retry.`)}function qa(e,t,n){return new Promise((r,o)=>{let i=Eo(e,t,{stdio:["ignore","pipe","pipe"]}),s=(c,g)=>{let u=[],h="";return c.on("data",v=>{h+=v.toString("utf-8");let p=h.indexOf(`
1180
- `);for(;p>=0;){let l=h.slice(0,p).replace(/\r$/,"");h=h.slice(p+1),u.push(l),n?.(l,g),p=h.indexOf(`
1181
- `)}}),c.on("end",()=>{if(h.length>0){let v=h.replace(/\r$/,"");u.push(v),n?.(v,g)}}),u},a=s(i.stderr,"stderr");s(i.stdout,"stdout"),i.on("error",o),i.on("close",c=>{if(c===0)r();else{let g=a.slice(-10).join(`
1182
- `).trim(),u=g.length>0?`: ${g}`:"";o(new Error(`${e} exited with code ${String(c)}${u}`))}})})}var So=null;function Pm(e,t){if(zt)return t&&So?.add(t),zt;let n=new Set;t&&n.add(t),So=n;let r=i=>{for(let s of n)s(i)},o=Ut(Kn,"bin","python");return zt=(async()=>{try{let i=!1;try{await ym(o);let s=await Xa(o);i=s!==null&&Ya(s)}catch{i=!1}if(!i){await Po(Kn,{recursive:!0,force:!0}).catch(()=>{});let s=await Sm(e);await qa(s,["-m","venv",Kn])}return r({kind:"start"}),await qa(o,["-m","pip","install","--disable-pip-version-check",...Ga],(s,a)=>{r({kind:"log",line:s,stream:a})}),r({kind:"complete"}),o}catch(i){let s=i instanceof Error?i.message:String(i);throw r({kind:"error",message:s}),zt=null,await Po(Kn,{recursive:!0,force:!0}).catch(()=>{}),i}finally{So=null}})(),zt}function Em(e){let t="__KIZEN_RESULT_START__",n="__KIZEN_RESULT_END__",r=e.indexOf(t),o=e.indexOf(n);if(r===-1||o===-1)return{userStdout:e,result:null};let i=e.slice(0,r).trimEnd(),s=e.slice(r+t.length,o).trim();try{let a=JSON.parse(s);return{userStdout:i,result:a}}catch{return{userStdout:e,result:null}}}function _m(e){return{success:!1,outputValues:{},logs:[],stdout:"",stderr:"",error:e,exitCode:1,durationMs:0}}async function Za(e){let t=e.timeout??km;if(!vm(e.scriptRuntime))return _m(`Unsupported runtime "${e.scriptRuntime}". Supported runtimes: ${Cm.join(", ")}. Update the step's config.json "runtime" field (e.g. "python 3.13").`);let r=await Pm(Ja(e.scriptRuntime),e.onInstallProgress),o=Date.now(),i;try{i=await gm(Ut(bm(),"kizen-step-"));let s=Ut(i,"wrapper.py"),a=Ut(i,"script.py");await Promise.all([Wa(s,xm,"utf-8"),Wa(a,e.script,"utf-8")]);let c={...process.env,__KIZEN_INPUTS__:JSON.stringify(e.inputs),__KIZEN_SECRETS__:JSON.stringify(e.secrets),__KIZEN_SCRIPT_PATH__:a},{exitCode:g,stdout:u,stderr:h}=await new Promise(C=>{let E=[],x=[],y=!1,P=Eo(r,[s],{env:c,cwd:i,stdio:["ignore","pipe","pipe"]}),b=setTimeout(()=>{P.kill("SIGKILL")},t);P.stdout.on("data",d=>{E.push(d)}),P.stderr.on("data",d=>{x.push(d)});let f=d=>{y||(y=!0,clearTimeout(b),C({exitCode:d??1,stdout:Buffer.concat(E).toString("utf-8"),stderr:Buffer.concat(x).toString("utf-8")}))};P.on("close",f),P.on("error",d=>{y||(y=!0,clearTimeout(b),C({exitCode:1,stdout:"",stderr:d.message}))})}),v=Date.now()-o,{userStdout:p,result:l}=Em(u);if(l){let C={success:l.success,outputValues:l.outputValues,logs:l.logs,stdout:p,stderr:h,exitCode:g,durationMs:v};return l.error!==null&&(C.error=l.error),l.httpRequests&&(C.httpRequests=l.httpRequests),C}let w={success:!1,outputValues:{},logs:[],stdout:p,stderr:h,exitCode:g,durationMs:v};return g!==0&&(w.error=`Process exited with code ${String(g)}`),w}finally{i&&Po(i,{recursive:!0,force:!0})}}var Qa=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 rc,CRYPTO_VERSION as oc,DEFAULT_AUTOMATION_RUNTIME as Bm,deserializeEnvelope as Fm,encrypt as jm,scriptRuntimeToApiName as Lm,serializeEnvelope as Mm}from"@kizenapps/packager";function _o(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 zm=2*1024*1024,Um=new Set([".DS_Store",".gitignore"]);function Hm(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 cc=["kizen.com","kizen.dev"];function Vm(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:cc.some(r=>n===r||n.endsWith("."+r))}function Km(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let n=t.hostname.toLowerCase();return cc.some(r=>n===r||n.endsWith("."+r))}function Wm(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 ic(e,t){if(t.includes("\0"))return null;let n=t.replace(/^\/+/,""),r=Rm(e,n);if(r!==e&&!r.startsWith(e+To))return null;try{let o=await Nm(r);return o!==e&&!o.startsWith(e+To)?null:o}catch{return null}}function sc(e,t){let n=t===e?"":t.slice(e.length+1);return n===""?!1:n.split(To).some(o=>bn.has(o))}function lc(){let e=Om(import.meta.url);return Vt(Dm(e),"viewer")}function ac(e,t,n){if(e.includes("/external-integrations/proxy")&&t["content-type"]?.includes("application/json"))try{let r=JSON.parse(n.toString("utf8"));return typeof r.status_code=="number"?r.status_code:void 0}catch{return}}async function Ao(e){try{return await Am(e),!0}catch{return!1}}function dc(e,t,n,r,o,i,s,a,c,g,u){let h=za({onChange:a,enabled:u}),v=Tm(g);return(p,l)=>{(async()=>{let w=p.url??"/";try{if(!Hm(p.headers.host)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Forbidden"}));return}if((p.method==="POST"||p.method==="PATCH"||p.method==="DELETE")&&!Wm(p.headers.origin)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Forbidden"}));return}if(t(`Received request: ${w}`),w==="/api/credentials"){l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({credentials:r.current??null,activeProfile:o.current??null}));return}if(w==="/api/credential-profiles"&&p.method==="GET"){let f=await je();l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({profiles:f,active:o.current}));return}if(w==="/api/credentials/switch"&&p.method==="POST"){let f=[];for await(let S of p)f.push(S);let m=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}").profile,k=m===void 0||m===""?await oe():await Pe(m);if(k!==null){r.current=k,o.current=m??void 0;let S=o.current,T=await we(i);await Ve(i,{...T,credentialMode:"global",...S!==void 0&&{activeCredentialProfile:S}}),s({type:"credentials-updated",credentials:k,activeProfile:o.current??null})}l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({ok:k!==null}));return}if(w==="/api/bundle"){let f=Vt(process.cwd(),".kizenapp","bundle.json");try{let d=await $m(f,"utf-8");l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(d)}catch{l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end("{}")}return}if(w==="/api/last-path"&&p.method==="POST"){let f=[];for await(let m of p)f.push(m);let d=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}");if(typeof d.path=="string"){c.current=d.path;let m=await we(i);await Ve(i,{...m,lastPath:d.path})}l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end('{"ok":true}');return}if(w==="/api/encryption-target"&&p.method==="GET"){let d=(await we(i)).encryptionTarget==="dev"?"dev":"prod";l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({target:d}));return}if(w==="/api/encryption-target"&&p.method==="POST"){let f=[];for await(let S of p)f.push(S);let d=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}"),m=d!==null&&typeof d=="object"?d:{};if(m.target!=="dev"&&m.target!=="prod"){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"target must be one of: 'dev', 'prod'"}));return}let k=await we(i);await Ve(i,{...k,encryptionTarget:m.target}),l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end('{"ok":true}');return}if(w==="/api/execute-step"&&p.method==="POST"){let f=[];for await(let S of p)f.push(S);let d=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}");if(typeof d.script!="string"){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing required field: script"}));return}let m={script:d.script,scriptRuntime:d.scriptRuntime??Lm(Bm),inputs:Ka(d.inputs),secrets:d.secrets??{},onInstallProgress:S=>{S.kind==="start"?s({type:"venv-install-start"}):S.kind==="log"?s({type:"venv-install-log",line:S.line,stream:S.stream}):S.kind==="complete"?s({type:"venv-install-complete"}):s({type:"venv-install-error",message:S.message})}};typeof d.timeout=="number"&&d.timeout>0&&(m.timeout=Math.min(d.timeout,300*1e3));let k=await Za(m);l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify(k));return}if(w==="/api/proxy-cache/clear"){h.clear(),n({kind:"info",message:"Proxy cache cleared"}),l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end('{"ok":true}');return}if(w==="/api/local/encrypt"&&p.method==="POST"){let f=[];for await(let m of p)f.push(m);let d=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}");if(typeof d.publicKeyPem!="string"||typeof d.value!="string"){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing required fields: publicKeyPem, value"}));return}try{let m=jm(d.value,d.publicKeyPem),k=Mm(m);l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify(k))}catch(m){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:m.message}))}return}if(w==="/api/local/validate"&&p.method==="POST"){let f=[];for await(let _ of p)f.push(_);let d=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}");if(typeof d.value!="string"){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing required field: value"}));return}let m,k;try{m=Fm(d.value)}catch(_){k=_.message}if(k!==void 0||m===void 0){l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({valid:!1,checks:[],error:k}));return}let S=_=>Buffer.from(_,"base64").length,T=[{label:"Version",expected:String(oc),actual:String(m.v),pass:m.v===oc},{label:"Algorithm",expected:rc,actual:m.alg,pass:m.alg===rc},{label:"Wrapped key",expected:"384 bytes (RSA-3072)",actual:`${String(S(m.k))} bytes`,pass:S(m.k)===384},{label:"IV",expected:"12 bytes",actual:`${String(S(m.iv))} bytes`,pass:S(m.iv)===12},{label:"Auth tag",expected:"16 bytes",actual:`${String(S(m.tag))} bytes`,pass:S(m.tag)===16},{label:"Ciphertext",expected:"\u2265 1 byte",actual:`${String(S(m.ct))} bytes`,pass:S(m.ct)>=1}];l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({valid:T.every(_=>_.pass),checks:T}));return}if(w.startsWith("/api/wizard")){let f=p.headers["x-encryption-target"],m=(Array.isArray(f)?f[0]:f)==="dev"?"dev":"prod",k=Mt(m);if(!Vm(k)){l.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:`Encryption API host is not allowed: ${k}`}));return}let S=w.slice(11)||"/",T=`${k}${S}`,_=p.method??"GET",R=[];for await(let Xe of p)R.push(Xe);let{host:z,"x-encryption-target":ee,...ae}=p.headers,me=R.length>0?Buffer.concat(R):void 0,he=me&&me.length>0?me:void 0,ue;try{ue=await fetch(T,{method:_,headers:ae,...he!==void 0&&{body:he}})}catch(Xe){let nr=Xe.code==="ECONNREFUSED"?`plugin-wizard is not running at ${k}`:`Failed to reach plugin-wizard: ${Xe.message}`;l.writeHead(503,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:nr}));return}let de=Vn(Object.fromEntries(ue.headers)),vt=await ue.arrayBuffer();l.writeHead(ue.status,de),l.end(Buffer.from(vt));return}if(w.startsWith("/api/proxy")){let f=p.headers["x-proxy-target"];if(typeof f!="string"){l.writeHead(400),l.end("Missing x-proxy-target header");return}if(!Km(f)){l.writeHead(400),l.end("Invalid proxy target");return}let d=w.slice(10)||"/",m=`${f}${d}`,k=p.method??"GET",S=[];for await(let ue of p)S.push(ue);let{host:T,"x-proxy-target":_,...R}=p.headers;if(k==="GET"){let ue=`GET::${m}`,{response:de,fromCache:vt}=await h.get(ue,()=>fetch(m,{method:"GET",headers:R}));n({kind:"request",method:"GET",status:de.status,upstreamStatus:ac(d,de.headers,de.body),fromCache:vt,url:d}),l.writeHead(de.status,de.headers),l.end(de.body);return}let z=S.length>0?Buffer.concat(S):void 0,ee=z&&z.length>0?z:void 0,ae=await fetch(m,{method:k,headers:R,...ee!==void 0&&{body:ee}}),me=Vn(Object.fromEntries(ae.headers)),he=await vo(ae,wo);n({kind:"request",method:k,status:ae.status,upstreamStatus:ac(d,me,he),fromCache:!1,url:d}),l.writeHead(ae.status,me),l.end(he);return}if(w.startsWith("/api/source/tree")&&p.method==="GET"){let d=new URL(w,"http://localhost").searchParams.get("path")??"",m=await ic(v,d);if(m===null){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Invalid path"}));return}if(sc(v,m)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Path is excluded"}));return}try{let k=await Im(m,{withFileTypes:!0}),S=await Promise.all(k.filter(_=>_.isDirectory()?!bn.has(_.name):_.isFile()?!Um.has(_.name):!1).map(async _=>{let R=_.isDirectory()?"dir":"file",z={name:_.name,kind:R};if(R==="file")try{let ee=await tc(Vt(m,_.name));z.size=ee.size}catch{}return z}));S.sort((_,R)=>_.kind!==R.kind?_.kind==="dir"?-1:1:_.name.localeCompare(R.name));let T=m===v?"":m.slice(v.length+1);l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({path:T,entries:S}))}catch(k){let S=k instanceof Error?k.message:String(k);t(`source/tree failed (${d}): ${S}`),l.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Not found"}))}return}if(w.startsWith("/api/source/file")&&p.method==="GET"){let d=new URL(w,"http://localhost").searchParams.get("path")??"";if(d===""){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing path"}));return}let m=await ic(v,d);if(m===null){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Invalid path"}));return}if(sc(v,m)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Path is excluded"}));return}try{let k=await tc(m);if(!k.isFile()){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Not a file"}));return}if(k.size>zm){l.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"File too large",size:k.size}));return}let S=nc(m).toLowerCase(),T=xo[S],_=Qa.has(S),R=T??(_?"text/plain; charset=utf-8":"application/octet-stream");l.writeHead(200,{"Content-Type":R,"Content-Length":String(k.size)}),ec(m).pipe(l)}catch(k){let S=k instanceof Error?k.message:String(k);t(`source/file failed (${d}): ${S}`),l.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Not found"}))}return}let x=Vt(e,w==="/"?"/index.html":w),y=await Ao(x)?x:Vt(e,"index.html"),P=nc(y),b=xo[P]??"application/octet-stream";l.writeHead(200,{"Content-Type":b}),ec(y).pipe(l)}catch(C){if(w.startsWith("/api/proxy")){let E=w.slice(10)||"/",x=p.method??"GET";C instanceof Lt?n({kind:"info",message:`${x} ${E} \u2192 502 (response exceeded ${String(C.limit)} bytes)`}):n({kind:"request",method:x,status:502,fromCache:!1,url:E})}else n({kind:"info",message:`Error handling ${w}: ${C instanceof Error?C.message:String(C)}`});l.headersSent||(l.writeHead(502),l.end("Bad Gateway"))}})()}}import{launch as qm}from"chrome-launcher";import{createRequire as Jm}from"module";import{mkdirSync as Gm}from"fs";import{readFile as Ym}from"fs/promises";import{dirname as Xm,join as Zm}from"path";import{fileURLToPath as Qm}from"url";var uc=Jm(import.meta.url)("chrome-remote-interface"),eh=new Set(["content-security-policy","content-security-policy-report-only","x-frame-options"]),fc=["kizen.dev","kizen.com"];function pc(e){try{let{hostname:t}=new URL(e);return fc.some(n=>t===n||t.endsWith("."+n))}catch{return!1}}async function th(e){try{let t=Zm(Xm(Qm(import.meta.url)),"viewer","icon.png"),n=await Ym(t);await e.Browser.setDockTile({image:n.toString("base64")})}catch{}}async function mc(e){Gm(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,n=await qm({startingUrl:t,chromeFlags:[`--app=${t}`,"--no-first-run","--no-default-browser-check","--disable-extensions","--disable-features=DeviceBoundSessions"],userDataDir:e.userDataDir,handleSIGINT:!1,logLevel:"silent"}),r=n.port,o=null,i=null,s=null,a=null,c=0,g=!1,u=y=>{e.debugLog?.(y)},h=y=>{e.verbose&&e.debugLog?.(y)},v=()=>{i!==null&&(clearInterval(i),i=null)},p=y=>y==="chrome://new-tab-page/"||y==="chrome://newtab/",l=async y=>{v(),s=null,await th(y),await y.Fetch.enable({patterns:fc.flatMap(b=>[{urlPattern:`*://${b}/*`,requestStage:"Response"},{urlPattern:`*://*.${b}/*`,requestStage:"Response"}])}),y.on("Fetch.requestPaused",b=>{(async()=>{let f=b,{requestId:d,request:m,responseHeaders:k,responseStatusCode:S}=f,T=m.url;h(`Fetch ${String(S??"?")} ${T}`);let _=[],R=!1;for(let z of k??[])if(!eh.has(z.name.toLowerCase()))if(z.name.toLowerCase()==="set-cookie"&&pc(T)){let ee=z.value.split(`
1183
- `).map(ae=>/SameSite=/i.test(ae)?ae.replace(/SameSite=\w+/i,"SameSite=None"):ae+"; SameSite=None; Secure").join(`
1184
- `);_.push({name:z.name,value:ee}),R=!0}else _.push(z);R&&h(` rewrote Set-Cookie SameSite on ${T}`);try{let{body:z,base64Encoded:ee}=await y.Fetch.getResponseBody({requestId:d});await y.Fetch.fulfillRequest({requestId:d,responseCode:S??200,responseHeaders:_,body:z,...ee&&{base64Encoded:!0}})}catch(z){h(` fulfillRequest failed (${z.message}), falling through`);try{await y.Fetch.continueRequest({requestId:d})}catch(ee){h(` continueRequest also failed (${ee.message})`)}}})()}),i=setInterval(()=>{(async()=>{try{let{cookies:b}=await y.Network.getAllCookies(),f=0;for(let d of b){if(!pc(`https://${d.domain??""}`)||d.sameSite==="None")continue;let m=d.domain??"",k=m.startsWith(".")?m.slice(1):m;await y.Network.setCookie({url:`https://${k}`,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"}),f++}f>0&&h(`cookie-patch cycle: updated ${String(f)} cookie(s) to SameSite=None`)}catch(b){h(`cookie-patch cycle failed: ${b.message}`)}})()},2e3),await y.Target.setDiscoverTargets({discover:!0});let P=b=>{if(b.type==="page"){if(p(b.url)){u(`closed stray new-tab-page target ${b.targetId}`),s!==null&&y.Target.activateTarget({targetId:s}).catch(()=>{}),y.Target.closeTarget({targetId:b.targetId}).catch(()=>{});return}s===null&&(s=b.targetId,u(`captured main target ${b.targetId} (${b.url})`))}};y.on("Target.targetCreated",b=>{let{targetInfo:f}=b;h(`target +${f.type} ${f.targetId} ${f.url}`),P(f)}),y.on("Target.targetInfoChanged",b=>{let{targetInfo:f}=b;h(`target ~${f.type} ${f.targetId} ${f.url}`),P(f)}),y.on("disconnect",()=>{g||o!==y||(u("CDP disconnected"),o=null,v(),w())})},w=()=>{if(g||a!==null)return;let y=Math.min(1e3*2**c,1e4),P=c+1;c++,u(`CDP reconnect scheduled in ${String(y)}ms (attempt #${String(P)})`),a=setTimeout(()=>{a=null,(async()=>{let b;try{b=await uc({port:r})}catch{u(`CDP reconnect attempt #${String(P)} failed`),w();return}if(g){try{await b.close()}catch{}return}o=b;try{await l(b),u(`CDP reconnected after ${String(P)} attempt(s)`),c=0}catch{o===b&&(o=null);try{await b.close()}catch{}u(`CDP reconnect attempt #${String(P)} failed during setup`),w()}})()},y)},C=30,E=300;for(let y=0;y<C;y++){await new Promise(P=>setTimeout(P,E)),u(`CDP connect attempt ${String(y+1)}/${String(C)}`);try{let P=await uc({port:r});o=P,e.path&&P.send("Page.navigate",{url:`${t}${e.path}`});try{await l(P),u("CDP connected")}catch{o===P&&(o=null);try{await P.close()}catch{}u("CDP setup failed after connect")}break}catch{if(y===C-1){let P=`CDP unavailable after ${String(C)} attempts \u2014 viewer running without interception (CSP/cookie rewrites disabled)`;return u(P),e.onWarn?.(P),{kill:()=>{n.kill()}}}}}return o?{kill:()=>{if(u("CDP kill requested \u2014 tearing down"),g=!0,a!==null&&(clearTimeout(a),a=null),v(),o!==null){try{o.close()}catch{}o=null}n.kill()}}:{kill:()=>{n.kill()}}}import{useCallback as nh,useState as rh}from"react";function Wn(e){let[t,n]=rh([]),r=nh(o=>{n(i=>[...i,`${new Date().toLocaleTimeString()}: ${o}`].slice(-e))},[e]);return[t,r]}import{useCallback as qn,useEffect as Io,useState as Jn}from"react";import{Box as Q,Text as M,useInput as oh}from"ink";import{jsx as N,jsxs as te}from"react/jsx-runtime";var Ge=["apiKey","userId","businessId"],ih={apiKey:"API Key",userId:"User ID",businessId:"Business ID"},Kt=({text:e})=>N(M,{dimColor:!0,children:e}),Gn=({initialMode:e,showProfileManager:t,onComplete:n,onCancel:r})=>{let[o,i]=Jn(e==="global"&&!t?{type:"loading"}:e==="global"&&t?{type:"profile-loading"}:{type:"mode-select",cursor:0}),[s,a]=Jn(""),[c,g]=Jn(null),[u,h]=Jn(void 0),v=qn(b=>{if(b==="local"){n({mode:"local",credentials:null});return}i({type:"profile-loading"})},[n]),p=qn(async b=>{if(b===null){i({type:"profile-loading"});let m=await je();i({type:"name-entry",nameBuffer:"",existingProfiles:m});return}h(b.isDefault?void 0:b.name),i({type:"loading"});let f=b.isDefault?await oe():await Pe(b.name),d=f?Math.max(0,W.indexOf(f.environment)):0;i({type:"creds-entry",field:0,values:f??{},envCursor:d})},[]),l=qn(async(b,f)=>{let d=W[f]??"go",m={...Ct(b),environment:d};i({type:"saving"});try{await Ho(u??Be,m),n({mode:"global",credentials:m,...u!==void 0&&{profileName:u}})}catch(k){g(k instanceof Error?k.message:String(k)),i({type:"creds-entry",field:0,values:b,envCursor:f})}},[n,u]);oh((b,f)=>{if(f.ctrl&&b==="c"&&process.exit(0),f.escape){if((o.type==="creds-entry"||o.type==="name-entry")&&e==="global"&&t){i({type:"profile-loading"}),w();return}r?.();return}if(o.type==="mode-select"){if(f.upArrow)i({type:"mode-select",cursor:0});else if(f.downArrow)i({type:"mode-select",cursor:1});else if(f.return){let d=o.cursor===0?"global":"local";v(d)}return}if(o.type==="profile-select"){let{profiles:d,cursor:m}=o,k=d.length,S=d.length+1;if(f.upArrow)i({...o,cursor:(m-1+S)%S});else if(f.downArrow)i({...o,cursor:(m+1)%S});else if(f.return)if(m===k)i({type:"name-entry",nameBuffer:"",existingProfiles:d});else{let T=d[m]??d[0];T&&p(T)}return}if(o.type==="name-entry"){let{nameBuffer:d,existingProfiles:m}=o;if(f.backspace||f.delete)i({type:"name-entry",nameBuffer:d.slice(0,-1),existingProfiles:m});else if(f.return){let k=d.trim();if(!k){i({...o,nameError:"Name cannot be empty"});return}if(k===Be){i({...o,nameError:`"${Be}" is reserved`});return}if(m.some(S=>S.name===k)){i({...o,nameError:`Profile "${k}" already exists`});return}h(k),i({type:"creds-entry",field:0,values:{},envCursor:0}),a("")}else b&&!f.ctrl&&!f.meta&&i({type:"name-entry",nameBuffer:d+b,existingProfiles:m});return}if(o.type==="creds-entry"){let{field:d,values:m,envCursor:k}=o;if(d===Ge.length){f.leftArrow?i({...o,envCursor:(k-1+W.length)%W.length}):f.rightArrow?i({...o,envCursor:(k+1)%W.length}):f.upArrow?(i({...o,field:d-1}),a(m[Ge[d-1]]??"")):f.return&&l(m,k);return}let T=Ge[d];if(!T)return;if(f.backspace||f.delete)a(_=>_.slice(0,-1));else if(f.upArrow&&d>0){let _={...m,[T]:s},R=d-1;i({...o,field:R,values:_}),a(_[Ge[R]]??"")}else if(f.return||f.tab||f.downArrow){let _={...m,[T]:s},R=d+1;i({...o,field:R,values:_}),R<Ge.length?a(_[Ge[R]]??""):a("")}else b&&!f.ctrl&&!f.meta&&a(_=>_+b)}});let w=qn(async()=>{let b=await je();i({type:"profile-select",profiles:b,cursor:0})},[]);if(Io(()=>{o.type==="profile-loading"&&w()},[o.type,w]),Io(()=>{e==="global"&&!t&&(async()=>{let b=await oe(),f=b?Math.max(0,W.indexOf(b.environment)):0;i({type:"creds-entry",field:0,values:b??{},envCursor:f})})()},[]),Io(()=>{o.type==="creds-entry"&&o.field===0&&a(o.values.apiKey??"")},[o.type]),o.type==="loading"||o.type==="saving"||o.type==="profile-loading"){let b=o.type==="saving"?"Saving credentials\u2026":o.type==="profile-loading"?"Loading profiles\u2026":"Loading credentials\u2026";return N(Q,{paddingY:1,paddingX:2,children:N(M,{dimColor:!0,children:b})})}if(o.type==="done")return null;if(o.type==="mode-select")return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[N(J,{}),te(Q,{flexDirection:"column",gap:0,children:[N(M,{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((f,d)=>{let m=o.cursor===d;return te(Q,{gap:2,children:[N(M,{...m&&{color:"cyan"},children:m?"\u276F":" "}),N(M,{bold:m,...m&&{color:"cyan"},children:f.label}),N(M,{dimColor:!0,children:f.desc})]},f.mode)})]}),N(Kt,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]});if(o.type==="profile-select"){let{profiles:b,cursor:f}=o,d=b.length;return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[N(J,{}),te(Q,{flexDirection:"column",gap:0,children:[N(M,{bold:!0,children:"Credential profiles"}),b.map((m,k)=>{let S=f===k;return te(Q,{gap:2,children:[N(M,{...S&&{color:"cyan"},children:S?"\u276F":" "}),N(M,{bold:S,...S&&{color:"cyan"},children:m.isDefault?"Default":m.name}),N(M,{dimColor:!0,children:m.path})]},m.name)}),te(Q,{gap:2,children:[N(M,{...f===d&&{color:"cyan"},children:f===d?"\u276F":" "}),N(M,{bold:f===d,...f===d&&{color:"cyan"},children:"+ Add new profile"})]})]}),N(Kt,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(o.type==="name-entry"){let{nameBuffer:b,nameError:f}=o;return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[N(J,{}),N(Q,{flexDirection:"column",gap:0,children:N(M,{bold:!0,children:"New credential profile"})}),f&&te(M,{color:"red",children:["Error: ",f]}),te(Q,{gap:2,children:[N(Q,{width:12,children:N(M,{bold:!0,color:"cyan",children:"Profile name"})}),N(M,{color:"cyan",children:">"}),N(M,{children:b}),N(M,{color:"cyan",children:"\u2588"})]}),N(Kt,{text:"Type a name \xB7 Enter to confirm \xB7 Esc to go back"})]})}let{field:C,values:E,envCursor:x}=o,y=C===Ge.length,P=u??Be;return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[N(J,{}),te(Q,{flexDirection:"column",gap:0,children:[N(M,{bold:!0,children:u!==void 0?`Profile: ${u}`:"Global credentials"}),te(M,{dimColor:!0,children:["Saved to:"," ",u!==void 0?`~/.kizenappbuilder/${u}.json`:Oe]})]}),c&&te(M,{color:"red",children:["Error: ",c]}),te(Q,{flexDirection:"column",gap:0,children:[Ge.map((b,f)=>{let d=C===f,m=d?s:E[b]??"";return te(Q,{gap:2,children:[N(Q,{width:12,children:N(M,{bold:d,...d&&{color:"cyan"},children:ih[b]})}),N(M,{...d&&{color:"cyan"},children:">"}),N(M,{children:m}),d&&N(M,{color:"cyan",children:"\u2588"})]},b)}),te(Q,{gap:2,children:[N(Q,{width:12,children:N(M,{bold:y,...y&&{color:"cyan"},children:"Environment"})}),N(M,{...y&&{color:"cyan"},children:">"}),N(Q,{gap:1,children:W.map((b,f)=>{let d=f===x;return y?N(M,{bold:d,...d&&{color:"cyan"},children:d?`[${b}]`:b},b):N(M,{dimColor:!d,bold:d,children:b},b)})})]})]}),y?N(Kt,{text:"\u2190\u2192 to select \xB7 \u2191\u2193 to move \xB7 Enter to save \xB7 Esc to cancel"}):N(Kt,{text:"\u2191\u2193 to move \xB7 Backspace to delete \xB7 Esc to cancel"}),te(M,{dimColor:!0,children:["Profile: ",P]})]})};import{jsx as j,jsxs as X}from"react/jsx-runtime";var ph=[".kizenapp",".git"],gc=({port:e,pluginDir:t,outputDir:n,credentials:r,credentialMode:o,activeCredentialProfile:i,lastPath:s,debug:a=!1,verbose:c=!1,autoViewer:g=!0,cacheEnabled:u=!0})=>{let h=$e(r),v=$e(i),p=$e(s),[l,w]=le("main"),[C,E]=le(o),[x,y]=le("starting"),[P,b]=le(null),[f,d]=Wn(50),[m,k]=Wn(50),[S,T]=Wn(50),[_,R]=le([]),[z,ee]=le("pending"),[ae,me]=le(null),[he,ue]=le(null),[de,vt]=le(null),[Xe,nr]=le(null),[rr,or]=le(0),[Ro,nl]=le(0),[rl,ol]=le(0),[ir,il]=le(0),sr=$e(!1),Oo=$e(!1),qt=$e(null),xt=$e(null),Ne=$e(new Set),Jt=$e([]),pe=wt(A=>{let H=JSON.stringify(A);if(Ne.current.size===0){Jt.current=[...Jt.current,H].slice(-50);return}let De=!1;for(let ge of Ne.current)if(ge.readyState===1)try{ge.send(H)}catch{Ne.current.delete(ge),De=!0}De&&or(Ne.current.size)},[]),Gt=d,ar=wt(()=>{qt.current?.kill(),qt.current=null,mc({port:e,userDataDir:hc(n,".chrome"),broadcast:pe,onWarn:A=>{d(`\u26A0 ${A}`)},...p.current!==void 0&&{path:p.current},...a&&{debugLog:T},...c&&{verbose:!0}}).then(A=>{qt.current=A})},[e,n,pe,a,c,T,d]);Yn(()=>{let A=()=>{qt.current?.kill()};return process.on("exit",A),()=>{process.off("exit",A)}},[]),ah((A,H)=>{(A==="q"||H.ctrl&&A==="c")&&process.exit(0),A==="c"&&w("editing"),A==="v"&&ar()},{isActive:l==="main"}),Yn(()=>{x!=="running"||Oo.current||!g||(Oo.current=!0,ar())},[x,g,ar]);let sl=wt(A=>{h.current=A.credentials,v.current=A.profileName,w("main"),E(A.mode);let H=A.profileName;Ve(n,{credentialMode:A.mode,...H!==void 0&&{activeCredentialProfile:H}}),pe({type:"credentials-updated",credentials:A.credentials})},[n,pe]),Bo=wt(A=>{R(H=>[...H,`${new Date().toLocaleTimeString()}: ${_o(A)}`].slice(-50)),A.kind==="request"&&(A.fromCache?ol(H=>H+1):il(H=>H+1)),pe({type:"proxy-log",entry:A})},[pe]),Ze=wt(A=>{k(A),pe({type:"log",message:A})},[k,pe]),cr=wt(()=>{sr.current||(sr.current=!0,ee("building"),me(null),ue(null),Ze("Build started"),vn(t,n).then(({bundleSize:A})=>{Ze(`Build finished \u2014 bundle: ${Rt(A)}`),ee("done"),vt(new Date),nr(A),Ze("Notifying viewers to reload"),pe({type:"rebuild"})}).catch(A=>{A instanceof ch?(ue(A.issues),me(null)):(me(A instanceof Error?A.message:String(A)),ue(null)),ee("error")}).finally(()=>{sr.current=!1}))},[t,n,Ze,pe]);if(Yn(()=>{cr();let A=lh(t,{recursive:!0},(H,De)=>{if(!De)return;let ge=De.replace(/\\/g,"/");ph.some(Yt=>ge.startsWith(Yt))||(Ze(`File change detected: ${De}`),xt.current!==null&&clearTimeout(xt.current),xt.current=setTimeout(cr,150))});return A.on("error",H=>{Ze(`File watcher error \u2014 rebuilds have stopped: ${H.message}`)}),()=>{A.close(),xt.current!==null&&clearTimeout(xt.current)}},[t,cr,Ze]),Yn(()=>{let A=lc();Ao(hc(A,"index.html")).then(H=>{if(!H){b("Viewer not built. Run 'pnpm build:viewer' first."),y("error");return}let De=dc(A,Gt,Bo,h,v,n,pe,nl,p,t,u),ge=dh(De),Yt=new uh({server:ge});return Yt.on("connection",Qe=>{for(let cl of Jt.current)Qe.readyState===1&&Qe.send(cl);Jt.current=[],Gt("Viewer connected for live reload"),Ne.current.add(Qe),or(Ne.current.size),Qe.on("close",()=>{Ne.current.delete(Qe),or(Ne.current.size)})}),ge.listen(e,"127.0.0.1",()=>{y("running"),Gt(`Server started on 127.0.0.1:${String(e)}`)}),ge.on("error",Qe=>{b(Qe.message),y("error")}),()=>{Yt.close(),ge.close()}})},[e,Gt,Bo,pe,n,t,u]),l==="editing")return j(Gn,{...C!==void 0&&{initialMode:C},showProfileManager:C==="global",onComplete:sl,onCancel:()=>{w("main")}});let lr=de!==null?Math.round((Date.now()-de.getTime())/1e3):null,al=lr===null?"":lr<5?" (just now)":` (${String(lr)}s ago)`,Fo=he?.filter(A=>A.severity==="error").length??0;return X(ne,{flexDirection:"column",paddingY:1,paddingX:2,children:[j(J,{marginBottom:1}),X(ne,{flexDirection:"column",children:[X(ne,{gap:2,marginBottom:0,children:[j(F,{bold:!0,dimColor:!0,children:"App Build"}),z==="pending"&&j(F,{dimColor:!0,children:"waiting\u2026"}),z==="building"&&X(ne,{gap:1,children:[j(xe,{}),j(F,{children:"Building plugin package\u2026"})]}),z==="done"&&X(ne,{gap:1,children:[j(F,{color:"green",children:"\u2713 Built"}),de!==null&&X(F,{dimColor:!0,children:["at ",de.toLocaleTimeString(),al]}),Xe!==null&&X(F,{dimColor:!0,children:["\xB7 bundle: ",Rt(Xe)]})]}),z==="error"&&(he!==null?X(F,{color:"red",children:["\u2717 ",Fo," validation ",Fo===1?"error":"errors"]}):X(F,{color:"red",children:["\u2717 ",ae??"unknown error"]}))]}),he!==null&&j(Rn,{issues:he}),j(ne,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:m.slice(-8).map((A,H)=>j(F,{dimColor:!0,wrap:"truncate",children:A},H))})]}),X(ne,{marginTop:1,flexDirection:"column",children:[X(ne,{gap:2,children:[j(F,{bold:!0,dimColor:!0,children:"Web Server"}),x==="starting"&&j(F,{dimColor:!0,children:"starting\u2026"}),x==="running"&&X(ne,{gap:2,children:[j(F,{color:"green",children:"\u2713 Running"}),X(F,{dimColor:!0,children:["\u25CF ",rr," viewer",rr!==1?"s":""]})]}),x==="error"&&X(F,{color:"red",children:["\u2717 ",P??"Server error"]})]}),j(ne,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:f.slice(-8).map((A,H)=>j(F,{dimColor:!0,wrap:"truncate",children:A},H))})]}),X(ne,{marginTop:1,flexDirection:"column",children:[X(ne,{gap:2,children:[j(F,{bold:!0,dimColor:!0,children:"Network Proxy"}),j(F,{color:"green",children:"\u2713 Active"}),j(F,{dimColor:!0,children:u?`\u25CF ${String(Ro)} key${Ro!==1?"s":""} in the network cache \xB7 ${String(rl)} hit \xB7 ${String(ir)} miss`:`\u25CF network cache disabled \xB7 ${String(ir)} request${ir!==1?"s":""}`})]}),j(ne,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:_.length===0?j(F,{dimColor:!0,children:" No requests yet."}):_.slice(-8).map((A,H)=>j(F,{dimColor:!0,wrap:"truncate",children:A},H))})]}),a&&X(ne,{marginTop:1,flexDirection:"column",children:[X(ne,{gap:2,children:[j(F,{bold:!0,dimColor:!0,children:"CDP Debug"}),X(F,{dimColor:!0,children:["\u25CF ",S.length," event(s)"]})]}),j(ne,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:S.length===0?j(F,{dimColor:!0,children:" No CDP events yet."}):S.slice(-8).map((A,H)=>j(F,{dimColor:!0,wrap:"truncate",children:A},H))})]}),X(ne,{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"}),X(F,{dimColor:!0,children:["] ",rr===0?"open viewer":"relaunch viewer"]})]})]})};async function yc(e){return new Promise(t=>{let n=null,r=i=>{n?.(),t(i)},{unmount:o}=wc(bc(Gn,{...e!==void 0&&{initialMode:e},onComplete:r}),{exitOnCtrlC:!1});n=o})}function vc(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 an API-key credentials JSON file (dev still uses API keys; sign-in support is planned)").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),r=process.cwd(),o=`${r}/.kizenapp`;ve(r);let i=null,s,a,{lastPath:c}=await we(o);if(t.credentials)i=await Fe(t.credentials);else{let l=await we(o);if(l.credentialMode==="local")s="local";else if(l.credentialMode==="global"){if(s="global",a=l.activeCredentialProfile,a?(i=await Pe(a),i||(i=await oe(),a=void 0)):i=await oe(),!i){let w=await yc("global");i=w.credentials,a=w.profileName}}else{let w=await yc();i=w.credentials,s=w.mode,a=w.profileName;let C=w.profileName;await Ve(o,{credentialMode:w.mode,...C!==void 0&&{activeCredentialProfile:C}})}}let g=t.verbose===!0,u=g||t.debug===!0,h=t.viewer!==!1,v=t.cache!==!1,{waitUntilExit:p}=wc(bc(gc,{port:n,pluginDir:r,outputDir:o,credentials:i,...s!==void 0&&{credentialMode:s},...a!==void 0&&{activeCredentialProfile:a},...c!==void 0&&{lastPath:c},debug:u,verbose:g,autoViewer:h,cacheEnabled:v}),{exitOnCtrlC:!1});await p()})}import{createElement as Ph}from"react";import{render as Eh}from"ink";import{useCallback as Zn,useEffect as Sc,useState as Qn}from"react";import{Box as ke,Text as U,useApp as wh,useInput as vh}from"ink";import{encrypt as fh,serializeEnvelope as mh}from"@kizenapps/packager";function hh(e){let t=e;return t.code==="ECONNREFUSED"||t.cause?.code==="ECONNREFUSED"}function xc(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 kc(e,t,n){try{return await fetch(`${e}${t}`,n)}catch(r){throw new Error(hh(r)?`Plugin-wizard is not running at ${e}`:`Failed to reach plugin-wizard: ${r.message}${Zt()==="unavailable"?` ${Xt}`:""}`)}}async function Cc(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 gh(e,t,n){let r=Mt(e.stage),o=await kc(r,"/get-public-key",{method:"POST",headers:xc(t),body:JSON.stringify({api_name:n})}),i=await Cc(o);if(!o.ok||typeof i.public_key!="string"){let s=typeof i.error=="string"?i.error:`HTTP ${String(o.status)}`;throw new Error(`Failed to fetch public key: ${s}`)}return i.public_key}function yh(e,t){let n=fh(t,e),r=mh(n);if(typeof r.value!="string")throw new Error("Unexpected serialized envelope shape from @kizenapps/packager");return r.value}async function bh(e,t,n,r){let o=Mt(e.stage),i=await kc(o,"/encrypt",{method:"POST",headers:xc(t),body:JSON.stringify({api_name:n,value:r})}),s=await Cc(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 Xn(e,t,n,r,o){if(e.isRemote)return o?.("encrypting"),bh(e,t,n,r);o?.("fetching-key");let i=await gh(e,t,n);return o?.("encrypting"),yh(i,r)}import{Fragment as er,jsx as L,jsxs as re}from"react/jsx-runtime";var $o=({text:e})=>L(U,{dimColor:!0,children:e}),Pc=({ctx:e,stageDefaulted:t,credentialsPath:n,initialApiName:r,defaultApiName:o,initialValue:i,onDone:s})=>{let a=wh(),[c,g]=Qn({type:"loading"}),[u,h]=Qn(null),[v,p]=Qn(r??""),[l,w]=Qn(i??""),C=Zn(d=>{process.exitCode=1,g({type:"error",message:d instanceof Error?d.message:String(d)})},[]),E=Zn(async(d,m,k)=>{try{let S=await Xn(e,d,m,k,R=>{g(R==="fetching-key"?{type:"fetching-key"}:{type:"encrypting"})}),T=JSON.stringify({encrypted:!0,value:S},null,2);s?.(S);let _=await mn(T);g({type:"done",envelope:T,copied:_})}catch(S){C(S)}},[e,C,s]),x=Zn((d,m,k)=>{if(m.trim()===""){g({type:"api-name-entry",buffer:o??""});return}if(k===""){g({type:"value-entry",buffer:""});return}E(d,m.trim(),k)},[o,E]),y=Zn(async d=>{try{g({type:"loading"});let m=d.isDefault?await oe():await Pe(d.name);if(m===null)throw new Error(`Could not load credential profile: ${d.name}`);h(m),x(m,v,l)}catch(m){C(m)}},[v,l,x,C]);Sc(()=>{(async()=>{try{if(n!==void 0){let k;try{k=await Fe(n)}catch(S){throw new Error(`Could not load credentials from ${n}: ${S instanceof Error?S.message:String(S)}`)}h(k),x(k,v,l);return}let d=await je();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 k=m.isDefault?await oe():await Pe(m.name);if(k===null)throw new Error(`Could not load credential profile: ${m.name}`);h(k),x(k,v,l);return}g({type:"profile-select",profiles:d,cursor:0})}catch(d){C(d)}})()},[]),Sc(()=>{(c.type==="done"||c.type==="error")&&a.exit()},[c,a]),vh((d,m)=>{if(m.ctrl&&d==="c"){process.exitCode=130,a.exit();return}if(c.type==="profile-select"){let{profiles:k,cursor:S}=c;if(m.upArrow)g({...c,cursor:(S-1+k.length)%k.length});else if(m.downArrow)g({...c,cursor:(S+1)%k.length});else if(m.return){let T=k[S];T!==void 0&&y(T)}return}if(c.type==="api-name-entry"){let{buffer:k}=c;if(m.backspace||m.delete)g({type:"api-name-entry",buffer:k.slice(0,-1)});else if(m.return){let S=k.trim();if(S===""){g({type:"api-name-entry",buffer:k,error:"api_name cannot be empty"});return}p(S),u?x(u,S,l):C(new Error("Internal error: credentials were not loaded"))}else d&&!m.ctrl&&!m.meta&&g({type:"api-name-entry",buffer:k+d});return}if(c.type==="value-entry"){let{buffer:k}=c;if(m.backspace||m.delete)g({type:"value-entry",buffer:k.slice(0,-1)});else if(m.return){if(k===""){g({type:"value-entry",buffer:k,error:"secret cannot be empty"});return}w(k),u?x(u,v,k):C(new Error("Internal error: credentials were not loaded"))}else d&&!m.ctrl&&!m.meta&&g({type:"value-entry",buffer:k+d});return}});let P=e.isRemote?"remote Kizen API":"on-machine",b=t===!0?`${e.stage} (default)`:e.stage,f=d=>re(ke,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[L(J,{}),re(U,{dimColor:!0,children:["Mode: ",P," Stage: ",b]}),d]});if(c.type==="loading")return f(re(ke,{gap:1,children:[L(xe,{}),L(U,{dimColor:!0,children:"Loading credentials\u2026"})]}));if(c.type==="profile-select"){let{profiles:d,cursor:m}=c;return f(re(er,{children:[L(U,{bold:!0,children:"Credential profile"}),L(ke,{flexDirection:"column",children:d.map((k,S)=>{let T=m===S;return re(ke,{gap:2,children:[L(U,{...T&&{color:"cyan"},children:T?"\u276F":" "}),L(U,{bold:T,...T&&{color:"cyan"},children:k.isDefault?"Default":k.name}),L(U,{dimColor:!0,children:k.path})]},k.name)})}),L($o,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]}))}return c.type==="api-name-entry"?f(re(er,{children:[L(U,{bold:!0,children:"Plugin api_name"}),c.error!==void 0&&re(U,{color:"red",children:["Error: ",c.error]}),re(ke,{gap:1,children:[L(U,{color:"cyan",children:">"}),L(U,{children:c.buffer}),L(U,{color:"cyan",children:"\u2588"})]}),L($o,{text:"Type the api_name \xB7 Enter to confirm \xB7 Ctrl+C to quit"})]})):c.type==="value-entry"?f(re(er,{children:[L(U,{bold:!0,children:"Secret value"}),c.error!==void 0&&re(U,{color:"red",children:["Error: ",c.error]}),re(ke,{gap:1,children:[L(U,{color:"cyan",children:">"}),L(U,{children:"\u2022".repeat(c.buffer.length)}),L(U,{color:"cyan",children:"\u2588"})]}),L($o,{text:"Input hidden \xB7 Enter to encrypt \xB7 Ctrl+C to quit"})]})):c.type==="fetching-key"?f(re(ke,{gap:1,children:[L(xe,{}),re(U,{children:["Fetching ",e.stage," public key for ",L(U,{bold:!0,children:v}),"\u2026"]})]})):c.type==="encrypting"?f(re(ke,{gap:1,children:[L(xe,{}),L(U,{children:"Encrypting\u2026"})]})):c.type==="error"?f(re(ke,{gap:1,children:[L(U,{color:"red",children:"\u2717"}),L(U,{color:"red",children:c.message})]})):f(re(er,{children:[re(ke,{gap:1,children:[L(U,{color:"green",children:"\u2713"}),L(U,{bold:!0,children:"Encrypted secret ready"})]}),c.copied?L(U,{color:"green",children:"\u2713 Copied to clipboard \u2014 paste it into the secret value in your kizen.json."}):L(U,{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):"}),L(U,{children:c.envelope})]}))};import{readFile as xh,writeFile as kh}from"fs/promises";import{join as Ch}from"path";function Ec(e){return{encrypted:!0,value:e}}function _c(e){return JSON.stringify(Ec(e))}async function No(e,t){await kh(e,`${JSON.stringify(Ec(t),null,2)}
1185
- `,"utf-8")}var Sh="prod";function Tc(e){return e==="dev"||e==="prod"}function Ac(e){return`Error: --stage must be "dev" or "prod" (got: "${e}")`}function Ic(e){return{stage:e==="dev"||e==="prod"?e:Sh,wasDefaulted:e===void 0}}function $c(e){return`No --stage given; defaulting to ${e} encryption keys (pass --stage dev to override)
1186
- `}async function Nc(e=process.cwd()){try{let t=await xh(Ch(e,"kizen.json"),"utf-8"),n=JSON.parse(t),r=Array.isArray(n)?n[0]:n,o=typeof r.api_name=="string"&&r.api_name!==""?r.api_name:void 0;return{...o!==void 0&&{apiName:o}}}catch{}return{}}function Dc(e){return e.replace(/[\r\n]+$/,"")}async function Rc(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}async function Oc(e,t,n,r,o){let i=t.credentials!==void 0?await o.loadCredentialsFromFile(t.credentials):await o.loadGlobalCredentials();if(i===null)throw new Error("No credentials found. Pass --credentials or create ~/.kizenappbuilder/credentials.json.");let s=t.apiName??n.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.");r&&o.writeStderr($c(e.stage));let a=t.value;if(a===void 0){if(o.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`).');o.writeStderr(`Reading secret from stdin (pass --value to skip)\u2026
1187
- `),a=Dc(await o.readStdin())}if(a==="")throw new Error("A secret value is required. Pass --value or pipe it via stdin.");let c=await o.encryptSecret(e,i,s.trim(),a);if(o.writeStdout(`${_c(c)}
1196
+ `.trim(),tg=3e4,cr=nn(process.cwd(),".kizenapp","venv"),ng=Zh.map(Nc),Dc=rs(_c);if(Dc.length===0)throw new Error("python-requirements.txt bundled no packages \u2014 check the build output");var tn=null;function Ic(e,t,n){return new Promise((r,o)=>{let i=$c(e,t,{stdio:["ignore","pipe","pipe"]}),s=(c,g)=>{let m=[],h="";return c.on("data",y=>{h+=y.toString("utf-8");let f=h.indexOf(`
1197
+ `);for(;f>=0;){let u=h.slice(0,f).replace(/\r$/,"");h=h.slice(f+1),m.push(u),n?.(u,g),f=h.indexOf(`
1198
+ `)}}),c.on("end",()=>{if(h.length>0){let y=h.replace(/\r$/,"");m.push(y),n?.(y,g)}}),m},a=s(i.stderr,"stderr");s(i.stdout,"stdout"),i.on("error",o),i.on("close",c=>{if(c===0)r();else{let g=a.slice(-10).join(`
1199
+ `).trim(),m=g.length>0?`: ${g}`:"";o(new Error(`${e} exited with code ${String(c)}${m}`))}})})}var Zo=null;function rg(e,t){if(tn)return t&&Zo?.add(t),tn;let n=new Set;t&&n.add(t),Zo=n;let r=i=>{for(let s of n)s(i)},o=nn(cr,"bin","python");return tn=(async()=>{try{let i=!1;try{await Yh(o);let s=await Sn(o);i=s!==null&&Hr(s,Ut)}catch{i=!1}if(!i){await Qo(cr,{recursive:!0,force:!0}).catch(()=>{});let s=await is(e);await Ic(s,["-m","venv",cr])}return r({kind:"start"}),await Ic(o,["-m","pip","install","--disable-pip-version-check",...Dc],(s,a)=>{r({kind:"log",line:s,stream:a})}),r({kind:"complete"}),o}catch(i){let s=i instanceof Error?i.message:String(i);throw r({kind:"error",message:s}),tn=null,await Qo(cr,{recursive:!0,force:!0}).catch(()=>{}),i}finally{Zo=null}})(),tn}function og(e){let t="__KIZEN_RESULT_START__",n="__KIZEN_RESULT_END__",r=e.indexOf(t),o=e.indexOf(n);if(r===-1||o===-1)return{userStdout:e,result:null};let i=e.slice(0,r).trimEnd(),s=e.slice(r+t.length,o).trim();try{let a=JSON.parse(s);return{userStdout:i,result:a}}catch{return{userStdout:e,result:null}}}function ig(e){return{success:!1,outputValues:{},logs:[],stdout:"",stderr:"",error:e,exitCode:1,durationMs:0}}async function Rc(e){let t=e.timeout??tg;if(!Qh(e.scriptRuntime))return ig(`Unsupported runtime "${e.scriptRuntime}". Supported runtimes: ${ng.join(", ")}. Update the step's config.json "runtime" field (e.g. "python 3.13").`);let r=await rg(Nc(e.scriptRuntime),e.onInstallProgress),o=Date.now(),i;try{i=await Jh(nn(Xh(),"kizen-step-"));let s=nn(i,"wrapper.py"),a=nn(i,"script.py");await Promise.all([Tc(s,eg,"utf-8"),Tc(a,e.script,"utf-8")]);let c={...process.env,__KIZEN_INPUTS__:JSON.stringify(e.inputs),__KIZEN_SECRETS__:JSON.stringify(e.secrets),__KIZEN_SCRIPT_PATH__:a},{exitCode:g,stdout:m,stderr:h}=await new Promise(k=>{let _=[],P=[],C=!1,T=$c(r,[s],{env:c,cwd:i,stdio:["ignore","pipe","pipe"]}),v=setTimeout(()=>{T.kill("SIGKILL")},t);T.stdout.on("data",d=>{_.push(d)}),T.stderr.on("data",d=>{P.push(d)});let l=d=>{C||(C=!0,clearTimeout(v),k({exitCode:d??1,stdout:Buffer.concat(_).toString("utf-8"),stderr:Buffer.concat(P).toString("utf-8")}))};T.on("close",l),T.on("error",d=>{C||(C=!0,clearTimeout(v),k({exitCode:1,stdout:"",stderr:d.message}))})}),y=Date.now()-o,{userStdout:f,result:u}=og(m);if(u){let k={success:u.success,outputValues:u.outputValues,logs:u.logs,stdout:f,stderr:h,exitCode:g,durationMs:y};return u.error!==null&&(k.error=u.error),u.httpRequests&&(k.httpRequests=u.httpRequests),k}let w={success:!1,outputValues:{},logs:[],stdout:f,stderr:h,exitCode:g,durationMs:y};return g!==0&&(w.error=`Process exited with code ${String(g)}`),w}finally{i&&Qo(i,{recursive:!0,force:!0})}}var Oc=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 Lc,CRYPTO_VERSION as zc,DEFAULT_AUTOMATION_RUNTIME as mg,deserializeEnvelope as hg,encrypt as gg,scriptRuntimeToApiName as yg,serializeEnvelope as bg}from"@kizenapps/packager";function ei(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 wg=2*1024*1024,vg=new Set([".DS_Store",".gitignore"]);function xg(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 Kc=["kizen.com","kizen.dev"];function kg(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:Kc.some(r=>n===r||n.endsWith("."+r))}function Cg(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let n=t.hostname.toLowerCase();return Kc.some(r=>n===r||n.endsWith("."+r))}function Sg(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 Mc(e,t){if(t.includes("\0"))return null;let n=t.replace(/^\/+/,""),r=pg(e,n);if(r!==e&&!r.startsWith(e+ti))return null;try{let o=await dg(r);return o!==e&&!o.startsWith(e+ti)?null:o}catch{return null}}function Uc(e,t){let n=t===e?"":t.slice(e.length+1);return n===""?!1:n.split(ti).some(o=>Rn.has(o))}function Vc(){let e=fg(import.meta.url);return rn(ug(e),"viewer")}function Hc(e,t,n){if(e.includes("/external-integrations/proxy")&&t["content-type"]?.includes("application/json"))try{let r=JSON.parse(n.toString("utf8"));return typeof r.status_code=="number"?r.status_code:void 0}catch{return}}async function ni(e){try{return await ag(e),!0}catch{return!1}}function Wc(e,t,n,r,o,i,s,a,c,g,m){let h=Ec({onChange:a,enabled:m}),y=sg(g);return(f,u)=>{(async()=>{let w=f.url??"/";try{if(!xg(f.headers.host)){u.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Forbidden"}));return}if((f.method==="POST"||f.method==="PATCH"||f.method==="DELETE")&&!Sg(f.headers.origin)){u.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Forbidden"}));return}if(t(`Received request: ${w}`),w==="/api/credentials"){u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({credentials:r.current??null,activeProfile:o.current??null}));return}if(w==="/api/credential-profiles"&&f.method==="GET"){let l=await We();u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({profiles:l,active:o.current}));return}if(w==="/api/credentials/switch"&&f.method==="POST"){let l=[];for await(let x of f)l.push(x);let p=JSON.parse(Buffer.concat(l).toString("utf-8")||"{}").profile,b=p===void 0||p===""?await se():await Ie(p);if(b!==null){r.current=b,o.current=p??void 0;let x=o.current,S=await Se(i);await Je(i,{...S,credentialMode:"global",...x!==void 0&&{activeCredentialProfile:x}}),s({type:"credentials-updated",credentials:b,activeProfile:o.current??null})}u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({ok:b!==null}));return}if(w==="/api/bundle"){let l=rn(process.cwd(),".kizenapp","bundle.json");try{let d=await lg(l,"utf-8");u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end(d)}catch{u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end("{}")}return}if(w==="/api/last-path"&&f.method==="POST"){let l=[];for await(let p of f)l.push(p);let d=JSON.parse(Buffer.concat(l).toString("utf-8")||"{}");if(typeof d.path=="string"){c.current=d.path;let p=await Se(i);await Je(i,{...p,lastPath:d.path})}u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end('{"ok":true}');return}if(w==="/api/encryption-target"&&f.method==="GET"){let d=(await Se(i)).encryptionTarget==="dev"?"dev":"prod";u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({target:d}));return}if(w==="/api/encryption-target"&&f.method==="POST"){let l=[];for await(let x of f)l.push(x);let d=JSON.parse(Buffer.concat(l).toString("utf-8")||"{}"),p=d!==null&&typeof d=="object"?d:{};if(p.target!=="dev"&&p.target!=="prod"){u.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"target must be one of: 'dev', 'prod'"}));return}let b=await Se(i);await Je(i,{...b,encryptionTarget:p.target}),u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end('{"ok":true}');return}if(w==="/api/execute-step"&&f.method==="POST"){let l=[];for await(let x of f)l.push(x);let d=JSON.parse(Buffer.concat(l).toString("utf-8")||"{}");if(typeof d.script!="string"){u.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Missing required field: script"}));return}let p={script:d.script,scriptRuntime:d.scriptRuntime??yg(mg),inputs:Ac(d.inputs),secrets:d.secrets??{},onInstallProgress:x=>{x.kind==="start"?s({type:"venv-install-start"}):x.kind==="log"?s({type:"venv-install-log",line:x.line,stream:x.stream}):x.kind==="complete"?s({type:"venv-install-complete"}):s({type:"venv-install-error",message:x.message})}};typeof d.timeout=="number"&&d.timeout>0&&(p.timeout=Math.min(d.timeout,300*1e3));let b=await Rc(p);u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify(b));return}if(w==="/api/proxy-cache/clear"){h.clear(),n({kind:"info",message:"Proxy cache cleared"}),u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end('{"ok":true}');return}if(w==="/api/local/encrypt"&&f.method==="POST"){let l=[];for await(let p of f)l.push(p);let d=JSON.parse(Buffer.concat(l).toString("utf-8")||"{}");if(typeof d.publicKeyPem!="string"||typeof d.value!="string"){u.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Missing required fields: publicKeyPem, value"}));return}try{let p=gg(d.value,d.publicKeyPem),b=bg(p);u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify(b))}catch(p){u.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:p.message}))}return}if(w==="/api/local/validate"&&f.method==="POST"){let l=[];for await(let E of f)l.push(E);let d=JSON.parse(Buffer.concat(l).toString("utf-8")||"{}");if(typeof d.value!="string"){u.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Missing required field: value"}));return}let p,b;try{p=hg(d.value)}catch(E){b=E.message}if(b!==void 0||p===void 0){u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({valid:!1,checks:[],error:b}));return}let x=E=>Buffer.from(E,"base64").length,S=[{label:"Version",expected:String(zc),actual:String(p.v),pass:p.v===zc},{label:"Algorithm",expected:Lc,actual:p.alg,pass:p.alg===Lc},{label:"Wrapped key",expected:"384 bytes (RSA-3072)",actual:`${String(x(p.k))} bytes`,pass:x(p.k)===384},{label:"IV",expected:"12 bytes",actual:`${String(x(p.iv))} bytes`,pass:x(p.iv)===12},{label:"Auth tag",expected:"16 bytes",actual:`${String(x(p.tag))} bytes`,pass:x(p.tag)===16},{label:"Ciphertext",expected:"\u2265 1 byte",actual:`${String(x(p.ct))} bytes`,pass:x(p.ct)>=1}];u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({valid:S.every(E=>E.pass),checks:S}));return}if(w.startsWith("/api/wizard")){let l=f.headers["x-encryption-target"],p=(Array.isArray(l)?l[0]:l)==="dev"?"dev":"prod",b=en(p);if(!kg(b)){u.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:`Encryption API host is not allowed: ${b}`}));return}let x=w.slice(11)||"/",S=`${b}${x}`,E=f.method??"GET",$=[];for await(let tt of f)$.push(tt);let{host:M,"x-encryption-target":ee,...ce}=f.headers,be=$.length>0?Buffer.concat($):void 0,we=be&&be.length>0?be:void 0,me;try{me=await fetch(S,{method:E,headers:ce,...we!==void 0&&{body:we}})}catch(tt){let wr=tt.code==="ECONNREFUSED"?`plugin-wizard is not running at ${b}`:`Failed to reach plugin-wizard: ${tt.message}`;u.writeHead(503,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:wr}));return}let pe=ar(Object.fromEntries(me.headers)),Pt=await me.arrayBuffer();u.writeHead(me.status,pe),u.end(Buffer.from(Pt));return}if(w.startsWith("/api/proxy")){let l=f.headers["x-proxy-target"];if(typeof l!="string"){u.writeHead(400),u.end("Missing x-proxy-target header");return}if(!Cg(l)){u.writeHead(400),u.end("Invalid proxy target");return}let d=w.slice(10)||"/",p=`${l}${d}`,b=f.method??"GET",x=[];for await(let me of f)x.push(me);let{host:S,"x-proxy-target":E,...$}=f.headers;if(b==="GET"){let me=`GET::${p}`,{response:pe,fromCache:Pt}=await h.get(me,()=>fetch(p,{method:"GET",headers:$}));n({kind:"request",method:"GET",status:pe.status,upstreamStatus:Hc(d,pe.headers,pe.body),fromCache:Pt,url:d}),u.writeHead(pe.status,pe.headers),u.end(pe.body);return}let M=x.length>0?Buffer.concat(x):void 0,ee=M&&M.length>0?M:void 0,ce=await fetch(p,{method:b,headers:$,...ee!==void 0&&{body:ee}}),be=ar(Object.fromEntries(ce.headers)),we=await Jo(ce,Go);n({kind:"request",method:b,status:ce.status,upstreamStatus:Hc(d,be,we),fromCache:!1,url:d}),u.writeHead(ce.status,be),u.end(we);return}if(w.startsWith("/api/source/tree")&&f.method==="GET"){let d=new URL(w,"http://localhost").searchParams.get("path")??"",p=await Mc(y,d);if(p===null){u.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Invalid path"}));return}if(Uc(y,p)){u.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Path is excluded"}));return}try{let b=await cg(p,{withFileTypes:!0}),x=await Promise.all(b.filter(E=>E.isDirectory()?!Rn.has(E.name):E.isFile()?!vg.has(E.name):!1).map(async E=>{let $=E.isDirectory()?"dir":"file",M={name:E.name,kind:$};if($==="file")try{let ee=await Fc(rn(p,E.name));M.size=ee.size}catch{}return M}));x.sort((E,$)=>E.kind!==$.kind?E.kind==="dir"?-1:1:E.name.localeCompare($.name));let S=p===y?"":p.slice(y.length+1);u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({path:S,entries:x}))}catch(b){let x=b instanceof Error?b.message:String(b);t(`source/tree failed (${d}): ${x}`),u.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Not found"}))}return}if(w.startsWith("/api/source/file")&&f.method==="GET"){let d=new URL(w,"http://localhost").searchParams.get("path")??"";if(d===""){u.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Missing path"}));return}let p=await Mc(y,d);if(p===null){u.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Invalid path"}));return}if(Uc(y,p)){u.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Path is excluded"}));return}try{let b=await Fc(p);if(!b.isFile()){u.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Not a file"}));return}if(b.size>wg){u.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"File too large",size:b.size}));return}let x=jc(p).toLowerCase(),S=Yo[x],E=Oc.has(x),$=S??(E?"text/plain; charset=utf-8":"application/octet-stream");u.writeHead(200,{"Content-Type":$,"Content-Length":String(b.size)}),Bc(p).pipe(u)}catch(b){let x=b instanceof Error?b.message:String(b);t(`source/file failed (${d}): ${x}`),u.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Not found"}))}return}let P=rn(e,w==="/"?"/index.html":w),C=await ni(P)?P:rn(e,"index.html"),T=jc(C),v=Yo[T]??"application/octet-stream";u.writeHead(200,{"Content-Type":v}),Bc(C).pipe(u)}catch(k){if(w.startsWith("/api/proxy")){let _=w.slice(10)||"/",P=f.method??"GET";k instanceof Qt?n({kind:"info",message:`${P} ${_} \u2192 502 (response exceeded ${String(k.limit)} bytes)`}):n({kind:"request",method:P,status:502,fromCache:!1,url:_})}else n({kind:"info",message:`Error handling ${w}: ${k instanceof Error?k.message:String(k)}`});u.headersSent||(u.writeHead(502),u.end("Bad Gateway"))}})()}}import{launch as Pg}from"chrome-launcher";import{createRequire as Eg}from"module";import{mkdirSync as _g}from"fs";import{readFile as Ag}from"fs/promises";import{dirname as Tg,join as Ig}from"path";import{fileURLToPath as $g}from"url";var qc=Eg(import.meta.url)("chrome-remote-interface"),Ng=new Set(["content-security-policy","content-security-policy-report-only","x-frame-options"]),Jc=["kizen.dev","kizen.com"];function Gc(e){try{let{hostname:t}=new URL(e);return Jc.some(n=>t===n||t.endsWith("."+n))}catch{return!1}}async function Dg(e){try{let t=Ig(Tg($g(import.meta.url)),"viewer","icon.png"),n=await Ag(t);await e.Browser.setDockTile({image:n.toString("base64")})}catch{}}async function Yc(e){_g(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,n=await Pg({startingUrl:t,chromeFlags:[`--app=${t}`,"--no-first-run","--no-default-browser-check","--disable-extensions","--disable-features=DeviceBoundSessions"],userDataDir:e.userDataDir,handleSIGINT:!1,logLevel:"silent"}),r=n.port,o=null,i=null,s=null,a=null,c=0,g=!1,m=C=>{e.debugLog?.(C)},h=C=>{e.verbose&&e.debugLog?.(C)},y=()=>{i!==null&&(clearInterval(i),i=null)},f=C=>C==="chrome://new-tab-page/"||C==="chrome://newtab/",u=async C=>{y(),s=null,await Dg(C),await C.Fetch.enable({patterns:Jc.flatMap(v=>[{urlPattern:`*://${v}/*`,requestStage:"Response"},{urlPattern:`*://*.${v}/*`,requestStage:"Response"}])}),C.on("Fetch.requestPaused",v=>{(async()=>{let l=v,{requestId:d,request:p,responseHeaders:b,responseStatusCode:x}=l,S=p.url;h(`Fetch ${String(x??"?")} ${S}`);let E=[],$=!1;for(let M of b??[])if(!Ng.has(M.name.toLowerCase()))if(M.name.toLowerCase()==="set-cookie"&&Gc(S)){let ee=M.value.split(`
1200
+ `).map(ce=>/SameSite=/i.test(ce)?ce.replace(/SameSite=\w+/i,"SameSite=None"):ce+"; SameSite=None; Secure").join(`
1201
+ `);E.push({name:M.name,value:ee}),$=!0}else E.push(M);$&&h(` rewrote Set-Cookie SameSite on ${S}`);try{let{body:M,base64Encoded:ee}=await C.Fetch.getResponseBody({requestId:d});await C.Fetch.fulfillRequest({requestId:d,responseCode:x??200,responseHeaders:E,body:M,...ee&&{base64Encoded:!0}})}catch(M){h(` fulfillRequest failed (${M.message}), falling through`);try{await C.Fetch.continueRequest({requestId:d})}catch(ee){h(` continueRequest also failed (${ee.message})`)}}})()}),i=setInterval(()=>{(async()=>{try{let{cookies:v}=await C.Network.getAllCookies(),l=0;for(let d of v){if(!Gc(`https://${d.domain??""}`)||d.sameSite==="None")continue;let p=d.domain??"",b=p.startsWith(".")?p.slice(1):p;await C.Network.setCookie({url:`https://${b}`,name:d.name,value:d.value,domain:p,path:d.path??"/",secure:!0,...d.httpOnly!==void 0&&{httpOnly:d.httpOnly},...d.expirationDate!==void 0&&{expires:d.expirationDate},sameSite:"None"}),l++}l>0&&h(`cookie-patch cycle: updated ${String(l)} cookie(s) to SameSite=None`)}catch(v){h(`cookie-patch cycle failed: ${v.message}`)}})()},2e3),await C.Target.setDiscoverTargets({discover:!0});let T=v=>{if(v.type==="page"){if(f(v.url)){m(`closed stray new-tab-page target ${v.targetId}`),s!==null&&C.Target.activateTarget({targetId:s}).catch(()=>{}),C.Target.closeTarget({targetId:v.targetId}).catch(()=>{});return}s===null&&(s=v.targetId,m(`captured main target ${v.targetId} (${v.url})`))}};C.on("Target.targetCreated",v=>{let{targetInfo:l}=v;h(`target +${l.type} ${l.targetId} ${l.url}`),T(l)}),C.on("Target.targetInfoChanged",v=>{let{targetInfo:l}=v;h(`target ~${l.type} ${l.targetId} ${l.url}`),T(l)}),C.on("disconnect",()=>{g||o!==C||(m("CDP disconnected"),o=null,y(),w())})},w=()=>{if(g||a!==null)return;let C=Math.min(1e3*2**c,1e4),T=c+1;c++,m(`CDP reconnect scheduled in ${String(C)}ms (attempt #${String(T)})`),a=setTimeout(()=>{a=null,(async()=>{let v;try{v=await qc({port:r})}catch{m(`CDP reconnect attempt #${String(T)} failed`),w();return}if(g){try{await v.close()}catch{}return}o=v;try{await u(v),m(`CDP reconnected after ${String(T)} attempt(s)`),c=0}catch{o===v&&(o=null);try{await v.close()}catch{}m(`CDP reconnect attempt #${String(T)} failed during setup`),w()}})()},C)},k=30,_=300;for(let C=0;C<k;C++){await new Promise(T=>setTimeout(T,_)),m(`CDP connect attempt ${String(C+1)}/${String(k)}`);try{let T=await qc({port:r});o=T,e.path&&T.send("Page.navigate",{url:`${t}${e.path}`});try{await u(T),m("CDP connected")}catch{o===T&&(o=null);try{await T.close()}catch{}m("CDP setup failed after connect")}break}catch{if(C===k-1){let T=`CDP unavailable after ${String(k)} attempts \u2014 viewer running without interception (CSP/cookie rewrites disabled)`;return m(T),e.onWarn?.(T),{kill:()=>{n.kill()}}}}}return o?{kill:()=>{if(m("CDP kill requested \u2014 tearing down"),g=!0,a!==null&&(clearTimeout(a),a=null),y(),o!==null){try{o.close()}catch{}o=null}n.kill()}}:{kill:()=>{n.kill()}}}import{useCallback as Rg,useState as Og}from"react";function lr(e){let[t,n]=Og([]),r=Rg(o=>{n(i=>[...i,`${new Date().toLocaleTimeString()}: ${o}`].slice(-e))},[e]);return[t,r]}import{useCallback as dr,useEffect as ri,useState as ur}from"react";import{Box as Q,Text as z,useInput as Bg}from"ink";import{jsx as D,jsxs as te}from"react/jsx-runtime";var Qe=["apiKey","userId","businessId"],Fg={apiKey:"API Key",userId:"User ID",businessId:"Business ID"},on=({text:e})=>D(z,{dimColor:!0,children:e}),pr=({initialMode:e,showProfileManager:t,onComplete:n,onCancel:r})=>{let[o,i]=ur(e==="global"&&!t?{type:"loading"}:e==="global"&&t?{type:"profile-loading"}:{type:"mode-select",cursor:0}),[s,a]=ur(""),[c,g]=ur(null),[m,h]=ur(void 0),y=dr(v=>{if(v==="local"){n({mode:"local",credentials:null});return}i({type:"profile-loading"})},[n]),f=dr(async v=>{if(v===null){i({type:"profile-loading"});let p=await We();i({type:"name-entry",nameBuffer:"",existingProfiles:p});return}h(v.isDefault?void 0:v.name),i({type:"loading"});let l=v.isDefault?await se():await Ie(v.name),d=l?Math.max(0,W.indexOf(l.environment)):0;i({type:"creds-entry",field:0,values:l??{},envCursor:d})},[]),u=dr(async(v,l)=>{let d=W[l]??"go",p={...Nt(v),environment:d};i({type:"saving"});try{await Ti(m??Ke,p),n({mode:"global",credentials:p,...m!==void 0&&{profileName:m}})}catch(b){g(b instanceof Error?b.message:String(b)),i({type:"creds-entry",field:0,values:v,envCursor:l})}},[n,m]);Bg((v,l)=>{if(l.ctrl&&v==="c"&&process.exit(0),l.escape){if((o.type==="creds-entry"||o.type==="name-entry")&&e==="global"&&t){i({type:"profile-loading"}),w();return}r?.();return}if(o.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 d=o.cursor===0?"global":"local";y(d)}return}if(o.type==="profile-select"){let{profiles:d,cursor:p}=o,b=d.length,x=d.length+1;if(l.upArrow)i({...o,cursor:(p-1+x)%x});else if(l.downArrow)i({...o,cursor:(p+1)%x});else if(l.return)if(p===b)i({type:"name-entry",nameBuffer:"",existingProfiles:d});else{let S=d[p]??d[0];S&&f(S)}return}if(o.type==="name-entry"){let{nameBuffer:d,existingProfiles:p}=o;if(l.backspace||l.delete)i({type:"name-entry",nameBuffer:d.slice(0,-1),existingProfiles:p});else if(l.return){let b=d.trim();if(!b){i({...o,nameError:"Name cannot be empty"});return}if(b===Ke){i({...o,nameError:`"${Ke}" is reserved`});return}if(p.some(x=>x.name===b)){i({...o,nameError:`Profile "${b}" already exists`});return}h(b),i({type:"creds-entry",field:0,values:{},envCursor:0}),a("")}else v&&!l.ctrl&&!l.meta&&i({type:"name-entry",nameBuffer:d+v,existingProfiles:p});return}if(o.type==="creds-entry"){let{field:d,values:p,envCursor:b}=o;if(d===Qe.length){l.leftArrow?i({...o,envCursor:(b-1+W.length)%W.length}):l.rightArrow?i({...o,envCursor:(b+1)%W.length}):l.upArrow?(i({...o,field:d-1}),a(p[Qe[d-1]]??"")):l.return&&u(p,b);return}let S=Qe[d];if(!S)return;if(l.backspace||l.delete)a(E=>E.slice(0,-1));else if(l.upArrow&&d>0){let E={...p,[S]:s},$=d-1;i({...o,field:$,values:E}),a(E[Qe[$]]??"")}else if(l.return||l.tab||l.downArrow){let E={...p,[S]:s},$=d+1;i({...o,field:$,values:E}),$<Qe.length?a(E[Qe[$]]??""):a("")}else v&&!l.ctrl&&!l.meta&&a(E=>E+v)}});let w=dr(async()=>{let v=await We();i({type:"profile-select",profiles:v,cursor:0})},[]);if(ri(()=>{o.type==="profile-loading"&&w()},[o.type,w]),ri(()=>{e==="global"&&!t&&(async()=>{let v=await se(),l=v?Math.max(0,W.indexOf(v.environment)):0;i({type:"creds-entry",field:0,values:v??{},envCursor:l})})()},[]),ri(()=>{o.type==="creds-entry"&&o.field===0&&a(o.values.apiKey??"")},[o.type]),o.type==="loading"||o.type==="saving"||o.type==="profile-loading"){let v=o.type==="saving"?"Saving credentials\u2026":o.type==="profile-loading"?"Loading profiles\u2026":"Loading credentials\u2026";return D(Q,{paddingY:1,paddingX:2,children:D(z,{dimColor:!0,children:v})})}if(o.type==="done")return null;if(o.type==="mode-select")return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[D(G,{}),te(Q,{flexDirection:"column",gap:0,children:[D(z,{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,d)=>{let p=o.cursor===d;return te(Q,{gap:2,children:[D(z,{...p&&{color:"cyan"},children:p?"\u276F":" "}),D(z,{bold:p,...p&&{color:"cyan"},children:l.label}),D(z,{dimColor:!0,children:l.desc})]},l.mode)})]}),D(on,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]});if(o.type==="profile-select"){let{profiles:v,cursor:l}=o,d=v.length;return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[D(G,{}),te(Q,{flexDirection:"column",gap:0,children:[D(z,{bold:!0,children:"Credential profiles"}),v.map((p,b)=>{let x=l===b;return te(Q,{gap:2,children:[D(z,{...x&&{color:"cyan"},children:x?"\u276F":" "}),D(z,{bold:x,...x&&{color:"cyan"},children:p.isDefault?"Default":p.name}),D(z,{dimColor:!0,children:p.path})]},p.name)}),te(Q,{gap:2,children:[D(z,{...l===d&&{color:"cyan"},children:l===d?"\u276F":" "}),D(z,{bold:l===d,...l===d&&{color:"cyan"},children:"+ Add new profile"})]})]}),D(on,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(o.type==="name-entry"){let{nameBuffer:v,nameError:l}=o;return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[D(G,{}),D(Q,{flexDirection:"column",gap:0,children:D(z,{bold:!0,children:"New credential profile"})}),l&&te(z,{color:"red",children:["Error: ",l]}),te(Q,{gap:2,children:[D(Q,{width:12,children:D(z,{bold:!0,color:"cyan",children:"Profile name"})}),D(z,{color:"cyan",children:">"}),D(z,{children:v}),D(z,{color:"cyan",children:"\u2588"})]}),D(on,{text:"Type a name \xB7 Enter to confirm \xB7 Esc to go back"})]})}let{field:k,values:_,envCursor:P}=o,C=k===Qe.length,T=m??Ke;return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[D(G,{}),te(Q,{flexDirection:"column",gap:0,children:[D(z,{bold:!0,children:m!==void 0?`Profile: ${m}`:"Global credentials"}),te(z,{dimColor:!0,children:["Saved to:"," ",m!==void 0?`~/.kizenappbuilder/${m}.json`:He]})]}),c&&te(z,{color:"red",children:["Error: ",c]}),te(Q,{flexDirection:"column",gap:0,children:[Qe.map((v,l)=>{let d=k===l,p=d?s:_[v]??"";return te(Q,{gap:2,children:[D(Q,{width:12,children:D(z,{bold:d,...d&&{color:"cyan"},children:Fg[v]})}),D(z,{...d&&{color:"cyan"},children:">"}),D(z,{children:p}),d&&D(z,{color:"cyan",children:"\u2588"})]},v)}),te(Q,{gap:2,children:[D(Q,{width:12,children:D(z,{bold:C,...C&&{color:"cyan"},children:"Environment"})}),D(z,{...C&&{color:"cyan"},children:">"}),D(Q,{gap:1,children:W.map((v,l)=>{let d=l===P;return C?D(z,{bold:d,...d&&{color:"cyan"},children:d?`[${v}]`:v},v):D(z,{dimColor:!d,bold:d,children:v},v)})})]})]}),C?D(on,{text:"\u2190\u2192 to select \xB7 \u2191\u2193 to move \xB7 Enter to save \xB7 Esc to cancel"}):D(on,{text:"\u2191\u2193 to move \xB7 Backspace to delete \xB7 Esc to cancel"}),te(z,{dimColor:!0,children:["Profile: ",T]})]})};import{jsx as j,jsxs as X}from"react/jsx-runtime";var Kg=[".kizenapp",".git"],Zc=({port:e,pluginDir:t,outputDir:n,credentials:r,credentialMode:o,activeCredentialProfile:i,lastPath:s,debug:a=!1,verbose:c=!1,autoViewer:g=!0,cacheEnabled:m=!0})=>{let h=Be(r),y=Be(i),f=Be(s),[u,w]=ue("main"),[k,_]=ue(o),[P,C]=ue("starting"),[T,v]=ue(null),[l,d]=lr(50),[p,b]=lr(50),[x,S]=lr(50),[E,$]=ue([]),[M,ee]=ue("pending"),[ce,be]=ue(null),[we,me]=ue(null),[pe,Pt]=ue(null),[tt,wr]=ue(null),[vr,xr]=ue(0),[ai,jl]=ue(0),[Ll,zl]=ue(0),[kr,Ml]=ue(0),Cr=Be(!1),ci=Be(!1),an=Be(null),Et=Be(null),Fe=Be(new Set),cn=Be([]),he=St(A=>{let H=JSON.stringify(A);if(Fe.current.size===0){cn.current=[...cn.current,H].slice(-50);return}let je=!1;for(let ve of Fe.current)if(ve.readyState===1)try{ve.send(H)}catch{Fe.current.delete(ve),je=!0}je&&xr(Fe.current.size)},[]),ln=d,Sr=St(()=>{an.current?.kill(),an.current=null,Yc({port:e,userDataDir:Xc(n,".chrome"),broadcast:he,onWarn:A=>{d(`\u26A0 ${A}`)},...f.current!==void 0&&{path:f.current},...a&&{debugLog:S},...c&&{verbose:!0}}).then(A=>{an.current=A})},[e,n,he,a,c,S,d]);fr(()=>{let A=()=>{an.current?.kill()};return process.on("exit",A),()=>{process.off("exit",A)}},[]),Lg((A,H)=>{(A==="q"||H.ctrl&&A==="c")&&process.exit(0),A==="c"&&w("editing"),A==="v"&&Sr()},{isActive:u==="main"}),fr(()=>{P!=="running"||ci.current||!g||(ci.current=!0,Sr())},[P,g,Sr]);let Ul=St(A=>{h.current=A.credentials,y.current=A.profileName,w("main"),_(A.mode);let H=A.profileName;Je(n,{credentialMode:A.mode,...H!==void 0&&{activeCredentialProfile:H}}),he({type:"credentials-updated",credentials:A.credentials})},[n,he]),li=St(A=>{$(H=>[...H,`${new Date().toLocaleTimeString()}: ${ei(A)}`].slice(-50)),A.kind==="request"&&(A.fromCache?zl(H=>H+1):Ml(H=>H+1)),he({type:"proxy-log",entry:A})},[he]),nt=St(A=>{b(A),he({type:"log",message:A})},[b,he]),Pr=St(()=>{Cr.current||(Cr.current=!0,ee("building"),be(null),me(null),nt("Build started"),Bn(t,n).then(({bundleSize:A})=>{nt(`Build finished \u2014 bundle: ${Gt(A)}`),ee("done"),Pt(new Date),wr(A),nt("Notifying viewers to reload"),he({type:"rebuild"})}).catch(A=>{A instanceof zg?(me(A.issues),be(null)):(be(A instanceof Error?A.message:String(A)),me(null)),ee("error")}).finally(()=>{Cr.current=!1}))},[t,n,nt,he]);if(fr(()=>{Pr();let A=Mg(t,{recursive:!0},(H,je)=>{if(!je)return;let ve=je.replace(/\\/g,"/");Kg.some(dn=>ve.startsWith(dn))||(nt(`File change detected: ${je}`),Et.current!==null&&clearTimeout(Et.current),Et.current=setTimeout(Pr,150))});return A.on("error",H=>{nt(`File watcher error \u2014 rebuilds have stopped: ${H.message}`)}),()=>{A.close(),Et.current!==null&&clearTimeout(Et.current)}},[t,Pr,nt]),fr(()=>{let A=Vc();ni(Xc(A,"index.html")).then(H=>{if(!H){v("Viewer not built. Run 'pnpm build:viewer' first."),C("error");return}let je=Wc(A,ln,li,h,y,n,he,jl,f,t,m),ve=Ug(je),dn=new Hg({server:ve});return dn.on("connection",rt=>{for(let Kl of cn.current)rt.readyState===1&&rt.send(Kl);cn.current=[],ln("Viewer connected for live reload"),Fe.current.add(rt),xr(Fe.current.size),rt.on("close",()=>{Fe.current.delete(rt),xr(Fe.current.size)})}),ve.listen(e,"127.0.0.1",()=>{C("running"),ln(`Server started on 127.0.0.1:${String(e)}`)}),ve.on("error",rt=>{v(rt.message),C("error")}),()=>{dn.close(),ve.close()}})},[e,ln,li,he,n,t,m]),u==="editing")return j(pr,{...k!==void 0&&{initialMode:k},showProfileManager:k==="global",onComplete:Ul,onCancel:()=>{w("main")}});let Er=pe!==null?Math.round((Date.now()-pe.getTime())/1e3):null,Hl=Er===null?"":Er<5?" (just now)":` (${String(Er)}s ago)`,di=we?.filter(A=>A.severity==="error").length??0;return X(ne,{flexDirection:"column",paddingY:1,paddingX:2,children:[j(G,{marginBottom:1}),X(ne,{flexDirection:"column",children:[X(ne,{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"&&X(ne,{gap:1,children:[j(Ee,{}),j(F,{children:"Building plugin package\u2026"})]}),M==="done"&&X(ne,{gap:1,children:[j(F,{color:"green",children:"\u2713 Built"}),pe!==null&&X(F,{dimColor:!0,children:["at ",pe.toLocaleTimeString(),Hl]}),tt!==null&&X(F,{dimColor:!0,children:["\xB7 bundle: ",Gt(tt)]})]}),M==="error"&&(we!==null?X(F,{color:"red",children:["\u2717 ",di," validation ",di===1?"error":"errors"]}):X(F,{color:"red",children:["\u2717 ",ce??"unknown error"]}))]}),we!==null&&j(Xn,{issues:we}),j(ne,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:p.slice(-8).map((A,H)=>j(F,{dimColor:!0,wrap:"truncate",children:A},H))})]}),X(ne,{marginTop:1,flexDirection:"column",children:[X(ne,{gap:2,children:[j(F,{bold:!0,dimColor:!0,children:"Web Server"}),P==="starting"&&j(F,{dimColor:!0,children:"starting\u2026"}),P==="running"&&X(ne,{gap:2,children:[j(F,{color:"green",children:"\u2713 Running"}),X(F,{dimColor:!0,children:["\u25CF ",vr," viewer",vr!==1?"s":""]})]}),P==="error"&&X(F,{color:"red",children:["\u2717 ",T??"Server error"]})]}),j(ne,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:l.slice(-8).map((A,H)=>j(F,{dimColor:!0,wrap:"truncate",children:A},H))})]}),X(ne,{marginTop:1,flexDirection:"column",children:[X(ne,{gap:2,children:[j(F,{bold:!0,dimColor:!0,children:"Network Proxy"}),j(F,{color:"green",children:"\u2713 Active"}),j(F,{dimColor:!0,children:m?`\u25CF ${String(ai)} key${ai!==1?"s":""} in the network cache \xB7 ${String(Ll)} hit \xB7 ${String(kr)} miss`:`\u25CF network cache disabled \xB7 ${String(kr)} request${kr!==1?"s":""}`})]}),j(ne,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:E.length===0?j(F,{dimColor:!0,children:" No requests yet."}):E.slice(-8).map((A,H)=>j(F,{dimColor:!0,wrap:"truncate",children:A},H))})]}),a&&X(ne,{marginTop:1,flexDirection:"column",children:[X(ne,{gap:2,children:[j(F,{bold:!0,dimColor:!0,children:"CDP Debug"}),X(F,{dimColor:!0,children:["\u25CF ",x.length," event(s)"]})]}),j(ne,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:x.length===0?j(F,{dimColor:!0,children:" No CDP events yet."}):x.slice(-8).map((A,H)=>j(F,{dimColor:!0,wrap:"truncate",children:A},H))})]}),X(ne,{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"}),X(F,{dimColor:!0,children:["] ",vr===0?"open viewer":"relaunch viewer"]})]})]})};async function Qc(e){return new Promise(t=>{let n=null,r=i=>{n?.(),t(i)},{unmount:o}=tl(el(pr,{...e!==void 0&&{initialMode:e},onComplete:r}),{exitOnCtrlC:!1});n=o})}function nl(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 an API-key credentials JSON file (dev still uses API keys; sign-in support is planned)").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),r=process.cwd(),o=`${r}/.kizenapp`;Pe(r);let i=null,s,a,{lastPath:c}=await Se(o);if(t.credentials)i=await Ve(t.credentials);else{let u=await Se(o);if(u.credentialMode==="local")s="local";else if(u.credentialMode==="global"){if(s="global",a=u.activeCredentialProfile,a?(i=await Ie(a),i||(i=await se(),a=void 0)):i=await se(),!i){let w=await Qc("global");i=w.credentials,a=w.profileName}}else{let w=await Qc();i=w.credentials,s=w.mode,a=w.profileName;let k=w.profileName;await Je(o,{credentialMode:w.mode,...k!==void 0&&{activeCredentialProfile:k}})}}let g=t.verbose===!0,m=g||t.debug===!0,h=t.viewer!==!1,y=t.cache!==!1,{waitUntilExit:f}=tl(el(Zc,{port:n,pluginDir:r,outputDir:o,credentials:i,...s!==void 0&&{credentialMode:s},...a!==void 0&&{activeCredentialProfile:a},...c!==void 0&&{lastPath:c},debug:m,verbose:g,autoViewer:h,cacheEnabled:y}),{exitOnCtrlC:!1});await f()})}import{createElement as ry}from"react";import{render as oy}from"ink";import{useCallback as hr,useEffect as sl,useState as gr}from"react";import{Box as _e,Text as U,useApp as Xg,useInput as Zg}from"ink";import{encrypt as Vg,serializeEnvelope as Wg}from"@kizenapps/packager";function qg(e){let t=e;return t.code==="ECONNREFUSED"||t.cause?.code==="ECONNREFUSED"}function rl(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 ol(e,t,n){try{return await fetch(`${e}${t}`,n)}catch(r){throw new Error(qg(r)?`Plugin-wizard is not running at ${e}`:`Failed to reach plugin-wizard: ${r.message}${pn()==="unavailable"?` ${un}`:""}`)}}async function il(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 Gg(e,t,n){let r=en(e.stage),o=await ol(r,"/get-public-key",{method:"POST",headers:rl(t),body:JSON.stringify({api_name:n})}),i=await il(o);if(!o.ok||typeof i.public_key!="string"){let s=typeof i.error=="string"?i.error:`HTTP ${String(o.status)}`;throw new Error(`Failed to fetch public key: ${s}`)}return i.public_key}function Jg(e,t){let n=Vg(t,e),r=Wg(n);if(typeof r.value!="string")throw new Error("Unexpected serialized envelope shape from @kizenapps/packager");return r.value}async function Yg(e,t,n,r){let o=en(e.stage),i=await ol(o,"/encrypt",{method:"POST",headers:rl(t),body:JSON.stringify({api_name:n,value:r})}),s=await il(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 mr(e,t,n,r,o){if(e.isRemote)return o?.("encrypting"),Yg(e,t,n,r);o?.("fetching-key");let i=await Gg(e,t,n);return o?.("encrypting"),Jg(i,r)}import{Fragment as yr,jsx as L,jsxs as re}from"react/jsx-runtime";var oi=({text:e})=>L(U,{dimColor:!0,children:e}),al=({ctx:e,stageDefaulted:t,credentialsPath:n,initialApiName:r,defaultApiName:o,initialValue:i,onDone:s})=>{let a=Xg(),[c,g]=gr({type:"loading"}),[m,h]=gr(null),[y,f]=gr(r??""),[u,w]=gr(i??""),k=hr(d=>{process.exitCode=1,g({type:"error",message:d instanceof Error?d.message:String(d)})},[]),_=hr(async(d,p,b)=>{try{let x=await mr(e,d,p,b,$=>{g($==="fetching-key"?{type:"fetching-key"}:{type:"encrypting"})}),S=JSON.stringify({encrypted:!0,value:x},null,2);s?.(x);let E=await In(S);g({type:"done",envelope:S,copied:E})}catch(x){k(x)}},[e,k,s]),P=hr((d,p,b)=>{if(p.trim()===""){g({type:"api-name-entry",buffer:o??""});return}if(b===""){g({type:"value-entry",buffer:""});return}_(d,p.trim(),b)},[o,_]),C=hr(async d=>{try{g({type:"loading"});let p=d.isDefault?await se():await Ie(d.name);if(p===null)throw new Error(`Could not load credential profile: ${d.name}`);h(p),P(p,y,u)}catch(p){k(p)}},[y,u,P,k]);sl(()=>{(async()=>{try{if(n!==void 0){let b;try{b=await Ve(n)}catch(x){throw new Error(`Could not load credentials from ${n}: ${x instanceof Error?x.message:String(x)}`)}h(b),P(b,y,u);return}let d=await We();if(d.length===0)throw new Error("No credential profiles found. Create ~/.kizenappbuilder/credentials.json first.");let[p]=d;if(d.length===1&&p!==void 0){let b=p.isDefault?await se():await Ie(p.name);if(b===null)throw new Error(`Could not load credential profile: ${p.name}`);h(b),P(b,y,u);return}g({type:"profile-select",profiles:d,cursor:0})}catch(d){k(d)}})()},[]),sl(()=>{(c.type==="done"||c.type==="error")&&a.exit()},[c,a]),Zg((d,p)=>{if(p.ctrl&&d==="c"){process.exitCode=130,a.exit();return}if(c.type==="profile-select"){let{profiles:b,cursor:x}=c;if(p.upArrow)g({...c,cursor:(x-1+b.length)%b.length});else if(p.downArrow)g({...c,cursor:(x+1)%b.length});else if(p.return){let S=b[x];S!==void 0&&C(S)}return}if(c.type==="api-name-entry"){let{buffer:b}=c;if(p.backspace||p.delete)g({type:"api-name-entry",buffer:b.slice(0,-1)});else if(p.return){let x=b.trim();if(x===""){g({type:"api-name-entry",buffer:b,error:"api_name cannot be empty"});return}f(x),m?P(m,x,u):k(new Error("Internal error: credentials were not loaded"))}else d&&!p.ctrl&&!p.meta&&g({type:"api-name-entry",buffer:b+d});return}if(c.type==="value-entry"){let{buffer:b}=c;if(p.backspace||p.delete)g({type:"value-entry",buffer:b.slice(0,-1)});else if(p.return){if(b===""){g({type:"value-entry",buffer:b,error:"secret cannot be empty"});return}w(b),m?P(m,y,b):k(new Error("Internal error: credentials were not loaded"))}else d&&!p.ctrl&&!p.meta&&g({type:"value-entry",buffer:b+d});return}});let T=e.isRemote?"remote Kizen API":"on-machine",v=t===!0?`${e.stage} (default)`:e.stage,l=d=>re(_e,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[L(G,{}),re(U,{dimColor:!0,children:["Mode: ",T," Stage: ",v]}),d]});if(c.type==="loading")return l(re(_e,{gap:1,children:[L(Ee,{}),L(U,{dimColor:!0,children:"Loading credentials\u2026"})]}));if(c.type==="profile-select"){let{profiles:d,cursor:p}=c;return l(re(yr,{children:[L(U,{bold:!0,children:"Credential profile"}),L(_e,{flexDirection:"column",children:d.map((b,x)=>{let S=p===x;return re(_e,{gap:2,children:[L(U,{...S&&{color:"cyan"},children:S?"\u276F":" "}),L(U,{bold:S,...S&&{color:"cyan"},children:b.isDefault?"Default":b.name}),L(U,{dimColor:!0,children:b.path})]},b.name)})}),L(oi,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]}))}return c.type==="api-name-entry"?l(re(yr,{children:[L(U,{bold:!0,children:"Plugin api_name"}),c.error!==void 0&&re(U,{color:"red",children:["Error: ",c.error]}),re(_e,{gap:1,children:[L(U,{color:"cyan",children:">"}),L(U,{children:c.buffer}),L(U,{color:"cyan",children:"\u2588"})]}),L(oi,{text:"Type the api_name \xB7 Enter to confirm \xB7 Ctrl+C to quit"})]})):c.type==="value-entry"?l(re(yr,{children:[L(U,{bold:!0,children:"Secret value"}),c.error!==void 0&&re(U,{color:"red",children:["Error: ",c.error]}),re(_e,{gap:1,children:[L(U,{color:"cyan",children:">"}),L(U,{children:"\u2022".repeat(c.buffer.length)}),L(U,{color:"cyan",children:"\u2588"})]}),L(oi,{text:"Input hidden \xB7 Enter to encrypt \xB7 Ctrl+C to quit"})]})):c.type==="fetching-key"?l(re(_e,{gap:1,children:[L(Ee,{}),re(U,{children:["Fetching ",e.stage," public key for ",L(U,{bold:!0,children:y}),"\u2026"]})]})):c.type==="encrypting"?l(re(_e,{gap:1,children:[L(Ee,{}),L(U,{children:"Encrypting\u2026"})]})):c.type==="error"?l(re(_e,{gap:1,children:[L(U,{color:"red",children:"\u2717"}),L(U,{color:"red",children:c.message})]})):l(re(yr,{children:[re(_e,{gap:1,children:[L(U,{color:"green",children:"\u2713"}),L(U,{bold:!0,children:"Encrypted secret ready"})]}),c.copied?L(U,{color:"green",children:"\u2713 Copied to clipboard \u2014 paste it into the secret value in your kizen.json."}):L(U,{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):"}),L(U,{children:c.envelope})]}))};import{readFile as Qg,writeFile as ey}from"fs/promises";import{join as ty}from"path";function cl(e){return{encrypted:!0,value:e}}function ll(e){return JSON.stringify(cl(e))}async function ii(e,t){await ey(e,`${JSON.stringify(cl(t),null,2)}
1202
+ `,"utf-8")}var ny="prod";function dl(e){return e==="dev"||e==="prod"}function ul(e){return`Error: --stage must be "dev" or "prod" (got: "${e}")`}function pl(e){return{stage:e==="dev"||e==="prod"?e:ny,wasDefaulted:e===void 0}}function fl(e){return`No --stage given; defaulting to ${e} encryption keys (pass --stage dev to override)
1203
+ `}async function ml(e=process.cwd()){try{let t=await Qg(ty(e,"kizen.json"),"utf-8"),n=JSON.parse(t),r=Array.isArray(n)?n[0]:n,o=typeof r.api_name=="string"&&r.api_name!==""?r.api_name:void 0;return{...o!==void 0&&{apiName:o}}}catch{}return{}}function hl(e){return e.replace(/[\r\n]+$/,"")}async function gl(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}async function yl(e,t,n,r,o){let i=t.credentials!==void 0?await o.loadCredentialsFromFile(t.credentials):await o.loadGlobalCredentials();if(i===null)throw new Error("No credentials found. Pass --credentials or create ~/.kizenappbuilder/credentials.json.");let s=t.apiName??n.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.");r&&o.writeStderr(fl(e.stage));let a=t.value;if(a===void 0){if(o.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`).');o.writeStderr(`Reading secret from stdin (pass --value to skip)\u2026
1204
+ `),a=hl(await o.readStdin())}if(a==="")throw new Error("A secret value is required. Pass --value or pipe it via stdin.");let c=await o.encryptSecret(e,i,s.trim(),a);if(o.writeStdout(`${ll(c)}
1188
1205
  `),t.out!==void 0)try{await o.writeEnvelopeFile(t.out,c),o.writeStderr(`Wrote encrypted envelope to ${t.out}
1189
1206
  `)}catch(g){o.writeStderr(`Error writing ${t.out}: ${g instanceof Error?g.message:String(g)}
1190
- `),o.setExitCode(1)}}function Bc(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 an API-key credentials JSON file (encrypt still uses API keys until plugin-wizard accepts sign-in sessions)").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&&!Tc(t.stage)&&(console.error(Ac(t.stage)),process.exit(1));let r=t.apiName===void 0?await Nc():{},{stage:o,wasDefaulted:i}=Ic(t.stage),s={isRemote:t.remote===!0,stage:o};if(!process.stdin.isTTY||!process.stdout.isTTY){try{await Oc(s,t,r,i,{loadCredentialsFromFile:Fe,loadGlobalCredentials:oe,encryptSecret:Xn,readStdin:Rc,stdinIsTTY:()=>process.stdin.isTTY,writeStdout:g=>{process.stdout.write(g)},writeStderr:g=>{process.stderr.write(g)},writeEnvelopeFile:No,setExitCode:g=>{process.exitCode=g}})}catch(g){console.error(`Error: ${g instanceof Error?g.message:String(g)}`),process.exit(1)}return}let a,{waitUntilExit:c}=Eh(Ph(Pc,{ctx:s,stageDefaulted:i,onDone:g=>{a=g},...t.credentials!==void 0&&{credentialsPath:t.credentials},...t.apiName!==void 0&&{initialApiName:t.apiName},...r.apiName!==void 0&&{defaultApiName:r.apiName},...t.value!==void 0&&{initialValue:t.value}}),{exitOnCtrlC:!1});if(await c(),a!==void 0&&t.out!==void 0)try{await No(t.out,a),process.stderr.write(`Wrote encrypted envelope to ${t.out}
1191
- `)}catch(g){console.error(`Error writing ${t.out}: ${g instanceof Error?g.message:String(g)}`),process.exitCode=1}})}var _h=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"]),Th=[..._h].sort(),Ah=new Set(["kizen-k","form-entity"]),Fc=[...Th,...[...Ah].sort()];function jc(e){e.command("icons").description("List all valid icon names accepted by toolbar items, pages, and adornments").action(()=>{for(let t of Fc)console.log(t)})}import{mkdir as Fh,writeFile as Gc,readFile as jh}from"fs/promises";import{join as tr}from"path";var Ih=new Set(["developer_business_id"]);function $h(e){return Array.isArray(e)?e.map(t=>{if(typeof t!="object"||t===null)return t;let n=t;if(typeof n.auth_credentials!="object"||n.auth_credentials===null)return n;let r=Object.fromEntries(Object.keys(n.auth_credentials).map(o=>[o,"*****"]));return{...n,auth_credentials:r}}):e}function Mc(e){let t={name:"",children:new Map,isFile:!1,filePath:""};for(let n of e){let r=n.path.split("/"),o=t;r.forEach((i,s)=>{o.children.has(i)||o.children.set(i,{name:i,children:new Map,isFile:s===r.length-1,filePath:r.slice(0,s+1).join("/")});let a=o.children.get(i);a&&(o=a)})}return t}function zc(e){return[...e.children.values()].sort((t,n)=>t.isFile!==n.isFile?t.isFile?1:-1:t.name.localeCompare(n.name))}function Do(e){return"file-"+e.replace(/[^a-zA-Z0-9]/g,"-")}function Ce(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Uc(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t).toLowerCase():""}var Nh={".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 Dh(e){return Nh[Uc(e)]??""}function Lc(e){let t=[...e.matchAll(/`+/g)].reduce((n,r)=>Math.max(n,r[0].length),0);return"`".repeat(Math.max(3,t+1))}function Hc(e,t=""){let n=zc(e);return n.map((r,o)=>{let i=o===n.length-1,s=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",a=i?" ":"\u2502 ";return r.isFile?`${t}${s}${r.name}`:`${t}${s}${r.name}/
1192
- ${Hc(r,t+a)}`}).join(`
1193
- `)}var Rh=/(^|\/)licen[cs]e(\.md|\.txt)?$/i;function Vc(e){return e.filter(t=>t.path!=="kizen.json"&&t.path!=="plugin-report.html"&&!Rh.test(t.path))}function Kc(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!Ih.has(t)).map(([t,n])=>[t,t==="services"?$h(n):n]))}var Oh={".png":"image/png",".svg":"image/svg+xml",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function Wc(e){return`<ul>${zc(e).map(r=>r.isFile?`<li class="tf"><a href="#${Do(r.filePath)}" data-id="${Do(r.filePath)}">${Ce(r.name)}</a></li>`:`<li class="td"><span class="dn">${Ce(r.name)}/</span>${Wc(r)}</li>`).join("")}</ul>`}function Bh(e){let t;return e.base64Image!==void 0?t=`<img src="data:${Oh[Uc(e.path)]??"image/png"};base64,${e.base64Image}" alt="${Ce(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>${Ce(e.content)}</code></pre>`,`<section id="${Do(e.path)}"><h2 class="fp">${Ce(e.path)}</h2><div class="fb">${t}</div></section>`}function qc(e,t){let n=Kc(e),r=typeof e.name=="string"?e.name:"Plugin",o=typeof e.version=="string"?e.version:"",i=typeof e.description=="string"?e.description:"",s=Vc(t),a=[];a.push(`# ${r}${o?` v${o}`:""}`),i&&a.push("",i);let c=JSON.stringify(n,null,2),g=Lc(c);a.push("","## Configuration (`kizen.json`)","",`${g}json`,c,g),a.push("","## File Tree","","```",Hc(Mc(s)),"```"),a.push("","## Files");for(let u of s)if(a.push("",`### \`${u.path}\``,""),u.base64Image!==void 0)a.push(`[Image file: ${u.path}]`);else if(u.binaryData!==void 0)a.push(`[Binary file: ${String(u.binaryData.length)} bytes]`);else{let h=Lc(u.content);a.push(`${h}${Dh(u.path)}`,u.content,h)}return a.join(`
1207
+ `),o.setExitCode(1)}}function bl(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 an API-key credentials JSON file (encrypt still uses API keys until plugin-wizard accepts sign-in sessions)").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&&!dl(t.stage)&&(console.error(ul(t.stage)),process.exit(1));let r=t.apiName===void 0?await ml():{},{stage:o,wasDefaulted:i}=pl(t.stage),s={isRemote:t.remote===!0,stage:o};if(!process.stdin.isTTY||!process.stdout.isTTY){try{await yl(s,t,r,i,{loadCredentialsFromFile:Ve,loadGlobalCredentials:se,encryptSecret:mr,readStdin:gl,stdinIsTTY:()=>process.stdin.isTTY,writeStdout:g=>{process.stdout.write(g)},writeStderr:g=>{process.stderr.write(g)},writeEnvelopeFile:ii,setExitCode:g=>{process.exitCode=g}})}catch(g){console.error(`Error: ${g instanceof Error?g.message:String(g)}`),process.exit(1)}return}let a,{waitUntilExit:c}=oy(ry(al,{ctx:s,stageDefaulted:i,onDone:g=>{a=g},...t.credentials!==void 0&&{credentialsPath:t.credentials},...t.apiName!==void 0&&{initialApiName:t.apiName},...r.apiName!==void 0&&{defaultApiName:r.apiName},...t.value!==void 0&&{initialValue:t.value}}),{exitOnCtrlC:!1});if(await c(),a!==void 0&&t.out!==void 0)try{await ii(t.out,a),process.stderr.write(`Wrote encrypted envelope to ${t.out}
1208
+ `)}catch(g){console.error(`Error writing ${t.out}: ${g instanceof Error?g.message:String(g)}`),process.exitCode=1}})}var iy=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","circle-check","arrow-progress","puzzle-piece","code"]),sy=[...iy].sort(),ay=new Set(["kizen-k","form-entity"]),wl=[...sy,...[...ay].sort()];function vl(e){e.command("icons").description("List all valid icon names accepted by toolbar items, pages, and adornments").action(()=>{for(let t of wl)console.log(t)})}import{mkdir as hy,writeFile as $l,readFile as gy}from"fs/promises";import{join as br}from"path";var cy=new Set(["developer_business_id"]);function ly(e){return Array.isArray(e)?e.map(t=>{if(typeof t!="object"||t===null)return t;let n=t;if(typeof n.auth_credentials!="object"||n.auth_credentials===null)return n;let r=Object.fromEntries(Object.keys(n.auth_credentials).map(o=>[o,"*****"]));return{...n,auth_credentials:r}}):e}function kl(e){let t={name:"",children:new Map,isFile:!1,filePath:""};for(let n of e){let r=n.path.split("/"),o=t;r.forEach((i,s)=>{o.children.has(i)||o.children.set(i,{name:i,children:new Map,isFile:s===r.length-1,filePath:r.slice(0,s+1).join("/")});let a=o.children.get(i);a&&(o=a)})}return t}function Cl(e){return[...e.children.values()].sort((t,n)=>t.isFile!==n.isFile?t.isFile?1:-1:t.name.localeCompare(n.name))}function si(e){return"file-"+e.replace(/[^a-zA-Z0-9]/g,"-")}function Ae(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Sl(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t).toLowerCase():""}var dy={".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 uy(e){return dy[Sl(e)]??""}function xl(e){let t=[...e.matchAll(/`+/g)].reduce((n,r)=>Math.max(n,r[0].length),0);return"`".repeat(Math.max(3,t+1))}function Pl(e,t=""){let n=Cl(e);return n.map((r,o)=>{let i=o===n.length-1,s=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",a=i?" ":"\u2502 ";return r.isFile?`${t}${s}${r.name}`:`${t}${s}${r.name}/
1209
+ ${Pl(r,t+a)}`}).join(`
1210
+ `)}var py=/(^|\/)licen[cs]e(\.md|\.txt)?$/i;function El(e){return e.filter(t=>t.path!=="kizen.json"&&t.path!=="plugin-report.html"&&!py.test(t.path))}function _l(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!cy.has(t)).map(([t,n])=>[t,t==="services"?ly(n):n]))}var fy={".png":"image/png",".svg":"image/svg+xml",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function Al(e){return`<ul>${Cl(e).map(r=>r.isFile?`<li class="tf"><a href="#${si(r.filePath)}" data-id="${si(r.filePath)}">${Ae(r.name)}</a></li>`:`<li class="td"><span class="dn">${Ae(r.name)}/</span>${Al(r)}</li>`).join("")}</ul>`}function my(e){let t;return e.base64Image!==void 0?t=`<img src="data:${fy[Sl(e.path)]??"image/png"};base64,${e.base64Image}" alt="${Ae(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>${Ae(e.content)}</code></pre>`,`<section id="${si(e.path)}"><h2 class="fp">${Ae(e.path)}</h2><div class="fb">${t}</div></section>`}function Tl(e,t){let n=_l(e),r=typeof e.name=="string"?e.name:"Plugin",o=typeof e.version=="string"?e.version:"",i=typeof e.description=="string"?e.description:"",s=El(t),a=[];a.push(`# ${r}${o?` v${o}`:""}`),i&&a.push("",i);let c=JSON.stringify(n,null,2),g=xl(c);a.push("","## Configuration (`kizen.json`)","",`${g}json`,c,g),a.push("","## File Tree","","```",Pl(kl(s)),"```"),a.push("","## Files");for(let m of s)if(a.push("",`### \`${m.path}\``,""),m.base64Image!==void 0)a.push(`[Image file: ${m.path}]`);else if(m.binaryData!==void 0)a.push(`[Binary file: ${String(m.binaryData.length)} bytes]`);else{let h=xl(m.content);a.push(`${h}${uy(m.path)}`,m.content,h)}return a.join(`
1194
1211
  `)+`
1195
- `}function Jc(e,t){let n=Kc(e),r=typeof e.name=="string"?e.name:"Plugin",o=typeof e.version=="string"?e.version:"",i=typeof e.description=="string"?e.description:"",s=Vc(t),a=Wc(Mc(s)),c=s.map(Bh).join(`
1212
+ `}function Il(e,t){let n=_l(e),r=typeof e.name=="string"?e.name:"Plugin",o=typeof e.version=="string"?e.version:"",i=typeof e.description=="string"?e.description:"",s=El(t),a=Al(kl(s)),c=s.map(my).join(`
1196
1213
  `);return`<!DOCTYPE html>
1197
1214
  <html lang="en">
1198
1215
  <head>
1199
1216
  <meta charset="UTF-8">
1200
1217
  <meta name="viewport" content="width=device-width,initial-scale=1">
1201
- <title>${Ce(r)} \u2014 Plugin Report</title>
1218
+ <title>${Ae(r)} \u2014 Plugin Report</title>
1202
1219
  <style>
1203
1220
  *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
1204
1221
  :root{
@@ -1235,8 +1252,8 @@ img{border:1px solid var(--bd);border-radius:4px}
1235
1252
  </head>
1236
1253
  <body>
1237
1254
  <header>
1238
- <h1>${Ce(r)}${o?` <span style="color:var(--mu);font-size:.8em">v${Ce(o)}</span>`:""}</h1>
1239
- ${i?`<p>${Ce(i)}</p>`:""}
1255
+ <h1>${Ae(r)}${o?` <span style="color:var(--mu);font-size:.8em">v${Ae(o)}</span>`:""}</h1>
1256
+ ${i?`<p>${Ae(i)}</p>`:""}
1240
1257
  </header>
1241
1258
  <div class="layout">
1242
1259
  <nav>
@@ -1244,7 +1261,7 @@ img{border:1px solid var(--bd);border-radius:4px}
1244
1261
  ${a}
1245
1262
  </nav>
1246
1263
  <main>
1247
- <section id="config"><h2 class="fp">kizen.json \u2014 Plugin Configuration</h2><div class="fb"><pre><code>${Ce(JSON.stringify(n,null,2))}</code></pre></div></section>
1264
+ <section id="config"><h2 class="fp">kizen.json \u2014 Plugin Configuration</h2><div class="fb"><pre><code>${Ae(JSON.stringify(n,null,2))}</code></pre></div></section>
1248
1265
  ${c}
1249
1266
  </main>
1250
1267
  </div>
@@ -1258,9 +1275,9 @@ ${c}
1258
1275
  })();
1259
1276
  </script>
1260
1277
  </body>
1261
- </html>`}var Yc=tr(Se,"examples");function Xc(e){e.command("report").description("Generate a self-contained HTML report of the plugin").option("-o, --output <path>",`output file path (default: ${Yc}/<api_name>.html)`).action(async t=>{let n=process.cwd(),r;try{let c=await jh(tr(n,"kizen.json"),"utf-8"),g=JSON.parse(c);r=Array.isArray(g)?g[0]:g}catch{console.error("Error: kizen.json not found. Run this command from a plugin directory."),process.exit(1)}let o=typeof r.api_name=="string"?r.api_name:"plugin",i=t.output??tr(Yc,`${o}.html`),s=i.replace(/\.html$/,".md"),a=await wn(n,{detectBinaryByContent:!0});await Fh(tr(i,".."),{recursive:!0}),await Promise.all([Gc(i,Jc(r,a),"utf-8"),Gc(s,qc(r,a),"utf-8")]),console.log(`Plugin report written to:
1278
+ </html>`}var Nl=br(ye,"examples");function Dl(e){e.command("report").description("Generate a self-contained HTML report of the plugin").option("-o, --output <path>",`output file path (default: ${Nl}/<api_name>.html)`).action(async t=>{let n=process.cwd(),r;try{let c=await gy(br(n,"kizen.json"),"utf-8"),g=JSON.parse(c);r=Array.isArray(g)?g[0]:g}catch{console.error("Error: kizen.json not found. Run this command from a plugin directory."),process.exit(1)}let o=typeof r.api_name=="string"?r.api_name:"plugin",i=t.output??br(Nl,`${o}.html`),s=i.replace(/\.html$/,".md"),a=await On(n,{detectBinaryByContent:!0});await hy(br(i,".."),{recursive:!0}),await Promise.all([$l(i,Il(r,a),"utf-8"),$l(s,Tl(r,a),"utf-8")]),console.log(`Plugin report written to:
1262
1279
  ${i}
1263
- ${s}`)})}function Zc(e,t){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)").option("--mcp","also register the Kizen MCP server in Claude Code (user scope)").option("--env <env>","environment of the MCP server to register (with --mcp; default: go)").option("--force","replace an existing Kizen MCP server registration (with --mcp)").action(async n=>{await Rs(process.cwd(),n,Ds(t))})}async function Qc(e,t={}){if(await qe(e)!=="has-manifest")throw new Error(`No kizen.json found in ${e}`);let n=t.dryRun===!0,r=await Pn(e,kn(),{dryRun:n});return n||ve(e),{files:r}}function el(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 n=process.cwd();if(await qe(n)!=="has-manifest"){console.error(`No kizen.json found in ${n} \u2014 run "appbuilder setup-copilot" from the root of a plugin repo.`),process.exitCode=1;return}let r=t.dryRun===!0;try{let o=await Qc(n,{dryRun:r});for(let i of o.files)console.log(En(i));if(r){console.log(`
1280
+ ${s}`)})}function Rl(e,t){e.command("setup-claude").description("Install or refresh the Claude Code files in a plugin, or with --mcp only register the Kizen MCP server").option("--dry-run","report what would change without writing files").option("--include-lib","also install the Kizen data helper library (<entry>/lib/kizenData.js)").option("--mcp","only register the Kizen MCP server in Claude Code (user scope); writes no files, so it works in any directory").option("--env <env>","environment of the MCP server to register (with --mcp; default: go)").option("--force","replace an existing Kizen MCP server registration (with --mcp)").action(async n=>{await wa(process.cwd(),n,ba(t))})}async function Ol(e,t={}){if(await Xe(e)!=="has-manifest")throw new Error(`No kizen.json found in ${e}`);let n=t.dryRun===!0,r=await Mn(e,jn(),{dryRun:n});return n||Pe(e),{files:r}}function Bl(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 n=process.cwd();if(await Xe(n)!=="has-manifest"){console.error(`No kizen.json found in ${n} \u2014 run "appbuilder setup-copilot" from the root of a plugin repo.`),process.exitCode=1;return}let r=t.dryRun===!0;try{let o=await Ol(n,{dryRun:r});for(let i of o.files)console.log(Un(i));if(r){console.log(`
1264
1281
  Dry run \u2014 no files and no .gitignore entries were written.`);return}console.log(`
1265
- 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(o){console.error(`Error: ${o instanceof Error?o.message:String(o)}`),process.exitCode=1}})}function Vh(){let e=zh(Mh(Uh(import.meta.url)),"..","package.json");return JSON.parse(Lh(e,"utf-8")).version}function tl(){let e=new Hh,t=Vh();return e.name("appbuilder").description("Kizen plugin app builder").version(t),La(e),Zc(e,t),el(e),ca(e),vc(e),Bc(e),Xc(e),jc(e),ra(e),Ti(e),e}jo({env:process.env,http:Kh});tl().parse();
1282
+ 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(o){console.error(`Error: ${o instanceof Error?o.message:String(o)}`),process.exitCode=1}})}function ky(){let e=wy(by(vy(import.meta.url)),"..","package.json");return JSON.parse(yy(e,"utf-8")).version}function Fl(){let e=new xy,t=ky();return e.name("appbuilder").description("Kizen plugin app builder").version(t),Sc(e),Rl(e,t),Bl(e),qa(e),nl(e),bl(e),Dl(e),vl(e),Ua(e),gs(e),fs(e),e}ui({env:process.env,http:Cy});Fl().parse();
1266
1283
  //# sourceMappingURL=index.js.map