@kizenapps/cli 1.17.0-d9d38e3 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import*as py from"http";var on="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.",Fl=["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy"],jl=e=>e!==void 0&&e!=="",je="not-configured";function ti({env:e,http:t}){return je==="applied"||(Fl.some(n=>jl(e[n]))?e.NODE_USE_ENV_PROXY==="1"?je="already-set":typeof t.setGlobalProxyFromEnv!="function"?je="unavailable":(t.setGlobalProxyFromEnv(e),je="applied"):je="not-configured"),je}var sn=()=>je;import{readFileSync as sy}from"fs";import{dirname as ay,join as cy}from"path";import{fileURLToPath as ly}from"url";import{Command as dy}from"commander";import{spawn as bu}from"child_process";import{Command as wu}from"commander";import{constants as Id}from"os";var xr={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"},Le=e=>new URL(xr[e]).origin,ni={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"},Ll=["go","fmo"];function kr(e){return Ll.includes(e)}import{posix as zl}from"path";var O=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ot=(e,t)=>e?.code===t,an=e=>e instanceof Error&&ot(e,"ENOENT"),it=async e=>{try{return await e}catch(t){if(ot(t,"ENOENT"))return;throw t}},ie=e=>typeof e=="string"&&e!==""?e:void 0,oe=e=>e instanceof Error?e.message:String(e),ze=e=>{let t=e;return t.cause?.code??t.code??t.cause?.message??t.message??String(e)},cn=e=>{let t=zl.normalize(e.trim().replaceAll("\\","/")).replace(/\/+$/,"");return t==="."?"":t};import{spawn as Wl}from"child_process";import{createHash as ql,randomBytes as Gl}from"crypto";import{createServer as Jl}from"http";import{platform as oi}from"process";var Ml=["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"],Ul=`<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)">${Ml.map(e=>`<path d="${e}"/>`).join("")}</g></svg>`,Hl={success:'<path d="M6 12.5l4 4 8-9"/>',error:'<path d="M8 8l8 8M16 8l-8 8"/>'},Kl=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">${Hl[e]}</svg>`,Vl=`
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,65 +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 ri(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>${Vl}</style></head><body><main>${Ul}<section class="card ${e}" data-status="${e}"><div class="status">${Kl(e)}</div><h1>${t}</h1><p>${n}</p></section></main></body></html>`}var ln="127.0.0.1",Cr="/callback",Yl=`http://${ln}${Cr}`,Xl="read write offline_access",Zl="Kizen App Builder CLI",Ql=300*1e3,Me="go",_t=2e4,W=class extends Error{constructor(n,r){super(r);this.code=n;this.name="OAuthError"}code},ve=e=>e===Me?"appbuilder login":`appbuilder login --env ${e}`,xe=(e,t,n={})=>new W("login_required",`${t} Run \`${ve(e)}\` to sign in${n.again===!0?" again":""}.`),ed=e=>{try{return e===""?void 0:JSON.parse(e)}catch{return}};async function Sr(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:ed(await i.text())}}catch(i){let s=o.aborted?`timed out after ${String(Math.round(r/1e3))}s`:ze(i);throw new W("network_error",`Couldn't reach ${new URL(t).origin}: ${s}`)}}function si(e,t,n){let r=O(n)?n:{},o=ie(r.error);if(o!==void 0){let i=ie(r.error_description);return new W(o,`${e} failed (${o}${i===void 0?"":`: ${i}`})`)}return new W("server_error",`${e} failed with HTTP ${String(t)}`)}async function ai(e,t,n=_t){let r=`${e}/.well-known/oauth-authorization-server`,o=a=>new W("server_error",`OAuth discovery at ${r} ${a}`),{res:i,body:s}=await Sr(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 ci(e,t,n=_t){let{res:r,body:o}=await Sr(t,e.registrationEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:Zl,redirect_uris:[Yl],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"})},n);if(!r.ok)throw si("App registration",r.status,o);let i=O(o)?ie(o.client_id):void 0;if(i===void 0)throw new W("server_error","App registration returned no client_id");return i}var td=e=>ql("sha256").update(e,"ascii").digest("base64url"),Pr=()=>Gl(32).toString("base64url");function li(){let e=Pr();return{verifier:e,challenge:td(e)}}function di(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",Xl),n.searchParams.set("state",t.state),n.searchParams.set("code_challenge",t.codeChallenge),n.searchParams.set("code_challenge_method","S256"),n.toString()}async function Er(e,t,n,r=_t){let{res:o,body:i}=await Sr(n,e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()},r);if(!o.ok)throw si("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 W("server_error","The token endpoint returned an unexpected response");return{accessToken:s,refreshToken:a,expiresIn:i.expires_in}}var ii=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store",Connection:"close"}).end(ri(n.kind,n.heading,n.text))},nd={kind:"success",heading:"You\u2019re signed in",text:"Sign-in complete. You can close this window."},rd={kind:"error",heading:"Sign-in failed",text:"Sign-in failed. Return to the terminal for details. You can close this window."},od={kind:"error",heading:"Outdated link",text:"This sign-in link is out of date. Use the latest link from the terminal."},id=e=>{try{return new URL(e??"/",`http://${ln}`)}catch{return}};async function ui(e){let t=e.timeoutMs??Ql,n,r=new Promise((m,b)=>{n={resolve:m,reject:b}});r.catch(()=>{});let o=!1,i,s=Jl((m,b)=>{let d=id(m.url);if(o||m.method!=="GET"||d?.pathname!==Cr){b.writeHead(404,{"Content-Type":"text/plain",Connection:"close"}).end("Not found");return}let l=d.searchParams;if(l.get("state")!==e.state){ii(b,400,od);return}let v=l.get("error"),C=l.get("error_description"),E=l.get("code")??"",x=v!==null?new W(v,`Kizen denied the sign-in (${v}${C?`: ${C}`:""})`):E?void 0:new W("invalid_callback","The sign-in callback had no authorization code");ii(b,x?400:200,x?rd:nd),c(x,E)}),a=()=>(i??=new Promise(m=>{clearTimeout(h),s.close(()=>{m()}),s.closeAllConnections()}),i);function c(m,b=""){o||(o=!0,m?n.reject(m):n.resolve({code:b}),a())}await new Promise((m,b)=>{s.once("error",b),s.listen(0,ln,()=>{s.off("error",b),m()})});let h=setTimeout(()=>{c(new W("timeout",`Timed out after ${String(Math.round(t/1e3))}s waiting for the browser sign-in`))},t),p=s.address();return{port:p.port,redirectUri:`http://${ln}:${String(p.port)}${Cr}`,result:r,close:a}}function pi(e){let[t,n]=oi==="darwin"?["open",[e]]:oi==="win32"?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{let r=Wl(t,n,{stdio:"ignore",detached:!0});r.on("error",()=>{}),r.unref()}catch{}}import{mkdir as fi,readFile as sd,readdir as ad,writeFile as mi}from"fs/promises";import{homedir as cd}from"os";import{dirname as ld,join as dn}from"path";var q=["go","fmo","staging","integration","test1"];function Tt(e){return typeof e=="string"?e.trim():""}function At(e){return{apiKey:Tt(e.apiKey),userId:Tt(e.userId),businessId:Tt(e.businessId)}}var ge=dn(cd(),".kizenappbuilder"),Ue=dn(ge,"credentials.json"),He="credentials",It=e=>q.includes(e),dd=e=>`Unknown --env "${e}". Use one of: ${q.join(", ")}.`,st=e=>It(e)?{environment:e}:{message:dd(e)};function ud(e){return typeof e=="string"?e.trim():e}function pd(e){return It(e)?"explicit":e==null||e===""?"missing":"invalid"}function fd(e){if(typeof e!="object"||e===null)throw new Error("Credentials must be a JSON object");let t=e,n=ud(t.environment);return{credentials:{...At(t),environment:It(n)?n:"go"},environmentSource:pd(n)}}async function un(e){let t=await sd(e,"utf-8");return fd(JSON.parse(t))}async function Ke(e){return(await un(e)).credentials}async function se(){try{return await Ke(Ue)}catch{return null}}async function md(e){await fi(ld(Ue),{recursive:!0,mode:448}),await mi(Ue,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function hi(e){return dn(ge,`${e}.json`)}async function Ve(){let e=[{name:He,path:Ue,isDefault:!0}];try{let t=await ad(ge);for(let n of t){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);r!==He&&e.push({name:r,path:dn(ge,n),isDefault:!1})}}catch{}return e}async function gi(e,t){if(e===He){await md(t);return}await fi(ge,{recursive:!0,mode:448}),await mi(hi(e),JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}async function Ae(e){try{return await Ke(hi(e))}catch{return null}}async function yi(){let e=await Ve(),t=await Promise.all(e.map(n=>un(n.path).then(()=>!0,()=>!1)));return e.filter((n,r)=>t[r]===!0)}import{randomBytes as bi}from"crypto";import{chmod as hd,mkdir as gd,open as yd,readdir as bd,readFile as _r,rename as wi,rm as vi,unlink as xi}from"fs/promises";import{join as $t}from"path";var wd="clients.json",vd=10*6e4,xd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ki=e=>typeof e=="string"&&xd.test(e),pn=e=>O(e)&&ki(e.businessId)&&ki(e.userId)?{businessId:e.businessId,userId:e.userId}:void 0,ke=(e,t)=>e.businessId===t.businessId&&e.userId===t.userId,gt=e=>{if(pn(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 pn(t)}var Tr=e=>typeof e=="string"?e:void 0;function kd(e,t){let n=pn(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:Tr(e.businessName),fullName:Tr(e.fullName),email:Tr(e.email),issuer:e.issuer,clientId:e.clientId,tokenEndpoint:e.tokenEndpoint,accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt}}function Ce(e=ge){let t=$t(e,"oauth"),n=x=>$t(t,`${x}.json`),r=(x,y)=>$t(t,`${x}.${gt(y)}.json`),o=$t(t,wd),i=(x,y)=>{let P=`${x}.`;if(!y.startsWith(P)||!y.endsWith(".json"))return;let w=y.slice(P.length,-5).split(".");if(w.length!==2)return;let[f,u]=w;return pn({businessId:f,userId:u})},s=async()=>await it(bd(t))??[],a=async()=>{await gd(t,{recursive:!0,mode:448}),await hd(t,448)},c=async(x,y)=>{await a();let P=`${x}.${bi(6).toString("hex")}.tmp`;try{let w=await yd(P,"wx",384);try{await w.writeFile(JSON.stringify(y,null,2),"utf-8"),await w.sync()}finally{await w.close()}await wi(P,x)}catch(w){throw await vi(P,{force:!0}),w}},h=(x,y)=>xe(x,`The saved ${x} session at ${y} can't be read.`,{again:!0}),p=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 w=y.exec(P)?.[1];w!==void 0&&Date.now()-Number(w)>vd&&await it(xi($t(t,P)))}}catch{}},m=async()=>{let x;try{x=JSON.parse(await it(_r(o,"utf-8"))??"{}")}catch(y){if(y instanceof SyntaxError)return{};throw y}return O(x)?x:{}},b=async(x,y)=>{try{return await it(_r(y,"utf-8"))}catch{throw h(x,y)}},d=async(x,y)=>{let P=r(x,y),w=await b(x,P);if(w===void 0)return null;try{let f=kd(JSON.parse(w),x);if(f!==null&&ke(f,y))return f}catch{}throw h(x,P)},l=async x=>{let y=n(x),P=await b(x,y);if(P===void 0)return;let w=Ci(P);if(w===void 0)throw h(x,y);return w},v=async x=>{let y=await l(x);return y===void 0?null:d(x,y)},C=async x=>{let y=n(x),P=`${y}.${String(Date.now())}-${bi(6).toString("hex")}.signout`;if(await it(wi(y,P).then(()=>!0))===!0)try{return{account:Ci(await _r(P,"utf-8"))}}catch{return{account:void 0}}finally{await vi(P,{force:!0})}},E=async(x,y)=>await it(xi(r(x,y)).then(()=>!0))??!1;return{dir:t,sessionPath:n,accountPath:r,readSession:v,readAccount:d,async listAccounts(x){let y;try{y=await l(x)}catch{}let P=(await s()).map(u=>i(x,u)).filter(u=>u!==void 0),w=await Promise.all(P.map(async u=>{let g;try{let k=await d(x,u);if(k===null)return;g=k}catch(k){if(!(k instanceof W&&k.code==="login_required"))throw k}return{account:u,session:g,current:y!==void 0&&ke(y,u)}})),f=u=>(u.session?.businessName??u.account.businessId).toLowerCase();return w.filter(u=>u!==void 0).sort((u,g)=>f(u).localeCompare(f(g))||gt(u.account).localeCompare(gt(g.account)))},async writeSession(x){await c(r(x.environment,x),x)},async setCurrent(x,y){let{businessId:P,userId:w}=y;await c(n(x),{businessId:P,userId:w}),await p(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 p(x),P},async removeAccount(x,y){let P=!1,w;try{w=await l(x)}catch{}w!==void 0&&ke(w,y)&&(P=await C(x)!==void 0);let f=await E(x,y);return await p(x),{removed:f,current:P}},async signOutAll(x){let y=await C(x),P=y!==void 0&&y.account===void 0,w=0;for(let f of await s()){let u=i(x,f);u!==void 0&&await E(x,u)&&(w+=1,P||=y?.account!==void 0&&ke(y.account,u))}return await p(x),{signedIn:P,removed:w}},async listSessions(){return(await Promise.all(q.map(async y=>{try{return await v(y)===null?void 0:y}catch(P){if(P instanceof W&&P.code==="login_required")return y;throw P}}))).filter(y=>y!==void 0)},async readClientId(x){let y=(await m())[x];return O(y)?ie(y.clientId):void 0},async writeClientId(x,y){await c(o,{...await m(),[x]:{clientId:y}})},async forgetClientId(x){let y=await m();x in y&&await c(o,Object.fromEntries(Object.entries(y).filter(([P])=>P!==x)))}}}var Cd=6e4,fn=class extends W{},Si=(e,t)=>fetch(e,t),Pi=()=>Date.now(),Ei=(e,t,n)=>({store:e,fetch:Si,now:Pi,print:t,openBrowser:pi,startLoopbackServer:ui,identify:n}),Sd=(e,t)=>({environment:e,getAccessToken:()=>Promise.resolve(t),refreshAccessToken:()=>Promise.reject(xe(e,`Kizen rejected the new ${e} sign-in.`))}),mn=e=>xe(e,`You're not signed in to ${e}.`),Pd=e=>({businessName:e.businessName,fullName:e.fullName,email:e.email}),_i=(e,t,n)=>({...e,accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:n+t.expiresIn*1e3}),Ed=(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 _d(e,t,n,r){let{verifier:o,challenge:i}=li(),s=Pr(),a=await n.startLoopbackServer({state:s,...n.timeoutMs!==void 0&&{timeoutMs:n.timeoutMs}});try{let c=di(e,{clientId:t,redirectUri:a.redirectUri,state:s,codeChallenge:i});n.print(r),n.print(c),n.openBrowser(c);let{code:h}=await a.result;return await Er(e.tokenEndpoint,{grant_type:"authorization_code",code:h,redirect_uri:a.redirectUri,client_id:t,code_verifier:o},n.fetch)}finally{await a.close()}}async function Ar(e,t,n={}){let r=Ed(e,n.interactive??!0),o=await ai(Le(e),t.fetch),i=await t.store.readClientId(o.issuer),s=i??await ci(o,t.fetch);i===void 0&&await t.store.writeClientId(o.issuer,s);let a;try{a=await _d(o,s,t,r)}catch(m){throw m instanceof W&&m.code==="timeout"&&i!==void 0?(await t.store.forgetClientId(o.issuer),new W("timeout",`${m.message}. If the browser showed an error instead of a consent page, the saved app registration was stale; it has been cleared. Run \`${ve(e)}\` again.`)):m}let c=await t.identify(Sd(e,a.accessToken)),h={businessId:c.businessId,userId:c.userId},p=_i({environment:e,...h,...Pd(c),issuer:o.issuer,clientId:s,tokenEndpoint:o.tokenEndpoint},a,t.now());if(await t.store.writeSession(p),n.makeCurrent!==void 0&&!n.makeCurrent(c)){if(await t.store.readAccount(e,h)===null)throw mn(e);return p}if(await t.store.setCurrent(e,h),await t.store.readSession(e)===null)throw mn(e);return p}async function Ti(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 mn(e);return r}function Td(e,t){let n,r=t.account,o=c=>c.expiresAt-t.now()>Cd,i=async()=>{let c=t.account===void 0?await t.store.readSession(e):await t.store.readAccount(e,t.account);if(c===null)throw mn(e);if(r??={businessId:c.businessId,userId:c.userId},!ke(c,r))throw new fn("login_required",`The ${e} sign-in changed while this command was running. Run it again.`);return c},s=async(c,h)=>{let p=await i();if(p.accessToken!==c&&o(p))return p.accessToken;let m=h??t.now()+(t.requestTimeoutMs??_t),b=async()=>{let E=await i();return{stored:E,rotated:E.refreshToken!==p.refreshToken}},d=m-t.now();if(d<=0)return p.accessToken;let l;try{l=await Er(p.tokenEndpoint,{grant_type:"refresh_token",refresh_token:p.refreshToken,client_id:p.clientId},t.fetch,d)}catch(E){if(E instanceof W&&(E.code==="invalid_grant"||E.code==="invalid_client")){let{stored:x,rotated:y}=await b();if(y)return o(x)||h!==void 0?x.accessToken:s(x.accessToken,m);if(await t.store.deleteSession(e,p)&&E.code==="invalid_client")try{await t.store.readClientId(p.issuer)===p.clientId&&await t.store.forgetClientId(p.issuer)}catch{}throw xe(e,`The ${e} session is no longer valid.`)}throw E}let v=_i(p,l,t.now()),C;try{({rotated:C}=await b())}catch(E){if(E instanceof fn){let x=await t.store.readAccount(e,p).catch(()=>null);x!==null&&x.refreshToken===p.refreshToken&&await t.store.writeSession(v).catch(()=>{})}throw E}return C||await t.store.writeSession(v),v.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 hn=(e,t,n={})=>Td(e,{store:t,now:Pi,...n,fetch:n.fetch??Si}),Ad=`You're not signed in. Run \`${ve(Me)}\` (add \`--env <env>\` to sign in to an environment other than ${Me}).`;async function Ie(e,t){if(e!==void 0){let{environment:o,message:i}=st(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:Ad}:{ok:!0,environment:r}}var pe=e=>/^[\w@%+:,./-][\w@%+=:,./-]*$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`;var gn="appbuilder admin",Nt="--env",Ai=["-h","--help"],$d="--force";function Nd(e){let t,n=0;for(;n<e.length;){let o=e[n]??"";if(o==="--")return{kind:"run",env:t,args:e.slice(n+1)};if(Ai.includes(o))return{kind:"help"};if(o===Nt||o.startsWith(`${Nt}=`)){let i=o===Nt?e[n+1]:o.slice(Nt.length+1);if(i===void 0||i==="")return{kind:"error",message:"option '--env <env>' argument missing"};t=i,n+=o===Nt?2:1;continue}break}let r=e.slice(n);if(r[0]==="init"){let o=r.slice(1);return o.length===0?{kind:"init",force:!1}:o.length===1&&o[0]===$d?{kind:"init",force:!0}:o.length===1&&Ai.includes(o[0]??"")?{kind:"init-help"}:{kind:"error",message:`admin init takes only --force, but got: ${o.map(pe).join(" ")}`}}return{kind:"run",env:t,args:r}}var Dd=(e,t,n,r)=>[e,t,"auth-header","--env",n,"--business",r.businessId,"--user",r.userId].map(pe).join(" "),Rd=["KIZEN_PROFILE","CLAUDE_CODE_MCP_SERVER_URL"];function Od(e,t){let n={};for(let[r,o]of Object.entries(e))o!==void 0&&!Rd.includes(r)&&(n[r]=o);return{...n,...t}}var Ii=["SIGTERM","SIGHUP"];function Bd(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(d){a(d instanceof Error?d:new Error(String(d)));return}let p=[...(i?Ii:[...Ii,"SIGINT"]).map(d=>[d,()=>{c.kill(d)}]),...i?[["SIGINT",()=>{}]]:[]];for(let[d,l]of p)o.on(d,l);let m=!1,b=d=>{if(!m){m=!0;for(let[l,v]of p)o.off(l,v);d()}};c.on("error",d=>{b(()=>{a(d)})}),c.on("close",(d,l)=>{b(()=>{s(d??128+(l===null?0:Id.signals[l]))})})})}var yt=(e,t)=>{e.writeStderr(`${gn}: ${t}
86
- `),e.setExitCode(1)};async function Fd(e,t=!1){let n;try{n=await e.ensureKizen(t?{force:t}:void 0)}catch(r){yt(e,oe(r));return}e.writeStderr(`${gn}: kizen ${n.version} is ready in ${n.dir}.
87
- `)}async function jd(e,t){let n=await Ie(e,()=>t.store.listSessions());if(!n.ok)return{ok:!1,message:n.message};let{environment:r}=n,o=await t.store.readSession(r);return o===null?{ok:!1,message:xe(r,`You're not signed in to ${r}.`).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:Dd(t.execPath,t.scriptPath,r,o),KIZEN_BASE_URL:Le(r),KIZEN_BUSINESS_ID:o.businessId,KIZEN_USER_ID:o.userId}}}async function $i(e,t){let n=Nd(e);switch(n.kind){case"help":t.outputHelp();return;case"init-help":t.outputInitHelp();return;case"init":await Fd(t,n.force);return;case"error":yt(t,n.message);return;case"run":break}let r;try{r=await jd(n.env,t)}catch(s){yt(t,oe(s));return}if(!r.ok){yt(t,r.message);return}let o;try{o=await t.ensureKizen()}catch(s){yt(t,oe(s));return}let i=Od(t.processEnv,r.session);try{t.setExitCode(await Bd(o,n.args,i,t.spawn,t.signals,t.interactive))}catch(s){yt(t,`couldn't start kizen: ${oe(s)}`)}}import{spawn as Md}from"child_process";import{createHash as Fi,randomBytes as Ud}from"crypto";import{createReadStream as Hd,createWriteStream as Kd}from"fs";import{access as Oi,mkdir as Bi,readdir as Vd,readFile as Wd,rename as qd,rm as Rt,stat as bn,utimes as Gd,writeFile as Jd}from"fs/promises";import{basename as Or,join as We}from"path";import{Readable as Yd,Transform as Xd}from"stream";import{pipeline as ji}from"stream/promises";import{spawn as Ld}from"child_process";function Ni(e){return e.split(`
88
- `).map(t=>t.trim().replace(/\s+#.*$/,"")).filter(t=>t.length>0&&!t.startsWith("#"))}function Di(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 Ir([e,t],n){return e>n[0]||e===n[0]&&t>=n[1]}function at(e){return`${String(e[0])}.${String(e[1])}`}var zd=(e,t)=>e[0]>t[0]||e[0]===t[0]&&e[1]>t[1];function yn(e){return new Promise(t=>{let n=Ld(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 $r(e,t,n,r=yn){let o=[],i;for(let s of e){let a=await r(s);if(!a){o.push(`${s}: not found`);continue}if(!Ir(a,t)){o.push(`${s}: ${at(a)} (too old)`);continue}if((i===void 0||zd(a,i.version))&&(i={bin:s,version:a}),n==="first")break}return{found:i,tried:o}}var Dt=[3,10];async function Ri(e,t=yn){let n=Di(e),r=n==="python3"?["python3"]:[n,"python3"],{found:o,tried:i}=await $r(r,Dt,"first",t);if(o!==void 0)return o.bin;throw new Error(`No Python >= ${at(Dt)} found for runtime "${e}". The local runner needs Python ${at(Dt)}+ 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 Zd=e=>`https://github.com/kizen/kizen-admin-cli/releases/download/v${e}/kizen_builder-${e}-py3-none-any.whl`,Qd={version:"0.3.0",wheelUrl:Zd("0.3.0"),sha256:"9f2017dd43bdc4554b655c87e25d1b5c754b04e0b8a32f1ed7516e30b9edf2d7"},wn="APPBUILDER_KIZEN_WHEEL",eu=We(ge,"kizen"),tu=".appbuilder-ready.json",Nr=[3,12],nu=["python3.14","python3.13","python3.12","python3"],ru=720*60*6e4,ou=60*6e4,iu=5*6e4,su=/^[0-9][\w.+!]*-[0-9a-f]{12}$/,au=/^kizen_builder-([^-]+)-.*\.whl$/;async function cu(e){let{found:t,tried:n}=await $r(nu,Nr,"newest",e);if(t===void 0)throw new Error(`No Python ${at(Nr)} or newer found to run kizen. Tried ${n.join(", ")}. Install Python ${at(Nr)} or newer and retry.`);return t}var lu=20,du=e=>(t,n)=>new Promise((r,o)=>{let i=Md(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,h)=>{if(c===0){r();return}let p=s.trimEnd().split(`
89
- `).slice(-lu).join(`
90
- `);p!==""&&e(`${p}
91
- `),o(new Error(`${Or(t)} exited with ${c===null?String(h):`code ${String(c)}`}`))})});function Li(e,t,n=process.env){let r=n[wn];return{baseDir:eu,pin:Qd,localWheel:r===""?void 0:r,fetch:(...o)=>fetch(...o),findPython:()=>cu(),run:du(t),log:e,now:Date.now}}var uu=async e=>{let t=Fi("sha256");return await ji(Hd(e),t),t.digest("hex")},vn=e=>We(e,tu),Ot=(e,t)=>We(e,"bin",t);async function Rr(e,t){try{let n=JSON.parse(await Wd(vn(e),"utf-8"));return!O(n)||n.sha256!==t?!1:(await Oi(Ot(e,"python")),await Oi(Ot(e,"kizen")),!0)}catch{return!1}}async function Dr(e,t){let n=new Date(t);await Gd(vn(e),n,n).catch(()=>{})}async function pu(e){if(e.localWheel!==void 0){let t=e.localWheel,n=au.exec(Or(t))?.[1];if(n===void 0)throw new Error(`${wn} must name a kizen_builder wheel (kizen_builder-<version>-\u2026.whl), not ${t}.`);let r;try{r=await uu(t)}catch(o){throw new Error(`Couldn't read ${wn} ${t}: ${ze(o)}`)}return{version:n,sha256:r,localPath:t}}return{version:e.pin.version,sha256:e.pin.sha256,localPath:void 0}}async function fu(e,t,n){let r=Fi("sha256");try{let o=await e.fetch(t,{signal:AbortSignal.timeout(iu)});if(!o.ok||o.body===null)throw new Error(`HTTP ${String(o.status)}`);await ji(Yd.fromWeb(o.body),new Xd({transform(i,s,a){r.update(i),a(null,i)}}),Kd(n))}catch(o){throw new Error(`Couldn't download kizen from ${t}: ${ze(o)}`)}return r.digest("hex")}var mu=e=>`.tmp-${e}-${String(process.pid)}-${Ud(4).toString("hex")}`;async function hu(e,t,n){let r;try{r=await Vd(e)}catch{return}await Promise.all(r.map(async o=>{if(o===t)return;let i=We(e,o);try{if(su.test(o)){let{mtimeMs:s}=await bn(vn(i)).catch(()=>bn(i));n-s>ru&&await Rt(i,{recursive:!0,force:!0})}else if(o.startsWith(".tmp-")){let{mtimeMs:s}=await bn(i);n-s>ou&&await Rt(i,{recursive:!0,force:!0})}}catch{}}))}var gu=e=>bn(e).then(()=>!0,()=>!1),zi=e=>new Error(`kizen's install at ${e} is damaged. Run \`appbuilder admin init --force\` to reinstall it.`);async function yu(e,t,n){try{return await qd(e,t),!0}catch(r){if(!ot(r,"ENOTEMPTY")&&!ot(r,"EEXIST"))throw r}if(await Rr(t,n))return!1;throw zi(t)}async function Mi(e,t={}){let n=await pu(e),r=`${n.version}-${n.sha256.slice(0,12)}`,o=We(e.baseDir,r),i=m=>({version:n.version,dir:o,python:Ot(o,"python"),kizen:Ot(o,"kizen"),built:m});if(t.force===!0)e.log(`Removing ${o}.`),await Rt(o,{recursive:!0,force:!0});else{if(await Rr(o,n.sha256))return await Dr(o,e.now()),i(!1);if(await gu(o)){if(await Rr(o,n.sha256))return await Dr(o,e.now()),i(!1);throw zi(o)}}e.log(`Installing kizen ${n.version} into ${o} (first run only).`);let s=await e.findPython();e.log(`Using ${s.bin} (Python ${at(s.version)}).`),await Bi(e.baseDir,{recursive:!0,mode:448});let a=We(e.baseDir,mu(r)),c=We(a,"venv"),h;try{await Bi(a);let m;if(n.localPath===void 0){m=We(a,Or(new URL(e.pin.wheelUrl).pathname)),e.log(`Downloading ${e.pin.wheelUrl}`);let b=await fu(e,e.pin.wheelUrl,m);if(b!==n.sha256)throw await Rt(m,{force:!0}),new Error(`The kizen ${n.version} download doesn't match its pinned sha256 (expected ${n.sha256}, got ${b}), so nothing was installed.`)}else m=n.localPath,e.log(`Using the local wheel ${m} (${wn}).`);e.log("Creating a virtual environment.");try{await e.run(s.bin,["-m","venv",c])}catch(b){throw new Error(`Couldn't create a virtual environment: ${oe(b)}`)}e.log(`Installing kizen ${n.version} from the wheel and its dependencies from PyPI.`);try{await e.run(Ot(c,"python"),["-m","pip","install","--disable-pip-version-check",m])}catch(b){throw new Error(`Couldn't install kizen: ${oe(b)}`)}await Jd(vn(c),`${JSON.stringify({version:n.version,sha256:n.sha256},null,2)}
92
- `),h=await yu(c,o,n.sha256)}finally{await Rt(a,{recursive:!0,force:!0}).catch(()=>{})}let p=e.now();return await Dr(o,p),h&&(e.log(`kizen ${n.version} is installed.`),await hu(e.baseDir,r,p)),i(h)}var Br="admin",vu=`Usage: appbuilder admin init [--force]
93
-
94
- Install kizen for appbuilder admin, or confirm it's installed. Needs Python 3.12 or newer.
95
-
96
- Options:
97
- --force remove kizen's install and install it again, to repair a damaged one; don't run it
98
- while appbuilder admin is running
99
- `,Fr=class extends wu{parseOptions(t){return{operands:[...t],unknown:[]}}};function xu(e){let t=o=>{process.stderr.write(o)},n=Li(o=>{t(`${gn}: ${o}
100
- `)},t),r=process.stdin;return{store:Ce(),ensureKizen:o=>Mi(n,o),spawn:bu,signals:process,interactive:r.isTTY===!0,processEnv:process.env,execPath:process.execPath,scriptPath:process.argv[1],outputHelp:()=>{e.outputHelp()},outputInitHelp:()=>{process.stdout.write(vu)},writeStderr:t,setExitCode:o=>{process.exitCode=o}}}function Ui(e){let t=new Fr(Br).copyInheritedSettings(e).description("Run Kizen's admin CLI (kizen) with the signed-in session").usage(`[--env <env>] [--] <kizen args...>
101
- appbuilder admin init [--force]`).option("--env <env>","environment to use (default: the only signed-in one)").allowExcessArguments().addHelpText("after",`
102
- Wrapper options end at the first other argument or at --; everything after goes to kizen.
103
- "appbuilder admin init" installs kizen ahead of time; it's otherwise installed on first use.`).action(async()=>{await $i(t.args,xu(t))});e.addCommand(t);let n=e.parseOptions.bind(e);e.parseOptions=r=>r[0]===Br?{operands:[Br],unknown:r.slice(1)}:n(r)}var ku="The API key is invalid for this business, or the user id doesn't match. Check the credentials file's apiKey, userId and businessId.",Cu="The API key's user needs the Standard API Keys permission and edit access to this dashboard. Homepages also need the Customize Homepages permission.",Su=e=>xe(e,"Kizen rejected the signed-in session.",{again:!0}).message,Pu="The signed-in user needs edit access to this dashboard. Homepages also need the Customize Homepages permission.",Eu={authFailed:ku,forbidden:Cu},_u=100,Tu=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}},Bt=encodeURIComponent,Ft=(e,t)=>t===void 0?`/dashboards/${Bt(e)}/dashlet`:`/dashboards/${Bt(e)}/dashlet/${Bt(t)}`;function jr(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&&jr(i,t,n);return}if(O(e))for(let[o,i]of Object.entries(e)){let s=t===""&&Tu.has(o)?"":t===""?o:`${t}.${o}`;jr(i,s,n)}}function Au(e){if(typeof e!="object"||e===null)return;let t=[];return jr(e,"",t),t.length>0?t.join("; "):void 0}async function Iu(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 $u(e,t,n,r,o){let i=Au(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 Hi(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 xn=e=>O(e)?e:{};function Ki(e){let t=xn(e);return{business:xn(t.business),team:xn(t.team)}}var Nu=new Map([["login_required","auth_failed"],["network_error","network_error"]]);function Du(e,t){let n=oe(e),r=e instanceof W?Nu.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 jt(e){let t=e.fetch??fetch,n=e.bearer?e.bearer.environment:e.credentials.environment,r=e.baseUrl??xr[n],o=e.bearer?{authFailed:Su(n),forbidden:Pu}:Eu,i=p=>{throw Du(p,n)},s=async()=>{if(!e.bearer){let{apiKey:b,userId:d,businessId:l}=e.credentials;return{headers:{"X-API-KEY":b,"X-USER-ID":d,"X-BUSINESS-ID":l}}}let{bearer:p}=e,m=await p.getAccessToken().catch(i);return{headers:{Authorization:`Bearer ${m}`},retry:async()=>({Authorization:`Bearer ${await p.refreshAccessToken(m).catch(i)}`})}},a=async(p,m,b)=>{let d=/^https?:\/\//.test(m)?m:`${r}${m}`,l=d.startsWith(r)?d.slice(r.length):d,v=async w=>{let f={...w,Accept:"application/json"},u={method:p,headers:f};b!==void 0&&(f["Content-Type"]="application/json",u.body=JSON.stringify(b));try{return await t(d,u)}catch(g){throw new Z("network_error",`Couldn't reach Kizen at ${r}: ${ze(g)}${sn()==="unavailable"?` ${on}`:""}`)}},{headers:C,retry:E}=await s(),x=await v(C);x.status===401&&E&&(await x.body?.cancel().catch(()=>{}),x=await v(await E()));let y,P;try{({text:y,json:P}=await Iu(x))}catch(w){throw new Z("network_error",`${p} ${l}: couldn't read the response: ${ze(w)}. The request may have been applied; check Kizen before retrying.`,{status:x.status})}if(!x.ok)throw $u(p,l,x.status,P,o);if(P===void 0&&y!=="")throw new Z("api_error",`${p} ${l} returned a response that is not JSON`,{status:x.status});return P},c=p=>{let m=new URL(r),b=new URL(p,m.origin);if(b.protocol=m.protocol,b.port=m.port,b.username="",b.password="",b.hash="",b.origin!==m.origin)throw new Z("api_error",`GET /custom-objects pagination pointed at an unexpected location ${b.origin}${b.pathname}`);return b.toString()},h;return{async listDashboards(p,m){let b=new URLSearchParams({size:"10000",include_sharing:"true",dashboard_type:p});m!==void 0&&b.set("custom_object_id",m);let d=`/dashboards/mine?${b.toString()}`;return Hi("GET",d,await a("GET",d)).results},async listCustomObjects(){let p=[],m=new Set,b="/custom-objects?page_size=200";for(;b!==void 0&&!m.has(b)&&m.size<_u;){m.add(b);let d=Hi("GET",b,await a("GET",b));p.push(...d.results),b=typeof d.next=="string"&&d.next!==""?c(d.next):void 0}return p},async getCustomObject(p){let m=`/custom-objects/${Bt(p)}`,b=await a("GET",m);if(!O(b)||typeof b.id!="string"||typeof b.fetch_url!="string")throw new Z("api_error",`GET ${m} returned an unexpected response shape`);return b},async getIdentity(){let p=await a("GET","/auth/bootstrap"),{business:m,team:b}=Ki(p),d=ie(m.id),l=ie(b.user);if(d===void 0||l===void 0)throw new Z("api_error","GET /auth/bootstrap returned an unexpected response shape");return h=p,{userId:l,businessId:d,businessName:ie(m.name),fullName:ie(b.full_name),email:ie(b.email)}},async getClientObjectId(){let p=h??await a("GET","/auth/bootstrap"),{business:m}=Ki(p);return ie(xn(m.client_object).id)??null},async getDashboard(p){return await a("GET",`/dashboards/${Bt(p)}`)},async createDashlet(p,m){return await a("POST",Ft(p),m)},async updateDashlet(p,m,b){return await a("PATCH",Ft(p,m),b)}}}var Ru=5e3,Ou=(e,t)=>e.isTTY===!0&&t.isTTY===!0;function Wi(e=Ce(),t){let n=(i,s)=>hn(i,e,s),r=i=>{process.stderr.write(i)},o=i=>jt({bearer:i}).getIdentity();return{store:e,loginDeps:Ei(e,i=>{r(`${i}
104
- `)},o),identify:o,tokenProvider:n,isInteractive:()=>Ou(process.stdin,process.stdout),...t!==void 0&&{pickAccount:t},authHeaderTimeouts:{requestTimeoutMs:Ru},processEnv:process.env,writeStdout:i=>{process.stdout.write(i)},writeStderr:r,setExitCode:i=>{process.exitCode=i}}}function qi(e){let{environment:t,message:n}=st(e);if(t===void 0)throw new Error(n);return t}async function Gi(e,t){let n=await Ie(e,()=>t.listSessions());if(!n.ok)throw new Error(n.message);return n.environment}var kn=(e,t)=>e?`${e} (${t})`:t,Ji=(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}
105
87
  User: ${n===""?t.userId:`${n} (${t.userId})`}
106
88
  Business: ${kn(t.businessName,t.businessId)}
107
- `};function Yi(e,t,{prefix:n="Error",oneLine:r=!1}={}){let o=oe(t),i=t instanceof Z&&t.hint!==void 0?`
89
+ `};function Gi(e,t,{prefix:n="Error",oneLine:r=!1}={}){let o=oe(t),i=t instanceof Z&&t.hint!==void 0?`
108
90
  ${t.hint}`:"";e.writeStderr(`${n}: ${r?o.replace(/\s+/g," ").trim():`${o}${i}`}
109
- `),e.setExitCode(1)}var zr=e=>async(t,n)=>{try{await e(t,n)}catch(r){Yi(n,r)}},Lr=(e,t)=>{e.writeStdout(`Signed in to ${t.environment}.
110
- `),e.writeStdout(Ji(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)":""}`,Bu=e=>[...e.map(({account:t,session:n,current:r})=>({key:gt(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"}],Fu=(e,t)=>e===ct?ct:t.find(({account:n})=>gt(n)===e),ju=(e,{business:t,user:n})=>(e.businessId===t||e.businessName?.toLowerCase()===t.toLowerCase())&&(n===void 0||e.userId===n);function Xi(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 Vi=e=>e.map(t=>`
111
- ${$e(t)}`).join(""),bt=({business:e,user:t})=>`--business ${pe(e)}${t===void 0?"":` --user ${pe(t)}`}`;function Zi(e,t,n,r=Xi(t,n.business,n.user)){if(r.kind==="one")return r.account;let o=bt(n);if(r.kind==="none")throw new Error(`No saved ${e} account matches ${o}. Saved accounts:${Vi(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 \`${bt({business:i.account.businessId,user:i.account.userId})}\`:${r.candidates.map(a=>`
112
- --user ${pe(a.account.userId)}: ${$e(a)}`).join("")}`):new Error(`${o} matches several saved ${e} accounts. Pass one of these business ids instead:${Vi(r.candidates)}`)}function Lu(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})))}
113
95
  `);return}if(t.length===0){r.writeStdout(`No saved accounts for ${e}.
114
96
  `);return}for(let o of t)r.writeStdout(`${$e(o)}${o.current?" (current)":""}
115
- `)}async function zu(e,t,n,r){if(t.business!==void 0){let o={business:t.business,user:t.user},i=Xi(n,o.business,o.user);return i.kind==="none"?{kind:"not_saved",request:o}:Zi(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.
116
- `),ct):Fu(await r.pickAccount(`Sign in to ${e}`,Bu(n)),n)}function Mu(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}
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}
117
99
  A browser window is opening to sign in to Kizen ${e}. On the consent page, choose ${s}.
118
100
  `:`${r}
119
101
  Waiting for the user to sign in to Kizen ${e} in a browser window. Ask them to choose ${s}.
120
- `}function Uu(e,t){if(t.kind==="expired"){let{account:n}=t.account;return{accepts:r=>ke(r,n),requested:$e(t.account),retry:`${ve(e)} ${bt({business:n.businessId,user:n.userId})}`}}return{accepts:n=>ju(n,t.request),requested:bt(t.request),retry:`${ve(e)} ${bt(t.request)}`}}var Qi=zr(async(e,t)=>{let n=qi(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){Lu(n,r,e.json===!0,t);return}let o=await zu(n,e,r,t);if(o===void 0){t.writeStderr(`Cancelled.
121
- `),t.setExitCode(1);return}if(o!==ct&&!("kind"in o)){let v=o,{account:C}=v;t.writeStderr(`Switching to ${$e(v)} on ${n}.
122
- `);let E=await Ti(n,C,{store:t.store,provider:t.tokenProvider(n,{account:C}),identify:t.identify});if(E!==void 0){Lr(t,E);return}o={kind:"expired",account:v}}if(o===ct){t.writeStderr(`Signing in to ${n}.
123
- `),Lr(t,await Ar(n,t.loginDeps,{interactive:t.isInteractive()}));return}let i=t.isInteractive(),s=Uu(n,o);t.writeStderr(Mu(n,o,i));let a=await Ar(n,t.loginDeps,{makeCurrent:s.accepts,interactive:i});if(s.accepts(a)){Lr(t,a);return}let c=await t.store.readSession(n).catch(()=>null),h=c!==null&&ke(c,a),p=$e({account:a,session:a,current:!1}),m=i?"You":"The user",b=h?`That's already the current ${n} account; its saved session was updated.`:`It was saved, but it isn't the current ${n} account.`,d=h?"":`To use it, run \`${ve(n)} ${bt({business:a.businessId,user:a.userId})}\`. `,l=i?"To try again":"To have them try again";t.writeStderr(`${m} signed in as ${p}, not ${s.requested}. ${b}
124
- ${d}${l}, run \`${s.retry}\`.
125
- `),t.setExitCode(1)}),es=zr(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 Ie(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.
126
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}.
127
- `);return}let s=Zi(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}.`:""}
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}.`:""}
128
110
  `:`No saved ${r} account ${$e(s)}.
129
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.
130
112
  `:`No saved accounts for ${r}.
131
113
  `);return}let o=await t.store.signOut(r);t.writeStdout(o?`Signed out of ${r}. The session was removed from this machine.
132
114
  `:`Not signed in to ${r}.
133
- `)}),ts=zr(async(e,t)=>{let n=await Gi(e.env,t.store);t.writeStdout(Ji(n,await t.identify(t.tokenProvider(n))))});function Hu(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=q.find(r=>Le(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 Ku(e,t){let n=e===void 0?void 0:qi(e),r=t.processEnv.CLAUDE_CODE_MCP_SERVER_URL;if(r!==void 0&&r!==""){let o=Hu(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??Gi(void 0,t.store)}function Vu(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}}}async function Wu(e,t,n){let r=async()=>{let s=await n.store.readSession(e);if(s===null||!ke(s,t)){let a=s===null?"nobody is signed in":`the current account is business ${s.businessId}, user ${s.userId}`;throw new Error(`--business ${t.businessId} --user ${t.userId} isn't the current ${e} account (${a}), so auth-header won't send its token. Run the command again.`)}};await r();let{requestTimeoutMs:o}=n.authHeaderTimeouts,i=await n.tokenProvider(e,{requestTimeoutMs:o,account:t}).getAccessToken();return await r(),i}var ns=async(e,t)=>{let n;try{let r=Vu(e),o=await Ku(e.env,t),{requestTimeoutMs:i}=t.authHeaderTimeouts,s=r===void 0?await t.tokenProvider(o,{requestTimeoutMs:i}).getAccessToken():await Wu(o,r,t);n=`${JSON.stringify({Authorization:`Bearer ${s}`})}
134
- `}catch(r){Yi(t,r,{prefix:"appbuilder auth-header",oneLine:!0});return}t.writeStdout(n)};import{render as Zu}from"ink";import{useMemo as qu,useState as Gu}from"react";import{Box as Mr,Text as lt,useInput as Ju}from"ink";var Cn=(e,t,n)=>Math.min(Math.max(e,t),n);function Sn(e,t,n,r={}){if(t<=0)return 0;let o=Cn(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 h=((o+s*c)%t+t)%t;if(i(h))return h}return o}let a=Cn(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 rs(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=Cn(Math.trunc(e)||0,0,t-1),i=Cn(o-Math.floor(r/2),0,t-r);return{start:i,end:i+r}}import{jsx as dt,jsxs as Hr}from"react/jsx-runtime";var Yu="\u2191/\u2193 to move, Enter to select, Esc to cancel",Ur=10,Xu=e=>{let t=Sn(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=Yu})=>{let[i,s]=Gu(()=>Xu(t)),a=qu(()=>t.map(d=>d.disabled===!0),[t]),c=Sn(i,t.length,0);Ju((d,l)=>{let v=C=>{s(Sn(c,t.length,C,{disabled:a}))};if(l.upArrow||d==="k")v(-1);else if(l.downArrow||d==="j")v(1);else if(l.pageUp)v(-Ur);else if(l.pageDown)v(Ur);else if(l.return){let C=t[c];C!==void 0&&C.disabled!==!0&&n(C,c)}else l.escape&&r?.()});let{start:h,end:p}=rs(c,t.length,Ur),m=h,b=t.length-p;return Hr(Mr,{flexDirection:"column",gap:1,children:[dt(lt,{bold:!0,children:e}),Hr(Mr,{flexDirection:"column",children:[m>0&&dt(lt,{dimColor:!0,children:` \u2191 ${String(m)} more`}),t.slice(h,p).map((d,l)=>{let C=h+l===c,E=d.disabled===!0,x=C&&!E;return Hr(Mr,{gap:2,children:[dt(lt,{...x&&{color:"cyan"},dimColor:E,children:C?"\u276F":" "}),dt(lt,{bold:x,dimColor:E,...x&&{color:"cyan"},children:d.label}),d.description!==void 0&&dt(lt,{dimColor:!0,children:d.description})]},d.key)}),b>0&&dt(lt,{dimColor:!0,children:` \u2193 ${String(b)} more`})]}),dt(lt,{dimColor:!0,children:o})]})};import{jsx as Qu}from"react/jsx-runtime";var os=async(e,t)=>{let n,r=Zu(Qu(Ne,{title:e,items:t,onSelect:o=>{n=o.key,r.unmount()},onCancel:()=>{r.unmount()}}));return await r.waitUntilExit(),n};var ep=[{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:Qi},{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:es},{name:"whoami",description:"Show the user and business of the stored session",env:"environment to check (default: the only signed-in one)",run:ts},{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 only this saved account, and fail if it isn't the environment's current one"],["--user <userId>","with --business, the user id of that account"]],run:ns}];function is(e){for(let{name:t,description:n,env:r,options:o=[],run:i}of ep){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,Wi(void 0,os))})}}import{createElement as Im}from"react";import{render as $m}from"ink";import{PluginValidationError as Nm}from"@kizenapps/packager";import{spawn as tp}from"child_process";import{platform as ss}from"process";function np(){return ss==="darwin"?[{cmd:"pbcopy",args:[]}]:ss==="win32"?[{cmd:"clip",args:[]}]:[{cmd:"wl-copy",args:[]},{cmd:"xclip",args:["-selection","clipboard"]},{cmd:"xsel",args:["--clipboard","--input"]}]}var rp=2e3;function op(e,{cmd:t,args:n}){return new Promise(r=>{let o;try{o=tp(t,n,{stdio:["pipe","ignore","ignore"]})}catch{r(!1);return}let i=o,s=!1;function a(h){s||(s=!0,clearTimeout(c),r(h))}let c=setTimeout(()=>{i.kill(),a(!1)},rp);c.unref(),i.on("error",()=>{a(!1)}),i.on("close",h=>{a(h===0)}),i.stdin.on("error",()=>{a(!1)});try{i.stdin.end(e)}catch{a(!1)}})}async function Pn(e){for(let t of np())if(await op(e,t))return!0;return!1}import{BLOCKS_DIRECTORY_NAME as jp,CONFIG_FILE_NAME as Lp,MANIFEST_FILE_NAME as zp,sanitizeToAPIName as Mp}from"@kizenapps/packager";var En=["min_w","max_w","min_h","max_h","default_w","default_h"];import{createHash as ip}from"crypto";import{mkdir as sp,readFile as ap,writeFile as cp}from"fs/promises";import{dirname as lp,join as ls}from"path";var Kr="appbuilder:",ut=".kizenapp/pushes.json",dp=["environment","businessId","pluginApiName","blockApiName","dashboardId","dashletId","contentHash","pushedAt"];function Vr(e){return typeof e=="number"&&Number.isFinite(e)}function _n(e,t,n){return Math.min(Math.max(e,t),n)}function up(e){let t={...e};return delete t.custom_object,t}function ds(e,t){return`${Kr}${e}/${t}`}function us(e){if(!e.startsWith(Kr))return null;let t=e.slice(Kr.length).split("/");if(t.length!==2)return null;let[n,r]=t;return!n||!r?null:{pluginApiName:n,blockApiName:r}}function ps(e){let t={};for(let n of En){let r=e[n];Vr(r)&&(t[n]=r)}return t}function fs(e){return typeof e.host_chrome=="boolean"?{host_chrome:e.host_chrome}:{}}var ms=e=>Object.entries(e).map(([t,n])=>({name:t,script:n}));function pp(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:ms(e.event_scripts)}}function qr(e){return e.length>0?{views:e.map(pp)}:{}}function hs(e,t=[]){return{kind:"custom_code",version:1,name:e.name,script:e.script,styles:e.styles,event_scripts:ms(e.event_scripts),...ps(e),...fs(e),...qr(t)}}function fp(e){return{object_id:e.objectId,entity_type:"static_content",report_type:"html",chart_type:"html",content:e.content,fe_extra_info:{}}}function mp(e){let t=0;for(let n of e){let r=n.layout;if(!O(r))continue;let{y:o,h:i}=r;!Vr(o)||!Vr(i)||(t=Math.max(t,o+i))}return t}function hp(e,t,n){let r=_n(t.default_w??t.min_w??6,t.min_w??1,t.max_w??12),o=_n(t.default_h??t.min_h??3,t.min_h??1,t.max_h??99);return{i:n,x:0,y:mp(e),w:_n(r,2,12),h:_n(o,1,99)}}function gs(e){return{name:ds(e.pluginApiName,e.blockApiName),layout:hp(e.dashlets,e.content,e.layoutId),config:fp({content:e.content,objectId:e.objectId})}}function ys(e,t){let n=e.config;return{config:{...up(O(n)?n:{}),content:t}}}function bs(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 ws(e){return e.dashlets.filter(wt)}function Tn(e){let t=bs(e);return O(t)&&typeof t.name=="string"?t.name:e.name}var qe=e=>typeof e=="string"?e:"";function vs(e){return Array.isArray(e)?e.filter(O).map(t=>({name:qe(t.name),script:qe(t.script)})):O(e)?Object.entries(e).map(([t,n])=>({name:t,script:qe(n)})):[]}function Wr(e){if(Array.isArray(e))return e.map(Wr);if(O(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Wr(e[n]);return t}return e}function xs(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e).trim():""}function gp(e){return Array.isArray(e)?e.filter(O).map(t=>({api_name:qe(t.api_name),name:xs(t.name),type:qe(t.type),script:qe(t.script),html:qe(t.html),css:qe(t.css),event_scripts:vs(t.event_scripts)})):[]}function Gr(e){let t=O(e)?e:{},n=gp(t.views),r={name:xs(t.name),script:typeof t.script=="string"?t.script:"",styles:typeof t.styles=="string"?t.styles:"",event_scripts:vs(t.event_scripts),...ps(t),...fs(t),...n.length>0&&{views:n}};return ip("sha256").update(JSON.stringify(Wr(r))).digest("hex")}function ks(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=ds(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 Cs(e,t){return t?.dashletId!==e.id?!1:Gr(bs(e))!==t.contentHash}function Jr(e,t){return e.environment===t.environment&&e.businessId===t.businessId&&e.pluginApiName===t.pluginApiName&&e.blockApiName===t.blockApiName}function Yr(e,t){return e.find(n=>Jr(n,t))}function Ss(e,t){let n=e.findIndex(r=>Jr(r,t));return n===-1?[...e,t]:e.map((r,o)=>o===n?t:r)}function Ps(e,t){return e.filter(n=>!Jr(n,t))}function yp(e){if(!O(e))return null;for(let n of dp)if(typeof e[n]!="string")return null;let t=e;return{environment:t.environment,businessId:Tt(t.businessId),pluginApiName:t.pluginApiName,blockApiName:t.blockApiName,dashboardId:t.dashboardId,dashletId:t.dashletId,contentHash:t.contentHash,pushedAt:t.pushedAt}}var as=e=>Date.parse(e.pushedAt)||0;function bp(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||as(n)>as(o))&&t.set(r,n)}return[...t.values()]}var cs=e=>e instanceof Error?e.message:String(e);async function Es(e){let t;try{t=await ap(ls(e,ut),"utf8")}catch(r){if(an(r))return[];throw new Error(`Couldn't read ${ut}: ${cs(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(`${ut} is not valid JSON (${cs(r)}). Fix it, or delete it to start a fresh push map.`)}if(!Array.isArray(n))throw new Error(`${ut} must contain a JSON array of push entries. Fix it, or delete it to start a fresh push map.`);return bp(n.map(yp).filter(r=>r!==null))}async function _s(e,t){let n=ls(e,ut);await sp(lp(n),{recursive:!0}),await cp(n,`${JSON.stringify(t,null,2)}
135
- `,"utf8")}var wp={generic_dashboard:"dashboard",homepage:"homepage",chart_group:"chart_group"},vp={dashboard:"generic_dashboard",homepage:"homepage",chart_group:"chart_group"};function Xr(e){return wp[e]}function Ts(e){return vp[e]}function As(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 Tp,writeFile as Ap}from"fs/promises";import{join as Ip}from"path";import{PluginValidationError as $p,packagePlugin as Np,parseManifestFromFiles as Dp,transformDeployablePlugin as Rp,transformFiles as Op,validatePluginApp as Bp}from"@kizenapps/packager";import{readdir as xp,readFile as Is}from"fs/promises";import{join as $s,relative as kp}from"path";var Cp=new Set([".png",".svg"]),Sp=new Set([".kzn"]),Pp=new Set([".DS_Store"]),An=new Set(["node_modules",".git",".kizenapp",".copilot-docs",".github",".claude","__pycache__"]),Ep=8e3;function _p(e){return e.subarray(0,Ep).includes(0)}async function Ns(e,t){let n=await xp(e,{withFileTypes:!0}),r=[];for(let o of n)if(o.isDirectory()){if(An.has(o.name))continue;r.push(...await Ns($s(e,o.name),t))}else o.isFile()&&(Pp.has(o.name)||r.push($s(e,o.name)));return r}async function In(e,{detectBinaryByContent:t=!1}={}){let n=await Ns(e,e);return Promise.all(n.map(async r=>{let o=kp(e,r).split("\\").join("/"),i=o.lastIndexOf("."),s=i>=0?o.slice(i).toLowerCase():"";if(Cp.has(s)){let c=await Is(r);return{path:o,content:"",base64Image:c.toString("base64")}}let a=await Is(r);return Sp.has(s)||t&&_p(a)?{path:o,content:"",binaryData:a}:{path:o,content:a.toString("utf-8")}}))}var Fp=(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 Zr(e,t){t?.("reading-files");let n=await In(e);t?.("validating");let r=Bp(n);if(r.some(c=>c.severity==="error"))throw new $p(r);t?.("minifying");let o=await Op(n);t?.("packaging");let i=Dp(o),s=Np(o,i),a=Object.values(s).map(Rp);return{files:n,deployable:a,issues:r}}async function $n(e,t,n){await Tp(t,{recursive:!0});let{files:r,deployable:o}=await Zr(e,n);n?.("writing-bundle");let i=o.map(h=>{let p=h.release_notes_directory?.replace(/\/$/,""),m=p?r.filter(b=>b.path.startsWith(p+"/")&&b.path.endsWith(".md")&&b.content).map(b=>({version:b.path.slice(b.path.lastIndexOf("/")+1,-3),notes:b.content})).sort((b,d)=>d.version.localeCompare(b.version,void 0,{numeric:!0})):[];return Fp(h,m)}),s=JSON.stringify(i,null,2),a=(h,p)=>h==="allReleaseNotes"?void 0:p,c=Buffer.byteLength(JSON.stringify(i,a,2),"utf-8");return await Ap(Ip(t,"bundle.json"),s,"utf-8"),{bundleSize:c}}var Os=["min_w","max_w","min_h","max_h"],Bs=[["min_w","max_w"],["min_h","max_h"]],Nn={default_w:["min_w","max_w"],default_h:["min_h","max_h"]},Up=Object.keys(Nn),Fs=[...En,"host_chrome"],Hp=["\0","{__ref:"],Qr="views",eo=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 Kp(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 Vp(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 Ds=e=>typeof e=="number"&&Number.isInteger(e)&&e>0,Lt=e=>Hp.some(t=>e.includes(t));function Wp(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 p=Object.entries(i).find(([m,b])=>typeof b!="string"||Lt(m)||Lt(b));if(p)return`event_scripts.${p[0]}`}let s=[["name",n],["script",r],["styles",o]].find(([,p])=>typeof p=="string"&&Lt(p));if(s)return s[0];let a=Os.find(p=>t[p]!==void 0&&!Ds(t[p]));if(a)return a;let c=Bs.find(([p,m])=>{let b=t[p],d=t[m];return typeof b=="number"&&typeof d=="number"&&b>d});if(c)return c[0];let h=Up.find(p=>{let m=t[p];if(m===void 0)return!1;if(typeof m!="number"||!Ds(m))return!0;let[b,d]=Nn[p],l=t[b],v=t[d];return typeof l=="number"&&m<l||typeof v=="number"&&m>v});if(h)return h;if(t.host_chrome!==void 0&&typeof t.host_chrome!="boolean")return"host_chrome"}var qp=["api_name","name","script","html","css"],Rs=e=>typeof e!="string"||Lt(e);function Gp(e){for(let t of e){let n=t,r=typeof n.api_name=="string"?n.api_name:String(n.api_name),o=qp.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])=>Lt(a)||Rs(c));if(s)return{view:r,field:`event_scripts.${s[0]}`}}}var Jp=({view:e,field:t})=>`views.${e}.${t}`,Yp=(e,t)=>`Block "${e}" can't carry view ${JSON.stringify(t.view)}: its ${t.field} must be a string without NUL characters or "{__ref:".`,Xp=(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=Bs.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 Nn){let[r,o]=Nn[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:".`},Zp=({reason:e,available:t},n,r)=>{let o=Kp(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}`},Qp=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},Ls=(e,t)=>{let n=cn(e);return n===""?t:`${n}/${t}`},zs=(e,t,n)=>{let r=`${Ls(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,...h]=s.path.slice(r.length).split("/");if(a&&(o.add(a),c===Lp&&h.length===0)){let p=Qp(s.content);p&&i.push([a,p])}}return{directories:o,configs:i}},Ms=(e,t)=>typeof e.api_name=="string"&&e.api_name!==""?e.api_name:Mp(t),ef=(e,t)=>{let n=new Map;for(let[r,o]of zs(e,t,jp).configs){let i=Ms(o,r),s={};for(let a of Fs)o[a]!==void 0&&(s[a]=o[a]);n.set(i,s)}return n},tf=(e,t={})=>({...Object.fromEntries(Object.entries(e).filter(([r])=>!Fs.includes(r))),...t});function nf(e,t){let n=js(t);return e.map(r=>{let o=n.get(r.api_name),i=o===void 0?new Map:ef(t,o);return{...r,artifacts:{...r.artifacts,custom_blocks:r.artifacts.custom_blocks.map(s=>tf(s,i.get(s.api_name)))}}})}var Us=(e,t)=>JSON.stringify([String(e),String(t)]),rf=(e,t)=>{let{directories:n,configs:r}=zs(e,t,Qr),o=new Map(r),i=new Set;for(let s of n){let a=o.get(s)??{};i.add(Us(Ms(a,s),a.name||s))}return i},of=(e,t)=>e.api_name.localeCompare(t.api_name)||String(e.name).localeCompare(String(t.name)),sf="appbuilder/views-unmatched";function af(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:rf(t,s),c=i.artifacts.routable_pages.filter(h=>a.has(Us(h.api_name,h.name))).sort(of);c.length!==a.size&&s!==void 0&&o.push({rule:sf,severity:"warning",message:`Found ${String(a.size)} ${Qr}/ components but matched ${String(c.length)} packaged views; the pushed block carries only the matched ones.`,path:Ls(s,Qr),pluginApiName:i.api_name}),r[i.api_name]=c}return{views:r,warnings:o}}function cf(e,t){return Object.hasOwn(e,t)?e[t]??[]:[]}function Hs(e){return{...e.block,...qr(e.views)}}async function to(e){let{files:t,deployable:n,issues:r}=await Zr(e),o=af(n,t);return{deployable:nf(n,t),views:o.views,warnings:[...r.filter(i=>i.severity==="warning"),...o.warnings]}}function no({deployable:e,views:t,warnings:n},r,o){let i=Vp(e,r);if(!i.ok)return{ok:!1,reason:i.reason,message:Zp(i,r,o),available:i.available};let s=Wp(i.block);if(s!==void 0)return{ok:!1,reason:"invalid_block",message:Xp(i.block.api_name,s),available:[],field:s};let a=cf(t,i.pluginApiName),c=Gp(a);return c!==void 0?{ok:!1,reason:"invalid_block",message:Yp(i.block.api_name,c),available:[],field:Jp(c)}:{ok:!0,value:{block:i.block,pluginApiName:i.pluginApiName,views:a,warnings:n}}}async function Ks(e,t){let n=no(await to(e),t,"export");if(!n.ok)throw new eo(n.reason,n.message,n);return n.value}var ro=(e,t,n)=>`${String(e)} ${e===1?t:n}`,oo=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},lf=e=>{let t=e.filter(o=>o.severity==="error").length,n=e.length-t;if(t===0)return`\u26A0 ${ro(n,"validation warning","validation warnings")}`;let r=`\u2717 ${ro(t,"validation error","validation errors")}`;return n===0?r:`${r}, ${ro(n,"warning","warnings")}`};function De(e){if(e.length===0)return"";let t=[...oo(e)].map(([n,r])=>[n,...r.map(o=>` ${o.severity==="error"?"\u2717":"\u26A0"} ${o.message} (${o.rule})`)].join(`
136
- `));return[lf(e),...t].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
137
 
138
- `)}import{randomUUID as Lf}from"crypto";import{join as zf}from"path";import{PluginValidationError as Mf}from"@kizenapps/packager";import{mkdir as df,readFile as uf,writeFile as pf}from"fs/promises";import{join as Vs}from"path";async function Se(e){try{let t=await uf(Vs(e,"config.json"),"utf-8");return JSON.parse(t)}catch{return{}}}async function Ge(e,t){await df(e,{recursive:!0}),await pf(Vs(e,"config.json"),JSON.stringify(t,null,2),"utf-8")}import*as vt from"fs";import*as Ws from"path";var ff=[".kizenapp/",".copilot-docs/"];function Pe(e){let t=Ws.join(e,".gitignore"),n="";vt.existsSync(t)&&(n=vt.readFileSync(t,"utf8"));let r=new Set(n.split(`
139
- `).map(a=>a.trim())),o=ff.filter(a=>!r.has(a)&&!r.has(a.replace(/\/$/,"")));if(o.length===0)return;let i=o.join(`
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(`
140
140
  `)+`
141
141
  `,s=n===""||n.endsWith(`
142
142
  `)?i:`
143
- `+i;vt.writeFileSync(t,n+s)}var mf="To use an API key instead (deprecated), pass --profile <name> or -c <path>.";function qs(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 Gs=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 ${pe(e)} to use the API key.`}`,Js=e=>`${e} ${mf}`;import{spawn as Tf}from"child_process";import{join as jn}from"path";var Ys="---\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 Xs=`# 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
144
144
 
145
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".
146
146
 
@@ -489,7 +489,7 @@ render(
489
489
  color: var(--color-font-placeholder);
490
490
  }
491
491
  \`\`\`
492
- `;var Zs=`# Copilot review instructions for this Kizen plugin
492
+ `;var sa=`# Copilot review instructions for this Kizen plugin
493
493
 
494
494
  This repo is a Kizen plugin app: a \`kizen.json\` manifest plus the artifacts
495
495
  that \`@kizenapps/packager\` finds by walking the directory tree under the
@@ -542,7 +542,7 @@ This file covers repo structure and general review. Two path-scoped files cover
542
542
  the rest: \`.github/instructions/security.instructions.md\` for security-sensitive
543
543
  patterns and \`.github/instructions/version-discipline.instructions.md\` for
544
544
  manifest version bumps.
545
- `;var Qs='---\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 ea=`---
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=`---
546
546
  applyTo: "kizen.json"
547
547
  ---
548
548
 
@@ -555,7 +555,7 @@ cannot drift out of date here.
555
555
  Check every \`kizen.json\` diff against the "How big a bump?" matrix in
556
556
  \`.copilot-docs/16-release-and-publish.md\` and the "Release & publish" section of
557
557
  \`.copilot-docs/17-gotchas.md\`, and name the change that sets the required level.
558
- `;var ta=`# 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.
559
559
  name: Copilot code review setup
560
560
 
561
561
  on:
@@ -594,7 +594,7 @@ jobs:
594
594
  echo "Fetched $count markdown files into .copilot-docs/ ($numbered numbered docs)"
595
595
  test "$count" -ge 24
596
596
  du -sh .copilot-docs
597
- `;var na=`const MAX_PAGE_SIZE = 1000;
597
+ `;var da=`const MAX_PAGE_SIZE = 1000;
598
598
  const DEFAULT_MAX_PAGES = 10;
599
599
 
600
600
  const fieldCache = new Map();
@@ -839,22 +839,22 @@ export const sumBy = (records, name, valueOf) =>
839
839
  total + (valueOf ? numberOf(valueOf(record)) : numberOf(fieldValue(record, name))),
840
840
  0,
841
841
  );
842
- `;function Dn(){return[{path:".github/copilot-instructions.md",content:Zs},{path:".github/instructions/security.instructions.md",content:Qs},{path:".github/instructions/version-discipline.instructions.md",content:ea},{path:".github/workflows/copilot-code-review.yml",content:ta}]}var ra="lib/kizenData.js",io=(e="src")=>e===""?ra:`${e}/${ra}`;function Rn(e=[]){return[{path:".claude/skills/kizen-custom-block/SKILL.md",content:Ys},{path:".claude/skills/kizen-custom-block/design.md",content:Xs},...[...new Set(e)].map(t=>({path:io(t),content:na}))]}import{access as kf,mkdir as Cf,readFile as Sf,writeFile as Pf}from"fs/promises";import{dirname as Ef,join as oa}from"path";var On={readFile:async e=>{try{return await Sf(e,"utf-8")}catch(t){if(an(t))return;throw t}},writeFile:async(e,t)=>{await Cf(Ef(e),{recursive:!0}),await Pf(e,t,"utf-8")},exists:async e=>{try{return await kf(e),!0}catch{return!1}}},_f=(e,t)=>e===void 0?"created":e===t?"unchanged":"updated";async function so(e,t,n=On){return Promise.all(t.map(async r=>({path:r.path,status:_f(await n.readFile(oa(e,r.path)),r.content)})))}async function Bn(e,t,n={},r=On){let o=await so(e,t,r);return n.dryRun===!0||await Promise.all(t.filter((i,s)=>o[s]?.status!=="unchanged").map(i=>r.writeFile(oa(e,i.path),i.content))),o}var Fn=e=>`${e.status.padEnd(9)} ${e.path}`;var ia=".claude/skills/kizen-custom-block/SKILL.md",aa="Claude files managed by appbuilder are out of date; run appbuilder setup-claude",co=On,Af=e=>{if(typeof e!="string"||e.trim()==="")return;let t=cn(e);if(!(t===".."||t.startsWith("../")||t.startsWith("/")))return t};function If(e){let n=(Array.isArray(e)?e:[e]).map(r=>typeof r=="object"&&r!==null&&"entry"in r?Af(r.entry):void 0).filter(r=>r!==void 0);return n.length>0?[...new Set(n)]:["src"]}var $f=async(e,t)=>{try{let n=await t.readFile(jn(e,"kizen.json"));return n===void 0?["src"]:If(JSON.parse(n))}catch{return["src"]}};async function ca(e,t=co,n={}){let r=await $f(e,t),o=n.includeLib===!0?r:(await Promise.all(r.map(async i=>await t.exists(jn(e,io(i)))?i:void 0))).filter(i=>i!==void 0);return Rn(o)}async function la(e,t=co){try{let n=await ca(e,t);return!n.some(o=>o.path===ia)||await t.readFile(jn(e,ia))===void 0?!1:(await so(e,n,t)).some(o=>o.status!=="unchanged")}catch{return!1}}var Nf="@kizenapps/cli",Df=6e4,Rf=(e,t)=>new Promise((n,r)=>{let o=Tf(e,[...t],{stdio:["ignore","pipe","pipe"],timeout:Df}),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})})}),da=e=>({run:Rf,hasOAuthSession:async t=>await Ce().readSession(t)!==null,cliVersion:e,fs:co,log:t=>{console.log(t)},error:t=>{console.error(t)},setExitCode:t=>{process.exitCode=t}}),ao=(e,t)=>`${String(e.filter(n=>n.status===t).length)} ${t}`;function Of(e,t){let n=`kizen-${e}`,r=`${Le(e)}/api/mcp`,o=JSON.stringify({type:"http",url:r,headersHelper:`npx -y ${Nf}@${t} auth-header`}),i=["mcp","add-json","--scope","user",n,o];return{environment:e,name:n,url:r,addArgs:i,addCommand:["claude",...i].map(pe).join(" ")}}function Bf(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:st(e.env).message}var Ff=e=>/already\s+exists/i.test(`${e.stdout}
843
- ${e.stderr}`),sa=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=Of(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&&Ff(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 ${sa(c)}`);return}i=!0,a=await n.run("claude",r.addArgs)}if(a.code!==0){s(`claude mcp add-json ${sa(a)}`);return}}catch(a){if(!i&&ot(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 \`${ve(e)}\` before using ${r.name}.`)}catch(a){n.log(oe(a))}}async function ua(e,t,n){let r=Bf(t);if(r!==void 0){n.error(`Error: ${r}`),n.setExitCode(1);return}if(!await n.fs.exists(jn(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 Bn(e,await ca(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(Fn(c));let s=`${ao(i,"created")}, ${ao(i,"updated")}, ${ao(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 jf((t.env===void 0?void 0:st(t.env).environment)??Me,{dryRun:o,force:t.force===!0},n)}function Uf(e,t={}){let{fetch:n}=t;return{listSessions:()=>e.listSessions(),connect:async r=>{let o=hn(r,e,{...n&&{fetch:n}}),i=jt({bearer:o,...n&&{fetch:n}});return{identity:await i.getIdentity(),client:i}}}}function uo(e){return{cwd:e,loadCredentialsDetailed:un,listLoadableCredentialProfiles:yi,loadConfig:Se,packageBlocks:to,createClient:t=>jt({credentials:t}),readPushMap:Es,writePushMap:_s,ensureGitignore:Pe,isClaudeSkillStale:t=>la(t),randomUUID:Lf,now:()=>new Date,writeStdout:t=>{process.stdout.write(t)},writeStderr:t=>{process.stderr.write(t)},setExitCode:t=>{process.exitCode=t},oauth:Uf(Ce())}}var Hf=new Set(["owner","admin","edit"]),Kf="Chart groups are not listed here; find them with `appbuilder block targets --object <id> --json` and pass --dashboard <id>.",po=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 he=e=>({ok:!0,value:e});function Je(e){return e instanceof Z?K(e.kind,e.message,e.hint===void 0?{}:{hint:e.hint}):e instanceof Mf?K("validation_failed",De(e.issues),{issues:e.issues}):K("local_error",po(e))}async function ma(e,t){let n;try{n=await t.loadCredentialsDetailed(e)}catch(i){return K("credentials_invalid",`Couldn't read credentials from ${e}: ${po(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: ${q.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(", ")}.`):he({credentials:r,client:t.createClient(r),notices:[]})}async function Vf(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 ${Ue} or pass -c <path>.`:`No loadable credential profile named "${e}". Loadable profiles: ${o.join(", ")}`)}return ma(r.path,t)}async function Wf(e){let{activeCredentialProfile:t}=await e.loadConfig(zf(e.cwd,".kizenapp"));return t===void 0||t===""?[]:[Gs(t)]}async function qf(e,t){let n=[],r=await Ie(e,async()=>(n=await t.oauth.listSessions(),n));if(!r.ok)switch(r.problem){case"not_signed_in":return K("credentials_invalid",Js(r.message));case"several_sessions":return K("needs_choice",r.message,{choice:"environment",choices:n.map(s=>({value:s,label:s,args:["--env",s]}))});case"unknown_environment":return K("usage_error",r.message)}let{environment:o}=r,i;try{i=await t.oauth.connect(o)}catch(s){return Je(s)}return he({credentials:{environment:o,businessId:i.identity.businessId},client:i.client,notices:await Wf(t)})}async function zn(e,t){let n=qs(e);if(!n.ok)return K("usage_error",n.message);let{selection:r}=n;return r.kind==="oauth"?qf(r.env,t):r.credentials===void 0?Vf(r.profile,t):ma(r.credentials,t)}function Gf(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 fo(e,t){let n=await t.packageBlocks(t.cwd),r=no(n,e,"push");if(!r.ok){let{reason:h,message:p,field:m}=r;return h==="no_blocks"||h==="invalid_block"?K("invalid_block",p,m===void 0?{}:{field:m}):K("needs_choice",p,{choice:"block",choices:Gf(n.deployable,r.available)})}let{block:o,pluginApiName:i,views:s,warnings:a}=r.value,c=hs(o,s);return he({block:o,pluginApiName:i,content:c,contentHash:Gr(c),warnings:a})}var ha=e=>e==null?null:Hf.has(e.toLowerCase());function zt(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:ha(e.employee_access)}}var ga=e=>({id:e.id,objectName:e.object_name,fetchUrl:e.fetch_url}),Jf="Contacts";async function mo(e){let[t,n]=await Promise.all([e.listCustomObjects(),e.getClientObjectId().catch(()=>null)]),r=t.map(ga).sort((o,i)=>o.objectName.localeCompare(i.objectName));return n!==null&&n!==""&&!r.some(o=>o.id===n)&&r.push({id:n,objectName:Jf,fetchUrl:"client"}),r}async function Yf(e,t,n){let{environment:r,businessId:o}=t;try{if(n.object!==void 0){let c=n.object,[h,p]=await Promise.all([e.getCustomObject(c).catch(()=>null),e.listDashboards("chart_group",c)]);return he({ok:!0,environment:r,businessId:o,object:h?ga(h):null,surfaces:{chart_group:p.map(m=>zt(m,"chart_group"))}})}let[i,s,a]=await Promise.all([e.listDashboards("generic_dashboard"),e.listDashboards("homepage"),mo(e)]);return he({ok:!0,environment:r,businessId:o,surfaces:{dashboard:i.map(c=>zt(c,"dashboard")),homepage:s.map(c=>zt(c,"homepage"))},customObjects:a})}catch(i){return Je(i)}}var ho=(e,t)=>t.dashboard===e.id;function Mn(e,t){return[...ws(e).filter(r=>ho(e,r)).map(r=>{let o=us(r.name);return{value:r.id,label:Tn(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 go=(e,t)=>ks({dashboardId:t.id,dashlets:t.dashlets,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name,entry:e.entry}),ya=(e,t)=>he({dashboard:e,surface:Xr(e.type),action:"create",dashlet:void 0,resolvedBy:t}),Ln=(e,t,n)=>he({dashboard:e,surface:Xr(e.type),action:"update",dashlet:t,resolvedBy:n});async function Xf(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:ha(i.employee_access)});return K("needs_choice",`Choose where to push; pass --dashboard <id>. ${Kf}`,{choice:"dashboard",choices:[...t.map(r("dashboard")),...n.map(r("homepage"))]})}async function Zf(e,t,n){let r=await e.client.getDashboard(t);if(n.create)return ya(r,"flag");let o=()=>Mn(r,e.block);if(n.dashlet!==void 0){let s=n.dashlet,a=r.dashlets.find(c=>c.id===s&&ho(r,c));return a?wt(a)?Ln(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=go(e,r);return i.kind==="map"?Ln(r,i.dashlet,"push_map"):i.kind==="name"?Ln(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 Qf(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 ya(r,"remembered");let o=r.dashlets.find(i=>i.id===t.dashletId&&ho(r,i));return o&&wt(o)?Ln(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:Mn(r,e.block)})}async function yo(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 Zf(e,t.dashboard,t):e.entry?await Qf(e,e.entry,t):await Xf(e)}catch(n){return Je(n)}}async function em(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 bo(e,t,n,r){let{credentials:o,block:i}=e,{dashboard:s,surface:a}=t,c=[],h,p;if(t.action==="update"){let{dashlet:b}=t;if(Cs(b,e.entry)){let d=`"${Tn(b)}" (dashlet ${b.id}) was changed in Kizen since the last push.`;if(!n.force)return K("drift_detected",`${d} Pushing would overwrite those changes; pass --force to overwrite them.`);c.push(`${d} Overwriting it because of --force.`)}h={action:"update",method:"PATCH",path:Ft(s.id,b.id),body:ys(b,i.content),dashletId:b.id},p=`Update "${Tn(b)}" (dashlet ${b.id})`}else h={action:"create",method:"POST",path:Ft(s.id),body:gs({pluginApiName:i.pluginApiName,blockApiName:i.block.api_name,content:i.content,dashlets:s.dashlets,objectId:r.randomUUID(),layoutId:r.randomUUID()}),dashletId:null},p=`Create a new block on "${s.name}"`;let m=As({appBaseUrl:ni[o.environment],surface:a,dashboardId:s.id,customObject:await em(e.client,s,a)});return he({...h,dashboard:{id:s.id,name:s.name,type:a},url:m,resolvedBy:t.resolvedBy,warnings:c,summary:{environment:o.environment,businessId:o.businessId,isProduction:kr(o.environment),surface:a,dashboardId:s.id,dashboardName:s.name,action:t.action,actionLine:p,dashletId:h.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 wo=e=>({environment:e.credentials.environment,businessId:e.credentials.businessId,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name});async function vo(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 Je(a)}let o=[...t.warnings],i={...wo(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,Ss(e.pushMap,i)),s=!0}catch(a){o.push(`The push succeeded, but ${ut} couldn't be written, so this target isn't remembered: ${po(a)}`)}return he({dashletId:r,remembered:s,warnings:o})}var tm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function xo(e){return tm.test(e)?{dashboardId:e,script:`await window.__kizenCustomBlocks?.refresh('${e}')`}:null}async function nm(e,t){let n=wo(e);if(!Yr(e.pushMap,n))return null;let r=Ps(e.pushMap,n);return await t.writePushMap(t.cwd,r),r}async function ko(e,t){let{client:n,credentials:r,block:o}=e,i=await t.readPushMap(t.cwd),s=!1;if(e.forget){let a=await nm({credentials:r,block:o,pushMap:i},t);a&&(i=a,s=!0)}return{context:{client:n,credentials:r,block:o,pushMap:i,entry:Yr(i,wo({credentials:r,block:o}))},forgotten:s}}function Co(e,t){return e.dryRun?he({kind:"dry-run",reason:"flag"}):e.yes?kr(t)&&!e.allowProduction?K("production_requires_flag",`${t} is a production environment. Pass --allow-production with --yes to write to it.`):he({kind:"apply"}):he({kind:"dry-run",reason:"no_yes"})}var rm="Dry run only: pass --yes to write.",pt=e=>e.map(t=>`Warning: ${t}`);function Mt(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 om=e=>`${e.path===void 0?"":`${e.path}: `}${e.message} (${e.rule})`;function im(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(pe).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(`
844
844
  `)}
845
- `}function ba(e,t,n,r){e.json?e.deps.writeStdout(`${JSON.stringify(t,null,2)}
846
- `):e.deps.writeStderr(im(t,n,r)),e.deps.setExitCode(1)}function pa(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 fa=e=>e.credentials!==void 0?["-c",e.credentials]:e.profile!==void 0?["--profile",e.profile]:e.env===void 0?[]:["--env",e.env],wa=(e,t)=>{for(let n of t)e.writeStderr(`${n}
848
- `)};async function sm(e){try{return await e.isClaudeSkillStale(e.cwd)?[aa]:[]}catch{return[]}}async function va(e,t,n){let r={json:t.json===!0,deps:n},o="appbuilder block push",i=e===void 0?[]:[e],s=(c,h)=>h==="environment"?[...i,...c.args]:h==="block"?[...c.args,...fa(t)]:[...i,...fa(t),...c.args],a=c=>{ba(r,c,o,s)};try{let c=await zn(t,n);if(!c.ok){a(c);return}let{credentials:h,client:p,notices:m}=c.value;wa(n,m);let b=await fo(e,n);if(!b.ok){a(b);return}let d=b.value;i=[d.block.api_name],d.warnings.length>0&&n.writeStderr(`${De(d.warnings)}
849
- `);let{context:l,forgotten:v}=await ko({client:p,credentials:h,block:d,forget:t.forget===!0},n);v&&n.writeStderr(`Forgot the remembered target for ${d.block.api_name}.
850
- `);let C=await yo(l,t);if(!C.ok){a(C);return}let E=Co(t,h.environment);if(!E.ok){a(E);return}let x=await bo(l,C.value,t,n);if(!x.ok){a(x);return}let y=x.value,P={pluginApiName:d.pluginApiName,apiName:d.block.api_name,name:d.block.name},w={environment:h.environment,businessId:h.businessId,dashboard:y.dashboard},f=[...d.warnings.map(om),...await sm(n)],u=E.value;if(u.kind==="dry-run"){let R=[...f,...y.warnings],M={ok:!0,applied:!1,dryRun:!0,reason:u.reason,action:y.action,...w,dashletId:y.dashletId,url:y.url,resolvedBy:y.resolvedBy,block:P,method:y.method,path:y.path,body:y.body,warnings:R,...v?{forgotten:!0}:{}};pa(r,M,[...Mt(y.summary),`URL: ${y.url}`,...pt(R),"",`${y.method} ${y.path}`,JSON.stringify(y.body,null,2),""].join(`
851
- `),[...Mt(y.summary),...pt(R),""].join(`
852
- `)),u.reason==="no_yes"&&n.writeStderr(`${rm}
853
- `);return}let g=await vo(l,y,n);if(!g.ok){a(g);return}let k=g.value,S=[...f,...k.warnings],T=xo(y.dashboard.id),_={ok:!0,applied:!0,dryRun:!1,action:y.action==="create"?"created":"updated",...w,dashletId:k.dashletId,url:y.url,...T?{refresh:T}:{},resolvedBy:y.resolvedBy,block:P,remembered:k.remembered,warnings:S,...v?{forgotten:!0}:{}};pa(r,_,[`\u2713 ${_.action==="created"?"Created":"Updated"} ${d.block.name} on "${y.dashboard.name}" (dashlet ${k.dashletId})`,...Mt(y.summary),`URL: ${y.url}`,...T?[`Refresh an open tab: ${T.script}`]:[],...pt(S),""].join(`
854
- `))}catch(c){a(Je(c))}}var am=(e,t)=>e.padEnd(t);function lo(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)=>am(a,o[c]??0)).join(" ")}`.trimEnd();return[e,i(n),...r.map(i)]}function cm(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})`,"",...lo("Chart groups",e.surfaces.chart_group)):t.push(...lo("Dashboards",e.surfaces.dashboard),"",...lo("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(`
855
855
  `)}
856
- `}async function xa(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=>{ba(n,a,r,i)};try{let a=await zn(e,t);if(!a.ok){s(a);return}let{credentials:c,client:h,notices:p}=a.value;wa(t,p);let m=await Yf(h,c,e.object===void 0?{}:{object:e.object});if(!m.ok){s(m);return}t.writeStdout(n.json?`${JSON.stringify(m.value,null,2)}
857
- `:cm(m.value))}catch(a){s(Je(a))}}import{useEffect as Pa,useState as Un}from"react";import{Box as le,Text as Y,useApp as vm,useInput as Aa}from"ink";import"@kizenapps/packager";import{Box as pm,Text as fm}from"ink";import{Box as lm,Text as dm}from"ink";import{jsx as ka}from"react/jsx-runtime";var um=[" :::::::: "," :::::: ::::::::::: "," :::::: :::::::::: "," :::::: :::::: ::::::: "," ::::: :::::: ::::::::::::::::: "," ::::: ::::: ::::::::::::::::::: "," ::::: ::::: :::::: ::::: ",":::: ::::: ::: ::::: :: ","::::: :::::: :::::::::: ","::::: :::::: ::::::::::: "," ::::: ::: ::::::: "," ::::::: ::: ::::: "," ::::::::::: :::::: :::::"," :::::::::: :::::: :::::"," :: ::::: ::: ::::: ::::"," ::::: :::::: ::::: ::::: ::: "," ::::::::::::::::::: ::::: ::::: "," ::::::::::::::::: ::::: ::::: "," ::::::::: :::::: :::::: "," :::::::::: :::::: "," ::::::::::: :::::: "," :::::::: "],Ca=()=>ka(lm,{flexDirection:"column",children:um.map((e,t)=>ka(dm,{color:"cyan",children:e},t))});import{Fragment as mm,jsx as So,jsxs as hm}from"react/jsx-runtime";var G=({marginBottom:e=0})=>hm(mm,{children:[So(Ca,{}),So(pm,{flexDirection:"column",marginTop:1,marginBottom:e,children:So(fm,{bold:!0,color:"cyan",children:"Kizen App Development Toolkit"})})]});import{useEffect as gm,useState as ym}from"react";import{Text as bm}from"ink";import{jsx as wm}from"react/jsx-runtime";var Sa=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ee=()=>{let[e,t]=ym(0);return gm(()=>{let n=setInterval(()=>{t(r=>(r+1)%Sa.length)},80);return()=>{clearInterval(n)}},[]),wm(bm,{color:"cyan",children:Sa[e]??"\u280B"})};import{Fragment as Am,jsx as D,jsxs as J}from"react/jsx-runtime";var Ea=[{key:"dashboard",label:"Dashboard"},{key:"homepage",label:"Homepage"},{key:"chart_group",label:"Chart group"}],xm={dashboard:"dashboard",homepage:"homepage",chart_group:"chart group"},Po="\u2191/\u2193 to move, Enter to select, Esc to go back",km="The block was edited in Kizen since your last push. Overwriting discards those edits.",Hn=e=>e.args.includes("--create");function _a(e,t){let n=e.filter(i=>i.value===t),r=e.filter(Hn),o=e.filter(i=>i.value!==t&&!Hn(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 Cm(e,t){if(Hn(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 Sm(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 Pm(e,t,n){let r={...e,dashboard:t};return delete r.dashlet,delete r.create,Hn(n)?{...r,create:!0}:{...r,dashlet:n.value}}function Em(e,t,n,r){let o=d=>{t.setExitCode(1),n({type:"error",view:d})},i=d=>{d().catch(l=>{o(Je(l))})},s=async(d,l)=>{n({type:"applying",plan:l});let v=await vo(d,l,t);if(!v.ok){o(v);return}n({type:"done",plan:l,applied:v.value})},a=async(d,l,v)=>{n({type:"loading",label:"Preparing the push\u2026"});let C=await bo(d,l,v,t);if(!C.ok){if(C.code==="drift_detected"){n({type:"confirm",kind:"drift",message:C.message,target:l,options:v,context:d});return}o(C);return}if(v.dryRun){n({type:"done",plan:C.value,applied:null});return}if(v.yes){let E=Co(v,d.credentials.environment);if(E.ok&&E.value.kind==="apply"){await s(d,C.value);return}}n({type:"confirm",kind:"push",plan:C.value,options:v,context:d})},c=async(d,l,v)=>{n({type:"loading",label:"Resolving the target\u2026"});let C=await yo(d,l);if(C.ok){await a(d,C.value,l);return}let E=l.dashboard??d.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:_a(C.choices,null),matchedId:null,back:v,options:l,context:d});return}o(C)},h=async(d,{credentials:l,client:v},C)=>{let{context:E,forgotten:x}=await ko({client:v,credentials:l,block:C,forget:d.forget===!0},t);if(x&&r(y=>({...y,notices:[...y.notices,`Forgot the remembered target for ${C.block.api_name}.`]})),d.dashboard!==void 0||E.entry){await c(E,d,null);return}n({type:"surface-select",options:d,context:E})},p=async(d,l,v)=>{n({type:"packaging"});let C=await fo(v,t);if(!C.ok){if(C.choice==="block"&&C.choices){n({type:"block-select",options:d,resolved:l,choices:C.choices});return}o(C);return}r(E=>({...E,warnings:C.value.warnings})),await h(d,l,C.value)},m=async d=>{n({type:"loading",label:"Loading credentials\u2026"});let l=await zn(d,t);if(!l.ok){if(l.choice==="environment"&&l.choices){n({type:"environment-select",options:d,choices:l.choices});return}o(l);return}r(v=>({...v,credentials:l.value.credentials,credentialNotices:l.value.notices})),await p(d,l.value,e)},b=async({options:d,context:l},v,C,E)=>{let x=xm[v];n({type:"loading",label:`Loading ${x}s\u2026`});let P=(await l.client.listDashboards(Ts(v),C?.id)).map(u=>zt(u,v)),{environment:w,businessId:f}=l.credentials;if(P.length===0){o({message:`No ${x}s found${C?` on ${C.objectName}`:""} for business ${f} (${w}).`});return}n({type:"dashboard-select",surface:v,objectId:C?.id??null,title:C?`Choose a chart group on ${C.objectName}`:`Choose a ${x}`,rows:P,back:E,options:d,context:l})};return{start:d=>{i(()=>m(d))},pickEnvironment:(d,l)=>{i(()=>m({...d.options,env:l.value}))},pickBlock:(d,l)=>{i(()=>p(d.options,d.resolved,l.value))},pickSurface:(d,l)=>{i(async()=>{if(l!=="chart_group"){await b(d,l,null,d);return}n({type:"loading",label:"Loading custom objects\u2026"});let v=await mo(d.context.client);if(v.length===0){o({message:"No custom objects found, so there are no chart groups to push to."});return}n({type:"object-select",objects:v,back:d,options:d.options,context:d.context})})},pickObject:(d,l)=>{i(()=>b(d,"chart_group",l,d))},pickDashboard:(d,l)=>{i(async()=>{let{context:v}=d,C={...d.options,dashboard:l.id};if(C.dashlet!==void 0||C.create){await c(v,C,d);return}n({type:"loading",label:`Loading "${l.name}"\u2026`});let E=await v.client.getDashboard(l.id),x=go(v,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:_a(Mn(E,v.block),y),matchedId:y,back:d,options:C,context:v})})},pickTarget:(d,l)=>{i(()=>c(d.context,Pm(d.options,d.dashboardId,l),d))},acceptDrift:d=>{i(()=>a(d.context,d.target,{...d.options,force:!0}))},acceptPush:d=>{i(()=>s(d.context,d.plan))},cancel:()=>{o({message:"Cancelled."})}}}var Ta=({prompt:e,strict:t,onAccept:n,onCancel:r})=>(Aa((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})),ft=({lines:e,color:t})=>D(le,{flexDirection:"column",children:e.map((n,r)=>D(Y,{...t&&{color:t},children:n},`${String(r)}-${n}`))}),Ia=({plan:e})=>J(le,{flexDirection:"column",children:[D(ft,{lines:Mt(e.summary)}),J(Y,{children:["URL: ",e.url]})]}),Eo=({label:e})=>J(le,{gap:1,children:[D(Ee,{}),D(Y,{dimColor:!0,children:e})]}),_m=({view:e})=>J(le,{flexDirection:"column",gap:1,children:[J(le,{gap:1,children:[D(Y,{color:"red",children:"\u2717"}),D(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(le,{flexDirection:"column",children:[D(Y,{children:"Choices:"}),D(ft,{lines:e.choices.map(t=>` ${t.label}`)})]})]}),Tm=({plan:e,applied:t})=>{let n=xo(e.dashboard.id);return t===null?J(le,{flexDirection:"column",gap:1,children:[D(Y,{color:"yellow",children:"Dry run: nothing was written."}),D(Ia,{plan:e}),e.warnings.length>0&&D(ft,{lines:pt(e.warnings),color:"yellow"}),J(le,{flexDirection:"column",children:[J(Y,{bold:!0,children:[e.method," ",e.path]}),D(Y,{children:JSON.stringify(e.body,null,2)})]})]}):J(le,{flexDirection:"column",gap:1,children:[J(le,{gap:1,children:[D(Y,{color:"green",children:"\u2713"}),J(Y,{bold:!0,children:[e.action==="create"?"Created":"Updated"," ",e.summary.blockName,' on "',e.dashboard.name,'"']})]}),J(le,{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&&D(ft,{lines:pt(t.warnings),color:"yellow"})]})},$a=({apiName:e,options:t,deps:n})=>{let r=vm(),[o,i]=Un({type:"loading",label:"Loading credentials\u2026"}),[s,a]=Un({credentials:null,credentialNotices:[],warnings:[],notices:[]}),[c]=Un(()=>Em(e,n,i,a)),[h]=Un(t);Pa(()=>{c.start(h)},[c,h]),Pa(()=>{(o.type==="done"||o.type==="error")&&r.exit()},[o,r]),Aa((m,b)=>{b.ctrl&&m==="c"&&o.type!=="done"&&o.type!=="error"&&(n.setExitCode(130),r.exit())});let p=m=>J(le,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[D(G,{}),s.credentials&&J(Y,{dimColor:!0,children:["Environment: ",s.credentials.environment," \xB7 Business:"," ",s.credentials.businessId]}),s.credentialNotices.length>0&&D(ft,{lines:s.credentialNotices,color:"yellow"}),s.warnings.length>0&&D(Y,{dimColor:!0,children:De(s.warnings)}),s.notices.length>0&&D(ft,{lines:s.notices}),m]});switch(o.type){case"loading":return p(D(Eo,{label:o.label}));case"packaging":return p(D(Eo,{label:"Packaging blocks\u2026"}));case"applying":return p(D(Eo,{label:`Pushing ${o.plan.summary.blockName} to "${o.plan.dashboard.name}"\u2026`}));case"environment-select":return p(D(Ne,{title:"Environment",items:o.choices.map(m=>({key:m.value,label:m.label})),onSelect:xt(o.choices,m=>{c.pickEnvironment(o,m)}),onCancel:c.cancel},"environment"));case"block-select":return p(D(Ne,{title:"Block to push",items:o.choices.map(m=>({key:m.value,label:m.label})),onSelect:xt(o.choices,m=>{c.pickBlock(o,m)}),onCancel:c.cancel},"block"));case"surface-select":return p(D(Ne,{title:"Where should the block go?",items:Ea,onSelect:xt(Ea,m=>{c.pickSurface(o,m.key)}),onCancel:c.cancel},"surface"));case"object-select":return p(D(Ne,{title:"Custom object",items:o.objects.map(m=>({key:m.id,label:m.objectName})),onSelect:xt(o.objects,m=>{c.pickObject(o,m)}),onCancel:()=>{i(o.back)},hint:Po},"object"));case"dashboard-select":return p(D(Ne,{title:o.title,items:o.rows.map(Sm),onSelect:xt(o.rows,m=>{c.pickDashboard(o,m)}),onCancel:()=>{i(o.back)},hint:Po},`dashboards-${o.surface}-${o.objectId??""}`));case"target-select":{let{back:m}=o;return p(J(Am,{children:[o.message!==null&&D(Y,{color:"yellow",children:o.message}),D(Ne,{title:o.title,items:o.choices.map(b=>Cm(b,o.matchedId)),onSelect:xt(o.choices,b=>{c.pickTarget(o,b)}),onCancel:m?()=>{i(m)}:c.cancel,...m&&{hint:Po}},`targets-${o.dashboardId}`)]}))}case"confirm":return o.kind==="drift"?p(J(le,{flexDirection:"column",gap:1,children:[D(Y,{color:"yellow",children:km}),D(Y,{dimColor:!0,children:o.message}),D(Ta,{prompt:"Type y to overwrite (y/N)",strict:!0,onAccept:()=>{c.acceptDrift(o)},onCancel:c.cancel},"drift")]})):p(J(le,{flexDirection:"column",gap:1,children:[D(Ia,{plan:o.plan}),o.plan.warnings.length>0&&D(ft,{lines:pt(o.plan.warnings),color:"yellow"}),o.plan.summary.isProduction&&D(Y,{color:"red",bold:!0,children:"PRODUCTION"}),D(Ta,{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 p(D(Tm,{plan:o.plan,applied:o.applied}));case"error":return p(D(_m,{view:o.view}))}};var Da=e=>`Error: ${e instanceof Error?e.message:String(e)}`,Dm=e=>e instanceof Nm?De(e.issues):Da(e),Na=e=>{console.error(Da(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 Ks(process.cwd(),n),{block:i,warnings:s}=o;s.length>0&&console.error(De(s));let a=JSON.stringify(Hs(o),null,2);console.log(a),r.copy&&console.error(await Pn(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(Dm(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=uo(process.cwd());if(!process.stdin.isTTY||!process.stdout.isTTY||r.json===!0){await va(n,r,o);return}let{waitUntilExit:i}=$m(Im($a,{...n!==void 0&&{apiName:n},options:r,deps:o}),{exitOnCtrlC:!1});await i()}catch(o){Na(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 xa(n,uo(process.cwd()))}catch(r){Na(r)}})}import{createElement as Fm}from"react";import{render as jm}from"ink";import{useEffect as Ba,useState as Kt}from"react";import{Box as Vt,Text as kt,useApp as Rm}from"ink";import{PluginValidationError as Om}from"@kizenapps/packager";function Ut(e){return e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}import{Box as _o,Text as Kn}from"ink";import{jsx as Oa,jsxs as Ht}from"react/jsx-runtime";var Vn=({issues:e})=>{let t=e.filter(n=>n.severity==="error").length;return Ht(_o,{flexDirection:"column",marginTop:1,children:[Ht(Kn,{color:"red",children:["\u2717 ",t," validation ",t===1?"error":"errors"]}),[...oo(e)].map(([n,r])=>Ht(_o,{flexDirection:"column",marginTop:1,children:[Oa(Kn,{bold:!0,children:n}),r.map((o,i)=>Oa(_o,{paddingLeft:2,children:Ht(Kn,{color:o.severity==="error"?"red":"yellow",children:[o.severity==="error"?"\u2717":"\u26A0"," ",o.message," ",Ht(Kn,{dimColor:!0,children:["(",o.rule,")"]})]})},`${o.rule}-${String(i)}`))]},n))]})};import{Fragment as Bm,jsx as Ye,jsxs as mt}from"react/jsx-runtime";var Fa=["creating-dir","reading-files","validating","minifying","packaging","writing-bundle"],Wn={"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"},ja=({outputDir:e,pluginDir:t})=>{let n=Rm(),[r,o]=Kt("creating-dir"),[i,s]=Kt(!1),[a,c]=Kt(null),[h,p]=Kt(null),[m,b]=Kt(null);Ba(()=>{$n(t,e,o).then(({bundleSize:v})=>{b(v),o("done")}).catch(v=>{v instanceof Om?c(v.issues):p(v instanceof Error?v.message:String(v)),s(!0),process.exitCode=1})},[e,t]),Ba(()=>{(r==="done"||i)&&n.exit()},[r,i,n]);let d=Fa.indexOf(r),l=r==="done";return mt(Vt,{flexDirection:"column",paddingY:1,paddingX:2,children:[Ye(G,{marginBottom:1}),mt(Vt,{flexDirection:"column",gap:0,children:[Fa.map((v,C)=>{let E=r===v,x=l||d>C;return Ye(Vt,{gap:1,children:i&&C===d?mt(kt,{color:"red",children:["\u2717 ",Wn[v]]}):x?mt(kt,{color:"green",children:["\u2713 ",Wn[v]]}):E?mt(Bm,{children:[Ye(Ee,{}),Ye(kt,{children:Wn[v]})]}):mt(kt,{dimColor:!0,children:[" ",Wn[v]]})},v)}),l&&m!==null&&Ye(Vt,{marginTop:1,gap:1,children:mt(kt,{color:"green",children:["\u2713 bundle \u2014 ",Ut(m)]})}),a!==null&&Ye(Vn,{issues:a}),h!==null&&Ye(Vt,{marginTop:1,borderStyle:"single",borderColor:"red",paddingX:1,children:Ye(kt,{color:"red",children:h})})]})]})};function La(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(Fm(ja,{outputDir:n,pluginDir:t}));await r()})}import{createElement as Ih}from"react";import{render as $h}from"ink";import{useCallback as Qn,useState as Ct}from"react";import{Box as V,Text as $,useApp as Sh,useInput as Ph}from"ink";import{join as er}from"path";import{access as vh,mkdir as Gn,writeFile as Do}from"fs/promises";import{dirname as xh,join as Re}from"path";var za=`{
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=`{
858
858
  "name": "Hello Frame",
859
859
  "api_name": "hello_frame",
860
860
  "title": "Hello Frame",
@@ -863,13 +863,13 @@ ${e.stderr}`),sa=e=>{let t=(e.stderr.trim()||e.stdout.trim()).replace(/\s+/g," "
863
863
  "height": 320,
864
864
  "width": 280
865
865
  }
866
- `;var Ma=`this.outputUI(\`
866
+ `;var Ja=`this.outputUI(\`
867
867
  <div class="hello-frame">
868
868
  <h2 class="hello-frame__title">Hello from a floating frame</h2>
869
869
  <p class="hello-frame__body">Edit src/floatingFrames/helloFrame/script.js to change this.</p>
870
870
  </div>
871
871
  \`);
872
- `;var Ua=`.hello-frame {
872
+ `;var Ya=`.hello-frame {
873
873
  padding: 16px;
874
874
  font-family: system-ui, sans-serif;
875
875
  }
@@ -883,18 +883,18 @@ ${e.stderr}`),sa=e=>{let t=(e.stderr.trim()||e.stdout.trim()).replace(/\s+/g," "
883
883
  margin: 0;
884
884
  color: #555;
885
885
  }
886
- `;var Ha=`{
886
+ `;var Xa=`{
887
887
  "name": "Hello Block",
888
888
  "api_name": "hello_block",
889
889
  "types": ["dashboards"]
890
890
  }
891
- `;var Ka=`this.outputUI(\`
891
+ `;var Za=`this.outputUI(\`
892
892
  <div class="hello-block">
893
893
  <h2 class="hello-block__title">Hello from a block</h2>
894
894
  <p class="hello-block__body">Edit src/blocks/helloBlock/script.js to change this.</p>
895
895
  </div>
896
896
  \`);
897
- `;var Va=`.hello-block {
897
+ `;var Qa=`.hello-block {
898
898
  padding: 16px;
899
899
  font-family: system-ui, sans-serif;
900
900
  background: #f8fafc;
@@ -910,25 +910,25 @@ ${e.stderr}`),sa=e=>{let t=(e.stderr.trim()||e.stdout.trim()).replace(/\s+/g," "
910
910
  margin: 0;
911
911
  color: #555;
912
912
  }
913
- `;var Wa=`{
913
+ `;var ec=`{
914
914
  "icon": "phone",
915
915
  "color": "#0ea5e9",
916
916
  "tooltip": "Hello adornment",
917
917
  "field_type": "phonenumber"
918
918
  }
919
- `;var qa=`this.showToast('Hello from a data adornment.', { variant: 'success' });
920
- `;var Ga=`{
919
+ `;var tc=`this.showToast('Hello from a data adornment.', { variant: 'success' });
920
+ `;var nc=`{
921
921
  "name": "Hello Page",
922
922
  "api_name": "hello_page"
923
923
  }
924
- `;var Ja=`this.outputUI(\`
924
+ `;var rc=`this.outputUI(\`
925
925
  <div class="hello-page">
926
926
  <p class="hello-page__loading">Loading\u2026</p>
927
927
  </div>
928
928
  \`);
929
929
 
930
930
  this.runEventScript('greet');
931
- `;var Ya=`.hello-page {
931
+ `;var oc=`.hello-page {
932
932
  padding: 24px;
933
933
  font-family: system-ui, sans-serif;
934
934
  }
@@ -966,7 +966,7 @@ this.runEventScript('greet');
966
966
  .hello-page__button:hover {
967
967
  background: #cbd5e1;
968
968
  }
969
- `;var Xa=`const tone = this.args?.formData?.tone?.[0] ?? 'plain';
969
+ `;var ic=`const tone = this.args?.formData?.tone?.[0] ?? 'plain';
970
970
 
971
971
  const greeting = tone === 'cheer' ? 'Hello, and good to see you!' : 'Hello from a routable page.';
972
972
 
@@ -989,33 +989,33 @@ this.outputUI(\`
989
989
  </div>
990
990
  </div>
991
991
  \`);
992
- `;var Za=`{
992
+ `;var sc=`{
993
993
  "api_name": "hello_toolbar_item",
994
994
  "label": "Hello Toolbar Item",
995
995
  "icon": "star",
996
996
  "color": "#0ea5e9"
997
997
  }
998
- `;var Qa=`this.showToast('Hello from a toolbar item.', { variant: 'success' });
999
- `;var ec=`{
998
+ `;var ac=`this.showToast('Hello from a toolbar item.', { variant: 'success' });
999
+ `;var cc=`{
1000
1000
  "api_name": "hello_object_settings_item",
1001
1001
  "label": "Hello Object Settings"
1002
1002
  }
1003
- `;var tc=`this.showToast('Hello from an object settings item.', { variant: 'success' });
1004
- `;var nc=`{
1003
+ `;var lc=`this.showToast('Hello from an object settings item.', { variant: 'success' });
1004
+ `;var dc=`{
1005
1005
  "name": "Hello Action",
1006
1006
  "api_name": "hello_action",
1007
1007
  "hint_object_name": "client_client"
1008
1008
  }
1009
- `;var rc=`this.showToast('Hello from a JS action.', { variant: 'success' });
1010
- `;var ae=["floatingFrame","block","dataAdornment","page","toolbarItem","objectSettingsItem","jsAction"],To={floatingFrame:"Floating frame",block:"Block",dataAdornment:"Data adornment",page:"Routable page",toolbarItem:"Toolbar item",objectSettingsItem:"Object settings item",jsAction:"JS action"},rh={floatingFrame:{directory:"floatingFrames",component:"helloFrame",files:{"config.json":za,"script.js":Ma,"styles.css":Ua}},block:{directory:"blocks",component:"helloBlock",files:{"config.json":Ha,"script.js":Ka,"styles.css":Va}},dataAdornment:{directory:"dataAdornments",component:"helloAdornment",files:{"config.json":Wa,"script.js":qa}},page:{directory:"pages",component:"helloPage",files:{"config.json":Ga,"script.js":Ja,"styles.css":Ya,"eventScripts/greet.js":Xa}},toolbarItem:{directory:"toolbarItems",component:"helloToolbarItem",files:{"config.json":Za,"script.js":Qa}},objectSettingsItem:{directory:"objectSettingsItems",component:"helloObjectSettingsItem",files:{"config.json":ec,"script.js":tc}},jsAction:{directory:"actions",component:"helloAction",files:{"config.json":nc,"script.js":rc}}};function oh(e,t="src"){let{directory:n,component:r,files:o}=rh[e];return Object.entries(o).map(([i,s])=>({path:`${t}/${n}/${r}/${i}`,content:s}))}function oc(e,t="src"){return[...new Set(e)].flatMap(n=>oh(n,t))}import{deflateSync as ih}from"zlib";var Io=512,sh=150,ah=26,$o=46,ic=.6,ch=$o*.55,lh=.55,dh=.47;function uh(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 ph(e){let t=uh(e);return{hue:t%360,quarterTurns:(t>>>16)%4}}function fh(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,h]=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((h+s)*255)]}function Wt(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 mh(e,t){let n=sh,r=$o,o=r*ic,i=ch,s=Wt(e,t,n,n,ah),a=Math.min(qn(e,t,0,-n-o,r),Wt(e,t+n+o/2,i,o/2+1,0)),c=Math.min(qn(e,t,n+o,0,r),Wt(e-n-o/2,t,o/2+1,i,0));s=Math.min(s,a,c);let h=Math.min(qn(e,t,0,n-o,r),Wt(e,t-n+o/2,i,o/2+1,0)),p=Math.min(qn(e,t,-n+o,0,r),Wt(e+n-o/2,t,o/2+1,i,0));return Math.max(s,-h,-p)}function hh(e){let t=Io,n=new Uint8Array(t*t*4),[r,o,i]=fh(e.hue,lh,dh),s=$o*(1+ic),a=(t-1)/2,c=s/2;for(let h=0;h<t;h+=1)for(let p=0;p<t;p+=1){let m=p-a,b=h-a;for(let C=0;C<e.quarterTurns;C+=1)[m,b]=[-b,m];let d=mh(m+c,b-c),l=Math.min(1,Math.max(0,.5-d));if(l<=0)continue;let v=(h*t+p)*4;n[v]=r,n[v+1]=o,n[v+2]=i,n[v+3]=Math.round(l*255)}return n}var gh=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 yh(e){let t=4294967295;for(let n of e)t=(gh[(t^n)&255]??0)^t>>>8;return(t^4294967295)>>>0}function Ao(e,t){let n=Buffer.from(e,"latin1"),r=Buffer.alloc(4);r.writeUInt32BE(t.length);let o=Buffer.alloc(4);return o.writeUInt32BE(yh(Buffer.concat([n,t]))),Buffer.concat([r,n,t,o])}var bh=Buffer.from([137,80,78,71,13,10,26,10]);function wh(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([bh,Ao("IHDR",r),Ao("IDAT",ih(i,{level:9})),Ao("IEND",new Uint8Array(0))])}function sc(e){return wh(Io,Io,hh(ph(e)))}var kh="src/thumbnail.png",Ch=["go","fmo"];async function Jn(e){try{return await vh(e),!0}catch{return!1}}async function Xe(e){return await Jn(Re(e,"kizen.json"))?"has-manifest":await Jn(Re(e,".kizenapp"))?"has-kizenapp":"ok"}async function ac(e,t){let n=Re(e,t);if(!await Jn(n))return n;for(let r=1;r<1e3;r++){let o=Re(e,`${t}-${String(r)}`);if(!await Jn(o))return o}throw new Error(`Could not find an available directory name for "${t}"`)}function Ro(e){let t=e.developerBusinessId.trim(),n=t!==""&&!Ch.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 No(e,t){let n=t.map(o=>({fullPath:Re(e,...o.path.split("/")),content:o.content})),r=new Set(n.map(o=>xh(o.fullPath)));await Promise.all([...r].map(o=>Gn(o,{recursive:!0}))),await Promise.all(n.map(o=>Do(o.fullPath,o.content,"utf-8")))}async function Yn(e){await Gn(e.targetDir,{recursive:!0});let t=Ro(e);await Do(Re(e.targetDir,"kizen.json"),JSON.stringify(t,null,2)+`
1011
- `,"utf-8"),await Gn(Re(e.targetDir,"src"),{recursive:!0}),await Gn(Re(e.targetDir,"releaseNotes"),{recursive:!0}),await Promise.all([No(e.targetDir,oc(e.artifacts??[])),No(e.targetDir,Dn()),No(e.targetDir,Rn(e.includeLib===!0?["src"]:[])),Do(Re(e.targetDir,...kh.split("/")),sc(e.apiName))]),Pe(e.targetDir)}var Ze=["name","apiName","externalLink","description","developerBusinessId"],Xn={name:"Name",apiName:"API name",externalLink:"External link",description:"Description",developerBusinessId:"Business ID"},Oo=["name","apiName","description"],Bo=/^[a-z_][a-z0-9_]+$/,Fo="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 cc(e){return{name:"",apiName:"",externalLink:"",description:"",developerBusinessId:e}}function lc(e,t){let n=t.trim();if(Oo.includes(e)&&!n)return`${Xn[e]} is required`;if(e==="apiName"&&!Bo.test(n))return`${Xn[e]} ${Fo}`}function dc(e,t){return e==="description"?t:t.trim()}function uc(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 ht=({text:e})=>I($,{dimColor:!0,children:e}),pc=({parentDir:e,defaultBusinessId:t,defaultEnvironment:n,includeLib:r=!1})=>{let o=Sh(),[i,s]=Ct({type:"target-select",cursor:0}),[a,c]=Ct("in-place"),[h,p]=Ct(()=>cc(t)),[m,b]=Ct(()=>[...ae]),[d,l]=Ct(""),[v,C]=Ct(e),E=Qn((w,f)=>{c(w),l(f.name),s({type:"field-entry",field:0,values:f})},[]),x=Qn(async w=>{let f=await Xe(w);if(f!=="ok"){s({type:"precheck-error",targetDir:w,reason:f});return}C(w),E("in-place",h)},[h,E]),y=Qn(async(w,f)=>{try{let u=await ac(e,w.apiName);C(u),s({type:"confirm",values:w,artifacts:f})}catch(u){s({type:"error",message:u instanceof Error?u.message:String(u)})}},[e]),P=Qn(async(w,f,u)=>{try{await Yn({targetDir:f,name:w.name,apiName:w.apiName,externalLink:w.externalLink,description:w.description,developerBusinessId:w.developerBusinessId,developerEnvironment:n,artifacts:u,includeLib:r}),s({type:"done",targetDir:f})}catch(g){s({type:"error",message:g instanceof Error?g.message:String(g)})}},[n,r]);if(Ph((w,f)=>{if(f.ctrl&&w==="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",h):f.escape&&o.exit();return}if(i.type==="precheck-error"){(f.return||f.escape)&&o.exit();return}if(i.type==="field-entry"){let{field:u,values:g}=i,k=Ze[u];if(!k)return;if(f.escape){o.exit();return}if(f.backspace||f.delete){l(S=>S.slice(0,-1));return}if(f.upArrow&&u>0){let S={...g,[k]:d},T=u-1,_=Ze[T];s({type:"field-entry",field:T,values:S}),p(S),l(_?S[_]:"");return}if(f.return||f.tab||f.downArrow){let S=lc(k,d);if(S!==void 0){s({type:"field-entry",field:u,values:g,fieldError:S});return}let T=dc(k,d),_={...g,[k]:T};p(_);let R=u+1;if(R>=Ze.length)l(""),s({type:"artifact-select",values:_,cursor:0,selected:m});else{let M=Ze[R],ee=M?_[M]:"",ce=M==="apiName"&&!ee?Zn(_.name):ee;s({type:"field-entry",field:R,values:_}),l(ce)}return}w&&!f.ctrl&&!f.meta&&l(S=>S+w);return}if(i.type==="artifact-select"){let{cursor:u,selected:g,values:k}=i;if(f.escape){let S=Ze.length-1,T=Ze[S];s({type:"field-entry",field:S,values:k}),l(T?k[T]:"");return}if(f.upArrow){s({...i,cursor:Math.max(0,u-1)});return}if(f.downArrow){s({...i,cursor:Math.min(ae.length-1,u+1)});return}if(w===" "){let S=ae[u];if(S){let T=uc(g,S);b(T),s({...i,selected:T})}return}if(w==="a"){b([...ae]),s({...i,selected:[...ae]});return}if(w==="n"){b([]),s({...i,selected:[]});return}f.return&&(a==="sub-dir"?(s({type:"resolving-target"}),y(k,g)):s({type:"confirm",values:k,artifacts:g}));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,v,i.artifacts));return}(i.type==="done"||i.type==="error")&&(f.return||f.escape)&&o.exit()}),i.type==="target-select"){let w=[{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($,{bold:!0,children:"Where should the new plugin live?"}),w.map((f,u)=>{let g=i.cursor===u;return B(V,{gap:2,children:[I($,{...g&&{color:"cyan"},children:g?"\u276F":" "}),I($,{bold:g,...g&&{color:"cyan"},children:f.label}),I($,{dimColor:!0,children:f.desc})]},f.label)})]}),I(ht,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(i.type==="precheck-error"){let{targetDir:w,reason:f}=i;return B(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(G,{}),I($,{color:"red",bold:!0,children:"Cannot create plugin"}),B(V,{flexDirection:"column",gap:0,children:[B($,{children:[w," 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(ht,{text:"Enter or Esc to exit"})]})}if(i.type==="field-entry"){let{field:w,fieldError:f}=i,u=a==="sub-dir"?`Target: sub-directory of ${e} (inferred from API name)`:`Target: ${v}`;return B(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(G,{}),B(V,{flexDirection:"column",gap:0,children:[I($,{bold:!0,children:"Plugin details"}),I($,{dimColor:!0,children:u})]}),f!==void 0&&B($,{color:"red",children:["Error: ",f]}),I(V,{flexDirection:"column",gap:0,children:Ze.map((g,k)=>{let S=w===k,T=S?d:h[g],_=Oo.includes(g),R=`${Xn[g]}${_?"":" (optional)"}`;return B(V,{gap:2,children:[I(V,{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"})]},g)})}),I(ht,{text:"Enter/Tab/\u2193 next \xB7 \u2191 previous \xB7 Backspace delete \xB7 Esc cancel"})]})}if(i.type==="artifact-select"){let{cursor:w,selected:f}=i;return B(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(G,{}),B(V,{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(V,{flexDirection:"column",gap:0,children:ae.map((u,g)=>{let k=w===g,S=f.includes(u);return B(V,{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:To[u]})]},u)})}),I(ht,{text:"\u2191\u2193 move \xB7 Space toggle \xB7 a all \xB7 n none \xB7 Enter continue \xB7 Esc back"})]})}if(i.type==="confirm"){let w=Ro({targetDir:v,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($,{bold:!0,children:"Ready to create"}),B($,{dimColor:!0,children:["Target: ",v]})]}),B(V,{flexDirection:"column",gap:0,children:[I($,{bold:!0,children:"kizen.json preview"}),I($,{children:JSON.stringify(w,null,2)})]}),B(V,{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:[" ",To[f]]},f))]}),B(V,{flexDirection:"column",gap:0,children:[I($,{dimColor:!0,children:"Also creates:"}),B($,{dimColor:!0,children:[" ",er(v,"src/")]}),B($,{dimColor:!0,children:[" ",er(v,"src/thumbnail.png")," (generated placeholder)"]}),B($,{dimColor:!0,children:[" ",er(v,"releaseNotes/")]}),B($,{dimColor:!0,children:[" ",er(v,".gitignore")," (adds .kizenapp/)"]})]}),I(ht,{text:"Enter to create \xB7 Esc to go back"})]})}return i.type==="resolving-target"?I(V,{paddingY:1,paddingX:2,children:I($,{dimColor:!0,children:"Finding available sub-directory\u2026"})}):i.type==="writing"?I(V,{paddingY:1,paddingX:2,children:I($,{dimColor:!0,children:"Creating plugin\u2026"})}):i.type==="done"?B(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(G,{}),B($,{color:"green",bold:!0,children:["Plugin created at ",i.targetDir]}),B(V,{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(ht,{text:"Enter or Esc to exit"})]}):B(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(G,{}),I($,{color:"red",bold:!0,children:"Failed to create plugin"}),I($,{children:i.message}),I(ht,{text:"Enter or Esc to exit"})]})};async function fc(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 Ie(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 Eh="A hello-world Kizen plugin.",mc=e=>Object.entries(e).some(([t,n])=>t!=="includeLib"&&n!==void 0);function _h(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 Th(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(!Bo.test(o))throw new Error(`api_name "${o}" is invalid: ${Fo}. Pass --api-name.`);let i=e.description?.trim(),s=e.businessId?.trim()??t.businessId,a=Ah(e,t);return{targetDir:n,name:r,apiName:o,externalLink:e.externalLink?.trim()??"",description:i===void 0||i===""?Eh:i,developerBusinessId:s,developerEnvironment:a,artifacts:_h(e.artifacts),includeLib:e.includeLib===!0}}function Ah(e,t){let n=e.environment?.trim();if(n!==void 0&&n!==""){if(!It(n))throw new Error(`Unknown environment "${n}". Valid environments: ${q.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 hc(e,t,n,r){let o;try{o=Th(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)}
1012
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.
1013
1013
  `),r.setExitCode(1);return}try{await r.createPlugin(o)}catch(a){r.writeStderr(`Error: ${a instanceof Error?a.message:String(a)}
1014
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}
1015
1015
  `),r.writeStdout(`Artifacts: ${s}
1016
1016
  `),r.writeStdout(`Thumbnail: src/thumbnail.png (generated placeholder; replace it before publishing)
1017
1017
  `),o.developerBusinessId.trim()===""&&r.writeStderr(`Warning: no developer_business_id configured, so this plugin cannot be preview-published yet.
1018
- `)}function gc(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: ${q.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 fc({listSessions:r.listSessions,readSession:r.readSession,loadGlobalCredentials:se,...t.environment!==void 0&&{requestedEnvironment:t.environment}});if(!process.stdin.isTTY||!process.stdout.isTTY||mc(t)){await hc(t,{businessId:o,environment:i},n,{precheckTargetDir:Xe,createPlugin:Yn,writeStdout:c=>{process.stdout.write(c)},writeStderr:c=>{process.stderr.write(c)},setExitCode:c=>{process.exitCode=c}});return}let{waitUntilExit:a}=$h(Ih(pc,{parentDir:n,defaultBusinessId:o,defaultEnvironment:i,includeLib:t.includeLib===!0}),{exitOnCtrlC:!1});await a()})}import{createElement as Wc}from"react";import{render as qc}from"ink";import{useCallback as St,useEffect as ar,useRef as Oe,useState as de}from"react";import{Box as ne,Text as F,useInput as Tg}from"ink";import{PluginValidationError as Ag}from"@kizenapps/packager";import{watch as Ig}from"fs";import{createServer as $g}from"http";import{join as Hc}from"path";import{WebSocketServer as Ng}from"ws";import{createReadStream as Tc,realpathSync as Jh}from"fs";import{access as Yh,readdir as Xh,readFile as Zh,realpath as Qh,stat as Ac}from"fs/promises";import{dirname as eg,extname as Ic,join as Xt,resolve as tg,sep as Vo}from"path";import{fileURLToPath as ng}from"url";var Nh=new Set(["set-cookie","strict-transport-security","content-security-policy","content-security-policy-report-only","x-frame-options","content-encoding","content-length"]);function tr(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.toLowerCase();Nh.has(o)||o.startsWith("access-control-")||(t[n]=r)}return t}var jo=10*1024*1024,Dh=6e4,Rh=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 Lo(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 yc(e){let t=tr(Object.fromEntries(e.headers)),n=await Lo(e,jo);return{status:e.status,headers:t,body:n}}function bc(e={}){let{onChange:t,enabled:n=!0}=e;if(!n)return{async get(s,a){return{response:await yc(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<Dh)return c.promise.then(p=>({response:p,fromCache:!0}));i(s)}if(r.size>=Rh){let p=r.keys().next().value;p!==void 0&&i(p)}let h=a().then(yc).catch(p=>{throw i(s),p});return r.set(s,{insertedAt:Date.now(),promise:h}),o(),h.then(p=>((p.status<200||p.status>=300)&&i(s),{response:p,fromCache:!1}))},clear(){r.clear(),o()}}}var zo={".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 Mo={prod:"https://plugin-wizard.kizen.com",dev:"https://plugin-wizard.kizen.dev",localDev:"http://localhost:9823"};function Gt(e){let t=process.env.PLUGIN_WIZARD_URL;return t!==void 0&&t!==""?t:e==="prod"?process.env.PLUGIN_WIZARD_URL_PROD||Mo.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!==""?Mo.localDev:Mo.dev}import{spawn as Cc}from"child_process";import{writeFile as xc,rm as Ho,mkdtemp as jh,access as Lh}from"fs/promises";import{join as Yt}from"path";import{tmpdir as zh}from"os";var wc=`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
1019
1019
  bcrypt
1020
1020
  boto3
1021
1021
  fpdf2
@@ -1033,7 +1033,7 @@ pytz
1033
1033
  requests
1034
1034
  sqlalchemy>=2.0,<2.1
1035
1035
  tzdata
1036
- `;import{AUTOMATION_SCRIPT_RUNTIMES as Mh,isSupportedScriptRuntime as Uh,scriptRuntimeToApiName as Sc}from"@kizenapps/packager";function Bh(e){return e==null||e.trim()===""?null:e}function Fh(e){return e==null?null:typeof e=="string"?Bh(e):typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):typeof e=="function"||typeof e=="symbol"?null:JSON.stringify(e)}function vc(e){return e?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Fh(n)])):{}}var Hh=`
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=`
1037
1037
  import sys, json, os, traceback
1038
1038
 
1039
1039
  # --- Inputs proxy (attribute access) ---
@@ -1193,29 +1193,29 @@ sys.stdout.write('\\n__KIZEN_RESULT_START__\\n')
1193
1193
  sys.stdout.write(json.dumps(result, ensure_ascii=False))
1194
1194
  sys.stdout.write('\\n__KIZEN_RESULT_END__\\n')
1195
1195
  sys.stdout.flush()
1196
- `.trim(),Kh=3e4,nr=Yt(process.cwd(),".kizenapp","venv"),Vh=Mh.map(Sc),Pc=Ni(wc);if(Pc.length===0)throw new Error("python-requirements.txt bundled no packages \u2014 check the build output");var Jt=null;function kc(e,t,n){return new Promise((r,o)=>{let i=Cc(e,t,{stdio:["ignore","pipe","pipe"]}),s=(c,h)=>{let p=[],m="";return c.on("data",b=>{m+=b.toString("utf-8");let d=m.indexOf(`
1197
- `);for(;d>=0;){let l=m.slice(0,d).replace(/\r$/,"");m=m.slice(d+1),p.push(l),n?.(l,h),d=m.indexOf(`
1198
- `)}}),c.on("end",()=>{if(m.length>0){let b=m.replace(/\r$/,"");p.push(b),n?.(b,h)}}),p},a=s(i.stderr,"stderr");s(i.stdout,"stdout"),i.on("error",o),i.on("close",c=>{if(c===0)r();else{let h=a.slice(-10).join(`
1199
- `).trim(),p=h.length>0?`: ${h}`:"";o(new Error(`${e} exited with code ${String(c)}${p}`))}})})}var Uo=null;function Wh(e,t){if(Jt)return t&&Uo?.add(t),Jt;let n=new Set;t&&n.add(t),Uo=n;let r=i=>{for(let s of n)s(i)},o=Yt(nr,"bin","python");return Jt=(async()=>{try{let i=!1;try{await Lh(o);let s=await yn(o);i=s!==null&&Ir(s,Dt)}catch{i=!1}if(!i){await Ho(nr,{recursive:!0,force:!0}).catch(()=>{});let s=await Ri(e);await kc(s,["-m","venv",nr])}return r({kind:"start"}),await kc(o,["-m","pip","install","--disable-pip-version-check",...Pc],(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}),Jt=null,await Ho(nr,{recursive:!0,force:!0}).catch(()=>{}),i}finally{Uo=null}})(),Jt}function qh(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 Gh(e){return{success:!1,outputValues:{},logs:[],stdout:"",stderr:"",error:e,exitCode:1,durationMs:0}}async function Ec(e){let t=e.timeout??Kh;if(!Uh(e.scriptRuntime))return Gh(`Unsupported runtime "${e.scriptRuntime}". Supported runtimes: ${Vh.join(", ")}. Update the step's config.json "runtime" field (e.g. "python 3.13").`);let r=await Wh(Sc(e.scriptRuntime),e.onInstallProgress),o=Date.now(),i;try{i=await jh(Yt(zh(),"kizen-step-"));let s=Yt(i,"wrapper.py"),a=Yt(i,"script.py");await Promise.all([xc(s,Hh,"utf-8"),xc(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:h,stdout:p,stderr:m}=await new Promise(C=>{let E=[],x=[],y=!1,P=Cc(r,[s],{env:c,cwd:i,stdio:["ignore","pipe","pipe"]}),w=setTimeout(()=>{P.kill("SIGKILL")},t);P.stdout.on("data",u=>{E.push(u)}),P.stderr.on("data",u=>{x.push(u)});let f=u=>{y||(y=!0,clearTimeout(w),C({exitCode:u??1,stdout:Buffer.concat(E).toString("utf-8"),stderr:Buffer.concat(x).toString("utf-8")}))};P.on("close",f),P.on("error",u=>{y||(y=!0,clearTimeout(w),C({exitCode:1,stdout:"",stderr:u.message}))})}),b=Date.now()-o,{userStdout:d,result:l}=qh(p);if(l){let C={success:l.success,outputValues:l.outputValues,logs:l.logs,stdout:d,stderr:m,exitCode:h,durationMs:b};return l.error!==null&&(C.error=l.error),l.httpRequests&&(C.httpRequests=l.httpRequests),C}let v={success:!1,outputValues:{},logs:[],stdout:d,stderr:m,exitCode:h,durationMs:b};return h!==0&&(v.error=`Process exited with code ${String(h)}`),v}finally{i&&Ho(i,{recursive:!0,force:!0})}}var _c=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 $c,CRYPTO_VERSION as Nc,DEFAULT_AUTOMATION_RUNTIME as rg,deserializeEnvelope as og,encrypt as ig,scriptRuntimeToApiName as sg,serializeEnvelope as ag}from"@kizenapps/packager";function Ko(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 cg=2*1024*1024,lg=new Set([".DS_Store",".gitignore"]);function dg(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 Bc=["kizen.com","kizen.dev"];function ug(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:Bc.some(r=>n===r||n.endsWith("."+r))}function pg(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let n=t.hostname.toLowerCase();return Bc.some(r=>n===r||n.endsWith("."+r))}function fg(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 Dc(e,t){if(t.includes("\0"))return null;let n=t.replace(/^\/+/,""),r=tg(e,n);if(r!==e&&!r.startsWith(e+Vo))return null;try{let o=await Qh(r);return o!==e&&!o.startsWith(e+Vo)?null:o}catch{return null}}function Rc(e,t){let n=t===e?"":t.slice(e.length+1);return n===""?!1:n.split(Vo).some(o=>An.has(o))}function Fc(){let e=ng(import.meta.url);return Xt(eg(e),"viewer")}function Oc(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 Wo(e){try{return await Yh(e),!0}catch{return!1}}function jc(e,t,n,r,o,i,s,a,c,h,p){let m=bc({onChange:a,enabled:p}),b=Jh(h);return(d,l)=>{(async()=>{let v=d.url??"/";try{if(!dg(d.headers.host)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Forbidden"}));return}if((d.method==="POST"||d.method==="PATCH"||d.method==="DELETE")&&!fg(d.headers.origin)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Forbidden"}));return}if(t(`Received request: ${v}`),v==="/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(v==="/api/credential-profiles"&&d.method==="GET"){let f=await Ve();l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({profiles:f,active:o.current}));return}if(v==="/api/credentials/switch"&&d.method==="POST"){let f=[];for await(let S of d)f.push(S);let g=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}").profile,k=g===void 0||g===""?await se():await Ae(g);if(k!==null){r.current=k,o.current=g??void 0;let S=o.current,T=await Se(i);await Ge(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(v==="/api/bundle"){let f=Xt(process.cwd(),".kizenapp","bundle.json");try{let u=await Zh(f,"utf-8");l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(u)}catch{l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end("{}")}return}if(v==="/api/last-path"&&d.method==="POST"){let f=[];for await(let g of d)f.push(g);let u=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}");if(typeof u.path=="string"){c.current=u.path;let g=await Se(i);await Ge(i,{...g,lastPath:u.path})}l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end('{"ok":true}');return}if(v==="/api/encryption-target"&&d.method==="GET"){let u=(await Se(i)).encryptionTarget==="dev"?"dev":"prod";l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({target:u}));return}if(v==="/api/encryption-target"&&d.method==="POST"){let f=[];for await(let S of d)f.push(S);let u=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}"),g=u!==null&&typeof u=="object"?u:{};if(g.target!=="dev"&&g.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 Se(i);await Ge(i,{...k,encryptionTarget:g.target}),l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end('{"ok":true}');return}if(v==="/api/execute-step"&&d.method==="POST"){let f=[];for await(let S of d)f.push(S);let u=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}");if(typeof u.script!="string"){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing required field: script"}));return}let g={script:u.script,scriptRuntime:u.scriptRuntime??sg(rg),inputs:vc(u.inputs),secrets:u.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 u.timeout=="number"&&u.timeout>0&&(g.timeout=Math.min(u.timeout,300*1e3));let k=await Ec(g);l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify(k));return}if(v==="/api/proxy-cache/clear"){m.clear(),n({kind:"info",message:"Proxy cache cleared"}),l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end('{"ok":true}');return}if(v==="/api/local/encrypt"&&d.method==="POST"){let f=[];for await(let g of d)f.push(g);let u=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}");if(typeof u.publicKeyPem!="string"||typeof u.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 g=ig(u.value,u.publicKeyPem),k=ag(g);l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify(k))}catch(g){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:g.message}))}return}if(v==="/api/local/validate"&&d.method==="POST"){let f=[];for await(let _ of d)f.push(_);let u=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}");if(typeof u.value!="string"){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing required field: value"}));return}let g,k;try{g=og(u.value)}catch(_){k=_.message}if(k!==void 0||g===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(Nc),actual:String(g.v),pass:g.v===Nc},{label:"Algorithm",expected:$c,actual:g.alg,pass:g.alg===$c},{label:"Wrapped key",expected:"384 bytes (RSA-3072)",actual:`${String(S(g.k))} bytes`,pass:S(g.k)===384},{label:"IV",expected:"12 bytes",actual:`${String(S(g.iv))} bytes`,pass:S(g.iv)===12},{label:"Auth tag",expected:"16 bytes",actual:`${String(S(g.tag))} bytes`,pass:S(g.tag)===16},{label:"Ciphertext",expected:"\u2265 1 byte",actual:`${String(S(g.ct))} bytes`,pass:S(g.ct)>=1}];l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({valid:T.every(_=>_.pass),checks:T}));return}if(v.startsWith("/api/wizard")){let f=d.headers["x-encryption-target"],g=(Array.isArray(f)?f[0]:f)==="dev"?"dev":"prod",k=Gt(g);if(!ug(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=v.slice(11)||"/",T=`${k}${S}`,_=d.method??"GET",R=[];for await(let tt of d)R.push(tt);let{host:M,"x-encryption-target":ee,...ce}=d.headers,ye=R.length>0?Buffer.concat(R):void 0,be=ye&&ye.length>0?ye:void 0,fe;try{fe=await fetch(T,{method:_,headers:ce,...be!==void 0&&{body:be}})}catch(tt){let fr=tt.code==="ECONNREFUSED"?`plugin-wizard is not running at ${k}`:`Failed to reach plugin-wizard: ${tt.message}`;l.writeHead(503,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:fr}));return}let ue=tr(Object.fromEntries(fe.headers)),Pt=await fe.arrayBuffer();l.writeHead(fe.status,ue),l.end(Buffer.from(Pt));return}if(v.startsWith("/api/proxy")){let f=d.headers["x-proxy-target"];if(typeof f!="string"){l.writeHead(400),l.end("Missing x-proxy-target header");return}if(!pg(f)){l.writeHead(400),l.end("Invalid proxy target");return}let u=v.slice(10)||"/",g=`${f}${u}`,k=d.method??"GET",S=[];for await(let fe of d)S.push(fe);let{host:T,"x-proxy-target":_,...R}=d.headers;if(k==="GET"){let fe=`GET::${g}`,{response:ue,fromCache:Pt}=await m.get(fe,()=>fetch(g,{method:"GET",headers:R}));n({kind:"request",method:"GET",status:ue.status,upstreamStatus:Oc(u,ue.headers,ue.body),fromCache:Pt,url:u}),l.writeHead(ue.status,ue.headers),l.end(ue.body);return}let M=S.length>0?Buffer.concat(S):void 0,ee=M&&M.length>0?M:void 0,ce=await fetch(g,{method:k,headers:R,...ee!==void 0&&{body:ee}}),ye=tr(Object.fromEntries(ce.headers)),be=await Lo(ce,jo);n({kind:"request",method:k,status:ce.status,upstreamStatus:Oc(u,ye,be),fromCache:!1,url:u}),l.writeHead(ce.status,ye),l.end(be);return}if(v.startsWith("/api/source/tree")&&d.method==="GET"){let u=new URL(v,"http://localhost").searchParams.get("path")??"",g=await Dc(b,u);if(g===null){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Invalid path"}));return}if(Rc(b,g)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Path is excluded"}));return}try{let k=await Xh(g,{withFileTypes:!0}),S=await Promise.all(k.filter(_=>_.isDirectory()?!An.has(_.name):_.isFile()?!lg.has(_.name):!1).map(async _=>{let R=_.isDirectory()?"dir":"file",M={name:_.name,kind:R};if(R==="file")try{let ee=await Ac(Xt(g,_.name));M.size=ee.size}catch{}return M}));S.sort((_,R)=>_.kind!==R.kind?_.kind==="dir"?-1:1:_.name.localeCompare(R.name));let T=g===b?"":g.slice(b.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 (${u}): ${S}`),l.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Not found"}))}return}if(v.startsWith("/api/source/file")&&d.method==="GET"){let u=new URL(v,"http://localhost").searchParams.get("path")??"";if(u===""){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing path"}));return}let g=await Dc(b,u);if(g===null){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Invalid path"}));return}if(Rc(b,g)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Path is excluded"}));return}try{let k=await Ac(g);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>cg){l.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"File too large",size:k.size}));return}let S=Ic(g).toLowerCase(),T=zo[S],_=_c.has(S),R=T??(_?"text/plain; charset=utf-8":"application/octet-stream");l.writeHead(200,{"Content-Type":R,"Content-Length":String(k.size)}),Tc(g).pipe(l)}catch(k){let S=k instanceof Error?k.message:String(k);t(`source/file failed (${u}): ${S}`),l.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Not found"}))}return}let x=Xt(e,v==="/"?"/index.html":v),y=await Wo(x)?x:Xt(e,"index.html"),P=Ic(y),w=zo[P]??"application/octet-stream";l.writeHead(200,{"Content-Type":w}),Tc(y).pipe(l)}catch(C){if(v.startsWith("/api/proxy")){let E=v.slice(10)||"/",x=d.method??"GET";C instanceof qt?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 ${v}: ${C instanceof Error?C.message:String(C)}`});l.headersSent||(l.writeHead(502),l.end("Bad Gateway"))}})()}}import{launch as mg}from"chrome-launcher";import{createRequire as hg}from"module";import{mkdirSync as gg}from"fs";import{readFile as yg}from"fs/promises";import{dirname as bg,join as wg}from"path";import{fileURLToPath as vg}from"url";var Lc=hg(import.meta.url)("chrome-remote-interface"),xg=new Set(["content-security-policy","content-security-policy-report-only","x-frame-options"]),Mc=["kizen.dev","kizen.com"];function zc(e){try{let{hostname:t}=new URL(e);return Mc.some(n=>t===n||t.endsWith("."+n))}catch{return!1}}async function kg(e){try{let t=wg(bg(vg(import.meta.url)),"viewer","icon.png"),n=await yg(t);await e.Browser.setDockTile({image:n.toString("base64")})}catch{}}async function Uc(e){gg(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,n=await mg({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,h=!1,p=y=>{e.debugLog?.(y)},m=y=>{e.verbose&&e.debugLog?.(y)},b=()=>{i!==null&&(clearInterval(i),i=null)},d=y=>y==="chrome://new-tab-page/"||y==="chrome://newtab/",l=async y=>{b(),s=null,await kg(y),await y.Fetch.enable({patterns:Mc.flatMap(w=>[{urlPattern:`*://${w}/*`,requestStage:"Response"},{urlPattern:`*://*.${w}/*`,requestStage:"Response"}])}),y.on("Fetch.requestPaused",w=>{(async()=>{let f=w,{requestId:u,request:g,responseHeaders:k,responseStatusCode:S}=f,T=g.url;m(`Fetch ${String(S??"?")} ${T}`);let _=[],R=!1;for(let M of k??[])if(!xg.has(M.name.toLowerCase()))if(M.name.toLowerCase()==="set-cookie"&&zc(T)){let ee=M.value.split(`
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
1200
  `).map(ce=>/SameSite=/i.test(ce)?ce.replace(/SameSite=\w+/i,"SameSite=None"):ce+"; SameSite=None; Secure").join(`
1201
- `);_.push({name:M.name,value:ee}),R=!0}else _.push(M);R&&m(` rewrote Set-Cookie SameSite on ${T}`);try{let{body:M,base64Encoded:ee}=await y.Fetch.getResponseBody({requestId:u});await y.Fetch.fulfillRequest({requestId:u,responseCode:S??200,responseHeaders:_,body:M,...ee&&{base64Encoded:!0}})}catch(M){m(` fulfillRequest failed (${M.message}), falling through`);try{await y.Fetch.continueRequest({requestId:u})}catch(ee){m(` continueRequest also failed (${ee.message})`)}}})()}),i=setInterval(()=>{(async()=>{try{let{cookies:w}=await y.Network.getAllCookies(),f=0;for(let u of w){if(!zc(`https://${u.domain??""}`)||u.sameSite==="None")continue;let g=u.domain??"",k=g.startsWith(".")?g.slice(1):g;await y.Network.setCookie({url:`https://${k}`,name:u.name,value:u.value,domain:g,path:u.path??"/",secure:!0,...u.httpOnly!==void 0&&{httpOnly:u.httpOnly},...u.expirationDate!==void 0&&{expires:u.expirationDate},sameSite:"None"}),f++}f>0&&m(`cookie-patch cycle: updated ${String(f)} cookie(s) to SameSite=None`)}catch(w){m(`cookie-patch cycle failed: ${w.message}`)}})()},2e3),await y.Target.setDiscoverTargets({discover:!0});let P=w=>{if(w.type==="page"){if(d(w.url)){p(`closed stray new-tab-page target ${w.targetId}`),s!==null&&y.Target.activateTarget({targetId:s}).catch(()=>{}),y.Target.closeTarget({targetId:w.targetId}).catch(()=>{});return}s===null&&(s=w.targetId,p(`captured main target ${w.targetId} (${w.url})`))}};y.on("Target.targetCreated",w=>{let{targetInfo:f}=w;m(`target +${f.type} ${f.targetId} ${f.url}`),P(f)}),y.on("Target.targetInfoChanged",w=>{let{targetInfo:f}=w;m(`target ~${f.type} ${f.targetId} ${f.url}`),P(f)}),y.on("disconnect",()=>{h||o!==y||(p("CDP disconnected"),o=null,b(),v())})},v=()=>{if(h||a!==null)return;let y=Math.min(1e3*2**c,1e4),P=c+1;c++,p(`CDP reconnect scheduled in ${String(y)}ms (attempt #${String(P)})`),a=setTimeout(()=>{a=null,(async()=>{let w;try{w=await Lc({port:r})}catch{p(`CDP reconnect attempt #${String(P)} failed`),v();return}if(h){try{await w.close()}catch{}return}o=w;try{await l(w),p(`CDP reconnected after ${String(P)} attempt(s)`),c=0}catch{o===w&&(o=null);try{await w.close()}catch{}p(`CDP reconnect attempt #${String(P)} failed during setup`),v()}})()},y)},C=30,E=300;for(let y=0;y<C;y++){await new Promise(P=>setTimeout(P,E)),p(`CDP connect attempt ${String(y+1)}/${String(C)}`);try{let P=await Lc({port:r});o=P,e.path&&P.send("Page.navigate",{url:`${t}${e.path}`});try{await l(P),p("CDP connected")}catch{o===P&&(o=null);try{await P.close()}catch{}p("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 p(P),e.onWarn?.(P),{kill:()=>{n.kill()}}}}}return o?{kill:()=>{if(p("CDP kill requested \u2014 tearing down"),h=!0,a!==null&&(clearTimeout(a),a=null),b(),o!==null){try{o.close()}catch{}o=null}n.kill()}}:{kill:()=>{n.kill()}}}import{useCallback as Cg,useState as Sg}from"react";function rr(e){let[t,n]=Sg([]),r=Cg(o=>{n(i=>[...i,`${new Date().toLocaleTimeString()}: ${o}`].slice(-e))},[e]);return[t,r]}import{useCallback as or,useEffect as qo,useState as ir}from"react";import{Box as Q,Text as z,useInput as Pg}from"ink";import{jsx as N,jsxs as te}from"react/jsx-runtime";var Qe=["apiKey","userId","businessId"],Eg={apiKey:"API Key",userId:"User ID",businessId:"Business ID"},Zt=({text:e})=>N(z,{dimColor:!0,children:e}),sr=({initialMode:e,showProfileManager:t,onComplete:n,onCancel:r})=>{let[o,i]=ir(e==="global"&&!t?{type:"loading"}:e==="global"&&t?{type:"profile-loading"}:{type:"mode-select",cursor:0}),[s,a]=ir(""),[c,h]=ir(null),[p,m]=ir(void 0),b=or(w=>{if(w==="local"){n({mode:"local",credentials:null});return}i({type:"profile-loading"})},[n]),d=or(async w=>{if(w===null){i({type:"profile-loading"});let g=await Ve();i({type:"name-entry",nameBuffer:"",existingProfiles:g});return}m(w.isDefault?void 0:w.name),i({type:"loading"});let f=w.isDefault?await se():await Ae(w.name),u=f?Math.max(0,q.indexOf(f.environment)):0;i({type:"creds-entry",field:0,values:f??{},envCursor:u})},[]),l=or(async(w,f)=>{let u=q[f]??"go",g={...At(w),environment:u};i({type:"saving"});try{await gi(p??He,g),n({mode:"global",credentials:g,...p!==void 0&&{profileName:p}})}catch(k){h(k instanceof Error?k.message:String(k)),i({type:"creds-entry",field:0,values:w,envCursor:f})}},[n,p]);Pg((w,f)=>{if(f.ctrl&&w==="c"&&process.exit(0),f.escape){if((o.type==="creds-entry"||o.type==="name-entry")&&e==="global"&&t){i({type:"profile-loading"}),v();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 u=o.cursor===0?"global":"local";b(u)}return}if(o.type==="profile-select"){let{profiles:u,cursor:g}=o,k=u.length,S=u.length+1;if(f.upArrow)i({...o,cursor:(g-1+S)%S});else if(f.downArrow)i({...o,cursor:(g+1)%S});else if(f.return)if(g===k)i({type:"name-entry",nameBuffer:"",existingProfiles:u});else{let T=u[g]??u[0];T&&d(T)}return}if(o.type==="name-entry"){let{nameBuffer:u,existingProfiles:g}=o;if(f.backspace||f.delete)i({type:"name-entry",nameBuffer:u.slice(0,-1),existingProfiles:g});else if(f.return){let k=u.trim();if(!k){i({...o,nameError:"Name cannot be empty"});return}if(k===He){i({...o,nameError:`"${He}" is reserved`});return}if(g.some(S=>S.name===k)){i({...o,nameError:`Profile "${k}" already exists`});return}m(k),i({type:"creds-entry",field:0,values:{},envCursor:0}),a("")}else w&&!f.ctrl&&!f.meta&&i({type:"name-entry",nameBuffer:u+w,existingProfiles:g});return}if(o.type==="creds-entry"){let{field:u,values:g,envCursor:k}=o;if(u===Qe.length){f.leftArrow?i({...o,envCursor:(k-1+q.length)%q.length}):f.rightArrow?i({...o,envCursor:(k+1)%q.length}):f.upArrow?(i({...o,field:u-1}),a(g[Qe[u-1]]??"")):f.return&&l(g,k);return}let T=Qe[u];if(!T)return;if(f.backspace||f.delete)a(_=>_.slice(0,-1));else if(f.upArrow&&u>0){let _={...g,[T]:s},R=u-1;i({...o,field:R,values:_}),a(_[Qe[R]]??"")}else if(f.return||f.tab||f.downArrow){let _={...g,[T]:s},R=u+1;i({...o,field:R,values:_}),R<Qe.length?a(_[Qe[R]]??""):a("")}else w&&!f.ctrl&&!f.meta&&a(_=>_+w)}});let v=or(async()=>{let w=await Ve();i({type:"profile-select",profiles:w,cursor:0})},[]);if(qo(()=>{o.type==="profile-loading"&&v()},[o.type,v]),qo(()=>{e==="global"&&!t&&(async()=>{let w=await se(),f=w?Math.max(0,q.indexOf(w.environment)):0;i({type:"creds-entry",field:0,values:w??{},envCursor:f})})()},[]),qo(()=>{o.type==="creds-entry"&&o.field===0&&a(o.values.apiKey??"")},[o.type]),o.type==="loading"||o.type==="saving"||o.type==="profile-loading"){let w=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(z,{dimColor:!0,children:w})})}if(o.type==="done")return null;if(o.type==="mode-select")return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[N(G,{}),te(Q,{flexDirection:"column",gap:0,children:[N(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((f,u)=>{let g=o.cursor===u;return te(Q,{gap:2,children:[N(z,{...g&&{color:"cyan"},children:g?"\u276F":" "}),N(z,{bold:g,...g&&{color:"cyan"},children:f.label}),N(z,{dimColor:!0,children:f.desc})]},f.mode)})]}),N(Zt,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]});if(o.type==="profile-select"){let{profiles:w,cursor:f}=o,u=w.length;return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[N(G,{}),te(Q,{flexDirection:"column",gap:0,children:[N(z,{bold:!0,children:"Credential profiles"}),w.map((g,k)=>{let S=f===k;return te(Q,{gap:2,children:[N(z,{...S&&{color:"cyan"},children:S?"\u276F":" "}),N(z,{bold:S,...S&&{color:"cyan"},children:g.isDefault?"Default":g.name}),N(z,{dimColor:!0,children:g.path})]},g.name)}),te(Q,{gap:2,children:[N(z,{...f===u&&{color:"cyan"},children:f===u?"\u276F":" "}),N(z,{bold:f===u,...f===u&&{color:"cyan"},children:"+ Add new profile"})]})]}),N(Zt,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(o.type==="name-entry"){let{nameBuffer:w,nameError:f}=o;return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[N(G,{}),N(Q,{flexDirection:"column",gap:0,children:N(z,{bold:!0,children:"New credential profile"})}),f&&te(z,{color:"red",children:["Error: ",f]}),te(Q,{gap:2,children:[N(Q,{width:12,children:N(z,{bold:!0,color:"cyan",children:"Profile name"})}),N(z,{color:"cyan",children:">"}),N(z,{children:w}),N(z,{color:"cyan",children:"\u2588"})]}),N(Zt,{text:"Type a name \xB7 Enter to confirm \xB7 Esc to go back"})]})}let{field:C,values:E,envCursor:x}=o,y=C===Qe.length,P=p??He;return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[N(G,{}),te(Q,{flexDirection:"column",gap:0,children:[N(z,{bold:!0,children:p!==void 0?`Profile: ${p}`:"Global credentials"}),te(z,{dimColor:!0,children:["Saved to:"," ",p!==void 0?`~/.kizenappbuilder/${p}.json`:Ue]})]}),c&&te(z,{color:"red",children:["Error: ",c]}),te(Q,{flexDirection:"column",gap:0,children:[Qe.map((w,f)=>{let u=C===f,g=u?s:E[w]??"";return te(Q,{gap:2,children:[N(Q,{width:12,children:N(z,{bold:u,...u&&{color:"cyan"},children:Eg[w]})}),N(z,{...u&&{color:"cyan"},children:">"}),N(z,{children:g}),u&&N(z,{color:"cyan",children:"\u2588"})]},w)}),te(Q,{gap:2,children:[N(Q,{width:12,children:N(z,{bold:y,...y&&{color:"cyan"},children:"Environment"})}),N(z,{...y&&{color:"cyan"},children:">"}),N(Q,{gap:1,children:q.map((w,f)=>{let u=f===x;return y?N(z,{bold:u,...u&&{color:"cyan"},children:u?`[${w}]`:w},w):N(z,{dimColor:!u,bold:u,children:w},w)})})]})]}),y?N(Zt,{text:"\u2190\u2192 to select \xB7 \u2191\u2193 to move \xB7 Enter to save \xB7 Esc to cancel"}):N(Zt,{text:"\u2191\u2193 to move \xB7 Backspace to delete \xB7 Esc to cancel"}),te(z,{dimColor:!0,children:["Profile: ",P]})]})};import{jsx as j,jsxs as X}from"react/jsx-runtime";var Dg=[".kizenapp",".git"],Kc=({port:e,pluginDir:t,outputDir:n,credentials:r,credentialMode:o,activeCredentialProfile:i,lastPath:s,debug:a=!1,verbose:c=!1,autoViewer:h=!0,cacheEnabled:p=!0})=>{let m=Oe(r),b=Oe(i),d=Oe(s),[l,v]=de("main"),[C,E]=de(o),[x,y]=de("starting"),[P,w]=de(null),[f,u]=rr(50),[g,k]=rr(50),[S,T]=rr(50),[_,R]=de([]),[M,ee]=de("pending"),[ce,ye]=de(null),[be,fe]=de(null),[ue,Pt]=de(null),[tt,fr]=de(null),[mr,hr]=de(0),[Xo,Il]=de(0),[$l,Nl]=de(0),[gr,Dl]=de(0),yr=Oe(!1),Zo=Oe(!1),en=Oe(null),Et=Oe(null),Be=Oe(new Set),tn=Oe([]),me=St(A=>{let H=JSON.stringify(A);if(Be.current.size===0){tn.current=[...tn.current,H].slice(-50);return}let Fe=!1;for(let we of Be.current)if(we.readyState===1)try{we.send(H)}catch{Be.current.delete(we),Fe=!0}Fe&&hr(Be.current.size)},[]),nn=u,br=St(()=>{en.current?.kill(),en.current=null,Uc({port:e,userDataDir:Hc(n,".chrome"),broadcast:me,onWarn:A=>{u(`\u26A0 ${A}`)},...d.current!==void 0&&{path:d.current},...a&&{debugLog:T},...c&&{verbose:!0}}).then(A=>{en.current=A})},[e,n,me,a,c,T,u]);ar(()=>{let A=()=>{en.current?.kill()};return process.on("exit",A),()=>{process.off("exit",A)}},[]),Tg((A,H)=>{(A==="q"||H.ctrl&&A==="c")&&process.exit(0),A==="c"&&v("editing"),A==="v"&&br()},{isActive:l==="main"}),ar(()=>{x!=="running"||Zo.current||!h||(Zo.current=!0,br())},[x,h,br]);let Rl=St(A=>{m.current=A.credentials,b.current=A.profileName,v("main"),E(A.mode);let H=A.profileName;Ge(n,{credentialMode:A.mode,...H!==void 0&&{activeCredentialProfile:H}}),me({type:"credentials-updated",credentials:A.credentials})},[n,me]),Qo=St(A=>{R(H=>[...H,`${new Date().toLocaleTimeString()}: ${Ko(A)}`].slice(-50)),A.kind==="request"&&(A.fromCache?Nl(H=>H+1):Dl(H=>H+1)),me({type:"proxy-log",entry:A})},[me]),nt=St(A=>{k(A),me({type:"log",message:A})},[k,me]),wr=St(()=>{yr.current||(yr.current=!0,ee("building"),ye(null),fe(null),nt("Build started"),$n(t,n).then(({bundleSize:A})=>{nt(`Build finished \u2014 bundle: ${Ut(A)}`),ee("done"),Pt(new Date),fr(A),nt("Notifying viewers to reload"),me({type:"rebuild"})}).catch(A=>{A instanceof Ag?(fe(A.issues),ye(null)):(ye(A instanceof Error?A.message:String(A)),fe(null)),ee("error")}).finally(()=>{yr.current=!1}))},[t,n,nt,me]);if(ar(()=>{wr();let A=Ig(t,{recursive:!0},(H,Fe)=>{if(!Fe)return;let we=Fe.replace(/\\/g,"/");Dg.some(rn=>we.startsWith(rn))||(nt(`File change detected: ${Fe}`),Et.current!==null&&clearTimeout(Et.current),Et.current=setTimeout(wr,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,wr,nt]),ar(()=>{let A=Fc();Wo(Hc(A,"index.html")).then(H=>{if(!H){w("Viewer not built. Run 'pnpm build:viewer' first."),y("error");return}let Fe=jc(A,nn,Qo,m,b,n,me,Il,d,t,p),we=$g(Fe),rn=new Ng({server:we});return rn.on("connection",rt=>{for(let Bl of tn.current)rt.readyState===1&&rt.send(Bl);tn.current=[],nn("Viewer connected for live reload"),Be.current.add(rt),hr(Be.current.size),rt.on("close",()=>{Be.current.delete(rt),hr(Be.current.size)})}),we.listen(e,"127.0.0.1",()=>{y("running"),nn(`Server started on 127.0.0.1:${String(e)}`)}),we.on("error",rt=>{w(rt.message),y("error")}),()=>{rn.close(),we.close()}})},[e,nn,Qo,me,n,t,p]),l==="editing")return j(sr,{...C!==void 0&&{initialMode:C},showProfileManager:C==="global",onComplete:Rl,onCancel:()=>{v("main")}});let vr=ue!==null?Math.round((Date.now()-ue.getTime())/1e3):null,Ol=vr===null?"":vr<5?" (just now)":` (${String(vr)}s ago)`,ei=be?.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"}),ue!==null&&X(F,{dimColor:!0,children:["at ",ue.toLocaleTimeString(),Ol]}),tt!==null&&X(F,{dimColor:!0,children:["\xB7 bundle: ",Ut(tt)]})]}),M==="error"&&(be!==null?X(F,{color:"red",children:["\u2717 ",ei," validation ",ei===1?"error":"errors"]}):X(F,{color:"red",children:["\u2717 ",ce??"unknown error"]}))]}),be!==null&&j(Vn,{issues:be}),j(ne,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:g.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 ",mr," viewer",mr!==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:p?`\u25CF ${String(Xo)} key${Xo!==1?"s":""} in the network cache \xB7 ${String($l)} hit \xB7 ${String(gr)} miss`:`\u25CF network cache disabled \xB7 ${String(gr)} request${gr!==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:["] ",mr===0?"open viewer":"relaunch viewer"]})]})]})};async function Vc(e){return new Promise(t=>{let n=null,r=i=>{n?.(),t(i)},{unmount:o}=qc(Wc(sr,{...e!==void 0&&{initialMode:e},onComplete:r}),{exitOnCtrlC:!1});n=o})}function Gc(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 Ke(t.credentials);else{let l=await Se(o);if(l.credentialMode==="local")s="local";else if(l.credentialMode==="global"){if(s="global",a=l.activeCredentialProfile,a?(i=await Ae(a),i||(i=await se(),a=void 0)):i=await se(),!i){let v=await Vc("global");i=v.credentials,a=v.profileName}}else{let v=await Vc();i=v.credentials,s=v.mode,a=v.profileName;let C=v.profileName;await Ge(o,{credentialMode:v.mode,...C!==void 0&&{activeCredentialProfile:C}})}}let h=t.verbose===!0,p=h||t.debug===!0,m=t.viewer!==!1,b=t.cache!==!1,{waitUntilExit:d}=qc(Wc(Kc,{port:n,pluginDir:r,outputDir:o,credentials:i,...s!==void 0&&{credentialMode:s},...a!==void 0&&{activeCredentialProfile:a},...c!==void 0&&{lastPath:c},debug:p,verbose:h,autoViewer:m,cacheEnabled:b}),{exitOnCtrlC:!1});await d()})}import{createElement as Wg}from"react";import{render as qg}from"ink";import{useCallback as lr,useEffect as Zc,useState as dr}from"react";import{Box as _e,Text as U,useApp as zg,useInput as Mg}from"ink";import{encrypt as Rg,serializeEnvelope as Og}from"@kizenapps/packager";function Bg(e){let t=e;return t.code==="ECONNREFUSED"||t.cause?.code==="ECONNREFUSED"}function Jc(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 Yc(e,t,n){try{return await fetch(`${e}${t}`,n)}catch(r){throw new Error(Bg(r)?`Plugin-wizard is not running at ${e}`:`Failed to reach plugin-wizard: ${r.message}${sn()==="unavailable"?` ${on}`:""}`)}}async function Xc(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 Fg(e,t,n){let r=Gt(e.stage),o=await Yc(r,"/get-public-key",{method:"POST",headers:Jc(t),body:JSON.stringify({api_name:n})}),i=await Xc(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=Rg(t,e),r=Og(n);if(typeof r.value!="string")throw new Error("Unexpected serialized envelope shape from @kizenapps/packager");return r.value}async function Lg(e,t,n,r){let o=Gt(e.stage),i=await Yc(o,"/encrypt",{method:"POST",headers:Jc(t),body:JSON.stringify({api_name:n,value:r})}),s=await Xc(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 cr(e,t,n,r,o){if(e.isRemote)return o?.("encrypting"),Lg(e,t,n,r);o?.("fetching-key");let i=await Fg(e,t,n);return o?.("encrypting"),jg(i,r)}import{Fragment as ur,jsx as L,jsxs as re}from"react/jsx-runtime";var Go=({text:e})=>L(U,{dimColor:!0,children:e}),Qc=({ctx:e,stageDefaulted:t,credentialsPath:n,initialApiName:r,defaultApiName:o,initialValue:i,onDone:s})=>{let a=zg(),[c,h]=dr({type:"loading"}),[p,m]=dr(null),[b,d]=dr(r??""),[l,v]=dr(i??""),C=lr(u=>{process.exitCode=1,h({type:"error",message:u instanceof Error?u.message:String(u)})},[]),E=lr(async(u,g,k)=>{try{let S=await cr(e,u,g,k,R=>{h(R==="fetching-key"?{type:"fetching-key"}:{type:"encrypting"})}),T=JSON.stringify({encrypted:!0,value:S},null,2);s?.(S);let _=await Pn(T);h({type:"done",envelope:T,copied:_})}catch(S){C(S)}},[e,C,s]),x=lr((u,g,k)=>{if(g.trim()===""){h({type:"api-name-entry",buffer:o??""});return}if(k===""){h({type:"value-entry",buffer:""});return}E(u,g.trim(),k)},[o,E]),y=lr(async u=>{try{h({type:"loading"});let g=u.isDefault?await se():await Ae(u.name);if(g===null)throw new Error(`Could not load credential profile: ${u.name}`);m(g),x(g,b,l)}catch(g){C(g)}},[b,l,x,C]);Zc(()=>{(async()=>{try{if(n!==void 0){let k;try{k=await Ke(n)}catch(S){throw new Error(`Could not load credentials from ${n}: ${S instanceof Error?S.message:String(S)}`)}m(k),x(k,b,l);return}let u=await Ve();if(u.length===0)throw new Error("No credential profiles found. Create ~/.kizenappbuilder/credentials.json first.");let[g]=u;if(u.length===1&&g!==void 0){let k=g.isDefault?await se():await Ae(g.name);if(k===null)throw new Error(`Could not load credential profile: ${g.name}`);m(k),x(k,b,l);return}h({type:"profile-select",profiles:u,cursor:0})}catch(u){C(u)}})()},[]),Zc(()=>{(c.type==="done"||c.type==="error")&&a.exit()},[c,a]),Mg((u,g)=>{if(g.ctrl&&u==="c"){process.exitCode=130,a.exit();return}if(c.type==="profile-select"){let{profiles:k,cursor:S}=c;if(g.upArrow)h({...c,cursor:(S-1+k.length)%k.length});else if(g.downArrow)h({...c,cursor:(S+1)%k.length});else if(g.return){let T=k[S];T!==void 0&&y(T)}return}if(c.type==="api-name-entry"){let{buffer:k}=c;if(g.backspace||g.delete)h({type:"api-name-entry",buffer:k.slice(0,-1)});else if(g.return){let S=k.trim();if(S===""){h({type:"api-name-entry",buffer:k,error:"api_name cannot be empty"});return}d(S),p?x(p,S,l):C(new Error("Internal error: credentials were not loaded"))}else u&&!g.ctrl&&!g.meta&&h({type:"api-name-entry",buffer:k+u});return}if(c.type==="value-entry"){let{buffer:k}=c;if(g.backspace||g.delete)h({type:"value-entry",buffer:k.slice(0,-1)});else if(g.return){if(k===""){h({type:"value-entry",buffer:k,error:"secret cannot be empty"});return}v(k),p?x(p,b,k):C(new Error("Internal error: credentials were not loaded"))}else u&&!g.ctrl&&!g.meta&&h({type:"value-entry",buffer:k+u});return}});let P=e.isRemote?"remote Kizen API":"on-machine",w=t===!0?`${e.stage} (default)`:e.stage,f=u=>re(_e,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[L(G,{}),re(U,{dimColor:!0,children:["Mode: ",P," Stage: ",w]}),u]});if(c.type==="loading")return f(re(_e,{gap:1,children:[L(Ee,{}),L(U,{dimColor:!0,children:"Loading credentials\u2026"})]}));if(c.type==="profile-select"){let{profiles:u,cursor:g}=c;return f(re(ur,{children:[L(U,{bold:!0,children:"Credential profile"}),L(_e,{flexDirection:"column",children:u.map((k,S)=>{let T=g===S;return re(_e,{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(Go,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]}))}return c.type==="api-name-entry"?f(re(ur,{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(Go,{text:"Type the api_name \xB7 Enter to confirm \xB7 Ctrl+C to quit"})]})):c.type==="value-entry"?f(re(ur,{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(Go,{text:"Input hidden \xB7 Enter to encrypt \xB7 Ctrl+C to quit"})]})):c.type==="fetching-key"?f(re(_e,{gap:1,children:[L(Ee,{}),re(U,{children:["Fetching ",e.stage," public key for ",L(U,{bold:!0,children:b}),"\u2026"]})]})):c.type==="encrypting"?f(re(_e,{gap:1,children:[L(Ee,{}),L(U,{children:"Encrypting\u2026"})]})):c.type==="error"?f(re(_e,{gap:1,children:[L(U,{color:"red",children:"\u2717"}),L(U,{color:"red",children:c.message})]})):f(re(ur,{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 Ug,writeFile as Hg}from"fs/promises";import{join as Kg}from"path";function el(e){return{encrypted:!0,value:e}}function tl(e){return JSON.stringify(el(e))}async function Jo(e,t){await Hg(e,`${JSON.stringify(el(t),null,2)}
1202
- `,"utf-8")}var Vg="prod";function nl(e){return e==="dev"||e==="prod"}function rl(e){return`Error: --stage must be "dev" or "prod" (got: "${e}")`}function ol(e){return{stage:e==="dev"||e==="prod"?e:Vg,wasDefaulted:e===void 0}}function il(e){return`No --stage given; defaulting to ${e} encryption keys (pass --stage dev to override)
1203
- `}async function sl(e=process.cwd()){try{let t=await Ug(Kg(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 al(e){return e.replace(/[\r\n]+$/,"")}async function cl(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}async function ll(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(il(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=al(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(`${tl(c)}
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)}
1205
1205
  `),t.out!==void 0)try{await o.writeEnvelopeFile(t.out,c),o.writeStderr(`Wrote encrypted envelope to ${t.out}
1206
- `)}catch(h){o.writeStderr(`Error writing ${t.out}: ${h instanceof Error?h.message:String(h)}
1207
- `),o.setExitCode(1)}}function dl(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&&!nl(t.stage)&&(console.error(rl(t.stage)),process.exit(1));let r=t.apiName===void 0?await sl():{},{stage:o,wasDefaulted:i}=ol(t.stage),s={isRemote:t.remote===!0,stage:o};if(!process.stdin.isTTY||!process.stdout.isTTY){try{await ll(s,t,r,i,{loadCredentialsFromFile:Ke,loadGlobalCredentials:se,encryptSecret:cr,readStdin:cl,stdinIsTTY:()=>process.stdin.isTTY,writeStdout:h=>{process.stdout.write(h)},writeStderr:h=>{process.stderr.write(h)},writeEnvelopeFile:Jo,setExitCode:h=>{process.exitCode=h}})}catch(h){console.error(`Error: ${h instanceof Error?h.message:String(h)}`),process.exit(1)}return}let a,{waitUntilExit:c}=qg(Wg(Qc,{ctx:s,stageDefaulted:i,onDone:h=>{a=h},...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 Jo(t.out,a),process.stderr.write(`Wrote encrypted envelope to ${t.out}
1208
- `)}catch(h){console.error(`Error writing ${t.out}: ${h instanceof Error?h.message:String(h)}`),process.exitCode=1}})}var Gg=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"]),Jg=[...Gg].sort(),Yg=new Set(["kizen-k","form-entity"]),ul=[...Jg,...[...Yg].sort()];function pl(e){e.command("icons").description("List all valid icon names accepted by toolbar items, pages, and adornments").action(()=>{for(let t of ul)console.log(t)})}import{mkdir as oy,writeFile as Cl,readFile as iy}from"fs/promises";import{join as pr}from"path";var Xg=new Set(["developer_business_id"]);function Zg(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 ml(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 hl(e){return[...e.children.values()].sort((t,n)=>t.isFile!==n.isFile?t.isFile?1:-1:t.name.localeCompare(n.name))}function Yo(e){return"file-"+e.replace(/[^a-zA-Z0-9]/g,"-")}function Te(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function gl(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t).toLowerCase():""}var Qg={".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 ey(e){return Qg[gl(e)]??""}function fl(e){let t=[...e.matchAll(/`+/g)].reduce((n,r)=>Math.max(n,r[0].length),0);return"`".repeat(Math.max(3,t+1))}function yl(e,t=""){let n=hl(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
- ${yl(r,t+a)}`}).join(`
1210
- `)}var ty=/(^|\/)licen[cs]e(\.md|\.txt)?$/i;function bl(e){return e.filter(t=>t.path!=="kizen.json"&&t.path!=="plugin-report.html"&&!ty.test(t.path))}function wl(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!Xg.has(t)).map(([t,n])=>[t,t==="services"?Zg(n):n]))}var ny={".png":"image/png",".svg":"image/svg+xml",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function vl(e){return`<ul>${hl(e).map(r=>r.isFile?`<li class="tf"><a href="#${Yo(r.filePath)}" data-id="${Yo(r.filePath)}">${Te(r.name)}</a></li>`:`<li class="td"><span class="dn">${Te(r.name)}/</span>${vl(r)}</li>`).join("")}</ul>`}function ry(e){let t;return e.base64Image!==void 0?t=`<img src="data:${ny[gl(e.path)]??"image/png"};base64,${e.base64Image}" alt="${Te(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>${Te(e.content)}</code></pre>`,`<section id="${Yo(e.path)}"><h2 class="fp">${Te(e.path)}</h2><div class="fb">${t}</div></section>`}function xl(e,t){let n=wl(e),r=typeof e.name=="string"?e.name:"Plugin",o=typeof e.version=="string"?e.version:"",i=typeof e.description=="string"?e.description:"",s=bl(t),a=[];a.push(`# ${r}${o?` v${o}`:""}`),i&&a.push("",i);let c=JSON.stringify(n,null,2),h=fl(c);a.push("","## Configuration (`kizen.json`)","",`${h}json`,c,h),a.push("","## File Tree","","```",yl(ml(s)),"```"),a.push("","## Files");for(let p of s)if(a.push("",`### \`${p.path}\``,""),p.base64Image!==void 0)a.push(`[Image file: ${p.path}]`);else if(p.binaryData!==void 0)a.push(`[Binary file: ${String(p.binaryData.length)} bytes]`);else{let m=fl(p.content);a.push(`${m}${ey(p.path)}`,p.content,m)}return a.join(`
1206
+ `)}catch(g){o.writeStderr(`Error writing ${t.out}: ${g instanceof Error?g.message:String(g)}
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(`
1211
1211
  `)+`
1212
- `}function kl(e,t){let n=wl(e),r=typeof e.name=="string"?e.name:"Plugin",o=typeof e.version=="string"?e.version:"",i=typeof e.description=="string"?e.description:"",s=bl(t),a=vl(ml(s)),c=s.map(ry).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(`
1213
1213
  `);return`<!DOCTYPE html>
1214
1214
  <html lang="en">
1215
1215
  <head>
1216
1216
  <meta charset="UTF-8">
1217
1217
  <meta name="viewport" content="width=device-width,initial-scale=1">
1218
- <title>${Te(r)} \u2014 Plugin Report</title>
1218
+ <title>${Ae(r)} \u2014 Plugin Report</title>
1219
1219
  <style>
1220
1220
  *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
1221
1221
  :root{
@@ -1252,8 +1252,8 @@ img{border:1px solid var(--bd);border-radius:4px}
1252
1252
  </head>
1253
1253
  <body>
1254
1254
  <header>
1255
- <h1>${Te(r)}${o?` <span style="color:var(--mu);font-size:.8em">v${Te(o)}</span>`:""}</h1>
1256
- ${i?`<p>${Te(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>`:""}
1257
1257
  </header>
1258
1258
  <div class="layout">
1259
1259
  <nav>
@@ -1261,7 +1261,7 @@ img{border:1px solid var(--bd);border-radius:4px}
1261
1261
  ${a}
1262
1262
  </nav>
1263
1263
  <main>
1264
- <section id="config"><h2 class="fp">kizen.json \u2014 Plugin Configuration</h2><div class="fb"><pre><code>${Te(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>
1265
1265
  ${c}
1266
1266
  </main>
1267
1267
  </div>
@@ -1275,9 +1275,9 @@ ${c}
1275
1275
  })();
1276
1276
  </script>
1277
1277
  </body>
1278
- </html>`}var Sl=pr(ge,"examples");function Pl(e){e.command("report").description("Generate a self-contained HTML report of the plugin").option("-o, --output <path>",`output file path (default: ${Sl}/<api_name>.html)`).action(async t=>{let n=process.cwd(),r;try{let c=await iy(pr(n,"kizen.json"),"utf-8"),h=JSON.parse(c);r=Array.isArray(h)?h[0]:h}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??pr(Sl,`${o}.html`),s=i.replace(/\.html$/,".md"),a=await In(n,{detectBinaryByContent:!0});await oy(pr(i,".."),{recursive:!0}),await Promise.all([Cl(i,kl(r,a),"utf-8"),Cl(s,xl(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:
1279
1279
  ${i}
1280
- ${s}`)})}function El(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 ua(process.cwd(),n,da(t))})}async function _l(e,t={}){if(await Xe(e)!=="has-manifest")throw new Error(`No kizen.json found in ${e}`);let n=t.dryRun===!0,r=await Bn(e,Dn(),{dryRun:n});return n||Pe(e),{files:r}}function Tl(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 _l(n,{dryRun:r});for(let i of o.files)console.log(Fn(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(`
1281
1281
  Dry run \u2014 no files and no .gitignore entries were written.`);return}console.log(`
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 uy(){let e=cy(ay(ly(import.meta.url)),"..","package.json");return JSON.parse(sy(e,"utf-8")).version}function Al(){let e=new dy,t=uy();return e.name("appbuilder").description("Kizen plugin app builder").version(t),gc(e),El(e,t),Tl(e),La(e),Gc(e),dl(e),Pl(e),pl(e),Ra(e),is(e),Ui(e),e}ti({env:process.env,http:py});Al().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();
1283
1283
  //# sourceMappingURL=index.js.map