@kizenapps/cli 1.16.0-f8f99f7 → 1.17.0-d9d38e3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -19
- package/dist/index.js +106 -89
- package/dist/index.js.map +1 -1
- package/dist/viewer/assets/{AppDetailPage-CGrukEIj.js → AppDetailPage-CW7hiOlY.js} +1 -1
- package/dist/viewer/assets/{IconReferencePage-BxPfyqlV.js → IconReferencePage-CIq1PaNE.js} +1 -1
- package/dist/viewer/assets/{SandboxPage-D3Qdh_0M.js → SandboxPage-B-KoJu8j.js} +1 -1
- package/dist/viewer/assets/{blockDimensions-BhWxVVcK.js → blockDimensions-BH7Y8TUQ.js} +1 -1
- package/dist/viewer/assets/{index-w3fkjFhR.js → index-CiPj7LCo.js} +2 -2
- package/dist/viewer/assets/{validIcons-D8mhuO5s.js → validIcons-Bfz0UVU1.js} +1 -1
- package/dist/viewer/index.html +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import*as Kh from"http";var Xt="If you're behind a proxy, upgrade Node to 24.14+ or set NODE_USE_ENV_PROXY=1 on a Node version that supports it.",ll=["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy"],dl=e=>e!==void 0&&e!=="",Re="not-configured";function jo({env:e,http:t}){return Re==="applied"||(ll.some(n=>dl(e[n]))?e.NODE_USE_ENV_PROXY==="1"?Re="already-set":typeof t.setGlobalProxyFromEnv!="function"?Re="unavailable":(t.setGlobalProxyFromEnv(e),Re="applied"):Re="not-configured"),Re}var Zt=()=>Re;import{readFileSync as Lh}from"fs";import{dirname as Mh,join as zh}from"path";import{fileURLToPath as Uh}from"url";import{Command as Hh}from"commander";var dr={go:"https://app.go.kizen.com/api",fmo:"https://app.fmo.kizen.com/api",staging:"https://staging.kizen.com/api",integration:"https://integration.kizen.dev/api",test1:"https://test1.kizen.dev/api"},ut=e=>new URL(dr[e]).origin,Lo={go:"https://go.kizen.com",fmo:"https://fmo.kizen.com",staging:"https://v2.staging.kizen.com",integration:"https://v2.integration.kizen.dev",test1:"https://test1.kizen.dev"},ul=["go","fmo"];function ur(e){return ul.includes(e)}import{mkdir as Mo,readFile as pl,readdir as fl,writeFile as zo}from"fs/promises";import{homedir as ml}from"os";import{dirname as hl,join as Qt}from"path";var W=["go","fmo","staging","integration","test1"];function kt(e){return typeof e=="string"?e.trim():""}function Ct(e){return{apiKey:kt(e.apiKey),userId:kt(e.userId),businessId:kt(e.businessId)}}var Se=Qt(ml(),".kizenappbuilder"),Oe=Qt(Se,"credentials.json"),Be="credentials",St=e=>W.includes(e),gl=e=>`Unknown --env "${e}". Use one of: ${W.join(", ")}.`,et=e=>St(e)?{environment:e}:{message:gl(e)};function yl(e){return typeof e=="string"?e.trim():e}function bl(e){return St(e)?"explicit":e==null||e===""?"missing":"invalid"}function wl(e){if(typeof e!="object"||e===null)throw new Error("Credentials must be a JSON object");let t=e,n=yl(t.environment);return{credentials:{...Ct(t),environment:St(n)?n:"go"},environmentSource:bl(n)}}async function en(e){let t=await pl(e,"utf-8");return wl(JSON.parse(t))}async function Fe(e){return(await en(e)).credentials}async function oe(){try{return await Fe(Oe)}catch{return null}}async function vl(e){await Mo(hl(Oe),{recursive:!0,mode:448}),await zo(Oe,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function Uo(e){return Qt(Se,`${e}.json`)}async function je(){let e=[{name:Be,path:Oe,isDefault:!0}];try{let t=await fl(Se);for(let n of t){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);r!==Be&&e.push({name:r,path:Qt(Se,n),isDefault:!1})}}catch{}return e}async function Ho(e,t){if(e===Be){await vl(t);return}await Mo(Se,{recursive:!0,mode:448}),await zo(Uo(e),JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}async function Pe(e){try{return await Fe(Uo(e))}catch{return null}}async function Vo(){let e=await je(),t=await Promise.all(e.map(n=>en(n.path).then(()=>!0,()=>!1)));return e.filter((n,r)=>t[r]===!0)}import{posix as xl}from"path";var O=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tn=(e,t)=>e?.code===t,nn=e=>e instanceof Error&&tn(e,"ENOENT"),tt=async e=>{try{return await e}catch(t){if(tn(t,"ENOENT"))return;throw t}},ie=e=>typeof e=="string"&&e!==""?e:void 0,Le=e=>e instanceof Error?e.message:String(e),Pt=e=>{let t=e;return t.cause?.code??t.code??t.cause?.message??t.message??String(e)},rn=e=>{let t=xl.normalize(e.trim().replaceAll("\\","/")).replace(/\/+$/,"");return t==="."?"":t};import{spawn as _l}from"child_process";import{createHash as Tl,randomBytes as Al}from"crypto";import{createServer as Il}from"http";import{platform as Wo}from"process";var kl=["M22.8852 7.03547C22.8112 7.5787 22.5356 8.0447 22.1428 8.36712C21.336 7.31995 20.1615 6.55456 18.7791 6.28228C18.6674 6.2606 18.5549 6.24164 18.4404 6.22606C17.0417 6.03708 15.6939 6.37914 14.6 7.09712C14.4293 7.20955 14.2646 7.33079 14.1068 7.46084C13.9084 7.62408 13.655 7.70942 13.3997 7.68233C13.3841 7.68098 13.3686 7.67894 13.353 7.67624C12.698 7.58073 12.2245 6.98196 12.2842 6.32291C12.2855 6.3087 12.2869 6.29447 12.2889 6.28092C12.3181 6.04522 12.442 5.83117 12.6249 5.67946C12.8246 5.51418 13.0326 5.35907 13.2473 5.21412C14.8059 4.16358 16.7417 3.65828 18.7513 3.92989C19.665 4.05317 20.5212 4.32749 21.2981 4.72441C21.5392 4.84701 21.7722 4.9818 21.9978 5.12743C22.6183 5.52908 22.9712 6.24503 22.8919 6.97926C22.8899 6.99822 22.8878 7.01719 22.8852 7.03547Z","M23.2333 16.1537C22.797 16.4857 22.2721 16.6198 21.7662 16.571C21.9369 15.2604 21.6476 13.8887 20.8626 12.7197C20.7996 12.6255 20.7325 12.532 20.6628 12.4406C19.8073 11.3183 18.6125 10.6077 17.331 10.3429C17.1304 10.3016 16.9286 10.2711 16.7254 10.2515C16.4694 10.2271 16.2297 10.1078 16.0684 9.90806C16.0582 9.89587 16.0488 9.88368 16.0393 9.87082C15.6437 9.34044 15.7325 8.58183 16.2411 8.15849C16.2519 8.14969 16.2628 8.1402 16.2743 8.13208C16.462 7.98645 16.701 7.9221 16.9375 7.94446C17.1955 7.96884 17.4522 8.00609 17.7069 8.05554C19.5526 8.41385 21.2785 9.42512 22.5072 11.0372C23.0659 11.7701 23.4771 12.5693 23.746 13.399C23.8293 13.6564 23.8991 13.9165 23.9553 14.1786C24.1097 14.9006 23.853 15.6566 23.2773 16.1199C23.2624 16.1314 23.2475 16.1436 23.2326 16.1551L23.2333 16.1537Z","M16.9978 22.8858C16.4545 22.8127 15.9878 22.5363 15.6654 22.1441C16.7132 21.3381 17.4793 20.1636 17.7516 18.7825C17.7732 18.6708 17.7923 18.5583 17.8078 18.4438C17.9968 17.0458 17.6547 15.6986 16.936 14.6053C16.8236 14.4347 16.7024 14.2701 16.5724 14.113C16.4091 13.9152 16.3231 13.6612 16.3508 13.4058C16.3523 13.3903 16.3543 13.3746 16.357 13.3591C16.4525 12.7041 17.0519 12.2313 17.7109 12.2909C17.7252 12.2922 17.7394 12.2937 17.7537 12.2957C17.9893 12.3248 18.204 12.4487 18.3551 12.6316C18.5203 12.8315 18.6755 13.0387 18.8204 13.2534C19.8716 14.8113 20.377 16.7458 20.1053 18.7541C19.982 19.6671 19.7071 20.5233 19.3108 21.2994C19.1882 21.5406 19.0534 21.7736 18.9078 21.9985C18.5061 22.6183 17.7895 22.9712 17.0553 22.8919C17.0364 22.8899 17.0173 22.8878 16.9991 22.8852L16.9978 22.8858Z","M7.86115 23.2332C7.52858 22.797 7.39447 22.2728 7.44391 21.7668C8.75523 21.9375 10.1275 21.6483 11.2973 20.864C11.3915 20.801 11.4849 20.7339 11.5764 20.6641C12.6994 19.8093 13.4105 18.6145 13.6754 17.3337C13.7167 17.1339 13.7472 16.9313 13.7668 16.7281C13.7912 16.4727 13.9104 16.233 14.1103 16.0718C14.1225 16.0617 14.1353 16.0522 14.1475 16.0427C14.6785 15.6471 15.4371 15.7365 15.8605 16.2445C15.8693 16.2554 15.8788 16.2662 15.8869 16.2777C16.0332 16.4653 16.0969 16.7037 16.0745 16.9408C16.0501 17.1989 16.0129 17.4556 15.9635 17.7096C15.6044 19.554 14.5932 21.2792 12.9798 22.5072C12.2462 23.0652 11.4469 23.4771 10.6165 23.7453C10.3592 23.8286 10.0991 23.8984 9.83693 23.9546C9.11422 24.1091 8.35831 23.8524 7.89502 23.2773C7.88282 23.2624 7.87131 23.2475 7.85979 23.2326L7.86115 23.2332Z","M1.13386 17.0634C1.20769 16.5202 1.48336 16.0542 1.87621 15.7318C2.68292 16.779 3.85742 17.5443 5.23986 17.8166C5.35163 17.8382 5.46406 17.8572 5.57853 17.8728C6.97722 18.0618 8.32512 17.7198 9.41902 17.0018C9.58971 16.8894 9.75427 16.7681 9.9121 16.638C10.1105 16.4748 10.3639 16.3895 10.6192 16.4166C10.6348 16.4179 10.6504 16.4199 10.666 16.4226C11.321 16.5181 11.7945 17.1169 11.7348 17.7759C11.7335 17.7902 11.7322 17.8044 11.73 17.818C11.701 18.0537 11.577 18.2677 11.3941 18.4194C11.1943 18.5847 10.9863 18.7398 10.7717 18.8847C9.21311 19.9354 7.27728 20.4406 5.26764 20.169C4.35391 20.0458 3.49776 19.7714 2.72085 19.3745C2.47972 19.2518 2.24672 19.1171 2.02117 18.9714C1.40073 18.5699 1.04784 17.8539 1.12709 17.1197C1.12911 17.1007 1.13115 17.0817 1.13386 17.0634Z","M0.766739 7.8774C1.20294 7.5455 1.72788 7.41139 2.23385 7.46016C2.06316 8.77081 2.35238 10.1424 3.13741 11.3115C3.20041 11.4057 3.26746 11.4991 3.33722 11.5906C4.1927 12.7129 5.38752 13.4234 6.66903 13.6883C6.86953 13.7295 7.07138 13.7601 7.27457 13.7797C7.5306 13.8041 7.77038 13.9233 7.93158 14.1231C7.94175 14.1353 7.95123 14.1475 7.96071 14.1604C8.35628 14.6907 8.26755 15.4493 7.75887 15.8726C7.74803 15.8815 7.73719 15.891 7.72567 15.899C7.53805 16.0447 7.29895 16.1091 7.06256 16.0867C6.8045 16.0623 6.54779 16.0251 6.29311 15.9756C4.44738 15.6173 2.72153 14.606 1.49284 12.994C0.934041 12.2611 0.522899 11.4618 0.253997 10.6321C0.170684 10.3747 0.100919 10.1147 0.0447005 9.85248C-0.109732 9.13047 0.146978 8.37457 0.722712 7.91127C0.737614 7.89975 0.752515 7.88756 0.767417 7.87605L0.766739 7.8774Z","M7.0287 1.14538C7.57192 1.21853 8.03861 1.49487 8.36102 1.88705C7.31318 2.69308 6.54711 3.86758 6.27483 5.24867C6.25315 5.36043 6.23419 5.47286 6.21861 5.58733C6.02963 6.98535 6.37168 8.33257 7.09034 9.42579C7.20277 9.59648 7.32402 9.76109 7.45407 9.91824C7.6173 10.116 7.70333 10.37 7.67555 10.6254C7.6742 10.6409 7.67216 10.6565 7.66946 10.6721C7.57396 11.327 6.97451 11.7998 6.31546 11.7402C6.30125 11.7389 6.28702 11.7375 6.27279 11.7355C6.03708 11.7063 5.82237 11.5824 5.67132 11.3995C5.50605 11.1997 5.35094 10.9925 5.20599 10.7777C4.15477 9.21988 3.64948 7.28541 3.92109 5.27711C4.04436 4.36406 4.31936 3.50792 4.7156 2.73169C4.8382 2.49056 4.97299 2.25755 5.11861 2.03268C5.52028 1.41292 6.2369 1.06003 6.97112 1.13928C6.99009 1.14131 7.00905 1.14334 7.02734 1.14605L7.0287 1.14538Z","M16.1579 0.766744C16.4904 1.20295 16.6245 1.7272 16.5751 2.23317C15.2637 2.06248 13.8915 2.3517 12.7217 3.13606C12.6276 3.19906 12.534 3.26611 12.4427 3.33588C11.3196 4.19067 10.6084 5.38549 10.3436 6.66633C10.3022 6.86614 10.2718 7.06866 10.2521 7.27187C10.2277 7.52723 10.1085 7.767 9.90873 7.92821C9.89654 7.93837 9.88368 7.94785 9.87149 7.95733C9.34044 8.35289 8.58183 8.26349 8.15849 7.75549C8.14969 7.74465 8.1402 7.73381 8.13208 7.7223C7.98578 7.53468 7.9221 7.29625 7.94446 7.05919C7.96884 6.80112 8.00609 6.54441 8.05554 6.29041C8.41452 4.44603 9.42579 2.72085 11.0392 1.49285C11.7728 0.934723 12.572 0.522903 13.4025 0.254678C13.6598 0.171366 13.9199 0.101601 14.1821 0.0453817C14.9048 -0.109051 15.6607 0.147659 16.124 0.722716C16.1362 0.737618 16.1477 0.752519 16.1592 0.76742L16.1579 0.766744Z","M37.833 18.812L33.0705 12.364L31.0715 14.5591V18.812H28.896V5.0929H31.0715V11.5801L36.9707 5.0929H39.6949L34.5601 10.7177L40.4593 18.812H37.833ZM41.3079 18.812V8.79706H43.3658V18.812H41.3079ZM41.0531 6.36192C41.0531 5.65636 41.6411 5.088 42.3467 5.088C43.0523 5.088 43.6206 5.65636 43.6206 6.36192C43.6206 7.06747 43.0523 7.63584 42.3467 7.63584C41.6411 7.63584 41.0531 7.06747 41.0531 6.36192ZM45.1032 18.812V17.1069L50.8653 10.6197H45.1032V8.79706H53.4523V10.5022L47.6903 16.9893H53.4523V18.812H45.1032ZM54.2765 13.8143C54.2765 10.8549 56.5303 8.60107 59.4898 8.60107C62.7039 8.60107 65.0166 11.2273 64.6442 14.5003H56.3539C56.6479 16.0878 57.9218 17.2245 59.6465 17.2245C60.9596 17.2245 62.0376 16.5386 62.6059 15.441L64.3307 16.2054C63.4683 17.8517 61.7828 19.008 59.5877 19.008C56.5695 19.008 54.2765 16.7541 54.2765 13.8143ZM56.4127 12.8932H62.5668C62.2335 11.4429 61.0772 10.3846 59.4898 10.3846C57.9022 10.3846 56.7655 11.4233 56.4127 12.8932ZM66.2386 18.812V8.79706H68.2964V10.2278C69.0216 9.24783 70.1975 8.60107 71.589 8.60107C74.0193 8.60107 75.744 10.3846 75.744 12.8344V18.812H73.6861V13.148C73.6861 11.5997 72.5494 10.4825 71.0011 10.4825C69.4528 10.4825 68.2964 11.5997 68.2964 13.148V18.812H66.2386Z"],Cl=`<svg class="wordmark" role="img" aria-label="Kizen" width="76" height="24" viewBox="0 0 76 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg"><defs><clipPath id="kizen-callback-wordmark-clip"><rect width="75.648" height="24"/></clipPath></defs><g clip-path="url(#kizen-callback-wordmark-clip)">${kl.map(e=>`<path d="${e}"/>`).join("")}</g></svg>`,Sl={success:'<path d="M6 12.5l4 4 8-9"/>',error:'<path d="M8 8l8 8M16 8l-8 8"/>'},Pl=e=>`<svg class="status-icon" aria-hidden="true" focusable="false" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.25" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">${Sl[e]}</svg>`,El=`
|
|
2
|
+
import*as 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=`
|
|
3
3
|
:root {
|
|
4
4
|
color-scheme: light dark;
|
|
5
5
|
--page-bg: #F4F9F7;
|
|
@@ -82,47 +82,65 @@ main {
|
|
|
82
82
|
.error { --accent: var(--error-accent); --tint: var(--error-bg); --glyph: var(--error-text); }
|
|
83
83
|
h1 { margin: 0 0 10px; font-size: 22px; line-height: 1.3; font-weight: 600; }
|
|
84
84
|
p { margin: 0; font-size: 15px; line-height: 1.5; color: var(--text-secondary); }
|
|
85
|
-
`.trim().replace(/\n\s*/g,"");function Ko(e,t,n){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="color-scheme" content="light dark"><title>Kizen App Builder</title><style>${El}</style></head><body><main>${Cl}<section class="card ${e}" data-status="${e}"><div class="status">${Pl(e)}</div><h1>${t}</h1><p>${n}</p></section></main></body></html>`}var on="127.0.0.1",pr="/callback",$l=`http://${on}${pr}`,Nl="read write offline_access",Dl="Kizen App Builder CLI",Rl=300*1e3,Me="go",Et=2e4,q=class extends Error{constructor(n,r){super(r);this.code=n;this.name="OAuthError"}code},ye=e=>e===Me?"appbuilder login":`appbuilder login --env ${e}`,ze=(e,t,n={})=>new q("login_required",`${t} Run \`${ye(e)}\` to sign in${n.again===!0?" again":""}.`),Ol=e=>{try{return e===""?void 0:JSON.parse(e)}catch{return}};async function fr(e,t,n,r){let o=AbortSignal.timeout(r);try{let i=await e(t,{...n,headers:{Accept:"application/json",...n.headers},signal:o});return{res:i,body:Ol(await i.text())}}catch(i){let s=o.aborted?`timed out after ${String(Math.round(r/1e3))}s`:Pt(i);throw new q("network_error",`Couldn't reach ${new URL(t).origin}: ${s}`)}}function Jo(e,t,n){let r=O(n)?n:{},o=ie(r.error);if(o!==void 0){let i=ie(r.error_description);return new q(o,`${e} failed (${o}${i===void 0?"":`: ${i}`})`)}return new q("server_error",`${e} failed with HTTP ${String(t)}`)}async function Go(e,t,n=Et){let r=`${e}/.well-known/oauth-authorization-server`,o=a=>new q("server_error",`OAuth discovery at ${r} ${a}`),{res:i,body:s}=await fr(t,r,{},n);if(!i.ok)throw o(`failed with HTTP ${String(i.status)}`);if(!O(s))throw o("didn't return valid JSON");if(s.issuer!==e)throw o(`returned issuer ${typeof s.issuer=="string"?JSON.stringify(s.issuer):"none"}, expected ${e}`);return{issuer:e,authorizationEndpoint:s.authorization_endpoint,tokenEndpoint:s.token_endpoint,registrationEndpoint:s.registration_endpoint}}async function Yo(e,t,n=Et){let{res:r,body:o}=await fr(t,e.registrationEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:Dl,redirect_uris:[$l],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"})},n);if(!r.ok)throw Jo("App registration",r.status,o);let i=O(o)?ie(o.client_id):void 0;if(i===void 0)throw new q("server_error","App registration returned no client_id");return i}var Bl=e=>Tl("sha256").update(e,"ascii").digest("base64url"),mr=()=>Al(32).toString("base64url");function Xo(){let e=mr();return{verifier:e,challenge:Bl(e)}}function Zo(e,t){let n=new URL(e.authorizationEndpoint);return n.searchParams.set("response_type","code"),n.searchParams.set("client_id",t.clientId),n.searchParams.set("redirect_uri",t.redirectUri),n.searchParams.set("scope",Nl),n.searchParams.set("state",t.state),n.searchParams.set("code_challenge",t.codeChallenge),n.searchParams.set("code_challenge_method","S256"),n.toString()}async function hr(e,t,n,r=Et){let{res:o,body:i}=await fr(n,e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()},r);if(!o.ok)throw Jo("The token request",o.status,i);let s=O(i)?ie(i.access_token):void 0,a=O(i)?ie(i.refresh_token):void 0;if(!O(i)||s===void 0||a===void 0)throw new q("server_error","The token endpoint returned an unexpected response");return{accessToken:s,refreshToken:a,expiresIn:i.expires_in}}var qo=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store",Connection:"close"}).end(Ko(n.kind,n.heading,n.text))},Fl={kind:"success",heading:"You\u2019re signed in",text:"Sign-in complete. You can close this window."},jl={kind:"error",heading:"Sign-in failed",text:"Sign-in failed. Return to the terminal for details. You can close this window."},Ll={kind:"error",heading:"Outdated link",text:"This sign-in link is out of date. Use the latest link from the terminal."},Ml=e=>{try{return new URL(e??"/",`http://${on}`)}catch{return}};async function Qo(e){let t=e.timeoutMs??Rl,n,r=new Promise((h,v)=>{n={resolve:h,reject:v}});r.catch(()=>{});let o=!1,i,s=Il((h,v)=>{let p=Ml(h.url);if(o||h.method!=="GET"||p?.pathname!==pr){v.writeHead(404,{"Content-Type":"text/plain",Connection:"close"}).end("Not found");return}let l=p.searchParams;if(l.get("state")!==e.state){qo(v,400,Ll);return}let w=l.get("error"),C=l.get("error_description"),E=l.get("code")??"",x=w!==null?new q(w,`Kizen denied the sign-in (${w}${C?`: ${C}`:""})`):E?void 0:new q("invalid_callback","The sign-in callback had no authorization code");qo(v,x?400:200,x?jl:Fl),c(x,E)}),a=()=>(i??=new Promise(h=>{clearTimeout(g),s.close(()=>{h()}),s.closeAllConnections()}),i);function c(h,v=""){o||(o=!0,h?n.reject(h):n.resolve({code:v}),a())}await new Promise((h,v)=>{s.once("error",v),s.listen(0,on,()=>{s.off("error",v),h()})});let g=setTimeout(()=>{c(new q("timeout",`Timed out after ${String(Math.round(t/1e3))}s waiting for the browser sign-in`))},t),u=s.address();return{port:u.port,redirectUri:`http://${on}:${String(u.port)}${pr}`,result:r,close:a}}function ei(e){let[t,n]=Wo==="darwin"?["open",[e]]:Wo==="win32"?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{let r=_l(t,n,{stdio:"ignore",detached:!0});r.on("error",()=>{}),r.unref()}catch{}}var zl="The API key is invalid for this business, or the user id doesn't match. Check the credentials file's apiKey, userId and businessId.",Ul="The API key's user needs the Standard API Keys permission and edit access to this dashboard. Homepages also need the Customize Homepages permission.",Hl=e=>ze(e,"Kizen rejected the signed-in session.",{again:!0}).message,Vl="The signed-in user needs edit access to this dashboard. Homepages also need the Customize Homepages permission.",Kl={authFailed:zl,forbidden:Ul},Wl=100,ql=new Set(["detail","non_field_errors"]),Z=class extends Error{kind;status;hint;constructor(t,n,r={}){super(n),this.name="KizenApiError",this.kind=t,this.status=r.status,this.hint=r.hint}},_t=encodeURIComponent,Tt=(e,t)=>t===void 0?`/dashboards/${_t(e)}/dashlet`:`/dashboards/${_t(e)}/dashlet/${_t(t)}`;function gr(e,t,n){let r=o=>{n.push(t===""?o:`${t}: ${o}`)};if(typeof e=="string"){e.trim()!==""&&r(e);return}if(typeof e=="number"||typeof e=="boolean"){r(String(e));return}if(Array.isArray(e)){let o=e.filter(i=>typeof i=="string"&&i.trim()!==""||typeof i=="number"||typeof i=="boolean");o.length>0&&r(o.map(String).join(" "));for(let i of e)typeof i=="object"&&i!==null&&gr(i,t,n);return}if(O(e))for(let[o,i]of Object.entries(e)){let s=t===""&&ql.has(o)?"":t===""?o:`${t}.${o}`;gr(i,s,n)}}function Jl(e){if(typeof e!="object"||e===null)return;let t=[];return gr(e,"",t),t.length>0?t.join("; "):void 0}async function Gl(e){let t=await e.text();if(t==="")return{text:t,json:void 0};try{return{text:t,json:JSON.parse(t)}}catch{return{text:t,json:void 0}}}function Yl(e,t,n,r,o){let i=Jl(r),s=`${e} ${t} failed with ${String(n)}${i===void 0?"":`: ${i}`}`;return n===401?new Z("auth_failed",s,{status:n,hint:o.authFailed}):n===403?new Z("forbidden",s,{status:n,hint:o.forbidden}):n===404?new Z("not_found",s,{status:n}):new Z("api_error",s,{status:n})}function ti(e,t,n){if(Array.isArray(n))return{results:n,next:null};if(O(n)&&Array.isArray(n.results))return{results:n.results,next:n.next};throw new Z("api_error",`${e} ${t} returned an unexpected response shape`)}var sn=e=>O(e)?e:{};function ni(e){let t=sn(e);return{business:sn(t.business),team:sn(t.team)}}var Xl=new Map([["login_required","auth_failed"],["network_error","network_error"]]);function Zl(e,t){let n=Le(e),r=e instanceof q?Xl.get(e.code):void 0;return r===void 0?new Z("api_error",`Couldn't refresh the ${t} session: ${n}`):new Z(r,n)}function At(e){let t=e.fetch??fetch,n=e.bearer?e.bearer.environment:e.credentials.environment,r=e.baseUrl??dr[n],o=e.bearer?{authFailed:Hl(n),forbidden:Vl}:Kl,i=u=>{throw Zl(u,n)},s=async()=>{if(!e.bearer){let{apiKey:v,userId:p,businessId:l}=e.credentials;return{headers:{"X-API-KEY":v,"X-USER-ID":p,"X-BUSINESS-ID":l}}}let{bearer:u}=e,h=await u.getAccessToken().catch(i);return{headers:{Authorization:`Bearer ${h}`},retry:async()=>({Authorization:`Bearer ${await u.refreshAccessToken(h).catch(i)}`})}},a=async(u,h,v)=>{let p=/^https?:\/\//.test(h)?h:`${r}${h}`,l=p.startsWith(r)?p.slice(r.length):p,w=async b=>{let f={...b,Accept:"application/json"},d={method:u,headers:f};v!==void 0&&(f["Content-Type"]="application/json",d.body=JSON.stringify(v));try{return await t(p,d)}catch(m){throw new Z("network_error",`Couldn't reach Kizen at ${r}: ${Pt(m)}${Zt()==="unavailable"?` ${Xt}`:""}`)}},{headers:C,retry:E}=await s(),x=await w(C);x.status===401&&E&&(await x.body?.cancel().catch(()=>{}),x=await w(await E()));let y,P;try{({text:y,json:P}=await Gl(x))}catch(b){throw new Z("network_error",`${u} ${l}: couldn't read the response: ${Pt(b)}. The request may have been applied; check Kizen before retrying.`,{status:x.status})}if(!x.ok)throw Yl(u,l,x.status,P,o);if(P===void 0&&y!=="")throw new Z("api_error",`${u} ${l} returned a response that is not JSON`,{status:x.status});return P},c=u=>{let h=new URL(r),v=new URL(u,h.origin);if(v.protocol=h.protocol,v.port=h.port,v.username="",v.password="",v.hash="",v.origin!==h.origin)throw new Z("api_error",`GET /custom-objects pagination pointed at an unexpected location ${v.origin}${v.pathname}`);return v.toString()},g;return{async listDashboards(u,h){let v=new URLSearchParams({size:"10000",include_sharing:"true",dashboard_type:u});h!==void 0&&v.set("custom_object_id",h);let p=`/dashboards/mine?${v.toString()}`;return ti("GET",p,await a("GET",p)).results},async listCustomObjects(){let u=[],h=new Set,v="/custom-objects?page_size=200";for(;v!==void 0&&!h.has(v)&&h.size<Wl;){h.add(v);let p=ti("GET",v,await a("GET",v));u.push(...p.results),v=typeof p.next=="string"&&p.next!==""?c(p.next):void 0}return u},async getCustomObject(u){let h=`/custom-objects/${_t(u)}`,v=await a("GET",h);if(!O(v)||typeof v.id!="string"||typeof v.fetch_url!="string")throw new Z("api_error",`GET ${h} returned an unexpected response shape`);return v},async getIdentity(){let u=await a("GET","/auth/bootstrap"),{business:h,team:v}=ni(u),p=ie(h.id),l=ie(v.user);if(p===void 0||l===void 0)throw new Z("api_error","GET /auth/bootstrap returned an unexpected response shape");return g=u,{userId:l,businessId:p,businessName:ie(h.name),fullName:ie(v.full_name),email:ie(v.email)}},async getClientObjectId(){let u=g??await a("GET","/auth/bootstrap"),{business:h}=ni(u);return ie(sn(h.client_object).id)??null},async getDashboard(u){return await a("GET",`/dashboards/${_t(u)}`)},async createDashlet(u,h){return await a("POST",Tt(u),h)},async updateDashlet(u,h,v){return await a("PATCH",Tt(u,h),v)}}}import{randomBytes as ri}from"crypto";import{chmod as Ql,mkdir as ed,open as td,readdir as nd,readFile as yr,rename as oi,rm as ii,unlink as si}from"fs/promises";import{join as It}from"path";var rd="clients.json",od=10*6e4,id=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ai=e=>typeof e=="string"&&id.test(e),an=e=>O(e)&&ai(e.businessId)&&ai(e.userId)?{businessId:e.businessId,userId:e.userId}:void 0,Ee=(e,t)=>e.businessId===t.businessId&&e.userId===t.userId,pt=e=>{if(an(e)===void 0)throw new Error("Refusing a session file name built from an invalid account id.");return`${e.businessId}.${e.userId}`};function ci(e){let t;try{t=JSON.parse(e)}catch{return}return an(t)}var br=e=>typeof e=="string"?e:void 0;function sd(e,t){let n=an(e);return!O(e)||n===void 0||e.environment!==t||typeof e.issuer!="string"||typeof e.clientId!="string"||typeof e.tokenEndpoint!="string"||typeof e.accessToken!="string"||typeof e.refreshToken!="string"||typeof e.expiresAt!="number"?null:{environment:t,...n,businessName:br(e.businessName),fullName:br(e.fullName),email:br(e.email),issuer:e.issuer,clientId:e.clientId,tokenEndpoint:e.tokenEndpoint,accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt}}function Ue(e=Se){let t=It(e,"oauth"),n=x=>It(t,`${x}.json`),r=(x,y)=>It(t,`${x}.${pt(y)}.json`),o=It(t,rd),i=(x,y)=>{let P=`${x}.`;if(!y.startsWith(P)||!y.endsWith(".json"))return;let b=y.slice(P.length,-5).split(".");if(b.length!==2)return;let[f,d]=b;return an({businessId:f,userId:d})},s=async()=>await tt(nd(t))??[],a=async()=>{await ed(t,{recursive:!0,mode:448}),await Ql(t,448)},c=async(x,y)=>{await a();let P=`${x}.${ri(6).toString("hex")}.tmp`;try{let b=await td(P,"wx",384);try{await b.writeFile(JSON.stringify(y,null,2),"utf-8"),await b.sync()}finally{await b.close()}await oi(P,x)}catch(b){throw await ii(P,{force:!0}),b}},g=(x,y)=>ze(x,`The saved ${x} session at ${y} can't be read.`,{again:!0}),u=async x=>{try{let y=new RegExp(`^${x}\\.json\\.([0-9]{1,16})-[0-9a-f]{12}\\.signout$`);for(let P of await s()){let b=y.exec(P)?.[1];b!==void 0&&Date.now()-Number(b)>od&&await tt(si(It(t,P)))}}catch{}},h=async()=>{let x;try{x=JSON.parse(await tt(yr(o,"utf-8"))??"{}")}catch(y){if(y instanceof SyntaxError)return{};throw y}return O(x)?x:{}},v=async(x,y)=>{try{return await tt(yr(y,"utf-8"))}catch{throw g(x,y)}},p=async(x,y)=>{let P=r(x,y),b=await v(x,P);if(b===void 0)return null;try{let f=sd(JSON.parse(b),x);if(f!==null&&Ee(f,y))return f}catch{}throw g(x,P)},l=async x=>{let y=n(x),P=await v(x,y);if(P===void 0)return;let b=ci(P);if(b===void 0)throw g(x,y);return b},w=async x=>{let y=await l(x);return y===void 0?null:p(x,y)},C=async x=>{let y=n(x),P=`${y}.${String(Date.now())}-${ri(6).toString("hex")}.signout`;if(await tt(oi(y,P).then(()=>!0))===!0)try{return{account:ci(await yr(P,"utf-8"))}}catch{return{account:void 0}}finally{await ii(P,{force:!0})}},E=async(x,y)=>await tt(si(r(x,y)).then(()=>!0))??!1;return{dir:t,sessionPath:n,accountPath:r,readSession:w,readAccount:p,async listAccounts(x){let y;try{y=await l(x)}catch{}let P=(await s()).map(d=>i(x,d)).filter(d=>d!==void 0),b=await Promise.all(P.map(async d=>{let m;try{let k=await p(x,d);if(k===null)return;m=k}catch(k){if(!(k instanceof q&&k.code==="login_required"))throw k}return{account:d,session:m,current:y!==void 0&&Ee(y,d)}})),f=d=>(d.session?.businessName??d.account.businessId).toLowerCase();return b.filter(d=>d!==void 0).sort((d,m)=>f(d).localeCompare(f(m))||pt(d.account).localeCompare(pt(m.account)))},async writeSession(x){await c(r(x.environment,x),x)},async setCurrent(x,y){let{businessId:P,userId:b}=y;await c(n(x),{businessId:P,userId:b}),await u(x)},async deleteSession(x,y){return E(x,y)},async signOut(x){let y=await C(x),P=y!==void 0;return y?.account!==void 0&&(P=await E(x,y.account)),await u(x),P},async removeAccount(x,y){let P=!1,b;try{b=await l(x)}catch{}b!==void 0&&Ee(b,y)&&(P=await C(x)!==void 0);let f=await E(x,y);return await u(x),{removed:f,current:P}},async signOutAll(x){let y=await C(x),P=y!==void 0&&y.account===void 0,b=0;for(let f of await s()){let d=i(x,f);d!==void 0&&await E(x,d)&&(b+=1,P||=y?.account!==void 0&&Ee(y.account,d))}return await u(x),{signedIn:P,removed:b}},async listSessions(){return(await Promise.all(W.map(async y=>{try{return await w(y)===null?void 0:y}catch(P){if(P instanceof q&&P.code==="login_required")return y;throw P}}))).filter(y=>y!==void 0)},async readClientId(x){let y=(await h())[x];return O(y)?ie(y.clientId):void 0},async writeClientId(x,y){await c(o,{...await h(),[x]:{clientId:y}})},async forgetClientId(x){let y=await h();x in y&&await c(o,Object.fromEntries(Object.entries(y).filter(([P])=>P!==x)))}}}var ad=6e4,cn=class extends q{},li=(e,t)=>fetch(e,t),di=()=>Date.now(),ui=(e,t,n)=>({store:e,fetch:li,now:di,print:t,openBrowser:ei,startLoopbackServer:Qo,identify:n}),cd=(e,t)=>({environment:e,getAccessToken:()=>Promise.resolve(t),refreshAccessToken:()=>Promise.reject(ze(e,`Kizen rejected the new ${e} sign-in.`))}),ln=e=>ze(e,`You're not signed in to ${e}.`),ld=e=>({businessName:e.businessName,fullName:e.fullName,email:e.email}),pi=(e,t,n)=>({...e,accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:n+t.expiresIn*1e3}),dd=(e,t)=>t?"Opening your browser to sign in to Kizen. If it does not open, visit:":`A browser window should open for the user to sign in to Kizen ${e}. If it doesn't, give them this URL:`;async function ud(e,t,n,r){let{verifier:o,challenge:i}=Xo(),s=mr(),a=await n.startLoopbackServer({state:s,...n.timeoutMs!==void 0&&{timeoutMs:n.timeoutMs}});try{let c=Zo(e,{clientId:t,redirectUri:a.redirectUri,state:s,codeChallenge:i});n.print(r),n.print(c),n.openBrowser(c);let{code:g}=await a.result;return await hr(e.tokenEndpoint,{grant_type:"authorization_code",code:g,redirect_uri:a.redirectUri,client_id:t,code_verifier:o},n.fetch)}finally{await a.close()}}async function wr(e,t,n={}){let r=dd(e,n.interactive??!0),o=await Go(ut(e),t.fetch),i=await t.store.readClientId(o.issuer),s=i??await Yo(o,t.fetch);i===void 0&&await t.store.writeClientId(o.issuer,s);let a;try{a=await ud(o,s,t,r)}catch(h){throw h instanceof q&&h.code==="timeout"&&i!==void 0?(await t.store.forgetClientId(o.issuer),new q("timeout",`${h.message}. If the browser showed an error instead of a consent page, the saved app registration was stale; it has been cleared. Run \`${ye(e)}\` again.`)):h}let c=await t.identify(cd(e,a.accessToken)),g={businessId:c.businessId,userId:c.userId},u=pi({environment:e,...g,...ld(c),issuer:o.issuer,clientId:s,tokenEndpoint:o.tokenEndpoint},a,t.now());if(await t.store.writeSession(u),n.makeCurrent!==void 0&&!n.makeCurrent(c)){if(await t.store.readAccount(e,g)===null)throw ln(e);return u}if(await t.store.setCurrent(e,g),await t.store.readSession(e)===null)throw ln(e);return u}async function fi(e,t,n){try{await n.identify(n.provider)}catch(o){if(await n.store.readAccount(e,t).then(s=>s===null,()=>!1))return;throw o}await n.store.setCurrent(e,t);let r=await n.store.readSession(e);if(r===null)throw ln(e);return r}function pd(e,t){let n,r=t.account,o=c=>c.expiresAt-t.now()>ad,i=async()=>{let c=t.account===void 0?await t.store.readSession(e):await t.store.readAccount(e,t.account);if(c===null)throw ln(e);if(r??={businessId:c.businessId,userId:c.userId},!Ee(c,r))throw new cn("login_required",`The ${e} sign-in changed while this command was running. Run it again.`);return c},s=async(c,g)=>{let u=await i();if(u.accessToken!==c&&o(u))return u.accessToken;let h=g??t.now()+(t.requestTimeoutMs??Et),v=async()=>{let E=await i();return{stored:E,rotated:E.refreshToken!==u.refreshToken}},p=h-t.now();if(p<=0)return u.accessToken;let l;try{l=await hr(u.tokenEndpoint,{grant_type:"refresh_token",refresh_token:u.refreshToken,client_id:u.clientId},t.fetch,p)}catch(E){if(E instanceof q&&(E.code==="invalid_grant"||E.code==="invalid_client")){let{stored:x,rotated:y}=await v();if(y)return o(x)||g!==void 0?x.accessToken:s(x.accessToken,h);if(await t.store.deleteSession(e,u)&&E.code==="invalid_client")try{await t.store.readClientId(u.issuer)===u.clientId&&await t.store.forgetClientId(u.issuer)}catch{}throw ze(e,`The ${e} session is no longer valid.`)}throw E}let w=pi(u,l,t.now()),C;try{({rotated:C}=await v())}catch(E){if(E instanceof cn){let x=await t.store.readAccount(e,u).catch(()=>null);x!==null&&x.refreshToken===u.refreshToken&&await t.store.writeSession(w).catch(()=>{})}throw E}return C||await t.store.writeSession(w),w.accessToken},a=c=>(n??=s(c).finally(()=>{n=void 0}),n);return{environment:e,async getAccessToken(){if(n)return n;let c=await i();return o(c)?c.accessToken:a(c.accessToken)},refreshAccessToken:a}}var dn=(e,t,n={})=>pd(e,{store:t,now:di,...n,fetch:n.fetch??li}),fd=`You're not signed in. Run \`${ye(Me)}\` (add \`--env <env>\` to sign in to an environment other than ${Me}).`;async function nt(e,t){if(e!==void 0){let{environment:o,message:i}=et(e);return o===void 0?{ok:!1,problem:"unknown_environment",message:i}:{ok:!0,environment:o}}let n=await t(),[r]=n;return n.length>1?{ok:!1,problem:"several_sessions",message:`You're signed in to several environments; pass --env <env>: ${n.join(", ")}`}:r===void 0?{ok:!1,problem:"not_signed_in",message:fd}:{ok:!0,environment:r}}var be=e=>/^[\w@%+:,./-][\w@%+=:,./-]*$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`;var md=5e3,hd=(e,t)=>e.isTTY===!0&&t.isTTY===!0;function hi(e=Ue(),t){let n=(i,s)=>dn(i,e,s),r=i=>{process.stderr.write(i)},o=i=>At({bearer:i}).getIdentity();return{store:e,loginDeps:ui(e,i=>{r(`${i}
|
|
86
|
-
`)
|
|
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}
|
|
87
105
|
User: ${n===""?t.userId:`${n} (${t.userId})`}
|
|
88
|
-
Business: ${
|
|
89
|
-
`};function
|
|
106
|
+
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?`
|
|
90
108
|
${t.hint}`:"";e.writeStderr(`${n}: ${r?o.replace(/\s+/g," ").trim():`${o}${i}`}
|
|
91
|
-
`),e.setExitCode(1)}var
|
|
92
|
-
`),e.writeStdout(
|
|
93
|
-
${
|
|
94
|
-
--user ${
|
|
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})))}
|
|
95
113
|
`);return}if(t.length===0){r.writeStdout(`No saved accounts for ${e}.
|
|
96
|
-
`);return}for(let o of t)r.writeStdout(`${
|
|
97
|
-
`)}async function
|
|
98
|
-
`),
|
|
114
|
+
`);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}
|
|
99
117
|
A browser window is opening to sign in to Kizen ${e}. On the consent page, choose ${s}.
|
|
100
118
|
`:`${r}
|
|
101
119
|
Waiting for the user to sign in to Kizen ${e} in a browser window. Ask them to choose ${s}.
|
|
102
|
-
`}function
|
|
103
|
-
`),t.setExitCode(1);return}if(o!==
|
|
104
|
-
`);let E=await
|
|
105
|
-
`),
|
|
106
|
-
${
|
|
107
|
-
`),t.setExitCode(1)}),
|
|
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.
|
|
108
126
|
`);return}let{environment:r}=n;if(e.business!==void 0){let i=await t.store.listAccounts(r);if(i.length===0){t.writeStdout(`No saved accounts for ${r}.
|
|
109
|
-
`);return}let s=
|
|
110
|
-
`:`No saved ${r} account ${
|
|
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}.`:""}
|
|
128
|
+
`:`No saved ${r} account ${$e(s)}.
|
|
111
129
|
`);return}if(e.all===!0){let{signedIn:i,removed:s}=await t.store.signOutAll(r);t.writeStdout(i||s>0?`Signed out of ${r}. Removed ${String(s)} saved ${s===1?"account":"accounts"} from this machine.
|
|
112
130
|
`:`No saved accounts for ${r}.
|
|
113
131
|
`);return}let o=await t.store.signOut(r);t.writeStdout(o?`Signed out of ${r}. The session was removed from this machine.
|
|
114
132
|
`:`Not signed in to ${r}.
|
|
115
|
-
`)}),
|
|
116
|
-
`}catch(r){wi(t,r,{prefix:"appbuilder auth-header",oneLine:!0});return}t.writeStdout(n)};import{render as Id}from"ink";import{useMemo as Pd,useState as Ed}from"react";import{Box as kr,Text as ot,useInput as _d}from"ink";var pn=(e,t,n)=>Math.min(Math.max(e,t),n);function fn(e,t,n,r={}){if(t<=0)return 0;let o=pn(Math.trunc(e)||0,0,t-1),i=c=>r.disabled?.[c]!==!0;if(n===0)return o;let s=n>0?1:-1;if(Math.abs(n)===1){for(let c=1;c<=t;c++){let g=((o+s*c)%t+t)%t;if(i(g))return g}return o}let a=pn(o+Math.trunc(n),0,t-1);for(let c=a;c>=0&&c<t;c+=s)if(i(c))return c;for(let c=a-s;c>=0&&c<t;c-=s)if(i(c))return c;return o}function Ei(e,t,n=10){if(t<=0)return{start:0,end:0};let r=Math.max(1,Math.floor(n));if(t<=r)return{start:0,end:t};let o=pn(Math.trunc(e)||0,0,t-1),i=pn(o-Math.floor(r/2),0,t-r);return{start:i,end:i+r}}import{jsx as it,jsxs as Sr}from"react/jsx-runtime";var Td="\u2191/\u2193 to move, Enter to select, Esc to cancel",Cr=10,Ad=e=>{let t=fn(0,e.length,0);if(e[t]?.disabled!==!0)return t;let n=e.findIndex(r=>r.disabled!==!0);return n===-1?t:n},Te=({title:e,items:t,onSelect:n,onCancel:r,hint:o=Td})=>{let[i,s]=Ed(()=>Ad(t)),a=Pd(()=>t.map(p=>p.disabled===!0),[t]),c=fn(i,t.length,0);_d((p,l)=>{let w=C=>{s(fn(c,t.length,C,{disabled:a}))};if(l.upArrow||p==="k")w(-1);else if(l.downArrow||p==="j")w(1);else if(l.pageUp)w(-Cr);else if(l.pageDown)w(Cr);else if(l.return){let C=t[c];C!==void 0&&C.disabled!==!0&&n(C,c)}else l.escape&&r?.()});let{start:g,end:u}=Ei(c,t.length,Cr),h=g,v=t.length-u;return Sr(kr,{flexDirection:"column",gap:1,children:[it(ot,{bold:!0,children:e}),Sr(kr,{flexDirection:"column",children:[h>0&&it(ot,{dimColor:!0,children:` \u2191 ${String(h)} more`}),t.slice(g,u).map((p,l)=>{let C=g+l===c,E=p.disabled===!0,x=C&&!E;return Sr(kr,{gap:2,children:[it(ot,{...x&&{color:"cyan"},dimColor:E,children:C?"\u276F":" "}),it(ot,{bold:x,dimColor:E,...x&&{color:"cyan"},children:p.label}),p.description!==void 0&&it(ot,{dimColor:!0,children:p.description})]},p.key)}),v>0&&it(ot,{dimColor:!0,children:` \u2193 ${String(v)} more`})]}),it(ot,{dimColor:!0,children:o})]})};import{jsx as $d}from"react/jsx-runtime";var _i=async(e,t)=>{let n,r=Id($d(Te,{title:e,items:t,onSelect:o=>{n=o.key,r.unmount()},onCancel:()=>{r.unmount()}}));return await r.waitUntilExit(),n};var Nd=[{name:"login",description:"Sign in to Kizen in the browser, or switch to a saved account, and store the session on this machine",env:"environment to sign in to (default: go)",options:[["--business <id-or-name>","switch to the saved account with this business id, or business name (ignoring case); signs in with the browser if none matches or it expired"],["--user <userId>","with --business, pick the saved account of this user id"],["--list","list the saved accounts for the environment and exit"],["--json","with --list, print the accounts as JSON"]],run:ki},{name:"logout",description:"Remove the stored session from this machine",env:"environment to sign out of (default: the only signed-in one)",options:[["--all","also remove every other saved account for the environment"],["--business <id-or-name>","remove only this saved account, by business id or name (ignoring case)"],["--user <userId>","with --business, remove the saved account of this user id"]],run:Ci},{name:"whoami",description:"Show the user and business of the stored session",env:"environment to check (default: the only signed-in one)",run:Si},{name:"auth-header",description:"Print an Authorization header for the stored session as JSON (for a Claude Code MCP headersHelper)",env:"environment to use; must match CLAUDE_CODE_MCP_SERVER_URL when that is set (default: the environment matching it, else the only signed-in one)",run:Pi}];function Ti(e){for(let{name:t,description:n,env:r,options:o=[],run:i}of Nd){let s=e.command(t).description(n).option("--env <env>",r);for(let[a,c]of o)s.option(a,c);s.action(async a=>{await i(a,hi(void 0,_i))})}}import{createElement as cf}from"react";import{render as lf}from"ink";import{PluginValidationError as df}from"@kizenapps/packager";import{spawn as Dd}from"child_process";import{platform as Ai}from"process";function Rd(){return Ai==="darwin"?[{cmd:"pbcopy",args:[]}]:Ai==="win32"?[{cmd:"clip",args:[]}]:[{cmd:"wl-copy",args:[]},{cmd:"xclip",args:["-selection","clipboard"]},{cmd:"xsel",args:["--clipboard","--input"]}]}var Od=2e3;function Bd(e,{cmd:t,args:n}){return new Promise(r=>{let o;try{o=Dd(t,n,{stdio:["pipe","ignore","ignore"]})}catch{r(!1);return}let i=o,s=!1;function a(g){s||(s=!0,clearTimeout(c),r(g))}let c=setTimeout(()=>{i.kill(),a(!1)},Od);c.unref(),i.on("error",()=>{a(!1)}),i.on("close",g=>{a(g===0)}),i.stdin.on("error",()=>{a(!1)});try{i.stdin.end(e)}catch{a(!1)}})}async function mn(e){for(let t of Rd())if(await Bd(e,t))return!0;return!1}import{BLOCKS_DIRECTORY_NAME as gu,CONFIG_FILE_NAME as yu,MANIFEST_FILE_NAME as bu,sanitizeToAPIName as wu}from"@kizenapps/packager";var hn=["min_w","max_w","min_h","max_h","default_w","default_h"];import{createHash as Fd}from"crypto";import{mkdir as jd,readFile as Ld,writeFile as Md}from"fs/promises";import{dirname as zd,join as Ni}from"path";var Pr="appbuilder:",st=".kizenapp/pushes.json",Ud=["environment","businessId","pluginApiName","blockApiName","dashboardId","dashletId","contentHash","pushedAt"];function Er(e){return typeof e=="number"&&Number.isFinite(e)}function gn(e,t,n){return Math.min(Math.max(e,t),n)}function Hd(e){let t={...e};return delete t.custom_object,t}function Di(e,t){return`${Pr}${e}/${t}`}function Ri(e){if(!e.startsWith(Pr))return null;let t=e.slice(Pr.length).split("/");if(t.length!==2)return null;let[n,r]=t;return!n||!r?null:{pluginApiName:n,blockApiName:r}}function Oi(e){let t={};for(let n of hn){let r=e[n];Er(r)&&(t[n]=r)}return t}function Bi(e){return typeof e.host_chrome=="boolean"?{host_chrome:e.host_chrome}:{}}var Fi=e=>Object.entries(e).map(([t,n])=>({name:t,script:n}));function Vd(e){return{api_name:e.api_name,name:e.name,type:e.type,...e.script!==""&&{script:e.script},...e.html!==""&&{html:e.html},...e.css!==""&&{css:e.css},event_scripts:Fi(e.event_scripts)}}function Tr(e){return e.length>0?{views:e.map(Vd)}:{}}function ji(e,t=[]){return{kind:"custom_code",version:1,name:e.name,script:e.script,styles:e.styles,event_scripts:Fi(e.event_scripts),...Oi(e),...Bi(e),...Tr(t)}}function Kd(e){return{object_id:e.objectId,entity_type:"static_content",report_type:"html",chart_type:"html",content:e.content,fe_extra_info:{}}}function Wd(e){let t=0;for(let n of e){let r=n.layout;if(!O(r))continue;let{y:o,h:i}=r;!Er(o)||!Er(i)||(t=Math.max(t,o+i))}return t}function qd(e,t,n){let r=gn(t.default_w??t.min_w??6,t.min_w??1,t.max_w??12),o=gn(t.default_h??t.min_h??3,t.min_h??1,t.max_h??99);return{i:n,x:0,y:Wd(e),w:gn(r,2,12),h:gn(o,1,99)}}function Li(e){return{name:Di(e.pluginApiName,e.blockApiName),layout:qd(e.dashlets,e.content,e.layoutId),config:Kd({content:e.content,objectId:e.objectId})}}function Mi(e,t){let n=e.config;return{config:{...Hd(O(n)?n:{}),content:t}}}function zi(e){let t=e.config;return O(t)?t.content:void 0}function mt(e){let t=e.config;if(!O(t)||t.chart_type!=="html")return!1;let n=t.content;return O(n)&&n.kind==="custom_code"}function Ui(e){return e.dashlets.filter(mt)}function yn(e){let t=zi(e);return O(t)&&typeof t.name=="string"?t.name:e.name}var He=e=>typeof e=="string"?e:"";function Hi(e){return Array.isArray(e)?e.filter(O).map(t=>({name:He(t.name),script:He(t.script)})):O(e)?Object.entries(e).map(([t,n])=>({name:t,script:He(n)})):[]}function _r(e){if(Array.isArray(e))return e.map(_r);if(O(e)){let t={};for(let n of Object.keys(e).sort())t[n]=_r(e[n]);return t}return e}function Vi(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e).trim():""}function Jd(e){return Array.isArray(e)?e.filter(O).map(t=>({api_name:He(t.api_name),name:Vi(t.name),type:He(t.type),script:He(t.script),html:He(t.html),css:He(t.css),event_scripts:Hi(t.event_scripts)})):[]}function Ar(e){let t=O(e)?e:{},n=Jd(t.views),r={name:Vi(t.name),script:typeof t.script=="string"?t.script:"",styles:typeof t.styles=="string"?t.styles:"",event_scripts:Hi(t.event_scripts),...Oi(t),...Bi(t),...n.length>0&&{views:n}};return Fd("sha256").update(JSON.stringify(_r(r))).digest("hex")}function Ki(e){let{entry:t}=e;if(t?.dashboardId===e.dashboardId){let i=e.dashlets.find(s=>s.id===t.dashletId);if(i&&mt(i))return{kind:"map",dashlet:i,entry:t}}let n=Di(e.pluginApiName,e.blockApiName),r=e.dashlets.filter(i=>i.name===n&&mt(i)),[o]=r;return r.length===1&&o?{kind:"name",dashlet:o}:r.length>1?{kind:"ambiguous",dashlets:r}:{kind:"none"}}function Wi(e,t){return t?.dashletId!==e.id?!1:Ar(zi(e))!==t.contentHash}function Ir(e,t){return e.environment===t.environment&&e.businessId===t.businessId&&e.pluginApiName===t.pluginApiName&&e.blockApiName===t.blockApiName}function $r(e,t){return e.find(n=>Ir(n,t))}function qi(e,t){let n=e.findIndex(r=>Ir(r,t));return n===-1?[...e,t]:e.map((r,o)=>o===n?t:r)}function Ji(e,t){return e.filter(n=>!Ir(n,t))}function Gd(e){if(!O(e))return null;for(let n of Ud)if(typeof e[n]!="string")return null;let t=e;return{environment:t.environment,businessId:kt(t.businessId),pluginApiName:t.pluginApiName,blockApiName:t.blockApiName,dashboardId:t.dashboardId,dashletId:t.dashletId,contentHash:t.contentHash,pushedAt:t.pushedAt}}var Ii=e=>Date.parse(e.pushedAt)||0;function Yd(e){let t=new Map;for(let n of e){let r=[n.environment,n.businessId,n.pluginApiName,n.blockApiName].join("\0"),o=t.get(r);(o===void 0||Ii(n)>Ii(o))&&t.set(r,n)}return[...t.values()]}var $i=e=>e instanceof Error?e.message:String(e);async function Gi(e){let t;try{t=await Ld(Ni(e,st),"utf8")}catch(r){if(nn(r))return[];throw new Error(`Couldn't read ${st}: ${$i(r)}. Fix its permissions, or delete it to start a fresh push map.`)}let n;try{n=JSON.parse(t)}catch(r){throw new Error(`${st} is not valid JSON (${$i(r)}). Fix it, or delete it to start a fresh push map.`)}if(!Array.isArray(n))throw new Error(`${st} must contain a JSON array of push entries. Fix it, or delete it to start a fresh push map.`);return Yd(n.map(Gd).filter(r=>r!==null))}async function Yi(e,t){let n=Ni(e,st);await jd(zd(n),{recursive:!0}),await Md(n,`${JSON.stringify(t,null,2)}
|
|
117
|
-
`,"utf8")}var
|
|
118
|
-
`));return[
|
|
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(`
|
|
119
137
|
|
|
120
|
-
`)}import{randomUUID as
|
|
121
|
-
`).map(a=>a.trim())),o=
|
|
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(`
|
|
122
140
|
`)+`
|
|
123
141
|
`,s=n===""||n.endsWith(`
|
|
124
142
|
`)?i:`
|
|
125
|
-
`+i;ht.writeFileSync(t,n+s)}var Ku="To use an API key instead (deprecated), pass --profile <name> or -c <path>.";function gs(e){return(e.credentials!==void 0||e.profile!==void 0)&&e.env!==void 0?{ok:!1,message:"--env selects a sign-in session, so it can't be combined with -c or --profile."}:e.credentials!==void 0?{ok:!0,selection:{kind:"api-key",credentials:e.credentials}}:e.profile!==void 0?{ok:!0,selection:{kind:"api-key",profile:e.profile}}:{ok:!0,selection:e.env===void 0?{kind:"oauth"}:{kind:"oauth",env:e.env}}}var ys=e=>`Ignoring the API-key profile ${JSON.stringify(e)} pinned in .kizenapp/config.json and using your sign-in session.${/[\x00-\x1f\x7f]/.test(e)?"":` Pass --profile ${be(e)} to use the API key.`}`,bs=e=>`${e} ${Ku}`;import{spawn as ip}from"child_process";import{join as _n}from"path";var ws="---\nname: kizen-custom-block\ndescription: Use this skill when the user asks to build, change or publish a Kizen content block, custom block, chart, or dashboard/homepage visualization in this plugin. It covers the block file layout, the plugin engine runtime rules, and the appbuilder validate, preview and push loop.\n---\n\n# Kizen custom blocks\n\nFollow these rules exactly. The runtime is strict, and a push changes a live Kizen dashlet.\n\n## Keep this skill current\n\nAt the start of any block task, run `appbuilder setup-claude --include-lib` in the plugin directory.\n\n- If it reports `updated` for `.claude/skills/kizen-custom-block/SKILL.md`, your loaded copy of this skill is stale. Re-read `.claude/skills/kizen-custom-block/SKILL.md` before doing anything else, and follow the new copy.\n- If it reports `created` for any file, or `updated` for `.claude/skills/kizen-custom-block/design.md`, read that file before writing any markup or styles.\n- If it reports `created` or `updated` for `lib/kizenData.js` (under the plugin's entry directory, usually `src/`), re-read its exports before using them.\n- If every file line reports `unchanged`, continue.\n- If the command doesn't exist (an older CLI), skip it and continue.\n- If it fails (for example, you aren't in the plugin directory that holds `kizen.json`), switch to that directory and run it once more. If it still fails, continue without it.\n\n`setup-claude` only rewrites the CLI-managed files: the ones in this skill directory and `src/lib/kizenData.js`. It never touches block code, so it's always safe to run.\n\n## What a block is\n\nA block is a directory under `src/blocks/<dir>/`:\n\n- `config.json` (required): `name`, `api_name` (always set it explicitly), `types` (any of `homepages`, `dashboards`, `charts` for chart groups, and `records`; a block only appears on the surfaces it lists), and the optional sizes `min_w`, `max_w`, `min_h`, `max_h`, `default_w` and `default_h`. Widths are grid columns (1 to 12) and heights are grid rows. Each size you set is a positive integer, each `min_*` is no greater than its `max_*`, and each `default_*` falls within whichever of its `min_*` and `max_*` you set. `default_w` and `default_h` are the starting size when `block push` creates a new dashlet; updates never resize an existing dashlet. Only the sizes you write are exported and pushed.\n - `host_chrome` (optional boolean, default `true`): whether the host paints the dashlet card around the block. Omit it unless you are turning chrome off. Only a value you write is exported and pushed, and any value other than `true` or `false` fails validation.\n- `script.js` (required): the render script.\n- `styles.css` (optional).\n- `eventScripts/<name>.js` (optional): one file per interactive handler.\n\nShared helpers live in `src/lib/*.js`. Import them with relative named imports only, for example `import { formatMoney } from '../../lib/format.js';`. No default imports, no bare package names.\n\n`src/lib/kizenData.js` is managed by appbuilder: `setup-claude` and CLI updates replace it. Never edit it. Put your own helpers in another file under `src/lib/`.\n\n### Host chrome\n\nDecide the mode yourself from the request. Ask the user only if they already raised it and their choice is unclear.\n\n- Keep host chrome (omit `host_chrome`) for standard data dashlets such as charts, KPIs, tables and lists that should match native cards.\n- Set `\"host_chrome\": false` for full-bleed heroes, imagery, custom-shaped cards, or any design whose background is part of the visual.\n\nChrome off, in `config.json`:\n\n```json\n{\n \"name\": \"Welcome hero\",\n \"api_name\": \"welcome_hero\",\n \"types\": [\"homepages\", \"dashboards\"],\n \"host_chrome\": false\n}\n```\n\nFollow \"Chrome off\" in `design.md` for the layout rules. In your summary to the user, state which mode you chose and why in one line. `block push --dry-run --json` shows the value as `body.config.content.host_chrome` (absent when chrome is on by default), so check it there. Changing `host_chrome` on a block you already pushed is an ordinary update: validate, then `block push <api_name> --yes --json`.\n\n## Runtime rules\n\nBlocks run in the plugin engine web worker.\n\n- `script.js` is the body of an async function, and `this` is the worker context. Use `await` at the top level.\n- There is no DOM: no `document` or `window`. There are no npm packages. Don't use `eval` or `Function`.\n- Render with `this.outputUI(htmlString)`. The output is sanitized with DOMPurify, so `<script>` tags and `on*` attributes are stripped. Don't rely on them.\n- Charts are hand-built inline SVG strings. There are no chart libraries.\n- Interactivity: put `data-script=\"<eventScriptName>\"` on a `<button>` whose content is text only. Clicking it runs `eventScripts/<eventScriptName>.js` in a fresh worker, so no state carries over from `script.js`.\n- Args:\n - `this.args.dateFilter`: `{ start, end }`, or `undefined`.\n - `this.args.teamFilter`.\n - `this.args.objectId`: set on chart groups.\n - Homepages have no date or team filter. Handle both being absent.\n- Data: read records with the `kizenData.js` helpers (see \"Reading Kizen data\"). They call `this.getWithErrors` and `this.postWithErrors`, which use relative URLs and run as the viewing user.\n- Toasts: `this.showToast(message, options)`. `message` MUST be a string. Passing an object crashes the host app.\n- Styling:\n - The host applies `* { font-size: 10px }`. Set explicit px font sizes on everything.\n - With host chrome (the default), the host paints the card (background, border, border radius and shadow) from the dashboard's style settings, like native dashlets. The block root is transparent, fills the card, and paints no card of its own.\n - With `\"host_chrome\": false`, the host paints nothing: no background, border, radius or shadow. The block root fills the card edge to edge and owns its whole look (see \"Chrome off\" in `design.md`).\n - Put chart labels inside the SVG as `<text>` so they scale with the `viewBox`.\n- The code is stored in a Kizen dashlet. Never include a NUL character or the literal text `{__ref:` anywhere in any file.\n\n## Reading Kizen data\n\nRead records through `src/lib/kizenData.js`. Always import it from `../../lib/kizenData.js`. Its helpers take the worker context as their first argument, so pass `this`.\n\n- `getFields(this, object)` loads an object's fields. `object` is the object's id or name, and Contacts is `client_client`. Match fields by `name`.\n- `blockFilters(this.args, fields)` returns `{ filters, unapplied }`. Always apply `filters`, so the block reacts to the dashboard's date and team filters the way native dashlets do (date on `created`, team on `owner`). When `unapplied` contains `'teamFilter'`, the team filter couldn't be applied (a roles-only selection, or an object with no owner field). Show \"(team filter not applied)\".\n- `dropdownFilter(field, 'Name')` or `dropdownFilter(field, ['A', 'B'])` filters a dropdown by option names.\n- `searchRecords(this, { object, fieldNames, filters })` returns `{ records, count, truncated }`. When `truncated` is true, show \"Showing first N\" with N = `records.length`.\n- `fieldValue(record, name)`, `fieldLabel(record, name)`, `countBy(records, name, field?)`, `sumBy(records, name, valueOf?)` and `formatNumber(n, prefix)` read and summarize the results. `countBy` groups empty values under `key: ''`. Filter that group out, or give it a label.\n- Every record value or label you put into markup goes through `escapeHtml(value)`, including option names, owner names and text fields. `this.outputUI` sanitizes scripts, but it keeps images, links, forms and styles, and the block renders for every viewer. `escapeHtml` is the only escaping helper; never write your own.\n- Never hand-build filter or search JSON when a helper exists. Every helper throws a readable `Error`, so wrap the fetch in `try` and render the error state from `design.md`.\n\nCount Contacts by a dropdown field named `status` for the current dashboard filters. Use a field name from `getFields`:\n\n```js\nimport {\n blockFilters,\n countBy,\n escapeHtml,\n getFields,\n searchRecords,\n} from '../../lib/kizenData.js';\n\ntry {\n const fields = await getFields(this, 'client_client');\n const { filters, unapplied } = blockFilters(this.args, fields);\n const search = { object: 'client_client', fieldNames: ['status'], filters };\n const { records, count, truncated } = await searchRecords(this, search);\n const rows = countBy(records, 'status').filter((row) => row.key !== '');\n const items = rows.map((row) => `<li>${escapeHtml(row.label)}: ${row.count}</li>`).join('');\n const note = truncated ? `Showing first ${records.length} of ${count}. ` : '';\n const team = unapplied.includes('teamFilter') ? '(team filter not applied)' : '';\n this.outputUI(`<ul>${items}</ul><p>${note}${team}</p>`);\n} catch {\n this.outputUI('<div class=\"kz-state kz-state--error\">Couldn\\'t load data.</div>');\n}\n```\n\n## Design\n\nBefore writing any markup or styles, read `design.md` in this skill directory and follow it exactly.\n\n## The loop\n\nRun these exact commands. The flags and JSON keys are the contract. `<api_name>` is the block's `config.json` `api_name`. `block targets` and `block push` use the user's `appbuilder login` session by default. `-c/--credentials <path>` and `--profile <name>` opt in to a deprecated API key; use them only when the user asks.\n\n1. **Validate.** Run `appbuilder block export <api_name>`. Fix every validation error it prints, then run it again until it passes.\n2. **Choose the target with the user (first publish only).**\n - `appbuilder block targets --json` returns `{ surfaces: { dashboard: [...], homepage: [...] }, customObjects: [{ id, objectName, fetchUrl }] }`. Contacts appears in `customObjects` when available.\n - `appbuilder block targets --object <id> --json` returns `{ surfaces: { chart_group: [...] } }` for that object.\n - Only offer rows where `canEdit !== false`. Ask the user which surface and which specific one. Don't pick for them.\n - Optionally run `appbuilder block push <api_name> --dashboard <id> --json` to get a `needs_choice` result listing the existing custom blocks and \"new\".\n3. **Preview.** Run `appbuilder block push <api_name> --dashboard <id> [--dashlet <id> | --create] --dry-run --json`. Show the user the `environment`, `businessId`, `dashboard.name`, `action` and any `warnings`.\n4. **Apply** once the user agrees: run the same command with `--yes` in place of `--dry-run`. Treat the push as done only when `applied === true`. Give the user the returned `url`, then refresh the browser (below).\n5. **Change requests.** Edit the files, validate again (step 1), then run `appbuilder block push <api_name> --yes --json`. With no target flags it updates the remembered dashlet. Refresh the browser (below) after each push. Repeat for each change.\n\nA headless run without `--yes` is always a dry run.\n\n### Refresh the browser after a push\n\nDo this after every applied push, only when Claude-in-Chrome tools are available. Dashlets don't poll, so the user's open tab keeps the old block until it's refreshed. Don't reload the page.\n\n1. List the open tabs (`tabs_context_mcp`) and find the one whose URL has the same origin and path as the result's `url`.\n2. If there is no such tab, open `url` in a new tab (`tabs_create_mcp`) and go to step 5.\n3. If the result has a `refresh` field, run `refresh.script` exactly as given in that tab with the page JavaScript tool (`javascript_tool`). If it has no `refresh` field, navigate that tab to `url` (`navigate`) and go to step 5.\n4. Check what the script returned:\n - `{ refreshed: true, ... }`: the dashboard refetched in place.\n - `undefined`: the refresh hook isn't available on this page (an older Kizen build, or a page without the hook). Navigate the tab to `url` instead.\n5. Wait a couple of seconds, take a screenshot (`computer`), and check that the block rendered: not blank, and no visible error. Report what you saw to the user. If the block is blank or shows an error, read the console and fix the block before pushing again.\n\nNever run any other injected code in the user's tabs. `refresh.script` is the only script you may run.\n\n### JSON results\n\n- Dry run: `{ ok: true, applied: false, dryRun: true, action: 'create' | 'update', environment, businessId, dashboard: { id, name, type }, dashletId | null, url, method, path, body, warnings }`.\n- Applied: `{ ok: true, applied: true, dryRun: false, action: 'created' | 'updated', ..., dashletId, url, refresh?: { dashboardId, script }, remembered }`. `refresh` is absent when the dashboard id isn't a uuid.\n- If a `block push` result's `warnings` contains `Claude files managed by appbuilder are out of date; run appbuilder setup-claude`, run `appbuilder setup-claude --include-lib`, re-read `.claude/skills/kizen-custom-block/SKILL.md`, then continue.\n- Error: `{ ok: false, code, message, choice?, choices? }`. `code` is one of `needs_choice`, `validation_failed`, `invalid_block`, `auth_failed`, `forbidden`, `remembered_target_missing`, `drift_detected`, `network_error`, `credentials_invalid`, `production_requires_flag`, `not_found`, `usage_error`, `api_error` or `local_error`.\n\n### `needs_choice`\n\n`choice` is `'environment'`, `'block'`, `'dashboard'` or `'target'`. `choices` is a list of `{ value, label, args, surface?, canEdit?, pushKey?, isFromThisPlugin? }`, where `args` is a string array. Ask the user using each option's `label`, then re-run the same command with the chosen option's `args` appended exactly. Never construct these flags by hand. The \"new\" option is `{ value: 'new', args: ['--dashboard', <id>, '--create'] }`.\n\n## Guardrails\n\n- Never pass `--allow-production` unless the user explicitly asked, in this conversation, to publish to production (`go` or `fmo`).\n- On `drift_detected`, stop and ask the user. Someone edited the block in Kizen since your last push, and `--force` overwrites their changes. Pass `--force` only when the user says to discard them.\n- On `needs_choice`, ask the user using the returned `choices` as described above. Never guess.\n- On `remembered_target_missing`, the remembered dashboard or dashlet is gone. Ask the user where to publish instead, then push with `--dashboard <id>` plus `--create` or a `--dashlet` choice, or use `--forget` to clear the memory. `--create` alone won't work.\n- On `credentials_invalid`, if `message` says they're not signed in, tell the user to run `appbuilder login` (add `--env <env>` for an environment other than `go`). Otherwise tell them to fix the credential file named in `message`. Don't run `--profile` or `-c` unless the user asks for an API key.\n- On `production_requires_flag`, the target is `go` or `fmo`. Apply the production rule above.\n- Never push to a new target without first showing the user a dry run.\n- Blocks run with the viewing user's permissions for every viewer. Don't write code that creates, updates or deletes data unless the user asked for it.\n";var vs=`# Designing a Kizen custom block
|
|
143
|
+
`+i;vt.writeFileSync(t,n+s)}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
|
|
126
144
|
|
|
127
145
|
With host chrome (the default), a block must look like a native Kizen dashlet. Follow every rule here exactly. Where a rule says "use judgment", pick the option that looks most native. A block whose \`config.json\` sets \`"host_chrome": false\` follows section M for its card and outer box, and skips every rule marked "with host chrome".
|
|
128
146
|
|
|
@@ -471,7 +489,7 @@ render(
|
|
|
471
489
|
color: var(--color-font-placeholder);
|
|
472
490
|
}
|
|
473
491
|
\`\`\`
|
|
474
|
-
`;var
|
|
492
|
+
`;var Zs=`# Copilot review instructions for this Kizen plugin
|
|
475
493
|
|
|
476
494
|
This repo is a Kizen plugin app: a \`kizen.json\` manifest plus the artifacts
|
|
477
495
|
that \`@kizenapps/packager\` finds by walking the directory tree under the
|
|
@@ -524,7 +542,7 @@ This file covers repo structure and general review. Two path-scoped files cover
|
|
|
524
542
|
the rest: \`.github/instructions/security.instructions.md\` for security-sensitive
|
|
525
543
|
patterns and \`.github/instructions/version-discipline.instructions.md\` for
|
|
526
544
|
manifest version bumps.
|
|
527
|
-
`;var
|
|
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=`---
|
|
528
546
|
applyTo: "kizen.json"
|
|
529
547
|
---
|
|
530
548
|
|
|
@@ -537,7 +555,7 @@ cannot drift out of date here.
|
|
|
537
555
|
Check every \`kizen.json\` diff against the "How big a bump?" matrix in
|
|
538
556
|
\`.copilot-docs/16-release-and-publish.md\` and the "Release & publish" section of
|
|
539
557
|
\`.copilot-docs/17-gotchas.md\`, and name the change that sets the required level.
|
|
540
|
-
`;var
|
|
558
|
+
`;var ta=`# Copilot only reads this file from the default branch, and only if the job is named copilot-setup-steps.
|
|
541
559
|
name: Copilot code review setup
|
|
542
560
|
|
|
543
561
|
on:
|
|
@@ -576,7 +594,7 @@ jobs:
|
|
|
576
594
|
echo "Fetched $count markdown files into .copilot-docs/ ($numbered numbered docs)"
|
|
577
595
|
test "$count" -ge 24
|
|
578
596
|
du -sh .copilot-docs
|
|
579
|
-
`;var
|
|
597
|
+
`;var na=`const MAX_PAGE_SIZE = 1000;
|
|
580
598
|
const DEFAULT_MAX_PAGES = 10;
|
|
581
599
|
|
|
582
600
|
const fieldCache = new Map();
|
|
@@ -821,22 +839,22 @@ export const sumBy = (records, name, valueOf) =>
|
|
|
821
839
|
total + (valueOf ? numberOf(valueOf(record)) : numberOf(fieldValue(record, name))),
|
|
822
840
|
0,
|
|
823
841
|
);
|
|
824
|
-
`;function
|
|
825
|
-
${e.stderr}`),As=e=>{let t=(e.stderr.trim()||e.stdout.trim()).replace(/\s+/g," "),n=e.code===null?"was stopped (timed out?)":`exited ${String(e.code)}`;return t===""?n:`${n}: ${t}`};async function hp(e,t,n){let r=pp(e,n.cliVersion),{name:o}=r,i=!1,s=a=>{n.error(`Error: couldn't register the MCP server ${o}: ${a}`),i&&(n.error(`The old ${o} registration was already removed, so Claude Code has no ${o} server now. Re-run \`appbuilder setup-claude --mcp --env ${e}\`, or run:`),n.error(` ${r.addCommand}`)),n.setExitCode(1)};if(t.dryRun){n.log(`Dry run: would register the MCP server ${r.name} with: ${r.addCommand}`);return}try{let a=await n.run("claude",r.addArgs);if(a.code!==0&&mp(a)){if(!t.force){n.log(`MCP server ${r.name} already exists in Claude Code; left unchanged. Pass --force to replace it.`);return}let c=await n.run("claude",["mcp","remove","--scope","user",r.name]);if(c.code!==0){s(`claude mcp remove --scope user ${As(c)}`);return}i=!0,a=await n.run("claude",r.addArgs)}if(a.code!==0){s(`claude mcp add-json ${As(a)}`);return}}catch(a){if(!i&&tn(a,"ENOENT")){n.log("Claude Code's `claude` command wasn't found. To register the MCP server, run (in a POSIX shell such as bash or zsh):"),n.log(` ${r.addCommand}`);return}s(Le(a));return}n.log(`Registered the MCP server ${r.name} (${r.url}) in Claude Code at user scope.`);try{await n.hasOAuthSession(e)||n.log(`You're not signed in to ${e} yet. Run \`${ye(e)}\` before using ${r.name}.`)}catch(a){n.log(Le(a))}}async function Rs(e,t,n){let r=fp(t);if(r!==void 0){n.error(`Error: ${r}`),n.setExitCode(1);return}if(!await n.fs.exists(_n(e,"kizen.json"))){n.error("Error: kizen.json not found. Run this command from a plugin directory."),n.setExitCode(1);return}let o=t.dryRun===!0,i;try{i=await Pn(e,await $s(e,n.fs,{includeLib:t.includeLib===!0}),{dryRun:o},n.fs)}catch(c){n.error(`Error: ${Le(c)}`),n.setExitCode(1);return}for(let c of i)n.log(En(c));let s=`${Ur(i,"created")}, ${Ur(i,"updated")}, ${Ur(i,"unchanged")}`,a="these files are managed by appbuilder, so local edits to them are replaced";n.log(o?`Dry run: ${s}; nothing written (${a}).`:`Claude files: ${s} (${a}).`),t.mcp===!0&&await hp((t.env===void 0?void 0:et(t.env).environment)??Me,{dryRun:o,force:t.force===!0},n)}function wp(e,t={}){let{fetch:n}=t;return{listSessions:()=>e.listSessions(),connect:async r=>{let o=dn(r,e,{...n&&{fetch:n}}),i=At({bearer:o,...n&&{fetch:n}});return{identity:await i.getIdentity(),client:i}}}}function Kr(e){return{cwd:e,loadCredentialsDetailed:en,listLoadableCredentialProfiles:Vo,loadConfig:we,packageBlocks:Br,createClient:t=>At({credentials:t}),readPushMap:Gi,writePushMap:Yi,ensureGitignore:ve,isClaudeSkillStale:t=>Ns(t),randomUUID:gp,now:()=>new Date,writeStdout:t=>{process.stdout.write(t)},writeStderr:t=>{process.stderr.write(t)},setExitCode:t=>{process.exitCode=t},oauth:wp(Ue())}}var vp=new Set(["owner","admin","edit"]),xp="Chart groups are not listed here; find them with `appbuilder block targets --object <id> --json` and pass --dashboard <id>.",Wr=e=>e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";function V(e,t,n={}){return{ok:!1,code:e,message:t,...n}}var fe=e=>({ok:!0,value:e});function Ke(e){return e instanceof Z?V(e.kind,e.message,e.hint===void 0?{}:{hint:e.hint}):e instanceof bp?V("validation_failed",Ae(e.issues),{issues:e.issues}):V("local_error",Wr(e))}async function Fs(e,t){let n;try{n=await t.loadCredentialsDetailed(e)}catch(i){return V("credentials_invalid",`Couldn't read credentials from ${e}: ${Wr(i)}`)}if(n.environmentSource!=="explicit"){let i=n.environmentSource==="missing"?'has no "environment"':'has an invalid "environment"';return V("credentials_invalid",`${e} ${i}. Set it to one of: ${W.join(", ")}. The CLI won't default to production.`)}let{credentials:r}=n,o=["apiKey","userId","businessId"].filter(i=>r[i].trim()==="");return o.length>0?V("credentials_invalid",`${e} is missing ${o.map(i=>`"${i}"`).join(", ")}.`):fe({credentials:r,client:t.createClient(r),notices:[]})}async function kp(e,t){let n=await t.listLoadableCredentialProfiles(),r=n.find(o=>o.name===e);if(!r){let o=n.map(i=>i.name);return V("credentials_invalid",o.length===0?`No loadable credential profile named "${e}". No profiles are loadable; create ${Oe} or pass -c <path>.`:`No loadable credential profile named "${e}". Loadable profiles: ${o.join(", ")}`)}return Fs(r.path,t)}async function Cp(e){let{activeCredentialProfile:t}=await e.loadConfig(yp(e.cwd,".kizenapp"));return t===void 0||t===""?[]:[ys(t)]}async function Sp(e,t){let n=[],r=await nt(e,async()=>(n=await t.oauth.listSessions(),n));if(!r.ok)switch(r.problem){case"not_signed_in":return V("credentials_invalid",bs(r.message));case"several_sessions":return V("needs_choice",r.message,{choice:"environment",choices:n.map(s=>({value:s,label:s,args:["--env",s]}))});case"unknown_environment":return V("usage_error",r.message)}let{environment:o}=r,i;try{i=await t.oauth.connect(o)}catch(s){return Ke(s)}return fe({credentials:{environment:o,businessId:i.identity.businessId},client:i.client,notices:await Cp(t)})}async function An(e,t){let n=gs(e);if(!n.ok)return V("usage_error",n.message);let{selection:r}=n;return r.kind==="oauth"?Sp(r.env,t):r.credentials===void 0?kp(r.profile,t):Fs(r.credentials,t)}function Pp(e,t){let n=new Set(t.map(r=>r.pluginApiName)).size>1;return t.map(({pluginApiName:r,apiName:o})=>{let i=e.find(a=>a.api_name===r)?.artifacts.custom_blocks.find(a=>a.api_name===o),s=n?`${r}/${o}`:o;return{value:o,label:`${i?.name??o} (${s})`,args:[o]}})}async function qr(e,t){let n=await t.packageBlocks(t.cwd),r=Fr(n,e,"push");if(!r.ok){let{reason:g,message:u,field:h}=r;return g==="no_blocks"||g==="invalid_block"?V("invalid_block",u,h===void 0?{}:{field:h}):V("needs_choice",u,{choice:"block",choices:Pp(n.deployable,r.available)})}let{block:o,pluginApiName:i,views:s,warnings:a}=r.value,c=ji(o,s);return fe({block:o,pluginApiName:i,content:c,contentHash:Ar(c),warnings:a})}var js=e=>e==null?null:vp.has(e.toLowerCase());function Nt(e,t){return{id:e.id,name:e.name,type:t,dashletsCount:e.dashlets_count??null,employeeAccess:e.employee_access??null,hidden:e.hidden??!1,canEdit:js(e.employee_access)}}var Ls=e=>({id:e.id,objectName:e.object_name,fetchUrl:e.fetch_url}),Ep="Contacts";async function Jr(e){let[t,n]=await Promise.all([e.listCustomObjects(),e.getClientObjectId().catch(()=>null)]),r=t.map(Ls).sort((o,i)=>o.objectName.localeCompare(i.objectName));return n!==null&&n!==""&&!r.some(o=>o.id===n)&&r.push({id:n,objectName:Ep,fetchUrl:"client"}),r}async function _p(e,t,n){let{environment:r,businessId:o}=t;try{if(n.object!==void 0){let c=n.object,[g,u]=await Promise.all([e.getCustomObject(c).catch(()=>null),e.listDashboards("chart_group",c)]);return fe({ok:!0,environment:r,businessId:o,object:g?Ls(g):null,surfaces:{chart_group:u.map(h=>Nt(h,"chart_group"))}})}let[i,s,a]=await Promise.all([e.listDashboards("generic_dashboard"),e.listDashboards("homepage"),Jr(e)]);return fe({ok:!0,environment:r,businessId:o,surfaces:{dashboard:i.map(c=>Nt(c,"dashboard")),homepage:s.map(c=>Nt(c,"homepage"))},customObjects:a})}catch(i){return Ke(i)}}var Gr=(e,t)=>t.dashboard===e.id;function In(e,t){return[...Ui(e).filter(r=>Gr(e,r)).map(r=>{let o=Ri(r.name);return{value:r.id,label:yn(r),args:["--dashboard",e.id,"--dashlet",r.id],pushKey:o?r.name:null,isFromThisPlugin:o?.pluginApiName===t.pluginApiName}}),{value:"new",label:"Create a new block",args:["--dashboard",e.id,"--create"]}]}var Yr=(e,t)=>Ki({dashboardId:t.id,dashlets:t.dashlets,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name,entry:e.entry}),Ms=(e,t)=>fe({dashboard:e,surface:Nr(e.type),action:"create",dashlet:void 0,resolvedBy:t}),Tn=(e,t,n)=>fe({dashboard:e,surface:Nr(e.type),action:"update",dashlet:t,resolvedBy:n});async function Tp(e){let[t,n]=await Promise.all([e.client.listDashboards("generic_dashboard"),e.client.listDashboards("homepage")]),r=o=>i=>({value:i.id,label:i.name,args:["--dashboard",i.id],surface:o,canEdit:js(i.employee_access)});return V("needs_choice",`Choose where to push; pass --dashboard <id>. ${xp}`,{choice:"dashboard",choices:[...t.map(r("dashboard")),...n.map(r("homepage"))]})}async function Ap(e,t,n){let r=await e.client.getDashboard(t);if(n.create)return Ms(r,"flag");let o=()=>In(r,e.block);if(n.dashlet!==void 0){let s=n.dashlet,a=r.dashlets.find(c=>c.id===s&&Gr(r,c));return a?mt(a)?Tn(r,a,"flag"):V("usage_error",`Dashlet ${s} is not a custom code block, so it can't be updated with a pushed block. Pass --create to add a new one.`):V("not_found",`Dashlet ${s} is not on dashboard "${r.name}" (${r.id}).`,{choice:"target",choices:o()})}let i=Yr(e,r);return i.kind==="map"?Tn(r,i.dashlet,"push_map"):i.kind==="name"?Tn(r,i.dashlet,"name"):V("needs_choice",i.kind==="ambiguous"?`Dashboard "${r.name}" has ${String(i.dashlets.length)} blocks pushed from this block; pass --dashlet <id> to pick one, or --create.`:`Choose a block to update on "${r.name}", or create a new one; pass --dashlet <id> or --create.`,{choice:"target",choices:o()})}async function Ip(e,t,n){let r;try{r=await e.client.getDashboard(t.dashboardId)}catch(i){if(i instanceof Z&&i.kind==="not_found")return V("remembered_target_missing",`The remembered dashboard ${t.dashboardId} no longer exists. Pass --dashboard <id> to choose another, or --forget to clear it.`);throw i}if(n.create)return Ms(r,"remembered");let o=r.dashlets.find(i=>i.id===t.dashletId&&Gr(r,i));return o&&mt(o)?Tn(r,o,"remembered"):V("remembered_target_missing",`The remembered block (dashlet ${t.dashletId}) is no longer on "${r.name}". Choose a block to update, or create a new one.`,{choice:"target",choices:In(r,e.block)})}async function Xr(e,t){if(t.dashlet!==void 0&&t.create)return V("usage_error","Pass either --dashlet <id> or --create, not both.");if(t.dashlet!==void 0&&t.dashboard===void 0)return V("usage_error","--dashlet <id> needs --dashboard <id>.");try{return t.dashboard!==void 0?await Ap(e,t.dashboard,t):e.entry?await Ip(e,e.entry,t):await Tp(e)}catch(n){return Ke(n)}}async function $p(e,t,n){let r=t.custom_object;if(r==null||r==="")return null;if(typeof r!="string"){if(typeof r!="object"||typeof r.id!="string")return null;let{id:o,fetch_url:i}=r;return typeof i=="string"?{id:o,fetchUrl:i}:{id:o}}if(n!=="chart_group")return{id:r};try{let o=await e.getCustomObject(r);return{id:r,fetchUrl:o.fetch_url}}catch{return{id:r}}}async function Zr(e,t,n,r){let{credentials:o,block:i}=e,{dashboard:s,surface:a}=t,c=[],g,u;if(t.action==="update"){let{dashlet:v}=t;if(Wi(v,e.entry)){let p=`"${yn(v)}" (dashlet ${v.id}) was changed in Kizen since the last push.`;if(!n.force)return V("drift_detected",`${p} Pushing would overwrite those changes; pass --force to overwrite them.`);c.push(`${p} Overwriting it because of --force.`)}g={action:"update",method:"PATCH",path:Tt(s.id,v.id),body:Mi(v,i.content),dashletId:v.id},u=`Update "${yn(v)}" (dashlet ${v.id})`}else g={action:"create",method:"POST",path:Tt(s.id),body:Li({pluginApiName:i.pluginApiName,blockApiName:i.block.api_name,content:i.content,dashlets:s.dashlets,objectId:r.randomUUID(),layoutId:r.randomUUID()}),dashletId:null},u=`Create a new block on "${s.name}"`;let h=Zi({appBaseUrl:Lo[o.environment],surface:a,dashboardId:s.id,customObject:await $p(e.client,s,a)});return fe({...g,dashboard:{id:s.id,name:s.name,type:a},url:h,resolvedBy:t.resolvedBy,warnings:c,summary:{environment:o.environment,businessId:o.businessId,isProduction:ur(o.environment),surface:a,dashboardId:s.id,dashboardName:s.name,action:t.action,actionLine:u,dashletId:g.dashletId,blockName:i.block.name,blockApiName:i.block.api_name,pluginApiName:i.pluginApiName,scriptBytes:Buffer.byteLength(i.content.script,"utf8"),stylesBytes:Buffer.byteLength(i.content.styles,"utf8"),...i.content.views&&{viewsBytes:Buffer.byteLength(JSON.stringify(i.content.views),"utf8")}}})}var Qr=e=>({environment:e.credentials.environment,businessId:e.credentials.businessId,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name});async function eo(e,t,n){let r;try{if(t.action==="create"){let c=(await e.client.createDashlet(t.dashboard.id,t.body)).id;if(typeof c!="string"||c==="")return V("api_error",`POST ${t.path} succeeded but the response had no dashlet id; check "${t.dashboard.name}" before pushing again.`);r=c}else await e.client.updateDashlet(t.dashboard.id,t.dashletId,t.body),r=t.dashletId}catch(a){return Ke(a)}let o=[...t.warnings],i={...Qr(e),dashboardId:t.dashboard.id,dashletId:r,contentHash:e.block.contentHash,pushedAt:n.now().toISOString()},s=!1;try{n.ensureGitignore(n.cwd),await n.writePushMap(n.cwd,qi(e.pushMap,i)),s=!0}catch(a){o.push(`The push succeeded, but ${st} couldn't be written, so this target isn't remembered: ${Wr(a)}`)}return fe({dashletId:r,remembered:s,warnings:o})}var Np=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function to(e){return Np.test(e)?{dashboardId:e,script:`await window.__kizenCustomBlocks?.refresh('${e}')`}:null}async function Dp(e,t){let n=Qr(e);if(!$r(e.pushMap,n))return null;let r=Ji(e.pushMap,n);return await t.writePushMap(t.cwd,r),r}async function no(e,t){let{client:n,credentials:r,block:o}=e,i=await t.readPushMap(t.cwd),s=!1;if(e.forget){let a=await Dp({credentials:r,block:o,pushMap:i},t);a&&(i=a,s=!0)}return{context:{client:n,credentials:r,block:o,pushMap:i,entry:$r(i,Qr({credentials:r,block:o}))},forgotten:s}}function ro(e,t){return e.dryRun?fe({kind:"dry-run",reason:"flag"}):e.yes?ur(t)&&!e.allowProduction?V("production_requires_flag",`${t} is a production environment. Pass --allow-production with --yes to write to it.`):fe({kind:"apply"}):fe({kind:"dry-run",reason:"no_yes"})}var Rp="Dry run only: pass --yes to write.",at=e=>e.map(t=>`Warning: ${t}`);function Dt(e){return[`Environment: ${e.environment}${e.isProduction?" (production)":""}`,`Business: ${e.businessId}`,`Surface: ${e.surface}`,`Dashboard: "${e.dashboardName}" (${e.dashboardId})`,`Action: ${e.actionLine}`,`Block: ${e.blockName} (${e.pluginApiName}/${e.blockApiName})`,`Size: script ${String(e.scriptBytes)} bytes, styles ${String(e.stylesBytes)} bytes${e.viewsBytes===void 0?"":`, views ${String(e.viewsBytes)} bytes`}`]}var Op=e=>`${e.path===void 0?"":`${e.path}: `}${e.message} (${e.rule})`;function Bp(e,t,n){let r=[`Error: ${e.message}`];if(e.hint!==void 0&&r.push(`Hint: ${e.hint}`),e.choices&&e.choices.length>0){r.push("Choices:");for(let o of e.choices){let i=n(o,e.choice).map(be).join(" ");r.push(` ${o.label} \u2192 ${t} ${i}`)}}return`${r.join(`
|
|
842
|
+
`;function 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(`
|
|
826
844
|
`)}
|
|
827
|
-
`}function
|
|
828
|
-
`):e.deps.writeStderr(
|
|
829
|
-
`),e.deps.writeStderr(r)):e.deps.writeStdout(n)}var
|
|
830
|
-
`)};async function
|
|
831
|
-
`);let{context:l,forgotten:
|
|
832
|
-
`);let C=await
|
|
833
|
-
`),[...
|
|
834
|
-
`)),
|
|
835
|
-
`);return}let
|
|
836
|
-
`))}catch(c){a(
|
|
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(`
|
|
837
855
|
`)}
|
|
838
|
-
`}async function
|
|
839
|
-
`:Lp(h.value))}catch(a){s(Ke(a))}}import{useEffect as Js,useState as $n}from"react";import{Box as ce,Text as Y,useApp as Xp,useInput as Zs}from"ink";import"@kizenapps/packager";import{Box as Hp,Text as Vp}from"ink";import{Box as Mp,Text as zp}from"ink";import{jsx as Ks}from"react/jsx-runtime";var Up=[" :::::::: "," :::::: ::::::::::: "," :::::: :::::::::: "," :::::: :::::: ::::::: "," ::::: :::::: ::::::::::::::::: "," ::::: ::::: ::::::::::::::::::: "," ::::: ::::: :::::: ::::: ",":::: ::::: ::: ::::: :: ","::::: :::::: :::::::::: ","::::: :::::: ::::::::::: "," ::::: ::: ::::::: "," ::::::: ::: ::::: "," ::::::::::: :::::: :::::"," :::::::::: :::::: :::::"," :: ::::: ::: ::::: ::::"," ::::: :::::: ::::: ::::: ::: "," ::::::::::::::::::: ::::: ::::: "," ::::::::::::::::: ::::: ::::: "," ::::::::: :::::: :::::: "," :::::::::: :::::: "," ::::::::::: :::::: "," :::::::: "],Ws=()=>Ks(Mp,{flexDirection:"column",children:Up.map((e,t)=>Ks(zp,{color:"cyan",children:e},t))});import{Fragment as Kp,jsx as oo,jsxs as Wp}from"react/jsx-runtime";var J=({marginBottom:e=0})=>Wp(Kp,{children:[oo(Ws,{}),oo(Hp,{flexDirection:"column",marginTop:1,marginBottom:e,children:oo(Vp,{bold:!0,color:"cyan",children:"Kizen App Development Toolkit"})})]});import{useEffect as qp,useState as Jp}from"react";import{Text as Gp}from"ink";import{jsx as Yp}from"react/jsx-runtime";var qs=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],xe=()=>{let[e,t]=Jp(0);return qp(()=>{let n=setInterval(()=>{t(r=>(r+1)%qs.length)},80);return()=>{clearInterval(n)}},[]),Yp(Gp,{color:"cyan",children:qs[e]??"\u280B"})};import{Fragment as af,jsx as D,jsxs as G}from"react/jsx-runtime";var Gs=[{key:"dashboard",label:"Dashboard"},{key:"homepage",label:"Homepage"},{key:"chart_group",label:"Chart group"}],Zp={dashboard:"dashboard",homepage:"homepage",chart_group:"chart group"},io="\u2191/\u2193 to move, Enter to select, Esc to go back",Qp="The block was edited in Kizen since your last push. Overwriting discards those edits.",Nn=e=>e.args.includes("--create");function Ys(e,t){let n=e.filter(i=>i.value===t),r=e.filter(Nn),o=e.filter(i=>i.value!==t&&!Nn(i));return n.length>0?[...n,...o,...r]:[...r,...o]}function gt(e,t){return(n,r)=>{let o=e[r];o!==void 0&&t(o)}}function ef(e,t){if(Nn(e))return{key:e.value,label:e.label};if(e.value===t)return{key:e.value,label:`Update "${e.label}" (last pushed here)`};let n=e.isFromThisPlugin?"pushed from this plugin":e.pushKey;return{key:e.value,label:`Update "${e.label}"`,...n?{description:n}:{}}}function tf(e){let t=e.dashletsCount===null?e.name:`${e.name} (${String(e.dashletsCount)} dashlets)`;if(e.canEdit===!1)return{key:e.id,label:t,description:"no edit access",disabled:!0};let n=[e.employeeAccess,e.hidden?"hidden":null].filter(r=>r!==null&&r!=="").join(" \xB7 ");return{key:e.id,label:t,...n===""?{}:{description:n}}}function nf(e,t,n){let r={...e,dashboard:t};return delete r.dashlet,delete r.create,Nn(n)?{...r,create:!0}:{...r,dashlet:n.value}}function rf(e,t,n,r){let o=p=>{t.setExitCode(1),n({type:"error",view:p})},i=p=>{p().catch(l=>{o(Ke(l))})},s=async(p,l)=>{n({type:"applying",plan:l});let w=await eo(p,l,t);if(!w.ok){o(w);return}n({type:"done",plan:l,applied:w.value})},a=async(p,l,w)=>{n({type:"loading",label:"Preparing the push\u2026"});let C=await Zr(p,l,w,t);if(!C.ok){if(C.code==="drift_detected"){n({type:"confirm",kind:"drift",message:C.message,target:l,options:w,context:p});return}o(C);return}if(w.dryRun){n({type:"done",plan:C.value,applied:null});return}if(w.yes){let E=ro(w,p.credentials.environment);if(E.ok&&E.value.kind==="apply"){await s(p,C.value);return}}n({type:"confirm",kind:"push",plan:C.value,options:w,context:p})},c=async(p,l,w)=>{n({type:"loading",label:"Resolving the target\u2026"});let C=await Xr(p,l);if(C.ok){await a(p,C.value,l);return}let E=l.dashboard??p.entry?.dashboardId;if((C.code==="needs_choice"&&C.choice==="target"||C.code==="remembered_target_missing")&&C.choices&&C.choices.length>0&&E!==void 0){n({type:"target-select",dashboardId:E,title:"Choose a block to update, or create a new one",message:C.message,choices:Ys(C.choices,null),matchedId:null,back:w,options:l,context:p});return}o(C)},g=async(p,{credentials:l,client:w},C)=>{let{context:E,forgotten:x}=await no({client:w,credentials:l,block:C,forget:p.forget===!0},t);if(x&&r(y=>({...y,notices:[...y.notices,`Forgot the remembered target for ${C.block.api_name}.`]})),p.dashboard!==void 0||E.entry){await c(E,p,null);return}n({type:"surface-select",options:p,context:E})},u=async(p,l,w)=>{n({type:"packaging"});let C=await qr(w,t);if(!C.ok){if(C.choice==="block"&&C.choices){n({type:"block-select",options:p,resolved:l,choices:C.choices});return}o(C);return}r(E=>({...E,warnings:C.value.warnings})),await g(p,l,C.value)},h=async p=>{n({type:"loading",label:"Loading credentials\u2026"});let l=await An(p,t);if(!l.ok){if(l.choice==="environment"&&l.choices){n({type:"environment-select",options:p,choices:l.choices});return}o(l);return}r(w=>({...w,credentials:l.value.credentials,credentialNotices:l.value.notices})),await u(p,l.value,e)},v=async({options:p,context:l},w,C,E)=>{let x=Zp[w];n({type:"loading",label:`Loading ${x}s\u2026`});let P=(await l.client.listDashboards(Xi(w),C?.id)).map(d=>Nt(d,w)),{environment:b,businessId:f}=l.credentials;if(P.length===0){o({message:`No ${x}s found${C?` on ${C.objectName}`:""} for business ${f} (${b}).`});return}n({type:"dashboard-select",surface:w,objectId:C?.id??null,title:C?`Choose a chart group on ${C.objectName}`:`Choose a ${x}`,rows:P,back:E,options:p,context:l})};return{start:p=>{i(()=>h(p))},pickEnvironment:(p,l)=>{i(()=>h({...p.options,env:l.value}))},pickBlock:(p,l)=>{i(()=>u(p.options,p.resolved,l.value))},pickSurface:(p,l)=>{i(async()=>{if(l!=="chart_group"){await v(p,l,null,p);return}n({type:"loading",label:"Loading custom objects\u2026"});let w=await Jr(p.context.client);if(w.length===0){o({message:"No custom objects found, so there are no chart groups to push to."});return}n({type:"object-select",objects:w,back:p,options:p.options,context:p.context})})},pickObject:(p,l)=>{i(()=>v(p,"chart_group",l,p))},pickDashboard:(p,l)=>{i(async()=>{let{context:w}=p,C={...p.options,dashboard:l.id};if(C.dashlet!==void 0||C.create){await c(w,C,p);return}n({type:"loading",label:`Loading "${l.name}"\u2026`});let E=await w.client.getDashboard(l.id),x=Yr(w,E),y=x.kind==="map"||x.kind==="name"?x.dashlet.id:null;n({type:"target-select",dashboardId:E.id,title:`Choose what to push to on "${E.name}"`,message:null,choices:Ys(In(E,w.block),y),matchedId:y,back:p,options:C,context:w})})},pickTarget:(p,l)=>{i(()=>c(p.context,nf(p.options,p.dashboardId,l),p))},acceptDrift:p=>{i(()=>a(p.context,p.target,{...p.options,force:!0}))},acceptPush:p=>{i(()=>s(p.context,p.plan))},cancel:()=>{o({message:"Cancelled."})}}}var Xs=({prompt:e,strict:t,onAccept:n,onCancel:r})=>(Zs((o,i)=>{if(i.ctrl)return;let s=o.toLowerCase();s==="y"||!t&&i.return?n():(t||s==="n"||i.escape)&&r()}),D(Y,{bold:!0,children:e})),ct=({lines:e,color:t})=>D(ce,{flexDirection:"column",children:e.map((n,r)=>D(Y,{...t&&{color:t},children:n},`${String(r)}-${n}`))}),Qs=({plan:e})=>G(ce,{flexDirection:"column",children:[D(ct,{lines:Dt(e.summary)}),G(Y,{children:["URL: ",e.url]})]}),so=({label:e})=>G(ce,{gap:1,children:[D(xe,{}),D(Y,{dimColor:!0,children:e})]}),of=({view:e})=>G(ce,{flexDirection:"column",gap:1,children:[G(ce,{gap:1,children:[D(Y,{color:"red",children:"\u2717"}),D(Y,{color:"red",children:e.issues&&e.issues.length>0?Ae(e.issues):e.message})]}),e.hint!==void 0&&G(Y,{dimColor:!0,children:["Hint: ",e.hint]}),e.choices&&e.choices.length>0&&G(ce,{flexDirection:"column",children:[D(Y,{children:"Choices:"}),D(ct,{lines:e.choices.map(t=>` ${t.label}`)})]})]}),sf=({plan:e,applied:t})=>{let n=to(e.dashboard.id);return t===null?G(ce,{flexDirection:"column",gap:1,children:[D(Y,{color:"yellow",children:"Dry run: nothing was written."}),D(Qs,{plan:e}),e.warnings.length>0&&D(ct,{lines:at(e.warnings),color:"yellow"}),G(ce,{flexDirection:"column",children:[G(Y,{bold:!0,children:[e.method," ",e.path]}),D(Y,{children:JSON.stringify(e.body,null,2)})]})]}):G(ce,{flexDirection:"column",gap:1,children:[G(ce,{gap:1,children:[D(Y,{color:"green",children:"\u2713"}),G(Y,{bold:!0,children:[e.action==="create"?"Created":"Updated"," ",e.summary.blockName,' on "',e.dashboard.name,'"']})]}),G(ce,{flexDirection:"column",children:[G(Y,{children:["URL: ",e.url]}),n&&G(Y,{dimColor:!0,children:["Refresh an open tab: ",n.script]})]}),t.warnings.length>0&&D(ct,{lines:at(t.warnings),color:"yellow"})]})},ea=({apiName:e,options:t,deps:n})=>{let r=Xp(),[o,i]=$n({type:"loading",label:"Loading credentials\u2026"}),[s,a]=$n({credentials:null,credentialNotices:[],warnings:[],notices:[]}),[c]=$n(()=>rf(e,n,i,a)),[g]=$n(t);Js(()=>{c.start(g)},[c,g]),Js(()=>{(o.type==="done"||o.type==="error")&&r.exit()},[o,r]),Zs((h,v)=>{v.ctrl&&h==="c"&&o.type!=="done"&&o.type!=="error"&&(n.setExitCode(130),r.exit())});let u=h=>G(ce,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[D(J,{}),s.credentials&&G(Y,{dimColor:!0,children:["Environment: ",s.credentials.environment," \xB7 Business:"," ",s.credentials.businessId]}),s.credentialNotices.length>0&&D(ct,{lines:s.credentialNotices,color:"yellow"}),s.warnings.length>0&&D(Y,{dimColor:!0,children:Ae(s.warnings)}),s.notices.length>0&&D(ct,{lines:s.notices}),h]});switch(o.type){case"loading":return u(D(so,{label:o.label}));case"packaging":return u(D(so,{label:"Packaging blocks\u2026"}));case"applying":return u(D(so,{label:`Pushing ${o.plan.summary.blockName} to "${o.plan.dashboard.name}"\u2026`}));case"environment-select":return u(D(Te,{title:"Environment",items:o.choices.map(h=>({key:h.value,label:h.label})),onSelect:gt(o.choices,h=>{c.pickEnvironment(o,h)}),onCancel:c.cancel},"environment"));case"block-select":return u(D(Te,{title:"Block to push",items:o.choices.map(h=>({key:h.value,label:h.label})),onSelect:gt(o.choices,h=>{c.pickBlock(o,h)}),onCancel:c.cancel},"block"));case"surface-select":return u(D(Te,{title:"Where should the block go?",items:Gs,onSelect:gt(Gs,h=>{c.pickSurface(o,h.key)}),onCancel:c.cancel},"surface"));case"object-select":return u(D(Te,{title:"Custom object",items:o.objects.map(h=>({key:h.id,label:h.objectName})),onSelect:gt(o.objects,h=>{c.pickObject(o,h)}),onCancel:()=>{i(o.back)},hint:io},"object"));case"dashboard-select":return u(D(Te,{title:o.title,items:o.rows.map(tf),onSelect:gt(o.rows,h=>{c.pickDashboard(o,h)}),onCancel:()=>{i(o.back)},hint:io},`dashboards-${o.surface}-${o.objectId??""}`));case"target-select":{let{back:h}=o;return u(G(af,{children:[o.message!==null&&D(Y,{color:"yellow",children:o.message}),D(Te,{title:o.title,items:o.choices.map(v=>ef(v,o.matchedId)),onSelect:gt(o.choices,v=>{c.pickTarget(o,v)}),onCancel:h?()=>{i(h)}:c.cancel,...h&&{hint:io}},`targets-${o.dashboardId}`)]}))}case"confirm":return o.kind==="drift"?u(G(ce,{flexDirection:"column",gap:1,children:[D(Y,{color:"yellow",children:Qp}),D(Y,{dimColor:!0,children:o.message}),D(Xs,{prompt:"Type y to overwrite (y/N)",strict:!0,onAccept:()=>{c.acceptDrift(o)},onCancel:c.cancel},"drift")]})):u(G(ce,{flexDirection:"column",gap:1,children:[D(Qs,{plan:o.plan}),o.plan.warnings.length>0&&D(ct,{lines:at(o.plan.warnings),color:"yellow"}),o.plan.summary.isProduction&&D(Y,{color:"red",bold:!0,children:"PRODUCTION"}),D(Xs,{prompt:o.plan.summary.isProduction?"Type y to push to production (y/N)":"Push? (Y/n)",strict:o.plan.summary.isProduction,onAccept:()=>{c.acceptPush(o)},onCancel:c.cancel},"push")]}));case"done":return u(D(sf,{plan:o.plan,applied:o.applied}));case"error":return u(D(of,{view:o.view}))}};var na=e=>`Error: ${e instanceof Error?e.message:String(e)}`,uf=e=>e instanceof df?Ae(e.issues):na(e),ta=e=>{console.error(na(e)),process.exitCode=1};function ra(e){let t=e.command("block").description("Work with plugin content blocks");t.command("export").description("Print one packaged block as JSON for the Custom Block (AI Coded) paste editor").argument("[api_name]","api_name of the block to export (optional when there is only one)").option("--copy","also copy the JSON to the clipboard").action(async(n,r)=>{try{let o=await fs(process.cwd(),n),{block:i,warnings:s}=o;s.length>0&&console.error(Ae(s));let a=JSON.stringify(ps(o),null,2);console.log(a),r.copy&&console.error(await mn(a)?`Copied block "${i.api_name}" to the clipboard.`:"Couldn't copy to the clipboard; use the JSON printed to stdout instead.")}catch(o){console.error(uf(o)),process.exitCode=1}}),t.command("push").description("Push a block to a Kizen dashboard, homepage or chart group dashlet").argument("[api_name]","api_name of the block to push (optional when there is only one)").option("-c, --credentials <path>","path to an API-key credentials JSON file (deprecated; replaces the sign-in session)").option("--profile <name>","stored API-key credential profile to use (deprecated; replaces the sign-in session)").option("--dashboard <id>","dashboard, homepage or chart group to push to").option("--dashlet <id>","existing custom code dashlet to update (needs --dashboard)").option("--create","create a new dashlet instead of updating one").option("--dry-run","show the request without writing anything").option("--yes","write without asking (headless runs are dry runs without it)").option("--allow-production","allow headless writes to go/fmo").option("--force","overwrite even if the block was edited in Kizen since the last push").option("--forget","clear the remembered target for this block first").option("--json","print a JSON result to stdout (always headless)").option("--env <env>","environment of the `appbuilder login` session to use").action(async(n,r)=>{try{let o=Kr(process.cwd());if(!process.stdin.isTTY||!process.stdout.isTTY||r.json===!0){await Hs(n,r,o);return}let{waitUntilExit:i}=lf(cf(ea,{...n!==void 0&&{apiName:n},options:r,deps:o}),{exitOnCtrlC:!1});await i()}catch(o){ta(o)}}),t.command("targets").description("List the dashboards, homepages and chart groups a block can be pushed to").option("-c, --credentials <path>","path to an API-key credentials JSON file (deprecated; replaces the sign-in session)").option("--profile <name>","stored API-key credential profile to use (deprecated; replaces the sign-in session)").option("--object <id>","list the chart groups of this custom object").option("--json","print a JSON result to stdout").option("--env <env>","environment of the `appbuilder login` session to use").action(async n=>{try{await Vs(n,Kr(process.cwd()))}catch(r){ta(r)}})}import{createElement as hf}from"react";import{render as gf}from"ink";import{useEffect as ia,useState as Bt}from"react";import{Box as Ft,Text as yt,useApp as pf}from"ink";import{PluginValidationError as ff}from"@kizenapps/packager";function Rt(e){return e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}import{Box as ao,Text as Dn}from"ink";import{jsx as oa,jsxs as Ot}from"react/jsx-runtime";var Rn=({issues:e})=>{let t=e.filter(n=>n.severity==="error").length;return Ot(ao,{flexDirection:"column",marginTop:1,children:[Ot(Dn,{color:"red",children:["\u2717 ",t," validation ",t===1?"error":"errors"]}),[...Lr(e)].map(([n,r])=>Ot(ao,{flexDirection:"column",marginTop:1,children:[oa(Dn,{bold:!0,children:n}),r.map((o,i)=>oa(ao,{paddingLeft:2,children:Ot(Dn,{color:o.severity==="error"?"red":"yellow",children:[o.severity==="error"?"\u2717":"\u26A0"," ",o.message," ",Ot(Dn,{dimColor:!0,children:["(",o.rule,")"]})]})},`${o.rule}-${String(i)}`))]},n))]})};import{Fragment as mf,jsx as We,jsxs as lt}from"react/jsx-runtime";var sa=["creating-dir","reading-files","validating","minifying","packaging","writing-bundle"],On={"creating-dir":"Creating .kizenapp directory","reading-files":"Reading plugin files",validating:"Validating plugin app",minifying:"Minifying scripts",packaging:"Packaging plugin","writing-bundle":"Writing bundle.json"},aa=({outputDir:e,pluginDir:t})=>{let n=pf(),[r,o]=Bt("creating-dir"),[i,s]=Bt(!1),[a,c]=Bt(null),[g,u]=Bt(null),[h,v]=Bt(null);ia(()=>{vn(t,e,o).then(({bundleSize:w})=>{v(w),o("done")}).catch(w=>{w instanceof ff?c(w.issues):u(w instanceof Error?w.message:String(w)),s(!0),process.exitCode=1})},[e,t]),ia(()=>{(r==="done"||i)&&n.exit()},[r,i,n]);let p=sa.indexOf(r),l=r==="done";return lt(Ft,{flexDirection:"column",paddingY:1,paddingX:2,children:[We(J,{marginBottom:1}),lt(Ft,{flexDirection:"column",gap:0,children:[sa.map((w,C)=>{let E=r===w,x=l||p>C;return We(Ft,{gap:1,children:i&&C===p?lt(yt,{color:"red",children:["\u2717 ",On[w]]}):x?lt(yt,{color:"green",children:["\u2713 ",On[w]]}):E?lt(mf,{children:[We(xe,{}),We(yt,{children:On[w]})]}):lt(yt,{dimColor:!0,children:[" ",On[w]]})},w)}),l&&h!==null&&We(Ft,{marginTop:1,gap:1,children:lt(yt,{color:"green",children:["\u2713 bundle \u2014 ",Rt(h)]})}),a!==null&&We(Rn,{issues:a}),g!==null&&We(Ft,{marginTop:1,borderStyle:"single",borderColor:"red",paddingX:1,children:We(yt,{color:"red",children:g})})]})]})};function ca(e){e.command("build").description("Bundle the plugin app into .kizenapp directory").action(async()=>{let t=process.cwd(),n=`${t}/.kizenapp`;ve(t);let{waitUntilExit:r}=gf(hf(aa,{outputDir:n,pluginDir:t}));await r()})}import{createElement as cm}from"react";import{render as lm}from"ink";import{useCallback as Un,useState as bt}from"react";import{Box as K,Text as $,useApp as nm,useInput as rm}from"ink";import{join as Hn}from"path";import{access as Zf,mkdir as Fn,writeFile as mo}from"fs/promises";import{dirname as Qf,join as Ie}from"path";var la=`{
|
|
856
|
+
`}async function 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=`{
|
|
840
858
|
"name": "Hello Frame",
|
|
841
859
|
"api_name": "hello_frame",
|
|
842
860
|
"title": "Hello Frame",
|
|
@@ -845,13 +863,13 @@ ${e.stderr}`),As=e=>{let t=(e.stderr.trim()||e.stdout.trim()).replace(/\s+/g," "
|
|
|
845
863
|
"height": 320,
|
|
846
864
|
"width": 280
|
|
847
865
|
}
|
|
848
|
-
`;var
|
|
866
|
+
`;var Ma=`this.outputUI(\`
|
|
849
867
|
<div class="hello-frame">
|
|
850
868
|
<h2 class="hello-frame__title">Hello from a floating frame</h2>
|
|
851
869
|
<p class="hello-frame__body">Edit src/floatingFrames/helloFrame/script.js to change this.</p>
|
|
852
870
|
</div>
|
|
853
871
|
\`);
|
|
854
|
-
`;var
|
|
872
|
+
`;var Ua=`.hello-frame {
|
|
855
873
|
padding: 16px;
|
|
856
874
|
font-family: system-ui, sans-serif;
|
|
857
875
|
}
|
|
@@ -865,18 +883,18 @@ ${e.stderr}`),As=e=>{let t=(e.stderr.trim()||e.stdout.trim()).replace(/\s+/g," "
|
|
|
865
883
|
margin: 0;
|
|
866
884
|
color: #555;
|
|
867
885
|
}
|
|
868
|
-
`;var
|
|
886
|
+
`;var Ha=`{
|
|
869
887
|
"name": "Hello Block",
|
|
870
888
|
"api_name": "hello_block",
|
|
871
889
|
"types": ["dashboards"]
|
|
872
890
|
}
|
|
873
|
-
`;var
|
|
891
|
+
`;var Ka=`this.outputUI(\`
|
|
874
892
|
<div class="hello-block">
|
|
875
893
|
<h2 class="hello-block__title">Hello from a block</h2>
|
|
876
894
|
<p class="hello-block__body">Edit src/blocks/helloBlock/script.js to change this.</p>
|
|
877
895
|
</div>
|
|
878
896
|
\`);
|
|
879
|
-
`;var
|
|
897
|
+
`;var Va=`.hello-block {
|
|
880
898
|
padding: 16px;
|
|
881
899
|
font-family: system-ui, sans-serif;
|
|
882
900
|
background: #f8fafc;
|
|
@@ -892,25 +910,25 @@ ${e.stderr}`),As=e=>{let t=(e.stderr.trim()||e.stdout.trim()).replace(/\s+/g," "
|
|
|
892
910
|
margin: 0;
|
|
893
911
|
color: #555;
|
|
894
912
|
}
|
|
895
|
-
`;var
|
|
913
|
+
`;var Wa=`{
|
|
896
914
|
"icon": "phone",
|
|
897
915
|
"color": "#0ea5e9",
|
|
898
916
|
"tooltip": "Hello adornment",
|
|
899
917
|
"field_type": "phonenumber"
|
|
900
918
|
}
|
|
901
|
-
`;var
|
|
902
|
-
`;var
|
|
919
|
+
`;var qa=`this.showToast('Hello from a data adornment.', { variant: 'success' });
|
|
920
|
+
`;var Ga=`{
|
|
903
921
|
"name": "Hello Page",
|
|
904
922
|
"api_name": "hello_page"
|
|
905
923
|
}
|
|
906
|
-
`;var
|
|
924
|
+
`;var Ja=`this.outputUI(\`
|
|
907
925
|
<div class="hello-page">
|
|
908
926
|
<p class="hello-page__loading">Loading\u2026</p>
|
|
909
927
|
</div>
|
|
910
928
|
\`);
|
|
911
929
|
|
|
912
930
|
this.runEventScript('greet');
|
|
913
|
-
`;var
|
|
931
|
+
`;var Ya=`.hello-page {
|
|
914
932
|
padding: 24px;
|
|
915
933
|
font-family: system-ui, sans-serif;
|
|
916
934
|
}
|
|
@@ -948,7 +966,7 @@ this.runEventScript('greet');
|
|
|
948
966
|
.hello-page__button:hover {
|
|
949
967
|
background: #cbd5e1;
|
|
950
968
|
}
|
|
951
|
-
`;var
|
|
969
|
+
`;var Xa=`const tone = this.args?.formData?.tone?.[0] ?? 'plain';
|
|
952
970
|
|
|
953
971
|
const greeting = tone === 'cheer' ? 'Hello, and good to see you!' : 'Hello from a routable page.';
|
|
954
972
|
|
|
@@ -971,33 +989,33 @@ this.outputUI(\`
|
|
|
971
989
|
</div>
|
|
972
990
|
</div>
|
|
973
991
|
\`);
|
|
974
|
-
`;var
|
|
992
|
+
`;var Za=`{
|
|
975
993
|
"api_name": "hello_toolbar_item",
|
|
976
994
|
"label": "Hello Toolbar Item",
|
|
977
995
|
"icon": "star",
|
|
978
996
|
"color": "#0ea5e9"
|
|
979
997
|
}
|
|
980
|
-
`;var
|
|
981
|
-
`;var
|
|
998
|
+
`;var Qa=`this.showToast('Hello from a toolbar item.', { variant: 'success' });
|
|
999
|
+
`;var ec=`{
|
|
982
1000
|
"api_name": "hello_object_settings_item",
|
|
983
1001
|
"label": "Hello Object Settings"
|
|
984
1002
|
}
|
|
985
|
-
`;var
|
|
986
|
-
`;var
|
|
1003
|
+
`;var tc=`this.showToast('Hello from an object settings item.', { variant: 'success' });
|
|
1004
|
+
`;var nc=`{
|
|
987
1005
|
"name": "Hello Action",
|
|
988
1006
|
"api_name": "hello_action",
|
|
989
1007
|
"hint_object_name": "client_client"
|
|
990
1008
|
}
|
|
991
|
-
`;var
|
|
992
|
-
`;var
|
|
993
|
-
`,"utf-8"),await Fn(Ie(e.targetDir,"src"),{recursive:!0}),await Fn(Ie(e.targetDir,"releaseNotes"),{recursive:!0}),await Promise.all([fo(e.targetDir,_a(e.artifacts??[])),fo(e.targetDir,kn()),fo(e.targetDir,Cn(e.includeLib===!0?["src"]:[])),mo(Ie(e.targetDir,...em.split("/")),Aa(e.apiName))]),ve(e.targetDir)}var Je=["name","apiName","externalLink","description","developerBusinessId"],Mn={name:"Name",apiName:"API name",externalLink:"External link",description:"Description",developerBusinessId:"Business ID"},go=["name","apiName","description"],yo=/^[a-z_][a-z0-9_]+$/,bo="must start with a letter or underscore and contain only lowercase letters, numbers, or underscores (minimum 2 characters)";function zn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}function $a(e){return{name:"",apiName:"",externalLink:"",description:"",developerBusinessId:e}}function Na(e,t){let n=t.trim();if(go.includes(e)&&!n)return`${Mn[e]} is required`;if(e==="apiName"&&!yo.test(n))return`${Mn[e]} ${bo}`}function Da(e,t){return e==="description"?t:t.trim()}function Ra(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),se.filter(r=>n.has(r))}import{jsx as I,jsxs as B}from"react/jsx-runtime";var dt=({text:e})=>I($,{dimColor:!0,children:e}),Oa=({parentDir:e,defaultBusinessId:t,defaultEnvironment:n,includeLib:r=!1})=>{let o=nm(),[i,s]=bt({type:"target-select",cursor:0}),[a,c]=bt("in-place"),[g,u]=bt(()=>$a(t)),[h,v]=bt(()=>[...se]),[p,l]=bt(""),[w,C]=bt(e),E=Un((b,f)=>{c(b),l(f.name),s({type:"field-entry",field:0,values:f})},[]),x=Un(async b=>{let f=await qe(b);if(f!=="ok"){s({type:"precheck-error",targetDir:b,reason:f});return}C(b),E("in-place",g)},[g,E]),y=Un(async(b,f)=>{try{let d=await Ia(e,b.apiName);C(d),s({type:"confirm",values:b,artifacts:f})}catch(d){s({type:"error",message:d instanceof Error?d.message:String(d)})}},[e]),P=Un(async(b,f,d)=>{try{await Ln({targetDir:f,name:b.name,apiName:b.apiName,externalLink:b.externalLink,description:b.description,developerBusinessId:b.developerBusinessId,developerEnvironment:n,artifacts:d,includeLib:r}),s({type:"done",targetDir:f})}catch(m){s({type:"error",message:m instanceof Error?m.message:String(m)})}},[n,r]);if(rm((b,f)=>{if(f.ctrl&&b==="c"){o.exit();return}if(i.type==="target-select"){f.upArrow?s({type:"target-select",cursor:0}):f.downArrow?s({type:"target-select",cursor:1}):f.return?i.cursor===0?x(e):E("sub-dir",g):f.escape&&o.exit();return}if(i.type==="precheck-error"){(f.return||f.escape)&&o.exit();return}if(i.type==="field-entry"){let{field:d,values:m}=i,k=Je[d];if(!k)return;if(f.escape){o.exit();return}if(f.backspace||f.delete){l(S=>S.slice(0,-1));return}if(f.upArrow&&d>0){let S={...m,[k]:p},T=d-1,_=Je[T];s({type:"field-entry",field:T,values:S}),u(S),l(_?S[_]:"");return}if(f.return||f.tab||f.downArrow){let S=Na(k,p);if(S!==void 0){s({type:"field-entry",field:d,values:m,fieldError:S});return}let T=Da(k,p),_={...m,[k]:T};u(_);let R=d+1;if(R>=Je.length)l(""),s({type:"artifact-select",values:_,cursor:0,selected:h});else{let z=Je[R],ee=z?_[z]:"",ae=z==="apiName"&&!ee?zn(_.name):ee;s({type:"field-entry",field:R,values:_}),l(ae)}return}b&&!f.ctrl&&!f.meta&&l(S=>S+b);return}if(i.type==="artifact-select"){let{cursor:d,selected:m,values:k}=i;if(f.escape){let S=Je.length-1,T=Je[S];s({type:"field-entry",field:S,values:k}),l(T?k[T]:"");return}if(f.upArrow){s({...i,cursor:Math.max(0,d-1)});return}if(f.downArrow){s({...i,cursor:Math.min(se.length-1,d+1)});return}if(b===" "){let S=se[d];if(S){let T=Ra(m,S);v(T),s({...i,selected:T})}return}if(b==="a"){v([...se]),s({...i,selected:[...se]});return}if(b==="n"){v([]),s({...i,selected:[]});return}f.return&&(a==="sub-dir"?(s({type:"resolving-target"}),y(k,m)):s({type:"confirm",values:k,artifacts:m}));return}if(i.type==="confirm"){if(f.escape){s({type:"artifact-select",values:i.values,cursor:0,selected:i.artifacts});return}f.return&&(s({type:"writing"}),P(i.values,w,i.artifacts));return}(i.type==="done"||i.type==="error")&&(f.return||f.escape)&&o.exit()}),i.type==="target-select"){let b=[{label:"Use current directory",desc:e},{label:"Create new sub-directory",desc:`${e}/<inferred from API name>`}];return B(K,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(J,{}),B(K,{flexDirection:"column",gap:0,children:[I($,{bold:!0,children:"Where should the new plugin live?"}),b.map((f,d)=>{let m=i.cursor===d;return B(K,{gap:2,children:[I($,{...m&&{color:"cyan"},children:m?"\u276F":" "}),I($,{bold:m,...m&&{color:"cyan"},children:f.label}),I($,{dimColor:!0,children:f.desc})]},f.label)})]}),I(dt,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(i.type==="precheck-error"){let{targetDir:b,reason:f}=i;return B(K,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(J,{}),I($,{color:"red",bold:!0,children:"Cannot create plugin"}),B(K,{flexDirection:"column",gap:0,children:[B($,{children:[b," already contains ",I($,{bold:!0,children:f==="has-manifest"?"kizen.json":".kizenapp/"}),"."]}),I($,{dimColor:!0,children:"Remove the conflicting file/directory or choose a different target to avoid overwriting an existing plugin."})]}),I(dt,{text:"Enter or Esc to exit"})]})}if(i.type==="field-entry"){let{field:b,fieldError:f}=i,d=a==="sub-dir"?`Target: sub-directory of ${e} (inferred from API name)`:`Target: ${w}`;return B(K,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(J,{}),B(K,{flexDirection:"column",gap:0,children:[I($,{bold:!0,children:"Plugin details"}),I($,{dimColor:!0,children:d})]}),f!==void 0&&B($,{color:"red",children:["Error: ",f]}),I(K,{flexDirection:"column",gap:0,children:Je.map((m,k)=>{let S=b===k,T=S?p:g[m],_=go.includes(m),R=`${Mn[m]}${_?"":" (optional)"}`;return B(K,{gap:2,children:[I(K,{width:24,children:I($,{bold:S,...S&&{color:"cyan"},children:R})}),I($,{...S&&{color:"cyan"},children:">"}),I($,{children:T}),S&&I($,{color:"cyan",children:"\u2588"})]},m)})}),I(dt,{text:"Enter/Tab/\u2193 next \xB7 \u2191 previous \xB7 Backspace delete \xB7 Esc cancel"})]})}if(i.type==="artifact-select"){let{cursor:b,selected:f}=i;return B(K,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(J,{}),B(K,{flexDirection:"column",gap:0,children:[I($,{bold:!0,children:"Which artifacts should we scaffold?"}),I($,{dimColor:!0,children:"Each one gets a directory with a config.json and a script that runs."})]}),I(K,{flexDirection:"column",gap:0,children:se.map((d,m)=>{let k=b===m,S=f.includes(d);return B(K,{gap:1,children:[I($,{...k&&{color:"cyan"},children:k?"\u276F":" "}),I($,{...S&&{color:"green"},children:S?"\u25C9":"\u25EF"}),I($,{bold:k,...k&&{color:"cyan"},children:co[d]})]},d)})}),I(dt,{text:"\u2191\u2193 move \xB7 Space toggle \xB7 a all \xB7 n none \xB7 Enter continue \xB7 Esc back"})]})}if(i.type==="confirm"){let b=ho({targetDir:w,name:i.values.name,apiName:i.values.apiName,externalLink:i.values.externalLink,description:i.values.description,developerBusinessId:i.values.developerBusinessId,developerEnvironment:n});return B(K,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(J,{}),B(K,{flexDirection:"column",gap:0,children:[I($,{bold:!0,children:"Ready to create"}),B($,{dimColor:!0,children:["Target: ",w]})]}),B(K,{flexDirection:"column",gap:0,children:[I($,{bold:!0,children:"kizen.json preview"}),I($,{children:JSON.stringify(b,null,2)})]}),B(K,{flexDirection:"column",gap:0,children:[I($,{bold:!0,children:"Artifacts"}),i.artifacts.length===0?B($,{dimColor:!0,children:[" ","none (src/ will hold only thumbnail.png)"]}):i.artifacts.map(f=>B($,{dimColor:!0,children:[" ",co[f]]},f))]}),B(K,{flexDirection:"column",gap:0,children:[I($,{dimColor:!0,children:"Also creates:"}),B($,{dimColor:!0,children:[" ",Hn(w,"src/")]}),B($,{dimColor:!0,children:[" ",Hn(w,"src/thumbnail.png")," (generated placeholder)"]}),B($,{dimColor:!0,children:[" ",Hn(w,"releaseNotes/")]}),B($,{dimColor:!0,children:[" ",Hn(w,".gitignore")," (adds .kizenapp/)"]})]}),I(dt,{text:"Enter to create \xB7 Esc to go back"})]})}return i.type==="resolving-target"?I(K,{paddingY:1,paddingX:2,children:I($,{dimColor:!0,children:"Finding available sub-directory\u2026"})}):i.type==="writing"?I(K,{paddingY:1,paddingX:2,children:I($,{dimColor:!0,children:"Creating plugin\u2026"})}):i.type==="done"?B(K,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(J,{}),B($,{color:"green",bold:!0,children:["Plugin created at ",i.targetDir]}),B(K,{flexDirection:"column",gap:0,children:[I($,{dimColor:!0,children:"Next steps:"}),B($,{children:[" ","cd ",i.targetDir]}),B($,{children:[" ","npx --yes @kizenapps/cli dev"]}),B($,{dimColor:!0,children:[" ","Replace src/thumbnail.png with real artwork before publishing."]})]}),I(dt,{text:"Enter or Esc to exit"})]}):B(K,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(J,{}),I($,{color:"red",bold:!0,children:"Failed to create plugin"}),I($,{children:i.message}),I(dt,{text:"Enter or Esc to exit"})]})};async function Ba(e){let t=await e.listSessions().catch(()=>[]);if(t.length===0){let i=await e.loadGlobalCredentials();return{businessId:i?.businessId??"",environment:i?.environment??"go"}}let n=await nt(e.requestedEnvironment?.trim()||void 0,()=>Promise.resolve(t)),r=n.ok?n.environment:"go";return{businessId:(await e.readSession(r).catch(()=>null))?.businessId??"",environment:r}}var om="A hello-world Kizen plugin.",Fa=e=>Object.entries(e).some(([t,n])=>t!=="includeLib"&&n!==void 0);function im(e){if(e===void 0||e.trim()===""||e.trim()==="all")return[...se];if(e.trim()==="none")return[];let t=e.split(",").map(r=>r.trim()).filter(r=>r!==""),n=t.filter(r=>!se.includes(r));if(n.length>0)throw new Error(`Unknown artifact type(s): ${n.join(", ")}. Valid types: ${se.join(", ")}, or "all" / "none".`);return[...new Set(t)]}function sm(e,t,n){let r=e.name?.trim()??"";if(r==="")throw new Error("--name is required for a non-interactive run.");let o=(e.apiName?.trim()??"")||zn(r);if(!yo.test(o))throw new Error(`api_name "${o}" is invalid: ${bo}. Pass --api-name.`);let i=e.description?.trim(),s=e.businessId?.trim()??t.businessId,a=am(e,t);return{targetDir:n,name:r,apiName:o,externalLink:e.externalLink?.trim()??"",description:i===void 0||i===""?om:i,developerBusinessId:s,developerEnvironment:a,artifacts:im(e.artifacts),includeLib:e.includeLib===!0}}function am(e,t){let n=e.environment?.trim();if(n!==void 0&&n!==""){if(!St(n))throw new Error(`Unknown environment "${n}". Valid environments: ${W.join(", ")}.`);return n}if(e.businessId!==void 0&&t.businessId==="")throw new Error("--environment is required alongside --business-id when neither a sign-in session nor saved credentials give a default business, so the id is keyed to the environment that issued it.");return t.environment}async function ja(e,t,n,r){let o;try{o=sm(e,t,n)}catch(a){r.writeStderr(`Error: ${a instanceof Error?a.message:String(a)}
|
|
1009
|
+
`;var 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)}
|
|
994
1012
|
`),r.setExitCode(1);return}let i=await r.precheckTargetDir(n);if(i!=="ok"){let a=i==="has-manifest"?"kizen.json":".kizenapp/";r.writeStderr(`Error: ${n} already contains ${a}. Refusing to overwrite an existing plugin.
|
|
995
1013
|
`),r.setExitCode(1);return}try{await r.createPlugin(o)}catch(a){r.writeStderr(`Error: ${a instanceof Error?a.message:String(a)}
|
|
996
1014
|
`),r.setExitCode(1);return}let s=o.artifacts&&o.artifacts.length>0?o.artifacts.join(", "):"none";r.writeStdout(`Created plugin ${o.apiName} at ${n}
|
|
997
1015
|
`),r.writeStdout(`Artifacts: ${s}
|
|
998
1016
|
`),r.writeStdout(`Thumbnail: src/thumbnail.png (generated placeholder; replace it before publishing)
|
|
999
1017
|
`),o.developerBusinessId.trim()===""&&r.writeStderr(`Warning: no developer_business_id configured, so this plugin cannot be preview-published yet.
|
|
1000
|
-
`)}function
|
|
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
|
|
1001
1019
|
bcrypt
|
|
1002
1020
|
boto3
|
|
1003
1021
|
fpdf2
|
|
@@ -1015,8 +1033,7 @@ pytz
|
|
|
1015
1033
|
requests
|
|
1016
1034
|
sqlalchemy>=2.0,<2.1
|
|
1017
1035
|
tzdata
|
|
1018
|
-
`;import{AUTOMATION_SCRIPT_RUNTIMES as
|
|
1019
|
-
`).map(t=>t.trim().replace(/\s+#.*$/,"")).filter(t=>t.length>0&&!t.startsWith("#"))}function Va(e){let t=/^python-(\d+)[.-](\d+)$/.exec(e),n=t?.[1],r=t?.[2];return n!==void 0&&r!==void 0?`python${n}.${r}`:"python3"}function mm(e){return e==null||e.trim()===""?null:e}function hm(e){return e==null?null:typeof e=="string"?mm(e):typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):typeof e=="function"||typeof e=="symbol"?null:JSON.stringify(e)}function Ka(e){return e?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,hm(n)])):{}}var xm=`
|
|
1036
|
+
`;import{AUTOMATION_SCRIPT_RUNTIMES as 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=`
|
|
1020
1037
|
import sys, json, os, traceback
|
|
1021
1038
|
|
|
1022
1039
|
# --- Inputs proxy (attribute access) ---
|
|
@@ -1176,29 +1193,29 @@ sys.stdout.write('\\n__KIZEN_RESULT_START__\\n')
|
|
|
1176
1193
|
sys.stdout.write(json.dumps(result, ensure_ascii=False))
|
|
1177
1194
|
sys.stdout.write('\\n__KIZEN_RESULT_END__\\n')
|
|
1178
1195
|
sys.stdout.flush()
|
|
1179
|
-
`.trim(),
|
|
1180
|
-
`);for(;
|
|
1181
|
-
`)}}),c.on("end",()=>{if(
|
|
1182
|
-
`).trim(),u=g.length>0?`: ${g}`:"";o(new Error(`${e} exited with code ${String(c)}${u}`))}})})}var So=null;function Pm(e,t){if(zt)return t&&So?.add(t),zt;let n=new Set;t&&n.add(t),So=n;let r=i=>{for(let s of n)s(i)},o=Ut(Kn,"bin","python");return zt=(async()=>{try{let i=!1;try{await ym(o);let s=await Xa(o);i=s!==null&&Ya(s)}catch{i=!1}if(!i){await Po(Kn,{recursive:!0,force:!0}).catch(()=>{});let s=await Sm(e);await qa(s,["-m","venv",Kn])}return r({kind:"start"}),await qa(o,["-m","pip","install","--disable-pip-version-check",...Ga],(s,a)=>{r({kind:"log",line:s,stream:a})}),r({kind:"complete"}),o}catch(i){let s=i instanceof Error?i.message:String(i);throw r({kind:"error",message:s}),zt=null,await Po(Kn,{recursive:!0,force:!0}).catch(()=>{}),i}finally{So=null}})(),zt}function Em(e){let t="__KIZEN_RESULT_START__",n="__KIZEN_RESULT_END__",r=e.indexOf(t),o=e.indexOf(n);if(r===-1||o===-1)return{userStdout:e,result:null};let i=e.slice(0,r).trimEnd(),s=e.slice(r+t.length,o).trim();try{let a=JSON.parse(s);return{userStdout:i,result:a}}catch{return{userStdout:e,result:null}}}function _m(e){return{success:!1,outputValues:{},logs:[],stdout:"",stderr:"",error:e,exitCode:1,durationMs:0}}async function Za(e){let t=e.timeout??km;if(!vm(e.scriptRuntime))return _m(`Unsupported runtime "${e.scriptRuntime}". Supported runtimes: ${Cm.join(", ")}. Update the step's config.json "runtime" field (e.g. "python 3.13").`);let r=await Pm(Ja(e.scriptRuntime),e.onInstallProgress),o=Date.now(),i;try{i=await gm(Ut(bm(),"kizen-step-"));let s=Ut(i,"wrapper.py"),a=Ut(i,"script.py");await Promise.all([Wa(s,xm,"utf-8"),Wa(a,e.script,"utf-8")]);let c={...process.env,__KIZEN_INPUTS__:JSON.stringify(e.inputs),__KIZEN_SECRETS__:JSON.stringify(e.secrets),__KIZEN_SCRIPT_PATH__:a},{exitCode:g,stdout:u,stderr:h}=await new Promise(C=>{let E=[],x=[],y=!1,P=Eo(r,[s],{env:c,cwd:i,stdio:["ignore","pipe","pipe"]}),b=setTimeout(()=>{P.kill("SIGKILL")},t);P.stdout.on("data",d=>{E.push(d)}),P.stderr.on("data",d=>{x.push(d)});let f=d=>{y||(y=!0,clearTimeout(b),C({exitCode:d??1,stdout:Buffer.concat(E).toString("utf-8"),stderr:Buffer.concat(x).toString("utf-8")}))};P.on("close",f),P.on("error",d=>{y||(y=!0,clearTimeout(b),C({exitCode:1,stdout:"",stderr:d.message}))})}),v=Date.now()-o,{userStdout:p,result:l}=Em(u);if(l){let C={success:l.success,outputValues:l.outputValues,logs:l.logs,stdout:p,stderr:h,exitCode:g,durationMs:v};return l.error!==null&&(C.error=l.error),l.httpRequests&&(C.httpRequests=l.httpRequests),C}let w={success:!1,outputValues:{},logs:[],stdout:p,stderr:h,exitCode:g,durationMs:v};return g!==0&&(w.error=`Process exited with code ${String(g)}`),w}finally{i&&Po(i,{recursive:!0,force:!0})}}var Qa=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".json",".md",".mdx",".yml",".yaml",".toml",".css",".scss",".html",".htm",".xml",".svg",".txt",".sh",".py",".env",".gitignore",".prettierrc",".eslintrc"]);import{CRYPTO_ALG as rc,CRYPTO_VERSION as oc,DEFAULT_AUTOMATION_RUNTIME as Bm,deserializeEnvelope as Fm,encrypt as jm,scriptRuntimeToApiName as Lm,serializeEnvelope as Mm}from"@kizenapps/packager";function _o(e){if(e.kind==="info")return e.message;let t=e.fromCache?" [cache]":"",n=e.upstreamStatus!==void 0?` (upstream ${String(e.upstreamStatus)})`:"";return`${e.method} ${e.url} \u2192 ${String(e.status)}${n}${t}`}var zm=2*1024*1024,Um=new Set([".DS_Store",".gitignore"]);function Hm(e){if(e===void 0||e==="")return!1;let t=e.startsWith("[")?e.slice(0,e.indexOf("]")+1):e.split(":")[0]??"";return t==="localhost"||t==="127.0.0.1"||t==="[::1]"}var cc=["kizen.com","kizen.dev"];function Vm(e){let t;try{t=new URL(e)}catch{return!1}let n=t.hostname.toLowerCase();return n==="localhost"||n==="127.0.0.1"||n==="[::1]"?!0:t.protocol!=="https:"?!1:cc.some(r=>n===r||n.endsWith("."+r))}function Km(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let n=t.hostname.toLowerCase();return cc.some(r=>n===r||n.endsWith("."+r))}function Wm(e){if(e===void 0||e==="")return!1;try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"}catch{return!1}}async function ic(e,t){if(t.includes("\0"))return null;let n=t.replace(/^\/+/,""),r=Rm(e,n);if(r!==e&&!r.startsWith(e+To))return null;try{let o=await Nm(r);return o!==e&&!o.startsWith(e+To)?null:o}catch{return null}}function sc(e,t){let n=t===e?"":t.slice(e.length+1);return n===""?!1:n.split(To).some(o=>bn.has(o))}function lc(){let e=Om(import.meta.url);return Vt(Dm(e),"viewer")}function ac(e,t,n){if(e.includes("/external-integrations/proxy")&&t["content-type"]?.includes("application/json"))try{let r=JSON.parse(n.toString("utf8"));return typeof r.status_code=="number"?r.status_code:void 0}catch{return}}async function Ao(e){try{return await Am(e),!0}catch{return!1}}function dc(e,t,n,r,o,i,s,a,c,g,u){let h=za({onChange:a,enabled:u}),v=Tm(g);return(p,l)=>{(async()=>{let w=p.url??"/";try{if(!Hm(p.headers.host)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Forbidden"}));return}if((p.method==="POST"||p.method==="PATCH"||p.method==="DELETE")&&!Wm(p.headers.origin)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Forbidden"}));return}if(t(`Received request: ${w}`),w==="/api/credentials"){l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({credentials:r.current??null,activeProfile:o.current??null}));return}if(w==="/api/credential-profiles"&&p.method==="GET"){let f=await je();l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({profiles:f,active:o.current}));return}if(w==="/api/credentials/switch"&&p.method==="POST"){let f=[];for await(let S of p)f.push(S);let m=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}").profile,k=m===void 0||m===""?await oe():await Pe(m);if(k!==null){r.current=k,o.current=m??void 0;let S=o.current,T=await we(i);await Ve(i,{...T,credentialMode:"global",...S!==void 0&&{activeCredentialProfile:S}}),s({type:"credentials-updated",credentials:k,activeProfile:o.current??null})}l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({ok:k!==null}));return}if(w==="/api/bundle"){let f=Vt(process.cwd(),".kizenapp","bundle.json");try{let d=await $m(f,"utf-8");l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(d)}catch{l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end("{}")}return}if(w==="/api/last-path"&&p.method==="POST"){let f=[];for await(let m of p)f.push(m);let d=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}");if(typeof d.path=="string"){c.current=d.path;let m=await we(i);await Ve(i,{...m,lastPath:d.path})}l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end('{"ok":true}');return}if(w==="/api/encryption-target"&&p.method==="GET"){let d=(await we(i)).encryptionTarget==="dev"?"dev":"prod";l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({target:d}));return}if(w==="/api/encryption-target"&&p.method==="POST"){let f=[];for await(let S of p)f.push(S);let d=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}"),m=d!==null&&typeof d=="object"?d:{};if(m.target!=="dev"&&m.target!=="prod"){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"target must be one of: 'dev', 'prod'"}));return}let k=await we(i);await Ve(i,{...k,encryptionTarget:m.target}),l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end('{"ok":true}');return}if(w==="/api/execute-step"&&p.method==="POST"){let f=[];for await(let S of p)f.push(S);let d=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}");if(typeof d.script!="string"){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing required field: script"}));return}let m={script:d.script,scriptRuntime:d.scriptRuntime??Lm(Bm),inputs:Ka(d.inputs),secrets:d.secrets??{},onInstallProgress:S=>{S.kind==="start"?s({type:"venv-install-start"}):S.kind==="log"?s({type:"venv-install-log",line:S.line,stream:S.stream}):S.kind==="complete"?s({type:"venv-install-complete"}):s({type:"venv-install-error",message:S.message})}};typeof d.timeout=="number"&&d.timeout>0&&(m.timeout=Math.min(d.timeout,300*1e3));let k=await Za(m);l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify(k));return}if(w==="/api/proxy-cache/clear"){h.clear(),n({kind:"info",message:"Proxy cache cleared"}),l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end('{"ok":true}');return}if(w==="/api/local/encrypt"&&p.method==="POST"){let f=[];for await(let m of p)f.push(m);let d=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}");if(typeof d.publicKeyPem!="string"||typeof d.value!="string"){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing required fields: publicKeyPem, value"}));return}try{let m=jm(d.value,d.publicKeyPem),k=Mm(m);l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify(k))}catch(m){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:m.message}))}return}if(w==="/api/local/validate"&&p.method==="POST"){let f=[];for await(let _ of p)f.push(_);let d=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}");if(typeof d.value!="string"){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing required field: value"}));return}let m,k;try{m=Fm(d.value)}catch(_){k=_.message}if(k!==void 0||m===void 0){l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({valid:!1,checks:[],error:k}));return}let S=_=>Buffer.from(_,"base64").length,T=[{label:"Version",expected:String(oc),actual:String(m.v),pass:m.v===oc},{label:"Algorithm",expected:rc,actual:m.alg,pass:m.alg===rc},{label:"Wrapped key",expected:"384 bytes (RSA-3072)",actual:`${String(S(m.k))} bytes`,pass:S(m.k)===384},{label:"IV",expected:"12 bytes",actual:`${String(S(m.iv))} bytes`,pass:S(m.iv)===12},{label:"Auth tag",expected:"16 bytes",actual:`${String(S(m.tag))} bytes`,pass:S(m.tag)===16},{label:"Ciphertext",expected:"\u2265 1 byte",actual:`${String(S(m.ct))} bytes`,pass:S(m.ct)>=1}];l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({valid:T.every(_=>_.pass),checks:T}));return}if(w.startsWith("/api/wizard")){let f=p.headers["x-encryption-target"],m=(Array.isArray(f)?f[0]:f)==="dev"?"dev":"prod",k=Mt(m);if(!Vm(k)){l.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:`Encryption API host is not allowed: ${k}`}));return}let S=w.slice(11)||"/",T=`${k}${S}`,_=p.method??"GET",R=[];for await(let Xe of p)R.push(Xe);let{host:z,"x-encryption-target":ee,...ae}=p.headers,me=R.length>0?Buffer.concat(R):void 0,he=me&&me.length>0?me:void 0,ue;try{ue=await fetch(T,{method:_,headers:ae,...he!==void 0&&{body:he}})}catch(Xe){let nr=Xe.code==="ECONNREFUSED"?`plugin-wizard is not running at ${k}`:`Failed to reach plugin-wizard: ${Xe.message}`;l.writeHead(503,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:nr}));return}let de=Vn(Object.fromEntries(ue.headers)),vt=await ue.arrayBuffer();l.writeHead(ue.status,de),l.end(Buffer.from(vt));return}if(w.startsWith("/api/proxy")){let f=p.headers["x-proxy-target"];if(typeof f!="string"){l.writeHead(400),l.end("Missing x-proxy-target header");return}if(!Km(f)){l.writeHead(400),l.end("Invalid proxy target");return}let d=w.slice(10)||"/",m=`${f}${d}`,k=p.method??"GET",S=[];for await(let ue of p)S.push(ue);let{host:T,"x-proxy-target":_,...R}=p.headers;if(k==="GET"){let ue=`GET::${m}`,{response:de,fromCache:vt}=await h.get(ue,()=>fetch(m,{method:"GET",headers:R}));n({kind:"request",method:"GET",status:de.status,upstreamStatus:ac(d,de.headers,de.body),fromCache:vt,url:d}),l.writeHead(de.status,de.headers),l.end(de.body);return}let z=S.length>0?Buffer.concat(S):void 0,ee=z&&z.length>0?z:void 0,ae=await fetch(m,{method:k,headers:R,...ee!==void 0&&{body:ee}}),me=Vn(Object.fromEntries(ae.headers)),he=await vo(ae,wo);n({kind:"request",method:k,status:ae.status,upstreamStatus:ac(d,me,he),fromCache:!1,url:d}),l.writeHead(ae.status,me),l.end(he);return}if(w.startsWith("/api/source/tree")&&p.method==="GET"){let d=new URL(w,"http://localhost").searchParams.get("path")??"",m=await ic(v,d);if(m===null){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Invalid path"}));return}if(sc(v,m)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Path is excluded"}));return}try{let k=await Im(m,{withFileTypes:!0}),S=await Promise.all(k.filter(_=>_.isDirectory()?!bn.has(_.name):_.isFile()?!Um.has(_.name):!1).map(async _=>{let R=_.isDirectory()?"dir":"file",z={name:_.name,kind:R};if(R==="file")try{let ee=await tc(Vt(m,_.name));z.size=ee.size}catch{}return z}));S.sort((_,R)=>_.kind!==R.kind?_.kind==="dir"?-1:1:_.name.localeCompare(R.name));let T=m===v?"":m.slice(v.length+1);l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({path:T,entries:S}))}catch(k){let S=k instanceof Error?k.message:String(k);t(`source/tree failed (${d}): ${S}`),l.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Not found"}))}return}if(w.startsWith("/api/source/file")&&p.method==="GET"){let d=new URL(w,"http://localhost").searchParams.get("path")??"";if(d===""){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing path"}));return}let m=await ic(v,d);if(m===null){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Invalid path"}));return}if(sc(v,m)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Path is excluded"}));return}try{let k=await tc(m);if(!k.isFile()){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Not a file"}));return}if(k.size>zm){l.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"File too large",size:k.size}));return}let S=nc(m).toLowerCase(),T=xo[S],_=Qa.has(S),R=T??(_?"text/plain; charset=utf-8":"application/octet-stream");l.writeHead(200,{"Content-Type":R,"Content-Length":String(k.size)}),ec(m).pipe(l)}catch(k){let S=k instanceof Error?k.message:String(k);t(`source/file failed (${d}): ${S}`),l.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Not found"}))}return}let x=Vt(e,w==="/"?"/index.html":w),y=await Ao(x)?x:Vt(e,"index.html"),P=nc(y),b=xo[P]??"application/octet-stream";l.writeHead(200,{"Content-Type":b}),ec(y).pipe(l)}catch(C){if(w.startsWith("/api/proxy")){let E=w.slice(10)||"/",x=p.method??"GET";C instanceof Lt?n({kind:"info",message:`${x} ${E} \u2192 502 (response exceeded ${String(C.limit)} bytes)`}):n({kind:"request",method:x,status:502,fromCache:!1,url:E})}else n({kind:"info",message:`Error handling ${w}: ${C instanceof Error?C.message:String(C)}`});l.headersSent||(l.writeHead(502),l.end("Bad Gateway"))}})()}}import{launch as qm}from"chrome-launcher";import{createRequire as Jm}from"module";import{mkdirSync as Gm}from"fs";import{readFile as Ym}from"fs/promises";import{dirname as Xm,join as Zm}from"path";import{fileURLToPath as Qm}from"url";var uc=Jm(import.meta.url)("chrome-remote-interface"),eh=new Set(["content-security-policy","content-security-policy-report-only","x-frame-options"]),fc=["kizen.dev","kizen.com"];function pc(e){try{let{hostname:t}=new URL(e);return fc.some(n=>t===n||t.endsWith("."+n))}catch{return!1}}async function th(e){try{let t=Zm(Xm(Qm(import.meta.url)),"viewer","icon.png"),n=await Ym(t);await e.Browser.setDockTile({image:n.toString("base64")})}catch{}}async function mc(e){Gm(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,n=await qm({startingUrl:t,chromeFlags:[`--app=${t}`,"--no-first-run","--no-default-browser-check","--disable-extensions","--disable-features=DeviceBoundSessions"],userDataDir:e.userDataDir,handleSIGINT:!1,logLevel:"silent"}),r=n.port,o=null,i=null,s=null,a=null,c=0,g=!1,u=y=>{e.debugLog?.(y)},h=y=>{e.verbose&&e.debugLog?.(y)},v=()=>{i!==null&&(clearInterval(i),i=null)},p=y=>y==="chrome://new-tab-page/"||y==="chrome://newtab/",l=async y=>{v(),s=null,await th(y),await y.Fetch.enable({patterns:fc.flatMap(b=>[{urlPattern:`*://${b}/*`,requestStage:"Response"},{urlPattern:`*://*.${b}/*`,requestStage:"Response"}])}),y.on("Fetch.requestPaused",b=>{(async()=>{let f=b,{requestId:d,request:m,responseHeaders:k,responseStatusCode:S}=f,T=m.url;h(`Fetch ${String(S??"?")} ${T}`);let _=[],R=!1;for(let z of k??[])if(!eh.has(z.name.toLowerCase()))if(z.name.toLowerCase()==="set-cookie"&&pc(T)){let ee=z.value.split(`
|
|
1183
|
-
`).map(
|
|
1184
|
-
`);_.push({name:z.name,value:ee}),R=!0}else _.push(z);R&&h(` rewrote Set-Cookie SameSite on ${T}`);try{let{body:z,base64Encoded:ee}=await y.Fetch.getResponseBody({requestId:d});await y.Fetch.fulfillRequest({requestId:d,responseCode:S??200,responseHeaders:_,body:z,...ee&&{base64Encoded:!0}})}catch(z){h(` fulfillRequest failed (${z.message}), falling through`);try{await y.Fetch.continueRequest({requestId:d})}catch(ee){h(` continueRequest also failed (${ee.message})`)}}})()}),i=setInterval(()=>{(async()=>{try{let{cookies:b}=await y.Network.getAllCookies(),f=0;for(let d of b){if(!pc(`https://${d.domain??""}`)||d.sameSite==="None")continue;let m=d.domain??"",k=m.startsWith(".")?m.slice(1):m;await y.Network.setCookie({url:`https://${k}`,name:d.name,value:d.value,domain:m,path:d.path??"/",secure:!0,...d.httpOnly!==void 0&&{httpOnly:d.httpOnly},...d.expirationDate!==void 0&&{expires:d.expirationDate},sameSite:"None"}),f++}f>0&&h(`cookie-patch cycle: updated ${String(f)} cookie(s) to SameSite=None`)}catch(b){h(`cookie-patch cycle failed: ${b.message}`)}})()},2e3),await y.Target.setDiscoverTargets({discover:!0});let P=b=>{if(b.type==="page"){if(p(b.url)){u(`closed stray new-tab-page target ${b.targetId}`),s!==null&&y.Target.activateTarget({targetId:s}).catch(()=>{}),y.Target.closeTarget({targetId:b.targetId}).catch(()=>{});return}s===null&&(s=b.targetId,u(`captured main target ${b.targetId} (${b.url})`))}};y.on("Target.targetCreated",b=>{let{targetInfo:f}=b;h(`target +${f.type} ${f.targetId} ${f.url}`),P(f)}),y.on("Target.targetInfoChanged",b=>{let{targetInfo:f}=b;h(`target ~${f.type} ${f.targetId} ${f.url}`),P(f)}),y.on("disconnect",()=>{g||o!==y||(u("CDP disconnected"),o=null,v(),w())})},w=()=>{if(g||a!==null)return;let y=Math.min(1e3*2**c,1e4),P=c+1;c++,u(`CDP reconnect scheduled in ${String(y)}ms (attempt #${String(P)})`),a=setTimeout(()=>{a=null,(async()=>{let b;try{b=await uc({port:r})}catch{u(`CDP reconnect attempt #${String(P)} failed`),w();return}if(g){try{await b.close()}catch{}return}o=b;try{await l(b),u(`CDP reconnected after ${String(P)} attempt(s)`),c=0}catch{o===b&&(o=null);try{await b.close()}catch{}u(`CDP reconnect attempt #${String(P)} failed during setup`),w()}})()},y)},C=30,E=300;for(let y=0;y<C;y++){await new Promise(P=>setTimeout(P,E)),u(`CDP connect attempt ${String(y+1)}/${String(C)}`);try{let P=await uc({port:r});o=P,e.path&&P.send("Page.navigate",{url:`${t}${e.path}`});try{await l(P),u("CDP connected")}catch{o===P&&(o=null);try{await P.close()}catch{}u("CDP setup failed after connect")}break}catch{if(y===C-1){let P=`CDP unavailable after ${String(C)} attempts \u2014 viewer running without interception (CSP/cookie rewrites disabled)`;return u(P),e.onWarn?.(P),{kill:()=>{n.kill()}}}}}return o?{kill:()=>{if(u("CDP kill requested \u2014 tearing down"),g=!0,a!==null&&(clearTimeout(a),a=null),v(),o!==null){try{o.close()}catch{}o=null}n.kill()}}:{kill:()=>{n.kill()}}}import{useCallback as nh,useState as rh}from"react";function Wn(e){let[t,n]=rh([]),r=nh(o=>{n(i=>[...i,`${new Date().toLocaleTimeString()}: ${o}`].slice(-e))},[e]);return[t,r]}import{useCallback as qn,useEffect as Io,useState as Jn}from"react";import{Box as Q,Text as M,useInput as oh}from"ink";import{jsx as N,jsxs as te}from"react/jsx-runtime";var Ge=["apiKey","userId","businessId"],ih={apiKey:"API Key",userId:"User ID",businessId:"Business ID"},Kt=({text:e})=>N(M,{dimColor:!0,children:e}),Gn=({initialMode:e,showProfileManager:t,onComplete:n,onCancel:r})=>{let[o,i]=Jn(e==="global"&&!t?{type:"loading"}:e==="global"&&t?{type:"profile-loading"}:{type:"mode-select",cursor:0}),[s,a]=Jn(""),[c,g]=Jn(null),[u,h]=Jn(void 0),v=qn(b=>{if(b==="local"){n({mode:"local",credentials:null});return}i({type:"profile-loading"})},[n]),p=qn(async b=>{if(b===null){i({type:"profile-loading"});let m=await je();i({type:"name-entry",nameBuffer:"",existingProfiles:m});return}h(b.isDefault?void 0:b.name),i({type:"loading"});let f=b.isDefault?await oe():await Pe(b.name),d=f?Math.max(0,W.indexOf(f.environment)):0;i({type:"creds-entry",field:0,values:f??{},envCursor:d})},[]),l=qn(async(b,f)=>{let d=W[f]??"go",m={...Ct(b),environment:d};i({type:"saving"});try{await Ho(u??Be,m),n({mode:"global",credentials:m,...u!==void 0&&{profileName:u}})}catch(k){g(k instanceof Error?k.message:String(k)),i({type:"creds-entry",field:0,values:b,envCursor:f})}},[n,u]);oh((b,f)=>{if(f.ctrl&&b==="c"&&process.exit(0),f.escape){if((o.type==="creds-entry"||o.type==="name-entry")&&e==="global"&&t){i({type:"profile-loading"}),w();return}r?.();return}if(o.type==="mode-select"){if(f.upArrow)i({type:"mode-select",cursor:0});else if(f.downArrow)i({type:"mode-select",cursor:1});else if(f.return){let d=o.cursor===0?"global":"local";v(d)}return}if(o.type==="profile-select"){let{profiles:d,cursor:m}=o,k=d.length,S=d.length+1;if(f.upArrow)i({...o,cursor:(m-1+S)%S});else if(f.downArrow)i({...o,cursor:(m+1)%S});else if(f.return)if(m===k)i({type:"name-entry",nameBuffer:"",existingProfiles:d});else{let T=d[m]??d[0];T&&p(T)}return}if(o.type==="name-entry"){let{nameBuffer:d,existingProfiles:m}=o;if(f.backspace||f.delete)i({type:"name-entry",nameBuffer:d.slice(0,-1),existingProfiles:m});else if(f.return){let k=d.trim();if(!k){i({...o,nameError:"Name cannot be empty"});return}if(k===Be){i({...o,nameError:`"${Be}" is reserved`});return}if(m.some(S=>S.name===k)){i({...o,nameError:`Profile "${k}" already exists`});return}h(k),i({type:"creds-entry",field:0,values:{},envCursor:0}),a("")}else b&&!f.ctrl&&!f.meta&&i({type:"name-entry",nameBuffer:d+b,existingProfiles:m});return}if(o.type==="creds-entry"){let{field:d,values:m,envCursor:k}=o;if(d===Ge.length){f.leftArrow?i({...o,envCursor:(k-1+W.length)%W.length}):f.rightArrow?i({...o,envCursor:(k+1)%W.length}):f.upArrow?(i({...o,field:d-1}),a(m[Ge[d-1]]??"")):f.return&&l(m,k);return}let T=Ge[d];if(!T)return;if(f.backspace||f.delete)a(_=>_.slice(0,-1));else if(f.upArrow&&d>0){let _={...m,[T]:s},R=d-1;i({...o,field:R,values:_}),a(_[Ge[R]]??"")}else if(f.return||f.tab||f.downArrow){let _={...m,[T]:s},R=d+1;i({...o,field:R,values:_}),R<Ge.length?a(_[Ge[R]]??""):a("")}else b&&!f.ctrl&&!f.meta&&a(_=>_+b)}});let w=qn(async()=>{let b=await je();i({type:"profile-select",profiles:b,cursor:0})},[]);if(Io(()=>{o.type==="profile-loading"&&w()},[o.type,w]),Io(()=>{e==="global"&&!t&&(async()=>{let b=await oe(),f=b?Math.max(0,W.indexOf(b.environment)):0;i({type:"creds-entry",field:0,values:b??{},envCursor:f})})()},[]),Io(()=>{o.type==="creds-entry"&&o.field===0&&a(o.values.apiKey??"")},[o.type]),o.type==="loading"||o.type==="saving"||o.type==="profile-loading"){let b=o.type==="saving"?"Saving credentials\u2026":o.type==="profile-loading"?"Loading profiles\u2026":"Loading credentials\u2026";return N(Q,{paddingY:1,paddingX:2,children:N(M,{dimColor:!0,children:b})})}if(o.type==="done")return null;if(o.type==="mode-select")return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[N(J,{}),te(Q,{flexDirection:"column",gap:0,children:[N(M,{bold:!0,children:"Credential mode"}),[{label:"Global",desc:"~/.kizenappbuilder/credentials.json",mode:"global"},{label:"Local",desc:"Enter credentials in the browser dev tools",mode:"local"}].map((f,d)=>{let m=o.cursor===d;return te(Q,{gap:2,children:[N(M,{...m&&{color:"cyan"},children:m?"\u276F":" "}),N(M,{bold:m,...m&&{color:"cyan"},children:f.label}),N(M,{dimColor:!0,children:f.desc})]},f.mode)})]}),N(Kt,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]});if(o.type==="profile-select"){let{profiles:b,cursor:f}=o,d=b.length;return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[N(J,{}),te(Q,{flexDirection:"column",gap:0,children:[N(M,{bold:!0,children:"Credential profiles"}),b.map((m,k)=>{let S=f===k;return te(Q,{gap:2,children:[N(M,{...S&&{color:"cyan"},children:S?"\u276F":" "}),N(M,{bold:S,...S&&{color:"cyan"},children:m.isDefault?"Default":m.name}),N(M,{dimColor:!0,children:m.path})]},m.name)}),te(Q,{gap:2,children:[N(M,{...f===d&&{color:"cyan"},children:f===d?"\u276F":" "}),N(M,{bold:f===d,...f===d&&{color:"cyan"},children:"+ Add new profile"})]})]}),N(Kt,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(o.type==="name-entry"){let{nameBuffer:b,nameError:f}=o;return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[N(J,{}),N(Q,{flexDirection:"column",gap:0,children:N(M,{bold:!0,children:"New credential profile"})}),f&&te(M,{color:"red",children:["Error: ",f]}),te(Q,{gap:2,children:[N(Q,{width:12,children:N(M,{bold:!0,color:"cyan",children:"Profile name"})}),N(M,{color:"cyan",children:">"}),N(M,{children:b}),N(M,{color:"cyan",children:"\u2588"})]}),N(Kt,{text:"Type a name \xB7 Enter to confirm \xB7 Esc to go back"})]})}let{field:C,values:E,envCursor:x}=o,y=C===Ge.length,P=u??Be;return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[N(J,{}),te(Q,{flexDirection:"column",gap:0,children:[N(M,{bold:!0,children:u!==void 0?`Profile: ${u}`:"Global credentials"}),te(M,{dimColor:!0,children:["Saved to:"," ",u!==void 0?`~/.kizenappbuilder/${u}.json`:Oe]})]}),c&&te(M,{color:"red",children:["Error: ",c]}),te(Q,{flexDirection:"column",gap:0,children:[Ge.map((b,f)=>{let d=C===f,m=d?s:E[b]??"";return te(Q,{gap:2,children:[N(Q,{width:12,children:N(M,{bold:d,...d&&{color:"cyan"},children:ih[b]})}),N(M,{...d&&{color:"cyan"},children:">"}),N(M,{children:m}),d&&N(M,{color:"cyan",children:"\u2588"})]},b)}),te(Q,{gap:2,children:[N(Q,{width:12,children:N(M,{bold:y,...y&&{color:"cyan"},children:"Environment"})}),N(M,{...y&&{color:"cyan"},children:">"}),N(Q,{gap:1,children:W.map((b,f)=>{let d=f===x;return y?N(M,{bold:d,...d&&{color:"cyan"},children:d?`[${b}]`:b},b):N(M,{dimColor:!d,bold:d,children:b},b)})})]})]}),y?N(Kt,{text:"\u2190\u2192 to select \xB7 \u2191\u2193 to move \xB7 Enter to save \xB7 Esc to cancel"}):N(Kt,{text:"\u2191\u2193 to move \xB7 Backspace to delete \xB7 Esc to cancel"}),te(M,{dimColor:!0,children:["Profile: ",P]})]})};import{jsx as j,jsxs as X}from"react/jsx-runtime";var ph=[".kizenapp",".git"],gc=({port:e,pluginDir:t,outputDir:n,credentials:r,credentialMode:o,activeCredentialProfile:i,lastPath:s,debug:a=!1,verbose:c=!1,autoViewer:g=!0,cacheEnabled:u=!0})=>{let h=$e(r),v=$e(i),p=$e(s),[l,w]=le("main"),[C,E]=le(o),[x,y]=le("starting"),[P,b]=le(null),[f,d]=Wn(50),[m,k]=Wn(50),[S,T]=Wn(50),[_,R]=le([]),[z,ee]=le("pending"),[ae,me]=le(null),[he,ue]=le(null),[de,vt]=le(null),[Xe,nr]=le(null),[rr,or]=le(0),[Ro,nl]=le(0),[rl,ol]=le(0),[ir,il]=le(0),sr=$e(!1),Oo=$e(!1),qt=$e(null),xt=$e(null),Ne=$e(new Set),Jt=$e([]),pe=wt(A=>{let H=JSON.stringify(A);if(Ne.current.size===0){Jt.current=[...Jt.current,H].slice(-50);return}let De=!1;for(let ge of Ne.current)if(ge.readyState===1)try{ge.send(H)}catch{Ne.current.delete(ge),De=!0}De&&or(Ne.current.size)},[]),Gt=d,ar=wt(()=>{qt.current?.kill(),qt.current=null,mc({port:e,userDataDir:hc(n,".chrome"),broadcast:pe,onWarn:A=>{d(`\u26A0 ${A}`)},...p.current!==void 0&&{path:p.current},...a&&{debugLog:T},...c&&{verbose:!0}}).then(A=>{qt.current=A})},[e,n,pe,a,c,T,d]);Yn(()=>{let A=()=>{qt.current?.kill()};return process.on("exit",A),()=>{process.off("exit",A)}},[]),ah((A,H)=>{(A==="q"||H.ctrl&&A==="c")&&process.exit(0),A==="c"&&w("editing"),A==="v"&&ar()},{isActive:l==="main"}),Yn(()=>{x!=="running"||Oo.current||!g||(Oo.current=!0,ar())},[x,g,ar]);let sl=wt(A=>{h.current=A.credentials,v.current=A.profileName,w("main"),E(A.mode);let H=A.profileName;Ve(n,{credentialMode:A.mode,...H!==void 0&&{activeCredentialProfile:H}}),pe({type:"credentials-updated",credentials:A.credentials})},[n,pe]),Bo=wt(A=>{R(H=>[...H,`${new Date().toLocaleTimeString()}: ${_o(A)}`].slice(-50)),A.kind==="request"&&(A.fromCache?ol(H=>H+1):il(H=>H+1)),pe({type:"proxy-log",entry:A})},[pe]),Ze=wt(A=>{k(A),pe({type:"log",message:A})},[k,pe]),cr=wt(()=>{sr.current||(sr.current=!0,ee("building"),me(null),ue(null),Ze("Build started"),vn(t,n).then(({bundleSize:A})=>{Ze(`Build finished \u2014 bundle: ${Rt(A)}`),ee("done"),vt(new Date),nr(A),Ze("Notifying viewers to reload"),pe({type:"rebuild"})}).catch(A=>{A instanceof ch?(ue(A.issues),me(null)):(me(A instanceof Error?A.message:String(A)),ue(null)),ee("error")}).finally(()=>{sr.current=!1}))},[t,n,Ze,pe]);if(Yn(()=>{cr();let A=lh(t,{recursive:!0},(H,De)=>{if(!De)return;let ge=De.replace(/\\/g,"/");ph.some(Yt=>ge.startsWith(Yt))||(Ze(`File change detected: ${De}`),xt.current!==null&&clearTimeout(xt.current),xt.current=setTimeout(cr,150))});return A.on("error",H=>{Ze(`File watcher error \u2014 rebuilds have stopped: ${H.message}`)}),()=>{A.close(),xt.current!==null&&clearTimeout(xt.current)}},[t,cr,Ze]),Yn(()=>{let A=lc();Ao(hc(A,"index.html")).then(H=>{if(!H){b("Viewer not built. Run 'pnpm build:viewer' first."),y("error");return}let De=dc(A,Gt,Bo,h,v,n,pe,nl,p,t,u),ge=dh(De),Yt=new uh({server:ge});return Yt.on("connection",Qe=>{for(let cl of Jt.current)Qe.readyState===1&&Qe.send(cl);Jt.current=[],Gt("Viewer connected for live reload"),Ne.current.add(Qe),or(Ne.current.size),Qe.on("close",()=>{Ne.current.delete(Qe),or(Ne.current.size)})}),ge.listen(e,"127.0.0.1",()=>{y("running"),Gt(`Server started on 127.0.0.1:${String(e)}`)}),ge.on("error",Qe=>{b(Qe.message),y("error")}),()=>{Yt.close(),ge.close()}})},[e,Gt,Bo,pe,n,t,u]),l==="editing")return j(Gn,{...C!==void 0&&{initialMode:C},showProfileManager:C==="global",onComplete:sl,onCancel:()=>{w("main")}});let lr=de!==null?Math.round((Date.now()-de.getTime())/1e3):null,al=lr===null?"":lr<5?" (just now)":` (${String(lr)}s ago)`,Fo=he?.filter(A=>A.severity==="error").length??0;return X(ne,{flexDirection:"column",paddingY:1,paddingX:2,children:[j(J,{marginBottom:1}),X(ne,{flexDirection:"column",children:[X(ne,{gap:2,marginBottom:0,children:[j(F,{bold:!0,dimColor:!0,children:"App Build"}),z==="pending"&&j(F,{dimColor:!0,children:"waiting\u2026"}),z==="building"&&X(ne,{gap:1,children:[j(xe,{}),j(F,{children:"Building plugin package\u2026"})]}),z==="done"&&X(ne,{gap:1,children:[j(F,{color:"green",children:"\u2713 Built"}),de!==null&&X(F,{dimColor:!0,children:["at ",de.toLocaleTimeString(),al]}),Xe!==null&&X(F,{dimColor:!0,children:["\xB7 bundle: ",Rt(Xe)]})]}),z==="error"&&(he!==null?X(F,{color:"red",children:["\u2717 ",Fo," validation ",Fo===1?"error":"errors"]}):X(F,{color:"red",children:["\u2717 ",ae??"unknown error"]}))]}),he!==null&&j(Rn,{issues:he}),j(ne,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:m.slice(-8).map((A,H)=>j(F,{dimColor:!0,wrap:"truncate",children:A},H))})]}),X(ne,{marginTop:1,flexDirection:"column",children:[X(ne,{gap:2,children:[j(F,{bold:!0,dimColor:!0,children:"Web Server"}),x==="starting"&&j(F,{dimColor:!0,children:"starting\u2026"}),x==="running"&&X(ne,{gap:2,children:[j(F,{color:"green",children:"\u2713 Running"}),X(F,{dimColor:!0,children:["\u25CF ",rr," viewer",rr!==1?"s":""]})]}),x==="error"&&X(F,{color:"red",children:["\u2717 ",P??"Server error"]})]}),j(ne,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:f.slice(-8).map((A,H)=>j(F,{dimColor:!0,wrap:"truncate",children:A},H))})]}),X(ne,{marginTop:1,flexDirection:"column",children:[X(ne,{gap:2,children:[j(F,{bold:!0,dimColor:!0,children:"Network Proxy"}),j(F,{color:"green",children:"\u2713 Active"}),j(F,{dimColor:!0,children:u?`\u25CF ${String(Ro)} key${Ro!==1?"s":""} in the network cache \xB7 ${String(rl)} hit \xB7 ${String(ir)} miss`:`\u25CF network cache disabled \xB7 ${String(ir)} request${ir!==1?"s":""}`})]}),j(ne,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:_.length===0?j(F,{dimColor:!0,children:" No requests yet."}):_.slice(-8).map((A,H)=>j(F,{dimColor:!0,wrap:"truncate",children:A},H))})]}),a&&X(ne,{marginTop:1,flexDirection:"column",children:[X(ne,{gap:2,children:[j(F,{bold:!0,dimColor:!0,children:"CDP Debug"}),X(F,{dimColor:!0,children:["\u25CF ",S.length," event(s)"]})]}),j(ne,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:S.length===0?j(F,{dimColor:!0,children:" No CDP events yet."}):S.slice(-8).map((A,H)=>j(F,{dimColor:!0,wrap:"truncate",children:A},H))})]}),X(ne,{marginTop:1,gap:1,children:[j(F,{dimColor:!0,children:"["}),j(F,{children:"q"}),j(F,{dimColor:!0,children:"] quit ["}),j(F,{children:"c"}),j(F,{dimColor:!0,children:"] credentials ["}),j(F,{children:"v"}),X(F,{dimColor:!0,children:["] ",rr===0?"open viewer":"relaunch viewer"]})]})]})};async function yc(e){return new Promise(t=>{let n=null,r=i=>{n?.(),t(i)},{unmount:o}=wc(bc(Gn,{...e!==void 0&&{initialMode:e},onComplete:r}),{exitOnCtrlC:!1});n=o})}function vc(e){e.command("dev").description("Start the plugin viewer dev server").option("-p, --port <port>","port to listen on","3121").option("-c, --credentials <path>","path to an API-key credentials JSON file (dev still uses API keys; sign-in support is planned)").option("-d, --debug","Enable CDP lifecycle logs in the TUI").option("-v, --verbose","Log every CDP event and handled error (implies --debug)").option("--no-viewer","Don't auto-launch the viewer on startup (press [v] to launch manually)").option("--no-cache","Disable the network proxy cache (always fetch upstream)").action(async t=>{let n=parseInt(t.port,10),r=process.cwd(),o=`${r}/.kizenapp`;ve(r);let i=null,s,a,{lastPath:c}=await we(o);if(t.credentials)i=await Fe(t.credentials);else{let l=await we(o);if(l.credentialMode==="local")s="local";else if(l.credentialMode==="global"){if(s="global",a=l.activeCredentialProfile,a?(i=await Pe(a),i||(i=await oe(),a=void 0)):i=await oe(),!i){let w=await yc("global");i=w.credentials,a=w.profileName}}else{let w=await yc();i=w.credentials,s=w.mode,a=w.profileName;let C=w.profileName;await Ve(o,{credentialMode:w.mode,...C!==void 0&&{activeCredentialProfile:C}})}}let g=t.verbose===!0,u=g||t.debug===!0,h=t.viewer!==!1,v=t.cache!==!1,{waitUntilExit:p}=wc(bc(gc,{port:n,pluginDir:r,outputDir:o,credentials:i,...s!==void 0&&{credentialMode:s},...a!==void 0&&{activeCredentialProfile:a},...c!==void 0&&{lastPath:c},debug:u,verbose:g,autoViewer:h,cacheEnabled:v}),{exitOnCtrlC:!1});await p()})}import{createElement as Ph}from"react";import{render as Eh}from"ink";import{useCallback as Zn,useEffect as Sc,useState as Qn}from"react";import{Box as ke,Text as U,useApp as wh,useInput as vh}from"ink";import{encrypt as fh,serializeEnvelope as mh}from"@kizenapps/packager";function hh(e){let t=e;return t.code==="ECONNREFUSED"||t.cause?.code==="ECONNREFUSED"}function xc(e){return{"Content-Type":"application/json","x-api-key":e.apiKey,"x-user-id":e.userId,"x-business-id":e.businessId,"x-auth-environment":e.environment}}async function kc(e,t,n){try{return await fetch(`${e}${t}`,n)}catch(r){throw new Error(hh(r)?`Plugin-wizard is not running at ${e}`:`Failed to reach plugin-wizard: ${r.message}${Zt()==="unavailable"?` ${Xt}`:""}`)}}async function Cc(e){let t=await e.text();if(t==="")return{};try{let n=JSON.parse(t);return typeof n=="object"&&n!==null?n:{}}catch{return{}}}async function gh(e,t,n){let r=Mt(e.stage),o=await kc(r,"/get-public-key",{method:"POST",headers:xc(t),body:JSON.stringify({api_name:n})}),i=await Cc(o);if(!o.ok||typeof i.public_key!="string"){let s=typeof i.error=="string"?i.error:`HTTP ${String(o.status)}`;throw new Error(`Failed to fetch public key: ${s}`)}return i.public_key}function yh(e,t){let n=fh(t,e),r=mh(n);if(typeof r.value!="string")throw new Error("Unexpected serialized envelope shape from @kizenapps/packager");return r.value}async function bh(e,t,n,r){let o=Mt(e.stage),i=await kc(o,"/encrypt",{method:"POST",headers:xc(t),body:JSON.stringify({api_name:n,value:r})}),s=await Cc(i);if(!i.ok||s.encrypted!==!0||typeof s.value!="string"){let a=typeof s.error=="string"?s.error:`HTTP ${String(i.status)}`;throw new Error(`Encryption via plugin-wizard failed: ${a}`)}return s.value}async function Xn(e,t,n,r,o){if(e.isRemote)return o?.("encrypting"),bh(e,t,n,r);o?.("fetching-key");let i=await gh(e,t,n);return o?.("encrypting"),yh(i,r)}import{Fragment as er,jsx as L,jsxs as re}from"react/jsx-runtime";var $o=({text:e})=>L(U,{dimColor:!0,children:e}),Pc=({ctx:e,stageDefaulted:t,credentialsPath:n,initialApiName:r,defaultApiName:o,initialValue:i,onDone:s})=>{let a=wh(),[c,g]=Qn({type:"loading"}),[u,h]=Qn(null),[v,p]=Qn(r??""),[l,w]=Qn(i??""),C=Zn(d=>{process.exitCode=1,g({type:"error",message:d instanceof Error?d.message:String(d)})},[]),E=Zn(async(d,m,k)=>{try{let S=await Xn(e,d,m,k,R=>{g(R==="fetching-key"?{type:"fetching-key"}:{type:"encrypting"})}),T=JSON.stringify({encrypted:!0,value:S},null,2);s?.(S);let _=await mn(T);g({type:"done",envelope:T,copied:_})}catch(S){C(S)}},[e,C,s]),x=Zn((d,m,k)=>{if(m.trim()===""){g({type:"api-name-entry",buffer:o??""});return}if(k===""){g({type:"value-entry",buffer:""});return}E(d,m.trim(),k)},[o,E]),y=Zn(async d=>{try{g({type:"loading"});let m=d.isDefault?await oe():await Pe(d.name);if(m===null)throw new Error(`Could not load credential profile: ${d.name}`);h(m),x(m,v,l)}catch(m){C(m)}},[v,l,x,C]);Sc(()=>{(async()=>{try{if(n!==void 0){let k;try{k=await Fe(n)}catch(S){throw new Error(`Could not load credentials from ${n}: ${S instanceof Error?S.message:String(S)}`)}h(k),x(k,v,l);return}let d=await je();if(d.length===0)throw new Error("No credential profiles found. Create ~/.kizenappbuilder/credentials.json first.");let[m]=d;if(d.length===1&&m!==void 0){let k=m.isDefault?await oe():await Pe(m.name);if(k===null)throw new Error(`Could not load credential profile: ${m.name}`);h(k),x(k,v,l);return}g({type:"profile-select",profiles:d,cursor:0})}catch(d){C(d)}})()},[]),Sc(()=>{(c.type==="done"||c.type==="error")&&a.exit()},[c,a]),vh((d,m)=>{if(m.ctrl&&d==="c"){process.exitCode=130,a.exit();return}if(c.type==="profile-select"){let{profiles:k,cursor:S}=c;if(m.upArrow)g({...c,cursor:(S-1+k.length)%k.length});else if(m.downArrow)g({...c,cursor:(S+1)%k.length});else if(m.return){let T=k[S];T!==void 0&&y(T)}return}if(c.type==="api-name-entry"){let{buffer:k}=c;if(m.backspace||m.delete)g({type:"api-name-entry",buffer:k.slice(0,-1)});else if(m.return){let S=k.trim();if(S===""){g({type:"api-name-entry",buffer:k,error:"api_name cannot be empty"});return}p(S),u?x(u,S,l):C(new Error("Internal error: credentials were not loaded"))}else d&&!m.ctrl&&!m.meta&&g({type:"api-name-entry",buffer:k+d});return}if(c.type==="value-entry"){let{buffer:k}=c;if(m.backspace||m.delete)g({type:"value-entry",buffer:k.slice(0,-1)});else if(m.return){if(k===""){g({type:"value-entry",buffer:k,error:"secret cannot be empty"});return}w(k),u?x(u,v,k):C(new Error("Internal error: credentials were not loaded"))}else d&&!m.ctrl&&!m.meta&&g({type:"value-entry",buffer:k+d});return}});let P=e.isRemote?"remote Kizen API":"on-machine",b=t===!0?`${e.stage} (default)`:e.stage,f=d=>re(ke,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[L(J,{}),re(U,{dimColor:!0,children:["Mode: ",P," Stage: ",b]}),d]});if(c.type==="loading")return f(re(ke,{gap:1,children:[L(xe,{}),L(U,{dimColor:!0,children:"Loading credentials\u2026"})]}));if(c.type==="profile-select"){let{profiles:d,cursor:m}=c;return f(re(er,{children:[L(U,{bold:!0,children:"Credential profile"}),L(ke,{flexDirection:"column",children:d.map((k,S)=>{let T=m===S;return re(ke,{gap:2,children:[L(U,{...T&&{color:"cyan"},children:T?"\u276F":" "}),L(U,{bold:T,...T&&{color:"cyan"},children:k.isDefault?"Default":k.name}),L(U,{dimColor:!0,children:k.path})]},k.name)})}),L($o,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]}))}return c.type==="api-name-entry"?f(re(er,{children:[L(U,{bold:!0,children:"Plugin api_name"}),c.error!==void 0&&re(U,{color:"red",children:["Error: ",c.error]}),re(ke,{gap:1,children:[L(U,{color:"cyan",children:">"}),L(U,{children:c.buffer}),L(U,{color:"cyan",children:"\u2588"})]}),L($o,{text:"Type the api_name \xB7 Enter to confirm \xB7 Ctrl+C to quit"})]})):c.type==="value-entry"?f(re(er,{children:[L(U,{bold:!0,children:"Secret value"}),c.error!==void 0&&re(U,{color:"red",children:["Error: ",c.error]}),re(ke,{gap:1,children:[L(U,{color:"cyan",children:">"}),L(U,{children:"\u2022".repeat(c.buffer.length)}),L(U,{color:"cyan",children:"\u2588"})]}),L($o,{text:"Input hidden \xB7 Enter to encrypt \xB7 Ctrl+C to quit"})]})):c.type==="fetching-key"?f(re(ke,{gap:1,children:[L(xe,{}),re(U,{children:["Fetching ",e.stage," public key for ",L(U,{bold:!0,children:v}),"\u2026"]})]})):c.type==="encrypting"?f(re(ke,{gap:1,children:[L(xe,{}),L(U,{children:"Encrypting\u2026"})]})):c.type==="error"?f(re(ke,{gap:1,children:[L(U,{color:"red",children:"\u2717"}),L(U,{color:"red",children:c.message})]})):f(re(er,{children:[re(ke,{gap:1,children:[L(U,{color:"green",children:"\u2713"}),L(U,{bold:!0,children:"Encrypted secret ready"})]}),c.copied?L(U,{color:"green",children:"\u2713 Copied to clipboard \u2014 paste it into the secret value in your kizen.json."}):L(U,{dimColor:!0,children:"Paste this into the secret value in your kizen.json (re-run with --out <path> to save it to a file; selecting it here may capture line wraps):"}),L(U,{children:c.envelope})]}))};import{readFile as xh,writeFile as kh}from"fs/promises";import{join as Ch}from"path";function Ec(e){return{encrypted:!0,value:e}}function _c(e){return JSON.stringify(Ec(e))}async function No(e,t){await kh(e,`${JSON.stringify(Ec(t),null,2)}
|
|
1185
|
-
`,"utf-8")}var
|
|
1186
|
-
`}async function
|
|
1187
|
-
`),a=
|
|
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(`
|
|
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)}
|
|
1188
1205
|
`),t.out!==void 0)try{await o.writeEnvelopeFile(t.out,c),o.writeStderr(`Wrote encrypted envelope to ${t.out}
|
|
1189
|
-
`)}catch(
|
|
1190
|
-
`),o.setExitCode(1)}}function
|
|
1191
|
-
`)}catch(
|
|
1192
|
-
${
|
|
1193
|
-
`)}var
|
|
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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}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(`
|
|
1194
1211
|
`)+`
|
|
1195
|
-
`}function
|
|
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(`
|
|
1196
1213
|
`);return`<!DOCTYPE html>
|
|
1197
1214
|
<html lang="en">
|
|
1198
1215
|
<head>
|
|
1199
1216
|
<meta charset="UTF-8">
|
|
1200
1217
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
1201
|
-
<title>${
|
|
1218
|
+
<title>${Te(r)} \u2014 Plugin Report</title>
|
|
1202
1219
|
<style>
|
|
1203
1220
|
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
|
|
1204
1221
|
:root{
|
|
@@ -1235,8 +1252,8 @@ img{border:1px solid var(--bd);border-radius:4px}
|
|
|
1235
1252
|
</head>
|
|
1236
1253
|
<body>
|
|
1237
1254
|
<header>
|
|
1238
|
-
<h1>${
|
|
1239
|
-
${i?`<p>${
|
|
1255
|
+
<h1>${Te(r)}${o?` <span style="color:var(--mu);font-size:.8em">v${Te(o)}</span>`:""}</h1>
|
|
1256
|
+
${i?`<p>${Te(i)}</p>`:""}
|
|
1240
1257
|
</header>
|
|
1241
1258
|
<div class="layout">
|
|
1242
1259
|
<nav>
|
|
@@ -1244,7 +1261,7 @@ img{border:1px solid var(--bd);border-radius:4px}
|
|
|
1244
1261
|
${a}
|
|
1245
1262
|
</nav>
|
|
1246
1263
|
<main>
|
|
1247
|
-
<section id="config"><h2 class="fp">kizen.json \u2014 Plugin Configuration</h2><div class="fb"><pre><code>${
|
|
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>
|
|
1248
1265
|
${c}
|
|
1249
1266
|
</main>
|
|
1250
1267
|
</div>
|
|
@@ -1258,9 +1275,9 @@ ${c}
|
|
|
1258
1275
|
})();
|
|
1259
1276
|
</script>
|
|
1260
1277
|
</body>
|
|
1261
|
-
</html>`}var
|
|
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:
|
|
1262
1279
|
${i}
|
|
1263
|
-
${s}`)})}function
|
|
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(`
|
|
1264
1281
|
Dry run \u2014 no files and no .gitignore entries were written.`);return}console.log(`
|
|
1265
|
-
Ensured .gitignore ignores .kizenapp/ and .copilot-docs/.`),console.log("The code review workflow only takes effect once it is on the repository default branch \u2014 merge it before expecting reviews to cite .copilot-docs/.")}catch(o){console.error(`Error: ${o instanceof Error?o.message:String(o)}`),process.exitCode=1}})}function
|
|
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();
|
|
1266
1283
|
//# sourceMappingURL=index.js.map
|