@kizenapps/cli 1.19.1-e3a10e9 → 1.19.2-1ac7f70
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +105 -105
- package/dist/index.js.map +1 -1
- package/dist/viewer/assets/AppDetailPage-C8jKuooP.js +1 -0
- package/dist/viewer/assets/{CodeStepsPage-CTfZK03G.js → CodeStepsPage-DWBPRgOK.js} +1 -1
- package/dist/viewer/assets/{ConfigurationPage-CLLy6iFh.js → ConfigurationPage-4wWsKb0Q.js} +1 -1
- package/dist/viewer/assets/{DevSidebar-DuVuRTJu.js → DevSidebar-C4AlIuxn.js} +1 -1
- package/dist/viewer/assets/{IconReferencePage-CIq1PaNE.js → IconReferencePage-DiEuDH1K.js} +1 -1
- package/dist/viewer/assets/{SandboxPage-BIG6-7Fa.js → SandboxPage-DhNAgqTy.js} +1 -1
- package/dist/viewer/assets/{SecretsPage-BWbgZ1eZ.js → SecretsPage-DqZTf01r.js} +1 -1
- package/dist/viewer/assets/{VersionsPage-yNilRkEf.js → VersionsPage-C2zAJwLC.js} +1 -1
- package/dist/viewer/assets/{bundleQuery-BE1Gb8Ii.js → bundleQuery-0281ndIj.js} +1 -1
- package/dist/viewer/assets/index-Bn0lFdkc.css +2 -0
- package/dist/viewer/assets/index-xmGIOqSm.js +5 -0
- package/dist/viewer/assets/{useCompleteSetup-Cmw-h_Vn.js → useCompleteSetup-BH7Ysa-t.js} +1 -1
- package/dist/viewer/assets/{usePluginConfig-Co8lbaWp.js → usePluginConfig-NYp4BceH.js} +1 -1
- package/dist/viewer/index.html +5 -5
- package/package.json +1 -1
- package/dist/viewer/assets/AppDetailPage-CW7hiOlY.js +0 -1
- package/dist/viewer/assets/index-MRuQEa3q.css +0 -2
- package/dist/viewer/assets/index-vb4au6lQ.js +0 -5
- /package/dist/viewer/assets/{Card-Sa52PGkn.js → Card-CahCepKE.js} +0 -0
- /package/dist/viewer/assets/{storageKeys-BDp-0diL.js → storageKeys-Dt0anHxP.js} +0 -0
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import*as vE from"http";var vi="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.",Dh=["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy"],Lh=e=>e!==void 0&&e!=="",zt="not-configured";function Dl({env:e,http:t}){return zt==="applied"||(Dh.some(n=>Lh(e[n]))?e.NODE_USE_ENV_PROXY==="1"?zt="already-set":typeof t.setGlobalProxyFromEnv!="function"?zt="unavailable":(t.setGlobalProxyFromEnv(e),zt="applied"):zt="not-configured"),zt}var ki=()=>zt;import{readFileSync as fE}from"fs";import{dirname as gE,join as hE}from"path";import{fileURLToPath as yE}from"url";import{Command as bE}from"commander";import{spawn as Jb}from"child_process";import{Command as qb}from"commander";import{constants as ob}from"os";var Os={go:"https://app.go.kizen.com/api",fmo:"https://app.fmo.kizen.com/api",staging:"https://staging.kizen.com/api","e2e-staging":"https://app.e2e-staging.kizen.com/api",integration:"https://integration.kizen.dev/api","e2e-integration":"https://e2e-integration.kizen.dev/api",test1:"https://app.test1.kizen.dev/api",perf:"https://app.perf.kizen.dev/api"},Ut=e=>new URL(Os[e]).origin,Ll={go:"https://go.kizen.com",fmo:"https://fmo.kizen.com",staging:"https://v2.staging.kizen.com","e2e-staging":"https://e2e-staging.kizen.com",integration:"https://v2.integration.kizen.dev","e2e-integration":"https://v2.e2e-integration.kizen.dev",test1:"https://test1.kizen.dev",perf:"https://perf.kizen.dev"},Bh=["go","fmo"];function Kn(e){return Bh.includes(e)}import{posix as Fh}from"path";var F=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),He=(e,t)=>e?.code===t,tt=e=>e instanceof Error&&He(e,"ENOENT"),_e=async e=>{try{return await e}catch(t){if(He(t,"ENOENT"))return;throw t}},Oe=e=>typeof e=="string"&&e!==""?e:void 0,ke=e=>e instanceof Error?e.message:String(e),xe=e=>{let t=e;return t.cause?.code??t.code??t.cause?.message??t.message??String(e)},Ai=e=>{let t=Fh.normalize(e.trim().replaceAll("\\","/")).replace(/\/+$/,"");return t==="."?"":t};import{spawn as Hh}from"child_process";import{createHash as Kh,randomBytes as Wh}from"crypto";import{createServer as Gh}from"http";import{platform as Fl}from"process";var jh=["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"],Mh=`<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)">${jh.map(e=>`<path d="${e}"/>`).join("")}</g></svg>`,zh={success:'<path d="M6 12.5l4 4 8-9"/>',error:'<path d="M8 8l8 8M16 8l-8 8"/>'},Uh=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">${zh[e]}</svg>`,Vh=`
|
|
2
|
+
import*as $E from"http";var vi="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.",Mh=["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy"],zh=e=>e!==void 0&&e!=="",Ut="not-configured";function Fl({env:e,http:t}){return Ut==="applied"||(Mh.some(n=>zh(e[n]))?e.NODE_USE_ENV_PROXY==="1"?Ut="already-set":typeof t.setGlobalProxyFromEnv!="function"?Ut="unavailable":(t.setGlobalProxyFromEnv(e),Ut="applied"):Ut="not-configured"),Ut}var ki=()=>Ut;import{readFileSync as _E}from"fs";import{dirname as EE,join as IE}from"path";import{fileURLToPath as TE}from"url";import{Command as NE}from"commander";import{spawn as Qb}from"child_process";import{Command as ew}from"commander";import{constants as ub}from"os";var Ds={go:"https://app.go.kizen.com/api",fmo:"https://app.fmo.kizen.com/api",staging:"https://staging.kizen.com/api","e2e-staging":"https://app.e2e-staging.kizen.com/api",integration:"https://integration.kizen.dev/api","e2e-integration":"https://e2e-integration.kizen.dev/api",test1:"https://app.test1.kizen.dev/api",perf:"https://app.perf.kizen.dev/api"},Vt=e=>new URL(Ds[e]).origin,jl={go:"https://go.kizen.com",fmo:"https://fmo.kizen.com",staging:"https://v2.staging.kizen.com","e2e-staging":"https://e2e-staging.kizen.com",integration:"https://v2.integration.kizen.dev","e2e-integration":"https://v2.e2e-integration.kizen.dev",test1:"https://test1.kizen.dev",perf:"https://perf.kizen.dev"},Uh=["go","fmo"];function Kn(e){return Uh.includes(e)}import{posix as Vh}from"path";var F=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),He=(e,t)=>e?.code===t,tt=e=>e instanceof Error&&He(e,"ENOENT"),_e=async e=>{try{return await e}catch(t){if(He(t,"ENOENT"))return;throw t}},Oe=e=>typeof e=="string"&&e!==""?e:void 0,ke=e=>e instanceof Error?e.message:String(e),xe=e=>{let t=e;return t.cause?.code??t.code??t.cause?.message??t.message??String(e)},Ai=e=>{let t=Vh.normalize(e.trim().replaceAll("\\","/")).replace(/\/+$/,"");return t==="."?"":t};import{spawn as qh}from"child_process";import{createHash as Yh,randomBytes as Zh}from"crypto";import{createServer as Xh}from"http";import{platform as zl}from"process";var Hh=["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"],Kh=`<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)">${Hh.map(e=>`<path d="${e}"/>`).join("")}</g></svg>`,Wh={success:'<path d="M6 12.5l4 4 8-9"/>',error:'<path d="M8 8l8 8M16 8l-8 8"/>'},Gh=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">${Wh[e]}</svg>`,Jh=`
|
|
3
3
|
:root {
|
|
4
4
|
color-scheme: light dark;
|
|
5
5
|
--page-bg: #F4F9F7;
|
|
@@ -82,72 +82,72 @@ 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 Bl(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>${Vh}</style></head><body><main>${Mh}<section class="card ${e}" data-status="${e}"><div class="status">${Uh(e)}</div><h1>${t}</h1><p>${n}</p></section></main></body></html>`}var xi="127.0.0.1",Ds="/callback",Jh=`http://${xi}${Ds}`,qh="read write offline_access",Yh="Kizen App Builder CLI",Zh=300*1e3,Ht="go",gr=2e4,ue=class extends Error{constructor(n,r){super(r);this.code=n;this.name="OAuthError"}code},Ml=["ENOSPC","EDQUOT"],zl=["EPERM","EACCES","EROFS",...Ml],Vt=class extends ue{hint;constructor(t,n,r){let i=Ml.includes(r);super("session_store_unwritable",i?`Can't write to ${t} (${r}): the disk is full or over quota. appbuilder keeps its sign-in sessions there.`:`Can't write to ${t} (${r}), where appbuilder keeps its sign-in sessions.`),this.name="SessionStoreUnwritableError",this.hint=i?`Free some disk space (or quota) for ${n}, then run the command again.`:`appbuilder needs write access to ${n} to keep you signed in. Under Codex, re-run the command with sandbox_permissions: "require_escalated" (prefix_rule: ["appbuilder"]). Under the Claude Code sandbox, add "appbuilder *" to sandbox.excludedCommands in your user settings (~/.claude/settings.json); allowing writes to ${n} alone isn't enough, since appbuilder also needs network access the sandbox blocks.`}},ut=e=>e===Ht?"appbuilder login":`appbuilder login --env ${e}`,dt=(e,t,n={})=>new ue("login_required",`${t} Run \`${ut(e)}\` to sign in${n.again===!0?" again":""}.`),Xh=e=>{try{return e===""?void 0:JSON.parse(e)}catch{return}};async function Ls(e,t,n,r){let i=AbortSignal.timeout(r);try{let o=await e(t,{...n,headers:{Accept:"application/json",...n.headers},signal:i});return{res:o,body:Xh(await o.text())}}catch(o){let s=i.aborted?`timed out after ${String(Math.round(r/1e3))}s`:xe(o);throw new ue("network_error",`Couldn't reach ${new URL(t).origin}: ${s}`)}}function Ul(e,t,n){let r=F(n)?n:{},i=Oe(r.error);if(i!==void 0){let o=Oe(r.error_description);return new ue(i,`${e} failed (${i}${o===void 0?"":`: ${o}`})`)}return new ue("server_error",`${e} failed with HTTP ${String(t)}`)}async function Vl(e,t,n=gr){let r=`${e}/.well-known/oauth-authorization-server`,i=a=>new ue("server_error",`OAuth discovery at ${r} ${a}`),{res:o,body:s}=await Ls(t,r,{},n);if(!o.ok)throw i(`failed with HTTP ${String(o.status)}`);if(!F(s))throw i("didn't return valid JSON");if(s.issuer!==e)throw i(`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 Hl(e,t,n=gr){let{res:r,body:i}=await Ls(t,e.registrationEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:Yh,redirect_uris:[Jh],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"})},n);if(!r.ok)throw Ul("App registration",r.status,i);let o=F(i)?Oe(i.client_id):void 0;if(o===void 0)throw new ue("server_error","App registration returned no client_id");return o}var Qh=e=>Kh("sha256").update(e,"ascii").digest("base64url"),Bs=()=>Wh(32).toString("base64url");function Kl(){let e=Bs();return{verifier:e,challenge:Qh(e)}}function Wl(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",qh),n.searchParams.set("state",t.state),n.searchParams.set("code_challenge",t.codeChallenge),n.searchParams.set("code_challenge_method","S256"),n.toString()}async function Fs(e,t,n,r=gr){let{res:i,body:o}=await Ls(n,e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()},r);if(!i.ok)throw Ul("The token request",i.status,o);let s=F(o)?Oe(o.access_token):void 0,a=F(o)?Oe(o.refresh_token):void 0;if(!F(o)||s===void 0||a===void 0)throw new ue("server_error","The token endpoint returned an unexpected response");return{accessToken:s,refreshToken:a,expiresIn:o.expires_in}}var jl=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store",Connection:"close"}).end(Bl(n.kind,n.heading,n.text))},ey={kind:"success",heading:"You\u2019re signed in",text:"Sign-in complete. You can close this window."},ty={kind:"error",heading:"Sign-in failed",text:"Sign-in failed. Return to the terminal for details. You can close this window."},ny={kind:"error",heading:"Outdated link",text:"This sign-in link is out of date. Use the latest link from the terminal."},ry=e=>{try{return new URL(e??"/",`http://${xi}`)}catch{return}};async function Gl(e){let t=e.timeoutMs??Zh,n,r=new Promise((u,f)=>{n={resolve:u,reject:f}});r.catch(()=>{});let i=!1,o,s=Gh((u,f)=>{let g=ry(u.url);if(i||u.method!=="GET"||g?.pathname!==Ds){f.writeHead(404,{"Content-Type":"text/plain",Connection:"close"}).end("Not found");return}let m=g.searchParams;if(m.get("state")!==e.state){jl(f,400,ny);return}let p=m.get("error"),h=m.get("error_description"),b=m.get("code")??"",y=p!==null?new ue(p,`Kizen denied the sign-in (${p}${h?`: ${h}`:""})`):b?void 0:new ue("invalid_callback","The sign-in callback had no authorization code");jl(f,y?400:200,y?ty:ey),c(y,b)}),a=()=>(o??=new Promise(u=>{clearTimeout(l),s.close(()=>{u()}),s.closeAllConnections()}),o);function c(u,f=""){i||(i=!0,u?n.reject(u):n.resolve({code:f}),a())}await new Promise((u,f)=>{s.once("error",f),s.listen(0,xi,()=>{s.off("error",f),u()})});let l=setTimeout(()=>{c(new ue("timeout",`Timed out after ${String(Math.round(t/1e3))}s waiting for the browser sign-in`))},t),d=s.address();return{port:d.port,redirectUri:`http://${xi}:${String(d.port)}${Ds}`,result:r,close:a}}function Jl(e){let[t,n]=Fl==="darwin"?["open",[e]]:Fl==="win32"?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{let r=Hh(t,n,{stdio:"ignore",detached:!0});r.on("error",()=>{}),r.unref()}catch{}}var ge=e=>/^[\w@%+:,./-][\w@%+=:,./-]*$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`;var hr="APPBUILDER_BUSINESS",yr="APPBUILDER_USER";function bn(e,t){if(e.business!==void 0)return{ok:!0,request:{business:e.business,user:e.user,source:"flags"}};if(e.user!==void 0)return{ok:!1,message:"--user only applies with --business."};let n=t[hr]||void 0,r=t[yr]||void 0;return n===void 0?r===void 0?{ok:!0,request:void 0}:{ok:!1,message:`${yr} only applies with ${hr}.`}:{ok:!0,request:{business:n,user:r,source:"env"}}}var iy="To use an API key instead (deprecated), pass --profile <name> or -c <path>.";function ql(e,t){let n=e.credentials!==void 0||e.profile!==void 0;if(n&&e.env!==void 0)return{ok:!1,message:"--env selects a sign-in session, so it can't be combined with -c or --profile."};if(n&&(e.business!==void 0||e.user!==void 0))return{ok:!1,message:`${e.business===void 0?"--user":"--business"} selects a saved sign-in account, so it can't be combined with -c or --profile.`};if(e.credentials!==void 0)return{ok:!0,selection:{kind:"api-key",credentials:e.credentials}};if(e.profile!==void 0)return{ok:!0,selection:{kind:"api-key",profile:e.profile}};let r=bn(e,t);return r.ok?{ok:!0,selection:{kind:"oauth",...e.env!==void 0&&{env:e.env},...r.request!==void 0&&{account:r.request}}}:r}var Yl=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 ${ge(e)} to use the API key.`}`,Zl=e=>`${e} ${iy}`;import{mkdir as Xl,readFile as oy,readdir as sy,writeFile as Ql}from"fs/promises";import{homedir as ay}from"os";import{dirname as cy,join as Pi}from"path";var pe=["go","fmo","staging","e2e-staging","integration","e2e-integration","test1","perf"];function br(e){return typeof e=="string"?e.trim():""}function wr(e){return{apiKey:br(e.apiKey),userId:br(e.userId),businessId:br(e.businessId)}}var nt=Pi(ay(),".kizenappbuilder"),Kt=Pi(nt,"credentials.json"),Wt="credentials",vr=e=>pe.includes(e),ly=e=>`Unknown --env "${e}". Use one of: ${pe.join(", ")}.`,wn=e=>vr(e)?{environment:e}:{message:ly(e)};function uy(e){return typeof e=="string"?e.trim():e}function dy(e){return vr(e)?"explicit":e==null||e===""?"missing":"invalid"}function py(e){if(typeof e!="object"||e===null)throw new Error("Credentials must be a JSON object");let t=e,n=uy(t.environment);return{credentials:{...wr(t),environment:vr(n)?n:"go"},environmentSource:dy(n)}}async function Ci(e){let t=await oy(e,"utf-8");return py(JSON.parse(t))}async function Gt(e){return(await Ci(e)).credentials}async function De(){try{return await Gt(Kt)}catch{return null}}async function my(e){await Xl(cy(Kt),{recursive:!0,mode:448}),await Ql(Kt,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function eu(e){return Pi(nt,`${e}.json`)}async function Jt(){let e=[{name:Wt,path:Kt,isDefault:!0}];try{let t=await sy(nt);for(let n of t){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);r!==Wt&&e.push({name:r,path:Pi(nt,n),isDefault:!1})}}catch{}return e}async function tu(e,t){if(e===Wt){await my(t);return}await Xl(nt,{recursive:!0,mode:448}),await Ql(eu(e),JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}async function Ct(e){try{return await Gt(eu(e))}catch{return null}}async function nu(){let e=await Jt(),t=await Promise.all(e.map(n=>Ci(n.path).then(()=>!0,()=>!1)));return e.filter((n,r)=>t[r]===!0)}var iu="APPBUILDER_NO_INTERACTIVE",ru=e=>e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false";function fy(e){return ru(e.CI)||e.CODEX_CI!==void 0||e.CLAUDECODE!==void 0||e.TERM==="dumb"||ru(e[iu])}function gy({stdin:e,stdout:t,json:n,noInteractive:r,env:i}){return e.isTTY===!0&&t.isTTY===!0&&n!==!0&&r!==!0&&!fy(i)}var pt=(e={})=>gy({stdin:process.stdin,stdout:process.stdout,env:process.env,...e}),mt=`run headless even at a terminal (also $${iu})`;function Ae(e){let{interactive:t,...n}=e;return{noInteractive:t===!1,options:n}}var hy="The API key is invalid for this business, or the user id doesn't match. Check the credentials file's apiKey, userId and businessId.",yy="The API key's user needs the Standard API Keys permission and edit access to this dashboard. Homepages also need the Customize Homepages permission.",by=e=>dt(e,"Kizen rejected the signed-in session.",{again:!0}).message,wy="The signed-in user needs edit access to this dashboard. Homepages also need the Customize Homepages permission.",vy={authFailed:hy,forbidden:yy},ky=100,Ay=new Set([301,302,303,307,308]),xy=5,Py=new Set(["detail","non_field_errors"]),q=class extends Error{kind;status;hint;details;constructor(t,n,r={}){super(n,r.cause===void 0?void 0:{cause:r.cause}),this.name="KizenApiError",this.kind=t,this.status=r.status,this.hint=r.hint,this.details=r.details}},kr=encodeURIComponent,Ar=(e,t)=>t===void 0?`/dashboards/${kr(e)}/dashlet`:`/dashboards/${kr(e)}/dashlet/${kr(t)}`;function js(e,t,n){let r=i=>{n.push(t===""?i:`${t}: ${i}`)};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 i=e.filter(o=>typeof o=="string"&&o.trim()!==""||typeof o=="number"||typeof o=="boolean");i.length>0&&r(i.map(String).join(" "));for(let o of e)typeof o=="object"&&o!==null&&js(o,t,n);return}if(F(e))for(let[i,o]of Object.entries(e)){let s=t===""&&Py.has(i)?"":t===""?i:`${t}.${i}`;js(o,s,n)}}function Cy(e){if(typeof e!="object"||e===null)return;let t=[];return js(e,"",t),t.length>0?t.join("; "):void 0}async function ou(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 su(e,t,n,r,i){let o=Cy(r),s=`${e} ${t} failed with ${String(n)}${o===void 0?"":`: ${o}`}`,a=r;return n===401?new q("auth_failed",s,{status:n,hint:i.authFailed,details:a}):n===403?new q("forbidden",s,{status:n,hint:i.forbidden,details:a}):n===404?new q("not_found",s,{status:n,details:a}):new q("api_error",s,{status:n,details:a})}function au(e,t,n){if(Array.isArray(n))return{results:n,next:null};if(F(n)&&Array.isArray(n.results))return{results:n.results,next:n.next};throw new q("api_error",`${e} ${t} returned an unexpected response shape`)}var Si=e=>F(e)?e:{};function cu(e){let t=Si(e);return{business:Si(t.business),team:Si(t.team)}}var Sy=new Map([["login_required","auth_failed"],["network_error","network_error"],["session_store_unwritable","session_store_unwritable"]]);function _y(e,t){let n=ke(e),r=e instanceof ue?Sy.get(e.code):void 0;return r===void 0?new q("api_error",`Couldn't refresh the ${t} session: ${n}`,{cause:e}):new q(r,n,{cause:e,...e instanceof Vt&&{hint:e.hint}})}function xr(e){let t=e.fetch??fetch,n=e.bearer?e.bearer.environment:e.credentials.environment,r=e.baseUrl??Os[n],i=new URL(r).origin,o=e.bearer?{authFailed:by(n),forbidden:wy}:vy,s=h=>{throw _y(h,n)},a=async()=>{if(!e.bearer){let{apiKey:y,userId:C,businessId:S}=e.credentials;return{headers:{"X-API-KEY":y,"X-USER-ID":C,"X-BUSINESS-ID":S}}}let{bearer:h}=e,b=await h.getAccessToken().catch(s);return{headers:{Authorization:`Bearer ${b}`},retry:async()=>({Authorization:`Bearer ${await h.refreshAccessToken(b).catch(s)}`})}},c=async(h,b,y,C)=>{let S=async(w,A,_,T)=>{let L={...T,Accept:y},$={method:A,headers:L,redirect:"manual"};_!==void 0&&(L["Content-Type"]=_.contentType,$.body=_.payload);try{return await t(w,$)}catch(V){throw new q("network_error",`Couldn't reach Kizen at ${r}: ${xe(V)}${ki()==="unavailable"?` ${vi}`:""}`)}},x=async w=>{let A=b,_=h,T=C;for(let L=0;;L+=1){let $=await S(A,_,T,w);if($.type==="opaqueredirect")throw new q("api_error",`${h} ${b} was redirected to an unknown location`);let V=Ay.has($.status)?$.headers.get("location"):null;if(V===null)return $;await $.body?.cancel().catch(()=>{});let X;try{X=new URL(V,A)}catch{throw new q("api_error",`${h} ${b} was redirected to an invalid location`,{status:$.status})}if(X.origin!==i)throw new q("api_error",`${h} ${b} was redirected to ${X.origin}, outside the Kizen API; the request was not sent there.`,{status:$.status});if(L>=xy)throw new q("api_error",`${h} ${b} redirected too many times`,{status:$.status});($.status===303||($.status===301||$.status===302)&&_==="POST")&&(_="GET",T=void 0),A=X.toString()}},{headers:v,retry:k}=await a(),P=await x(v);return P.status===401&&k&&(await P.body?.cancel().catch(()=>{}),P=await x(await k())),P},l=(h,b,y,C)=>new q("network_error",`${h} ${b}: couldn't read the response: ${xe(C)}. The request may have been applied; check Kizen before retrying.`,{status:y}),d=h=>{let b=/^https?:\/\//.test(h)?h:`${r}${h}`;return{url:b,path:b.startsWith(r)?b.slice(r.length):b}},u=async(h,b,y)=>{let{url:C,path:S}=d(b),x=await c(h,C,"application/json",y),v,k;try{({text:v,json:k}=await ou(x))}catch(P){throw l(h,S,x.status,P)}if(!x.ok)throw su(h,S,x.status,k,o);if(k===void 0&&v!=="")throw new q("api_error",`${h} ${S} returned a response that is not JSON`,{status:x.status});return k},f=h=>h===void 0?void 0:{contentType:"application/json",payload:JSON.stringify(h)},g=(h,b)=>{if(!b.startsWith("/")||b.startsWith("//"))throw new q("api_error",`${h} ${b}: expected a path under the Kizen API`);return b},m=h=>{let b=new URL(r),y=new URL(h,b.origin);if(y.protocol=b.protocol,y.port=b.port,y.username="",y.password="",y.hash="",y.origin!==b.origin)throw new q("api_error",`GET /custom-objects pagination pointed at an unexpected location ${y.origin}${y.pathname}`);return y.toString()},p;return{async listDashboards(h,b){let y=new URLSearchParams({size:"10000",include_sharing:"true",dashboard_type:h});b!==void 0&&y.set("custom_object_id",b);let C=`/dashboards/mine?${y.toString()}`;return au("GET",C,await u("GET",C)).results},async listCustomObjects(h={}){let b=[],y=new Set,C=`/custom-objects?page_size=200${h.customOnly===!1?"&custom_only=false":""}`;for(;C!==void 0&&!y.has(C)&&y.size<ky;){y.add(C);let S=au("GET",C,await u("GET",C));b.push(...S.results),C=typeof S.next=="string"&&S.next!==""?m(S.next):void 0}return b},async getCustomObject(h){let b=`/custom-objects/${kr(h)}`,y=await u("GET",b);if(!F(y)||typeof y.id!="string"||typeof y.fetch_url!="string")throw new q("api_error",`GET ${b} returned an unexpected response shape`);return y},async getIdentity(){let h=await u("GET","/auth/bootstrap"),{business:b,team:y}=cu(h),C=Oe(b.id),S=Oe(y.user);if(C===void 0||S===void 0)throw new q("api_error","GET /auth/bootstrap returned an unexpected response shape");return p=h,{userId:S,businessId:C,businessName:Oe(b.name),fullName:Oe(y.full_name),email:Oe(y.email)}},async getClientObjectId(){let h=p??await u("GET","/auth/bootstrap"),{business:b}=cu(h);return Oe(Si(b.client_object).id)??null},async getDashboard(h){return await u("GET",`/dashboards/${kr(h)}`)},async createDashlet(h,b){return await u("POST",Ar(h),f(b))},async updateDashlet(h,b,y){return await u("PATCH",Ar(h,b),f(y))},async requestJson(h,b,y){return u(h,g(h,b),f(y))},async postForm(h,b){return u("POST",g("POST",h),{contentType:"application/x-www-form-urlencoded",payload:new URLSearchParams(b).toString()})},async getBinary(h){let{url:b,path:y}=d(g("GET",h)),C=await c("GET",b,"*/*");if(!C.ok){let S;try{({json:S}=await ou(C))}catch(x){throw l("GET",y,C.status,x)}throw su("GET",y,C.status,S,o)}try{return new Uint8Array(await C.arrayBuffer())}catch(S){throw l("GET",y,C.status,S)}}}}var Ey=6e4,lu=(e,t)=>fetch(e,t),uu=()=>Date.now(),du=(e,t,n)=>({store:e,fetch:lu,now:uu,print:t,openBrowser:Jl,startLoopbackServer:Gl,identify:n}),Iy=(e,t)=>({environment:e,getAccessToken:()=>Promise.resolve(t),refreshAccessToken:()=>Promise.reject(dt(e,`Kizen rejected the new ${e} sign-in.`))}),Pr=e=>dt(e,`You're not signed in to ${e}.`),Ty=e=>({businessName:e.businessName,fullName:e.fullName,email:e.email}),pu=(e,t,n)=>({...e,accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:n+t.expiresIn*1e3}),Ny=(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 Ry(e,t,n,r){let{verifier:i,challenge:o}=Kl(),s=Bs(),a=await n.startLoopbackServer({state:s,...n.timeoutMs!==void 0&&{timeoutMs:n.timeoutMs}});try{let c=Wl(e,{clientId:t,redirectUri:a.redirectUri,state:s,codeChallenge:o});n.print(r),n.print(c),n.openBrowser(c);let{code:l}=await a.result;return await Fs(e.tokenEndpoint,{grant_type:"authorization_code",code:l,redirect_uri:a.redirectUri,client_id:t,code_verifier:i},n.fetch)}finally{await a.close()}}async function Ms(e,t,n={}){let r=Ny(e,n.interactive??!0);await t.store.probeWritable();let i=await Vl(Ut(e),t.fetch),o=await t.store.readClientId(i.issuer),s=o??await Hl(i,t.fetch);o===void 0&&await t.store.writeClientId(i.issuer,s);let a;try{a=await Ry(i,s,t,r)}catch(u){throw u instanceof ue&&u.code==="timeout"&&o!==void 0?(await t.store.forgetClientId(i.issuer),new ue("timeout",`${u.message}. If the browser showed an error instead of a consent page, the saved app registration was stale; it has been cleared. Run \`${ut(e)}\` again.`)):u}let c=await t.identify(Iy(e,a.accessToken)),l={businessId:c.businessId,userId:c.userId},d=pu({environment:e,...l,...Ty(c),issuer:i.issuer,clientId:s,tokenEndpoint:i.tokenEndpoint},a,t.now());if(await t.store.writeSession(d),n.makeCurrent!==void 0&&!n.makeCurrent(c)){if(await t.store.readAccount(e,l)===null)throw Pr(e);return d}if(await t.store.setCurrent(e,l),await t.store.readSession(e)===null)throw Pr(e);return d}async function mu(e,t,n){try{await n.identify(n.provider)}catch(i){if(await n.store.readAccount(e,t).then(s=>s===null,()=>!1))return;throw i}await n.store.setCurrent(e,t);let r=await n.store.readSession(e);if(r===null)throw Pr(e);return r}function $y(e,t){let n,r=t.account,i,o=d=>d.expiresAt-t.now()>Ey,s=d=>{if(d===null)throw Pr(e);return d},a=async()=>r!==void 0?s(await t.store.readAccount(e,r)):(i??=t.store.readSession(e).then(d=>{let u=s(d);return r={businessId:u.businessId,userId:u.userId},u}).finally(()=>{i=void 0}),i),c=async(d,u)=>{let f=await a();if(f.accessToken!==d&&o(f))return f.accessToken;let g=u??t.now()+(t.requestTimeoutMs??gr),m=async()=>{let y=await a();return{stored:y,rotated:y.refreshToken!==f.refreshToken}},p=g-t.now();if(p<=0)return f.accessToken;await t.store.probeWritable();let h;try{h=await Fs(f.tokenEndpoint,{grant_type:"refresh_token",refresh_token:f.refreshToken,client_id:f.clientId},t.fetch,p)}catch(y){if(y instanceof ue&&(y.code==="invalid_grant"||y.code==="invalid_client")){let{stored:C,rotated:S}=await m();if(S)return o(C)||u!==void 0?C.accessToken:c(C.accessToken,g);if(await t.store.deleteSession(e,f)&&y.code==="invalid_client")try{await t.store.readClientId(f.issuer)===f.clientId&&await t.store.forgetClientId(f.issuer)}catch{}throw dt(e,`The ${e} session is no longer valid.`)}throw y}let b=pu(f,h,t.now());if(await t.store.commitRefresh(b,f.refreshToken)==="gone")throw Pr(e);return b.accessToken},l=d=>(n??=c(d).finally(()=>{n=void 0}),n);return{environment:e,async getAccessToken(){if(n)return n;let d=await a();return o(d)?d.accessToken:l(d.accessToken)},refreshAccessToken:l}}var _i=(e,t,n={})=>$y(e,{store:t,now:uu,...n,fetch:n.fetch??lu}),Oy=`You're not signed in. Run \`${ut(Ht)}\` (add \`--env <env>\` to sign in to an environment other than ${Ht}).`;async function Cr(e,t){if(e!==void 0){let{environment:i,message:o}=wn(e);return i===void 0?{ok:!1,problem:"unknown_environment",message:o}:{ok:!0,environment:i}}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:Oy}:{ok:!0,environment:r}}import{randomBytes as Ei}from"crypto";import{chmod as Dy,mkdir as Ly,open as yu,readdir as By,readFile as Ii,rename as fu,rm as Us,stat as bu,unlink as Wn}from"fs/promises";import{dirname as Fy,join as vn}from"path";import{setTimeout as jy}from"timers/promises";var My="clients.json",zy=" ".repeat(4096),Uy=10*6e4,Vy={waitMs:2e3,staleMs:3e4,pollMs:25};async function Hy(e,{waitMs:t,staleMs:n,pollMs:r}){let i=Date.now()+t;for(;;){let o;try{o=await yu(e,"wx",384)}catch(a){if(!He(a,"EEXIST"))return;try{let c=await _e(bu(e));if(c===void 0)continue;if(Date.now()-c.mtimeMs>n){await _e(Wn(e));continue}}catch{return}if(Date.now()>=i)return;await jy(r);continue}let s=Ei(16).toString("hex");try{await o.writeFile(s,"utf-8")}catch{s=void 0}try{await o.close()}catch{s=void 0}return s===void 0&&await Us(e,{force:!0}).catch(()=>{}),s}}async function Ky(e,t,n){let r=await Hy(e,t);try{return{value:await n(),held:r!==void 0}}finally{if(r!==void 0)try{await _e(Ii(e,"utf-8"))===r&&await _e(Wn(e))}catch{}}}var Wy=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,gu=e=>typeof e=="string"&&Wy.test(e),Ti=e=>F(e)&&gu(e.businessId)&&gu(e.userId)?{businessId:e.businessId,userId:e.userId}:void 0,kn=(e,t)=>e.businessId===t.businessId&&e.userId===t.userId,An=e=>{if(Ti(e)===void 0)throw new Error("Refusing a session file name built from an invalid account id.");return`${e.businessId}.${e.userId}`};function hu(e){let t;try{t=JSON.parse(e)}catch{return}return Ti(t)}var zs=e=>typeof e=="string"?e:void 0;function Gy(e,t){let n=Ti(e);return!F(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:zs(e.businessName),fullName:zs(e.fullName),email:zs(e.email),issuer:e.issuer,clientId:e.clientId,tokenEndpoint:e.tokenEndpoint,accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt}}function ft(e=nt,t={}){let n=vn(e,"oauth"),r={...Vy,...t.lock},i=w=>vn(n,`${w}.json`),o=(w,A)=>vn(n,`${w}.${An(A)}.json`),s=(w,A)=>vn(n,`${w}.${An(A)}.lock`),a=async(w,A,_)=>(await Ky(s(w,A),r,_)).value,c=vn(n,My),l=(w,A)=>{let _=`${w}.`;if(!A.startsWith(_)||!A.endsWith(".json"))return;let T=A.slice(_.length,-5).split(".");if(T.length!==2)return;let[L,$]=T;return Ti({businessId:L,userId:$})},d=async()=>await _e(By(n))??[],u=async w=>{try{return await w()}catch(A){let _=zl.find(T=>He(A,T));throw _!==void 0?new Vt(n,Fy(n),_):A}},f=async()=>{await Ly(n,{recursive:!0,mode:448}),await Dy(n,448)},g=async(w,A,_)=>{let T=`${w}.${Ei(6).toString("hex")}.tmp`;try{let L=await yu(T,"wx",384);try{await L.writeFile(A,"utf-8"),await L.sync()}finally{await L.close()}await fu(T,_)}catch(L){throw await Us(T,{force:!0}).catch(()=>{}),L}},m=(w,A)=>u(async()=>{await f(),await g(w,JSON.stringify(A,null,2),w)}),p=()=>u(async()=>{await f();let w=vn(n,`.write-probe.${Ei(6).toString("hex")}`);await g(w,zy,w),await Wn(w)}),h=(w,A)=>dt(w,`The saved ${w} session at ${A} can't be read.`,{again:!0}),b=async w=>{try{let A=new RegExp(`^${w}\\.json\\.([0-9]{1,16})-[0-9a-f]{12}\\.signout$`);for(let _ of await d()){let T=A.exec(_)?.[1];T!==void 0&&Date.now()-Number(T)>Uy&&await _e(Wn(vn(n,_)));let L=_.endsWith(".lock")?l(w,`${_.slice(0,-5)}.json`):void 0;if(L!==void 0){let $=s(w,L),V=await _e(bu($));V!==void 0&&Date.now()-V.mtimeMs>r.staleMs&&await _e(Wn($))}}}catch{}},y=async()=>{let w;try{w=JSON.parse(await _e(Ii(c,"utf-8"))??"{}")}catch(A){if(A instanceof SyntaxError)return{};throw A}return F(w)?w:{}},C=async(w,A)=>{try{return await _e(Ii(A,"utf-8"))}catch{throw h(w,A)}},S=async(w,A)=>{let _=o(w,A),T=await C(w,_);if(T===void 0)return null;try{let L=Gy(JSON.parse(T),w);if(L!==null&&kn(L,A))return L}catch{}throw h(w,_)},x=async w=>{let A=i(w),_=await C(w,A);if(_===void 0)return;let T=hu(_);if(T===void 0)throw h(w,A);return T},v=async w=>{let A=await x(w);return A===void 0?null:S(w,A)},k=async w=>{let A=i(w),_=`${A}.${String(Date.now())}-${Ei(6).toString("hex")}.signout`;if(await u(()=>_e(fu(A,_).then(()=>!0)))===!0)try{return{account:hu(await Ii(_,"utf-8"))}}catch{return{account:void 0}}finally{await Us(_,{force:!0})}},P=(w,A)=>a(w,A,async()=>await u(()=>_e(Wn(o(w,A)).then(()=>!0)))??!1);return{dir:n,sessionPath:i,accountPath:o,readSession:v,readAccount:S,async listAccounts(w){let A;try{A=await x(w)}catch{}let _=(await d()).map($=>l(w,$)).filter($=>$!==void 0),T=await Promise.all(_.map(async $=>{let V;try{let X=await S(w,$);if(X===null)return;V=X}catch(X){if(!(X instanceof ue&&X.code==="login_required"))throw X}return{account:$,session:V,current:A!==void 0&&kn(A,$)}})),L=$=>($.session?.businessName??$.account.businessId).toLowerCase();return T.filter($=>$!==void 0).sort(($,V)=>L($).localeCompare(L(V))||An($.account).localeCompare(An(V.account)))},async writeSession(w){await m(o(w.environment,w),w)},probeWritable:p,async commitRefresh(w,A){let{environment:_}=w;return a(_,w,async()=>{let T=await S(_,w);return T===null?"gone":T.refreshToken!==A?"rotated":(await m(o(_,w),w),"written")})},async setCurrent(w,A){let{businessId:_,userId:T}=A;await m(i(w),{businessId:_,userId:T}),await b(w)},async deleteSession(w,A){return P(w,A)},async signOut(w){let A=await k(w),_=A!==void 0;return A?.account!==void 0&&(_=await P(w,A.account)),await b(w),_},async removeAccount(w,A){let _=!1,T;try{T=await x(w)}catch{}T!==void 0&&kn(T,A)&&(_=await k(w)!==void 0);let L=await P(w,A);return await b(w),{removed:L,current:_}},async signOutAll(w){let A=await k(w),_=A!==void 0&&A.account===void 0,T=0;for(let L of await d()){let $=l(w,L);$!==void 0&&await P(w,$)&&(T+=1,_||=A?.account!==void 0&&kn(A.account,$))}return await b(w),{signedIn:_,removed:T}},async listSessions(){return(await Promise.all(pe.map(async A=>{try{return await v(A)===null?void 0:A}catch(_){if(_ instanceof ue&&_.code==="login_required")return A;throw _}}))).filter(A=>A!==void 0)},async readClientId(w){let A=(await y())[w];return F(A)?Oe(A.clientId):void 0},async writeClientId(w,A){await m(c,{...await y(),[w]:{clientId:A}})},async forgetClientId(w){let A=await y();w in A&&await m(c,Object.fromEntries(Object.entries(A).filter(([_])=>_!==w)))}}}var Jy=5e3;function vu(e=ft(),t,n=!1){let r=(s,a)=>_i(s,e,a),i=s=>{process.stderr.write(s)},o=s=>xr({bearer:s}).getIdentity();return{store:e,loginDeps:du(e,s=>{i(`${s}
|
|
86
|
-
`)},o),identify:o,tokenProvider:r,isInteractive:()=>
|
|
85
|
+
`.trim().replace(/\n\s*/g,"");function Ml(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>${Jh}</style></head><body><main>${Kh}<section class="card ${e}" data-status="${e}"><div class="status">${Gh(e)}</div><h1>${t}</h1><p>${n}</p></section></main></body></html>`}var xi="127.0.0.1",Ls="/callback",Qh=`http://${xi}${Ls}`,ey="read write offline_access",ty="Kizen App Builder CLI",ny=300*1e3,Kt="go",gr=2e4,ue=class extends Error{constructor(n,r){super(r);this.code=n;this.name="OAuthError"}code},Vl=["ENOSPC","EDQUOT"],Hl=["EPERM","EACCES","EROFS",...Vl],Ht=class extends ue{hint;constructor(t,n,r){let i=Vl.includes(r);super("session_store_unwritable",i?`Can't write to ${t} (${r}): the disk is full or over quota. appbuilder keeps its sign-in sessions there.`:`Can't write to ${t} (${r}), where appbuilder keeps its sign-in sessions.`),this.name="SessionStoreUnwritableError",this.hint=i?`Free some disk space (or quota) for ${n}, then run the command again.`:`appbuilder needs write access to ${n} to keep you signed in. Under Codex, re-run the command with sandbox_permissions: "require_escalated" (prefix_rule: ["appbuilder"]). Under the Claude Code sandbox, add "appbuilder *" to sandbox.excludedCommands in your user settings (~/.claude/settings.json); allowing writes to ${n} alone isn't enough, since appbuilder also needs network access the sandbox blocks.`}},pt=e=>e===Kt?"appbuilder login":`appbuilder login --env ${e}`,mt=(e,t,n={})=>new ue("login_required",`${t} Run \`${pt(e)}\` to sign in${n.again===!0?" again":""}.`),ry=e=>{try{return e===""?void 0:JSON.parse(e)}catch{return}};async function Bs(e,t,n,r){let i=AbortSignal.timeout(r);try{let o=await e(t,{...n,headers:{Accept:"application/json",...n.headers},signal:i});return{res:o,body:ry(await o.text())}}catch(o){let s=i.aborted?`timed out after ${String(Math.round(r/1e3))}s`:xe(o);throw new ue("network_error",`Couldn't reach ${new URL(t).origin}: ${s}`)}}function Kl(e,t,n){let r=F(n)?n:{},i=Oe(r.error);if(i!==void 0){let o=Oe(r.error_description);return new ue(i,`${e} failed (${i}${o===void 0?"":`: ${o}`})`)}return new ue("server_error",`${e} failed with HTTP ${String(t)}`)}async function Wl(e,t,n=gr){let r=`${e}/.well-known/oauth-authorization-server`,i=a=>new ue("server_error",`OAuth discovery at ${r} ${a}`),{res:o,body:s}=await Bs(t,r,{},n);if(!o.ok)throw i(`failed with HTTP ${String(o.status)}`);if(!F(s))throw i("didn't return valid JSON");if(s.issuer!==e)throw i(`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 Gl(e,t,n=gr){let{res:r,body:i}=await Bs(t,e.registrationEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:ty,redirect_uris:[Qh],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"})},n);if(!r.ok)throw Kl("App registration",r.status,i);let o=F(i)?Oe(i.client_id):void 0;if(o===void 0)throw new ue("server_error","App registration returned no client_id");return o}var iy=e=>Yh("sha256").update(e,"ascii").digest("base64url"),Fs=()=>Zh(32).toString("base64url");function Jl(){let e=Fs();return{verifier:e,challenge:iy(e)}}function ql(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",ey),n.searchParams.set("state",t.state),n.searchParams.set("code_challenge",t.codeChallenge),n.searchParams.set("code_challenge_method","S256"),n.toString()}async function js(e,t,n,r=gr){let{res:i,body:o}=await Bs(n,e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()},r);if(!i.ok)throw Kl("The token request",i.status,o);let s=F(o)?Oe(o.access_token):void 0,a=F(o)?Oe(o.refresh_token):void 0;if(!F(o)||s===void 0||a===void 0)throw new ue("server_error","The token endpoint returned an unexpected response");return{accessToken:s,refreshToken:a,expiresIn:o.expires_in}}var Ul=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store",Connection:"close"}).end(Ml(n.kind,n.heading,n.text))},oy={kind:"success",heading:"You\u2019re signed in",text:"Sign-in complete. You can close this window."},sy={kind:"error",heading:"Sign-in failed",text:"Sign-in failed. Return to the terminal for details. You can close this window."},ay={kind:"error",heading:"Outdated link",text:"This sign-in link is out of date. Use the latest link from the terminal."},cy=e=>{try{return new URL(e??"/",`http://${xi}`)}catch{return}};async function Yl(e){let t=e.timeoutMs??ny,n,r=new Promise((u,f)=>{n={resolve:u,reject:f}});r.catch(()=>{});let i=!1,o,s=Xh((u,f)=>{let g=cy(u.url);if(i||u.method!=="GET"||g?.pathname!==Ls){f.writeHead(404,{"Content-Type":"text/plain",Connection:"close"}).end("Not found");return}let p=g.searchParams;if(p.get("state")!==e.state){Ul(f,400,ay);return}let m=p.get("error"),h=p.get("error_description"),b=p.get("code")??"",y=m!==null?new ue(m,`Kizen denied the sign-in (${m}${h?`: ${h}`:""})`):b?void 0:new ue("invalid_callback","The sign-in callback had no authorization code");Ul(f,y?400:200,y?sy:oy),c(y,b)}),a=()=>(o??=new Promise(u=>{clearTimeout(l),s.close(()=>{u()}),s.closeAllConnections()}),o);function c(u,f=""){i||(i=!0,u?n.reject(u):n.resolve({code:f}),a())}await new Promise((u,f)=>{s.once("error",f),s.listen(0,xi,()=>{s.off("error",f),u()})});let l=setTimeout(()=>{c(new ue("timeout",`Timed out after ${String(Math.round(t/1e3))}s waiting for the browser sign-in`))},t),d=s.address();return{port:d.port,redirectUri:`http://${xi}:${String(d.port)}${Ls}`,result:r,close:a}}function Zl(e){let[t,n]=zl==="darwin"?["open",[e]]:zl==="win32"?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{let r=qh(t,n,{stdio:"ignore",detached:!0});r.on("error",()=>{}),r.unref()}catch{}}var ge=e=>/^[\w@%+:,./-][\w@%+=:,./-]*$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`;var hr="APPBUILDER_BUSINESS",yr="APPBUILDER_USER";function bn(e,t){if(e.business!==void 0)return{ok:!0,request:{business:e.business,user:e.user,source:"flags"}};if(e.user!==void 0)return{ok:!1,message:"--user only applies with --business."};let n=t[hr]||void 0,r=t[yr]||void 0;return n===void 0?r===void 0?{ok:!0,request:void 0}:{ok:!1,message:`${yr} only applies with ${hr}.`}:{ok:!0,request:{business:n,user:r,source:"env"}}}var ly="To use an API key instead (deprecated), pass --profile <name> or -c <path>.";function Xl(e,t){let n=e.credentials!==void 0||e.profile!==void 0;if(n&&e.env!==void 0)return{ok:!1,message:"--env selects a sign-in session, so it can't be combined with -c or --profile."};if(n&&(e.business!==void 0||e.user!==void 0))return{ok:!1,message:`${e.business===void 0?"--user":"--business"} selects a saved sign-in account, so it can't be combined with -c or --profile.`};if(e.credentials!==void 0)return{ok:!0,selection:{kind:"api-key",credentials:e.credentials}};if(e.profile!==void 0)return{ok:!0,selection:{kind:"api-key",profile:e.profile}};let r=bn(e,t);return r.ok?{ok:!0,selection:{kind:"oauth",...e.env!==void 0&&{env:e.env},...r.request!==void 0&&{account:r.request}}}:r}var Ql=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 ${ge(e)} to use the API key.`}`,eu=e=>`${e} ${ly}`;import{mkdir as tu,readFile as uy,readdir as dy,writeFile as nu}from"fs/promises";import{homedir as py}from"os";import{dirname as my,join as Pi}from"path";var pe=["go","fmo","staging","e2e-staging","integration","e2e-integration","test1","perf"];function br(e){return typeof e=="string"?e.trim():""}function wr(e){return{apiKey:br(e.apiKey),userId:br(e.userId),businessId:br(e.businessId)}}var nt=Pi(py(),".kizenappbuilder"),Wt=Pi(nt,"credentials.json"),Gt="credentials",vr=e=>pe.includes(e),fy=e=>`Unknown --env "${e}". Use one of: ${pe.join(", ")}.`,wn=e=>vr(e)?{environment:e}:{message:fy(e)};function gy(e){return typeof e=="string"?e.trim():e}function hy(e){return vr(e)?"explicit":e==null||e===""?"missing":"invalid"}function yy(e){if(typeof e!="object"||e===null)throw new Error("Credentials must be a JSON object");let t=e,n=gy(t.environment);return{credentials:{...wr(t),environment:vr(n)?n:"go"},environmentSource:hy(n)}}async function Ci(e){let t=await uy(e,"utf-8");return yy(JSON.parse(t))}async function Jt(e){return(await Ci(e)).credentials}async function De(){try{return await Jt(Wt)}catch{return null}}async function by(e){await tu(my(Wt),{recursive:!0,mode:448}),await nu(Wt,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function ru(e){return Pi(nt,`${e}.json`)}async function qt(){let e=[{name:Gt,path:Wt,isDefault:!0}];try{let t=await dy(nt);for(let n of t){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);r!==Gt&&e.push({name:r,path:Pi(nt,n),isDefault:!1})}}catch{}return e}async function iu(e,t){if(e===Gt){await by(t);return}await tu(nt,{recursive:!0,mode:448}),await nu(ru(e),JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}async function _t(e){try{return await Jt(ru(e))}catch{return null}}async function ou(){let e=await qt(),t=await Promise.all(e.map(n=>Ci(n.path).then(()=>!0,()=>!1)));return e.filter((n,r)=>t[r]===!0)}var au="APPBUILDER_NO_INTERACTIVE",su=e=>e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false";function wy(e){return su(e.CI)||e.CODEX_CI!==void 0||e.CLAUDECODE!==void 0||e.TERM==="dumb"||su(e[au])}function vy({stdin:e,stdout:t,json:n,noInteractive:r,env:i}){return e.isTTY===!0&&t.isTTY===!0&&n!==!0&&r!==!0&&!wy(i)}var ft=(e={})=>vy({stdin:process.stdin,stdout:process.stdout,env:process.env,...e}),gt=`run headless even at a terminal (also $${au})`;function Ae(e){let{interactive:t,...n}=e;return{noInteractive:t===!1,options:n}}var ky="The API key is invalid for this business, or the user id doesn't match. Check the credentials file's apiKey, userId and businessId.",Ay="The API key's user needs the Standard API Keys permission and edit access to this dashboard. Homepages also need the Customize Homepages permission.",xy=e=>mt(e,"Kizen rejected the signed-in session.",{again:!0}).message,Py="The signed-in user needs edit access to this dashboard. Homepages also need the Customize Homepages permission.",Cy={authFailed:ky,forbidden:Ay},Sy=100,_y=new Set([301,302,303,307,308]),Ey=5,Iy=new Set(["detail","non_field_errors"]),q=class extends Error{kind;status;hint;details;constructor(t,n,r={}){super(n,r.cause===void 0?void 0:{cause:r.cause}),this.name="KizenApiError",this.kind=t,this.status=r.status,this.hint=r.hint,this.details=r.details}},kr=encodeURIComponent,Ar=(e,t)=>t===void 0?`/dashboards/${kr(e)}/dashlet`:`/dashboards/${kr(e)}/dashlet/${kr(t)}`;function Ms(e,t,n){let r=i=>{n.push(t===""?i:`${t}: ${i}`)};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 i=e.filter(o=>typeof o=="string"&&o.trim()!==""||typeof o=="number"||typeof o=="boolean");i.length>0&&r(i.map(String).join(" "));for(let o of e)typeof o=="object"&&o!==null&&Ms(o,t,n);return}if(F(e))for(let[i,o]of Object.entries(e)){let s=t===""&&Iy.has(i)?"":t===""?i:`${t}.${i}`;Ms(o,s,n)}}function Ty(e){if(typeof e!="object"||e===null)return;let t=[];return Ms(e,"",t),t.length>0?t.join("; "):void 0}async function cu(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 lu(e,t,n,r,i){let o=Ty(r),s=`${e} ${t} failed with ${String(n)}${o===void 0?"":`: ${o}`}`,a=r;return n===401?new q("auth_failed",s,{status:n,hint:i.authFailed,details:a}):n===403?new q("forbidden",s,{status:n,hint:i.forbidden,details:a}):n===404?new q("not_found",s,{status:n,details:a}):new q("api_error",s,{status:n,details:a})}function uu(e,t,n){if(Array.isArray(n))return{results:n,next:null};if(F(n)&&Array.isArray(n.results))return{results:n.results,next:n.next};throw new q("api_error",`${e} ${t} returned an unexpected response shape`)}var Si=e=>F(e)?e:{};function du(e){let t=Si(e);return{business:Si(t.business),team:Si(t.team)}}var Ny=new Map([["login_required","auth_failed"],["network_error","network_error"],["session_store_unwritable","session_store_unwritable"]]);function Ry(e,t){let n=ke(e),r=e instanceof ue?Ny.get(e.code):void 0;return r===void 0?new q("api_error",`Couldn't refresh the ${t} session: ${n}`,{cause:e}):new q(r,n,{cause:e,...e instanceof Ht&&{hint:e.hint}})}function xr(e){let t=e.fetch??fetch,n=e.bearer?e.bearer.environment:e.credentials.environment,r=e.baseUrl??Ds[n],i=new URL(r).origin,o=e.bearer?{authFailed:xy(n),forbidden:Py}:Cy,s=h=>{throw Ry(h,n)},a=async()=>{if(!e.bearer){let{apiKey:y,userId:C,businessId:S}=e.credentials;return{headers:{"X-API-KEY":y,"X-USER-ID":C,"X-BUSINESS-ID":S}}}let{bearer:h}=e,b=await h.getAccessToken().catch(s);return{headers:{Authorization:`Bearer ${b}`},retry:async()=>({Authorization:`Bearer ${await h.refreshAccessToken(b).catch(s)}`})}},c=async(h,b,y,C)=>{let S=async(w,A,_,T)=>{let L={...T,Accept:y},$={method:A,headers:L,redirect:"manual"};_!==void 0&&(L["Content-Type"]=_.contentType,$.body=_.payload);try{return await t(w,$)}catch(V){throw new q("network_error",`Couldn't reach Kizen at ${r}: ${xe(V)}${ki()==="unavailable"?` ${vi}`:""}`)}},x=async w=>{let A=b,_=h,T=C;for(let L=0;;L+=1){let $=await S(A,_,T,w);if($.type==="opaqueredirect")throw new q("api_error",`${h} ${b} was redirected to an unknown location`);let V=_y.has($.status)?$.headers.get("location"):null;if(V===null)return $;await $.body?.cancel().catch(()=>{});let X;try{X=new URL(V,A)}catch{throw new q("api_error",`${h} ${b} was redirected to an invalid location`,{status:$.status})}if(X.origin!==i)throw new q("api_error",`${h} ${b} was redirected to ${X.origin}, outside the Kizen API; the request was not sent there.`,{status:$.status});if(L>=Ey)throw new q("api_error",`${h} ${b} redirected too many times`,{status:$.status});($.status===303||($.status===301||$.status===302)&&_==="POST")&&(_="GET",T=void 0),A=X.toString()}},{headers:v,retry:k}=await a(),P=await x(v);return P.status===401&&k&&(await P.body?.cancel().catch(()=>{}),P=await x(await k())),P},l=(h,b,y,C)=>new q("network_error",`${h} ${b}: couldn't read the response: ${xe(C)}. The request may have been applied; check Kizen before retrying.`,{status:y}),d=h=>{let b=/^https?:\/\//.test(h)?h:`${r}${h}`;return{url:b,path:b.startsWith(r)?b.slice(r.length):b}},u=async(h,b,y)=>{let{url:C,path:S}=d(b),x=await c(h,C,"application/json",y),v,k;try{({text:v,json:k}=await cu(x))}catch(P){throw l(h,S,x.status,P)}if(!x.ok)throw lu(h,S,x.status,k,o);if(k===void 0&&v!=="")throw new q("api_error",`${h} ${S} returned a response that is not JSON`,{status:x.status});return k},f=h=>h===void 0?void 0:{contentType:"application/json",payload:JSON.stringify(h)},g=(h,b)=>{if(!b.startsWith("/")||b.startsWith("//"))throw new q("api_error",`${h} ${b}: expected a path under the Kizen API`);return b},p=h=>{let b=new URL(r),y=new URL(h,b.origin);if(y.protocol=b.protocol,y.port=b.port,y.username="",y.password="",y.hash="",y.origin!==b.origin)throw new q("api_error",`GET /custom-objects pagination pointed at an unexpected location ${y.origin}${y.pathname}`);return y.toString()},m;return{async listDashboards(h,b){let y=new URLSearchParams({size:"10000",include_sharing:"true",dashboard_type:h});b!==void 0&&y.set("custom_object_id",b);let C=`/dashboards/mine?${y.toString()}`;return uu("GET",C,await u("GET",C)).results},async listCustomObjects(h={}){let b=[],y=new Set,C=`/custom-objects?page_size=200${h.customOnly===!1?"&custom_only=false":""}`;for(;C!==void 0&&!y.has(C)&&y.size<Sy;){y.add(C);let S=uu("GET",C,await u("GET",C));b.push(...S.results),C=typeof S.next=="string"&&S.next!==""?p(S.next):void 0}return b},async getCustomObject(h){let b=`/custom-objects/${kr(h)}`,y=await u("GET",b);if(!F(y)||typeof y.id!="string"||typeof y.fetch_url!="string")throw new q("api_error",`GET ${b} returned an unexpected response shape`);return y},async getIdentity(){let h=await u("GET","/auth/bootstrap"),{business:b,team:y}=du(h),C=Oe(b.id),S=Oe(y.user);if(C===void 0||S===void 0)throw new q("api_error","GET /auth/bootstrap returned an unexpected response shape");return m=h,{userId:S,businessId:C,businessName:Oe(b.name),fullName:Oe(y.full_name),email:Oe(y.email)}},async getClientObjectId(){let h=m??await u("GET","/auth/bootstrap"),{business:b}=du(h);return Oe(Si(b.client_object).id)??null},async getDashboard(h){return await u("GET",`/dashboards/${kr(h)}`)},async createDashlet(h,b){return await u("POST",Ar(h),f(b))},async updateDashlet(h,b,y){return await u("PATCH",Ar(h,b),f(y))},async requestJson(h,b,y){return u(h,g(h,b),f(y))},async postForm(h,b){return u("POST",g("POST",h),{contentType:"application/x-www-form-urlencoded",payload:new URLSearchParams(b).toString()})},async getBinary(h){let{url:b,path:y}=d(g("GET",h)),C=await c("GET",b,"*/*");if(!C.ok){let S;try{({json:S}=await cu(C))}catch(x){throw l("GET",y,C.status,x)}throw lu("GET",y,C.status,S,o)}try{return new Uint8Array(await C.arrayBuffer())}catch(S){throw l("GET",y,C.status,S)}}}}var $y=6e4,pu=(e,t)=>fetch(e,t),mu=()=>Date.now(),fu=(e,t,n)=>({store:e,fetch:pu,now:mu,print:t,openBrowser:Zl,startLoopbackServer:Yl,identify:n}),Oy=(e,t)=>({environment:e,getAccessToken:()=>Promise.resolve(t),refreshAccessToken:()=>Promise.reject(mt(e,`Kizen rejected the new ${e} sign-in.`))}),Pr=e=>mt(e,`You're not signed in to ${e}.`),Dy=e=>({businessName:e.businessName,fullName:e.fullName,email:e.email}),gu=(e,t,n)=>({...e,accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:n+t.expiresIn*1e3}),Ly=(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 By(e,t,n,r){let{verifier:i,challenge:o}=Jl(),s=Fs(),a=await n.startLoopbackServer({state:s,...n.timeoutMs!==void 0&&{timeoutMs:n.timeoutMs}});try{let c=ql(e,{clientId:t,redirectUri:a.redirectUri,state:s,codeChallenge:o});n.print(r),n.print(c),n.openBrowser(c);let{code:l}=await a.result;return await js(e.tokenEndpoint,{grant_type:"authorization_code",code:l,redirect_uri:a.redirectUri,client_id:t,code_verifier:i},n.fetch)}finally{await a.close()}}async function zs(e,t,n={}){let r=Ly(e,n.interactive??!0);await t.store.probeWritable();let i=await Wl(Vt(e),t.fetch),o=await t.store.readClientId(i.issuer),s=o??await Gl(i,t.fetch);o===void 0&&await t.store.writeClientId(i.issuer,s);let a;try{a=await By(i,s,t,r)}catch(u){throw u instanceof ue&&u.code==="timeout"&&o!==void 0?(await t.store.forgetClientId(i.issuer),new ue("timeout",`${u.message}. If the browser showed an error instead of a consent page, the saved app registration was stale; it has been cleared. Run \`${pt(e)}\` again.`)):u}let c=await t.identify(Oy(e,a.accessToken)),l={businessId:c.businessId,userId:c.userId},d=gu({environment:e,...l,...Dy(c),issuer:i.issuer,clientId:s,tokenEndpoint:i.tokenEndpoint},a,t.now());if(await t.store.writeSession(d),n.makeCurrent!==void 0&&!n.makeCurrent(c)){if(await t.store.readAccount(e,l)===null)throw Pr(e);return d}if(await t.store.setCurrent(e,l),await t.store.readSession(e)===null)throw Pr(e);return d}async function hu(e,t,n){try{await n.identify(n.provider)}catch(i){if(await n.store.readAccount(e,t).then(s=>s===null,()=>!1))return;throw i}await n.store.setCurrent(e,t);let r=await n.store.readSession(e);if(r===null)throw Pr(e);return r}function Fy(e,t){let n,r=t.account,i,o=d=>d.expiresAt-t.now()>$y,s=d=>{if(d===null)throw Pr(e);return d},a=async()=>r!==void 0?s(await t.store.readAccount(e,r)):(i??=t.store.readSession(e).then(d=>{let u=s(d);return r={businessId:u.businessId,userId:u.userId},u}).finally(()=>{i=void 0}),i),c=async(d,u)=>{let f=await a();if(f.accessToken!==d&&o(f))return f.accessToken;let g=u??t.now()+(t.requestTimeoutMs??gr),p=async()=>{let y=await a();return{stored:y,rotated:y.refreshToken!==f.refreshToken}},m=g-t.now();if(m<=0)return f.accessToken;await t.store.probeWritable();let h;try{h=await js(f.tokenEndpoint,{grant_type:"refresh_token",refresh_token:f.refreshToken,client_id:f.clientId},t.fetch,m)}catch(y){if(y instanceof ue&&(y.code==="invalid_grant"||y.code==="invalid_client")){let{stored:C,rotated:S}=await p();if(S)return o(C)||u!==void 0?C.accessToken:c(C.accessToken,g);if(await t.store.deleteSession(e,f)&&y.code==="invalid_client")try{await t.store.readClientId(f.issuer)===f.clientId&&await t.store.forgetClientId(f.issuer)}catch{}throw mt(e,`The ${e} session is no longer valid.`)}throw y}let b=gu(f,h,t.now());if(await t.store.commitRefresh(b,f.refreshToken)==="gone")throw Pr(e);return b.accessToken},l=d=>(n??=c(d).finally(()=>{n=void 0}),n);return{environment:e,async getAccessToken(){if(n)return n;let d=await a();return o(d)?d.accessToken:l(d.accessToken)},refreshAccessToken:l}}var _i=(e,t,n={})=>Fy(e,{store:t,now:mu,...n,fetch:n.fetch??pu}),jy=`You're not signed in. Run \`${pt(Kt)}\` (add \`--env <env>\` to sign in to an environment other than ${Kt}).`;async function Cr(e,t){if(e!==void 0){let{environment:i,message:o}=wn(e);return i===void 0?{ok:!1,problem:"unknown_environment",message:o}:{ok:!0,environment:i}}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:jy}:{ok:!0,environment:r}}import{randomBytes as Ei}from"crypto";import{chmod as My,mkdir as zy,open as vu,readdir as Uy,readFile as Ii,rename as yu,rm as Vs,stat as ku,unlink as Wn}from"fs/promises";import{dirname as Vy,join as vn}from"path";import{setTimeout as Hy}from"timers/promises";var Ky="clients.json",Wy=" ".repeat(4096),Gy=10*6e4,Jy={waitMs:2e3,staleMs:3e4,pollMs:25};async function qy(e,{waitMs:t,staleMs:n,pollMs:r}){let i=Date.now()+t;for(;;){let o;try{o=await vu(e,"wx",384)}catch(a){if(!He(a,"EEXIST"))return;try{let c=await _e(ku(e));if(c===void 0)continue;if(Date.now()-c.mtimeMs>n){await _e(Wn(e));continue}}catch{return}if(Date.now()>=i)return;await Hy(r);continue}let s=Ei(16).toString("hex");try{await o.writeFile(s,"utf-8")}catch{s=void 0}try{await o.close()}catch{s=void 0}return s===void 0&&await Vs(e,{force:!0}).catch(()=>{}),s}}async function Yy(e,t,n){let r=await qy(e,t);try{return{value:await n(),held:r!==void 0}}finally{if(r!==void 0)try{await _e(Ii(e,"utf-8"))===r&&await _e(Wn(e))}catch{}}}var Zy=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,bu=e=>typeof e=="string"&&Zy.test(e),Ti=e=>F(e)&&bu(e.businessId)&&bu(e.userId)?{businessId:e.businessId,userId:e.userId}:void 0,kn=(e,t)=>e.businessId===t.businessId&&e.userId===t.userId,An=e=>{if(Ti(e)===void 0)throw new Error("Refusing a session file name built from an invalid account id.");return`${e.businessId}.${e.userId}`};function wu(e){let t;try{t=JSON.parse(e)}catch{return}return Ti(t)}var Us=e=>typeof e=="string"?e:void 0;function Xy(e,t){let n=Ti(e);return!F(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:Us(e.businessName),fullName:Us(e.fullName),email:Us(e.email),issuer:e.issuer,clientId:e.clientId,tokenEndpoint:e.tokenEndpoint,accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt}}function ht(e=nt,t={}){let n=vn(e,"oauth"),r={...Jy,...t.lock},i=w=>vn(n,`${w}.json`),o=(w,A)=>vn(n,`${w}.${An(A)}.json`),s=(w,A)=>vn(n,`${w}.${An(A)}.lock`),a=async(w,A,_)=>(await Yy(s(w,A),r,_)).value,c=vn(n,Ky),l=(w,A)=>{let _=`${w}.`;if(!A.startsWith(_)||!A.endsWith(".json"))return;let T=A.slice(_.length,-5).split(".");if(T.length!==2)return;let[L,$]=T;return Ti({businessId:L,userId:$})},d=async()=>await _e(Uy(n))??[],u=async w=>{try{return await w()}catch(A){let _=Hl.find(T=>He(A,T));throw _!==void 0?new Ht(n,Vy(n),_):A}},f=async()=>{await zy(n,{recursive:!0,mode:448}),await My(n,448)},g=async(w,A,_)=>{let T=`${w}.${Ei(6).toString("hex")}.tmp`;try{let L=await vu(T,"wx",384);try{await L.writeFile(A,"utf-8"),await L.sync()}finally{await L.close()}await yu(T,_)}catch(L){throw await Vs(T,{force:!0}).catch(()=>{}),L}},p=(w,A)=>u(async()=>{await f(),await g(w,JSON.stringify(A,null,2),w)}),m=()=>u(async()=>{await f();let w=vn(n,`.write-probe.${Ei(6).toString("hex")}`);await g(w,Wy,w),await Wn(w)}),h=(w,A)=>mt(w,`The saved ${w} session at ${A} can't be read.`,{again:!0}),b=async w=>{try{let A=new RegExp(`^${w}\\.json\\.([0-9]{1,16})-[0-9a-f]{12}\\.signout$`);for(let _ of await d()){let T=A.exec(_)?.[1];T!==void 0&&Date.now()-Number(T)>Gy&&await _e(Wn(vn(n,_)));let L=_.endsWith(".lock")?l(w,`${_.slice(0,-5)}.json`):void 0;if(L!==void 0){let $=s(w,L),V=await _e(ku($));V!==void 0&&Date.now()-V.mtimeMs>r.staleMs&&await _e(Wn($))}}}catch{}},y=async()=>{let w;try{w=JSON.parse(await _e(Ii(c,"utf-8"))??"{}")}catch(A){if(A instanceof SyntaxError)return{};throw A}return F(w)?w:{}},C=async(w,A)=>{try{return await _e(Ii(A,"utf-8"))}catch{throw h(w,A)}},S=async(w,A)=>{let _=o(w,A),T=await C(w,_);if(T===void 0)return null;try{let L=Xy(JSON.parse(T),w);if(L!==null&&kn(L,A))return L}catch{}throw h(w,_)},x=async w=>{let A=i(w),_=await C(w,A);if(_===void 0)return;let T=wu(_);if(T===void 0)throw h(w,A);return T},v=async w=>{let A=await x(w);return A===void 0?null:S(w,A)},k=async w=>{let A=i(w),_=`${A}.${String(Date.now())}-${Ei(6).toString("hex")}.signout`;if(await u(()=>_e(yu(A,_).then(()=>!0)))===!0)try{return{account:wu(await Ii(_,"utf-8"))}}catch{return{account:void 0}}finally{await Vs(_,{force:!0})}},P=(w,A)=>a(w,A,async()=>await u(()=>_e(Wn(o(w,A)).then(()=>!0)))??!1);return{dir:n,sessionPath:i,accountPath:o,readSession:v,readAccount:S,async listAccounts(w){let A;try{A=await x(w)}catch{}let _=(await d()).map($=>l(w,$)).filter($=>$!==void 0),T=await Promise.all(_.map(async $=>{let V;try{let X=await S(w,$);if(X===null)return;V=X}catch(X){if(!(X instanceof ue&&X.code==="login_required"))throw X}return{account:$,session:V,current:A!==void 0&&kn(A,$)}})),L=$=>($.session?.businessName??$.account.businessId).toLowerCase();return T.filter($=>$!==void 0).sort(($,V)=>L($).localeCompare(L(V))||An($.account).localeCompare(An(V.account)))},async writeSession(w){await p(o(w.environment,w),w)},probeWritable:m,async commitRefresh(w,A){let{environment:_}=w;return a(_,w,async()=>{let T=await S(_,w);return T===null?"gone":T.refreshToken!==A?"rotated":(await p(o(_,w),w),"written")})},async setCurrent(w,A){let{businessId:_,userId:T}=A;await p(i(w),{businessId:_,userId:T}),await b(w)},async deleteSession(w,A){return P(w,A)},async signOut(w){let A=await k(w),_=A!==void 0;return A?.account!==void 0&&(_=await P(w,A.account)),await b(w),_},async removeAccount(w,A){let _=!1,T;try{T=await x(w)}catch{}T!==void 0&&kn(T,A)&&(_=await k(w)!==void 0);let L=await P(w,A);return await b(w),{removed:L,current:_}},async signOutAll(w){let A=await k(w),_=A!==void 0&&A.account===void 0,T=0;for(let L of await d()){let $=l(w,L);$!==void 0&&await P(w,$)&&(T+=1,_||=A?.account!==void 0&&kn(A.account,$))}return await b(w),{signedIn:_,removed:T}},async listSessions(){return(await Promise.all(pe.map(async A=>{try{return await v(A)===null?void 0:A}catch(_){if(_ instanceof ue&&_.code==="login_required")return A;throw _}}))).filter(A=>A!==void 0)},async readClientId(w){let A=(await y())[w];return F(A)?Oe(A.clientId):void 0},async writeClientId(w,A){await p(c,{...await y(),[w]:{clientId:A}})},async forgetClientId(w){let A=await y();w in A&&await p(c,Object.fromEntries(Object.entries(A).filter(([_])=>_!==w)))}}}var Qy=5e3;function xu(e=ht(),t,n=!1){let r=(s,a)=>_i(s,e,a),i=s=>{process.stderr.write(s)},o=s=>xr({bearer:s}).getIdentity();return{store:e,loginDeps:fu(e,s=>{i(`${s}
|
|
86
|
+
`)},o),identify:o,tokenProvider:r,isInteractive:()=>ft({noInteractive:n}),...t!==void 0&&{pickAccount:t},authHeaderTimeouts:{requestTimeoutMs:Qy},processEnv:process.env,writeStdout:s=>{process.stdout.write(s)},writeStderr:i,setExitCode:s=>{process.exitCode=s}}}function Pu(e){let{environment:t,message:n}=wn(e);if(t===void 0)throw new Error(n);return t}async function Cu(e,t,n){let r=await _r(e,n,t);if(!r.ok)throw new Error(r.message);return r.environment}var Ni=(e,t)=>e?`${e} (${t})`:t,Ri=(e,t)=>{let n=[t.fullName,t.email&&`<${t.email}>`].filter(Boolean).join(" ");return`Environment: ${e}
|
|
87
87
|
User: ${n===""?t.userId:`${n} (${t.userId})`}
|
|
88
88
|
Business: ${Ni(t.businessName,t.businessId)}
|
|
89
|
-
`};function
|
|
89
|
+
`};function Su(e,t,{prefix:n="Error",oneLine:r=!1}={}){let i=ke(t),o=(t instanceof q||t instanceof Ht)&&t.hint!==void 0?`
|
|
90
90
|
${t.hint}`:"";e.writeStderr(`${n}: ${r?i.replace(/\s+/g," ").trim():`${i}${o}`}
|
|
91
|
-
`),e.setExitCode(1)}var
|
|
92
|
-
`),e.writeStdout(Ri(t.environment,t))},Pn="browser",
|
|
93
|
-
${
|
|
94
|
-
${
|
|
91
|
+
`),e.setExitCode(1)}var Ks=e=>async(t,n)=>{try{await e(t,n)}catch(r){Su(n,r)}},Hs=(e,t)=>{e.writeStdout(`Signed in to ${t.environment}.
|
|
92
|
+
`),e.writeStdout(Ri(t.environment,t))},Pn="browser",Et=({account:e,session:t})=>`${Ni(t?.businessName,e.businessId)} ${t?.email??`user ${e.userId}`}${t===void 0?" (can't be read)":""}`,eb=e=>[...e.map(({account:t,session:n,current:r})=>({key:An(t),label:Ni(n?.businessName,t.businessId),description:[n?.email??t.userId,n===void 0?"(can't be read)":"",r?"(current)":""].filter(Boolean).join(" ")})),{key:Pn,label:"Sign in with the browser"}],tb=(e,t)=>e===Pn?Pn:t.find(({account:n})=>An(n)===e),nb=(e,{business:t,user:n})=>(e.businessId===t||e.businessName?.toLowerCase()===t.toLowerCase())&&(n===void 0||e.userId===n);function Sr(e,t,n){let r=e.filter(({account:a})=>a.businessId===t),i=r.length>0?r:e.filter(({session:a})=>a?.businessName?.toLowerCase()===t.toLowerCase()),o=n===void 0?i:i.filter(({account:a})=>a.userId===n),[s]=o;return o.length===1&&s!==void 0?{kind:"one",account:s}:o.length===0?{kind:"none",candidates:[...e]}:{kind:"several",candidates:o}}var Au=e=>e.map(t=>`
|
|
93
|
+
${Et(t)}`).join(""),_u=(e,t)=>e==="env"?`${yr}=${ge(t)}`:`--user ${ge(t)}`,xn=({business:e,user:t,source:n})=>`${n==="env"?`${hr}=${ge(e)}`:`--business ${ge(e)}`}${t===void 0?"":` ${_u(n,t)}`}`;function Ws(e,t,n,r=Sr(t,n.business,n.user)){if(r.kind==="one")return r.account;let i=xn(n);if(r.kind==="none")throw new Error(`No saved ${e} account matches ${i}. Saved accounts:${Au(r.candidates)}`);let[o]=r.candidates;if(o!==void 0&&r.candidates.every(({account:a})=>a.businessId===o.account.businessId)){let{source:a}=n;throw new Error(`${i} matches several saved ${e} users of the same business. ${a==="env"?`Set ${yr}`:"Pass --user"} too, for example \`${xn({business:o.account.businessId,user:o.account.userId,source:a})}\`:${r.candidates.map(c=>`
|
|
94
|
+
${_u(a,c.account.userId)}: ${Et(c)}`).join("")}`)}throw new Error(`${i} matches several saved ${e} accounts. ${n.source==="env"?`Set ${hr} to`:"Pass"} one of these business ids instead:${Au(r.candidates)}`)}async function _r(e,t,n){let r=async a=>{let c=[],l=await Cr(e,async()=>(c=await a(),c));return l.ok?l:{...l,environments:c}};if(t===void 0||e!==void 0)return r(()=>n.listSessions());let i=await Promise.all(pe.map(async a=>({environment:a,accounts:await n.listAccounts(a)}))),o=i.filter(({accounts:a})=>Sr(a,t.business,t.user).kind!=="none").map(({environment:a})=>a),[s]=o;return o.length===1&&s!==void 0?{ok:!0,environment:s}:o.length>1?{ok:!1,problem:"several_sessions",message:`${xn(t)} matches saved accounts in several environments; pass --env <env>: ${o.join(", ")}`,environments:o}:r(()=>Promise.resolve(i.filter(({accounts:a})=>a.length>0).map(({environment:a})=>a)))}var Er=(e,t,n)=>Ws(e,t,n).account;function Gs(e,t){let n=bn(e,t);if(!n.ok)throw new Error(n.message);return n.request}function rb(e,t,n,r){if(n){r.writeStdout(`${JSON.stringify(t.map(({account:i,session:o,current:s})=>({businessId:i.businessId,userId:i.userId,businessName:o?.businessName??null,fullName:o?.fullName??null,email:o?.email??null,current:s,readable:o!==void 0})))}
|
|
95
95
|
`);return}if(t.length===0){r.writeStdout(`No saved accounts for ${e}.
|
|
96
|
-
`);return}for(let i of t)r.writeStdout(`${
|
|
97
|
-
`)}async function
|
|
98
|
-
`),Pn):
|
|
96
|
+
`);return}for(let i of t)r.writeStdout(`${Et(i)}${i.current?" (current)":""}
|
|
97
|
+
`)}async function ib(e,t,n,r){if(t.business!==void 0){let i={business:t.business,user:t.user},o=Sr(n,i.business,i.user);return o.kind==="none"?{kind:"not_saved",request:i}:Ws(e,n,i,o)}return n.length===0?Pn:r.pickAccount===void 0||!r.isInteractive()?(r.writeStderr(`Saved accounts for ${e} exist; pass --business <id> to switch without the browser, or --list to see them.
|
|
98
|
+
`),Pn):tb(await r.pickAccount(`Sign in to ${e}`,eb(n)),n)}function ob(e,t,n){let r=t.kind==="expired"?`The saved sign-in for ${Et(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)}`}.`,i=t.kind==="expired"?Ni(t.account.session?.businessName&&JSON.stringify(t.account.session.businessName),t.account.account.businessId):JSON.stringify(t.request.business),o=t.kind==="expired"?t.account.session?.email??t.account.account.userId:t.request.user,s=`the business ${i}${o===void 0?"":`, signed in as ${o}`}`;return n?`${r}
|
|
99
99
|
A browser window is opening to sign in to Kizen ${e}. On the consent page, choose ${s}.
|
|
100
100
|
`:`${r}
|
|
101
101
|
Waiting for the user to sign in to Kizen ${e} in a browser window. Ask them to choose ${s}.
|
|
102
|
-
`}function
|
|
103
|
-
`),t.setExitCode(1);return}if(i!==Pn&&!("kind"in i)){let
|
|
104
|
-
`);let b=await
|
|
105
|
-
`),
|
|
106
|
-
${g}${
|
|
107
|
-
`),t.setExitCode(1)}),
|
|
102
|
+
`}function sb(e,t){if(t.kind==="expired"){let{account:n}=t.account;return{accepts:r=>kn(r,n),requested:Et(t.account),retry:`${pt(e)} ${xn({business:n.businessId,user:n.userId})}`}}return{accepts:n=>nb(n,t.request),requested:xn(t.request),retry:`${pt(e)} ${xn(t.request)}`}}var Eu=Ks(async(e,t)=>{let n=Pu(e.env??Kt);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){rb(n,r,e.json===!0,t);return}let i=await ib(n,e,r,t);if(i===void 0){t.writeStderr(`Cancelled.
|
|
103
|
+
`),t.setExitCode(1);return}if(i!==Pn&&!("kind"in i)){let m=i,{account:h}=m;t.writeStderr(`Switching to ${Et(m)} on ${n}.
|
|
104
|
+
`);let b=await hu(n,h,{store:t.store,provider:t.tokenProvider(n,{account:h}),identify:t.identify});if(b!==void 0){Hs(t,b);return}i={kind:"expired",account:m}}if(i===Pn){t.writeStderr(`Signing in to ${n}.
|
|
105
|
+
`),Hs(t,await zs(n,t.loginDeps,{interactive:t.isInteractive()}));return}let o=t.isInteractive(),s=sb(n,i);t.writeStderr(ob(n,i,o));let a=await zs(n,t.loginDeps,{makeCurrent:s.accepts,interactive:o});if(s.accepts(a)){Hs(t,a);return}let c=await t.store.readSession(n).catch(()=>null),l=c!==null&&kn(c,a),d=Et({account:a,session:a,current:!1}),u=o?"You":"The user",f=l?`That's already the current ${n} account; its saved session was updated.`:`It was saved, but it isn't the current ${n} account.`,g=l?"":`To use it, run \`${pt(n)} ${xn({business:a.businessId,user:a.userId})}\`. `,p=o?"To try again":"To have them try again";t.writeStderr(`${u} signed in as ${d}, not ${s.requested}. ${f}
|
|
106
|
+
${g}${p}, run \`${s.retry}\`.
|
|
107
|
+
`),t.setExitCode(1)}),Iu=Ks(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 Cr(e.env,()=>t.store.listSessions());if(!n.ok){if(n.problem!=="not_signed_in")throw new Error(n.message);if(e.business!==void 0)throw new Error("Pass --env <env> with --business to remove a saved account.");if(e.all===!0)throw new Error("Pass --env <env> with --all to remove every saved account.");t.writeStdout(`Not signed in.
|
|
108
108
|
`);return}let{environment:r}=n;if(e.business!==void 0){let o=await t.store.listAccounts(r);if(o.length===0){t.writeStdout(`No saved accounts for ${r}.
|
|
109
|
-
`);return}let s=
|
|
110
|
-
`:`No saved ${r} account ${
|
|
109
|
+
`);return}let s=Ws(r,o,{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 ${Et(s)} from this machine.${c?` You're no longer signed in to ${r}.`:""}
|
|
110
|
+
`:`No saved ${r} account ${Et(s)}.
|
|
111
111
|
`);return}if(e.all===!0){let{signedIn:o,removed:s}=await t.store.signOutAll(r);t.writeStdout(o||s>0?`Signed out of ${r}. Removed ${String(s)} saved ${s===1?"account":"accounts"} from this machine.
|
|
112
112
|
`:`No saved accounts for ${r}.
|
|
113
113
|
`);return}let i=await t.store.signOut(r);t.writeStdout(i?`Signed out of ${r}. The session was removed from this machine.
|
|
114
114
|
`:`Not signed in to ${r}.
|
|
115
|
-
`)}),
|
|
116
|
-
`}catch(r){
|
|
117
|
-
`),e.setExitCode(1)};async function
|
|
118
|
-
`)}async function
|
|
119
|
-
`).map(t=>t.trim().replace(/\s+#.*$/,"")).filter(t=>t.length>0&&!t.startsWith("#"))}function
|
|
120
|
-
`).slice(-
|
|
115
|
+
`)}),Tu=Ks(async(e,t)=>{let n=Gs(e,t.processEnv),r=await Cu(e.env,t.store,n),i=n===void 0?void 0:Er(r,await t.store.listAccounts(r),n);t.writeStdout(Ri(r,await t.identify(t.tokenProvider(r,i===void 0?void 0:{account:i}))))});function ab(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=pe.find(r=>Vt(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 cb(e,t){let n=e===void 0?void 0:Pu(e),r=t.processEnv.CLAUDE_CODE_MCP_SERVER_URL;if(r!==void 0&&r!==""){let i=ab(r);if(n!==void 0&&n!==i.environment)throw new Error(`--env ${n} doesn't match the MCP server ${i.origin} (${i.environment}), so auth-header won't send it a token.`);return i.environment}return n??Cu(void 0,t.store)}function lb(e){let{business:t,user:n}=e;if(!(t===void 0&&n===void 0)){if(t===void 0||n===void 0)throw new Error("auth-header takes --business and --user together.");return{businessId:t,userId:n}}}var Nu=async(e,t)=>{let n;try{let r=lb(e),i=await cb(e.env,t),{requestTimeoutMs:o}=t.authHeaderTimeouts,s=await t.tokenProvider(i,{requestTimeoutMs:o,...r!==void 0&&{account:r}}).getAccessToken();n=`${JSON.stringify({Authorization:`Bearer ${s}`})}
|
|
116
|
+
`}catch(r){Su(t,r,{prefix:"appbuilder auth-header",oneLine:!0});return}t.writeStdout(n)};var $i="appbuilder admin",db={env:["--env","<env>"],business:["--business","<id-or-name>"],user:["--user","<userId>"]},Ru=["-h","--help"],pb="--force";function mb(e){let t={},n=0,r=o=>({kind:"run",env:t.env,...t.business!==void 0&&{business:t.business},...t.user!==void 0&&{user:t.user},args:o});e:for(;n<e.length;){let o=e[n]??"";if(o==="--")return r(e.slice(n+1));if(Ru.includes(o))return{kind:"help"};for(let[s,[a,c]]of Object.entries(db))if(o===a||o.startsWith(`${a}=`)){let l=o===a?e[n+1]:o.slice(a.length+1);if(l===void 0||l==="")return{kind:"error",message:`option '${a} ${c}' argument missing`};t[s]=l,n+=o===a?2:1;continue e}break}let i=e.slice(n);if(i[0]==="init"){let o=i.slice(1);return o.length===0?{kind:"init",force:!1}:o.length===1&&o[0]===pb?{kind:"init",force:!0}:o.length===1&&Ru.includes(o[0]??"")?{kind:"init-help"}:{kind:"error",message:`admin init takes only --force, but got: ${o.map(ge).join(" ")}`}}return r(i)}var fb=(e,t,n,r)=>[e,t,"auth-header","--env",n,"--business",r.businessId,"--user",r.userId].map(ge).join(" "),gb=["KIZEN_PROFILE","CLAUDE_CODE_MCP_SERVER_URL","KICODE_API_KEY"];function hb(e,t){let n={};for(let[r,i]of Object.entries(e))i!==void 0&&!gb.includes(r)&&(n[r]=i);return{...n,...t}}var $u=["SIGTERM","SIGHUP"];function yb(e,t,n,r,i,o){return new Promise((s,a)=>{let c;try{c=r(e.python,[e.kizen,...t],{stdio:"inherit",env:n})}catch(g){a(g instanceof Error?g:new Error(String(g)));return}let d=[...(o?$u:[...$u,"SIGINT"]).map(g=>[g,()=>{c.kill(g)}]),...o?[["SIGINT",()=>{}]]:[]];for(let[g,p]of d)i.on(g,p);let u=!1,f=g=>{if(!u){u=!0;for(let[p,m]of d)i.off(p,m);g()}};c.on("error",g=>{f(()=>{a(g)})}),c.on("close",(g,p)=>{f(()=>{s(g??128+(p===null?0:ub.signals[p]))})})})}var Gn=(e,t)=>{e.writeStderr(`${$i}: ${t}
|
|
117
|
+
`),e.setExitCode(1)};async function bb(e,t=!1){let n;try{n=await e.ensureKizen(t?{force:t}:void 0)}catch(r){Gn(e,ke(r));return}e.writeStderr(`${$i}: kizen ${n.version} is ready in ${n.dir}.
|
|
118
|
+
`)}async function wb(e,t){let n=Gs(e,t.processEnv),r=await _r(e.env,n,t.store);if(!r.ok)return{ok:!1,message:r.message};let{environment:i}=r,o;if(n===void 0)o=await t.store.readSession(i);else{let s=Er(i,await t.store.listAccounts(i),n);o=await t.store.readAccount(i,s)}return o===null?{ok:!1,message:mt(i,`You're not signed in to ${i}.`).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:fb(t.execPath,t.scriptPath,i,o),KIZEN_BASE_URL:Vt(i),KIZEN_BUSINESS_ID:o.businessId,KIZEN_USER_ID:o.userId}}}async function Ou(e,t){let n=mb(e);switch(n.kind){case"help":t.outputHelp();return;case"init-help":t.outputInitHelp();return;case"init":await bb(t,n.force);return;case"error":Gn(t,n.message);return;case"run":break}let r;try{r=await wb(n,t)}catch(s){Gn(t,ke(s));return}if(!r.ok){Gn(t,r.message);return}let i;try{i=await t.ensureKizen()}catch(s){Gn(t,ke(s));return}let o=hb(t.processEnv,r.session);try{t.setExitCode(await yb(i,n.args,o,t.spawn,t.signals,t.interactive))}catch(s){Gn(t,`couldn't start kizen: ${ke(s)}`)}}import{spawn as Ab}from"child_process";import{createHash as Mu,randomBytes as xb}from"crypto";import{createReadStream as Pb,createWriteStream as Cb}from"fs";import{access as Fu,mkdir as ju,readdir as Sb,readFile as _b,rename as Eb,rm as Tr,stat as Di,utimes as Ib,writeFile as Tb}from"fs/promises";import{basename as Qs,join as Yt}from"path";import{Readable as Nb,Transform as Rb}from"stream";import{pipeline as zu}from"stream/promises";import{spawn as vb}from"child_process";function Du(e){return e.split(`
|
|
119
|
+
`).map(t=>t.trim().replace(/\s+#.*$/,"")).filter(t=>t.length>0&&!t.startsWith("#"))}function Lu(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 Js([e,t],n){return e>n[0]||e===n[0]&&t>=n[1]}function Cn(e){return`${String(e[0])}.${String(e[1])}`}var kb=(e,t)=>e[0]>t[0]||e[0]===t[0]&&e[1]>t[1];function Oi(e){return new Promise(t=>{let n=vb(e,["-c","import sys; print('%d.%d' % sys.version_info[:2])"],{stdio:["ignore","pipe","ignore"]}),r="";n.stdout.on("data",i=>{r+=i.toString("utf-8")}),n.on("error",()=>{t(null)}),n.on("close",i=>{let o=/(\d+)\.(\d+)/.exec(r);if(i!==0||!o){t(null);return}t([Number(o[1]),Number(o[2])])})})}async function qs(e,t,n,r=Oi){let i=[],o;for(let s of e){let a=await r(s);if(!a){i.push(`${s}: not found`);continue}if(!Js(a,t)){i.push(`${s}: ${Cn(a)} (too old)`);continue}if((o===void 0||kb(a,o.version))&&(o={bin:s,version:a}),n==="first")break}return{found:o,tried:i}}var Ir=[3,10];async function Bu(e,t=Oi){let n=Lu(e),r=n==="python3"?["python3"]:[n,"python3"],{found:i,tried:o}=await qs(r,Ir,"first",t);if(i!==void 0)return i.bin;throw new Error(`No Python >= ${Cn(Ir)} found for runtime "${e}". The local runner needs Python ${Cn(Ir)}+ to install the bundled packages (e.g. psycopg 3.3), matching the remote code-runner (3.12 / 3.13). Tried ${o.join(", ")}. Install Python 3.12 or 3.13 and retry.`)}var $b=e=>`https://github.com/kizen/kizen-admin-cli/releases/download/v${e}/kizen_builder-${e}-py3-none-any.whl`,Ob={version:"0.5.0",wheelUrl:$b("0.5.0"),sha256:"903f8824f3d624d23cf904e49bf03434ea849588ecf74ba7cdf190279bfff7c7"},Li="APPBUILDER_KIZEN_WHEEL",Db=Yt(nt,"kizen"),Lb=".appbuilder-ready.json",Ys=[3,12],Bb=["python3.14","python3.13","python3.12","python3"],Fb=720*60*6e4,jb=60*6e4,Mb=5*6e4,zb=/^[0-9][\w.+!]*-[0-9a-f]{12}$/,Ub=/^kizen_builder-([^-]+)-.*\.whl$/;async function Vb(e){let{found:t,tried:n}=await qs(Bb,Ys,"newest",e);if(t===void 0)throw new Error(`No Python ${Cn(Ys)} or newer found to run kizen. Tried ${n.join(", ")}. Install Python ${Cn(Ys)} or newer and retry.`);return t}var Hb=20,Kb=e=>(t,n)=>new Promise((r,i)=>{let o=Ab(t,n,{stdio:["ignore","pipe","pipe"]}),s="",a=c=>{s+=c.toString("utf-8")};o.stdout.on("data",a),o.stderr.on("data",a),o.on("error",c=>{i(new Error(`couldn't run ${t}: ${c.message}`))}),o.on("close",(c,l)=>{if(c===0){r();return}let d=s.trimEnd().split(`
|
|
120
|
+
`).slice(-Hb).join(`
|
|
121
121
|
`);d!==""&&e(`${d}
|
|
122
|
-
`),i(new Error(`${
|
|
123
|
-
`),l=await
|
|
122
|
+
`),i(new Error(`${Qs(t)} exited with ${c===null?String(l):`code ${String(c)}`}`))})});function Uu(e,t,n=process.env){let r=n[Li];return{baseDir:Db,pin:Ob,localWheel:r===""?void 0:r,fetch:(...i)=>fetch(...i),findPython:()=>Vb(),run:Kb(t),log:e,now:Date.now}}var Wb=async e=>{let t=Mu("sha256");return await zu(Pb(e),t),t.digest("hex")},Bi=e=>Yt(e,Lb),Nr=(e,t)=>Yt(e,"bin",t);async function Xs(e,t){try{let n=JSON.parse(await _b(Bi(e),"utf-8"));return!F(n)||n.sha256!==t?!1:(await Fu(Nr(e,"python")),await Fu(Nr(e,"kizen")),!0)}catch{return!1}}async function Zs(e,t){let n=new Date(t);await Ib(Bi(e),n,n).catch(()=>{})}async function Gb(e){if(e.localWheel!==void 0){let t=e.localWheel,n=Ub.exec(Qs(t))?.[1];if(n===void 0)throw new Error(`${Li} must name a kizen_builder wheel (kizen_builder-<version>-\u2026.whl), not ${t}.`);let r;try{r=await Wb(t)}catch(i){throw new Error(`Couldn't read ${Li} ${t}: ${xe(i)}`)}return{version:n,sha256:r,localPath:t}}return{version:e.pin.version,sha256:e.pin.sha256,localPath:void 0}}async function Jb(e,t,n){let r=Mu("sha256");try{let i=await e.fetch(t,{signal:AbortSignal.timeout(Mb)});if(!i.ok||i.body===null)throw new Error(`HTTP ${String(i.status)}`);await zu(Nb.fromWeb(i.body),new Rb({transform(o,s,a){r.update(o),a(null,o)}}),Cb(n))}catch(i){throw new Error(`Couldn't download kizen from ${t}: ${xe(i)}`)}return r.digest("hex")}var qb=e=>`.tmp-${e}-${String(process.pid)}-${xb(4).toString("hex")}`;async function Yb(e,t,n){let r;try{r=await Sb(e)}catch{return}await Promise.all(r.map(async i=>{if(i===t)return;let o=Yt(e,i);try{if(zb.test(i)){let{mtimeMs:s}=await Di(Bi(o)).catch(()=>Di(o));n-s>Fb&&await Tr(o,{recursive:!0,force:!0})}else if(i.startsWith(".tmp-")){let{mtimeMs:s}=await Di(o);n-s>jb&&await Tr(o,{recursive:!0,force:!0})}}catch{}}))}var Zb=e=>Di(e).then(()=>!0,()=>!1),Vu=e=>new Error(`kizen's install at ${e} is damaged. Run \`appbuilder admin init --force\` to reinstall it.`);async function Xb(e,t,n){try{return await Eb(e,t),!0}catch(r){if(!He(r,"ENOTEMPTY")&&!He(r,"EEXIST"))throw r}if(await Xs(t,n))return!1;throw Vu(t)}async function Hu(e,t={}){let n=await Gb(e),r=`${n.version}-${n.sha256.slice(0,12)}`,i=Yt(e.baseDir,r),o=u=>({version:n.version,dir:i,python:Nr(i,"python"),kizen:Nr(i,"kizen"),built:u});if(t.force===!0)e.log(`Removing ${i}.`),await Tr(i,{recursive:!0,force:!0});else{if(await Xs(i,n.sha256))return await Zs(i,e.now()),o(!1);if(await Zb(i)){if(await Xs(i,n.sha256))return await Zs(i,e.now()),o(!1);throw Vu(i)}}e.log(`Installing kizen ${n.version} into ${i} (first run only).`);let s=await e.findPython();e.log(`Using ${s.bin} (Python ${Cn(s.version)}).`),await ju(e.baseDir,{recursive:!0,mode:448});let a=Yt(e.baseDir,qb(r)),c=Yt(a,"venv"),l;try{await ju(a);let u;if(n.localPath===void 0){u=Yt(a,Qs(new URL(e.pin.wheelUrl).pathname)),e.log(`Downloading ${e.pin.wheelUrl}`);let f=await Jb(e,e.pin.wheelUrl,u);if(f!==n.sha256)throw await Tr(u,{force:!0}),new Error(`The kizen ${n.version} download doesn't match its pinned sha256 (expected ${n.sha256}, got ${f}), so nothing was installed.`)}else u=n.localPath,e.log(`Using the local wheel ${u} (${Li}).`);e.log("Creating a virtual environment.");try{await e.run(s.bin,["-m","venv",c])}catch(f){throw new Error(`Couldn't create a virtual environment: ${ke(f)}`)}e.log(`Installing kizen ${n.version} from the wheel and its dependencies from PyPI.`);try{await e.run(Nr(c,"python"),["-m","pip","install","--disable-pip-version-check",u])}catch(f){throw new Error(`Couldn't install kizen: ${ke(f)}`)}await Tb(Bi(c),`${JSON.stringify({version:n.version,sha256:n.sha256},null,2)}
|
|
123
|
+
`),l=await Xb(c,i,n.sha256)}finally{await Tr(a,{recursive:!0,force:!0}).catch(()=>{})}let d=e.now();return await Zs(i,d),l&&(e.log(`kizen ${n.version} is installed.`),await Yb(e.baseDir,r,d)),o(l)}var ea="admin",tw=`Usage: appbuilder admin init [--force]
|
|
124
124
|
|
|
125
125
|
Install kizen for appbuilder admin, or confirm it's installed. Needs Python 3.12 or newer.
|
|
126
126
|
|
|
127
127
|
Options:
|
|
128
128
|
--force remove kizen's install and install it again, to repair a damaged one; don't run it
|
|
129
129
|
while appbuilder admin is running
|
|
130
|
-
`,
|
|
131
|
-
`)},t),r=process.stdin;return{store:
|
|
130
|
+
`,ta=class extends ew{parseOptions(t){return{operands:[...t],unknown:[]}}};function nw(e){let t=i=>{process.stderr.write(i)},n=Uu(i=>{t(`${$i}: ${i}
|
|
131
|
+
`)},t),r=process.stdin;return{store:ht(),ensureKizen:i=>Hu(n,i),spawn:Qb,signals:process,interactive:r.isTTY===!0,processEnv:process.env,execPath:process.execPath,scriptPath:process.argv[1],outputHelp:()=>{e.outputHelp()},outputInitHelp:()=>{process.stdout.write(tw)},writeStderr:t,setExitCode:i=>{process.exitCode=i}}}function Ku(e){let t=new ta(ea).copyInheritedSettings(e).description("Run Kizen's admin CLI (kizen) with the signed-in session").usage(`[--env <env>] [--business <id-or-name> [--user <userId>]] [--] <kizen args...>
|
|
132
132
|
appbuilder admin init [--force]`).option("--env <env>","environment to use (default: the only signed-in one, or with --business the only one where it's saved)").option("--business <id-or-name>","use this saved account, by business id or name (ignoring case), instead of the current one (default: $APPBUILDER_BUSINESS)").option("--user <userId>","with --business, use the saved account of this user id (default: $APPBUILDER_USER)").allowExcessArguments().addHelpText("after",`
|
|
133
133
|
Wrapper options end at the first other argument or at --; everything after goes to kizen.
|
|
134
|
-
"appbuilder admin init" installs kizen ahead of time; it's otherwise installed on first use.`).action(async()=>{await
|
|
135
|
-
`)){let s=
|
|
136
|
-
`).replace(/\{\{([^}]*)\}\}/g,(o,s)=>{let a=
|
|
137
|
-
`),{mtime:$r}],
|
|
138
|
-
`,
|
|
134
|
+
"appbuilder admin init" installs kizen ahead of time; it's otherwise installed on first use.`).action(async()=>{await Ou(t.args,nw(t))});e.addCommand(t);let n=e.parseOptions.bind(e);e.parseOptions=r=>r[0]===ea?{operands:[ea],unknown:r.slice(1)}:n(r)}import{createElement as mP}from"react";import{render as fP}from"ink";import{createHash as qk}from"crypto";import{access as Yk,mkdtemp as Zk,readFile as cp,rm as Xk}from"fs/promises";import{tmpdir as Qk}from"os";import{dirname as eA,join as $n,resolve as op,sep as tA}from"path";import{execFile as Uw}from"child_process";import{createHash as Vw,randomUUID as Hw}from"crypto";import{constants as ld}from"fs";import{chmod as Kw,lstat as En,mkdir as Qt,mkdtemp as Ww,open as Gw,readdir as Jw,readFile as qw,rename as Yw,rm as ud,rmdir as dd,stat as Zw,writeFile as pd}from"fs/promises";import{devNull as Mr,tmpdir as Xw}from"os";import{dirname as id,join as he,resolve as Vi,sep as md}from"path";import{execFile as ow}from"child_process";import{accessSync as sw,constants as aw,statSync as cw}from"fs";import{lstat as ca,mkdir as na,readdir as lw,readFile as Yu,writeFile as uw}from"fs/promises";import{dirname as Ju,isAbsolute as dw,join as Yn,posix as pw,resolve as qu,sep as mw,win32 as fw}from"path";import{promisify as gw}from"util";import{unzipSync as ia,zipSync as Zu}from"fflate";import hw from"ignore";import{MANIFEST_FILE_NAME as Xu}from"@kizenapps/packager";var Fi=["claude","codex"],Ke={claude:{filesLabel:"Claude",skillsDir:".claude/skills",setupCommand:"appbuilder setup-claude",staleWarning:"Claude files managed by appbuilder are out of date; run appbuilder setup-claude"},codex:{filesLabel:"Codex",skillsDir:".agents/skills",setupCommand:"appbuilder setup-codex",staleWarning:"Codex files managed by appbuilder are out of date; run appbuilder setup-codex"}},ji=["kizen-custom-block","kizen-business-apps"],Wu=Fi.flatMap(e=>ji.map(t=>`${Ke[e].skillsDir}/${t}`)),rw={SKILLS_DIR:e=>e.skillsDir,SETUP_COMMAND:e=>e.setupCommand,STALE_WARNING:e=>e.staleWarning},iw=/^\{\{([#/])(claude|codex)\}\}$/;function Gu(e,t){let n=Ke[t],r=[],i;for(let o of e.split(`
|
|
135
|
+
`)){let s=iw.exec(o);if(s!==null){let[,a,c]=s;if(a==="#"&&i===void 0)i=c;else if(a==="/"&&i===c)i=void 0;else throw new Error(`Unbalanced skill template block: ${o}`);continue}(i===void 0||i===t)&&r.push(o)}if(i!==void 0)throw new Error(`Unclosed skill template block: {{#${i}}}`);return r.join(`
|
|
136
|
+
`).replace(/\{\{([^}]*)\}\}/g,(o,s)=>{let a=rw[s];if(a===void 0)throw new Error(`Unknown skill template token: ${o}`);return a(n)})}var yw=gw(ow),bw=new Set(["node_modules",".git",".kizenapp",".kizenappbuilder",".copilot-docs","__pycache__","dist"]),ww=new Set([".DS_Store",".env",".npmrc","credentials.json"]),la=".kizenignore",vw=new Set([...bw,...ww].map(e=>e.toLowerCase())),Qu=e=>{let t=e.toLowerCase().replace(/[. ]+$/,"");return vw.has(t)||t.startsWith(".env.")},ed=e=>e.toLowerCase().replace(/[. ]+$/,""),kw=Wu.map(e=>e.split("/").map(ed)),Aw=e=>{let t=e.replace(/\/$/,"").split("/").map(ed);return kw.some(n=>t.length>=n.length&&n.every((r,i)=>t[i]===r))},jr=e=>e.replace(/\/$/,"").split("/").some(Qu)||Aw(e),$r=new Date(1980,0,1,0,0,0),xw=15e3,Pw=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_NOSYSTEM","GIT_CEILING_DIRECTORIES","GIT_DISCOVERY_ACROSS_FILESYSTEM"]);function ua(e=process.env){return Object.fromEntries(Object.entries(e).filter(([t])=>!t.startsWith("GIT_")||Pw.has(t)))}var Cw=["--no-optional-locks","-c","core.fsmonitor=false","-c","core.hooksPath=/dev/null"],Sw=e=>{try{return cw(e).isFile()?(sw(e,aw.X_OK),!0):!1}catch{return!1}};function _w(e,{env:t,platform:n,isExecutable:r}){let i=n==="win32",o=i?fw:pw,s=c=>i?Object.entries(t).find(([l])=>l.toUpperCase()===c)?.[1]:t[c],a=i?(s("PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").filter(c=>c!==""):[""];for(let c of(s("PATH")??"").split(o.delimiter))if(!(c===""||!o.isAbsolute(c)))for(let l of a){let d=o.join(c,`${e}${l}`);if(r(d))return d}}var ra;function da(){if(ra??=_w("git",{env:process.env,platform:process.platform,isExecutable:Sw})??null,ra===null)throw Object.assign(new Error("git was not found on PATH"),{code:"ENOENT"});return ra}var pa=async(e,t)=>(await yw(da(),[...Cw,...e],{cwd:t,env:ua(),timeout:xw,maxBuffer:64*1024*1024,encoding:"utf8"})).stdout,Mi="so the source zip honors only the root .gitignore and .kizenignore.";function Ew(e){let t=e?.code;return t==="ENOENT"?`git isn't installed, ${Mi}`:t===128?`Not in a git work tree, ${Mi}`:`Couldn't list files with git (${xe(e)}), ${Mi}`}var Or=class extends Error{constructor(){super("The enclosing git repository ignores this folder, so none of its files can be picked for the source zip. Nothing was uploaded."),this.name="SourceZipIgnoredDirError"}},Dr=class extends Error{mode;constructor(t){super(`${Xu} isn't among the files picked for the source zip. Check that .gitignore${t==="git"?" (or a git exclude)":""} or .kizenignore doesn't exclude it.`),this.name="SourceZipMissingManifestError",this.mode=t}},oa=(e,t)=>e<t?-1:e>t?1:0,Lr=class extends Error{file;constructor(t,n){super(`${t} exists but couldn't be read (${xe(n)}), so the files it excludes can't be left out of the source zip. Nothing was uploaded; fix its permissions and try again.`,{cause:n}),this.name="SourceZipIgnoreUnreadableError",this.file=t}};async function Br(e,t){let n;try{n=await Yu(Yn(e,t),"utf-8")}catch(r){if(He(r,"ENOENT")||He(r,"ENOTDIR"))return;throw new Lr(t,r)}return hw().add(n)}async function Iw(e,t,n){let r=t.split("/");for(let i=1;i<r.length;i+=1)if(!await n(r.slice(0,i).join("/")))return!1;try{return(await ca(Yn(e,...r))).isFile()}catch{return!1}}function Tw(e){let t=new Map;return n=>{let r=t.get(n);return r===void 0&&(r=ca(Yn(e,...n.split("/"))).then(i=>i.isDirectory(),()=>!1),t.set(n,r)),r}}async function Nw(e,t){try{if((await t(["rev-parse","--is-inside-work-tree"],e)).trim()!=="true")return{notice:`Not in a git work tree, ${Mi}`};let r=await t(["ls-files","--cached","--others","--exclude-standard","-z"],e),i=[...new Set(r.split("\0"))].filter(Zn);if(i.length===0)return{ignored:!0};let o=Tw(e),s=await Promise.all(i.map(c=>Iw(e,c,o)));return{files:i.filter((c,l)=>s[l])}}catch(n){return{notice:Ew(n)}}}async function Rw(e,t){let n=[],r=async(i,o)=>{let s=await lw(i,{withFileTypes:!0});for(let a of s){let c=`${o}${a.name}`;a.isDirectory()?!Qu(a.name)&&t?.ignores(`${c}/`)!==!0&&await r(Yn(i,a.name),`${c}/`):a.isFile()&&t?.ignores(c)!==!0&&n.push(c)}};return await r(e,""),n}async function ma(e,t={}){let n=await Nw(e,t.git??pa);if("ignored"in n)throw new Or;let r=await Br(e,la),i="files"in n?{files:n.files,mode:"git"}:{files:await Rw(e,await Br(e,".gitignore")),mode:"walk",notice:n.notice};if(i.files=i.files.filter(o=>Zn(o)&&r?.ignores(o)!==!0&&!jr(o)).sort(oa),!i.files.includes(Xu))throw new Dr(i.mode);return i}var qn=class extends Error{constructor(t){super(t),this.name="SourceZipTooLargeError"}};async function $w(e,t,n){let r=0;for(let i of t){let{size:o}=await ca(Yn(e,...i.split("/")));if(o>n.entryBytes)throw new qn(`${i} is ${String(o)} bytes, over the ${String(n.entryBytes)}-byte limit for one file in an app's source. Exclude it with .kizenignore.`);if(r+=o,r>n.totalBytes)throw new qn(`The app's source is over the ${String(n.totalBytes)}-byte limit. Exclude large files with .kizenignore.`)}}async function td(e,t={}){let n=await ma(e,t);await $w(e,n.files,t.limits??{entryBytes:sa,totalBytes:aa});let r=await Promise.all(n.files.map(o=>Yu(Yn(e,...o.split("/"))))),i={};return n.files.forEach((o,s)=>{i[o]=[new Uint8Array(r[s]),{mtime:$r}]}),{...n,bytes:Zu(i,{level:6,mtime:$r})}}var Sn=class extends Error{entry;constructor(t,n="is unsafe"){super(`The source zip entry "${t}" ${n}; nothing was extracted.`),this.name="UnsafeZipEntryError",this.entry=t}},Fr=class extends Error{destination;constructor(t){super(`${t} already exists; the source zip is only extracted into a new directory.`),this.name="ZipDestinationExistsError",this.destination=t}};function Zn(e){let t=(e.endsWith("/")?e.slice(0,-1):e).split("/");return!(e===""||e.includes("\\")||e.includes("\0")||dw(e)||/^[A-Za-z]:/.test(e)||t.some(n=>n===""||n==="."||n===".."))}function Ow(e){if(!Zn(e))throw new Sn(e)}var Ui=e=>e.normalize("NFC").toLowerCase();function Dw(e){let t=new Map,n=new Map;for(let r of e){let i=r.endsWith("/"),o=Ui(i?r.slice(0,-1):r),s=o.split("/");if(t.has(o)||!i&&n.has(o))throw new Sn(r,"collides with another entry");(i?n:t).set(o,r);for(let a=1;a<s.length;a+=1)n.set(s.slice(0,a).join("/"),r)}for(let[r,i]of t)if(n.has(r))throw new Sn(i,"is a file where another entry needs a directory")}var sa=50*1024*1024,aa=200*1024*1024,Zt=class extends Error{entry;constructor(t,n){super(t),this.name="ZipLimitError",this.entry=n}},Jn=(e,t)=>(e[t]??0)|(e[t+1]??0)<<8,Rr=(e,t)=>(Jn(e,t)|Jn(e,t+2)<<16)>>>0;function Lw(e){let t=e.length-22;for(;t>=0&&Rr(e,t)!==101010256;)t-=1;if(t<0)throw new Zt("The source zip isn't a valid zip file; nothing was extracted.");if(t>=20&&Rr(e,t-20)===117853008)throw new Zt("The source zip uses ZIP64, which a source zip never needs; nothing was extracted.");let n=[],r=Rr(e,t+16);for(let i=Jn(e,t+8);i>0;i-=1){if(Rr(e,r)!==33639248)throw new Zt("The source zip isn't a valid zip file; nothing was extracted.");n.push(Rr(e,r+16)),r+=46+Jn(e,r+28)+Jn(e,r+30)+Jn(e,r+32)}return n}var Bw=Uint32Array.from({length:256},(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 Fw(e){let t=4294967295;for(let n of e)t=(Bw[(t^n)&255]??0)^t>>>8;return(t^4294967295)>>>0}function _n(e){let t=Lw(e),n=[];if(ia(e,{filter:u=>(n.push(u),!1)}),n.length!==t.length)throw new Zt("The source zip isn't a valid zip file; nothing was extracted.");let r=n.map(u=>u.name);r.forEach(Ow),Dw(r);let i=[],o=new Map,s=0;n.forEach((u,f)=>{if(!u.name.endsWith("/")){if(jr(u.name)){i.push(u.name);return}if(u.originalSize>sa)throw new Zt(`The source zip entry "${u.name}" expands to ${String(u.originalSize)} bytes, over the ${String(sa)}-byte limit; nothing was extracted.`,u.name);if(s+=u.originalSize,s>aa)throw new Zt(`The source zip expands to more than ${String(aa)} bytes; nothing was extracted.`);o.set(f,u)}});let a=0,c=ia(e,{filter:()=>o.has(a++)}),l=new Map;for(let[u,f]of o){let g=c[f.name];if(g?.length!==f.originalSize||Fw(g)!==t[u])throw new Sn(f.name,"doesn't match its recorded size or checksum");l.set(f.name,g)}let d=i.filter(u=>u!==zi).sort(oa);return{files:new Map([...l].sort(([u],[f])=>oa(u,f))),skipped:d}}var zi=".kizenapp/lineage.json",nd=1,jw=4096,Mw=e=>typeof e=="string"&&/^[1-9]\d*$/.test(e);function zw(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e,n=t.baseLiveVersion,r=t.baseSourcePackageId;return t.format!==nd?null:n===null&&r===null?{baseLiveVersion:null,baseSourcePackageId:null}:Mw(n)&&typeof r=="string"&&r!==""?{baseLiveVersion:n,baseSourcePackageId:r}:null}function fa(e){try{let t=-1,r=ia(e,{filter:i=>i.name!==zi||i.originalSize>jw?!1:(t=i.originalSize,!0)})[zi];return r?.length!==t?null:zw(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r)))}catch{return null}}function ga(e,t){let{files:n}=_n(e),r={};for(let[o,s]of n)r[o]=[s,{mtime:$r}];let i={format:nd,...t};return r[zi]=[new TextEncoder().encode(`${JSON.stringify(i,null,2)}
|
|
137
|
+
`),{mtime:$r}],Zu(r,{level:6,mtime:$r})}async function rd(e,t){let n=qu(t),{files:r,skipped:i}=_n(e),o=[];for(let[s,a]of r){let c=qu(n,...s.split("/"));if(!c.startsWith(n+mw))throw new Sn(s);o.push([s,c,a])}await na(Ju(n),{recursive:!0});try{await na(n)}catch(s){throw s.code==="EEXIST"?new Fr(t):s}for(let[,s,a]of o)await na(Ju(s),{recursive:!0}),await uw(s,a,{flag:"wx"});return{written:o.map(([s])=>s),skipped:i}}var It=class extends Error{step;constructor(t,n){super(`git ${t} failed while merging (${n}). Nothing was written.`),this.name="MergeGitError",this.step=t}},od=10,Hi=class extends Error{paths;constructor(t){let n=t.slice(0,od).join(", "),r=t.length-od;super(`The plugin folder changed after the merge was planned (${r>0?`${n} and ${String(r)} more`:n}). Nothing was written; run the merge again.`),this.name="MergeStaleError",this.paths=t}},ha=class extends Error{recoveryDir;constructor(t,n){super(`Applying the merge stopped partway (${xe(n)}). Files it removed are in ${he(t,"removed")}, and merged files it hadn't put in place yet are in ${he(t,"merged")}, each at its path in the plugin folder.`,{cause:n}),this.name="MergeApplyError",this.recoveryDir=t}},ya=class extends Error{path;constructor(t,n){super(`${t} ${n}, so the merge has nowhere safe to stage files. Nothing was written.`),this.name="MergeStagingError",this.path=t}},zr=class extends Error{path;constructor(t){super(`The merge plan includes "${t}", which isn't a writable source file. Nothing was written.`),this.name="UnsafeMergePathError",this.path=t}},Qw=[2,24],ev="git isn't installed or isn't on PATH.",tv=6e4,nv=1024*1024*1024,rv=[["user.name","appbuilder"],["user.email","appbuilder@localhost"],["commit.gpgSign","false"],["core.autocrlf","false"],["core.safecrlf","false"],["core.fsmonitor","false"],["core.hooksPath",Mr],["core.attributesFile",Mr],["core.excludesFile",Mr],["merge.conflictStyle","merge"],["merge.renormalize","false"],["core.precomposeUnicode","false"],["init.defaultBranch","main"],["rerere.enabled","false"],["gc.auto","0"],["maintenance.auto","false"],["color.ui","false"]].flatMap(([e,t])=>["-c",`${e}=${t}`]),iv=`* -text -eol -filter -ident -working-tree-encoding merge conflict-marker-size=7
|
|
138
|
+
`,ov="appbuilder <appbuilder@localhost> 0 +0000",ba=new TextEncoder,sv=e=>Vw("sha256").update(e).digest("hex"),av=e=>e.subarray(0,8e3).includes(0),Le=e=>e.split("/");function cv(){try{return da()}catch{return}}function lv(e,t){return{...ua(e),HOME:t,XDG_CONFIG_HOME:t,GIT_CONFIG_GLOBAL:Mr,GIT_CONFIG_SYSTEM:Mr,GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"}}function fd(e,t,n,r,i){return new Promise((o,s)=>{let a=Uw(e,[...rv,...t],{cwd:n,env:r,timeout:tv,maxBuffer:nv,encoding:"buffer",windowsHide:!0},(c,l,d)=>{let u=c===null?0:c.code;if(typeof u!="number"){s(c??new Error("git did not exit"));return}o({code:u,stdout:l,stderr:d.toString("utf8")})});a.stdin?.on("error",()=>{});for(let c of i??[])a.stdin?.write(c);a.stdin?.end()})}async function uv(e,t,n){let r;try{r=await fd(e,["--version"],n,t)}catch(l){return`git couldn't be run (${xe(l)}).`}let i=/git version (\d+)\.(\d+)/.exec(r.stdout.toString("utf8"));if(r.code!==0||i===null)return"git couldn't report its version.";let[o,s]=[Number(i[1]),Number(i[2])],[a,c]=Qw;if(o<a||o===a&&s<c)return`git ${String(o)}.${String(s)} is older than ${String(a)}.${String(c)}, which merging needs.`}function dv(e){let t='"';for(let n of e){let r=n.charCodeAt(0);n==='"'||n==="\\"?t+=`\\${n}`:r<32||r===127?t+=`\\${r.toString(8).padStart(3,"0")}`:t+=n}return`${t}"`}function pv(e,t,n){let r=[],i=a=>{r.push(ba.encode(a))},o=a=>{i(`data ${String(a.length)}
|
|
139
139
|
`),r.push(a),i(`
|
|
140
140
|
`)},s=(a,c,l,d)=>{i(`commit refs/heads/${a}
|
|
141
141
|
mark :${String(c)}
|
|
142
|
-
committer ${
|
|
143
|
-
`),o(
|
|
142
|
+
committer ${ov}
|
|
143
|
+
`),o(ba.encode(a)),d!==void 0&&i(`from :${String(d)}
|
|
144
144
|
deleteall
|
|
145
|
-
`);for(let[u,f]of l)i(`M 100644 inline ${
|
|
145
|
+
`);for(let[u,f]of l)i(`M 100644 inline ${dv(u)}
|
|
146
146
|
`),o(f)};return s("base",1,e),s("live",2,t,1),s("local",3,n,1),i(`done
|
|
147
|
-
`),r}var
|
|
148
|
-
`).join(""))])).stdout),f=new Set(l.filter(([,b])=>[...b.values()].some(y=>
|
|
149
|
-
`))}catch(d){if(d?.code===1)return new Set;let u=d?.stderr;throw new
|
|
150
|
-
`,{encoding:"utf8",flag:"wx"}),await _d(n)!==(t.fingerprint??null))throw new Ur;if(t.corrupt)try{await wd(n,`${n}${Ad}`)}catch(o){if(!tt(o))throw o}await wd(r,n)}catch(o){throw await Pv(r,{force:!0}).catch(()=>{}),o}}import{join as qi}from"path";var Nd="---\nname: kizen-business-apps\ndescription: Publish, preview, merge, roll back or pull this plugin as a Kizen Business App with `appbuilder app` (versions, push, publish, merge, rollback, pull, actions, preview). Use it when the user wants to release this plugin to their Kizen business, save, update or delete their preview, publish a new Live version, resolve a publish conflict or merge someone else's Live changes, restore an earlier release, download a released version's or their preview's source, or link the app's JS actions to objects.\n---\n\n# Kizen Business Apps\n\n`appbuilder app` publishes the plugin in this folder as a Business App on the business the user is signed in to. Publishing replaces Live for everyone in that business, so every write is a dry run first. Follow these rules exactly.\n\n## Before you start\n\n- Run every command from the plugin folder (the one with `kizen.json`), with `--json`.\n- If `appbuilder app` is an unknown command, the CLI is too old. Ask the user to upgrade `@kizenapps/cli` to 1.18.0 or later, then continue.\n- If a result's `warnings` contains `{{STALE_WARNING}}`, run `{{SETUP_COMMAND}}`, re-read `{{SKILLS_DIR}}/kizen-business-apps/SKILL.md`, and follow the new copy.\n- Never edit, delete or commit anything in `.kizenapp/`. `.kizenapp/apps.json` records what this folder is based on; push and merge depend on it. Your preview's base isn't in it: it lives only in the preview's source on the server (see \"Another machine or folder\"), so publishing works from any machine.\n- The server numbers releases with whole numbers (1, 2, 3\u2026) when you publish. They aren't semver, and they can skip numbers, so never predict one: the publish dry run's `nextReleaseAtLeast` is only a lower bound.\n- Business App releases don't publish release notes and don't use `kizen.json` `version` (it isn't sent), so for an app release don't bump `version` or create or edit files in `release_notes_directory`.\n\n## The contract\n\n- `--json` prints one JSON object on stdout. Human text goes to stderr. Parse stdout only.\n- Exit `0`: success, dry runs included. Exit `2`: a decision is needed (`needs_choice` or `base_required`); its `choices` say how to go on. Exit `1`: any other failure, `{ ok: false, code, message, hint? }`.\n- Every `argv` you get (`choices[].argv`, `next[].argv`, `applyArgv`, `login.argv`, and a JS action's `linkArgv`, `linkMenuArgv`, `linkNoMenuArgv` and `unlinkArgv`) is a whole command starting with `appbuilder`. Run it exactly as given. Never add, drop or reorder its flags, and never build these commands yourself. The only edit you may make to any argv is replacing an element that is exactly `<object>` (in `linkArgv`, `linkMenuArgv` and `linkNoMenuArgv`) with an object's api name or id. They carry the account the run used (`--env`, `--business`, `--user`, or its `-c`/`--profile`), so they act on the same business.\n- `push`, `publish`, `merge`, `rollback` and `preview delete` without `--yes` are dry runs: `{ ok: true, applied: false, dryRun: true, \u2026, applyArgv, requiresProductionConsent, next: [] }`. `applyArgv` is that command with `--yes` (and `--allow-production` on `go` or `fmo`). It is pinned to what the dry run showed: `publish` to the preview it reviewed (`--expect-preview <id>`), `merge` to the version it planned (`--release <n>`), `rollback` to its version, `preview delete` to the preview's owner (`--owner <userId>`, yours included) and the preview it reviewed (`--expect-updated <ts>`), with `--delete-app` only when it warned that the app goes too. A `push` apply uploads the folder as it is when the apply runs.\n- `requiresProductionConsent: true` means the target is production (`go` or `fmo`). Show the user the dry run and get their explicit go-ahead in this conversation before running `applyArgv`.\n- Applied results have `applied: true` and `next`: the commands to run next, in order, each `{ step, argv }`. After a merge with conflicts, `next` starts with `{ step: \"resolve\", files, markers }`.\n- An applied publish whose `warnings` say \"this folder's base wasn't advanced\" did publish, but this folder still counts as based on the old Live. The next publish from it stops with `publish_conflict`; run the merge it offers, then push and publish.\n\n## Workflow\n\n1. **Look.** `appbuilder app versions --json` returns `live`, `released`, `previews`, `yourPreview`, `base` and `next`. `published: false` means the app isn't on this business yet; the first push and publish create it.\n2. **Push your preview.** `appbuilder app push --json` is a dry run. Show the user `environment`, `businessId`, `app`, `source.files`, `base` and `warnings`. When they agree, run `applyArgv`. A push saves only the user's own preview; Live doesn't change.\n3. **Link its JS actions.** Read the applied push's `jsActions` and link every action that needs it, `unlinked` and `unknown` alike (see \"JS actions\" below), before you move on.\n4. **Publish.** Run the applied push's `next` step `publish` (`appbuilder app publish --json`), a dry run. Show the user `app`, `conflictCheck`, `nextReleaseAtLeast` and `warnings`. When they agree, run `applyArgv`. It's done when `applied` is `true`; tell the user the new `liveVersion`, then check its `jsActions` again.\n5. **Every change after that:** edit, push (dry run, then `applyArgv`), link new JS actions, publish (dry run, then `applyArgv`).\n\n### Live moved: `publish_conflict`\n\nSomeone published since your preview's base, and publishing now would overwrite their changes. Never answer with `--force`.\n\n1. Run `next[0].argv` (`appbuilder app merge \u2026`), a dry run. Show the user `written`, `deleted`, `conflicted` and any other lists, then run `applyArgv` when they agree. A merge changes only local files.\n2. If the applied merge's `next` starts with a `resolve` step, edit every file in its `files`. The side between `<<<<<<< HEAD` and `=======` is this folder's; the side between `=======` and `>>>>>>> live` is Live's (or the merged `--release`). Keep both sides' intended changes and delete the three marker lines. `appbuilder app push` refuses with `unresolved_conflicts` (listing `files`) until no markers are left.\n3. Then follow the rest of `next`: push (dry run, `applyArgv`), publish (dry run, `applyArgv`).\n\n### No recorded base: `base_required` (exit 2)\n\nThis happens when Live exists, the folder matches neither your preview nor a released version exactly (an exact match is detected and used automatically: `base.source` is `\"preview\"` or `\"detected\"`), and no usable base is recorded for it. That's the first push from a fresh clone, another machine or another developer's folder, or a push whose recorded base no longer applies (that version was deleted, or the app was deleted and created again; a notice in the `message` says which). Show the user the `message` and each choice's `label`:\n\n- \"Preview merging Live vN into this folder\" is a dry run. You may run it without asking. With no base to merge from, it always comes back with `kind: \"fallback\"`, whose `choices` are \"Merge, if this folder was copied from vM\" (`--base <M>`) for recent releases, and \"This folder already contains vN\".\n- \"This folder already contains Live vN\" records the base without merging (`--accept-live-base`). Run it only when the user confirms the folder really contains that version, or the next publish drops Live's changes.\n- \"This folder continues your preview (based on vN)\" (`appbuilder app push --base-from-preview <id>`) is a push dry run that gives this folder your preview's base. Never run it on your own judgment: ask the user whether this folder really is the work they pushed as that preview (for example, carried on from another machine). Run it only when they say yes; a wrong yes lets the next publish overwrite Live's changes. Then show its dry run and run its `applyArgv` as for any push. If the user isn't sure, use the merge preview instead.\n\nAfter the fallback, ask the user which release this folder was copied from:\n\n- They know it: run that release's `--base <M>` choice. It merges for real; continue as after any merge (resolve markers, push, publish). A wrong base drops the changes made since then, so never guess one.\n- They don't know: run the fallback's `applyArgv`. It extracts Live's source into `.kizenapp/live-v<N>-<time>/` (reported as `extracted.dir`) and changes nothing else. Help the user merge Live's changes into this folder by hand, then run the \"This folder already contains vN\" choice, and push.\n\n### Another machine or folder\n\nEvery push and rollback stores the preview's base inside the preview's source on the server, and publish reads it from there. So:\n\n- Publishing a preview the user pushed from another machine or folder needs no merge and no `--force`, unless Live moved since (then it's the usual `publish_conflict`).\n- A push from a folder with nothing recorded takes the preview's base by itself when the folder's files equal the preview's (`base.source: \"preview\"`); otherwise `base_required` offers \"This folder continues your preview\", which only the user may choose.\n- `conflict.reason: \"base_replaced\"` (a `publish_conflict`) means the version your preview was based on has been replaced on the business (the app was deleted and created again). Handle it like any `publish_conflict`: run `next[0].argv`, the merge dry run.\n- `conflict.reason: \"base_unknown\"` (a `publish_conflict`) means the preview's source doesn't say what it's based on. Run `next[0].argv`, a push dry run of this folder; with the user's go-ahead, its `applyArgv`, then publish again.\n- A preview pushed from this folder and published outside the CLI (in Kizen, say) is recognised: the folder's base becomes that Live version, with a notice; don't merge because of the old base.\n\n### Roll back and pull\n\n- `appbuilder app rollback <n> --json` restores released version n as the user's preview (dry run, then `applyArgv`). Its `next` is the publish dry run that makes it Live.\n- `appbuilder app pull <n> --json` downloads release n into a new folder, `../<api_name>-v<n>` or `--out <dir>`, and records n as that folder's base. It never writes into an existing folder and needs no `--yes`. Continue in the folder it reports as `dir`.\n- `appbuilder app pull --preview --json` does the same with the user's own preview, into `../<api_name>-preview` or `--out <dir>`. Pass `<n>` or `--preview`, never both. The result has `source: \"preview\"`, `preview` and `base` instead of `version`. `base.recorded: true` means the folder's base is the preview's base, so you can push and publish from it as usual; `false` (with a warning) means the preview doesn't say what it's based on, and the first push from the folder may stop with `base_required`. `no_preview` means the user has no preview to pull.\n\n### Delete a preview\n\nOnly when the user asks to delete a preview:\n\n1. Run `appbuilder app preview delete --json`, a dry run for the user's own preview. For another developer's preview, add `--owner <userId>` with the user id from `previews[].previewOwner.id` in `appbuilder app versions --json`, and only when the user explicitly named that developer's preview.\n2. Show the user `owner`, `preview` and every `warnings` entry. They say when the preview is the app's only version (deleting it deletes the whole app from the business, settings and secrets included), when it belongs to someone else, and when other users are using it.\n3. When the user agrees to every warning, run `applyArgv`. Never add `--delete-app` yourself; `applyArgv` carries it only when the dry run warned that the app goes too. A dry run with no `applyArgv` can't be applied: relay its `notices` to the user. The result has `status: \"deleted\"` and `appDeleted` (`true` when the app went with it). After deleting their own preview, its `next` is a push dry run, which makes a new preview.\n\n`preview_changed` means the preview was pushed again after the dry run, or deleting it would now delete the whole app when the dry run said it stays: nothing was deleted. Run `next[0].argv`, a new dry run, and show it to the user again.\n\n### JS actions: link them to objects\n\nA JS action template does nothing until it's linked to an object. Always create these links with the CLI, even though the app's setup assistant may have a step for it. `push`, `publish` and `versions` results carry `jsActions`: `{ status, liveVersion, actions, next }`; `appbuilder app actions list --json` returns the same `actions`. Each action is `{ apiName, name, hintObjectName, status, inLive, links, linkArgv, linkMenuArgv, linkNoMenuArgv }`:\n\n- `linked`: it has at least one link (`links[]`, each with the object's `objectName`, `includePerformAction` (the Perform Action menu setting) and `unlinkArgv`). Nothing to do.\n- `unlinked`: in Live (or the app isn't on the business yet) with no link. Link it.\n- `unknown`: only in a preview, so its links can't be listed, and it may not be linked yet. Link it right after the push, like an `unlinked` one.\n\nHow to link:\n\n1. Pick the object with the user. For an `unlinked` action with a hint object, `jsActions.next` has a `link` step naming `hintObjectName`: it only suggests that object. Confirm it with the user, or ask which object (no hint, an `unknown` action, or the user wants another one). Don't run the `link` step itself; step 2's argv makes the one dry run.\n2. Ask whether the action should show in the object's Perform Action menus. Take the action's `linkMenuArgv` if it should, and its `linkNoMenuArgv` if it shouldn't (for a link that exists, that turns the menu off); `linkArgv` leaves a new link off the menus and an existing one as it is. Replace the one element that is exactly `<object>` with the object's api name (like `client_client`) or id, change nothing else, and run it: a dry run of `appbuilder app actions link \u2026`. Contacts counts as an object. Exit 2 with `choice: \"object\"` means several objects match: show the user the `choices` and run the one they pick.\n3. Show the user the dry run (`environment`, `businessId`, `jsAction`, `object`, `change`, `includePerformAction`, `warnings`). When they agree, run `applyArgv`. `status` is `created`, `updated`, `up_to_date` or `already_linked` (the link already existed and its menu setting wasn't changed: for an action only in a preview, linked before while its links couldn't be listed; for an action in Live, linked after this command listed the links, in which case run `appbuilder app actions list` and link it again to set the menu setting the user wants).\n4. Review with `appbuilder app actions list --json`: every action with its `status`, `links` and argvs, and link dry runs in `next`. It lists the links of Live's actions only; a preview-only action stays `unknown` until it's published.\n\nIf a link of an `unknown` action fails with `api_error` and a `hint` saying Kizen couldn't find it, that Kizen environment can only link actions in Live. Relay the hint: publish first, then link it.\n\nA link change to an action in Live (`inLive: true`), whether a new link, a menu setting or an unlink, reaches everyone using Live as soon as it's applied; its dry run's `warnings` say so. Treat it like a publish: confirm the object and the menu setting with the user before running its `applyArgv`.\n\nRemove a link only when the user asks: run that link's `unlinkArgv` (`appbuilder app actions unlink \u2026`, a dry run), then its `applyArgv` when they agree.\n\n### What a push uploads\n\nGit's file list (tracked files, plus untracked ones `.gitignore` doesn't exclude; outside git, everything minus the root `.gitignore`), minus the root `.kizenignore` (gitignore syntax; it can only exclude more). These are never uploaded, whatever either file says: `node_modules`, `.git`, `.kizenapp`, `.kizenappbuilder`, `.copilot-docs`, `__pycache__`, `dist`, `.DS_Store`, `.env`, `.env.*`, `.npmrc`, `credentials.json`, and the skill folders appbuilder manages (`kizen-custom-block` and `kizen-business-apps` under `.claude/skills/` and `.agents/skills/`). Other skills in those folders are uploaded like any file. Check `source.files` in the dry run, and suggest a `.kizenignore` entry for anything that shouldn't ship. A release needs a thumbnail.\n\n## Failures\n\n| `code` | What to do |\n| --- | --- |\n| `not_signed_in` | Ask the user to sign in by running `login.argv` themselves: it opens a browser (see Sandboxes). Then run your command again. |\n| `needs_choice` | `choice` is `environment`: the user is signed in to several. Ask which, then run that choice's `argv`. |\n| `base_required` | See \"No recorded base\" above. |\n| `publish_conflict` | Run `next[0].argv`: a merge dry run; a push dry run when `conflict.reason` is `base_unknown`; or, when your preview changed since the dry run, a new publish dry run. |\n| `unresolved_conflicts` | Resolve the markers in `files`, then push again. |\n| `no_preview` | Push first. For `pull --preview`, the user has no preview: tell them, or pull a release instead. |\n| `preview_changed` | Nothing was deleted. Run `next[0].argv`, a new `preview delete` dry run, and show it to the user before going on. |\n| `preview_incomplete` | Push again, then publish (or pull). |\n| `thumbnail_required` | Add a thumbnail to the plugin, push, then publish. |\n| `source_invalid` | The folder can't be zipped (no `kizen.json`, an unreadable `.kizenignore`, a folder git ignores, or a file over 50 MiB or 200 MiB in all). Fix what `message` says, for example with a `.kizenignore` entry. |\n| `validation_failed` | Fix every item in `issues`, then run the command again. |\n| `forbidden` | Tell the user they need the Marketplace \u203A Business App Developer permission at the Delete/All level. Don't retry. |\n| `production_requires_flag` | You ran a write against `go` or `fmo` without `--allow-production`. Run the dry run, get consent, then its `applyArgv`. |\n| `credentials_invalid` | The API-key file from `-c` or `--profile` is bad. Tell the user what `message` says. Use API keys only when the user asks. |\n| `auth_failed` | Kizen refused the session. Ask the user to sign in again (`appbuilder login`, with `--env <env>` for an environment other than `go`). |\n| `session_store_unwritable`, `network_error` | Usually a sandbox; see below. Otherwise relay `message` and `hint`. |\n| `not_found`, `usage_error`, `api_error`, `local_error` | Relay `message` to the user. |\n\n## Sandboxes\n\n`appbuilder` needs the network and write access to `~/.kizenappbuilder`, where it keeps the sign-in session and refreshes its tokens. It talks to the Kizen environment's hosts, and `push` uploads go to whichever file-storage host Kizen names for each upload.\n\n{{#codex}}\n- Codex's sandbox turns the network off and allows writes only to the workspace and `/tmp`. Run `appbuilder` commands with `sandbox_permissions: \"require_escalated\"`, and suggest `prefix_rule: [\"appbuilder\"]` so the user approves `appbuilder` once. A `network_error` with `sandbox: \"codex_network_disabled\"`, or a `session_store_unwritable`, means it ran without that.\n- `.agents/` is read-only in the sandbox, so `appbuilder setup-codex` needs the escalation too.\n- `appbuilder app pull` writes next to the plugin folder by default, outside the workspace. Escalate it, or pass an `--out <dir>` inside the workspace that `.gitignore` or `.kizenignore` excludes.\n- `not_signed_in`: the user runs `login.argv` in their own terminal. It opens a browser and waits for the sign-in.\n{{/codex}}\n{{#claude}}\n- Claude Code's sandbox, when enabled, allows writes only to the working directory and the network only to allowed domains. Because uploads go to a storage host Kizen picks, a domain list can't cover `appbuilder`. If it fails with `session_store_unwritable` or a `network_error`, ask the user to add `\"appbuilder *\"` to `sandbox.excludedCommands` in their user settings (`~/.claude/settings.json`), so `appbuilder` runs outside the sandbox. Project settings don't work for this when Claude Code runs in strict mode.\n- `not_signed_in`: the user types `! ` followed by the `login.argv` command in this session, or runs it in their own terminal. It opens a browser and waits for the sign-in.\n{{/claude}}\n\n## Guardrails\n\n- Never pass `--force`, `--allow-production` or `--accept-live-base`, or run a choice whose `argv` contains one, unless the user explicitly asked for it in this conversation.\n- Always show the user a dry run before you run its `applyArgv`.\n- On exit 2, show the user the `choices` and run the one they pick. The merge preview is the only choice you may run without asking. Never pick \"This folder continues your preview\" for the user.\n- Never edit `.kizenapp/`.\n- Publish only when the user asked to publish.\n- Link a JS action only to an object the user confirmed, and unlink only when the user asked.\n- Delete a preview only when the user asked, and another developer's (`--owner`) only when the user named it.\n";var Rd="---\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 `{{SETUP_COMMAND}} --include-lib` in the plugin directory.\n\n- If it reports `updated` for `{{SKILLS_DIR}}/kizen-custom-block/SKILL.md`, your loaded copy of this skill is stale. Re-read `{{SKILLS_DIR}}/kizen-custom-block/SKILL.md` before doing anything else, and follow the new copy.\n- If it reports `created` for any file in this skill directory, or `updated` for `{{SKILLS_DIR}}/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{{#codex}}\n- In the Codex sandbox `.agents/` is read-only, so run it with `sandbox_permissions: \"require_escalated\"`.\n{{/codex}}\n\n`{{SETUP_COMMAND}}` 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_COMMAND}}` 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 `appbuilder 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\nWith `--json` (`block targets` and `block push`), stdout is one JSON object and human text goes to stderr. Exit `0` is success (dry runs included), exit `2` means a decision is needed (`needs_choice`), and exit `1` is any other failure. Every `argv` a result gives you (`applyArgv`, `choices[].argv`, `login.argv`) is a whole command starting with `appbuilder`: run it exactly as given, without adding, dropping or reordering flags.\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 dry run's `applyArgv` exactly. It is the same push with `--yes`, pinned to the dashboard and dashlet the dry run showed. If `requiresProductionConsent` is `true` (the target is `go` or `fmo`), it also carries `--allow-production`: run it only after the user explicitly agreed to publish to production in this conversation. 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, applyArgv, requiresProductionConsent }`.\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 `{{STALE_WARNING}}`, run `{{SETUP_COMMAND}} --include-lib`, re-read `{{SKILLS_DIR}}/kizen-custom-block/SKILL.md`, then continue.\n- Error: `{ ok: false, code, message, hint?, choice?, choices?, login?, sandbox? }`. `code` is one of `needs_choice`, `validation_failed`, `invalid_block`, `not_signed_in`, `auth_failed`, `forbidden`, `remembered_target_missing`, `drift_detected`, `network_error`, `session_store_unwritable`, `credentials_invalid`, `production_requires_flag`, `not_found`, `usage_error`, `api_error` or `local_error`. When `hint` is present, follow it.\n\n### `needs_choice`\n\n`choice` is `'environment'`, `'block'`, `'dashboard'` or `'target'`. `choices` is a list of `{ value, label, argv, args, surface?, canEdit?, pushKey?, isFromThisPlugin? }`. Ask the user using each option's `label`, then run the chosen option's `argv` exactly as given: it is the push with that choice, as a dry run, so continue from its result (show it, then run its `applyArgv`). Ignore `args`, and never construct these flags by hand.\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 `not_signed_in`, ask the user to sign in by running the `login.argv` command themselves (it opens a browser), then run your command again.\n{{#claude}}\n In Claude Code they can type `! ` followed by that command in this session.\n{{/claude}}\n- On `credentials_invalid`, the API-key file from `-c` or `--profile` is bad. Tell the user to fix the file named in `message`. Don't run `--profile` or `-c` unless the user asks for an API key.\n- On `session_store_unwritable`, or a `network_error` with `sandbox: \"codex_network_disabled\"`, a sandbox is blocking `appbuilder`, which needs the network and write access to `~/.kizenappbuilder`.\n{{#codex}}\n Re-run the command with `sandbox_permissions: \"require_escalated\"`, and suggest `prefix_rule: [\"appbuilder\"]`.\n{{/codex}}\n{{#claude}}\n Ask the user to add `\"appbuilder *\"` to `sandbox.excludedCommands` in their user settings (`~/.claude/settings.json`), so `appbuilder` runs outside the sandbox. Project settings don't work for this when Claude Code runs in strict mode.\n{{/claude}}\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 $d=`# Designing a Kizen custom block
|
|
147
|
+
`),r}var gd=e=>e.toString("utf8").split("\0").filter(t=>t!=="");function mv(e){let t=new Map;for(let n of gd(e)){let r=n.indexOf(" "),[,i,o]=n.slice(0,r).split(" "),s=n.slice(r+1),a=t.get(s)??new Map;a.set(Number(o),i??""),t.set(s,a)}return t}function fv(e){let t=new Map,n=0;for(;n<e.length;){let r=e.indexOf(10,n),[i="",,o]=e.subarray(n,r).toString("utf8").split(" ");if(o===void 0)throw new It("cat-file",`missing object ${i}`);let s=r+1,a=s+Number(o);t.set(i,e.subarray(s,a)),n=a+1}return t}async function gv(e,t,n,r){await Qt(n);let i=async(b,y,C)=>{let S;try{S=await fd(e,y,n,t,C)}catch(x){throw new It(b,xe(x))}if(S.code!==0&&!(b==="merge"&&S.code===1))throw new It(b,S.stderr.trim()||`exit ${String(S.code)}`);return S};await i("init",["init","-q","--template=","."]),await Qt(he(n,".git","info"),{recursive:!0}),await pd(he(n,".git","info","attributes"),iv),await i("fast-import",["fast-import","--quiet","--done"],pv(r.base,r.live,r.local));let o=(await i("rev-parse",["rev-parse","--verify","local^{tree}"])).stdout.toString("utf8").trim();await i("checkout",["checkout","-q","local","--"]);let s=await i("merge",["merge","--no-ff","--no-edit","--no-verify","-q","live"]),a=mv((await i("ls-files",["ls-files","-u","-z"])).stdout),c=a.size>0;if(s.code===1!==c)throw new It("merge",s.stderr.trim()||`exit ${String(s.code)}`);let l=[...a].filter(([,b])=>b.has(2)&&b.has(3)),d=[...new Set(l.flatMap(([,b])=>[...b.values()]))],u=d.length===0?new Map:fv((await i("cat-file",["cat-file","--batch"],[ba.encode(d.map(b=>`${b}
|
|
148
|
+
`).join(""))])).stdout),f=new Set(l.filter(([,b])=>[...b.values()].some(y=>av(u.get(y)??new Uint8Array))).map(([b])=>b));await i("add",["add","-A","-f"]);let g=(await i("write-tree",["write-tree"])).stdout.toString("utf8").trim(),p=gd((await i("diff-tree",["diff-tree","-r","-z","--no-renames","--no-ext-diff","--no-textconv","--name-status",o,g])).stdout),m=[];for(let b=0;b+1<p.length;b+=2)m.push({status:p[b]??"",path:p[b+1]??""});let h=new Map;for(let{status:b,path:y}of m){if(!Zn(y))throw new It("merge",`unexpected path "${y}"`);b!=="D"&&h.set(y,await qw(he(n,...Le(y))))}return{changes:m,contents:h,unmerged:a,binary:f}}var hv=ld.O_NOFOLLOW??0;async function yv(e){let t=await Gw(e,ld.O_RDONLY|hv);try{return new Uint8Array(await t.readFile())}finally{await t.close()}}async function hd(e,t){let n=await ma(e,t===void 0?{}:{git:t}),r=await Promise.all(n.files.map(l=>yv(he(e,...Le(l))))),i=n.files.map(l=>l.normalize("NFC")),o=new Set(i).size===i.length?i:n.files,s=new Map,a=new Map,c=new Map;return n.files.forEach((l,d)=>{let u=o[d]??l,f=r[d]??new Uint8Array;s.set(u,f),a.set(u,sv(f)),c.set(u,l)}),{files:s,hashes:a,diskPaths:c,mode:n.mode}}var sd=e=>new Map([...e].map(([t,n])=>[t.normalize("NFC"),n]));async function bv(e,t){let n=Le(t);for(let r=1;r<=n.length;r+=1){let i=await _e(En(he(e,...n.slice(0,r))));if(i===void 0)return"absent";if(r===n.length)return i.isFile()?"file":"blocked";if(!i.isDirectory())return"blocked"}return"blocked"}var wa=e=>e.isFile()&&e.nlink===1n?`${String(e.dev)}:${String(e.ino)}`:void 0;async function yd(e,t){let n=new Set;for(let r of t){let i=await _e(En(he(e,...Le(r)),{bigint:!0})),o=i===void 0?void 0:wa(i);o!==void 0&&n.add(o)}return n}async function bd(e,t){let n=await Jw(e);if(n.length===0)return!1;for(let r of n){let i=he(e,r),o=await En(i,{bigint:!0});if(!(o.isDirectory()?await bd(i,t):t.has(wa(o)??"")))return!1}return!0}async function wd(e,t,n){let r=Le(t);for(let i=1;i<=r.length;i+=1){let o=he(e,...r.slice(0,i)),s=await _e(En(o,{bigint:!0}));if(s===void 0)return"absent";if(s.isFile())return n.has(wa(s)??"")?"absent":"blocked";if(!s.isDirectory())return"blocked";if(i===r.length)return await bd(o,n)?"absent":"blocked"}return"blocked"}async function wv(e,t,n,r){let i=new Set;if(t.length===0)return i;let o=[await Br(e,la),n==="walk"?await Br(e,".gitignore"):void 0];for(let s of t)o.some(a=>a?.ignores(s)===!0)&&i.add(s);if(n==="git"){let s=l=>/["\\\p{Cc}]/u.test(l),a=async l=>{try{let d=await r(["-c","core.quotePath=false","check-ignore","--",...l.map(u=>`./${u}`)],e);return new Set(d.split(`
|
|
149
|
+
`))}catch(d){if(d?.code===1)return new Set;let u=d?.stderr;throw new It("check-ignore",typeof u=="string"&&u.trim()!==""?u.trim():xe(d))}},c=t.filter(l=>!s(l));for(let l=0;l<c.length;l+=100){let d=c.slice(l,l+100),u=await a(d);d.filter(f=>u.has(`./${f}`)).forEach(f=>i.add(f))}for(let l of t.filter(s))(await a([l])).size>0&&i.add(l)}return i}var Xt=e=>[...e].sort();function ad(e,t){let[n,r]=[Ui(e),Ui(t)];return n===r||n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}async function vv(e,t,n,r){let i=b=>t.diskPaths.get(b)??b;for(let{path:b}of n.changes)if(jr(b))throw new It("merge",`unexpected path "${b}"`);let o=new Set(n.changes.filter(({status:b,path:y})=>b==="D"&&t.files.has(y)).map(({path:b})=>b)),s=await yd(e,[...o].map(i)),a=new Set,c=new Set,l=[];for(let{status:b,path:y}of n.changes)b!=="D"&&(t.files.has(y)?a.add(y):await wd(e,y,s)==="absent"?l.push(y):c.add(y));let d=await wv(e,l,t.mode,r);for(let b of l)(d.has(b)?c:a).add(b);let u=new Set,f=[],g=[],p=[];for(let[b,y]of n.unmerged)n.binary.has(b)?p.push(b):c.has(b)||(u.add(b),y.has(1)&&y.has(2)&&!y.has(3)?f.push(b):y.has(1)&&y.has(3)&&!y.has(2)&&g.push(b));let m=[...o].filter(b=>[...c].some(y=>ad(y,b)));for(let b of m)o.delete(b),u.add(b);for(let b of[...c,...a])!t.files.has(b)&&m.some(y=>ad(b,y))&&(c.delete(b),a.delete(b),u.add(b));let h=new Map;for(let b of a)h.set(b,n.contents.get(b)??new Uint8Array);return{written:Xt(a),deleted:Xt(o),conflicted:Xt(u),deletedOnLive:Xt(f),deletedLocally:Xt(g),binaryConflicts:Xt(p),ignoredIncoming:Xt(c),contents:h}}async function vd(e,t={}){if(e.base===null)return{status:"no_base"};let n=(t.findGit??cv)();if(n===void 0)return{status:"git_unavailable",reason:ev};let r=Vi(e.pluginDir),i=Vi(t.tmpDir??Xw());if(i===r||i.startsWith(r+md))throw new Error("The merge workspace must not be inside the plugin folder.");let o=await Ww(he(i,"appbuilder-merge-"));try{let s=he(o,"home");await Qt(s);let a=lv(t.env??process.env,s),c=await uv(n,a,o);if(c!==void 0)return{status:"git_unavailable",reason:c};let l=sd(_n(e.base.zip).files),d=sd(_n(e.live.zip).files),u=await hd(r,t.git),f=await gv(n,a,he(o,"repo"),{base:l,live:d,local:u.files}),g=await vv(r,u,f,t.git??pa);return g.written.length===0&&g.deleted.length===0&&g.conflicted.length===0&&g.binaryConflicts.length===0?{status:"up_to_date",ignoredIncoming:g.ignoredIncoming}:{status:"ready",pluginDir:r,baseVersion:e.base.version,liveVersion:e.live.version,...g,localHashes:u.hashes}}finally{await ud(o,{recursive:!0,force:!0})}}function cd(e,t){let n=Vi(e,...Le(t));if(!Zn(t)||jr(t)||!n.startsWith(e+md))throw new zr(t)}async function kv(e,t){let n=Le(t);for(let r=1;r<n.length;r+=1){let i=he(e,...n.slice(0,r));try{await Qt(i)}catch(o){if(o.code!=="EEXIST"||!(await En(i)).isDirectory())throw o}}}async function Av(e,t){let n=new Set;for(let i of t){let o=Le(i);for(let s=1;s<o.length;s+=1)n.add(o.slice(0,s).join("/"))}let r=[...n].sort((i,o)=>Le(o).length-Le(i).length);for(let i of r)await dd(he(e,...Le(i))).catch(()=>{})}var xv=".kizenapp",Pv=(e,t)=>t?Zw(e,{bigint:!0}):En(e,{bigint:!0});async function Cv(e,t){let n=he(e,xv),r=!1;try{await Qt(n),r=!0}catch(l){if(l.code!=="EEXIST")throw l}let i=async()=>{r&&await dd(n).catch(()=>{})},[o,s]=await Promise.all([t(n,!1),t(e,!0)]),a=o.isDirectory()?o.dev!==s.dev?"is on a different disk than the plugin folder":void 0:"isn't a real folder";if(a!==void 0)throw await i(),new ya(n,a);let c=he(n,`merge-${Hw()}`);return await Qt(c),{staging:c,cleanUp:async()=>{await ud(c,{recursive:!0,force:!0}),await i()}}}async function kd(e,t={}){if(e.status!=="ready")return e;let n=Vi(e.pluginDir);for(let g of e.written){if(!e.contents.has(g))throw new zr(g);cd(n,g)}for(let g of e.deleted){if(!e.localHashes.has(g))throw new zr(g);cd(n,g)}let r=await hd(n,t.git),i=Xt(new Set([...e.localHashes.keys(),...r.hashes.keys()].filter(g=>e.localHashes.get(g)!==r.hashes.get(g))));if(i.length>0)throw new Hi(i);let o=g=>r.diskPaths.get(g)??g,s=await yd(n,e.deleted.map(o)),a=[];for(let g of[...e.written,...e.deleted])(e.localHashes.has(g)?await bv(n,o(g))==="file":await wd(n,g,s)==="absent")||a.push(g);if(a.length>0)throw new Hi(a);let{staging:c,cleanUp:l}=await Cv(n,t.stat??Pv),d=[];try{for(let g of e.written){let p=he(n,...Le(o(g))),m=he(c,"merged",...Le(o(g)));await Qt(id(m),{recursive:!0}),await pd(m,e.contents.get(g)??new Uint8Array,{flag:"wx"}),e.localHashes.has(g)&&await Kw(m,(await En(p)).mode&4095),d.push({path:o(g),source:m,target:p})}}catch(g){throw await l(),g}if(t.isAborted?.()===!0)return await l(),{status:"cancelled"};let u=t.rename??Yw;try{for(let g of e.deleted.map(o)){let p=he(c,"removed",...Le(g));await Qt(id(p),{recursive:!0}),await u(he(n,...Le(g)),p)}await Av(n,e.deleted.map(o));for(let{path:g,source:p,target:m}of d)await kv(n,g),await u(p,m)}catch(g){throw new ha(c,g)}await l();let f={written:e.written,deleted:e.deleted,ignoredIncoming:e.ignoredIncoming};return e.conflicted.length===0&&e.binaryConflicts.length===0?{status:"merged",...f}:{status:"conflicts",...f,conflicted:e.conflicted,deletedOnLive:e.deletedOnLive,deletedLocally:e.deletedLocally,binaryConflicts:e.binaryConflicts}}import{randomUUID as Sv}from"crypto";import{mkdir as _v,readFile as Ev,rename as Ad,rm as Iv,stat as Tv,writeFile as Nv}from"fs/promises";import{dirname as Rv,join as Pd}from"path";var In=".kizenapp/apps.json",Cd=".corrupt",Ur=class extends Error{constructor(){super(`${In} changed while this command ran, so it wasn't written.`),this.name="AppStateChangedError"}},va=class extends Error{constructor(){super(`${In} exists but couldn't be read, so it wasn't overwritten. Fix its permissions and run the command again.`),this.name="AppStateUnreadableError"}},Vr=()=>({rest:{},entries:[],corrupt:!1,fingerprint:null}),Sd=["environment","businessId","baseApiName","userId"],_d=e=>e===null||typeof e=="string",$v=e=>e===void 0||_d(e),Ed=(e,t)=>F(e)&&Sd.every(n=>e[n]===t[n]);function Id(e){return F(e)&&Sd.every(t=>typeof e[t]=="string"&&e[t]!=="")&&$v(e.folderBaseLiveVersion)&&(typeof e.folderBaseLiveVersion=="string"?typeof e.folderBaseSourcePackageId=="string"&&e.folderBaseSourcePackageId!=="":e.folderBaseSourcePackageId===void 0)&&(e.previewSourcePackageId===void 0||typeof e.previewSourcePackageId=="string")&&_d(e.lastPushedSourceHash)&&(e.previewRestoredFrom===void 0||typeof e.previewRestoredFrom=="string")&&(e.conflictedPaths===void 0||Array.isArray(e.conflictedPaths)&&e.conflictedPaths.every(t=>typeof t=="string"))}async function Td(e){try{let t=await Tv(e,{bigint:!0});return`${String(t.ino)}:${String(t.size)}:${String(t.mtimeNs)}`}catch(t){if(tt(t))return null;throw t}}var xd=(e,t)=>({doc:{...Vr(),corrupt:!0,fingerprint:t},notice:`${In} ${e}, so it was ignored. It will be moved to ${In}${Cd} on the next write.`});async function Nd(e){let t=Pd(e,In),n,r;try{n=await Td(t),r=await Ev(t,"utf8")}catch(c){return tt(c)?{doc:Vr()}:{doc:{...Vr(),unreadable:!0},notice:`Couldn't read ${In} (${ke(c)}), so it was ignored and won't be written.`}}let i;try{i=JSON.parse(r)}catch{return xd("is not valid JSON",n)}if(!F(i)||i.apps!==void 0&&!Array.isArray(i.apps))return xd("is not in the expected format",n);let{apps:o,...s}=i,a=Array.isArray(o)?[...o]:[];return{doc:{rest:s,entries:a,corrupt:!1,fingerprint:n}}}function ka(e,t){let r=e.entries.filter(i=>Ed(i,t)).at(-1);return r===void 0?{status:"missing"}:Id(r)?{status:"found",entry:r}:{status:"malformed"}}var Ov=["environment","businessId","baseApiName"];function Rd(e,t,n){let r=e.entries.map(i=>{if(!F(i)||!Ov.every(s=>i[s]===t[s])||!Id(i))return i;let o=n(i);return JSON.stringify(o)===JSON.stringify(i)?i:o});return r.some((i,o)=>i!==e.entries[o])?{...e,entries:r}:null}function Aa(e,t){return{...e,entries:[...e.entries.filter(n=>!Ed(n,t)),t]}}async function $d(e,t){if(t.unreadable===!0)throw new va;let n=Pd(e,In),r=`${n}.${Sv()}.tmp`;await _v(Rv(n),{recursive:!0});let i={...t.rest,apps:t.entries};try{if(await Nv(r,`${JSON.stringify(i,null,2)}
|
|
150
|
+
`,{encoding:"utf8",flag:"wx"}),await Td(n)!==(t.fingerprint??null))throw new Ur;if(t.corrupt)try{await Ad(n,`${n}${Cd}`)}catch(o){if(!tt(o))throw o}await Ad(r,n)}catch(o){throw await Iv(r,{force:!0}).catch(()=>{}),o}}import{join as qi}from"path";var Od="---\nname: kizen-business-apps\ndescription: Publish, preview, merge, roll back or pull this plugin as a Kizen Business App with `appbuilder app` (versions, push, publish, merge, rollback, pull, actions, preview). Use it when the user wants to release this plugin to their Kizen business, save, update or delete their preview, publish a new Live version, resolve a publish conflict or merge someone else's Live changes, restore an earlier release, download a released version's or their preview's source, or link the app's JS actions to objects.\n---\n\n# Kizen Business Apps\n\n`appbuilder app` publishes the plugin in this folder as a Business App on the business the user is signed in to. Publishing replaces Live for everyone in that business, so every write is a dry run first. Follow these rules exactly.\n\n## Before you start\n\n- Run every command from the plugin folder (the one with `kizen.json`), with `--json`.\n- If `appbuilder app` is an unknown command, the CLI is too old. Ask the user to upgrade `@kizenapps/cli` to 1.18.0 or later, then continue.\n- If a result's `warnings` contains `{{STALE_WARNING}}`, run `{{SETUP_COMMAND}}`, re-read `{{SKILLS_DIR}}/kizen-business-apps/SKILL.md`, and follow the new copy.\n- Never edit, delete or commit anything in `.kizenapp/`. `.kizenapp/apps.json` records what this folder is based on; push and merge depend on it. Your preview's base isn't in it: it lives only in the preview's source on the server (see \"Another machine or folder\"), so publishing works from any machine.\n- The server numbers releases with whole numbers (1, 2, 3\u2026) when you publish. They aren't semver, and they can skip numbers, so never predict one: the publish dry run's `nextReleaseAtLeast` is only a lower bound.\n- Business App releases don't publish release notes and don't use `kizen.json` `version` (it isn't sent), so for an app release don't bump `version` or create or edit files in `release_notes_directory`.\n\n## The contract\n\n- `--json` prints one JSON object on stdout. Human text goes to stderr. Parse stdout only.\n- Exit `0`: success, dry runs included. Exit `2`: a decision is needed (`needs_choice` or `base_required`); its `choices` say how to go on. Exit `1`: any other failure, `{ ok: false, code, message, hint? }`.\n- Every `argv` you get (`choices[].argv`, `next[].argv`, `applyArgv`, `login.argv`, and a JS action's `linkArgv`, `linkMenuArgv`, `linkNoMenuArgv` and `unlinkArgv`) is a whole command starting with `appbuilder`. Run it exactly as given. Never add, drop or reorder its flags, and never build these commands yourself. The only edit you may make to any argv is replacing an element that is exactly `<object>` (in `linkArgv`, `linkMenuArgv` and `linkNoMenuArgv`) with an object's api name or id. They carry the account the run used (`--env`, `--business`, `--user`, or its `-c`/`--profile`), so they act on the same business.\n- `push`, `publish`, `merge`, `rollback` and `preview delete` without `--yes` are dry runs: `{ ok: true, applied: false, dryRun: true, \u2026, applyArgv, requiresProductionConsent, next: [] }`. `applyArgv` is that command with `--yes` (and `--allow-production` on `go` or `fmo`). It is pinned to what the dry run showed: `publish` to the preview it reviewed (`--expect-preview <id>`), `merge` to the version it planned (`--release <n>`), `rollback` to its version, `preview delete` to the preview's owner (`--owner <userId>`, yours included) and the preview it reviewed (`--expect-updated <ts>`), with `--delete-app` only when it warned that the app goes too. A `push` apply uploads the folder as it is when the apply runs.\n- `requiresProductionConsent: true` means the target is production (`go` or `fmo`). Show the user the dry run and get their explicit go-ahead in this conversation before running `applyArgv`.\n- Applied results have `applied: true` and `next`: the commands to run next, in order, each `{ step, argv }`. After a merge with conflicts, `next` starts with `{ step: \"resolve\", files, markers }`.\n- An applied publish whose `warnings` say \"this folder's base wasn't advanced\" did publish, but this folder still counts as based on the old Live. The next publish from it stops with `publish_conflict`; run the merge it offers, then push and publish.\n\n## Workflow\n\n1. **Look.** `appbuilder app versions --json` returns `live`, `released`, `previews`, `yourPreview`, `base` and `next`. `published: false` means the app isn't on this business yet; the first push and publish create it.\n2. **Push your preview.** `appbuilder app push --json` is a dry run. Show the user `environment`, `businessId`, `app`, `source.files`, `base` and `warnings`. When they agree, run `applyArgv`. A push saves only the user's own preview; Live doesn't change.\n3. **Link its JS actions.** Read the applied push's `jsActions` and link every action that needs it, `unlinked` and `unknown` alike (see \"JS actions\" below), before you move on.\n4. **Publish.** Run the applied push's `next` step `publish` (`appbuilder app publish --json`), a dry run. Show the user `app`, `conflictCheck`, `nextReleaseAtLeast` and `warnings`. When they agree, run `applyArgv`. It's done when `applied` is `true`; tell the user the new `liveVersion`, then check its `jsActions` again.\n5. **Every change after that:** edit, push (dry run, then `applyArgv`), link new JS actions, publish (dry run, then `applyArgv`).\n\n### Live moved: `publish_conflict`\n\nSomeone published since your preview's base, and publishing now would overwrite their changes. Never answer with `--force`.\n\n1. Run `next[0].argv` (`appbuilder app merge \u2026`), a dry run. Show the user `written`, `deleted`, `conflicted` and any other lists, then run `applyArgv` when they agree. A merge changes only local files.\n2. If the applied merge's `next` starts with a `resolve` step, edit every file in its `files`. The side between `<<<<<<< HEAD` and `=======` is this folder's; the side between `=======` and `>>>>>>> live` is Live's (or the merged `--release`). Keep both sides' intended changes and delete the three marker lines. `appbuilder app push` refuses with `unresolved_conflicts` (listing `files`) until no markers are left.\n3. Then follow the rest of `next`: push (dry run, `applyArgv`), publish (dry run, `applyArgv`).\n\n### No recorded base: `base_required` (exit 2)\n\nThis happens when Live exists, the folder matches neither your preview nor a released version exactly (an exact match is detected and used automatically: `base.source` is `\"preview\"` or `\"detected\"`), and no usable base is recorded for it. That's the first push from a fresh clone, another machine or another developer's folder, or a push whose recorded base no longer applies (that version was deleted, or the app was deleted and created again; a notice in the `message` says which). Show the user the `message` and each choice's `label`:\n\n- \"Preview merging Live vN into this folder\" is a dry run. You may run it without asking. With no base to merge from, it always comes back with `kind: \"fallback\"`, whose `choices` are \"Merge, if this folder was copied from vM\" (`--base <M>`) for recent releases, and \"This folder already contains vN\".\n- \"This folder already contains Live vN\" records the base without merging (`--accept-live-base`). Run it only when the user confirms the folder really contains that version, or the next publish drops Live's changes.\n- \"This folder continues your preview (based on vN)\" (`appbuilder app push --base-from-preview <id>`) is a push dry run that gives this folder your preview's base. Never run it on your own judgment: ask the user whether this folder really is the work they pushed as that preview (for example, carried on from another machine). Run it only when they say yes; a wrong yes lets the next publish overwrite Live's changes. Then show its dry run and run its `applyArgv` as for any push. If the user isn't sure, use the merge preview instead.\n\nAfter the fallback, ask the user which release this folder was copied from:\n\n- They know it: run that release's `--base <M>` choice. It merges for real; continue as after any merge (resolve markers, push, publish). A wrong base drops the changes made since then, so never guess one.\n- They don't know: run the fallback's `applyArgv`. It extracts Live's source into `.kizenapp/live-v<N>-<time>/` (reported as `extracted.dir`) and changes nothing else. Help the user merge Live's changes into this folder by hand, then run the \"This folder already contains vN\" choice, and push.\n\n### Another machine or folder\n\nEvery push and rollback stores the preview's base inside the preview's source on the server, and publish reads it from there. So:\n\n- Publishing a preview the user pushed from another machine or folder needs no merge and no `--force`, unless Live moved since (then it's the usual `publish_conflict`).\n- A push from a folder with nothing recorded takes the preview's base by itself when the folder's files equal the preview's (`base.source: \"preview\"`); otherwise `base_required` offers \"This folder continues your preview\", which only the user may choose.\n- `conflict.reason: \"base_replaced\"` (a `publish_conflict`) means the version your preview was based on has been replaced on the business (the app was deleted and created again). Handle it like any `publish_conflict`: run `next[0].argv`, the merge dry run.\n- `conflict.reason: \"base_unknown\"` (a `publish_conflict`) means the preview's source doesn't say what it's based on. Run `next[0].argv`, a push dry run of this folder; with the user's go-ahead, its `applyArgv`, then publish again.\n- A preview pushed from this folder and published outside the CLI (in Kizen, say) is recognised: the folder's base becomes that Live version, with a notice; don't merge because of the old base.\n\n### Roll back and pull\n\n- `appbuilder app rollback <n> --json` restores released version n as the user's preview (dry run, then `applyArgv`). Its `next` is the publish dry run that makes it Live.\n- `appbuilder app pull <n> --json` downloads release n into a new folder, `../<api_name>-v<n>` or `--out <dir>`, and records n as that folder's base. It never writes into an existing folder and needs no `--yes`. Continue in the folder it reports as `dir`.\n- `appbuilder app pull --preview --json` does the same with the user's own preview, into `../<api_name>-preview` or `--out <dir>`. Pass `<n>` or `--preview`, never both. The result has `source: \"preview\"`, `preview` and `base` instead of `version`. `base.recorded: true` means the folder's base is the preview's base, so you can push and publish from it as usual; `false` (with a warning) means the preview doesn't say what it's based on, and the first push from the folder may stop with `base_required`. `no_preview` means the user has no preview to pull.\n\n### Delete a preview\n\nOnly when the user asks to delete a preview:\n\n1. Run `appbuilder app preview delete --json`, a dry run for the user's own preview. For another developer's preview, add `--owner <userId>` with the user id from `previews[].previewOwner.id` in `appbuilder app versions --json`, and only when the user explicitly named that developer's preview.\n2. Show the user `owner`, `preview` and every `warnings` entry. They say when the preview is the app's only version (deleting it deletes the whole app from the business, settings and secrets included), when it belongs to someone else, and when other users are using it.\n3. When the user agrees to every warning, run `applyArgv`. Never add `--delete-app` yourself; `applyArgv` carries it only when the dry run warned that the app goes too. A dry run with no `applyArgv` can't be applied: relay its `notices` to the user. The result has `status: \"deleted\"` and `appDeleted` (`true` when the app went with it). After deleting their own preview, its `next` is a push dry run, which makes a new preview.\n\n`preview_changed` means the preview was pushed again after the dry run, or deleting it would now delete the whole app when the dry run said it stays: nothing was deleted. Run `next[0].argv`, a new dry run, and show it to the user again.\n\n### JS actions: link them to objects\n\nA JS action template does nothing until it's linked to an object. Always create these links with the CLI, even though the app's setup assistant may have a step for it. `push`, `publish` and `versions` results carry `jsActions`: `{ status, liveVersion, actions, next }`; `appbuilder app actions list --json` returns the same `actions`. Each action is `{ apiName, name, hintObjectName, status, inLive, links, linkArgv, linkMenuArgv, linkNoMenuArgv }`:\n\n- `linked`: it has at least one link (`links[]`, each with the object's `objectName`, `includePerformAction` (the Perform Action menu setting) and `unlinkArgv`). Nothing to do.\n- `unlinked`: in Live (or the app isn't on the business yet) with no link. Link it.\n- `unknown`: only in a preview, so its links can't be listed, and it may not be linked yet. Link it right after the push, like an `unlinked` one.\n\nHow to link:\n\n1. Pick the object with the user. For an `unlinked` action with a hint object, `jsActions.next` has a `link` step naming `hintObjectName`: it only suggests that object. Confirm it with the user, or ask which object (no hint, an `unknown` action, or the user wants another one). Don't run the `link` step itself; step 2's argv makes the one dry run.\n2. Ask whether the action should show in the object's Perform Action menus. Take the action's `linkMenuArgv` if it should, and its `linkNoMenuArgv` if it shouldn't (for a link that exists, that turns the menu off); `linkArgv` leaves a new link off the menus and an existing one as it is. Replace the one element that is exactly `<object>` with the object's api name (like `client_client`) or id, change nothing else, and run it: a dry run of `appbuilder app actions link \u2026`. Contacts counts as an object. Exit 2 with `choice: \"object\"` means several objects match: show the user the `choices` and run the one they pick.\n3. Show the user the dry run (`environment`, `businessId`, `jsAction`, `object`, `change`, `includePerformAction`, `warnings`). When they agree, run `applyArgv`. `status` is `created`, `updated`, `up_to_date` or `already_linked` (the link already existed and its menu setting wasn't changed: for an action only in a preview, linked before while its links couldn't be listed; for an action in Live, linked after this command listed the links, in which case run `appbuilder app actions list` and link it again to set the menu setting the user wants).\n4. Review with `appbuilder app actions list --json`: every action with its `status`, `links` and argvs, and link dry runs in `next`. It lists the links of Live's actions only; a preview-only action stays `unknown` until it's published.\n\nIf a link of an `unknown` action fails with `api_error` and a `hint` saying Kizen couldn't find it, that Kizen environment can only link actions in Live. Relay the hint: publish first, then link it.\n\nA link change to an action in Live (`inLive: true`), whether a new link, a menu setting or an unlink, reaches everyone using Live as soon as it's applied; its dry run's `warnings` say so. Treat it like a publish: confirm the object and the menu setting with the user before running its `applyArgv`.\n\nRemove a link only when the user asks: run that link's `unlinkArgv` (`appbuilder app actions unlink \u2026`, a dry run), then its `applyArgv` when they agree.\n\n### What a push uploads\n\nGit's file list (tracked files, plus untracked ones `.gitignore` doesn't exclude; outside git, everything minus the root `.gitignore`), minus the root `.kizenignore` (gitignore syntax; it can only exclude more). These are never uploaded, whatever either file says: `node_modules`, `.git`, `.kizenapp`, `.kizenappbuilder`, `.copilot-docs`, `__pycache__`, `dist`, `.DS_Store`, `.env`, `.env.*`, `.npmrc`, `credentials.json`, and the skill folders appbuilder manages (`kizen-custom-block` and `kizen-business-apps` under `.claude/skills/` and `.agents/skills/`). Other skills in those folders are uploaded like any file. Check `source.files` in the dry run, and suggest a `.kizenignore` entry for anything that shouldn't ship. A release needs a thumbnail.\n\n## Failures\n\n| `code` | What to do |\n| --- | --- |\n| `not_signed_in` | Ask the user to sign in by running `login.argv` themselves: it opens a browser (see Sandboxes). Then run your command again. |\n| `needs_choice` | `choice` is `environment`: the user is signed in to several. Ask which, then run that choice's `argv`. |\n| `base_required` | See \"No recorded base\" above. |\n| `publish_conflict` | Run `next[0].argv`: a merge dry run; a push dry run when `conflict.reason` is `base_unknown`; or, when your preview changed since the dry run, a new publish dry run. |\n| `unresolved_conflicts` | Resolve the markers in `files`, then push again. |\n| `no_preview` | Push first. For `pull --preview`, the user has no preview: tell them, or pull a release instead. |\n| `preview_changed` | Nothing was deleted. Run `next[0].argv`, a new `preview delete` dry run, and show it to the user before going on. |\n| `preview_incomplete` | Push again, then publish (or pull). |\n| `thumbnail_required` | Add a thumbnail to the plugin, push, then publish. |\n| `source_invalid` | The folder can't be zipped (no `kizen.json`, an unreadable `.kizenignore`, a folder git ignores, or a file over 50 MiB or 200 MiB in all). Fix what `message` says, for example with a `.kizenignore` entry. |\n| `validation_failed` | Fix every item in `issues`, then run the command again. |\n| `forbidden` | Tell the user they need the Marketplace \u203A Business App Developer permission at the Delete/All level. Don't retry. |\n| `production_requires_flag` | You ran a write against `go` or `fmo` without `--allow-production`. Run the dry run, get consent, then its `applyArgv`. |\n| `credentials_invalid` | The API-key file from `-c` or `--profile` is bad. Tell the user what `message` says. Use API keys only when the user asks. |\n| `auth_failed` | Kizen refused the session. Ask the user to sign in again (`appbuilder login`, with `--env <env>` for an environment other than `go`). |\n| `session_store_unwritable`, `network_error` | Usually a sandbox; see below. Otherwise relay `message` and `hint`. |\n| `not_found`, `usage_error`, `api_error`, `local_error` | Relay `message` to the user. |\n\n## Sandboxes\n\n`appbuilder` needs the network and write access to `~/.kizenappbuilder`, where it keeps the sign-in session and refreshes its tokens. It talks to the Kizen environment's hosts, and `push` uploads go to whichever file-storage host Kizen names for each upload.\n\n{{#codex}}\n- Codex's sandbox turns the network off and allows writes only to the workspace and `/tmp`. Run `appbuilder` commands with `sandbox_permissions: \"require_escalated\"`, and suggest `prefix_rule: [\"appbuilder\"]` so the user approves `appbuilder` once. A `network_error` with `sandbox: \"codex_network_disabled\"`, or a `session_store_unwritable`, means it ran without that.\n- `.agents/` is read-only in the sandbox, so `appbuilder setup-codex` needs the escalation too.\n- `appbuilder app pull` writes next to the plugin folder by default, outside the workspace. Escalate it, or pass an `--out <dir>` inside the workspace that `.gitignore` or `.kizenignore` excludes.\n- `not_signed_in`: the user runs `login.argv` in their own terminal. It opens a browser and waits for the sign-in.\n{{/codex}}\n{{#claude}}\n- Claude Code's sandbox, when enabled, allows writes only to the working directory and the network only to allowed domains. Because uploads go to a storage host Kizen picks, a domain list can't cover `appbuilder`. If it fails with `session_store_unwritable` or a `network_error`, ask the user to add `\"appbuilder *\"` to `sandbox.excludedCommands` in their user settings (`~/.claude/settings.json`), so `appbuilder` runs outside the sandbox. Project settings don't work for this when Claude Code runs in strict mode.\n- `not_signed_in`: the user types `! ` followed by the `login.argv` command in this session, or runs it in their own terminal. It opens a browser and waits for the sign-in.\n{{/claude}}\n\n## Guardrails\n\n- Never pass `--force`, `--allow-production` or `--accept-live-base`, or run a choice whose `argv` contains one, unless the user explicitly asked for it in this conversation.\n- Always show the user a dry run before you run its `applyArgv`.\n- On exit 2, show the user the `choices` and run the one they pick. The merge preview is the only choice you may run without asking. Never pick \"This folder continues your preview\" for the user.\n- Never edit `.kizenapp/`.\n- Publish only when the user asked to publish.\n- Link a JS action only to an object the user confirmed, and unlink only when the user asked.\n- Delete a preview only when the user asked, and another developer's (`--owner`) only when the user named it.\n";var Dd="---\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 `{{SETUP_COMMAND}} --include-lib` in the plugin directory.\n\n- If it reports `updated` for `{{SKILLS_DIR}}/kizen-custom-block/SKILL.md`, your loaded copy of this skill is stale. Re-read `{{SKILLS_DIR}}/kizen-custom-block/SKILL.md` before doing anything else, and follow the new copy.\n- If it reports `created` for any file in this skill directory, or `updated` for `{{SKILLS_DIR}}/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{{#codex}}\n- In the Codex sandbox `.agents/` is read-only, so run it with `sandbox_permissions: \"require_escalated\"`.\n{{/codex}}\n\n`{{SETUP_COMMAND}}` 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_COMMAND}}` 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 `appbuilder 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\nWith `--json` (`block targets` and `block push`), stdout is one JSON object and human text goes to stderr. Exit `0` is success (dry runs included), exit `2` means a decision is needed (`needs_choice`), and exit `1` is any other failure. Every `argv` a result gives you (`applyArgv`, `choices[].argv`, `login.argv`) is a whole command starting with `appbuilder`: run it exactly as given, without adding, dropping or reordering flags.\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 dry run's `applyArgv` exactly. It is the same push with `--yes`, pinned to the dashboard and dashlet the dry run showed. If `requiresProductionConsent` is `true` (the target is `go` or `fmo`), it also carries `--allow-production`: run it only after the user explicitly agreed to publish to production in this conversation. 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, applyArgv, requiresProductionConsent }`.\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 `{{STALE_WARNING}}`, run `{{SETUP_COMMAND}} --include-lib`, re-read `{{SKILLS_DIR}}/kizen-custom-block/SKILL.md`, then continue.\n- Error: `{ ok: false, code, message, hint?, choice?, choices?, login?, sandbox? }`. `code` is one of `needs_choice`, `validation_failed`, `invalid_block`, `not_signed_in`, `auth_failed`, `forbidden`, `remembered_target_missing`, `drift_detected`, `network_error`, `session_store_unwritable`, `credentials_invalid`, `production_requires_flag`, `not_found`, `usage_error`, `api_error` or `local_error`. When `hint` is present, follow it.\n\n### `needs_choice`\n\n`choice` is `'environment'`, `'block'`, `'dashboard'` or `'target'`. `choices` is a list of `{ value, label, argv, args, surface?, canEdit?, pushKey?, isFromThisPlugin? }`. Ask the user using each option's `label`, then run the chosen option's `argv` exactly as given: it is the push with that choice, as a dry run, so continue from its result (show it, then run its `applyArgv`). Ignore `args`, and never construct these flags by hand.\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 `not_signed_in`, ask the user to sign in by running the `login.argv` command themselves (it opens a browser), then run your command again.\n{{#claude}}\n In Claude Code they can type `! ` followed by that command in this session.\n{{/claude}}\n- On `credentials_invalid`, the API-key file from `-c` or `--profile` is bad. Tell the user to fix the file named in `message`. Don't run `--profile` or `-c` unless the user asks for an API key.\n- On `session_store_unwritable`, or a `network_error` with `sandbox: \"codex_network_disabled\"`, a sandbox is blocking `appbuilder`, which needs the network and write access to `~/.kizenappbuilder`.\n{{#codex}}\n Re-run the command with `sandbox_permissions: \"require_escalated\"`, and suggest `prefix_rule: [\"appbuilder\"]`.\n{{/codex}}\n{{#claude}}\n Ask the user to add `\"appbuilder *\"` to `sandbox.excludedCommands` in their user settings (`~/.claude/settings.json`), so `appbuilder` runs outside the sandbox. Project settings don't work for this when Claude Code runs in strict mode.\n{{/claude}}\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 Ld=`# Designing a Kizen custom block
|
|
151
151
|
|
|
152
152
|
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".
|
|
153
153
|
|
|
@@ -496,7 +496,7 @@ render(
|
|
|
496
496
|
color: var(--color-font-placeholder);
|
|
497
497
|
}
|
|
498
498
|
\`\`\`
|
|
499
|
-
`;var
|
|
499
|
+
`;var Bd=`# Copilot review instructions for this Kizen plugin
|
|
500
500
|
|
|
501
501
|
This repo is a Kizen plugin app: a \`kizen.json\` manifest plus the artifacts
|
|
502
502
|
that \`@kizenapps/packager\` finds by walking the directory tree under the
|
|
@@ -549,7 +549,7 @@ This file covers repo structure and general review. Two path-scoped files cover
|
|
|
549
549
|
the rest: \`.github/instructions/security.instructions.md\` for security-sensitive
|
|
550
550
|
patterns and \`.github/instructions/version-discipline.instructions.md\` for
|
|
551
551
|
manifest version bumps.
|
|
552
|
-
`;var
|
|
552
|
+
`;var Fd='---\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 jd=`---
|
|
553
553
|
applyTo: "kizen.json"
|
|
554
554
|
---
|
|
555
555
|
|
|
@@ -562,7 +562,7 @@ cannot drift out of date here.
|
|
|
562
562
|
Check every \`kizen.json\` diff against the "How big a bump?" matrix in
|
|
563
563
|
\`.copilot-docs/16-release-and-publish.md\` and the "Release & publish" section of
|
|
564
564
|
\`.copilot-docs/17-gotchas.md\`, and name the change that sets the required level.
|
|
565
|
-
`;var
|
|
565
|
+
`;var Md=`# Copilot only reads this file from the default branch, and only if the job is named copilot-setup-steps.
|
|
566
566
|
name: Copilot code review setup
|
|
567
567
|
|
|
568
568
|
on:
|
|
@@ -601,7 +601,7 @@ jobs:
|
|
|
601
601
|
echo "Fetched $count markdown files into .copilot-docs/ ($numbered numbered docs)"
|
|
602
602
|
test "$count" -ge 24
|
|
603
603
|
du -sh .copilot-docs
|
|
604
|
-
`;var
|
|
604
|
+
`;var zd=`const MAX_PAGE_SIZE = 1000;
|
|
605
605
|
const DEFAULT_MAX_PAGES = 10;
|
|
606
606
|
|
|
607
607
|
const fieldCache = new Map();
|
|
@@ -846,35 +846,35 @@ export const sumBy = (records, name, valueOf) =>
|
|
|
846
846
|
total + (valueOf ? numberOf(valueOf(record)) : numberOf(fieldValue(record, name))),
|
|
847
847
|
0,
|
|
848
848
|
);
|
|
849
|
-
`;function Ki(){return[{path:".github/copilot-instructions.md",content:Od},{path:".github/instructions/security.instructions.md",content:Dd},{path:".github/instructions/version-discipline.instructions.md",content:Ld},{path:".github/workflows/copilot-code-review.yml",content:Bd}]}var jd="lib/kizenData.js",Aa=(e="src")=>e===""?jd:`${e}/${jd}`,Fv={"kizen-custom-block":[["SKILL.md",Rd],["design.md",$d]],"kizen-business-apps":[["SKILL.md",Nd]]};var Md=e=>ji.map(t=>`${Ke[e].skillsDir}/${t}/SKILL.md`);function Wi(e,t=[]){let{skillsDir:n}=Ke[e];return[...ji.flatMap(r=>Fv[r].map(([i,o])=>({path:`${n}/${r}/${i}`,content:Hu(o,e)}))),...[...new Set(t)].map(r=>({path:Aa(r),content:Fd}))]}var zd=(e=[])=>Wi("claude",e),Ud=(e=[])=>Wi("codex",e);import{access as jv,lstat as Mv,mkdir as zv,readFile as Uv,realpath as Vd,writeFile as Vv}from"fs/promises";import{dirname as Hv,join as xa,sep as Kv}from"path";var Xn=class extends Error{constructor(n,r){super(`Refusing to write ${n}: ${r}. appbuilder writes its managed files only as regular files inside the plugin folder, so nothing was written. Remove or replace it, then run this command again.`);this.path=n;this.name="UnsafeManagedPathError"}path},Wv=(e,t)=>t===e||t.startsWith(e+Kv);async function Gv(e,t){let n=t.split("/");if(n.some(o=>o===""||o==="."||o===".."))throw new Xn(t,"it is not a plain relative path");let r=await Vd(e),i=e;for(let[o,s]of n.entries()){i=xa(i,s);let a=n.slice(0,o+1).join("/"),c;try{c=await Mv(i)}catch(d){if(tt(d))return;throw d}if(c.isSymbolicLink())throw new Xn(t,`${a} is a symbolic link`);let l=o===n.length-1;if(l?!c.isFile():!c.isDirectory())throw new Xn(t,`${a} is not a ${l?"regular file":"directory"}`)}if(!Wv(r,await Vd(i)))throw new Xn(t,"it resolves outside the plugin folder")}var gt={readFile:async e=>{try{return await Uv(e,"utf-8")}catch(t){if(tt(t))return;throw t}},writeFile:async(e,t)=>{await zv(Hv(e),{recursive:!0}),await Vv(e,t,"utf-8")},exists:async e=>{try{return await jv(e),!0}catch{return!1}},checkPath:Gv},Jv=(e,t)=>e===void 0?"created":e===t?"unchanged":"updated";async function Pa(e,t,n=gt){for(let r of t)await n.checkPath(e,r.path);return Promise.all(t.map(async r=>({path:r.path,status:Jv(await n.readFile(xa(e,r.path)),r.content)})))}async function Gi(e,t,n={},r=gt){let i=await Pa(e,t,r);return n.dryRun===!0||await Promise.all(t.filter((o,s)=>i[s]?.status!=="unchanged").map(o=>r.writeFile(xa(e,o.path),o.content))),i}var Ji=e=>`${e.status.padEnd(9)} ${e.path}`;var qv=e=>{if(typeof e!="string"||e.trim()==="")return;let t=Ai(e);if(!(t===".."||t.startsWith("../")||t.startsWith("/")))return t};function Hd(e){let n=(Array.isArray(e)?e:[e]).map(r=>typeof r=="object"&&r!==null&&"entry"in r?qv(r.entry):void 0).filter(r=>r!==void 0);return n.length>0?[...new Set(n)]:["src"]}var Yv=async(e,t)=>{try{let n=await t.readFile(qi(e,"kizen.json"));return n===void 0?["src"]:Hd(JSON.parse(n))}catch{return["src"]}};async function Sa(e,t,n=gt,r={}){let i=await Yv(e,n),o=r.includeLib===!0?i:(await Promise.all(i.map(async s=>await n.exists(qi(e,Aa(s)))?s:void 0))).filter(s=>s!==void 0);return Wi(t,o)}async function _a(e,t,n=gt){try{return(await Promise.all(Md(t).map(async o=>await n.readFile(qi(e,o))!==void 0))).includes(!0)?(await Pa(e,await Sa(e,t,n),n)).some(o=>o.status!=="unchanged"):!1}catch{return!1}}async function Yi(e,t=gt){let n=await Promise.all(Fi.map(r=>_a(e,r,t)));return Fi.filter((r,i)=>n[i]===!0).map(r=>Ke[r].staleWarning)}var Ca=(e,t)=>`${String(e.filter(n=>n.status===t).length)} ${t}`;async function Zi(e,t,n,r){if(!await r.fs.exists(qi(e,"kizen.json"))){r.error(`Error: kizen.json not found. Run this command from a plugin directory${n.notFoundHint??""}.`),r.setExitCode(1);return}let i;try{i=await Gi(e,await Sa(e,t,r.fs,{includeLib:n.includeLib}),{dryRun:n.dryRun},r.fs)}catch(a){r.error(`Error: ${ke(a)}`),r.setExitCode(1);return}for(let a of i)r.log(Ji(a));let o=`${Ca(i,"created")}, ${Ca(i,"updated")}, ${Ca(i,"unchanged")}`,s="these files are managed by appbuilder, so local edits to them are replaced";r.log(n.dryRun?`Dry run: ${o}; nothing written (${s}).`:`${Ke[t].filesLabel} files: ${o} (${s}).`)}var tn=class extends Error{code;constructor(t,n){super(n),this.name="BusinessAppError",this.code=t}},Ea="A thumbnail is required to publish a release. Add a thumbnail image to the app.",Qt=encodeURIComponent,Zv="Business Apps aren't available on this Kizen environment yet.",Xv="Kizen has no Business Apps list on this environment (it answered 404). Use an environment where Business Apps are available, with --env.",Qv=e=>e instanceof q&&e.kind==="not_found",ek=e=>new q("not_found",Zv,{...e.status!==void 0&&{status:e.status},hint:Xv,details:e.details,cause:e}),en=(e,t)=>new q("api_error",`${e} ${t} returned an unexpected response shape`);function Tn(e,t,n){if(!F(n))throw en(e,t);return n}var Kd=(e,t)=>t.every(n=>typeof e[n]=="string");function tk(e,t){let n=Tn("GET",e,t),{url:r,fields:i,s3object_id:o,max_file_size:s}=n;if(typeof r!="string"||!F(i)||!Object.values(i).every(a=>typeof a=="string")||typeof i.key!="string"||typeof o!="string"||typeof s!="number")throw en("GET",e);return{url:r,fields:i,key:i.key,s3objectId:o,maxFileSize:s}}var Qn=e=>typeof e=="string"?e:void 0;function nk(e){if(!F(e)||typeof e.id!="string")return null;let t=e.browser_js_action_template,n=e.custom_object,r=e.include_perform_action;if(!F(t)||typeof t.api_name!="string"||!F(n)||typeof n.id!="string"||r!=null&&typeof r!="boolean")return null;let i=Qn(n.object_name),o=Qn(n.entity_name);return{id:e.id,include_perform_action:r??null,browser_js_action_template:{id:Qn(t.id)??"",api_name:t.api_name,name:Qn(t.name)??t.api_name,hint_object_name:Qn(t.hint_object_name)??null},custom_object:{id:n.id,name:Qn(n.name)??"",...i===void 0?{}:{object_name:i},...o===void 0?{}:{entity_name:o}}}}function Wd(e,t,n={}){let r=n.fetch??fetch,i=`/external-integrations/plugin-apps/${Qt(t)}`,o=u=>`${i}/${Qt(u)}`,s=(u,f)=>`${o(u)}/previews/${Qt(f)}`,a=u=>`/external-integrations/business-plugin-apps/${Qt(u)}/browser-js-action-template-associations`,c="/external-integrations/browser-js-action-template-association",l=async u=>Tn("GET",u,await e.requestJson("GET",u)),d=async(u,f,g,m)=>{let p=new FormData;for(let[b,y]of Object.entries(u.fields))p.append(b,y);p.append("file",new Blob([f],{type:g}),m);let h;try{h=await r(u.url,{method:"POST",body:p})}catch(b){throw new q("network_error",`Couldn't upload ${m} to file storage: ${xe(b)}`)}if(!h.ok){let b=await h.text().catch(()=>""),y=/<Code>([^<]+)<\/Code>/.exec(b)?.[1];throw new q("api_error",`Uploading ${m} to file storage failed with ${String(h.status)}${y===void 0?"":`: ${y}`}`,{status:h.status,details:b===""?void 0:b})}return await h.body?.cancel().catch(()=>{}),h.headers.get("etag")??""};return{async listApps(u){let f=u===void 0||u===""?"":`?${new URLSearchParams({search:u}).toString()}`,g=`${i}/apps${f}`,m;try{m=await e.requestJson("GET",g)}catch(p){throw Qv(p)?ek(p):p}if(!Array.isArray(m)||!m.every(F))throw en("GET",g);return m},async getApp(u,f={}){let g=f.previewOwner===void 0?"":`?${new URLSearchParams({preview_owner:f.previewOwner}).toString()}`,m=`${o(u)}${g}`;return Tn("GET",m,await e.requestJson("GET",m))},async getVersion(u,f){return l(`${o(u)}/versions/${Qt(String(f))}`)},async getPreview(u,f){return l(s(u,f))},async publish(u){if(u.release&&!u.thumbnail)throw new tn("thumbnail_required",Ea);let f=`${i}/publish`,g=Tn("POST",f,await e.requestJson("POST",f,u));if(!Kd(g,["api_name","base_api_name","version"]))throw en("POST",f);return g},async promotePreview(u,f){let g=`${s(u,f)}/promote`,m=Tn("POST",g,await e.requestJson("POST",g));if(!Kd(m,["api_name","version"]))throw en("POST",g);return m},async deletePreview(u,f){await e.requestJson("DELETE",s(u,f))},async uploadFile(u,f){let m=`/s3/presigned-post?${new URLSearchParams({filename:f.filename,contenttype:f.contentType,source:f.source}).toString()}`,p=tk(m,await e.requestJson("GET",m));if(u.byteLength>p.maxFileSize)throw new tn("file_too_large",`${f.filename} is ${String(u.byteLength)} bytes; the limit is ${String(p.maxFileSize)} bytes.`);let h=await d(p,u,f.contentType,f.filename),b=`/s3/success?${new URLSearchParams({source:f.source}).toString()}`,y={uuid:p.s3objectId,key:p.key,name:f.filename,etag:h};f.isPublic===!0&&(y.is_public="true");let C=Tn("POST",b,await e.postForm(b,y));if(typeof C.id!="string")throw en("POST",b);return C.id},async downloadFile(u){return e.getBinary(`/files/${Qt(u)}/download`)},async listActionAssociations(u){let f=a(u),g=Tn("GET",f,await e.requestJson("GET",f));if(!Array.isArray(g.associations))throw en("GET",f);return g.associations.map(m=>{let p=nk(m);if(p===null)throw en("GET",f);return p})},async createActionAssociation(u){await e.requestJson("POST",c,{browser_js_action_template:{api_name:u.actionApiName,plugin_app_api_name:u.appApiName},custom_object:{id:u.objectId},include_perform_action:u.includePerformAction})},async updateActionAssociation(u,f,g){await e.requestJson("PATCH",`${a(u)}/${Qt(f)}`,{include_perform_action:g})},async deleteActionAssociation(u){await e.requestJson("DELETE",`${c}/${Qt(u)}`)},async listObjects(){return(await e.listCustomObjects({customOnly:!1})).map(f=>({id:f.id,name:f.name??"",objectName:f.object_name,entityName:f.entity_name??null}))}}}function rk(e){return structuredClone(Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!==void 0)))}function ik(e){let t=n=>structuredClone(n??[]);return{data_adornments:t(e.data_adornments),floating_frames:t(e.floating_frames),custom_blocks:t(e.custom_blocks),routable_pages:t(e.routable_pages),toolbar_items:t(e.toolbar_items),object_settings_menu_items:t(e.object_settings_menu_items),calendar_sources:t(e.calendar_sources),js_action_templates:t(e.js_action_templates),route_script_templates:t(e.route_scripts),automation_action_configs:t(e.automation_action_configs)}}var Xi=e=>typeof e=="string"?e:void 0;function Ia(e,t){if(t.release&&!t.thumbnailId)throw new tn("thumbnail_required",Ea);let n=e,r={name:e.name,api_name:e.api_name,engine:e.engine,services:structuredClone(e.services??[]),base_config:rk(e.base_config),artifacts:ik(e.artifacts),release:t.release,source_filesystem_package:t.sourcePackageId,thumbnail:t.thumbnailId},i=Xi(e.description),o=Xi(e.agentic_description),s=Xi(n.external_link),a=Xi(e.releaseNotes);return i!==void 0&&(r.description=i),o!==void 0&&(r.agentic_description=o),s!==void 0&&(r.external_link=s),e.config_template!==void 0&&(r.config_template=structuredClone(e.config_template)),Array.isArray(n.catalogs)&&n.catalogs.every(c=>typeof c=="string")&&(r.catalogs=[...n.catalogs]),a!==void 0&&(r.release_notes=a),r}import{join as lk}from"path";import{PluginValidationError as uk}from"@kizenapps/packager";import{mkdir as ok,readFile as sk,writeFile as ak}from"fs/promises";import{join as Gd}from"path";async function ht(e){try{let t=await sk(Gd(e,"config.json"),"utf-8");return JSON.parse(t)}catch{return{}}}async function nn(e,t){await ok(e,{recursive:!0}),await ak(Gd(e,"config.json"),JSON.stringify(t,null,2),"utf-8")}var Ta=(e,t,n)=>`${String(e)} ${e===1?t:n}`,Na=e=>{let t=new Map;for(let n of e){let r=n.path??n.pluginApiName??"general",i=t.get(r)??[];i.push(n),t.set(r,i)}return t},ck=e=>{let t=e.filter(i=>i.severity==="error").length,n=e.length-t;if(t===0)return`\u26A0 ${Ta(n,"validation warning","validation warnings")}`;let r=`\u2717 ${Ta(t,"validation error","validation errors")}`;return n===0?r:`${r}, ${Ta(n,"warning","warnings")}`};function We(e){if(e.length===0)return"";let t=[...Na(e)].map(([n,r])=>[n,...r.map(i=>` ${i.severity==="error"?"\u2717":"\u26A0"} ${i.message} (${i.rule})`)].join(`
|
|
850
|
-
`));return[
|
|
849
|
+
`;function Ki(){return[{path:".github/copilot-instructions.md",content:Bd},{path:".github/instructions/security.instructions.md",content:Fd},{path:".github/instructions/version-discipline.instructions.md",content:jd},{path:".github/workflows/copilot-code-review.yml",content:Md}]}var Ud="lib/kizenData.js",xa=(e="src")=>e===""?Ud:`${e}/${Ud}`,Vv={"kizen-custom-block":[["SKILL.md",Dd],["design.md",Ld]],"kizen-business-apps":[["SKILL.md",Od]]};var Vd=e=>ji.map(t=>`${Ke[e].skillsDir}/${t}/SKILL.md`);function Wi(e,t=[]){let{skillsDir:n}=Ke[e];return[...ji.flatMap(r=>Vv[r].map(([i,o])=>({path:`${n}/${r}/${i}`,content:Gu(o,e)}))),...[...new Set(t)].map(r=>({path:xa(r),content:zd}))]}var Hd=(e=[])=>Wi("claude",e),Kd=(e=[])=>Wi("codex",e);import{access as Hv,lstat as Kv,mkdir as Wv,readFile as Gv,realpath as Wd,writeFile as Jv}from"fs/promises";import{dirname as qv,join as Pa,sep as Yv}from"path";var Xn=class extends Error{constructor(n,r){super(`Refusing to write ${n}: ${r}. appbuilder writes its managed files only as regular files inside the plugin folder, so nothing was written. Remove or replace it, then run this command again.`);this.path=n;this.name="UnsafeManagedPathError"}path},Zv=(e,t)=>t===e||t.startsWith(e+Yv);async function Xv(e,t){let n=t.split("/");if(n.some(o=>o===""||o==="."||o===".."))throw new Xn(t,"it is not a plain relative path");let r=await Wd(e),i=e;for(let[o,s]of n.entries()){i=Pa(i,s);let a=n.slice(0,o+1).join("/"),c;try{c=await Kv(i)}catch(d){if(tt(d))return;throw d}if(c.isSymbolicLink())throw new Xn(t,`${a} is a symbolic link`);let l=o===n.length-1;if(l?!c.isFile():!c.isDirectory())throw new Xn(t,`${a} is not a ${l?"regular file":"directory"}`)}if(!Zv(r,await Wd(i)))throw new Xn(t,"it resolves outside the plugin folder")}var yt={readFile:async e=>{try{return await Gv(e,"utf-8")}catch(t){if(tt(t))return;throw t}},writeFile:async(e,t)=>{await Wv(qv(e),{recursive:!0}),await Jv(e,t,"utf-8")},exists:async e=>{try{return await Hv(e),!0}catch{return!1}},checkPath:Xv},Qv=(e,t)=>e===void 0?"created":e===t?"unchanged":"updated";async function Ca(e,t,n=yt){for(let r of t)await n.checkPath(e,r.path);return Promise.all(t.map(async r=>({path:r.path,status:Qv(await n.readFile(Pa(e,r.path)),r.content)})))}async function Gi(e,t,n={},r=yt){let i=await Ca(e,t,r);return n.dryRun===!0||await Promise.all(t.filter((o,s)=>i[s]?.status!=="unchanged").map(o=>r.writeFile(Pa(e,o.path),o.content))),i}var Ji=e=>`${e.status.padEnd(9)} ${e.path}`;var ek=e=>{if(typeof e!="string"||e.trim()==="")return;let t=Ai(e);if(!(t===".."||t.startsWith("../")||t.startsWith("/")))return t};function Gd(e){let n=(Array.isArray(e)?e:[e]).map(r=>typeof r=="object"&&r!==null&&"entry"in r?ek(r.entry):void 0).filter(r=>r!==void 0);return n.length>0?[...new Set(n)]:["src"]}var tk=async(e,t)=>{try{let n=await t.readFile(qi(e,"kizen.json"));return n===void 0?["src"]:Gd(JSON.parse(n))}catch{return["src"]}};async function _a(e,t,n=yt,r={}){let i=await tk(e,n),o=r.includeLib===!0?i:(await Promise.all(i.map(async s=>await n.exists(qi(e,xa(s)))?s:void 0))).filter(s=>s!==void 0);return Wi(t,o)}async function Ea(e,t,n=yt){try{return(await Promise.all(Vd(t).map(async o=>await n.readFile(qi(e,o))!==void 0))).includes(!0)?(await Ca(e,await _a(e,t,n),n)).some(o=>o.status!=="unchanged"):!1}catch{return!1}}async function Yi(e,t=yt){let n=await Promise.all(Fi.map(r=>Ea(e,r,t)));return Fi.filter((r,i)=>n[i]===!0).map(r=>Ke[r].staleWarning)}var Sa=(e,t)=>`${String(e.filter(n=>n.status===t).length)} ${t}`;async function Zi(e,t,n,r){if(!await r.fs.exists(qi(e,"kizen.json"))){r.error(`Error: kizen.json not found. Run this command from a plugin directory${n.notFoundHint??""}.`),r.setExitCode(1);return}let i;try{i=await Gi(e,await _a(e,t,r.fs,{includeLib:n.includeLib}),{dryRun:n.dryRun},r.fs)}catch(a){r.error(`Error: ${ke(a)}`),r.setExitCode(1);return}for(let a of i)r.log(Ji(a));let o=`${Sa(i,"created")}, ${Sa(i,"updated")}, ${Sa(i,"unchanged")}`,s="these files are managed by appbuilder, so local edits to them are replaced";r.log(n.dryRun?`Dry run: ${o}; nothing written (${s}).`:`${Ke[t].filesLabel} files: ${o} (${s}).`)}var nn=class extends Error{code;constructor(t,n){super(n),this.name="BusinessAppError",this.code=t}},Ia="A thumbnail is required to publish a release. Add a thumbnail image to the app.",en=encodeURIComponent,nk="Business Apps aren't available on this Kizen environment yet.",rk="Kizen has no Business Apps list on this environment (it answered 404). Use an environment where Business Apps are available, with --env.",ik=e=>e instanceof q&&e.kind==="not_found",ok=e=>new q("not_found",nk,{...e.status!==void 0&&{status:e.status},hint:rk,details:e.details,cause:e}),tn=(e,t)=>new q("api_error",`${e} ${t} returned an unexpected response shape`);function Tn(e,t,n){if(!F(n))throw tn(e,t);return n}var Jd=(e,t)=>t.every(n=>typeof e[n]=="string");function sk(e,t){let n=Tn("GET",e,t),{url:r,fields:i,s3object_id:o,max_file_size:s}=n;if(typeof r!="string"||!F(i)||!Object.values(i).every(a=>typeof a=="string")||typeof i.key!="string"||typeof o!="string"||typeof s!="number")throw tn("GET",e);return{url:r,fields:i,key:i.key,s3objectId:o,maxFileSize:s}}var Qn=e=>typeof e=="string"?e:void 0;function ak(e){if(!F(e)||typeof e.id!="string")return null;let t=e.browser_js_action_template,n=e.custom_object,r=e.include_perform_action;if(!F(t)||typeof t.api_name!="string"||!F(n)||typeof n.id!="string"||r!=null&&typeof r!="boolean")return null;let i=Qn(n.object_name),o=Qn(n.entity_name);return{id:e.id,include_perform_action:r??null,browser_js_action_template:{id:Qn(t.id)??"",api_name:t.api_name,name:Qn(t.name)??t.api_name,hint_object_name:Qn(t.hint_object_name)??null},custom_object:{id:n.id,name:Qn(n.name)??"",...i===void 0?{}:{object_name:i},...o===void 0?{}:{entity_name:o}}}}function qd(e,t,n={}){let r=n.fetch??fetch,i=`/external-integrations/plugin-apps/${en(t)}`,o=u=>`${i}/${en(u)}`,s=(u,f)=>`${o(u)}/previews/${en(f)}`,a=u=>`/external-integrations/business-plugin-apps/${en(u)}/browser-js-action-template-associations`,c="/external-integrations/browser-js-action-template-association",l=async u=>Tn("GET",u,await e.requestJson("GET",u)),d=async(u,f,g,p)=>{let m=new FormData;for(let[b,y]of Object.entries(u.fields))m.append(b,y);m.append("file",new Blob([f],{type:g}),p);let h;try{h=await r(u.url,{method:"POST",body:m})}catch(b){throw new q("network_error",`Couldn't upload ${p} to file storage: ${xe(b)}`)}if(!h.ok){let b=await h.text().catch(()=>""),y=/<Code>([^<]+)<\/Code>/.exec(b)?.[1];throw new q("api_error",`Uploading ${p} to file storage failed with ${String(h.status)}${y===void 0?"":`: ${y}`}`,{status:h.status,details:b===""?void 0:b})}return await h.body?.cancel().catch(()=>{}),h.headers.get("etag")??""};return{async listApps(u){let f=u===void 0||u===""?"":`?${new URLSearchParams({search:u}).toString()}`,g=`${i}/apps${f}`,p;try{p=await e.requestJson("GET",g)}catch(m){throw ik(m)?ok(m):m}if(!Array.isArray(p)||!p.every(F))throw tn("GET",g);return p},async getApp(u,f={}){let g=f.previewOwner===void 0?"":`?${new URLSearchParams({preview_owner:f.previewOwner}).toString()}`,p=`${o(u)}${g}`;return Tn("GET",p,await e.requestJson("GET",p))},async getVersion(u,f){return l(`${o(u)}/versions/${en(String(f))}`)},async getPreview(u,f){return l(s(u,f))},async publish(u){if(u.release&&!u.thumbnail)throw new nn("thumbnail_required",Ia);let f=`${i}/publish`,g=Tn("POST",f,await e.requestJson("POST",f,u));if(!Jd(g,["api_name","base_api_name","version"]))throw tn("POST",f);return g},async promotePreview(u,f){let g=`${s(u,f)}/promote`,p=Tn("POST",g,await e.requestJson("POST",g));if(!Jd(p,["api_name","version"]))throw tn("POST",g);return p},async deletePreview(u,f){await e.requestJson("DELETE",s(u,f))},async uploadFile(u,f){let p=`/s3/presigned-post?${new URLSearchParams({filename:f.filename,contenttype:f.contentType,source:f.source}).toString()}`,m=sk(p,await e.requestJson("GET",p));if(u.byteLength>m.maxFileSize)throw new nn("file_too_large",`${f.filename} is ${String(u.byteLength)} bytes; the limit is ${String(m.maxFileSize)} bytes.`);let h=await d(m,u,f.contentType,f.filename),b=`/s3/success?${new URLSearchParams({source:f.source}).toString()}`,y={uuid:m.s3objectId,key:m.key,name:f.filename,etag:h};f.isPublic===!0&&(y.is_public="true");let C=Tn("POST",b,await e.postForm(b,y));if(typeof C.id!="string")throw tn("POST",b);return C.id},async downloadFile(u){return e.getBinary(`/files/${en(u)}/download`)},async listActionAssociations(u){let f=a(u),g=Tn("GET",f,await e.requestJson("GET",f));if(!Array.isArray(g.associations))throw tn("GET",f);return g.associations.map(p=>{let m=ak(p);if(m===null)throw tn("GET",f);return m})},async createActionAssociation(u){await e.requestJson("POST",c,{browser_js_action_template:{api_name:u.actionApiName,plugin_app_api_name:u.appApiName},custom_object:{id:u.objectId},include_perform_action:u.includePerformAction})},async updateActionAssociation(u,f,g){await e.requestJson("PATCH",`${a(u)}/${en(f)}`,{include_perform_action:g})},async deleteActionAssociation(u){await e.requestJson("DELETE",`${c}/${en(u)}`)},async listObjects(){return(await e.listCustomObjects({customOnly:!1})).map(f=>({id:f.id,name:f.name??"",objectName:f.object_name,entityName:f.entity_name??null}))}}}function ck(e){return structuredClone(Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!==void 0)))}function lk(e){let t=n=>structuredClone(n??[]);return{data_adornments:t(e.data_adornments),floating_frames:t(e.floating_frames),custom_blocks:t(e.custom_blocks),routable_pages:t(e.routable_pages),toolbar_items:t(e.toolbar_items),object_settings_menu_items:t(e.object_settings_menu_items),calendar_sources:t(e.calendar_sources),js_action_templates:t(e.js_action_templates),route_script_templates:t(e.route_scripts),automation_action_configs:t(e.automation_action_configs)}}var Xi=e=>typeof e=="string"?e:void 0;function Ta(e,t){if(t.release&&!t.thumbnailId)throw new nn("thumbnail_required",Ia);let n=e,r={name:e.name,api_name:e.api_name,engine:e.engine,services:structuredClone(e.services??[]),base_config:ck(e.base_config),artifacts:lk(e.artifacts),release:t.release,source_filesystem_package:t.sourcePackageId,thumbnail:t.thumbnailId},i=Xi(e.description),o=Xi(e.agentic_description),s=Xi(n.external_link),a=Xi(e.releaseNotes);return i!==void 0&&(r.description=i),o!==void 0&&(r.agentic_description=o),s!==void 0&&(r.external_link=s),e.config_template!==void 0&&(r.config_template=structuredClone(e.config_template)),Array.isArray(n.catalogs)&&n.catalogs.every(c=>typeof c=="string")&&(r.catalogs=[...n.catalogs]),a!==void 0&&(r.release_notes=a),r}import{join as fk}from"path";import{PluginValidationError as gk}from"@kizenapps/packager";import{mkdir as uk,readFile as dk,writeFile as pk}from"fs/promises";import{join as Yd}from"path";async function rt(e){try{let t=await dk(Yd(e,"config.json"),"utf-8");return JSON.parse(t)}catch{return{}}}async function bt(e,t){await uk(e,{recursive:!0}),await pk(Yd(e,"config.json"),JSON.stringify(t,null,2),"utf-8")}var Na=(e,t,n)=>`${String(e)} ${e===1?t:n}`,Ra=e=>{let t=new Map;for(let n of e){let r=n.path??n.pluginApiName??"general",i=t.get(r)??[];i.push(n),t.set(r,i)}return t},mk=e=>{let t=e.filter(i=>i.severity==="error").length,n=e.length-t;if(t===0)return`\u26A0 ${Na(n,"validation warning","validation warnings")}`;let r=`\u2717 ${Na(t,"validation error","validation errors")}`;return n===0?r:`${r}, ${Na(n,"warning","warnings")}`};function We(e){if(e.length===0)return"";let t=[...Ra(e)].map(([n,r])=>[n,...r.map(i=>` ${i.severity==="error"?"\u2717":"\u26A0"} ${i.message} (${i.rule})`)].join(`
|
|
850
|
+
`));return[mk(e),...t].join(`
|
|
851
851
|
|
|
852
|
-
`)}function me(e,t,n={}){return{ok:!1,code:e,message:t,...n}}var I=e=>({ok:!0,value:e}),je=e=>e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";function Me(e){return e instanceof q?me(e.kind,e.message,e.hint===void 0?{}:{hint:e.hint}):e instanceof
|
|
852
|
+
`)}function me(e,t,n={}){return{ok:!1,code:e,message:t,...n}}var I=e=>({ok:!0,value:e}),je=e=>e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";function Me(e){return e instanceof q?me(e.kind,e.message,e.hint===void 0?{}:{hint:e.hint}):e instanceof gk?me("validation_failed",We(e.issues),{issues:e.issues}):me("local_error",je(e))}function Qd(e,t={}){let{fetch:n}=t;return{listSessions:()=>e.listSessions(),listAccounts:r=>e.listAccounts(r),connect:async(r,i)=>{let o=_i(r,e,{...n&&{fetch:n},...i!==void 0&&{account:i}}),s=xr({bearer:o,...n&&{fetch:n}});return{identity:await s.getIdentity(),client:s}}}}function Qi(e){return{cwd:e,loadCredentialsDetailed:Ci,listLoadableCredentialProfiles:ou,loadConfig:rt,createClient:t=>xr({credentials:t}),now:()=>new Date,writeStdout:t=>{process.stdout.write(t)},writeStderr:t=>{process.stderr.write(t)},setExitCode:t=>{process.exitCode=t},processEnv:process.env,oauth:Qd(ht())}}var hk=(e,t)=>["appbuilder","login",...e===void 0?[]:["--env",e],...t===void 0?[]:["--business",t.business,...t.user===void 0?[]:["--user",t.user]]];function yk(e,t){return t.CODEX_CI!==void 0?`Ask the user to sign in: they run \`${e}\` in their own terminal, where it opens a browser and waits for the sign-in. Then run this command again.`:t.CLAUDECODE!==void 0?`Ask the user to sign in: they type \`! ${e}\` in this Claude Code session, or you run it in the background and give them the URL it prints. Then run this command again.`:`Ask the user to sign in: they run \`${e}\` in a terminal, or you run it in the background and give them the URL it prints. Then run this command again.`}function $a(e,t,n,r){let i=hk(t,n);return me("not_signed_in",e,{login:{argv:i},hint:yk(i.map(ge).join(" "),r)})}var bk=e=>e instanceof q&&e.cause instanceof ue&&e.cause.code==="login_required";async function ep(e,t){let n;try{n=await t.loadCredentialsDetailed(e)}catch(o){return me("credentials_invalid",`Couldn't read credentials from ${e}: ${je(o)}`)}if(n.environmentSource!=="explicit"){let o=n.environmentSource==="missing"?'has no "environment"':'has an invalid "environment"';return me("credentials_invalid",`${e} ${o}. Set it to one of: ${pe.join(", ")}. The CLI won't default to production.`)}let{credentials:r}=n,i=["apiKey","userId","businessId"].filter(o=>r[o].trim()==="");return i.length>0?me("credentials_invalid",`${e} is missing ${i.map(o=>`"${o}"`).join(", ")}.`):I({credentials:{environment:r.environment,businessId:r.businessId,userId:r.userId},client:t.createClient(r),notices:[]})}async function wk(e,t){let n=await t.listLoadableCredentialProfiles(),r=n.find(i=>i.name===e);if(!r){let i=n.map(o=>o.name);return me("credentials_invalid",i.length===0?`No loadable credential profile named "${e}". No profiles are loadable; create ${Wt} or pass -c <path>.`:`No loadable credential profile named "${e}". Loadable profiles: ${i.join(", ")}`)}return ep(r.path,t)}async function vk(e){let{activeCredentialProfile:t}=await e.loadConfig(fk(e.cwd,".kizenapp"));return t===void 0||t===""?[]:[Ql(t)]}async function Oa(e,t,n){let{sessions:r,processEnv:i,signedOutMessage:o=l=>l}=n,s=await _r(e,t,r);if(!s.ok)switch(s.problem){case"not_signed_in":return $a(o(s.message),e,t,i);case"several_sessions":return me("needs_choice",s.message,{choice:"environment",choices:s.environments.map(l=>({value:l,label:l,args:["--env",l]}))});case"unknown_environment":return me("usage_error",s.message)}let{environment:a}=s,c;if(t!==void 0){let l;try{l=await r.listAccounts(a)}catch(d){return Me(d)}try{c=Er(a,l,t)}catch(d){return Sr(l,t.business,t.user).kind==="none"?$a(je(d),a,t,i):me("usage_error",je(d))}}try{return I({environment:a,connected:await n.connect(a,c)})}catch(l){return bk(l)?$a(je(l),a,t,i):Me(l)}}async function kk(e,t,n){let r=await Oa(e,t,{sessions:n.oauth,connect:(s,a)=>n.oauth.connect(s,a),processEnv:n.processEnv,signedOutMessage:eu});if(!r.ok)return r;let{environment:i,connected:o}=r.value;return I({credentials:{environment:i,businessId:o.identity.businessId,userId:o.identity.userId},client:o.client,notices:await vk(n)})}async function Nn(e,t){let n=Xl(e,t.processEnv);if(!n.ok)return me("usage_error",n.message);let{selection:r}=n;return r.kind==="oauth"?kk(r.env,r.account,t):r.credentials===void 0?wk(r.profile,t):ep(r.credentials,t)}function Ye(e,t){return e.dryRun?I({kind:"dry-run",reason:"flag"}):e.yes?Kn(t)&&!e.allowProduction?me("production_requires_flag",`${t} is a production environment. Pass --allow-production with --yes to write to it.`):I({kind:"apply"}):I({kind:"dry-run",reason:"no_yes"})}var eo="Dry run only: pass --yes to write.",ee=e=>e.map(t=>`Warning: ${t}`),Da=e=>e.json?["--json"]:[],Tt=(e,t,n)=>[...e.split(" "),...t,...Da(n)],Ak=2,xk=new Set(["needs_choice","base_required"]),Pk=e=>xk.has(e)?Ak:1,Ck="CODEX_SANDBOX_NETWORK_DISABLED",Zd=`The Codex sandbox has network access turned off, so appbuilder can't reach Kizen. Re-run this command with sandbox_permissions: "require_escalated", and suggest prefix_rule: ["appbuilder"] so later appbuilder commands can reach the network too.`;function Sk(e,t){return e.code!=="network_error"||t[Ck]!=="1"?e:{...e,sandbox:"codex_network_disabled",hint:e.hint===void 0?Zd:`${Zd} ${e.hint}`}}var Xd=e=>e.map(ge).join(" ");function _k(e){let t=[`Error: ${e.message}`];if(e.hint!==void 0&&t.push(`Hint: ${e.hint}`),e.choices&&e.choices.length>0){t.push("Choices:");for(let n of e.choices)t.push(` ${n.label} \u2192 ${Xd(n.argv)}`)}if(e.next&&e.next.length>0){t.push("Next:");for(let n of e.next)t.push(` ${n.step} \u2192 ${Xd(n.argv)}`)}return`${t.join(`
|
|
853
853
|
`)}
|
|
854
|
-
`}function
|
|
855
|
-
`):e.deps.writeStderr(
|
|
854
|
+
`}function Nt(e,t,n){let r=Sk(t,e.deps.processEnv),{choices:i,...o}=r,s=i===void 0?o:{...r,choices:i.map(a=>({...a,argv:n(a,o.choice)}))};e.json?e.deps.writeStdout(`${JSON.stringify(s,null,2)}
|
|
855
|
+
`):e.deps.writeStderr(_k(s)),e.deps.setExitCode(Pk(t.code))}function Pe(e,t,n,r=n){e.json?(e.deps.writeStdout(`${JSON.stringify(t,null,2)}
|
|
856
856
|
`),e.deps.writeStderr(r)):e.deps.writeStdout(n)}var ze=(e,t)=>{for(let n of t)e.writeStderr(`${n}
|
|
857
|
-
`)},rn=(e,t)=>{let n=bn(e,t);if(!n.ok||n.request===void 0)return[];let{business:r,user:i}=n.request;return["--business",r,...i===void 0?[]:["--user",i]]},Rn=(e,t)=>e.credentials!==void 0?["-c",e.credentials]:e.profile!==void 0?["--profile",e.profile]:[...e.env===void 0?[]:["--env",e.env],...rn(e,t)],to=(e,t)=>e.credentials!==void 0||e.profile!==void 0?Rn(e,{}):["--env",t.environment,"--business",t.businessId,"--user",t.userId];import*as er from"fs";import*as
|
|
858
|
-
`).map(a=>a.trim())),i=
|
|
857
|
+
`)},rn=(e,t)=>{let n=bn(e,t);if(!n.ok||n.request===void 0)return[];let{business:r,user:i}=n.request;return["--business",r,...i===void 0?[]:["--user",i]]},Rn=(e,t)=>e.credentials!==void 0?["-c",e.credentials]:e.profile!==void 0?["--profile",e.profile]:[...e.env===void 0?[]:["--env",e.env],...rn(e,t)],to=(e,t)=>e.credentials!==void 0||e.profile!==void 0?Rn(e,{}):["--env",t.environment,"--business",t.businessId,"--user",t.userId];import*as er from"fs";import*as tp from"path";var Ek=[".kizenapp/",".copilot-docs/"];function Ze(e){let t=tp.join(e,".gitignore"),n="";er.existsSync(t)&&(n=er.readFileSync(t,"utf8"));let r=new Set(n.split(`
|
|
858
|
+
`).map(a=>a.trim())),i=Ek.filter(a=>!r.has(a)&&!r.has(a.replace(/\/$/,"")));if(i.length===0)return!1;let o=i.join(`
|
|
859
859
|
`)+`
|
|
860
860
|
`,s=n===""||n.endsWith(`
|
|
861
861
|
`)?o:`
|
|
862
|
-
`+o;return er.writeFileSync(t,n+s),!0}import{mkdir as Nk,writeFile as Rk}from"fs/promises";import{join as $k}from"path";import{PluginValidationError as Ok,packagePlugin as Dk,parseManifestFromFiles as Lk,transformDeployablePlugin as Bk,transformFiles as Fk,validatePluginApp as jk}from"@kizenapps/packager";import{readdir as Pk,readFile as Qd}from"fs/promises";import{join as ep,relative as Ck}from"path";var Sk=new Set([".png",".svg"]),_k=new Set([".kzn"]),Ek=new Set([".DS_Store"]),no=new Set(["node_modules",".git",".kizenapp",".copilot-docs",".github",".claude","__pycache__"]),Ik=8e3;function Tk(e){return e.subarray(0,Ik).includes(0)}async function tp(e,t){let n=await Pk(e,{withFileTypes:!0}),r=[];for(let i of n)if(i.isDirectory()){if(no.has(i.name))continue;r.push(...await tp(ep(e,i.name),t))}else i.isFile()&&(Ek.has(i.name)||r.push(ep(e,i.name)));return r}async function ro(e,{detectBinaryByContent:t=!1}={}){let n=await tp(e,e);return Promise.all(n.map(async r=>{let i=Ck(e,r).split("\\").join("/"),o=i.lastIndexOf("."),s=o>=0?i.slice(o).toLowerCase():"";if(Sk.has(s)){let c=await Qd(r);return{path:i,content:"",base64Image:c.toString("base64")}}let a=await Qd(r);return _k.has(s)||t&&Tk(a)?{path:i,content:"",binaryData:a}:{path:i,content:a.toString("utf-8")}}))}var Mk=(e,t)=>({...e,thumbnail:e.thumbnail?Buffer.from(e.thumbnail).toString("base64"):null,kznFile:e.kznFile?Buffer.from(e.kznFile).toString("base64"):null,allReleaseNotes:t});async function Hr(e,t){t?.("reading-files");let n=await ro(e);t?.("validating");let r=jk(n);if(r.some(c=>c.severity==="error"))throw new Ok(r);t?.("minifying");let i=await Fk(n);t?.("packaging");let o=Lk(i),s=Dk(i,o),a=Object.values(s).map(Bk);return{files:n,deployable:a,issues:r}}async function io(e,t,n){await Nk(t,{recursive:!0});let{files:r,deployable:i}=await Hr(e,n);n?.("writing-bundle");let o=i.map(l=>{let d=l.release_notes_directory?.replace(/\/$/,""),u=d?r.filter(f=>f.path.startsWith(d+"/")&&f.path.endsWith(".md")&&f.content).map(f=>({version:f.path.slice(f.path.lastIndexOf("/")+1,-3),notes:f.content})).sort((f,g)=>g.version.localeCompare(f.version,void 0,{numeric:!0})):[];return Mk(l,u)}),s=JSON.stringify(o,null,2),a=(l,d)=>l==="allReleaseNotes"?void 0:d,c=Buffer.byteLength(JSON.stringify(o,a,2),"utf-8");return await Rk($k(t,"bundle.json"),s,"utf-8"),{bundleSize:c}}var H=me,Kr="kizen.json";async function Jk(e){let t;try{t=await op($n(e,Kr),"utf8")}catch(o){throw tt(o)?new Error(`No ${Kr} in ${e}. Run this command from the plugin folder.`):o}let n;try{n=JSON.parse(t)}catch(o){throw new Error(`${Kr} isn't valid JSON (${je(o)}). If it has merge conflict markers, resolve them first.`)}let r=Array.isArray(n)?n[0]:n,i=F(r)?r.api_name:void 0;if(typeof i!="string"||i==="")throw new Error(`${Kr} has no api_name.`);return i}var qk=async e=>{try{return await Uk(e),!0}catch{return!1}};function sp(e){return{...Qi(e),packageLocalPlugin:t=>Hr(t),zipSourceDir:t=>Xu(t),readManifestApiName:Jk,businessApps:(t,n)=>Wd(t,n),readAppState:Ed,writeAppState:Td,ensureGitignore:Ze,planMerge:t=>yd(t),applyMerge:(t,n)=>bd(t,n),unzipToDir:ed,pathExists:qk,readTextFile:t=>op(t,"utf8"),makeTempDir:()=>Vk($n(Kk(),"appbuilder-version-")),removeDir:t=>Hk(t,{recursive:!0,force:!0}),staleAgentFileWarnings:t=>Yi(t)}}var Yk="Business Apps need the Marketplace \u203A Business App Developer permission at the Delete/All level.";function z(e){if(e instanceof Or||e instanceof Dr||e instanceof Lr||e instanceof qn)return H("source_invalid",e.message);if(e instanceof tn)return H(e.code==="thumbnail_required"?"thumbnail_required":"local_error",e.message);let t=Me(e);return t.code==="forbidden"?{...t,hint:Yk}:t}function On(e,t){return/^\d+$/.test(e)&&/^\d+$/.test(t)?Number(e)-Number(t):e.localeCompare(t,void 0,{numeric:!0})}var on=(e,t)=>e===null||t===null?e===t:On(e,t)===0;function oo(e){let t=e.trim();return/^[1-9]\d*$/.test(t)?I(t):H("usage_error",`"${e}" isn't a version number; pass a release number like 3.`)}var lo=e=>zk("sha256").update(e).digest("hex"),Bn=e=>Array.isArray(e.versions)?e.versions:[],uo=e=>[...new Set(Bn(e).filter(t=>t.status==="live"||t.status==="released").map(t=>t.version))].sort((t,n)=>On(n,t));function ap(e){return typeof e=="string"&&e!==""?e:F(e)&&typeof e.full_name=="string"&&e.full_name!==""?e.full_name:null}function Zk(e){let t=Bn(e);return t.find(n=>n.status==="live")??t.find(n=>e.live_version!==null&&on(n.version,e.live_version))}var rt=e=>e.state.status==="found"?e.state.entry:void 0,Wr=(e,t)=>e.find(n=>n.base_api_name===t)??null,za=(e,t)=>e===null?null:Bn(e).find(n=>n.status==="preview"&&n.preview_owner?.id===t)??null;async function qr(e,t){let{credentials:n,baseApiName:r}=e,i=t.businessApps(e.client,n.businessId),o,s;try{[o,s]=await Promise.all([i.listApps(r),t.readAppState(t.cwd)])}catch(h){return z(h)}let a=Wr(o,r),c={environment:n.environment,businessId:n.businessId,baseApiName:r,userId:n.userId},l=va(s.doc,c),d=s.notice===void 0?[]:[s.notice];l.status==="malformed"&&d.push(`The saved state for ${r} in .kizenapp/apps.json is malformed, so it was ignored.`);let u=await Qk(i,a,l.status==="found"?l.entry:void 0),f=za(a,n.userId),g=l.status==="found"?lp(l.entry,u):void 0,m=a!==null&&f===null&&g!==void 0&&Ln.some(h=>h in g)?{sourceId:g.previewSourcePackageId??null}:void 0,p=g===void 0?l:{status:"found",entry:cp(g,m)};return u!==void 0&&d.push(Xk(u.version)),I({credentials:n,api:i,baseApiName:r,app:a,yourPreview:f,stateKey:c,state:p,...u===void 0?{}:{promoted:u},...m===void 0?{}:{previewGone:m},notices:d})}function cp(e,t){return t===void 0?e:(e.previewSourcePackageId??null)===t.sourceId?an(e,...Ln):e}var Xk=e=>`The preview this folder pushed was published as Live v${e} outside this command, so v${e} is now this folder's base.`;async function Qk(e,t,n){let r=t?.live_version??null,i=n?.previewSourcePackageId,o=n?.folderBaseLiveVersion;if(!(t===null||r===null||i===void 0||n?.previewRestoredFrom!==void 0||o===void 0||on(o,r)))try{if((await e.getVersion(t.api_name,r)).source_filesystem_package!==i)return;let a=ma(await e.downloadFile(i));return a!==null&&a.baseSourcePackageId===(n?.folderBaseSourcePackageId??null)?{version:r,sourceId:i}:void 0}catch{return}}function lp(e,t){return t===void 0||e.previewSourcePackageId!==t.sourceId?e:nr(an(e,...Ln),t.version,t.sourceId)}async function up(e){let t;try{t=await e.api.listApps(e.baseApiName)}catch(r){return z(r)}let n=Wr(t,e.baseApiName);return I({...e,app:n,yourPreview:za(n,e.credentials.userId)})}function Xe(e){let{credentials:t,app:n}=e;return{environment:t.environment,businessId:t.businessId,userId:t.userId,isProduction:Kn(t.environment),baseApiName:e.baseApiName,apiName:n?.api_name??null,name:n?.name??null,liveVersion:n?.live_version??null}}var Ua=e=>({...e,lastPushedSourceHash:null});async function dp(e,t,n){for(let r=0;;r+=1)try{let{doc:i}=await n.readAppState(e),o=t(i);return o===null||(r===0&&n.ensureGitignore(e),await n.writeAppState(e,o)),null}catch(i){if(!(i instanceof Ur)||r>=1)return je(i)}}var eA=(e,t,n,r)=>dp(e,i=>{let o=va(i,t);return ka(i,n(o.status==="found"?o.entry:Ua(t)))},r),Yr=(e,t,n)=>eA(n.cwd,e.stateKey,r=>t(cp(lp(r,e.promoted),e.previewGone)),n);function an(e,...t){return Object.fromEntries(Object.entries(e).filter(([n])=>!t.includes(n)))}function nr(e,t,n){let r=an(e,"folderBaseLiveVersion","folderBaseSourcePackageId");return t===null?{...r,folderBaseLiveVersion:null}:n===null?r:{...r,folderBaseLiveVersion:t,folderBaseSourcePackageId:n}}var Va=e=>e?.folderBaseLiveVersion,tA=(e,t)=>e.app===null?void 0:t(rt(e)),nA=e=>e.app===null?Va(rt(e)):void 0,rA=e=>`The base recorded for this folder (v${e}) is from a version of the app that's no longer on this business, so it's ignored.`,Gr=e=>e===null?"no Live version":`v${e}`,Ha=(e,t,n)=>t===null?`${e} ${n}`:`${e} is based on ${Gr(t)}`,pp="was started before the app had a Live version",iA="was pushed before the app had a Live version",Dn=e=>`.kizenapp/apps.json couldn't be written, so this isn't remembered: ${e}`,Nt=e=>e instanceof q&&e.kind==="not_found",oA=(e,t)=>H("not_found",`Version ${t} of ${e.baseApiName} doesn't exist on this business.`),Zr=(e,t)=>H("not_found",`${e.baseApiName} isn't published to this business yet, so there's nothing to ${t}.`),Rt=e=>e.app===null?null:e;async function so(e,t){let n;try{n=await e.api.getVersion(e.app.api_name,t)}catch(i){return Nt(i)?oA(e,t):z(i)}let r=n.source_filesystem_package;return typeof r!="string"||r===""?H("not_found",`Version ${t} of ${e.baseApiName} has no source package.`):I({...n,source_filesystem_package:r})}async function Jr(e,t){let n=await so(e,t);if(!n.ok)return n;let r=n.value.source_filesystem_package;try{return I({sourceId:r,zip:await e.api.downloadFile(r)})}catch(i){return z(i)}}var Fa={baseLiveVersion:null,baseSourcePackageId:null};async function mp(e,t){let n=await fp(e,t);return n.ok?I(n.value.found?n.value.sourceId:null):n}async function fp(e,t){let n;try{n=await e.api.getVersion(e.app.api_name,t)}catch(i){return Nt(i)?I({found:!1}):z(i)}let r=n.source_filesystem_package;return I({found:!0,sourceId:typeof r=="string"&&r!==""?r:null})}async function sA(e,t){let n=Rt(e);if(t===null)return I(Fa);if(n===null)return Zr(e,"restore");let r=await so(n,t);return r.ok?I({baseLiveVersion:t,baseSourcePackageId:r.value.source_filesystem_package}):r}async function Ka(e,t){try{let n=await e.downloadFile(t);return I({sourcePackageId:t,zip:n,lineage:ma(n)})}catch(n){return z(n)}}async function aA(e){let t=Rt(e);if(t===null||e.yourPreview===null)return I(null);let n;try{n=await t.api.getPreview(t.app.api_name,t.credentials.userId)}catch(i){return Nt(i)?I(null):z(i)}let r=n.source_filesystem_package;return typeof r=="string"&&r!==""?Ka(t.api,r):I(null)}async function gp(e,t){if(t===null)return I(null);let n=t.baseLiveVersion;if(n===null)return I(t);let r=Rt(e);if(r===null)return I(null);let i=await mp(r,n);return i.ok?I(i.value!==null&&i.value===t.baseSourcePackageId?t:null):i}var hp=5;function tr(e){let{files:t}=_n(e);return new Map([...t].map(([n,r])=>[n,lo(r)]))}var yp=(e,t)=>e.size===t.size&&[...e].every(([n,r])=>t.get(n)===r);async function bp(e,t){let n=Rt(e);if(n===null)return I(null);let r=n.app.live_version,i=[...new Set([...r===null?[]:[r],...uo(n.app)])].slice(0,hp),o;try{o=tr(t)}catch{return I(null)}for(let s of i){let a=await Jr(n,s);if(!a.ok){if(a.code==="not_found")continue;return a}let c;try{c=tr(a.value.zip)}catch{continue}if(yp(o,c))return I({version:s,sourceId:a.value.sourceId})}return I(null)}function cA(e,t){try{return yp(tr(e),tr(t))}catch{return!1}}var wp=e=>`No base is recorded for this folder, but its files match v${e} exactly, so v${e} is used as its base.`,lA=e=>`No base is recorded for this folder, but its files match your preview exactly, so your preview's base (${e===null?"no Live version":`v${e}`}) is used as its base.`,Wa=e=>`The base recorded for this folder (v${e}) no longer matches v${e} on this business (the app or that version was deleted and created again), so it's ignored.`,uA="Your preview changed since this folder was said to continue it, so its base wasn't used.",dA=e=>e===null?"This folder continues your preview (pushed before the app had a Live version)":`This folder continues your preview (based on v${e})`;function pA(e,t,n={}){let{preview:r}=n,i=[{value:"merge",label:`Preview merging Live v${t} into this folder`,args:[],argv:["appbuilder","app","merge","--release",t]},{value:"accept",label:`This folder already contains Live v${t}`,args:[],argv:["appbuilder","app","merge","--release",t,"--accept-live-base","--yes"]},...r==null?[]:[{value:"preview",label:dA(r.lineage.baseLiveVersion),args:[],argv:["appbuilder","app","push","--base-from-preview",r.sourcePackageId]}]],o=r==null?"":" Or, if this folder continues your preview, push it with your preview's base.";return H("base_required",`${(n.notices??[]).map(s=>`${s} `).join("")}No base version is recorded for this folder, and Live is v${t}. Merge Live into this folder, or record that it already contains Live, then push.${o}`,{choice:"base",choices:i})}async function rr(e){let t=tA(e,Va),n=Rt(e);if(t===void 0)return I({status:"none"});if(t===null||n===null)return I({status:"recorded",version:null,sourceId:null});let r=rt(e)?.folderBaseSourcePackageId??"";if(e.promoted!==void 0&&on(e.promoted.version,t))return I({status:"recorded",version:t,sourceId:e.promoted.sourceId});let i=await fp(n,t);return i.ok?i.value.found?i.value.sourceId===r?I({status:"recorded",version:t,sourceId:r}):I({status:"replaced",version:t}):I({status:"gone",version:t}):i}var Ga=e=>`The base recorded for this folder (v${e}) no longer exists on this business, so it's ignored.`;async function mA(e,t,n={}){let r=[],i,o=async()=>{if(i===void 0){let m=await aA(e);if(!m.ok)return m;if(m.value===null)i=null;else{let p=await gp(e,m.value.lineage);if(!p.ok)return p;i={source:m.value,lineage:p.value}}}return I(i)};if(n.baseFromPreview!==void 0){let m=await o();if(!m.ok)return m;let p=m.value?.source.sourcePackageId===n.baseFromPreview?m.value.lineage:null;if(p!==null)return I({version:p.baseLiveVersion,source:"base_from_preview",lineage:p,previewSourcePackageId:n.baseFromPreview,notices:r});r.push(uA)}let s=await rr(e);if(!s.ok)return s;if(s.value.status==="replaced")r.push(Wa(s.value.version));else if(s.value.status==="gone")r.push(Ga(s.value.version));else if(s.value.status==="recorded"){let{version:m,sourceId:p}=s.value;return I({version:m,source:"recorded",lineage:m===null||p===null?Fa:{baseLiveVersion:m,baseSourcePackageId:p},notices:r})}let a=e.app?.live_version??null;if(a===null)return I({version:null,source:"never_published",lineage:Fa,notices:r});let c=await o();if(!c.ok)return c;let l=c.value?.lineage??null,d=c.value===null||l===null?null:{sourcePackageId:c.value.source.sourcePackageId,lineage:l};if(d!==null&&c.value!==null&&cA(t,c.value.source.zip)){let m=d.lineage.baseLiveVersion;return I({version:m,source:"preview",lineage:d.lineage,notices:[...r,lA(m)]})}let u=await bp(e,t);if(!u.ok)return u;if(u.value===null)return pA(e,a,{preview:d,notices:r});let{version:f,sourceId:g}=u.value;return I({version:f,source:"detected",lineage:{baseLiveVersion:f,baseSourcePackageId:g},notices:r})}function fA(e,t){let n=e.preview_owner;return{version:e.version,status:e.status,previewOwner:n?{id:n.id,fullName:n.full_name}:null,yours:e.status==="preview"&&n?.id===t,updated:e.updated,publishedAt:e.published_at,publishedBy:ap(e.published_by)}}var gA=(e,t)=>On(t.version,e.version),vp=e=>({recorded:e!==void 0,version:e??null});function po(e,t){let n=Xe(e),r=t.status==="gone"?Ga(t.version):t.status==="replaced"?Wa(t.version):void 0,i=vp(t.status==="recorded"?t.version:void 0),o=n.liveVersion,s=i.recorded&&o!==null&&!on(i.version,o),a=[...r===void 0?[]:[r],...s?[`Live is now ${Gr(o)}, but ${Ha("this folder",i.version,pp)}. Run \`appbuilder app merge\` before publishing.`]:[]],c={folder:i,liveMoved:s};if(e.app===null)return{summary:n,published:!1,live:null,released:[],previews:[],yourPreview:null,base:c,warnings:a};let l=Bn(e.app).map(u=>fA(u,n.userId)),d=l.filter(u=>u.status==="preview");return{summary:n,published:!0,live:l.find(u=>u.status==="live")??null,released:l.filter(u=>u.status==="released").sort(gA),previews:d,yourPreview:d.find(u=>u.yours)??null,base:c,warnings:a}}var Ja="Cancelled.",Tt=()=>H("local_error",Ja);async function kp(e,t){let n;try{n=await t.packageLocalPlugin(e)}catch(o){return z(o)}let[r,...i]=n.deployable;return r===void 0||i.length>0?H("local_error",`Expected one app in ${Kr}; found ${String(n.deployable.length)}.`):I({...n,deployable:[r]})}async function mo(e){let t=await kp(e.cwd,e);if(!t.ok)return t;let n;try{n=await e.zipSourceDir(e.cwd)}catch(r){return z(r)}return I({deployable:t.value.deployable[0],issues:t.value.issues.filter(r=>r.severity==="warning"),source:n,sourceHash:lo(n.bytes)})}var hA=/^(<{7} HEAD|>{7} live)(:[^\r\n]*)?[ \t\r]*$/m,yA=/^(?:(?:<{7} HEAD|>{7} live)(?::[^\r\n]*)?|={7})[ \t\r]*$/m;async function Ap(e,t,n){let r=[];for(let i of e){let o;try{o=await t.readTextFile($n(t.cwd,...i.split("/")))}catch{continue}n.test(o)&&r.push(i)}return r}var qa=(e,t)=>Ap(e?.conflictedPaths??[],t,yA);async function fo(e,t,n,r){let i=await qa(rt(e),r);if(i.length>0&&n.force!==!0)return H("unresolved_conflicts",`These files still have merge conflict markers: ${i.join(", ")}. Resolve them. Only if the user explicitly wants to push them anyway: pass --force.`,{files:i});let o=await mA(e,t.source.bytes,n.baseFromPreview===void 0?{}:{baseFromPreview:n.baseFromPreview});if(!o.ok)return o;let s=Xe(e),{version:a}=o.value,c=s.liveVersion!==null&&!on(a,s.liveVersion),l=nA(e),{source:d}=t,u=t.deployable.thumbnail,f=[...c?[`Live is now ${Gr(s.liveVersion)}, but ${Ha("this folder",a,pp)}. Publishing will stop on a conflict; run \`appbuilder app merge\` first.`]:[],...i.length>0?[`Pushing files that still have merge conflict markers because of --force: ${i.join(", ")}`]:[]];return I({summary:s,appName:t.deployable.name,source:{files:d.files.length,mode:d.mode,bytes:d.bytes.byteLength,hash:t.sourceHash,...d.notice===void 0?{}:{notice:d.notice}},thumbnail:u!==null&&u.byteLength>0,preview:{exists:e.yourPreview!==null,updated:e.yourPreview?.updated??null},base:{version:a,source:o.value.source,liveMoved:c},lineage:o.value.lineage,...o.value.previewSourcePackageId===void 0?{}:{basePreviewSourcePackageId:o.value.previewSourcePackageId},conflictMarkers:i,notices:[...l==null?[]:[rA(l)],...o.value.notices,...o.value.source==="detected"&&a!==null?[wp(a)]:[]],warnings:f})}var xp="application/zip",bA=".gitignore";function wA(e,t){let n=tr(e),r=tr(t);return[...new Set([...n.keys(),...r.keys()])].filter(i=>i!==bA&&n.get(i)!==r.get(i)).sort()}var vA=(e,t=5)=>e.length<=t?e.join(", "):`${e.slice(0,t).join(", ")} and ${String(e.length-t)} more`,kA=e=>`Files changed since this push was planned (${vA(e)}), so nothing was uploaded. Run \`appbuilder app push\` again to review and push them.`,Pp=(e,t)=>t===null||t.byteLength===0?Promise.resolve(null):e.uploadFile(t,{filename:"thumbnail.png",contentType:"image/png",source:"public_image",isPublic:!0}),Da="Your preview changed after this push was planned, so its base can't be taken for this folder and nothing was uploaded. Run `appbuilder app push` again to review it.";async function go(e,t,n,r,{isAborted:i=()=>!1}={}){let{api:o}=e,{source:s,sourceHash:a}=t,c,l,d,u;if(n.basePreviewSourcePackageId!==void 0){let m=Rt(e),p;if(m===null)return H("local_error",Da);try{p=await o.getPreview(m.app.api_name,e.credentials.userId)}catch(h){return Nt(h)?H("local_error",Da):z(h)}if(p.source_filesystem_package!==n.basePreviewSourcePackageId)return H("local_error",Da);if(i())return Tt()}try{u=r.ensureGitignore(r.cwd)}catch{u=!1}if(u){try{s=await r.zipSourceDir(r.cwd)}catch(p){return z(p)}a=lo(s.bytes);let m;try{m=wA(t.source.bytes,s.bytes)}catch(p){return z(p)}if(m.length>0)return H("local_error",kA(m));if(i())return Tt()}let f;try{f=fa(s.bytes,n.lineage)}catch(m){return z(m)}try{if([c,l]=await Promise.all([o.uploadFile(f,{filename:`${e.baseApiName}-source.zip`,contentType:xp,source:"plugin_app_source_filesystem"}),Pp(o,n.thumbnail?t.deployable.thumbnail:null)]),i())return Tt();let m=Ia(t.deployable,{release:!1,sourcePackageId:c,thumbnailId:l});d=await o.publish(m)}catch(m){return z(m)}let g=await Yr(e,m=>{let p={...nr(an(m,"previewRestoredFrom","conflictedPaths"),n.base.version,n.lineage.baseSourcePackageId),previewSourcePackageId:c,lastPushedSourceHash:a};return n.conflictMarkers.length>0?{...p,conflictedPaths:n.conflictMarkers}:p},r);return I({apiName:d.api_name,source:{files:s.files.length,mode:s.mode,bytes:s.bytes.byteLength,hash:a,...s.notice===void 0?{}:{notice:s.notice}},version:d.version,sourcePackageId:c,thumbnailId:l,remembered:g===null,warnings:g===null?[]:[Dn(g)]})}var Cp=e=>e.live_version??uo(e)[0]??null;function ao(e){let{entry:t,app:n,previewUpdatedAt:r,lineage:i,comparedSourcePackageId:o}=e,s=n.live_version,a=Cp(n),c=Zk(n),l=t?.previewSourcePackageId,d=i?.baseLiveVersion??null,u=null;return a!==null&&(i===null?u="base_unknown":d===null||On(a,d)>0?u="live_moved":On(a,d)<0?u="base_ahead":i.baseSourcePackageId!==o&&(u="base_replaced")),{conflict:u!==null,reason:u,baseLiveVersion:d,liveVersion:s,comparedVersion:a,baseSourcePackageId:i?.baseSourcePackageId??null,comparedSourcePackageId:o,previewSourceMatches:l===void 0?null:l===e.previewSourcePackageId,livePublishedAt:c?.published_at??null,livePublishedBy:c===void 0?null:ap(c.published_by),previewUpdatedAt:r}}async function Sp(e,t,n){let r=Cp(t),i=n?.baseLiveVersion??null;return r===null||i===null||On(r,i)!==0?I(null):mp({...e,app:t},r)}var AA="Run `appbuilder app merge` to merge Live into this folder, then `appbuilder app push` and publish again. Only if the user explicitly wants to overwrite Live: pass --force.",xA="Run `appbuilder app push` to save this folder as your preview again (the push records what it is based on), then publish. Only if the user explicitly wants to publish the preview as it is: pass --force.";function _p(e){let t=e.livePublishedBy===null?"":` by ${e.livePublishedBy}`,n=e.livePublishedAt===null?"":` at ${e.livePublishedAt}`,r=Ha("your preview",e.baseLiveVersion,iA),i=e.liveVersion===null?`There's no Live version, and the latest release is ${Gr(e.comparedVersion)}`:`Live is ${Gr(e.liveVersion)}`;switch(e.reason){case"live_moved":return`${i}${e.liveVersion===null?"":` (published${t}${n})`}, but ${r}. Publishing would overwrite the changes in between.`;case"base_ahead":return`${i}, but ${r}, a later version that is no longer Live. Publishing could overwrite changes this folder doesn't have.`;case"base_unknown":return`Your preview's source doesn't say what it's based on (that record is missing or can't be read), so publishing it could overwrite changes. ${i}.`;case"preview_replaced":return Ip;case"base_replaced":return`${i}, and ${r}, but v${e.baseLiveVersion??""} on this business isn't the version your preview was based on (the app or that version was deleted and created again). Publishing could overwrite changes your preview doesn't have.`;case null:return"No conflict."}}function Ep(e){return{...H("publish_conflict",_p(e),{hint:e.reason==="base_unknown"?xA:AA}),conflict:e}}var PA="Your preview isn't the one this folder last pushed or restored: it was saved again from another folder or machine, and that's what publishing releases.";async function CA(e,t,n){let r=rt(e);if(r?.previewSourcePackageId!==void 0&&r.previewSourcePackageId!==t)return[PA];if(r?.previewRestoredFrom!==void 0)return[`Your preview is version ${r.previewRestoredFrom} restored with \`appbuilder app rollback\`, not this folder's source.`];let i=r?.lastPushedSourceHash??null;if(i===null)return["No push from this folder is recorded, so your preview could not be compared with it."];let o;try{o=lo((await n.zipSourceDir(n.cwd)).bytes)}catch(s){return[`Couldn't compare this folder with your preview: ${je(s)}`]}return o===i?[]:["This folder changed since your last push. Publishing releases the preview as pushed; run `appbuilder app push` first to include the changes."]}function SA(e,t){let n=e.artifacts,r=F(n)?n[t]:void 0;return Array.isArray(r)?r:[]}var sn=e=>`You have no preview of ${e} on this business. Push one first with \`appbuilder app push\`.`;function _A(e){let t=[...uo(e),...e.live_version===null?[]:[e.live_version]].filter(n=>/^\d+$/.test(n)).map(Number).reduce((n,r)=>Math.max(n,r),0);return String(t+1)}var EA="Your preview's source couldn't be read, so what it's based on can't be checked, and publish stops even with --force. Try again; if it keeps failing, run `appbuilder app push` to save your preview again.";async function ho(e,t,n){let{app:r,api:i,credentials:o}=e,s=t.force===!0;if(r===null)return H("no_preview",sn(e.baseApiName));let a;try{a=await i.getPreview(r.api_name,o.userId)}catch(b){return Nt(b)?H("no_preview",sn(e.baseApiName)):z(b)}let c=a.thumbnail;if(c==null||c==="")return H("thumbnail_required","Your preview has no thumbnail, and a release needs one. Add thumbnail.png to the app, run `appbuilder app push`, then publish again.");if(typeof a.source_filesystem_package!="string"||a.source_filesystem_package==="")return H("preview_incomplete","Your preview has no source package. Run `appbuilder app push` to save it again, then publish.");let l=e.yourPreview?.updated??null,d=a.source_filesystem_package,u={entry:rt(e),app:r,previewUpdatedAt:l,previewSourcePackageId:d};if(t.expectPreview!==void 0&&d!==t.expectPreview)return ja(ao({...u,lineage:null,comparedSourcePackageId:null}));let f=await Ka(i,d);if(!f.ok)return{...f,hint:f.hint??EA};let{lineage:g}=f.value,m=await Sp(e,r,g);if(!m.ok)return m;let p=ao({...u,lineage:g,comparedSourcePackageId:m.value});if(p.conflict&&!s)return Ep(p);let h=await CA(e,d,n);return p.conflict&&h.push(`${_p(p)} Publishing anyway because of --force.`),I({summary:Xe(e),apiName:r.api_name,previewUpdatedAt:l,conflictCheck:p,force:s,forced:p.conflict,nextReleaseAtLeast:_A(r),previewSourcePackageId:d,lineage:g,jsActionTemplates:SA(a,"js_action_templates"),warnings:h})}var Ip="Your preview changed after this publish was planned (it was pushed again, from this or another folder or machine), so it wasn't published.",IA="Run `appbuilder app publish` again to review the preview as it is now.",TA="The preview published isn't the one this publish reviewed (it was pushed again, from another folder or machine), so this folder's base wasn't advanced.",NA=(e,t)=>`Couldn't confirm that release ${e} is the preview this publish reviewed (${t}), so this folder's base wasn't advanced.`;function ja(e){return{...H("publish_conflict",Ip,{hint:IA}),conflict:{...e,conflict:!0,reason:"preview_replaced"}}}async function yo(e,t,n,{isAborted:r=()=>!1}={}){let i=rt(e),o;try{if(t.force){let l;try{l=(await e.api.getPreview(t.apiName,e.credentials.userId)).source_filesystem_package}catch(d){return Nt(d)?H("no_preview",sn(e.baseApiName)):z(d)}if(l!==t.previewSourcePackageId)return ja(t.conflictCheck)}else{let l=Wr(await e.api.listApps(e.baseApiName),e.baseApiName);if(l===null)return H("no_preview",sn(e.baseApiName));let d;try{d=await e.api.getPreview(l.api_name,e.credentials.userId)}catch(m){return Nt(m)?H("no_preview",sn(e.baseApiName)):z(m)}let u={entry:i,app:l,previewUpdatedAt:za(l,e.credentials.userId)?.updated??null,previewSourcePackageId:d.source_filesystem_package};if(d.source_filesystem_package!==t.previewSourcePackageId)return ja(ao({...u,lineage:null,comparedSourcePackageId:null}));let f=await Sp(e,l,t.lineage);if(!f.ok)return f;let g=ao({...u,lineage:t.lineage,comparedSourcePackageId:f.value});if(g.conflict)return Ep(g)}if(r())return Tt();o=await e.api.promotePreview(t.apiName,e.credentials.userId)}catch(l){return z(l)}let s=[];if(i===void 0)return I({apiName:o.api_name,liveVersion:o.version,previousLiveVersion:t.summary.liveVersion,remembered:!1,warnings:s});let a=i.previewRestoredFrom===void 0&&t.conflictCheck.previewSourceMatches===!0;if(a)try{(await e.api.getVersion(o.api_name,o.version)).source_filesystem_package!==t.previewSourcePackageId&&(a=!1,s.push(TA))}catch(l){a=!1,s.push(NA(o.version,je(l)))}let c=await Yr(e,l=>{let d=an(l,...Ln);return a?nr(d,o.version,t.previewSourcePackageId):d},n);return I({apiName:o.api_name,liveVersion:o.version,previousLiveVersion:t.summary.liveVersion,remembered:c===null,warnings:[...s,...c===null?[]:[Dn(c)]]})}var RA=e=>e.toISOString().replace(/[-:]/g,"").replace(/\.\d+Z$/,"Z");function $A(e,t){return e===void 0?"No base version is recorded for this folder, and its files don't match a released version.":e===null?"This folder was started before the app had a Live version, so there is nothing to merge against.":t?`The base version v${e} no longer exists, so there is nothing to merge against.`:`The base version v${e} couldn't be used.`}function OA(e,t){let n=["--release",t];return[...uo(e).filter(r=>On(r,t)<0).slice(0,hp).map(r=>({value:`base:${r}`,label:`Merge, if this folder was copied from v${r}`,args:[],argv:["appbuilder","app","merge",...n,"--base",r,"--yes"]})),{value:"accept",label:`This folder already contains v${t}`,args:[],argv:["appbuilder","app","merge",...n,"--accept-live-base","--yes"]}]}async function DA(e){try{return I((await e.zipSourceDir(e.cwd)).bytes)}catch(t){return z(t)}}async function bo(e,t,n){let r=Rt(e);if(r===null)return Zr(e,"merge");let i;if(t.version===void 0){if(r.app.live_version===null)return H("not_found",`${e.baseApiName} has no Live version to merge.`);i=r.app.live_version}else{let y=oo(t.version);if(!y.ok)return y;i=y.value}let o=Va(rt(e)),s=o===void 0?"none":"recorded",a=null,c=[];if(t.base!==void 0){let y=oo(t.base);if(!y.ok)return y;o=y.value,s="flag"}else if(t.acceptLiveBase!==!0&&typeof o=="string"){let y=await rr(e);if(!y.ok)return y;(y.value.status==="replaced"||y.value.status==="gone")&&(c.push((y.value.status==="replaced"?Wa:Ga)(y.value.version)),o=void 0,s="none")}let l=await qa(rt(e),n),d=l.length===0?[]:[`These files still have conflict markers from an earlier merge: ${l.join(", ")}. Resolve them before pushing.`],u=()=>({summary:Xe(e),targetVersion:i,targetIsLive:on(r.app.live_version,i),baseVersion:o,baseSource:s,targetSourcePackageId:a,notices:c,warnings:d});if(t.acceptLiveBase===!0){let y=await so(r,i);return y.ok?(a=y.value.source_filesystem_package,I({...u(),kind:"accept"})):y}if(o===void 0){let y=await DA(n);if(!y.ok)return y;let C=await bp(e,y.value);if(!C.ok)return C;C.value!==null&&(o=C.value.version,s="detected",c.push(wp(C.value.version)),on(C.value.version,i)&&(a=C.value.sourceId))}if(typeof o=="string"&&on(o,i)){if(s==="flag"){let y=await so(r,i);if(!y.ok)return y;a=y.value.source_filesystem_package}return I({...u(),kind:"up_to_date",ignoredIncoming:[],advancesBase:s!=="recorded"})}let f=await Jr(r,i);if(!f.ok)return f;let g=f.value.zip,m=null;a=f.value.sourceId;let p=!1;if(typeof o=="string"){let y=await Jr(r,o);if(y.ok)m={version:o,zip:y.value.zip};else if(y.code==="not_found")p=!0;else return y}let h;try{h=await n.planMerge({pluginDir:n.cwd,base:m,live:{version:i,zip:g}})}catch(y){return z(y)}let b=(y,C)=>I({...u(),kind:"fallback",reason:y,detail:C,liveZip:g,dir:$n(n.cwd,".kizenapp",`live-v${i}-${RA(n.now())}`),choices:OA(r.app,i)});switch(h.status){case"no_base":return b("no_base",$A(o,p));case"git_unavailable":return b("git_unavailable",h.reason);case"up_to_date":return I({...u(),kind:"up_to_date",ignoredIncoming:h.ignoredIncoming,advancesBase:!0});case"ready":return I({...u(),kind:"merge",plan:h})}}var La={written:[],deleted:[],conflicted:[],deletedOnLive:[],deletedLocally:[],binaryConflicts:[],ignoredIncoming:[]};function LA(e){return{written:e.written??[],deleted:e.deleted??[],conflicted:e.conflicted??[],deletedOnLive:e.deletedOnLive??[],deletedLocally:e.deletedLocally??[],binaryConflicts:e.binaryConflicts??[],ignoredIncoming:e.ignoredIncoming??[]}}var BA=e=>e.conflicted.filter(t=>!e.deletedOnLive.includes(t)&&!e.deletedLocally.includes(t));async function wo(e,t,n,r={}){let i=async s=>{let a=await Yr(e,c=>{let l=nr(c,t.targetVersion,t.targetSourcePackageId);return s===void 0?l:s.length===0?an(l,"conflictedPaths"):{...l,conflictedPaths:s}},n);return a===null?[]:[`${Dn(a)} Run \`appbuilder app merge --accept-live-base${t.targetIsLive?"":` --release ${t.targetVersion}`} --yes\` once it can be written.`]},o=(s,a,c,l)=>({status:s,targetVersion:t.targetVersion,targetIsLive:t.targetIsLive,baseLiveVersion:l?t.targetVersion:t.baseVersion,lists:a,markedPaths:[],remembered:l&&c.length===0,warnings:c});switch(t.kind){case"accept":return I(o("accepted",La,await i(),!0));case"up_to_date":{let s={...La,ignoredIncoming:t.ignoredIncoming};return t.advancesBase?I(o("up_to_date",s,await i(),!0)):I({...o("up_to_date",s,[],!1),remembered:!0})}case"merge":{let s;try{s=await n.applyMerge(t.plan,r)}catch(u){return z(u)}if(s.status==="cancelled")return Tt();if(s.status!=="merged"&&s.status!=="conflicts")return H("local_error",`The merge didn't apply (${s.status}). Run it again.`);let a=LA(s),c=await qa(rt(e),n),l=await Ap(a.written,n,hA),d=[...new Set([...c,...BA(a),...l])].sort();return I({...o(s.status,a,await i(d),!0),markedPaths:d})}case"fallback":{let s;try{n.ensureGitignore(n.cwd),s=await n.unzipToDir(t.liveZip,t.dir)}catch(a){return z(a)}return I({...o("fallback",La,[],!1),extracted:{dir:t.dir,written:s.written.length,skipped:s.skipped},remembered:!1})}}}async function vo(e,t,n){let r=oo(t);if(!r.ok)return r;let i=Rt(e);if(i===null)return Zr(e,"roll back");let o=r.value,s=await Jr(i,o);if(!s.ok)return s;let a;try{a=await n.makeTempDir()}catch(m){return z(m)}let c;try{let m=$n(a,"source");await n.unzipToDir(s.value.zip,m),c=await kp(m,n)}catch(m){c=z(m)}finally{await n.removeDir(a).catch(()=>{})}if(!c.ok)return{...c,message:`Version ${o}'s source couldn't be packaged, so it can't be restored: ${c.message}`};let[l]=c.value.deployable;if(l.api_name!==e.baseApiName)return H("local_error",`Version ${o}'s source is for ${l.api_name}, not ${e.baseApiName}.`);let d=await sA(e,Xe(e).liveVersion);if(!d.ok)return d;let u;try{u=fa(s.value.zip,d.value)}catch(m){return z(m)}let f={exists:e.yourPreview!==null,updated:e.yourPreview?.updated??null},g=[...f.exists?[`This replaces your current preview (last updated ${f.updated??"unknown"}).`]:[],`This folder's source isn't changed, and the next \`appbuilder app push\` replaces the restored preview with it. To keep working from version ${o}'s source, publish this preview, then pull the new Live version with \`appbuilder app pull\`.`];return I({summary:Xe(e),version:o,preview:f,deployable:l,source:u,warnings:g})}async function ko(e,t,n,{isAborted:r=()=>!1}={}){let i,o;try{let a;if([o,a]=await Promise.all([e.api.uploadFile(t.source,{filename:`${e.baseApiName}-source.zip`,contentType:xp,source:"plugin_app_source_filesystem"}),Pp(e.api,t.deployable.thumbnail)]),r())return Tt();let c=Ia(t.deployable,{release:!1,sourcePackageId:o,thumbnailId:a});i=await e.api.publish(c)}catch(a){return z(a)}let s=await Yr(e,a=>({...a,previewSourcePackageId:o,previewRestoredFrom:t.version,lastPushedSourceHash:null}),n);return I({apiName:i.api_name,version:t.version,sourcePackageId:o,remembered:s===null,warnings:s===null?[]:[Dn(s)]})}function Ao(e,t){return e!==void 0&&t?H("usage_error","Pass either <version> or --preview, not both."):e!==void 0?I({kind:"release",version:e}):t?I({kind:"preview"}):H("usage_error","Missing argument <version>. Usage: appbuilder app pull <version>, or appbuilder app pull --preview for your preview.")}var Ba=(e,t)=>t.startsWith(e+Gk),FA="Your preview has no source package. Push it again with `appbuilder app push`.";async function xo(e,t,n,r){let i;if(t.kind==="release"){let c=oo(t.version);if(!c.ok)return c;if(e.app===null)return Zr(e,"pull");i={source:"release",version:c.value}}else{if(e.app===null||e.yourPreview===null)return H("no_preview",sn(e.baseApiName));i={source:"preview",updated:e.yourPreview.updated}}let o=np(r.cwd),s=n.out===void 0||n.out===""?$n(Wk(o),i.source==="release"?`${e.baseApiName}-v${i.version}`:`${e.baseApiName}-preview`):np(o,n.out);if(s===o||Ba(s,o))return H("usage_error",`${s} holds the plugin folder; pass --out <dir> to choose a new folder.`);if(await r.pathExists(s))return H("usage_error",`${s} already exists; pass --out <dir> to choose a new folder.`);let a=Ba(o,s)&&!Ba($n(o,".kizenapp"),s)?[`${s} is inside the plugin folder, so the next \`appbuilder app push\` includes it unless .gitignore or .kizenignore excludes it.`]:[];return I({summary:Xe(e),...i,dir:s,warnings:a})}var jA=e=>`No base is recorded for ${e}. A push from there finds one when it can, or stops with \`base_required\`.`;async function MA(e,t){let n=await Jr(e,t);return n.ok?I({zip:n.value.zip,entry:nr(Ua(e.stateKey),t,n.value.sourceId)}):n}async function zA(e){let t;try{t=await e.api.getPreview(e.app.api_name,e.credentials.userId)}catch(a){return Nt(a)?H("no_preview",sn(e.baseApiName)):z(a)}let n=t.source_filesystem_package;if(typeof n!="string"||n==="")return H("preview_incomplete",FA);let r=await Ka(e.api,n);if(!r.ok)return r;let i=await gp(e,r.value.lineage);if(!i.ok)return i;let o=Ua(e.stateKey),s=i.value;return I({zip:r.value.zip,entry:{...s===null?o:nr(o,s.baseLiveVersion,s.baseSourcePackageId),previewSourcePackageId:n},preview:{sourcePackageId:n,base:vp(s?.baseLiveVersion)}})}async function Po(e,t,n,{isAborted:r=()=>!1}={}){let i=Rt(e);if(i===null)return t.source==="release"?Zr(e,"pull"):H("no_preview",sn(e.baseApiName));let o=t.source==="release"?await MA(i,t.version):await zA(i);if(!o.ok)return o;if(r())return Tt();let s;try{s=await n.unzipToDir(o.value.zip,t.dir)}catch(u){return u instanceof Fr?H("usage_error",`${t.dir} already exists; pass --out <dir> to choose a new folder.`):z(u)}let a;try{await n.writeAppState(t.dir,ka(Vr(),o.value.entry)),a=null}catch(u){a=je(u)}let{preview:c}=o.value,l=t.source==="release"?t.version:c?.base.version??null,d=c!==void 0&&!c.base.recorded;return I({dir:t.dir,written:s.written,skipped:s.skipped,remembered:a===null,warnings:[...d?[jA(t.dir)]:[],...a===null?[]:[l===null?Dn(a):`${Dn(a)} Before pushing from ${t.dir}, run \`appbuilder app merge --accept-live-base --release ${l} --yes\` there.`]],...c===void 0?{}:{preview:c}})}var Ln=["previewSourcePackageId","previewRestoredFrom"],UA=["folderBaseLiveVersion","folderBaseSourcePackageId",...Ln],Tp=(e,t)=>Bn(e).find(n=>n.status==="preview"&&n.preview_owner?.id===t)??null,Np=(e,t)=>Bn(e).every(n=>n.status==="preview"&&n.preview_owner?.id===t),rp=e=>typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null,Rp=e=>e.fullName??e.id,co=e=>typeof e=="string"&&e!==""?e:null,VA=e=>{let t=Bn(e).flatMap(n=>n.status==="preview"&&n.preview_owner!==null?[`${co(n.preview_owner.full_name)??"unknown"} (${n.preview_owner.id})`]:[]);return t.length===0?void 0:`Previews of ${e.base_api_name}: ${t.join(", ")}. Pass one of these user ids to --owner.`},HA=(e,t,n)=>n?`You have no preview of ${e} on this business.`:`User ${t} has no preview of ${e} on this business.`,$p=e=>`This preview is the only version of ${e}, so deleting it deletes the whole app from this business, with its settings and secrets.`,KA=e=>`This is ${e}'s preview, not yours.`,Ma=(e,t)=>`${String(e)} other ${e===1?"user is":"users are"} using this preview.${t?"":" Deleting it switches them to their own preview, or Live, and notifies them."}`,Ya=e=>e.yours?"Your preview":`${Rp(e)}'s preview`,Op=e=>`Run \`appbuilder app preview delete --owner ${e.id}\` to review it as it is now.`,ip=(e,t)=>`${Ya(t)} of ${e} no longer exists, so nothing was deleted.`,Dp=e=>`${Ya(e)} was pushed again after this delete was reviewed, so nothing was deleted. ${Op(e)}`,Lp=e=>`${Ya(e)} is now the app's only version, so deleting it would delete the whole app, which wasn't agreed to. Nothing was deleted. ${Op(e)}`;function Co(e,t){let{app:n,credentials:r}=e,i=(t.owner??r.userId).trim();if(i==="")return H("usage_error","--owner needs the user id of the preview to delete.");let o=i===r.userId;if(n===null)return H("not_found",`${e.baseApiName} isn't published to this business yet, so it has no preview to delete.`);let s=Tp(n,i);if(s===null){let f=VA(n);return H("not_found",HA(e.baseApiName,i,o),f===void 0?{}:{hint:f})}let a={id:i,fullName:co(s.preview_owner?.full_name),yours:o};if(t.expectUpdated!==void 0&&s.updated!==t.expectUpdated)return H("preview_changed",Dp(a));let c=rp(s.active_users_count),l=c===null?null:Math.max(0,c-(s.is_current_for_viewer?1:0)),d=Np(n,i),u=[...d?[$p(co(n.name)??e.baseApiName)]:[],...o?[]:[KA(Rp(a))],...l!==null&&l>0?[Ma(l,d)]:[]];return I({summary:Xe(e),apiName:n.api_name,owner:a,preview:{updated:s.updated,activeUsersCount:c,installedCount:rp(s.installed_count),otherActiveUsersCount:l},deletesApp:d,warnings:u})}var Bp=(e,t)=>e.deletesApp&&!t?H("preview_changed",Lp(e.owner)):null,WA=e=>`The preview was deleted, but whether the app still exists couldn't be checked: ${e}`;async function So(e,t,n,{isAborted:r=()=>!1}={}){let{api:i,baseApiName:o}=e;if(r())return Tt();let s;try{s=Wr(await i.listApps(o),o)}catch(g){return z(g)}let a=s===null?null:Tp(s,t.owner.id);if(s===null||a===null)return H("not_found",ip(o,t.owner));if(a.updated!==t.preview.updated)return H("preview_changed",Dp(t.owner));if(!t.deletesApp&&Np(s,t.owner.id))return H("preview_changed",Lp(t.owner));if(r())return Tt();try{await i.deletePreview(s.api_name,t.owner.id)}catch(g){return Nt(g)?H("not_found",ip(o,t.owner)):z(g)}let c=[],l;try{l=Wr(await i.listApps(o),o)===null}catch(g){l=null,c.push(WA(je(g)))}let d=rt(e),u=t.owner.yours&&d!==void 0&&Ln.some(g=>g in d),f=null;if(l===!0){let{environment:g,businessId:m,baseApiName:p}=e.stateKey,h={environment:g,businessId:m,baseApiName:p};f=await dp(n.cwd,b=>Id(b,h,y=>({...an(y,...UA),lastPushedSourceHash:null})),n)}else u&&(f=await Yr(e,g=>an(g,...Ln),n));return I({status:"deleted",appDeleted:l,remembered:f===null,warnings:[...c,...f===null?[]:[Dn(f)]]})}function _o(e,t){if(!e.deletesApp||t.appDeleted!==!1)return e;let n=$p(co(e.summary.name)??e.summary.baseApiName),r=e.preview.otherActiveUsersCount;return{...e,deletesApp:!1,warnings:e.warnings.flatMap(i=>i===n?[]:r!==null&&i===Ma(r,!0)?[Ma(r,!1)]:[i])}}var ir=me;function Fn(e){return Array.isArray(e)?e.flatMap(t=>{if(!F(t)||typeof t.api_name!="string"||t.api_name==="")return[];let n=t.hint_object_name;return[{apiName:t.api_name,name:typeof t.name=="string"&&t.name!==""?t.name:t.api_name,hintObjectName:typeof n=="string"&&n!==""?n:null}]}):[]}var Fp=e=>{let t=e.artifacts;return Fn(F(t)?t.js_action_templates:void 0)},GA=e=>e.object_name??e.entity_name??e.name,JA=e=>({id:e.id,objectId:e.custom_object.id,objectName:e.custom_object.name,label:GA(e.custom_object),includePerformAction:e.include_perform_action});function jp(e){let{templates:t,installed:n,liveApiNames:r,associations:i}=e;return t.map(o=>{let s=i.filter(l=>l.browser_js_action_template.api_name===o.apiName).map(JA),a=r?.has(o.apiName)??!1,c=s.length>0?"linked":!n||a?"unlinked":"unknown";return{...o,status:c,inLive:a,links:s}})}var Xa=e=>{let t=new Set;return e.filter(n=>t.has(n.apiName)?!1:(t.add(n.apiName),!0))},qA=e=>e instanceof q&&e.kind==="not_found";async function Qa(e,t){let{app:n,api:r}=e;if(n===null){let s=t.kind==="version"?Xa(t.templates):[];return I({status:"not_installed",liveVersion:null,actions:jp({templates:s,installed:!1,liveApiNames:null,associations:[]})})}let i=t.kind==="live"?t.version:n.live_version;if(t.kind==="version"&&t.templates.length===0)return I({status:"checked",liveVersion:i,actions:[]});let o=e.yourPreview;try{let[s,a,c]=await Promise.all([i===null?null:r.getVersion(n.api_name,i).then(Fp),t.kind==="app"&&o!==null?r.getPreview(n.api_name,e.credentials.userId).then(Fp).catch(d=>{if(qA(d))return[];throw d}):[],i===null?[]:r.listActionAssociations(n.api_name)]),l=t.kind==="version"?t.templates:[...s??[],...a];return I({status:i===null?"no_live_version":"checked",liveVersion:i,actions:jp({templates:Xa(l),installed:!0,liveApiNames:s===null?null:new Set(s.map(d=>d.apiName)),associations:c})})}catch(s){return z(s)}}async function it(e,t){let n=await Qa(e,t);return n.ok?n.value:Up(e,t,n.message)}function Up(e,t,n){let r=t.kind==="version"?Xa(t.templates):[];return{status:"failed",liveVersion:t.kind==="live"?t.version:e.app?.live_version??null,actions:r.map(i=>({...i,status:"unknown",inLive:!1,links:[]})),error:n}}async function Eo(e,t){let n={kind:"version",templates:t},r=await up(e);return r.ok?it(r.value,n):Up(e,n,r.message)}var Mp=e=>e.map(t=>t.apiName).join(", "),zp="with `--json`, run an action's `linkArgv`, `linkMenuArgv` or `linkNoMenuArgv`; at a terminal, run `appbuilder app actions link` to pick them";function Ge(e){let t=e.actions.filter(i=>i.status==="unlinked"),n=e.actions.filter(i=>i.status==="unknown"),r=[];return t.length>0&&r.push(`These JS actions aren't linked to any object: ${Mp(t)}. Link them: ${zp}.`),n.length>0&&e.status!=="failed"&&r.push(`These JS actions aren't in the Live version, so their links can't be listed and they may not be linked to any object: ${Mp(n)}. To make sure, link them: ${zp}.`),r}var ot=e=>e.status==="failed"?[`Couldn't check which JS actions are linked to objects: ${e.error??"unknown error"}. Run \`appbuilder app actions list\` to check.`]:[];function Io(e){return!e.actions.some(n=>n.status!=="linked")&&e.status!=="failed"?[]:[{step:"actions",args:["actions","list"]},...e.actions.flatMap(n=>n.status==="unlinked"&&n.hintObjectName!==null?[{step:"link",args:["actions","link",n.apiName,n.hintObjectName]}]:[])]}var Za=(e,t)=>e.localeCompare(t,void 0,{sensitivity:"accent"})===0;function To(e,t,n){let r=t.trim(),i=e.find(a=>a.id===r)??e.find(a=>a.name===r);if(i!==void 0)return I(i);let o=e.filter(a=>Za(a.name,r)||Za(a.objectName,r)||a.entityName!==null&&Za(a.entityName,r)),[s]=o;if(s!==void 0&&o.length===1)return I(s);if(o.length>1){let a=o.map(c=>({value:c.id,label:`${c.objectName} (${c.name})`,args:[],argv:n(c)}));return ir("needs_choice",`Several objects match "${t}". Pick one by its api name or id.`,{choice:"object",choices:a})}return ir("not_found",`No object "${t}" on this business that you can see. Pass an object's api name (like client_client) or its id.`)}var Vp=e=>({id:e.id,name:e.name,label:e.objectName});async function No(e){let t=await Qa(e,{kind:"app"});return t.ok?I({summary:Xe(e),check:t.value}):t}var YA=e=>ir("not_found",`${e.baseApiName} isn't on this business yet, so it has no JS actions to link. Push it first with \`appbuilder app push\`.`),ZA=(e,t)=>ir("not_found",`${e.baseApiName} has no JS action "${t}" in its Live version or your preview. If it's new, push this folder first with \`appbuilder app push\`.`);async function ec(e){let{app:t}=e;if(t===null)return YA(e);let n,r;try{[r,n]=await Promise.all([Qa(e,{kind:"app"}),e.api.listObjects()])}catch(i){return z(i)}return r.ok?I({appApiName:t.api_name,check:r.value,objects:n}):r}function Ro(e,t,n){let r=t.check.actions.find(i=>i.apiName===n);return r===void 0?ZA(e,n):I(r)}async function Hp(e,t,n,r){let i=await ec(e);if(!i.ok)return i;let o=To(i.value.objects,n,r);if(!o.ok)return o;let s=Ro(e,i.value,t);return s.ok?I({choices:i.value,action:s.value,object:o.value}):s}var XA=(e,t)=>`${e} is in the Live version, so this change to its link to ${t} applies to everyone using Live as soon as it's made.`,Kp=(e,t)=>e.inLive?[XA(e.apiName,t)]:[],QA=e=>`${e} isn't in the Live version, so an existing link to this object can't be seen. If there is one, linking reports it as already linked and leaves its menu setting as it is.`;async function Wp(e,t,n){let r=await Hp(e,t.action,t.object,n);if(!r.ok)return r;let{choices:i,action:o,object:s}=r.value;return I(tc(e,i,o,s,{...t.menu!==void 0&&{menu:t.menu}}))}function tc(e,t,n,r,{menu:i}){let o=n.links.find(l=>l.objectId===r.id),s=o===void 0?null:{id:o.id,includePerformAction:o.includePerformAction},a,c;return s===null?(a="create",c=i??!1):i===void 0||i===s.includePerformAction?(a="up_to_date",c=s.includePerformAction):(a="update",c=i),{summary:Xe(e),appApiName:t.appApiName,action:n,object:Vp(r),change:a,includePerformAction:c,existing:s,notices:a==="create"&&!n.inLive?[QA(n.apiName)]:[],warnings:a==="up_to_date"?[]:Kp(n,r.name)}}var ex=(e,t)=>`${e} was already linked to ${t}. Its link isn't listed (the action isn't in the Live version), so its menu setting couldn't be checked or changed.`,tx=(e,t)=>`${e} was already linked to ${t} (the link was made after this command listed the links), so nothing was changed and its menu setting wasn't set. Run \`appbuilder app actions list\`, then link it again to set the menu setting.`,nx=e=>e instanceof q&&e.status===400&&/already exists/i.test(e.message),rx=e=>e instanceof q&&e.status===400&&/Browser JS action template not found/i.test(e.message),ix=e=>`${e} is only in your preview, and Kizen couldn't find it to link it. Kizen environments without the fix for linking preview-only actions (KZN-19521) only link actions in Live: publish it first, then link it.`,Gp=()=>ir("local_error",Ja);async function $o(e,t,{isAborted:n=()=>!1}={}){let r=t.includePerformAction;if(t.change==="up_to_date"||r===null)return I({status:"up_to_date",warnings:[]});if(n())return Gp();try{return t.change==="update"&&t.existing!==null?(await e.api.updateActionAssociation(t.appApiName,t.existing.id,r),I({status:"updated",warnings:[]})):(await e.api.createActionAssociation({appApiName:t.appApiName,actionApiName:t.action.apiName,objectId:t.object.id,includePerformAction:r}),I({status:"created",warnings:[]}))}catch(i){return t.change==="create"&&nx(i)?I({status:"already_linked",warnings:[(t.action.inLive?tx:ex)(t.action.apiName,t.object.name)]}):t.change==="create"&&!t.action.inLive&&rx(i)?{...z(i),hint:ix(t.action.apiName)}:z(i)}}var ox=(e,t)=>`${e} isn't linked to ${t}.`,nc=e=>`${e} isn't in the Live version, so its links can't be listed or removed here. If it was linked while only in a preview, publish it first, then unlink it.`;async function Jp(e,t,n){let r=await Hp(e,t.action,t.object,n);if(!r.ok)return r;let{choices:i,action:o,object:s}=r.value;return rc(e,i,o,s)}function rc(e,t,n,r){let i=n.links.find(o=>o.objectId===r.id);return i===void 0?ir("not_found",ox(n.apiName,r.name),n.inLive?{}:{hint:nc(n.apiName)}):I({summary:Xe(e),appApiName:t.appApiName,action:n,object:Vp(r),associationId:i.id,includePerformAction:i.includePerformAction,warnings:Kp(n,r.name)})}async function Oo(e,t,{isAborted:n=()=>!1}={}){if(n())return Gp();try{await e.api.deleteActionAssociation(t.associationId)}catch(r){return z(r)}return I({status:"unlinked"})}var sx={local:"HEAD",incoming:"live"};function Je(e,t,n,r){let i={json:n.json===!0,deps:r},o=Rn(n,r.processEnv),s=d=>[...d,...d[2]==="push"&&n.allowProduction===!0?["--allow-production"]:[],...o,...Oa(i)],a=d=>d.map(u=>({...u,argv:s(u.argv??[])})),c=(d,u)=>u==="base"||u==="object"?s(d.argv??[]):Et(e,[...t,...d.args,...rn(n,r.processEnv)],i),l=d=>Et("appbuilder app",[...d,...o],i);return{output:i,runnable:a,appArgv:l,pin:d=>{o=to(n,d)},apply:(d,u)=>({applyArgv:l([...d,"--yes",...u?["--allow-production"]:[]]),requiresProductionConsent:u}),fail:d=>{let u=d.conflict?.reason,f=d.code==="publish_conflict"?[u==="preview_replaced"?{step:"publish",argv:l(["publish"])}:u==="base_unknown"?{step:"push",argv:l(["push"])}:{step:"merge",argv:l(["merge"])}]:void 0;It(i,f===void 0?d:{...d,next:f},c)}}}async function Zp(e,t,n){let r=await Nn(e,t);return r.ok?(n(r.value.credentials),ze(t,r.value.notices),I({credentials:r.value.credentials,client:r.value.client})):r}async function Xp(e,t,n){let r=t;if(r===void 0)try{r=await n.readManifestApiName(n.cwd)}catch(o){return z(o)}let i=await qr({...e,baseApiName:r},n);return i.ok&&ze(n,i.value.notices),i}async function $t(e,t,{fail:n,pin:r}){let i=await Zp(e,t,r);if(!i.ok)return n(i),null;let o=await Xp(i.value,void 0,t);return o.ok?o.value:(n(o),null)}var ti=e=>e===null?"none":`v${e}`;function qe(e){return[`Environment: ${e.environment}${e.isProduction?" (production)":""}`,`Business: ${e.businessId}`,e.apiName===null?`App: ${e.baseApiName} (not published to this business yet)`:`App: ${e.name??e.baseApiName} (${e.apiName})`,`Live: ${ti(e.liveVersion)}`]}var yt=e=>({environment:e.environment,businessId:e.businessId,userId:e.userId,app:{baseApiName:e.baseApiName,apiName:e.apiName,name:e.name,liveVersion:e.liveVersion}}),Ce=(...e)=>`${e.filter(t=>typeof t=="string").join(`
|
|
862
|
+
`+o;return er.writeFileSync(t,n+s),!0}import{randomBytes as Lk}from"crypto";import{mkdir as Bk,rename as Fk,rm as jk,writeFile as Mk}from"fs/promises";import{join as zk}from"path";import{PluginValidationError as Uk,packagePlugin as Vk,parseManifestFromFiles as Hk,transformDeployablePlugin as Kk,transformFiles as Wk,validatePluginApp as Gk}from"@kizenapps/packager";import{readdir as Ik,readFile as np}from"fs/promises";import{join as rp,relative as Tk}from"path";var Nk=new Set([".png",".svg"]),Rk=new Set([".kzn"]),$k=new Set([".DS_Store"]),no=new Set(["node_modules",".git",".kizenapp",".copilot-docs",".github",".claude","__pycache__"]),Ok=8e3;function Dk(e){return e.subarray(0,Ok).includes(0)}async function ip(e,t){let n=await Ik(e,{withFileTypes:!0}),r=[];for(let i of n)if(i.isDirectory()){if(no.has(i.name))continue;r.push(...await ip(rp(e,i.name),t))}else i.isFile()&&($k.has(i.name)||r.push(rp(e,i.name)));return r}async function ro(e,{detectBinaryByContent:t=!1}={}){let n=await ip(e,e);return Promise.all(n.map(async r=>{let i=Tk(e,r).split("\\").join("/"),o=i.lastIndexOf("."),s=o>=0?i.slice(o).toLowerCase():"";if(Nk.has(s)){let c=await np(r);return{path:i,content:"",base64Image:c.toString("base64")}}let a=await np(r);return Rk.has(s)||t&&Dk(a)?{path:i,content:"",binaryData:a}:{path:i,content:a.toString("utf-8")}}))}var Jk=(e,t)=>({...e,thumbnail:e.thumbnail?Buffer.from(e.thumbnail).toString("base64"):null,kznFile:e.kznFile?Buffer.from(e.kznFile).toString("base64"):null,allReleaseNotes:t});async function Hr(e,t){t?.("reading-files");let n=await ro(e);t?.("validating");let r=Gk(n);if(r.some(c=>c.severity==="error"))throw new Uk(r);t?.("minifying");let i=await Wk(n);t?.("packaging");let o=Hk(i),s=Vk(i,o),a=Object.values(s).map(Kk);return{files:n,deployable:a,issues:r}}async function io(e,t,n){await Bk(t,{recursive:!0});let{files:r,deployable:i}=await Hr(e,n);n?.("writing-bundle");let o=i.map(u=>{let f=u.release_notes_directory?.replace(/\/$/,""),g=f?r.filter(p=>p.path.startsWith(f+"/")&&p.path.endsWith(".md")&&p.content).map(p=>({version:p.path.slice(p.path.lastIndexOf("/")+1,-3),notes:p.content})).sort((p,m)=>m.version.localeCompare(p.version,void 0,{numeric:!0})):[];return Jk(u,g)}),s=JSON.stringify(o,null,2),a=(u,f)=>u==="allReleaseNotes"?void 0:f,c=Buffer.byteLength(JSON.stringify(o,a,2),"utf-8"),l=zk(t,"bundle.json"),d=`${l}.${String(process.pid)}.${Lk(6).toString("hex")}.tmp`;try{await Mk(d,s,"utf-8"),await Fk(d,l)}catch(u){throw await jk(d,{force:!0}).catch(()=>{}),u}return{bundleSize:c}}var H=me,Kr="kizen.json";async function nA(e){let t;try{t=await cp($n(e,Kr),"utf8")}catch(o){throw tt(o)?new Error(`No ${Kr} in ${e}. Run this command from the plugin folder.`):o}let n;try{n=JSON.parse(t)}catch(o){throw new Error(`${Kr} isn't valid JSON (${je(o)}). If it has merge conflict markers, resolve them first.`)}let r=Array.isArray(n)?n[0]:n,i=F(r)?r.api_name:void 0;if(typeof i!="string"||i==="")throw new Error(`${Kr} has no api_name.`);return i}var rA=async e=>{try{return await Yk(e),!0}catch{return!1}};function lp(e){return{...Qi(e),packageLocalPlugin:t=>Hr(t),zipSourceDir:t=>td(t),readManifestApiName:nA,businessApps:(t,n)=>qd(t,n),readAppState:Nd,writeAppState:$d,ensureGitignore:Ze,planMerge:t=>vd(t),applyMerge:(t,n)=>kd(t,n),unzipToDir:rd,pathExists:rA,readTextFile:t=>cp(t,"utf8"),makeTempDir:()=>Zk($n(Qk(),"appbuilder-version-")),removeDir:t=>Xk(t,{recursive:!0,force:!0}),staleAgentFileWarnings:t=>Yi(t)}}var iA="Business Apps need the Marketplace \u203A Business App Developer permission at the Delete/All level.";function z(e){if(e instanceof Or||e instanceof Dr||e instanceof Lr||e instanceof qn)return H("source_invalid",e.message);if(e instanceof nn)return H(e.code==="thumbnail_required"?"thumbnail_required":"local_error",e.message);let t=Me(e);return t.code==="forbidden"?{...t,hint:iA}:t}function On(e,t){return/^\d+$/.test(e)&&/^\d+$/.test(t)?Number(e)-Number(t):e.localeCompare(t,void 0,{numeric:!0})}var on=(e,t)=>e===null||t===null?e===t:On(e,t)===0;function oo(e){let t=e.trim();return/^[1-9]\d*$/.test(t)?I(t):H("usage_error",`"${e}" isn't a version number; pass a release number like 3.`)}var lo=e=>qk("sha256").update(e).digest("hex"),Bn=e=>Array.isArray(e.versions)?e.versions:[],uo=e=>[...new Set(Bn(e).filter(t=>t.status==="live"||t.status==="released").map(t=>t.version))].sort((t,n)=>On(n,t));function up(e){return typeof e=="string"&&e!==""?e:F(e)&&typeof e.full_name=="string"&&e.full_name!==""?e.full_name:null}function oA(e){let t=Bn(e);return t.find(n=>n.status==="live")??t.find(n=>e.live_version!==null&&on(n.version,e.live_version))}var it=e=>e.state.status==="found"?e.state.entry:void 0,Wr=(e,t)=>e.find(n=>n.base_api_name===t)??null,Ua=(e,t)=>e===null?null:Bn(e).find(n=>n.status==="preview"&&n.preview_owner?.id===t)??null;async function qr(e,t){let{credentials:n,baseApiName:r}=e,i=t.businessApps(e.client,n.businessId),o,s;try{[o,s]=await Promise.all([i.listApps(r),t.readAppState(t.cwd)])}catch(h){return z(h)}let a=Wr(o,r),c={environment:n.environment,businessId:n.businessId,baseApiName:r,userId:n.userId},l=ka(s.doc,c),d=s.notice===void 0?[]:[s.notice];l.status==="malformed"&&d.push(`The saved state for ${r} in .kizenapp/apps.json is malformed, so it was ignored.`);let u=await aA(i,a,l.status==="found"?l.entry:void 0),f=Ua(a,n.userId),g=l.status==="found"?pp(l.entry,u):void 0,p=a!==null&&f===null&&g!==void 0&&Ln.some(h=>h in g)?{sourceId:g.previewSourcePackageId??null}:void 0,m=g===void 0?l:{status:"found",entry:dp(g,p)};return u!==void 0&&d.push(sA(u.version)),I({credentials:n,api:i,baseApiName:r,app:a,yourPreview:f,stateKey:c,state:m,...u===void 0?{}:{promoted:u},...p===void 0?{}:{previewGone:p},notices:d})}function dp(e,t){return t===void 0?e:(e.previewSourcePackageId??null)===t.sourceId?an(e,...Ln):e}var sA=e=>`The preview this folder pushed was published as Live v${e} outside this command, so v${e} is now this folder's base.`;async function aA(e,t,n){let r=t?.live_version??null,i=n?.previewSourcePackageId,o=n?.folderBaseLiveVersion;if(!(t===null||r===null||i===void 0||n?.previewRestoredFrom!==void 0||o===void 0||on(o,r)))try{if((await e.getVersion(t.api_name,r)).source_filesystem_package!==i)return;let a=fa(await e.downloadFile(i));return a!==null&&a.baseSourcePackageId===(n?.folderBaseSourcePackageId??null)?{version:r,sourceId:i}:void 0}catch{return}}function pp(e,t){return t===void 0||e.previewSourcePackageId!==t.sourceId?e:nr(an(e,...Ln),t.version,t.sourceId)}async function mp(e){let t;try{t=await e.api.listApps(e.baseApiName)}catch(r){return z(r)}let n=Wr(t,e.baseApiName);return I({...e,app:n,yourPreview:Ua(n,e.credentials.userId)})}function Xe(e){let{credentials:t,app:n}=e;return{environment:t.environment,businessId:t.businessId,userId:t.userId,isProduction:Kn(t.environment),baseApiName:e.baseApiName,apiName:n?.api_name??null,name:n?.name??null,liveVersion:n?.live_version??null}}var Va=e=>({...e,lastPushedSourceHash:null});async function fp(e,t,n){for(let r=0;;r+=1)try{let{doc:i}=await n.readAppState(e),o=t(i);return o===null||(r===0&&n.ensureGitignore(e),await n.writeAppState(e,o)),null}catch(i){if(!(i instanceof Ur)||r>=1)return je(i)}}var cA=(e,t,n,r)=>fp(e,i=>{let o=ka(i,t);return Aa(i,n(o.status==="found"?o.entry:Va(t)))},r),Yr=(e,t,n)=>cA(n.cwd,e.stateKey,r=>t(dp(pp(r,e.promoted),e.previewGone)),n);function an(e,...t){return Object.fromEntries(Object.entries(e).filter(([n])=>!t.includes(n)))}function nr(e,t,n){let r=an(e,"folderBaseLiveVersion","folderBaseSourcePackageId");return t===null?{...r,folderBaseLiveVersion:null}:n===null?r:{...r,folderBaseLiveVersion:t,folderBaseSourcePackageId:n}}var Ha=e=>e?.folderBaseLiveVersion,lA=(e,t)=>e.app===null?void 0:t(it(e)),uA=e=>e.app===null?Ha(it(e)):void 0,dA=e=>`The base recorded for this folder (v${e}) is from a version of the app that's no longer on this business, so it's ignored.`,Gr=e=>e===null?"no Live version":`v${e}`,Ka=(e,t,n)=>t===null?`${e} ${n}`:`${e} is based on ${Gr(t)}`,gp="was started before the app had a Live version",pA="was pushed before the app had a Live version",Dn=e=>`.kizenapp/apps.json couldn't be written, so this isn't remembered: ${e}`,$t=e=>e instanceof q&&e.kind==="not_found",mA=(e,t)=>H("not_found",`Version ${t} of ${e.baseApiName} doesn't exist on this business.`),Zr=(e,t)=>H("not_found",`${e.baseApiName} isn't published to this business yet, so there's nothing to ${t}.`),Ot=e=>e.app===null?null:e;async function so(e,t){let n;try{n=await e.api.getVersion(e.app.api_name,t)}catch(i){return $t(i)?mA(e,t):z(i)}let r=n.source_filesystem_package;return typeof r!="string"||r===""?H("not_found",`Version ${t} of ${e.baseApiName} has no source package.`):I({...n,source_filesystem_package:r})}async function Jr(e,t){let n=await so(e,t);if(!n.ok)return n;let r=n.value.source_filesystem_package;try{return I({sourceId:r,zip:await e.api.downloadFile(r)})}catch(i){return z(i)}}var ja={baseLiveVersion:null,baseSourcePackageId:null};async function hp(e,t){let n=await yp(e,t);return n.ok?I(n.value.found?n.value.sourceId:null):n}async function yp(e,t){let n;try{n=await e.api.getVersion(e.app.api_name,t)}catch(i){return $t(i)?I({found:!1}):z(i)}let r=n.source_filesystem_package;return I({found:!0,sourceId:typeof r=="string"&&r!==""?r:null})}async function fA(e,t){let n=Ot(e);if(t===null)return I(ja);if(n===null)return Zr(e,"restore");let r=await so(n,t);return r.ok?I({baseLiveVersion:t,baseSourcePackageId:r.value.source_filesystem_package}):r}async function Wa(e,t){try{let n=await e.downloadFile(t);return I({sourcePackageId:t,zip:n,lineage:fa(n)})}catch(n){return z(n)}}async function gA(e){let t=Ot(e);if(t===null||e.yourPreview===null)return I(null);let n;try{n=await t.api.getPreview(t.app.api_name,t.credentials.userId)}catch(i){return $t(i)?I(null):z(i)}let r=n.source_filesystem_package;return typeof r=="string"&&r!==""?Wa(t.api,r):I(null)}async function bp(e,t){if(t===null)return I(null);let n=t.baseLiveVersion;if(n===null)return I(t);let r=Ot(e);if(r===null)return I(null);let i=await hp(r,n);return i.ok?I(i.value!==null&&i.value===t.baseSourcePackageId?t:null):i}var wp=5;function tr(e){let{files:t}=_n(e);return new Map([...t].map(([n,r])=>[n,lo(r)]))}var vp=(e,t)=>e.size===t.size&&[...e].every(([n,r])=>t.get(n)===r);async function kp(e,t){let n=Ot(e);if(n===null)return I(null);let r=n.app.live_version,i=[...new Set([...r===null?[]:[r],...uo(n.app)])].slice(0,wp),o;try{o=tr(t)}catch{return I(null)}for(let s of i){let a=await Jr(n,s);if(!a.ok){if(a.code==="not_found")continue;return a}let c;try{c=tr(a.value.zip)}catch{continue}if(vp(o,c))return I({version:s,sourceId:a.value.sourceId})}return I(null)}function hA(e,t){try{return vp(tr(e),tr(t))}catch{return!1}}var Ap=e=>`No base is recorded for this folder, but its files match v${e} exactly, so v${e} is used as its base.`,yA=e=>`No base is recorded for this folder, but its files match your preview exactly, so your preview's base (${e===null?"no Live version":`v${e}`}) is used as its base.`,Ga=e=>`The base recorded for this folder (v${e}) no longer matches v${e} on this business (the app or that version was deleted and created again), so it's ignored.`,bA="Your preview changed since this folder was said to continue it, so its base wasn't used.",wA=e=>e===null?"This folder continues your preview (pushed before the app had a Live version)":`This folder continues your preview (based on v${e})`;function vA(e,t,n={}){let{preview:r}=n,i=[{value:"merge",label:`Preview merging Live v${t} into this folder`,args:[],argv:["appbuilder","app","merge","--release",t]},{value:"accept",label:`This folder already contains Live v${t}`,args:[],argv:["appbuilder","app","merge","--release",t,"--accept-live-base","--yes"]},...r==null?[]:[{value:"preview",label:wA(r.lineage.baseLiveVersion),args:[],argv:["appbuilder","app","push","--base-from-preview",r.sourcePackageId]}]],o=r==null?"":" Or, if this folder continues your preview, push it with your preview's base.";return H("base_required",`${(n.notices??[]).map(s=>`${s} `).join("")}No base version is recorded for this folder, and Live is v${t}. Merge Live into this folder, or record that it already contains Live, then push.${o}`,{choice:"base",choices:i})}async function rr(e){let t=lA(e,Ha),n=Ot(e);if(t===void 0)return I({status:"none"});if(t===null||n===null)return I({status:"recorded",version:null,sourceId:null});let r=it(e)?.folderBaseSourcePackageId??"";if(e.promoted!==void 0&&on(e.promoted.version,t))return I({status:"recorded",version:t,sourceId:e.promoted.sourceId});let i=await yp(n,t);return i.ok?i.value.found?i.value.sourceId===r?I({status:"recorded",version:t,sourceId:r}):I({status:"replaced",version:t}):I({status:"gone",version:t}):i}var Ja=e=>`The base recorded for this folder (v${e}) no longer exists on this business, so it's ignored.`;async function kA(e,t,n={}){let r=[],i,o=async()=>{if(i===void 0){let p=await gA(e);if(!p.ok)return p;if(p.value===null)i=null;else{let m=await bp(e,p.value.lineage);if(!m.ok)return m;i={source:p.value,lineage:m.value}}}return I(i)};if(n.baseFromPreview!==void 0){let p=await o();if(!p.ok)return p;let m=p.value?.source.sourcePackageId===n.baseFromPreview?p.value.lineage:null;if(m!==null)return I({version:m.baseLiveVersion,source:"base_from_preview",lineage:m,previewSourcePackageId:n.baseFromPreview,notices:r});r.push(bA)}let s=await rr(e);if(!s.ok)return s;if(s.value.status==="replaced")r.push(Ga(s.value.version));else if(s.value.status==="gone")r.push(Ja(s.value.version));else if(s.value.status==="recorded"){let{version:p,sourceId:m}=s.value;return I({version:p,source:"recorded",lineage:p===null||m===null?ja:{baseLiveVersion:p,baseSourcePackageId:m},notices:r})}let a=e.app?.live_version??null;if(a===null)return I({version:null,source:"never_published",lineage:ja,notices:r});let c=await o();if(!c.ok)return c;let l=c.value?.lineage??null,d=c.value===null||l===null?null:{sourcePackageId:c.value.source.sourcePackageId,lineage:l};if(d!==null&&c.value!==null&&hA(t,c.value.source.zip)){let p=d.lineage.baseLiveVersion;return I({version:p,source:"preview",lineage:d.lineage,notices:[...r,yA(p)]})}let u=await kp(e,t);if(!u.ok)return u;if(u.value===null)return vA(e,a,{preview:d,notices:r});let{version:f,sourceId:g}=u.value;return I({version:f,source:"detected",lineage:{baseLiveVersion:f,baseSourcePackageId:g},notices:r})}function AA(e,t){let n=e.preview_owner;return{version:e.version,status:e.status,previewOwner:n?{id:n.id,fullName:n.full_name}:null,yours:e.status==="preview"&&n?.id===t,updated:e.updated,publishedAt:e.published_at,publishedBy:up(e.published_by)}}var xA=(e,t)=>On(t.version,e.version),xp=e=>({recorded:e!==void 0,version:e??null});function po(e,t){let n=Xe(e),r=t.status==="gone"?Ja(t.version):t.status==="replaced"?Ga(t.version):void 0,i=xp(t.status==="recorded"?t.version:void 0),o=n.liveVersion,s=i.recorded&&o!==null&&!on(i.version,o),a=[...r===void 0?[]:[r],...s?[`Live is now ${Gr(o)}, but ${Ka("this folder",i.version,gp)}. Run \`appbuilder app merge\` before publishing.`]:[]],c={folder:i,liveMoved:s};if(e.app===null)return{summary:n,published:!1,live:null,released:[],previews:[],yourPreview:null,base:c,warnings:a};let l=Bn(e.app).map(u=>AA(u,n.userId)),d=l.filter(u=>u.status==="preview");return{summary:n,published:!0,live:l.find(u=>u.status==="live")??null,released:l.filter(u=>u.status==="released").sort(xA),previews:d,yourPreview:d.find(u=>u.yours)??null,base:c,warnings:a}}var qa="Cancelled.",Rt=()=>H("local_error",qa);async function Pp(e,t){let n;try{n=await t.packageLocalPlugin(e)}catch(o){return z(o)}let[r,...i]=n.deployable;return r===void 0||i.length>0?H("local_error",`Expected one app in ${Kr}; found ${String(n.deployable.length)}.`):I({...n,deployable:[r]})}async function mo(e){let t=await Pp(e.cwd,e);if(!t.ok)return t;let n;try{n=await e.zipSourceDir(e.cwd)}catch(r){return z(r)}return I({deployable:t.value.deployable[0],issues:t.value.issues.filter(r=>r.severity==="warning"),source:n,sourceHash:lo(n.bytes)})}var PA=/^(<{7} HEAD|>{7} live)(:[^\r\n]*)?[ \t\r]*$/m,CA=/^(?:(?:<{7} HEAD|>{7} live)(?::[^\r\n]*)?|={7})[ \t\r]*$/m;async function Cp(e,t,n){let r=[];for(let i of e){let o;try{o=await t.readTextFile($n(t.cwd,...i.split("/")))}catch{continue}n.test(o)&&r.push(i)}return r}var Ya=(e,t)=>Cp(e?.conflictedPaths??[],t,CA);async function fo(e,t,n,r){let i=await Ya(it(e),r);if(i.length>0&&n.force!==!0)return H("unresolved_conflicts",`These files still have merge conflict markers: ${i.join(", ")}. Resolve them. Only if the user explicitly wants to push them anyway: pass --force.`,{files:i});let o=await kA(e,t.source.bytes,n.baseFromPreview===void 0?{}:{baseFromPreview:n.baseFromPreview});if(!o.ok)return o;let s=Xe(e),{version:a}=o.value,c=s.liveVersion!==null&&!on(a,s.liveVersion),l=uA(e),{source:d}=t,u=t.deployable.thumbnail,f=[...c?[`Live is now ${Gr(s.liveVersion)}, but ${Ka("this folder",a,gp)}. Publishing will stop on a conflict; run \`appbuilder app merge\` first.`]:[],...i.length>0?[`Pushing files that still have merge conflict markers because of --force: ${i.join(", ")}`]:[]];return I({summary:s,appName:t.deployable.name,source:{files:d.files.length,mode:d.mode,bytes:d.bytes.byteLength,hash:t.sourceHash,...d.notice===void 0?{}:{notice:d.notice}},thumbnail:u!==null&&u.byteLength>0,preview:{exists:e.yourPreview!==null,updated:e.yourPreview?.updated??null},base:{version:a,source:o.value.source,liveMoved:c},lineage:o.value.lineage,...o.value.previewSourcePackageId===void 0?{}:{basePreviewSourcePackageId:o.value.previewSourcePackageId},conflictMarkers:i,notices:[...l==null?[]:[dA(l)],...o.value.notices,...o.value.source==="detected"&&a!==null?[Ap(a)]:[]],warnings:f})}var Sp="application/zip",SA=".gitignore";function _A(e,t){let n=tr(e),r=tr(t);return[...new Set([...n.keys(),...r.keys()])].filter(i=>i!==SA&&n.get(i)!==r.get(i)).sort()}var EA=(e,t=5)=>e.length<=t?e.join(", "):`${e.slice(0,t).join(", ")} and ${String(e.length-t)} more`,IA=e=>`Files changed since this push was planned (${EA(e)}), so nothing was uploaded. Run \`appbuilder app push\` again to review and push them.`,_p=(e,t)=>t===null||t.byteLength===0?Promise.resolve(null):e.uploadFile(t,{filename:"thumbnail.png",contentType:"image/png",source:"public_image",isPublic:!0}),La="Your preview changed after this push was planned, so its base can't be taken for this folder and nothing was uploaded. Run `appbuilder app push` again to review it.";async function go(e,t,n,r,{isAborted:i=()=>!1}={}){let{api:o}=e,{source:s,sourceHash:a}=t,c,l,d,u;if(n.basePreviewSourcePackageId!==void 0){let p=Ot(e),m;if(p===null)return H("local_error",La);try{m=await o.getPreview(p.app.api_name,e.credentials.userId)}catch(h){return $t(h)?H("local_error",La):z(h)}if(m.source_filesystem_package!==n.basePreviewSourcePackageId)return H("local_error",La);if(i())return Rt()}try{u=r.ensureGitignore(r.cwd)}catch{u=!1}if(u){try{s=await r.zipSourceDir(r.cwd)}catch(m){return z(m)}a=lo(s.bytes);let p;try{p=_A(t.source.bytes,s.bytes)}catch(m){return z(m)}if(p.length>0)return H("local_error",IA(p));if(i())return Rt()}let f;try{f=ga(s.bytes,n.lineage)}catch(p){return z(p)}try{if([c,l]=await Promise.all([o.uploadFile(f,{filename:`${e.baseApiName}-source.zip`,contentType:Sp,source:"plugin_app_source_filesystem"}),_p(o,n.thumbnail?t.deployable.thumbnail:null)]),i())return Rt();let p=Ta(t.deployable,{release:!1,sourcePackageId:c,thumbnailId:l});d=await o.publish(p)}catch(p){return z(p)}let g=await Yr(e,p=>{let m={...nr(an(p,"previewRestoredFrom","conflictedPaths"),n.base.version,n.lineage.baseSourcePackageId),previewSourcePackageId:c,lastPushedSourceHash:a};return n.conflictMarkers.length>0?{...m,conflictedPaths:n.conflictMarkers}:m},r);return I({apiName:d.api_name,source:{files:s.files.length,mode:s.mode,bytes:s.bytes.byteLength,hash:a,...s.notice===void 0?{}:{notice:s.notice}},version:d.version,sourcePackageId:c,thumbnailId:l,remembered:g===null,warnings:g===null?[]:[Dn(g)]})}var Ep=e=>e.live_version??uo(e)[0]??null;function ao(e){let{entry:t,app:n,previewUpdatedAt:r,lineage:i,comparedSourcePackageId:o}=e,s=n.live_version,a=Ep(n),c=oA(n),l=t?.previewSourcePackageId,d=i?.baseLiveVersion??null,u=null;return a!==null&&(i===null?u="base_unknown":d===null||On(a,d)>0?u="live_moved":On(a,d)<0?u="base_ahead":i.baseSourcePackageId!==o&&(u="base_replaced")),{conflict:u!==null,reason:u,baseLiveVersion:d,liveVersion:s,comparedVersion:a,baseSourcePackageId:i?.baseSourcePackageId??null,comparedSourcePackageId:o,previewSourceMatches:l===void 0?null:l===e.previewSourcePackageId,livePublishedAt:c?.published_at??null,livePublishedBy:c===void 0?null:up(c.published_by),previewUpdatedAt:r}}async function Ip(e,t,n){let r=Ep(t),i=n?.baseLiveVersion??null;return r===null||i===null||On(r,i)!==0?I(null):hp({...e,app:t},r)}var TA="Run `appbuilder app merge` to merge Live into this folder, then `appbuilder app push` and publish again. Only if the user explicitly wants to overwrite Live: pass --force.",NA="Run `appbuilder app push` to save this folder as your preview again (the push records what it is based on), then publish. Only if the user explicitly wants to publish the preview as it is: pass --force.";function Tp(e){let t=e.livePublishedBy===null?"":` by ${e.livePublishedBy}`,n=e.livePublishedAt===null?"":` at ${e.livePublishedAt}`,r=Ka("your preview",e.baseLiveVersion,pA),i=e.liveVersion===null?`There's no Live version, and the latest release is ${Gr(e.comparedVersion)}`:`Live is ${Gr(e.liveVersion)}`;switch(e.reason){case"live_moved":return`${i}${e.liveVersion===null?"":` (published${t}${n})`}, but ${r}. Publishing would overwrite the changes in between.`;case"base_ahead":return`${i}, but ${r}, a later version that is no longer Live. Publishing could overwrite changes this folder doesn't have.`;case"base_unknown":return`Your preview's source doesn't say what it's based on (that record is missing or can't be read), so publishing it could overwrite changes. ${i}.`;case"preview_replaced":return Rp;case"base_replaced":return`${i}, and ${r}, but v${e.baseLiveVersion??""} on this business isn't the version your preview was based on (the app or that version was deleted and created again). Publishing could overwrite changes your preview doesn't have.`;case null:return"No conflict."}}function Np(e){return{...H("publish_conflict",Tp(e),{hint:e.reason==="base_unknown"?NA:TA}),conflict:e}}var RA="Your preview isn't the one this folder last pushed or restored: it was saved again from another folder or machine, and that's what publishing releases.";async function $A(e,t,n){let r=it(e);if(r?.previewSourcePackageId!==void 0&&r.previewSourcePackageId!==t)return[RA];if(r?.previewRestoredFrom!==void 0)return[`Your preview is version ${r.previewRestoredFrom} restored with \`appbuilder app rollback\`, not this folder's source.`];let i=r?.lastPushedSourceHash??null;if(i===null)return["No push from this folder is recorded, so your preview could not be compared with it."];let o;try{o=lo((await n.zipSourceDir(n.cwd)).bytes)}catch(s){return[`Couldn't compare this folder with your preview: ${je(s)}`]}return o===i?[]:["This folder changed since your last push. Publishing releases the preview as pushed; run `appbuilder app push` first to include the changes."]}function OA(e,t){let n=e.artifacts,r=F(n)?n[t]:void 0;return Array.isArray(r)?r:[]}var sn=e=>`You have no preview of ${e} on this business. Push one first with \`appbuilder app push\`.`;function DA(e){let t=[...uo(e),...e.live_version===null?[]:[e.live_version]].filter(n=>/^\d+$/.test(n)).map(Number).reduce((n,r)=>Math.max(n,r),0);return String(t+1)}var LA="Your preview's source couldn't be read, so what it's based on can't be checked, and publish stops even with --force. Try again; if it keeps failing, run `appbuilder app push` to save your preview again.";async function ho(e,t,n){let{app:r,api:i,credentials:o}=e,s=t.force===!0;if(r===null)return H("no_preview",sn(e.baseApiName));let a;try{a=await i.getPreview(r.api_name,o.userId)}catch(b){return $t(b)?H("no_preview",sn(e.baseApiName)):z(b)}let c=a.thumbnail;if(c==null||c==="")return H("thumbnail_required","Your preview has no thumbnail, and a release needs one. Add thumbnail.png to the app, run `appbuilder app push`, then publish again.");if(typeof a.source_filesystem_package!="string"||a.source_filesystem_package==="")return H("preview_incomplete","Your preview has no source package. Run `appbuilder app push` to save it again, then publish.");let l=e.yourPreview?.updated??null,d=a.source_filesystem_package,u={entry:it(e),app:r,previewUpdatedAt:l,previewSourcePackageId:d};if(t.expectPreview!==void 0&&d!==t.expectPreview)return Ma(ao({...u,lineage:null,comparedSourcePackageId:null}));let f=await Wa(i,d);if(!f.ok)return{...f,hint:f.hint??LA};let{lineage:g}=f.value,p=await Ip(e,r,g);if(!p.ok)return p;let m=ao({...u,lineage:g,comparedSourcePackageId:p.value});if(m.conflict&&!s)return Np(m);let h=await $A(e,d,n);return m.conflict&&h.push(`${Tp(m)} Publishing anyway because of --force.`),I({summary:Xe(e),apiName:r.api_name,previewUpdatedAt:l,conflictCheck:m,force:s,forced:m.conflict,nextReleaseAtLeast:DA(r),previewSourcePackageId:d,lineage:g,jsActionTemplates:OA(a,"js_action_templates"),warnings:h})}var Rp="Your preview changed after this publish was planned (it was pushed again, from this or another folder or machine), so it wasn't published.",BA="Run `appbuilder app publish` again to review the preview as it is now.",FA="The preview published isn't the one this publish reviewed (it was pushed again, from another folder or machine), so this folder's base wasn't advanced.",jA=(e,t)=>`Couldn't confirm that release ${e} is the preview this publish reviewed (${t}), so this folder's base wasn't advanced.`;function Ma(e){return{...H("publish_conflict",Rp,{hint:BA}),conflict:{...e,conflict:!0,reason:"preview_replaced"}}}async function yo(e,t,n,{isAborted:r=()=>!1}={}){let i=it(e),o;try{if(t.force){let l;try{l=(await e.api.getPreview(t.apiName,e.credentials.userId)).source_filesystem_package}catch(d){return $t(d)?H("no_preview",sn(e.baseApiName)):z(d)}if(l!==t.previewSourcePackageId)return Ma(t.conflictCheck)}else{let l=Wr(await e.api.listApps(e.baseApiName),e.baseApiName);if(l===null)return H("no_preview",sn(e.baseApiName));let d;try{d=await e.api.getPreview(l.api_name,e.credentials.userId)}catch(p){return $t(p)?H("no_preview",sn(e.baseApiName)):z(p)}let u={entry:i,app:l,previewUpdatedAt:Ua(l,e.credentials.userId)?.updated??null,previewSourcePackageId:d.source_filesystem_package};if(d.source_filesystem_package!==t.previewSourcePackageId)return Ma(ao({...u,lineage:null,comparedSourcePackageId:null}));let f=await Ip(e,l,t.lineage);if(!f.ok)return f;let g=ao({...u,lineage:t.lineage,comparedSourcePackageId:f.value});if(g.conflict)return Np(g)}if(r())return Rt();o=await e.api.promotePreview(t.apiName,e.credentials.userId)}catch(l){return z(l)}let s=[];if(i===void 0)return I({apiName:o.api_name,liveVersion:o.version,previousLiveVersion:t.summary.liveVersion,remembered:!1,warnings:s});let a=i.previewRestoredFrom===void 0&&t.conflictCheck.previewSourceMatches===!0;if(a)try{(await e.api.getVersion(o.api_name,o.version)).source_filesystem_package!==t.previewSourcePackageId&&(a=!1,s.push(FA))}catch(l){a=!1,s.push(jA(o.version,je(l)))}let c=await Yr(e,l=>{let d=an(l,...Ln);return a?nr(d,o.version,t.previewSourcePackageId):d},n);return I({apiName:o.api_name,liveVersion:o.version,previousLiveVersion:t.summary.liveVersion,remembered:c===null,warnings:[...s,...c===null?[]:[Dn(c)]]})}var MA=e=>e.toISOString().replace(/[-:]/g,"").replace(/\.\d+Z$/,"Z");function zA(e,t){return e===void 0?"No base version is recorded for this folder, and its files don't match a released version.":e===null?"This folder was started before the app had a Live version, so there is nothing to merge against.":t?`The base version v${e} no longer exists, so there is nothing to merge against.`:`The base version v${e} couldn't be used.`}function UA(e,t){let n=["--release",t];return[...uo(e).filter(r=>On(r,t)<0).slice(0,wp).map(r=>({value:`base:${r}`,label:`Merge, if this folder was copied from v${r}`,args:[],argv:["appbuilder","app","merge",...n,"--base",r,"--yes"]})),{value:"accept",label:`This folder already contains v${t}`,args:[],argv:["appbuilder","app","merge",...n,"--accept-live-base","--yes"]}]}async function VA(e){try{return I((await e.zipSourceDir(e.cwd)).bytes)}catch(t){return z(t)}}async function bo(e,t,n){let r=Ot(e);if(r===null)return Zr(e,"merge");let i;if(t.version===void 0){if(r.app.live_version===null)return H("not_found",`${e.baseApiName} has no Live version to merge.`);i=r.app.live_version}else{let y=oo(t.version);if(!y.ok)return y;i=y.value}let o=Ha(it(e)),s=o===void 0?"none":"recorded",a=null,c=[];if(t.base!==void 0){let y=oo(t.base);if(!y.ok)return y;o=y.value,s="flag"}else if(t.acceptLiveBase!==!0&&typeof o=="string"){let y=await rr(e);if(!y.ok)return y;(y.value.status==="replaced"||y.value.status==="gone")&&(c.push((y.value.status==="replaced"?Ga:Ja)(y.value.version)),o=void 0,s="none")}let l=await Ya(it(e),n),d=l.length===0?[]:[`These files still have conflict markers from an earlier merge: ${l.join(", ")}. Resolve them before pushing.`],u=()=>({summary:Xe(e),targetVersion:i,targetIsLive:on(r.app.live_version,i),baseVersion:o,baseSource:s,targetSourcePackageId:a,notices:c,warnings:d});if(t.acceptLiveBase===!0){let y=await so(r,i);return y.ok?(a=y.value.source_filesystem_package,I({...u(),kind:"accept"})):y}if(o===void 0){let y=await VA(n);if(!y.ok)return y;let C=await kp(e,y.value);if(!C.ok)return C;C.value!==null&&(o=C.value.version,s="detected",c.push(Ap(C.value.version)),on(C.value.version,i)&&(a=C.value.sourceId))}if(typeof o=="string"&&on(o,i)){if(s==="flag"){let y=await so(r,i);if(!y.ok)return y;a=y.value.source_filesystem_package}return I({...u(),kind:"up_to_date",ignoredIncoming:[],advancesBase:s!=="recorded"})}let f=await Jr(r,i);if(!f.ok)return f;let g=f.value.zip,p=null;a=f.value.sourceId;let m=!1;if(typeof o=="string"){let y=await Jr(r,o);if(y.ok)p={version:o,zip:y.value.zip};else if(y.code==="not_found")m=!0;else return y}let h;try{h=await n.planMerge({pluginDir:n.cwd,base:p,live:{version:i,zip:g}})}catch(y){return z(y)}let b=(y,C)=>I({...u(),kind:"fallback",reason:y,detail:C,liveZip:g,dir:$n(n.cwd,".kizenapp",`live-v${i}-${MA(n.now())}`),choices:UA(r.app,i)});switch(h.status){case"no_base":return b("no_base",zA(o,m));case"git_unavailable":return b("git_unavailable",h.reason);case"up_to_date":return I({...u(),kind:"up_to_date",ignoredIncoming:h.ignoredIncoming,advancesBase:!0});case"ready":return I({...u(),kind:"merge",plan:h})}}var Ba={written:[],deleted:[],conflicted:[],deletedOnLive:[],deletedLocally:[],binaryConflicts:[],ignoredIncoming:[]};function HA(e){return{written:e.written??[],deleted:e.deleted??[],conflicted:e.conflicted??[],deletedOnLive:e.deletedOnLive??[],deletedLocally:e.deletedLocally??[],binaryConflicts:e.binaryConflicts??[],ignoredIncoming:e.ignoredIncoming??[]}}var KA=e=>e.conflicted.filter(t=>!e.deletedOnLive.includes(t)&&!e.deletedLocally.includes(t));async function wo(e,t,n,r={}){let i=async s=>{let a=await Yr(e,c=>{let l=nr(c,t.targetVersion,t.targetSourcePackageId);return s===void 0?l:s.length===0?an(l,"conflictedPaths"):{...l,conflictedPaths:s}},n);return a===null?[]:[`${Dn(a)} Run \`appbuilder app merge --accept-live-base${t.targetIsLive?"":` --release ${t.targetVersion}`} --yes\` once it can be written.`]},o=(s,a,c,l)=>({status:s,targetVersion:t.targetVersion,targetIsLive:t.targetIsLive,baseLiveVersion:l?t.targetVersion:t.baseVersion,lists:a,markedPaths:[],remembered:l&&c.length===0,warnings:c});switch(t.kind){case"accept":return I(o("accepted",Ba,await i(),!0));case"up_to_date":{let s={...Ba,ignoredIncoming:t.ignoredIncoming};return t.advancesBase?I(o("up_to_date",s,await i(),!0)):I({...o("up_to_date",s,[],!1),remembered:!0})}case"merge":{let s;try{s=await n.applyMerge(t.plan,r)}catch(u){return z(u)}if(s.status==="cancelled")return Rt();if(s.status!=="merged"&&s.status!=="conflicts")return H("local_error",`The merge didn't apply (${s.status}). Run it again.`);let a=HA(s),c=await Ya(it(e),n),l=await Cp(a.written,n,PA),d=[...new Set([...c,...KA(a),...l])].sort();return I({...o(s.status,a,await i(d),!0),markedPaths:d})}case"fallback":{let s;try{n.ensureGitignore(n.cwd),s=await n.unzipToDir(t.liveZip,t.dir)}catch(a){return z(a)}return I({...o("fallback",Ba,[],!1),extracted:{dir:t.dir,written:s.written.length,skipped:s.skipped},remembered:!1})}}}async function vo(e,t,n){let r=oo(t);if(!r.ok)return r;let i=Ot(e);if(i===null)return Zr(e,"roll back");let o=r.value,s=await Jr(i,o);if(!s.ok)return s;let a;try{a=await n.makeTempDir()}catch(p){return z(p)}let c;try{let p=$n(a,"source");await n.unzipToDir(s.value.zip,p),c=await Pp(p,n)}catch(p){c=z(p)}finally{await n.removeDir(a).catch(()=>{})}if(!c.ok)return{...c,message:`Version ${o}'s source couldn't be packaged, so it can't be restored: ${c.message}`};let[l]=c.value.deployable;if(l.api_name!==e.baseApiName)return H("local_error",`Version ${o}'s source is for ${l.api_name}, not ${e.baseApiName}.`);let d=await fA(e,Xe(e).liveVersion);if(!d.ok)return d;let u;try{u=ga(s.value.zip,d.value)}catch(p){return z(p)}let f={exists:e.yourPreview!==null,updated:e.yourPreview?.updated??null},g=[...f.exists?[`This replaces your current preview (last updated ${f.updated??"unknown"}).`]:[],`This folder's source isn't changed, and the next \`appbuilder app push\` replaces the restored preview with it. To keep working from version ${o}'s source, publish this preview, then pull the new Live version with \`appbuilder app pull\`.`];return I({summary:Xe(e),version:o,preview:f,deployable:l,source:u,warnings:g})}async function ko(e,t,n,{isAborted:r=()=>!1}={}){let i,o;try{let a;if([o,a]=await Promise.all([e.api.uploadFile(t.source,{filename:`${e.baseApiName}-source.zip`,contentType:Sp,source:"plugin_app_source_filesystem"}),_p(e.api,t.deployable.thumbnail)]),r())return Rt();let c=Ta(t.deployable,{release:!1,sourcePackageId:o,thumbnailId:a});i=await e.api.publish(c)}catch(a){return z(a)}let s=await Yr(e,a=>({...a,previewSourcePackageId:o,previewRestoredFrom:t.version,lastPushedSourceHash:null}),n);return I({apiName:i.api_name,version:t.version,sourcePackageId:o,remembered:s===null,warnings:s===null?[]:[Dn(s)]})}function Ao(e,t){return e!==void 0&&t?H("usage_error","Pass either <version> or --preview, not both."):e!==void 0?I({kind:"release",version:e}):t?I({kind:"preview"}):H("usage_error","Missing argument <version>. Usage: appbuilder app pull <version>, or appbuilder app pull --preview for your preview.")}var Fa=(e,t)=>t.startsWith(e+tA),WA="Your preview has no source package. Push it again with `appbuilder app push`.";async function xo(e,t,n,r){let i;if(t.kind==="release"){let c=oo(t.version);if(!c.ok)return c;if(e.app===null)return Zr(e,"pull");i={source:"release",version:c.value}}else{if(e.app===null||e.yourPreview===null)return H("no_preview",sn(e.baseApiName));i={source:"preview",updated:e.yourPreview.updated}}let o=op(r.cwd),s=n.out===void 0||n.out===""?$n(eA(o),i.source==="release"?`${e.baseApiName}-v${i.version}`:`${e.baseApiName}-preview`):op(o,n.out);if(s===o||Fa(s,o))return H("usage_error",`${s} holds the plugin folder; pass --out <dir> to choose a new folder.`);if(await r.pathExists(s))return H("usage_error",`${s} already exists; pass --out <dir> to choose a new folder.`);let a=Fa(o,s)&&!Fa($n(o,".kizenapp"),s)?[`${s} is inside the plugin folder, so the next \`appbuilder app push\` includes it unless .gitignore or .kizenignore excludes it.`]:[];return I({summary:Xe(e),...i,dir:s,warnings:a})}var GA=e=>`No base is recorded for ${e}. A push from there finds one when it can, or stops with \`base_required\`.`;async function JA(e,t){let n=await Jr(e,t);return n.ok?I({zip:n.value.zip,entry:nr(Va(e.stateKey),t,n.value.sourceId)}):n}async function qA(e){let t;try{t=await e.api.getPreview(e.app.api_name,e.credentials.userId)}catch(a){return $t(a)?H("no_preview",sn(e.baseApiName)):z(a)}let n=t.source_filesystem_package;if(typeof n!="string"||n==="")return H("preview_incomplete",WA);let r=await Wa(e.api,n);if(!r.ok)return r;let i=await bp(e,r.value.lineage);if(!i.ok)return i;let o=Va(e.stateKey),s=i.value;return I({zip:r.value.zip,entry:{...s===null?o:nr(o,s.baseLiveVersion,s.baseSourcePackageId),previewSourcePackageId:n},preview:{sourcePackageId:n,base:xp(s?.baseLiveVersion)}})}async function Po(e,t,n,{isAborted:r=()=>!1}={}){let i=Ot(e);if(i===null)return t.source==="release"?Zr(e,"pull"):H("no_preview",sn(e.baseApiName));let o=t.source==="release"?await JA(i,t.version):await qA(i);if(!o.ok)return o;if(r())return Rt();let s;try{s=await n.unzipToDir(o.value.zip,t.dir)}catch(u){return u instanceof Fr?H("usage_error",`${t.dir} already exists; pass --out <dir> to choose a new folder.`):z(u)}let a;try{await n.writeAppState(t.dir,Aa(Vr(),o.value.entry)),a=null}catch(u){a=je(u)}let{preview:c}=o.value,l=t.source==="release"?t.version:c?.base.version??null,d=c!==void 0&&!c.base.recorded;return I({dir:t.dir,written:s.written,skipped:s.skipped,remembered:a===null,warnings:[...d?[GA(t.dir)]:[],...a===null?[]:[l===null?Dn(a):`${Dn(a)} Before pushing from ${t.dir}, run \`appbuilder app merge --accept-live-base --release ${l} --yes\` there.`]],...c===void 0?{}:{preview:c}})}var Ln=["previewSourcePackageId","previewRestoredFrom"],YA=["folderBaseLiveVersion","folderBaseSourcePackageId",...Ln],$p=(e,t)=>Bn(e).find(n=>n.status==="preview"&&n.preview_owner?.id===t)??null,Op=(e,t)=>Bn(e).every(n=>n.status==="preview"&&n.preview_owner?.id===t),sp=e=>typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null,Dp=e=>e.fullName??e.id,co=e=>typeof e=="string"&&e!==""?e:null,ZA=e=>{let t=Bn(e).flatMap(n=>n.status==="preview"&&n.preview_owner!==null?[`${co(n.preview_owner.full_name)??"unknown"} (${n.preview_owner.id})`]:[]);return t.length===0?void 0:`Previews of ${e.base_api_name}: ${t.join(", ")}. Pass one of these user ids to --owner.`},XA=(e,t,n)=>n?`You have no preview of ${e} on this business.`:`User ${t} has no preview of ${e} on this business.`,Lp=e=>`This preview is the only version of ${e}, so deleting it deletes the whole app from this business, with its settings and secrets.`,QA=e=>`This is ${e}'s preview, not yours.`,za=(e,t)=>`${String(e)} other ${e===1?"user is":"users are"} using this preview.${t?"":" Deleting it switches them to their own preview, or Live, and notifies them."}`,Za=e=>e.yours?"Your preview":`${Dp(e)}'s preview`,Bp=e=>`Run \`appbuilder app preview delete --owner ${e.id}\` to review it as it is now.`,ap=(e,t)=>`${Za(t)} of ${e} no longer exists, so nothing was deleted.`,Fp=e=>`${Za(e)} was pushed again after this delete was reviewed, so nothing was deleted. ${Bp(e)}`,jp=e=>`${Za(e)} is now the app's only version, so deleting it would delete the whole app, which wasn't agreed to. Nothing was deleted. ${Bp(e)}`;function Co(e,t){let{app:n,credentials:r}=e,i=(t.owner??r.userId).trim();if(i==="")return H("usage_error","--owner needs the user id of the preview to delete.");let o=i===r.userId;if(n===null)return H("not_found",`${e.baseApiName} isn't published to this business yet, so it has no preview to delete.`);let s=$p(n,i);if(s===null){let f=ZA(n);return H("not_found",XA(e.baseApiName,i,o),f===void 0?{}:{hint:f})}let a={id:i,fullName:co(s.preview_owner?.full_name),yours:o};if(t.expectUpdated!==void 0&&s.updated!==t.expectUpdated)return H("preview_changed",Fp(a));let c=sp(s.active_users_count),l=c===null?null:Math.max(0,c-(s.is_current_for_viewer?1:0)),d=Op(n,i),u=[...d?[Lp(co(n.name)??e.baseApiName)]:[],...o?[]:[QA(Dp(a))],...l!==null&&l>0?[za(l,d)]:[]];return I({summary:Xe(e),apiName:n.api_name,owner:a,preview:{updated:s.updated,activeUsersCount:c,installedCount:sp(s.installed_count),otherActiveUsersCount:l},deletesApp:d,warnings:u})}var Mp=(e,t)=>e.deletesApp&&!t?H("preview_changed",jp(e.owner)):null,ex=e=>`The preview was deleted, but whether the app still exists couldn't be checked: ${e}`;async function So(e,t,n,{isAborted:r=()=>!1}={}){let{api:i,baseApiName:o}=e;if(r())return Rt();let s;try{s=Wr(await i.listApps(o),o)}catch(g){return z(g)}let a=s===null?null:$p(s,t.owner.id);if(s===null||a===null)return H("not_found",ap(o,t.owner));if(a.updated!==t.preview.updated)return H("preview_changed",Fp(t.owner));if(!t.deletesApp&&Op(s,t.owner.id))return H("preview_changed",jp(t.owner));if(r())return Rt();try{await i.deletePreview(s.api_name,t.owner.id)}catch(g){return $t(g)?H("not_found",ap(o,t.owner)):z(g)}let c=[],l;try{l=Wr(await i.listApps(o),o)===null}catch(g){l=null,c.push(ex(je(g)))}let d=it(e),u=t.owner.yours&&d!==void 0&&Ln.some(g=>g in d),f=null;if(l===!0){let{environment:g,businessId:p,baseApiName:m}=e.stateKey,h={environment:g,businessId:p,baseApiName:m};f=await fp(n.cwd,b=>Rd(b,h,y=>({...an(y,...YA),lastPushedSourceHash:null})),n)}else u&&(f=await Yr(e,g=>an(g,...Ln),n));return I({status:"deleted",appDeleted:l,remembered:f===null,warnings:[...c,...f===null?[]:[Dn(f)]]})}function _o(e,t){if(!e.deletesApp||t.appDeleted!==!1)return e;let n=Lp(co(e.summary.name)??e.summary.baseApiName),r=e.preview.otherActiveUsersCount;return{...e,deletesApp:!1,warnings:e.warnings.flatMap(i=>i===n?[]:r!==null&&i===za(r,!0)?[za(r,!1)]:[i])}}var ir=me;function Fn(e){return Array.isArray(e)?e.flatMap(t=>{if(!F(t)||typeof t.api_name!="string"||t.api_name==="")return[];let n=t.hint_object_name;return[{apiName:t.api_name,name:typeof t.name=="string"&&t.name!==""?t.name:t.api_name,hintObjectName:typeof n=="string"&&n!==""?n:null}]}):[]}var zp=e=>{let t=e.artifacts;return Fn(F(t)?t.js_action_templates:void 0)},tx=e=>e.object_name??e.entity_name??e.name,nx=e=>({id:e.id,objectId:e.custom_object.id,objectName:e.custom_object.name,label:tx(e.custom_object),includePerformAction:e.include_perform_action});function Up(e){let{templates:t,installed:n,liveApiNames:r,associations:i}=e;return t.map(o=>{let s=i.filter(l=>l.browser_js_action_template.api_name===o.apiName).map(nx),a=r?.has(o.apiName)??!1,c=s.length>0?"linked":!n||a?"unlinked":"unknown";return{...o,status:c,inLive:a,links:s}})}var Qa=e=>{let t=new Set;return e.filter(n=>t.has(n.apiName)?!1:(t.add(n.apiName),!0))},rx=e=>e instanceof q&&e.kind==="not_found";async function ec(e,t){let{app:n,api:r}=e;if(n===null){let s=t.kind==="version"?Qa(t.templates):[];return I({status:"not_installed",liveVersion:null,actions:Up({templates:s,installed:!1,liveApiNames:null,associations:[]})})}let i=t.kind==="live"?t.version:n.live_version;if(t.kind==="version"&&t.templates.length===0)return I({status:"checked",liveVersion:i,actions:[]});let o=e.yourPreview;try{let[s,a,c]=await Promise.all([i===null?null:r.getVersion(n.api_name,i).then(zp),t.kind==="app"&&o!==null?r.getPreview(n.api_name,e.credentials.userId).then(zp).catch(d=>{if(rx(d))return[];throw d}):[],i===null?[]:r.listActionAssociations(n.api_name)]),l=t.kind==="version"?t.templates:[...s??[],...a];return I({status:i===null?"no_live_version":"checked",liveVersion:i,actions:Up({templates:Qa(l),installed:!0,liveApiNames:s===null?null:new Set(s.map(d=>d.apiName)),associations:c})})}catch(s){return z(s)}}async function ot(e,t){let n=await ec(e,t);return n.ok?n.value:Kp(e,t,n.message)}function Kp(e,t,n){let r=t.kind==="version"?Qa(t.templates):[];return{status:"failed",liveVersion:t.kind==="live"?t.version:e.app?.live_version??null,actions:r.map(i=>({...i,status:"unknown",inLive:!1,links:[]})),error:n}}async function Eo(e,t){let n={kind:"version",templates:t},r=await mp(e);return r.ok?ot(r.value,n):Kp(e,n,r.message)}var Vp=e=>e.map(t=>t.apiName).join(", "),Hp="with `--json`, run an action's `linkArgv`, `linkMenuArgv` or `linkNoMenuArgv`; at a terminal, run `appbuilder app actions link` to pick them";function Ge(e){let t=e.actions.filter(i=>i.status==="unlinked"),n=e.actions.filter(i=>i.status==="unknown"),r=[];return t.length>0&&r.push(`These JS actions aren't linked to any object: ${Vp(t)}. Link them: ${Hp}.`),n.length>0&&e.status!=="failed"&&r.push(`These JS actions aren't in the Live version, so their links can't be listed and they may not be linked to any object: ${Vp(n)}. To make sure, link them: ${Hp}.`),r}var st=e=>e.status==="failed"?[`Couldn't check which JS actions are linked to objects: ${e.error??"unknown error"}. Run \`appbuilder app actions list\` to check.`]:[];function Io(e){return!e.actions.some(n=>n.status!=="linked")&&e.status!=="failed"?[]:[{step:"actions",args:["actions","list"]},...e.actions.flatMap(n=>n.status==="unlinked"&&n.hintObjectName!==null?[{step:"link",args:["actions","link",n.apiName,n.hintObjectName]}]:[])]}var Xa=(e,t)=>e.localeCompare(t,void 0,{sensitivity:"accent"})===0;function To(e,t,n){let r=t.trim(),i=e.find(a=>a.id===r)??e.find(a=>a.name===r);if(i!==void 0)return I(i);let o=e.filter(a=>Xa(a.name,r)||Xa(a.objectName,r)||a.entityName!==null&&Xa(a.entityName,r)),[s]=o;if(s!==void 0&&o.length===1)return I(s);if(o.length>1){let a=o.map(c=>({value:c.id,label:`${c.objectName} (${c.name})`,args:[],argv:n(c)}));return ir("needs_choice",`Several objects match "${t}". Pick one by its api name or id.`,{choice:"object",choices:a})}return ir("not_found",`No object "${t}" on this business that you can see. Pass an object's api name (like client_client) or its id.`)}var Wp=e=>({id:e.id,name:e.name,label:e.objectName});async function No(e){let t=await ec(e,{kind:"app"});return t.ok?I({summary:Xe(e),check:t.value}):t}var ix=e=>ir("not_found",`${e.baseApiName} isn't on this business yet, so it has no JS actions to link. Push it first with \`appbuilder app push\`.`),ox=(e,t)=>ir("not_found",`${e.baseApiName} has no JS action "${t}" in its Live version or your preview. If it's new, push this folder first with \`appbuilder app push\`.`);async function tc(e){let{app:t}=e;if(t===null)return ix(e);let n,r;try{[r,n]=await Promise.all([ec(e,{kind:"app"}),e.api.listObjects()])}catch(i){return z(i)}return r.ok?I({appApiName:t.api_name,check:r.value,objects:n}):r}function Ro(e,t,n){let r=t.check.actions.find(i=>i.apiName===n);return r===void 0?ox(e,n):I(r)}async function Gp(e,t,n,r){let i=await tc(e);if(!i.ok)return i;let o=To(i.value.objects,n,r);if(!o.ok)return o;let s=Ro(e,i.value,t);return s.ok?I({choices:i.value,action:s.value,object:o.value}):s}var sx=(e,t)=>`${e} is in the Live version, so this change to its link to ${t} applies to everyone using Live as soon as it's made.`,Jp=(e,t)=>e.inLive?[sx(e.apiName,t)]:[],ax=e=>`${e} isn't in the Live version, so an existing link to this object can't be seen. If there is one, linking reports it as already linked and leaves its menu setting as it is.`;async function qp(e,t,n){let r=await Gp(e,t.action,t.object,n);if(!r.ok)return r;let{choices:i,action:o,object:s}=r.value;return I(nc(e,i,o,s,{...t.menu!==void 0&&{menu:t.menu}}))}function nc(e,t,n,r,{menu:i}){let o=n.links.find(l=>l.objectId===r.id),s=o===void 0?null:{id:o.id,includePerformAction:o.includePerformAction},a,c;return s===null?(a="create",c=i??!1):i===void 0||i===s.includePerformAction?(a="up_to_date",c=s.includePerformAction):(a="update",c=i),{summary:Xe(e),appApiName:t.appApiName,action:n,object:Wp(r),change:a,includePerformAction:c,existing:s,notices:a==="create"&&!n.inLive?[ax(n.apiName)]:[],warnings:a==="up_to_date"?[]:Jp(n,r.name)}}var cx=(e,t)=>`${e} was already linked to ${t}. Its link isn't listed (the action isn't in the Live version), so its menu setting couldn't be checked or changed.`,lx=(e,t)=>`${e} was already linked to ${t} (the link was made after this command listed the links), so nothing was changed and its menu setting wasn't set. Run \`appbuilder app actions list\`, then link it again to set the menu setting.`,ux=e=>e instanceof q&&e.status===400&&/already exists/i.test(e.message),dx=e=>e instanceof q&&e.status===400&&/Browser JS action template not found/i.test(e.message),px=e=>`${e} is only in your preview, and Kizen couldn't find it to link it. Kizen environments without the fix for linking preview-only actions (KZN-19521) only link actions in Live: publish it first, then link it.`,Yp=()=>ir("local_error",qa);async function $o(e,t,{isAborted:n=()=>!1}={}){let r=t.includePerformAction;if(t.change==="up_to_date"||r===null)return I({status:"up_to_date",warnings:[]});if(n())return Yp();try{return t.change==="update"&&t.existing!==null?(await e.api.updateActionAssociation(t.appApiName,t.existing.id,r),I({status:"updated",warnings:[]})):(await e.api.createActionAssociation({appApiName:t.appApiName,actionApiName:t.action.apiName,objectId:t.object.id,includePerformAction:r}),I({status:"created",warnings:[]}))}catch(i){return t.change==="create"&&ux(i)?I({status:"already_linked",warnings:[(t.action.inLive?lx:cx)(t.action.apiName,t.object.name)]}):t.change==="create"&&!t.action.inLive&&dx(i)?{...z(i),hint:px(t.action.apiName)}:z(i)}}var mx=(e,t)=>`${e} isn't linked to ${t}.`,rc=e=>`${e} isn't in the Live version, so its links can't be listed or removed here. If it was linked while only in a preview, publish it first, then unlink it.`;async function Zp(e,t,n){let r=await Gp(e,t.action,t.object,n);if(!r.ok)return r;let{choices:i,action:o,object:s}=r.value;return ic(e,i,o,s)}function ic(e,t,n,r){let i=n.links.find(o=>o.objectId===r.id);return i===void 0?ir("not_found",mx(n.apiName,r.name),n.inLive?{}:{hint:rc(n.apiName)}):I({summary:Xe(e),appApiName:t.appApiName,action:n,object:Wp(r),associationId:i.id,includePerformAction:i.includePerformAction,warnings:Jp(n,r.name)})}async function Oo(e,t,{isAborted:n=()=>!1}={}){if(n())return Yp();try{await e.api.deleteActionAssociation(t.associationId)}catch(r){return z(r)}return I({status:"unlinked"})}var fx={local:"HEAD",incoming:"live"};function Je(e,t,n,r){let i={json:n.json===!0,deps:r},o=Rn(n,r.processEnv),s=d=>[...d,...d[2]==="push"&&n.allowProduction===!0?["--allow-production"]:[],...o,...Da(i)],a=d=>d.map(u=>({...u,argv:s(u.argv??[])})),c=(d,u)=>u==="base"||u==="object"?s(d.argv??[]):Tt(e,[...t,...d.args,...rn(n,r.processEnv)],i),l=d=>Tt("appbuilder app",[...d,...o],i);return{output:i,runnable:a,appArgv:l,pin:d=>{o=to(n,d)},apply:(d,u)=>({applyArgv:l([...d,"--yes",...u?["--allow-production"]:[]]),requiresProductionConsent:u}),fail:d=>{let u=d.conflict?.reason,f=d.code==="publish_conflict"?[u==="preview_replaced"?{step:"publish",argv:l(["publish"])}:u==="base_unknown"?{step:"push",argv:l(["push"])}:{step:"merge",argv:l(["merge"])}]:void 0;Nt(i,f===void 0?d:{...d,next:f},c)}}}async function em(e,t,n){let r=await Nn(e,t);return r.ok?(n(r.value.credentials),ze(t,r.value.notices),I({credentials:r.value.credentials,client:r.value.client})):r}async function tm(e,t,n){let r=t;if(r===void 0)try{r=await n.readManifestApiName(n.cwd)}catch(o){return z(o)}let i=await qr({...e,baseApiName:r},n);return i.ok&&ze(n,i.value.notices),i}async function Dt(e,t,{fail:n,pin:r}){let i=await em(e,t,r);if(!i.ok)return n(i),null;let o=await tm(i.value,void 0,t);return o.ok?o.value:(n(o),null)}var ti=e=>e===null?"none":`v${e}`;function qe(e){return[`Environment: ${e.environment}${e.isProduction?" (production)":""}`,`Business: ${e.businessId}`,e.apiName===null?`App: ${e.baseApiName} (not published to this business yet)`:`App: ${e.name??e.baseApiName} (${e.apiName})`,`Live: ${ti(e.liveVersion)}`]}var wt=e=>({environment:e.environment,businessId:e.businessId,userId:e.userId,app:{baseApiName:e.baseApiName,apiName:e.apiName,name:e.name,liveVersion:e.liveVersion}}),Ce=(...e)=>`${e.filter(t=>typeof t=="string").join(`
|
|
863
863
|
`)}
|
|
864
|
-
`;async function
|
|
865
|
-
`)}function
|
|
864
|
+
`;async function vt(e){try{return await e.staleAgentFileWarnings(e.cwd)}catch{return[]}}var gx=(e,t)=>t.length===0?[]:[e,...t.map(n=>` ${n.label} \u2192 ${n.argv.map(ge).join(" ")}`)];function hx(e){let t=`${e.apiName} (${e.name})`;switch(e.status){case"linked":return` ${t}: linked to ${e.links.map(n=>`${n.label} (${n.objectName}, menu: ${n.includePerformAction===!0?"on":"off"})`).join(", ")}`;case"unlinked":return` ${t}: not linked${e.hintObjectName===null?"":` (hint: ${e.hintObjectName})`}`;case"unknown":return` ${t}: not in Live, so its links can't be listed`}}var Qe=e=>e.actions.length===0?[]:["JS actions:",...e.actions.map(hx)],Xr=(e,t)=>Io(e).map(({step:n,args:r})=>({step:n,argv:t(r)})),oc="<object>",nm=(e,t)=>e.map(n=>({...n,links:n.links.map(r=>({...r,unlinkArgv:t(["actions","unlink",n.apiName,r.objectId])})),linkArgv:t(["actions","link",n.apiName,oc]),linkMenuArgv:t(["actions","link",n.apiName,oc,"--menu"]),linkNoMenuArgv:t(["actions","link",n.apiName,oc,"--no-menu"])})),Lo=(e,t,n)=>({status:e.status,liveVersion:e.liveVersion,...e.error===void 0?{}:{error:e.error},actions:nm(e.actions,n),next:t});function jn(e,t,n,r,i){Pe(e,{ok:!0,applied:!1,dryRun:!0,reason:t.reason,...n,...r??{},next:[]},i),t.reason==="no_yes"&&e.deps.writeStderr(`${eo}
|
|
865
|
+
`)}function Xp(e){let t=[e.publishedAt===null?void 0:`published ${e.publishedAt}`,e.publishedBy===null?void 0:`by ${e.publishedBy}`].filter(n=>n!==void 0);return`v${e.version}${t.length===0?"":` (${t.join(" ")})`}`}var rm=e=>e.recorded?ti(e.version):"not recorded";function uc(e){let t=qe(e.summary).filter(r=>!r.startsWith("Live:")),n=[`Folder base: ${rm(e.base.folder)}`];return e.published?[...t,`Live: ${e.live===null?"none":Xp(e.live)}`,"Released:",...e.released.length===0?[" (none)"]:e.released.map(r=>` ${Xp(r)}`),"Previews:",...e.previews.length===0?[" (none)"]:e.previews.map(r=>` ${r.previewOwner?.fullName??"unknown"}${r.yours?" (yours)":""}, updated ${r.updated??"unknown"}`),...n]:[...t,"",`${e.summary.baseApiName} isn't published to this business yet.`,...n]}function yx(e,t){return e.base.liveMoved?[{step:"merge",argv:t(["merge"])}]:[{step:"push",argv:t(["push"])},{step:"publish",argv:t(["publish"])}]}async function im(e,t){let n=Je("appbuilder app versions",[],e,t),{output:r,fail:i}=n;try{let o=await Dt(e,t,n);if(o===null)return;let s=await rr(o);if(!s.ok){i(s);return}let a=po(o,s.value),c=await ot(o,{kind:"app"}),l=st(c),d=Xr(c,n.appArgv),u={...a,warnings:[...a.warnings,...Ge(c),...await vt(t)]};ze(t,l),Pe(r,{ok:!0,...wt(u.summary),published:u.published,live:u.live,released:u.released,previews:u.previews,yourPreview:u.yourPreview,base:u.base,jsActions:Lo(c,d,n.appArgv),notices:l,warnings:u.warnings,next:[...yx(u,n.appArgv),...d]},Ce(...uc(u),...Qe(c),...ee(u.warnings)))}catch(o){i(z(o))}}var bx=e=>`${e.path===void 0?"":`${e.path}: `}${e.message} (${e.rule})`,wx={recorded:"recorded for this folder",never_published:"the app has no Live version yet",detected:"matched exactly",preview:"matches your preview exactly; your preview's base, read from the server",base_from_preview:"continues your preview; your preview's base, read from the server"},Qr=e=>[...qe(e.summary),`Source: ${String(e.source.files)} files (${e.source.mode}), ${String(e.source.bytes)} bytes`,`Thumbnail: ${e.thumbnail?"yes":"no"}`,e.preview.exists?`Preview: replaces yours (last updated ${e.preview.updated??"unknown"})`:"Preview: new",`Base: ${ti(e.base.version)} (${wx[e.base.source]})`],dc=(e,t)=>`\u2713 Saved your preview of ${e} (${t.apiName})`;async function om(e,t){let n=Je("appbuilder app push",[],e,t),{output:r,fail:i,appArgv:o,apply:s}=n,a=["push",...e.force===!0?["--force"]:[],...e.baseFromPreview===void 0?[]:["--base-from-preview",e.baseFromPreview]];try{let c=await em(e,t,n.pin);if(!c.ok){i(c);return}let l=await mo(t);if(!l.ok){i(l);return}let{deployable:d,issues:u,source:f}=l.value;u.length>0&&t.writeStderr(`${We(u)}
|
|
866
866
|
`),f.notice!==void 0&&t.writeStderr(`${f.notice}
|
|
867
|
-
`);let g=await Xp(c.value,d.api_name,t);if(!g.ok){i(g);return}let m=g.value,p=await fo(m,l.value,{force:e.force===!0,...e.baseFromPreview!==void 0&&{baseFromPreview:e.baseFromPreview}},t);if(!p.ok){i(p);return}let h=p.value;ze(t,h.notices);let b=Ye(e,m.credentials.environment);if(!b.ok){i(b);return}let y=Fn(d.artifacts.js_action_templates),C=await bt(t),S=$=>{let V=ot($),X=Xr($,o);return ze(t,V),{jsNext:X,warnings:[...u.map(ux),...h.warnings,...Ge($),...C],notices:[...h.notices,...V],jsActions:Lo($,X,o)}},x={...yt(h.summary),source:h.source,thumbnail:h.thumbnail,preview:h.preview,base:h.base,conflictMarkers:h.conflictMarkers};if(b.value.kind==="dry-run"){let $=await it(m,{kind:"version",templates:y}),{warnings:V,notices:X,jsActions:ve}=S($);jn(r,b.value,{action:"push",...x,jsActions:ve,notices:X,warnings:V},s(a,h.summary.isProduction),Ce(...Qr(h),...Qe($),...Q(V)));return}let v=await go(m,l.value,h,t);if(!v.ok){i(v);return}let k=await Eo(m,y),{jsNext:P,warnings:w,notices:A,jsActions:_}=S(k),T=[...w,...v.value.warnings],L={...h,source:v.value.source};Pe(r,{ok:!0,applied:!0,dryRun:!1,action:"push",...x,jsActions:_,source:v.value.source,previewVersion:v.value.version,apiName:v.value.apiName,sourcePackageId:v.value.sourcePackageId,thumbnailId:v.value.thumbnailId,remembered:v.value.remembered,notices:A,warnings:T,next:[...P,{step:"publish",argv:o(["publish"])}]},Ce(uc(d.name,v.value),...Qr(L),...Qe(k),...Q(T)))}catch(c){i(z(c))}}function px(e,t){let n=e.reason==="base_unknown"?"your preview's source doesn't say what it's based on":`your preview's base ${ti(e.baseLiveVersion)}, read from its source on the server`;return`Conflict check: ${e.conflict?t?"conflict, overridden by --force":"conflict":"none"} (${n})`}var dc=e=>[...qe(e.summary),`Preview: last updated ${e.previewUpdatedAt??"unknown"}`,px(e.conflictCheck,e.forced)],pc=e=>`Publish: Live becomes the next release number (at least v${e.nextReleaseAtLeast})`,mc=(e,t)=>`\u2713 Published Live v${t.liveVersion} of ${e.summary.name??e.summary.baseApiName}`;async function rm(e,t){let n=Je("appbuilder app publish",[],e,t),{output:r,fail:i,apply:o,appArgv:s}=n,a=["publish",...e.force===!0?["--force"]:[]];try{let c=await $t(e,t,n);if(c===null)return;let l=await ho(c,{force:e.force===!0,...e.expectPreview!==void 0&&{expectPreview:e.expectPreview}},t);if(!l.ok){i(l);return}let d=l.value,u=Ye(e,c.credentials.environment);if(!u.ok){i(u);return}let f=dc(d),g=[...d.warnings,...await bt(t)],m={...yt(d.summary),previewUpdatedAt:d.previewUpdatedAt,conflictCheck:d.conflictCheck,forced:d.forced};if(u.value.kind==="dry-run"){let S=await it(c,{kind:"version",templates:Fn(d.jsActionTemplates)}),x=ot(S),v=[...g,...Ge(S)];ze(t,x),jn(r,u.value,{action:"publish",...m,nextReleaseAtLeast:d.nextReleaseAtLeast,jsActions:Lo(S,Xr(S,s),s),notices:x,warnings:v},o([...a,"--expect-preview",d.previewSourcePackageId],d.summary.isProduction),Ce(...f,pc(d),...Qe(S),...Q(v)));return}let p=await yo(c,d,t);if(!p.ok){i(p);return}let h=await it(c,{kind:"live",version:p.value.liveVersion}),b=ot(h),y=Xr(h,s),C=[...g,...p.value.warnings,...Ge(h)];ze(t,b),Pe(r,{ok:!0,applied:!0,dryRun:!1,action:"publish",...m,apiName:p.value.apiName,liveVersion:p.value.liveVersion,previousLiveVersion:p.value.previousLiveVersion,remembered:p.value.remembered,jsActions:Lo(h,y,s),notices:b,warnings:C,next:y},Ce(mc(d,p.value),...f,...Qe(h),...Q(C)))}catch(c){i(z(c))}}var st=(e,t)=>t.length===0?[]:[`${e} (${String(t.length)}):`,...t.map(n=>` ${n}`)];function cc(e){return[...st("Written",e.written),...st("Deleted",e.deleted),...st("Conflicted",e.conflicted),...st("Edited here, deleted on Live (kept)",e.deletedOnLive),...st("Deleted here, changed on Live (restored)",e.deletedLocally),...st("Binary files changed on both sides (yours kept)",e.binaryConflicts),...st("On Live but excluded here (not written)",e.ignoredIncoming)]}var Bo=(e,t)=>t?`Live v${e}`:`v${e}`,mx=e=>`Resolve the conflict markers in the files above: the side marked <<<<<<< HEAD is your file and the side marked >>>>>>> live is ${e}. Then run \`appbuilder app push\` and \`appbuilder app publish\`.`,fc="Merge it into this folder by hand and then record its base, or merge from the release this folder was copied from with --base <n>. Use --base only with the release it was really copied from: a wrong one drops the changes made since then.";function gc(e){let t=e.baseVersion===void 0?"not recorded":ti(e.baseVersion),n=Bo(e.targetVersion,e.targetIsLive);switch(e.kind){case"accept":return[`Base: ${t}`,`Record v${e.targetVersion} as this folder's base without merging.`];case"up_to_date":return[`Base: ${t}`,`This folder already includes v${e.targetVersion}.`,...st("On Live but excluded here (not written)",e.ignoredIncoming)];case"merge":return[`Merge ${n} into this folder (base ${t}).`,...cc(e.plan)];case"fallback":return[`Base: ${t}`,`Can't merge automatically: ${e.detail}`,`${n}'s source goes into ${e.dir}.`]}}function fx(e){let t={kind:e.kind,targetVersion:e.targetVersion,targetIsLive:e.targetIsLive,baseVersion:e.baseVersion??null,baseSource:e.baseSource,notices:e.notices};switch(e.kind){case"accept":return t;case"up_to_date":return{...t,ignoredIncoming:e.ignoredIncoming};case"merge":{let{written:n,deleted:r,conflicted:i,deletedOnLive:o,deletedLocally:s,binaryConflicts:a,ignoredIncoming:c}=e.plan;return{...t,written:n,deleted:r,conflicted:i,deletedOnLive:o,deletedLocally:s,binaryConflicts:a,ignoredIncoming:c}}case"fallback":return{...t,fallback:{reason:e.reason,detail:e.detail,dir:e.dir}}}}function gx(e){let t=(e.baseSource==="flag"||e.baseSource==="detected")&&typeof e.baseVersion=="string";return["merge","--release",e.targetVersion,...t&&typeof e.baseVersion=="string"?["--base",e.baseVersion]:[],...e.kind==="accept"?["--accept-live-base"]:[]]}function hx(e,t){return e.status!=="merged"&&e.status!=="conflicts"&&e.status!=="accepted"?[]:[...e.markedPaths.length===0?[]:[{step:"resolve",files:e.markedPaths,markers:sx}],{step:"push",argv:t(["push"])},{step:"publish",argv:t(["publish"])}]}function hc(e,t){let{targetVersion:n}=t,r=Bo(e.targetVersion,e.targetIsLive);switch(t.status){case"accepted":return[`\u2713 Recorded v${n} as this folder's base.`];case"up_to_date":return[`\u2713 This folder already includes v${n}.`,...st("On Live but excluded here (not written)",t.lists.ignoredIncoming)];case"merged":return[`\u2713 Merged ${r} into this folder.`,...cc(t.lists),"Run `appbuilder app push`, then `appbuilder app publish`."];case"conflicts":return[`Merged ${r} into this folder with conflicts.`,...cc(t.lists),mx(r)];case"fallback":return[...e.kind==="fallback"?[`Can't merge automatically: ${e.detail}`]:[],`${r}'s source is in ${t.extracted?.dir??""}.`,...st("Left out (safety list)",t.extracted?.skipped??[])]}}async function im(e,t){let n=[...e.release===void 0?[]:["--release",e.release],...e.base===void 0?[]:["--base",e.base],...e.acceptLiveBase===!0?["--accept-live-base"]:[]],r=Je("appbuilder app merge",n,e,t),{output:i,fail:o,runnable:s,appArgv:a,apply:c}=r;try{let l=await $t(e,t,r);if(l===null)return;let d=await bo(l,{...e.release===void 0?{}:{version:e.release},...e.base===void 0?{}:{base:e.base},...e.acceptLiveBase===!0?{acceptLiveBase:!0}:{}},t);if(!d.ok){o(d);return}let u=d.value;ze(t,u.notices);let f=Ye({dryRun:e.dryRun===!0,yes:e.yes===!0,allowProduction:!0},l.credentials.environment);if(!f.ok){o(f);return}let g=qe(u.summary),m=[...u.warnings,...await bt(t)],p=u.kind==="fallback"?s(u.choices):[],h={...yt(u.summary),...fx(u),...u.kind==="fallback"?{choices:p}:{}};if(f.value.kind==="dry-run"){jn(i,f.value,{action:"merge",...h,warnings:m},c(gx(u),!1),Ce(...g,...gc(u),...Q(m)));return}let b=await wo(l,u,t);if(!b.ok){o(b);return}let y=b.value,C=[...hc(u,y),...y.status==="fallback"?ax(fc,p):[]];Pe(i,{ok:!0,applied:!0,dryRun:!1,action:"merge",...h,status:y.status,baseLiveVersion:y.baseLiveVersion??null,...y.lists,...y.extracted===void 0?{}:{extracted:y.extracted},remembered:y.remembered,warnings:[...m,...y.warnings],next:hx(y,a)},Ce(...g,...C,...Q([...m,...y.warnings])))}catch(l){o(z(l))}}var yc=e=>[...qe(e.summary),`Rollback: restore v${e.version} as your preview`],bc=e=>`\u2713 Restored v${e.version} as your preview of ${e.summary.name??e.summary.baseApiName}`;async function om(e,t,n){let r=Je("appbuilder app rollback",[e],t,n),{output:i,fail:o,appArgv:s,apply:a}=r;try{let c=await $t(t,n,r);if(c===null)return;let l=await vo(c,e,n);if(!l.ok){o(l);return}let d=l.value,u=Ye(t,c.credentials.environment);if(!u.ok){o(u);return}let f=yc(d),g=[...d.warnings,...await bt(n)],m={...yt(d.summary),version:d.version,preview:d.preview};if(u.value.kind==="dry-run"){jn(i,u.value,{action:"rollback",...m,warnings:g},a(["rollback",e],d.summary.isProduction),Ce(...f,...Q(g)));return}let p=await ko(c,d,n);if(!p.ok){o(p);return}let h=[...g,...p.value.warnings];Pe(i,{ok:!0,applied:!0,dryRun:!1,action:"rollback",...m,apiName:p.value.apiName,sourcePackageId:p.value.sourcePackageId,remembered:p.value.remembered,warnings:h,next:[{step:"publish",argv:s(["publish"])}]},Ce(bc(d),...f,...Q(h)))}catch(c){o(z(c))}}var wc=(e,t)=>{let n=e.summary.name??e.summary.baseApiName,r=`(${String(t.written.length)} files)`;return[e.source==="release"?`\u2713 Extracted v${e.version} of ${n} into ${t.dir} ${r}`:`\u2713 Extracted your preview of ${n} into ${t.dir} ${r}`,...t.preview===void 0?[]:[`Folder base: ${em(t.preview.base)}`],...st("Left out (safety list)",t.skipped)]},yx=(e,t)=>e.source==="release"?{version:e.version}:{source:"preview",preview:{updated:e.updated,sourcePackageId:t.preview?.sourcePackageId??null},base:t.preview?.base??null};async function sm(e,t,n){let r=Ao(e,t.preview===!0);if(!r.ok){Je("appbuilder app pull",[],t,n).fail(r);return}let i=[...r.value.kind==="release"?[r.value.version]:["--preview"],...t.out===void 0?[]:["--out",t.out]],o=Je("appbuilder app pull",i,t,n),{output:s,fail:a}=o;try{let c=await $t(t,n,o);if(c===null)return;let l=await xo(c,r.value,t,n);if(!l.ok){a(l);return}let d=l.value,u=await Po(c,d,n);if(!u.ok){a(u);return}let{dir:f,written:g,skipped:m,remembered:p}=u.value,h=[...d.warnings,...u.value.warnings,...await bt(n)];Pe(s,{ok:!0,...yt(d.summary),...yx(d,u.value),dir:f,written:g,skipped:m,remembered:p,warnings:h,next:[]},Ce(...wc(d,u.value),...Q(h)))}catch(c){a(z(c))}}var vc=(e,t)=>[...qe(e),...t.actions.length===0?["No JS actions."]:Qe(t)],oc=e=>e===!0?"shown in its Perform Action menus":"not shown in its Perform Action menus",Do=e=>`${e.object.label} (${e.object.name})`;function kc(e){let t=e.action.apiName;switch(e.change){case"create":return[`Link ${t} to ${Do(e)}, ${oc(e.includePerformAction)}.`];case"update":return[`Change ${t}'s link to ${Do(e)}: ${oc(e.includePerformAction)}.`];case"up_to_date":return[`${t} is already linked to ${Do(e)}, ${oc(e.includePerformAction)}.`]}}var Ac=e=>[`Unlink ${e.action.apiName} from ${Do(e)}.`],xc=(e,t)=>t==="updated"?`\u2713 Updated ${e.action.apiName}'s link to ${e.object.label}`:t==="already_linked"?`${e.action.apiName} was already linked to ${e.object.label}`:`\u2713 Linked ${e.action.apiName} to ${e.object.label}`,Pc=e=>`\u2713 Unlinked ${e.action.apiName} from ${e.object.label}`;function am(e,t){let{action:n,object:r}=t;return n!==void 0&&r!==void 0?I({action:n,object:r}):me("usage_error",`Missing argument <${n===void 0?"action":"object"}>. Usage: appbuilder app actions ${e} <action> <object>. A headless run needs both; at a terminal, leave them out to pick them.`)}var sc=e=>({...yt(e.summary),jsAction:{apiName:e.action.apiName,name:e.action.name,hintObjectName:e.action.hintObjectName,inLive:e.action.inLive},object:e.object,change:e.change,includePerformAction:e.includePerformAction,existing:e.existing});async function cm(e,t){let n=Je("appbuilder app actions list",[],e,t),{output:r,fail:i,appArgv:o}=n;try{let s=await $t(e,t,n);if(s===null)return;let a=await No(s);if(!a.ok){i(a);return}let{summary:c,check:l}=a.value,d=[...Ge(l),...await bt(t)];Pe(r,{ok:!0,...yt(c),published:s.app!==null,status:l.status,actions:Qp(l.actions,o),warnings:d,next:Xr(l,o).filter(u=>u.step!=="actions")},Ce(...vc(c,l),...Q(d)))}catch(s){i(z(s))}}async function lm(e,t,n,r){let i=am("link",{action:e,object:t});if(!i.ok){Je("appbuilder app actions link",[],n,r).fail(i);return}let{action:o,object:s}=i.value,a=n.menu===void 0?[]:[n.menu?"--menu":"--no-menu"],c=Je("appbuilder app actions link",[o,s,...a],n,r),{output:l,fail:d,appArgv:u,apply:f}=c,g=m=>["appbuilder","app","actions","link",o,m.id,...a];try{let m=await $t(n,r,c);if(m===null)return;let p=await Wp(m,{action:o,object:s,...n.menu===void 0?{}:{menu:n.menu}},g);if(!p.ok){d(p);return}let h=p.value,b=[...qe(h.summary),...kc(h)],y=await bt(r),C=[...h.warnings,...y];if(ze(r,h.notices),h.change==="up_to_date"){Pe(l,{ok:!0,applied:!1,dryRun:!1,action:"actions link",...sc(h),status:"up_to_date",notices:h.notices,warnings:C,next:[]},Ce(...b,...Q(C)));return}let S=Ye(n,m.credentials.environment);if(!S.ok){d(S);return}if(S.value.kind==="dry-run"){jn(l,S.value,{action:"actions link",...sc(h),notices:h.notices,warnings:C},f(["actions","link",h.action.apiName,h.object.id,h.includePerformAction===!0?"--menu":"--no-menu"],h.summary.isProduction),Ce(...b,...Q(C)));return}let x=await $o(m,h);if(!x.ok){d(x);return}let v=[...x.value.status==="already_linked"?y:C,...x.value.warnings],k=xc(h,x.value.status);Pe(l,{ok:!0,applied:x.value.status!=="already_linked",dryRun:!1,action:"actions link",...sc(h),status:x.value.status,notices:h.notices,warnings:v,next:[{step:"actions",argv:u(["actions","list"])}]},Ce(k,...b,...Q(v)))}catch(m){d(z(m))}}async function um(e,t,n,r){let i=am("unlink",{action:e,object:t});if(!i.ok){Je("appbuilder app actions unlink",[],n,r).fail(i);return}let{action:o,object:s}=i.value,a=Je("appbuilder app actions unlink",[o,s],n,r),{output:c,fail:l,appArgv:d,apply:u}=a,f=g=>["appbuilder","app","actions","unlink",o,g.id];try{let g=await $t(n,r,a);if(g===null)return;let m=await Jp(g,{action:o,object:s},f);if(!m.ok){l(m);return}let p=m.value,h=Ye(n,g.credentials.environment);if(!h.ok){l(h);return}let b=[...qe(p.summary),...Ac(p)],y=[...p.warnings,...await bt(r)],C={...yt(p.summary),jsAction:{apiName:p.action.apiName,name:p.action.name,hintObjectName:p.action.hintObjectName,inLive:p.action.inLive},object:p.object,associationId:p.associationId,includePerformAction:p.includePerformAction};if(h.value.kind==="dry-run"){jn(c,h.value,{action:"actions unlink",...C,warnings:y},u(["actions","unlink",p.action.apiName,p.object.id],p.summary.isProduction),Ce(...b,...Q(y)));return}let S=await Oo(g,p);if(!S.ok){l(S);return}Pe(c,{ok:!0,applied:!0,dryRun:!1,action:"actions unlink",...C,status:S.value.status,warnings:y,next:[{step:"actions",argv:d(["actions","list"])}]},Ce(Pc(p),...b,...Q(y)))}catch(g){l(z(g))}}function ei(e){let{owner:t,preview:n}=e;return[...qe(e.summary),`Preview: ${t.fullName??t.id} (${t.yours?"yours":t.id}), last updated ${n.updated??"unknown"}`,...n.activeUsersCount===null?[]:[`Active users: ${String(n.activeUsersCount)}`],...n.installedCount===null?[]:[`Installs: ${String(n.installedCount)}`],e.deletesApp?"Delete: this preview, and with it the app":"Delete: this preview"]}var Cc=(e,t)=>{let n=e.summary.name??e.summary.baseApiName;return[`\u2713 Deleted ${e.owner.yours?"your":`${e.owner.fullName??e.owner.id}'s`} preview of ${n}`,...t.appDeleted===!0?[`${n} had no other version, so it was deleted from this business.`]:[],...e.deletesApp&&t.appDeleted===!1?[`${n} has another version now, so it wasn't deleted.`]:[]]},ac=(e,t,n)=>e.code==="preview_changed"?{...e,next:[{step:"preview delete",argv:n(["preview","delete","--owner",t])}]}:e,bx="Kizen reports no last update for this preview, so this dry run can't be pinned to it and has no applyArgv: it can't be applied from this dry run.",Yp=e=>({...yt(e.summary),owner:e.owner,preview:e.preview,deletesApp:e.deletesApp});async function dm(e,t){let n=e.owner===void 0?[]:["--owner",e.owner],r=Je("appbuilder app preview delete",n,e,t),{output:i,fail:o,appArgv:s,apply:a}=r;try{let c=await $t(e,t,r);if(c===null)return;let l=(e.owner??c.credentials.userId).trim(),d=Co(c,{...e.owner!==void 0&&{owner:e.owner},...e.expectUpdated!==void 0&&{expectUpdated:e.expectUpdated}});if(!d.ok){o(ac(d,l,s));return}let u=d.value,f=Ye(e,c.credentials.environment);if(!f.ok){o(f);return}let g=ei(u),m=[...u.warnings,...await bt(t)];if(f.value.kind==="dry-run"){let{updated:C}=u.preview,S=C===null?[bx]:[];ze(t,S),jn(i,f.value,{action:"preview delete",...Yp(u),notices:S,warnings:m},C===null?null:a(["preview","delete","--owner",u.owner.id,"--expect-updated",C,...u.deletesApp?["--delete-app"]:[]],u.summary.isProduction),Ce(...g,...Q(m)));return}let p=Bp(u,e.deleteApp===!0);if(p!==null){o(ac(p,u.owner.id,s));return}let h=await So(c,u,t);if(!h.ok){o(ac(h,u.owner.id,s));return}let b=_o(u,h.value),y=[...b.warnings,...m.slice(u.warnings.length),...h.value.warnings];Pe(i,{ok:!0,applied:!0,dryRun:!1,action:"preview delete",...Yp(b),status:h.value.status,appDeleted:h.value.appDeleted,remembered:h.value.remembered,warnings:y,next:u.owner.yours?[{step:"push",argv:s(["push"])}]:[]},Ce(...Cc(u,h.value),...ei(b),...Q(y)))}catch(c){o(z(c))}}import{useEffect as nP,useState as Lc}from"react";import{Box as Qo,Text as Fc}from"ink";var Fo={credentials:null,credentialNotices:[],warnings:[],notices:[]},pm=e=>t=>e.length===0?t:{...t,notices:[...t.notices,...e]},ni="Loading credentials\u2026",jo="Dry run: nothing was written.";function mm(e){if(e.login===void 0)return e;let{login:t,...n}=e;return{...n,hint:`Sign in with: ${t.argv.map(ge).join(" ")}`}}function Mo({deps:e,setPhase:t,setSession:n,next:r,toView:i=Me,present:o=s=>s}){let s=!1,a=f=>g=>{s||f(g)},c=a(t),l=a(n),d=f=>{s||(e.setExitCode(1),c({type:"error",view:o(f)}))},u=async f=>{c({type:"loading",label:ni});let g=await Nn(f,e);if(s)return;if(!g.ok){if(g.choice==="environment"&&g.choices){c({type:"environment-select",options:f,choices:g.choices});return}d(g);return}let{environment:m,businessId:p}=g.value.credentials;l(h=>({...h,credentials:{environment:m,businessId:p},credentialNotices:g.value.notices})),await r(f,g.value)};return{load:u,pickEnvironment:(f,g)=>u({...f.options,env:g.value}),fail:d,guard:f=>{f().catch(g=>{d(i(g))})},abort:()=>{s=!0},isAborted:()=>s,whileRunning:a}}function fm(e,t){e(),t(130)}function zo(e,t){if(e.dryRun)return"dry-run";if(e.yes){let n=Ye(e,t);if(n.ok&&n.value.kind==="apply")return"apply"}return"confirm"}var wm=e=>e.type==="done"||e.type==="report"||e.type==="error";function wx(e){let t={dryRun:!1,yes:!1,allowProduction:!1,force:!1};switch(e.command){case"versions":case"pull":case"actions list":return t;case"merge":return{...t,dryRun:e.options.dryRun===!0,yes:e.options.yes===!0};case"push":case"publish":return{dryRun:e.options.dryRun===!0,yes:e.options.yes===!0,allowProduction:e.options.allowProduction===!0,force:e.options.force===!0};case"rollback":case"actions link":case"actions unlink":case"preview delete":return{...t,dryRun:e.options.dryRun===!0,yes:e.options.yes===!0,allowProduction:e.options.allowProduction===!0}}}var vx={dryRun:!1,yes:!1,allowProduction:!1};function kx(e){let t=e.argv??[];if(t[0]!=="appbuilder"||t[1]!=="app")return null;let n=o=>{let s=t.indexOf(o);return s===-1?void 0:t[s+1]},r=n("--release"),i=n("--base");if(t[2]==="push"){let o=n("--base-from-preview");return{command:"push",...o!==void 0&&{baseFromPreview:o}}}return t[2]==="actions"&&t[3]==="link"&&t.length===4?{command:"actions link"}:t[2]==="merge"?{command:"merge",options:{...r!==void 0&&{version:r},...i!==void 0&&{base:i},...t.includes("--accept-live-base")&&{acceptLiveBase:!0}}}:null}var gm=e=>e.replace(/ Only if the user explicitly wants[^:]*: pass --force\./g,""),hm={value:"exit",label:"Exit without publishing",args:[]},Ax={value:"merge",label:"Merge Live into this folder",args:[],argv:["appbuilder","app","merge"]},xx={value:"push",label:"Push this folder as your preview",args:[],argv:["appbuilder","app","push"]},Px={value:"link-actions",label:"Link JS actions now",args:[],argv:["appbuilder","app","actions","link"]},ym={value:"finish",label:"Done",args:[]},Cx=e=>({value:e.id,label:`${e.objectName} (${e.name})`,args:[]}),Sx={linked:"linked",unlinked:"not linked",unknown:"not in Live, links can't be listed"},_x=e=>({value:e.apiName,label:`${e.apiName} (${e.name}): ${Sx[e.status]}`,args:[]});function bm(e,t){if(t===void 0)return I([...e]);let n=To(e,t,()=>[]);if(n.ok)return I([n.value]);if(n.code==="needs_choice"){let r=new Set((n.choices??[]).map(i=>i.value));return I(e.filter(i=>r.has(i.id)))}return n}var Ex=e=>`Conflicted files get git conflict markers: <<<<<<< HEAD is your file and >>>>>>> live is ${e}.`;function vm(e,t,n,r){let i=wx(e),o=e.command==="pull"?Ao(e.version,e.options.preview===!0):null,s=e.command==="publish"?e.options.expectPreview:void 0,a=null,c=Mo({deps:t,setPhase:n,setSession:r,toView:z,present:mm,next:async(E,N)=>{a={credentials:N.credentials,client:N.client},await fr(a)}}),{fail:l}=c,d=c.whileRunning(n),u=c.whileRunning(r),f=()=>!c.isAborted(),g={isAborted:c.isAborted},m=E=>{u(pm(E))},p=E=>{d({type:"loading",label:E})},h=E=>{d({type:"done",outcome:E})},b=(E,N,B)=>{if(Io(B).length===0){d(N);return}d({type:"choose",title:"What next?",message:"",lines:[],above:N,choices:[Px,ym],run:async R=>{if(R.value===ym.value){d(N);return}await P(E,R,null)},dismissed:N})},y=()=>{l({message:"Cancelled."})},C=E=>["appbuilder","app",...E,...Rn(e.options,t.processEnv)].map(ge).join(" "),S=async(E,N)=>{let B=await qr({...E,baseApiName:N},t);return B.ok?(m(B.value.notices),B.value):(l(B),null)},x=async E=>{if(a===null)return null;p("Loading the app\u2026");let N=await qr({...a,baseApiName:E.baseApiName},t);return N.ok?N.value:(l(N),null)},v=async(E,N,B,R)=>{switch(zo(B,E.credentials.environment)){case"dry-run":h({title:jo,tone:"warning",lines:N.lines,warnings:N.warnings,next:null});return;case"apply":await R();return;case"confirm":d({type:"confirm",...N,apply:R})}},k=(E,N,B,R)=>{if(N.code==="base_required"&&N.choices&&N.choices.length>0){d({type:"choose",title:"Choose how to go on",message:gm(N.message),lines:[],choices:N.choices,run:O=>P(E,O,B,R),dismissed:null});return}if(N.code==="publish_conflict"&&N.conflict?.reason!=="preview_replaced"){let{message:O}=N,D=N.conflict?.reason==="base_unknown";d({type:"choose",title:"What next?",message:gm(O),lines:[],choices:[D?xx:Ax,hm],run:async M=>{if(M.value===hm.value){l({message:O});return}await P(E,M,D?B:null)},dismissed:null});return}l(N)},P=async(E,N,B,R)=>{let O=kx(N);if(O===null){l({message:`Can't run "${N.label}" here.`});return}let D=await x(E);if(D!==null){if(O.command==="push"){await A(D,R===void 0?B:R,O.baseFromPreview===void 0?{}:{baseFromPreview:O.baseFromPreview});return}if(O.command==="actions link"){await $e(D,{},vx);return}await T(D,O.options,O.options.acceptLiveBase===!0?B:null)}},w=async(E,N,B,R)=>{if(!f())return;p("Checking the push\u2026");let O=await fo(E,N,{force:i.force,...R},t);if(!O.ok){k(E,O,async()=>{let J=await x(E);J!==null&&await w(J,N,B,{})},B);return}let D=O.value,M=Fn(N.deployable.artifacts.js_action_templates),Y=await it(E,{kind:"version",templates:M}),G=[...Qr(D),...Qe(Y)],Z=[...D.warnings,...Ge(Y)];m([...D.notices,...ot(Y)]),await v(E,{lines:G,warnings:Z,isProduction:D.summary.isProduction,prompt:"Push? (Y/n)",productionPrompt:"Type y to push to production (y/N)"},i,async()=>{if(!f())return;p(`Saving your preview of ${D.appName}\u2026`);let J=await go(E,N,D,t,g);if(!J.ok){l(J);return}let le=uc(D.appName,J.value);if(B!==null){m([le,...Q([...Z,...J.value.warnings])]),await B();return}p("Checking the JS actions\u2026");let se=await Eo(E,M);m(ot(se)),b(E,{type:"done",outcome:{title:le,tone:"success",lines:[...Qr(D),...Qe(se)],warnings:[...D.warnings,...Ge(se),...J.value.warnings],next:C(["publish"])}},se)})},A=async(E,N,B)=>{if(!f())return;p("Packaging the app\u2026");let R=await mo(t);if(!R.ok){l(R);return}let{issues:O,source:D,deployable:M}=R.value;u(G=>({...G,warnings:O})),m(D.notice===void 0?[]:[D.notice]);let Y="api"in E?E:await S(E,M.api_name);Y!==null&&await w(Y,R.value,N,B)},_=async E=>{if(!f())return;p("Checking for conflicts\u2026");let N=async()=>{let M=await x(E);M!==null&&await _(M)},B=await ho(E,{force:i.force,...s!==void 0&&{expectPreview:s}},t);if(!B.ok){k(E,B,N);return}let R=B.value,O=dc(R),D=await it(E,{kind:"version",templates:Fn(R.jsActionTemplates)});m(ot(D)),await v(E,{lines:[...O,pc(R),...Qe(D)],warnings:[...R.warnings,...Ge(D)],isProduction:R.summary.isProduction,prompt:"Publish? (Y/n)",productionPrompt:"Type y to publish to production (y/N)"},i,async()=>{if(!f())return;p("Publishing\u2026");let M=await yo(E,R,t,g);if(!M.ok){k(E,M,N);return}let Y=await it(E,{kind:"live",version:M.value.liveVersion});m(ot(Y)),b(E,{type:"done",outcome:{title:mc(R,M.value),tone:"success",lines:[...O,...Qe(Y)],warnings:[...R.warnings,...M.value.warnings,...Ge(Y)],next:null}},Y)})},T=async(E,N,B)=>{if(!f())return;p("Planning the merge\u2026");let R=await bo(E,N,t);if(!R.ok){l(R);return}let O=R.value,D=Bo(O.targetVersion,O.targetIsLive),M=O.kind==="merge"&&O.plan.conflicted.length>0;m(O.notices);let Y=async()=>{if(!f())return;p(O.kind==="fallback"?`Extracting ${D}\u2026`:O.kind==="merge"?"Merging\u2026":"Recording the base\u2026");let G=await wo(E,O,t,g);if(!G.ok){l(G);return}let Z=G.value,[J="",...le]=hc(O,Z),se=[...O.warnings,...Z.warnings],Fe=Z.status==="accepted"||Z.status==="up_to_date";if(B!==null&&Fe){m([J,...Q(se)]),await B();return}let Hn={title:J,tone:Z.status==="conflicts"||Z.status==="fallback"?"warning":"success",lines:le,warnings:se,next:Z.status==="accepted"?C(["push"]):null};if(Z.status==="fallback"&&O.kind==="fallback"){d({type:"choose",title:"Choose how to go on",message:fc,lines:[J,...le],choices:O.choices,run:Ns=>P(E,Ns,null),dismissed:{type:"done",outcome:Hn}});return}h(Hn)};if(O.kind==="up_to_date"&&!O.advancesBase){await Y();return}await v(E,{lines:[...qe(O.summary),...gc(O),...M?[Ex(D)]:[]],warnings:O.warnings,isProduction:!1,prompt:O.kind==="merge"?"Merge? (Y/n)":O.kind==="fallback"?"Extract it? (Y/n)":"Record it? (Y/n)",productionPrompt:""},{dryRun:i.dryRun,yes:i.yes||B!==null&&O.kind==="accept",allowProduction:!0},Y)},L=async(E,N)=>{if(!f())return;p(`Preparing v${N}\u2026`);let B=await vo(E,N,t);if(!B.ok){l(B);return}let R=B.value,O=yc(R);await v(E,{lines:O,warnings:R.warnings,isProduction:R.summary.isProduction,prompt:"Restore it? (Y/n)",productionPrompt:"Type y to restore it on production (y/N)"},i,async()=>{if(!f())return;p(`Restoring v${R.version}\u2026`);let D=await ko(E,R,t,g);if(!D.ok){l(D);return}h({title:bc(R),tone:"success",lines:O,warnings:[...R.warnings,...D.value.warnings],next:C(["publish"])})})},$=async(E,N,B)=>{if(!f())return;p(N.kind==="release"?`Downloading v${N.version}\u2026`:"Downloading your preview\u2026");let R=await xo(E,N,B===void 0?{}:{out:B},t);if(!R.ok){l(R);return}let O=R.value;if(!f())return;let D=await Po(E,O,t,g);if(!D.ok){l(D);return}let[M="",...Y]=wc(O,D.value);h({title:M,tone:"success",lines:Y,warnings:[...O.warnings,...D.value.warnings],next:null})},V=async E=>{p("Reading the JS actions\u2026");let N=await No(E);if(!N.ok){l(N);return}let{summary:B,check:R}=N.value;d({type:"report",lines:vc(B,R),warnings:Ge(R)})},X=async E=>{p("Reading the JS actions\u2026");let N=await ec(E);return N.ok?N.value:(l(N),null)},ve=(E,N)=>{d({type:"choose",message:"",lines:[],...E,run:N,dismissed:null})},Re=async(E,N,B,R)=>{let[O]=N;if(B&&O!==void 0&&N.length===1){await R(O);return}if(O===void 0){l({message:"There's no object on this business that you can see."});return}let D=E.hintObjectName===null?null:To(N,E.hintObjectName,()=>[]);ve({title:`Object for ${E.apiName}`,choices:N.map(Cx),...D?.ok===!0&&{initial:D.value.id},searchable:!0},async M=>{let Y=N.find(G=>G.id===M.value);Y!==void 0&&await R(Y)})},$e=async(E,N,B)=>{if(!f())return;let R=await X(E);if(R===null)return;let O=bm(R.objects,N.object);if(!O.ok){l(O);return}let D=N.action===void 0||N.object===void 0,M=async(J,le)=>{if(N.menu!==void 0||!D){await Te(E,R,J,le,N.menu,B);return}let se=J.links.find(Fe=>Fe.objectId===le.id);ve({title:`Show ${J.apiName} in the Perform Action menus of ${le.objectName}?`,choices:[{value:"no",label:"No",args:[]},{value:"yes",label:"Yes",args:[]}],initial:se?.includePerformAction===!0?"yes":"no"},Fe=>Te(E,R,J,le,Fe.value==="yes",B))},Y=J=>Re(J,O.value,N.object!==void 0,le=>M(J,le));if(N.action!==void 0){let J=Ro(E,R,N.action);if(!J.ok){l(J);return}await Y(J.value);return}let{actions:G}=R.check;if(G.length===0){l({message:`${E.baseApiName} has no JS actions to link.`});return}let Z=G.find(J=>J.status!=="linked");ve({title:"JS action to link",choices:G.map(_x),...Z!==void 0&&{initial:Z.apiName},searchable:!0},async J=>{let le=G.find(se=>se.apiName===J.value);le!==void 0&&await Y(le)})},Te=async(E,N,B,R,O,D)=>{if(!f())return;let M=tc(E,N,B,R,{...O!==void 0&&{menu:O}}),Y=[...qe(M.summary),...kc(M)];if(m(M.notices),M.change==="up_to_date"){h({title:"Nothing to change.",tone:"success",lines:Y,warnings:[],next:null});return}let G=M.change==="create";await v(E,{lines:Y,warnings:M.warnings,isProduction:M.summary.isProduction,prompt:G?"Link it? (Y/n)":"Change it? (Y/n)",productionPrompt:G?"Type y to link it on production (y/N)":"Type y to change it on production (y/N)"},D,async()=>{if(!f())return;p(G?"Linking\u2026":"Changing the link\u2026");let Z=await $o(E,M,g);if(!Z.ok){l(Z);return}h({title:xc(M,Z.value.status),tone:Z.value.status==="already_linked"?"warning":"success",lines:Y,warnings:[...Z.value.status==="already_linked"?[]:M.warnings,...Z.value.warnings],next:C(["actions","list"])})})},gn=async(E,N,B)=>{if(!f())return;let R=await X(E);if(R===null)return;let O=bm(R.objects,N.object);if(!O.ok){l(O);return}let D=N.action===void 0?null:Ro(E,R,N.action);if(D!==null&&!D.ok){l(D);return}if(D!==null&&N.object!==void 0){await Re(D.value,O.value,!0,G=>ct(E,R,D.value,G,B));return}let M=new Set(O.value.map(G=>G.id)),Y=(D===null?R.check.actions:[D.value]).flatMap(G=>G.links.filter(Z=>M.has(Z.objectId)).map(Z=>({action:G,link:Z})));if(Y.length===0){l(D===null?{message:`${E.baseApiName} has no listed JS action links to remove.`}:{message:`${D.value.apiName} isn't linked to any object.`,...!D.value.inLive&&{hint:nc(D.value.apiName)}});return}ve({title:"Link to remove",choices:Y.map(({action:G,link:Z})=>({value:Z.id,label:`${G.apiName} \u2192 ${Z.label} (${Z.objectName})`,args:[]})),searchable:!0},async G=>{let Z=Y.find(({link:Fe})=>Fe.id===G.value);if(Z===void 0)return;let{action:J,link:le}=Z,se=R.objects.find(Fe=>Fe.id===le.objectId)??{id:le.objectId,name:le.objectName,objectName:le.label,entityName:null};await ct(E,R,J,se,B)})},ct=async(E,N,B,R,O)=>{if(!f())return;let D=rc(E,N,B,R);if(!D.ok){l(D);return}let M=D.value,Y=[...qe(M.summary),...Ac(M)];await v(E,{lines:Y,warnings:M.warnings,isProduction:M.summary.isProduction,prompt:"Unlink it? (Y/n)",productionPrompt:"Type y to unlink it on production (y/N)"},O,async()=>{if(!f())return;p("Unlinking\u2026");let G=await Oo(E,M,g);if(!G.ok){l(G);return}h({title:Pc(M),tone:"success",lines:Y,warnings:M.warnings,next:C(["actions","list"])})})},mr=async(E,N)=>{if(!f())return;let B=Co(E,{...N.owner!==void 0&&{owner:N.owner},...N.expectUpdated!==void 0&&{expectUpdated:N.expectUpdated}});if(!B.ok){l(B);return}let R=B.value,O=ei(R);await v(E,{lines:O,warnings:R.warnings,isProduction:R.summary.isProduction,strict:R.deletesApp,prompt:"Delete it? (Y/n)",productionPrompt:R.deletesApp?`Type y to delete the preview and the whole app${R.summary.isProduction?" on production":""} (y/N)`:"Type y to delete it on production (y/N)"},R.deletesApp&&N.deleteApp!==!0?{...i,yes:!1}:i,async()=>{if(!f())return;p("Deleting the preview\u2026");let D=await So(E,R,t,g);if(!D.ok){l(D);return}let[M="",...Y]=Cc(R,D.value),G=_o(R,D.value);h({title:M,tone:"success",lines:[...Y,...ei(G)],warnings:[...G.warnings,...D.value.warnings],next:R.owner.yours?C(["push"]):null})})},fr=async E=>{if(e.command==="push"){let{baseFromPreview:R}=e.options;await A(E,null,R===void 0?{}:{baseFromPreview:R});return}p("Loading the app\u2026");let N;try{N=await t.readManifestApiName(t.cwd)}catch(R){l(z(R));return}let B=await S(E,N);if(B!==null)switch(e.command){case"versions":{let R=await rr(B);if(!R.ok){l(R);return}let O=po(B,R.value),D=await it(B,{kind:"app"});m(ot(D)),b(B,{type:"report",lines:[...lc(O),...Qe(D)],warnings:[...O.warnings,...Ge(D)]},D);return}case"publish":await _(B);return;case"merge":await T(B,{...e.options.release!==void 0&&{version:e.options.release},...e.options.base!==void 0&&{base:e.options.base},...e.options.acceptLiveBase===!0&&{acceptLiveBase:!0}},null);return;case"rollback":await L(B,e.version);return;case"pull":o?.ok===!0&&await $(B,o.value,e.options.out);return;case"actions list":await V(B);return;case"actions link":await $e(B,{...e.action!==void 0&&{action:e.action},...e.object!==void 0&&{object:e.object},...e.options.menu!==void 0&&{menu:e.options.menu}},i);return;case"actions unlink":await gn(B,{...e.action!==void 0&&{action:e.action},...e.object!==void 0&&{object:e.object}},i);return;case"preview delete":await mr(B,e.options)}},{guard:jt}=c;return{start:()=>{if(o?.ok===!1){l(o);return}jt(()=>c.load(e.options))},pickEnvironment:(E,N)=>{jt(()=>c.pickEnvironment(E,N))},accept:E=>{jt(E.apply)},choose:(E,N)=>{jt(()=>E.run(N))},dismiss:E=>{E.dismissed===null?y():d(E.dismissed)},cancel:y,abort:c.abort}}import{useMemo as _c,useState as Am}from"react";import{Box as Ec,Text as Ot,useInput as Ix}from"ink";function Sc(e,t){let n=i=>i.normalize("NFD").replace(new RegExp("\\p{Diacritic}","gu"),"").toLowerCase(),r=n(t).split(/\s+/).filter(Boolean);return e.flatMap((i,o)=>{let s=n(`${i.label} ${i.description??""}`);return r.every(a=>s.includes(a))?[{item:i,index:o}]:[]})}var Uo=(e,t,n)=>Math.min(Math.max(e,t),n);function Vo(e,t,n,r={}){if(t<=0)return 0;let i=Uo(Math.trunc(e)||0,0,t-1),o=c=>r.disabled?.[c]!==!0;if(n===0)return i;let s=n>0?1:-1;if(Math.abs(n)===1){for(let c=1;c<=t;c++){let l=((i+s*c)%t+t)%t;if(o(l))return l}return i}let a=Uo(i+Math.trunc(n),0,t-1);for(let c=a;c>=0&&c<t;c+=s)if(o(c))return c;for(let c=a-s;c>=0&&c<t;c-=s)if(o(c))return c;return i}function km(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 i=Uo(Math.trunc(e)||0,0,t-1),o=Uo(i-Math.floor(r/2),0,t-r);return{start:o,end:o+r}}import{jsx as Dt,jsxs as Tc}from"react/jsx-runtime";var Tx="\u2191/\u2193 to move, Enter to select, Esc to cancel",Nx="Type to filter, \u2191/\u2193 to move, Enter to select, Esc to clear or cancel",Ic=10,xm=(e,t)=>{let n=e.findIndex(o=>o.key===t&&o.disabled!==!0);if(n!==-1)return n;let r=Vo(0,e.length,0);if(e[r]?.disabled!==!0)return r;let i=e.findIndex(o=>o.disabled!==!0);return i===-1?r:i},Lt=({title:e,items:t,onSelect:n,onCancel:r,hint:i,initialKey:o,searchable:s=!1})=>{let[a,c]=Am(""),l=_c(()=>Sc(t,s?a:""),[t,s,a]),d=_c(()=>l.map(({item:C})=>C),[l]),[u,f]=Am(()=>xm(t,o)),g=_c(()=>d.map(C=>C.disabled===!0),[d]),m=Vo(u,d.length,0);Ix((C,S)=>{let x=k=>{f(Vo(m,d.length,k,{disabled:g}))},v=k=>{c(k),f(xm(Sc(t,k).map(({item:P})=>P)))};if(S.upArrow||!s&&C==="k")x(-1);else if(S.downArrow||!s&&C==="j")x(1);else if(S.pageUp)x(-Ic);else if(S.pageDown)x(Ic);else if(S.return){let k=l[m];k!==void 0&&k.item.disabled!==!0&&n(k.item,k.index)}else S.escape?s&&a!==""?v(""):r?.():s&&(S.backspace||S.delete)?v(a.slice(0,-1)):s&&C!==""&&!S.ctrl&&!S.meta&&!S.tab&&v(a+C)});let{start:p,end:h}=km(m,d.length,Ic),b=p,y=d.length-h;return Tc(Ec,{flexDirection:"column",gap:1,children:[Dt(Ot,{bold:!0,children:e}),s&&Dt(Ot,{children:`Filter: ${a}`}),Tc(Ec,{flexDirection:"column",children:[b>0&&Dt(Ot,{dimColor:!0,children:` \u2191 ${String(b)} more`}),s&&d.length===0&&Dt(Ot,{dimColor:!0,children:" No matches"}),d.slice(p,h).map((C,S)=>{let v=p+S===m,k=C.disabled===!0,P=v&&!k;return Tc(Ec,{gap:2,children:[Dt(Ot,{...P&&{color:"cyan"},dimColor:k,children:v?"\u276F":" "}),Dt(Ot,{bold:P,dimColor:k,...P&&{color:"cyan"},children:C.label}),C.description!==void 0&&Dt(Ot,{dimColor:!0,children:C.description})]},C.key)}),y>0&&Dt(Ot,{dimColor:!0,children:` \u2193 ${String(y)} more`})]}),Dt(Ot,{dimColor:!0,children:i??(s?Nx:Tx)})]})};import{jsx as Rx}from"react/jsx-runtime";function or(e,t){return(n,r)=>{let i=e[r];i!==void 0&&t(i)}}function sr({title:e,choices:t,onPick:n,onCancel:r,initial:i,searchable:o=!1}){return Rx(Lt,{title:e,items:t.map(s=>({key:s.value,label:s.label})),onSelect:or(t,n),onCancel:r,...i!==void 0&&{initialKey:i},searchable:o})}import{Text as Pm,useInput as $x}from"ink";import{Fragment as Ox,jsx as Nc,jsxs as Dx}from"react/jsx-runtime";var Rc=({prompt:e,strict:t,onAccept:n,onCancel:r})=>($x((i,o)=>{if(o.ctrl)return;let s=i.toLowerCase();s==="y"||!t&&o.return?n():(t||s==="n"||o.escape)&&r()}),Nc(Pm,{bold:!0,children:e})),Ho=({isProduction:e,strict:t=!1,prompt:n,productionPrompt:r,onAccept:i,onCancel:o})=>Dx(Ox,{children:[e&&Nc(Pm,{color:"red",bold:!0,children:"PRODUCTION"}),Nc(Rc,{prompt:e||t?r:n,strict:e||t,onAccept:i,onCancel:o})]});import{Box as $c,Text as Ko}from"ink";import{Box as Lx,Text as Bx}from"ink";import{jsx as Cm}from"react/jsx-runtime";var Ne=({lines:e,color:t})=>Cm(Lx,{flexDirection:"column",children:e.map((n,r)=>Cm(Bx,{...t&&{color:t},children:n},`${String(r)}-${n}`))});import{jsx as Wo,jsxs as Go}from"react/jsx-runtime";var Jo=({view:e})=>Go($c,{flexDirection:"column",gap:1,children:[Go($c,{gap:1,children:[Wo(Ko,{color:"red",children:"\u2717"}),Wo(Ko,{color:"red",children:e.issues&&e.issues.length>0?We(e.issues):e.message})]}),e.hint!==void 0&&Go(Ko,{dimColor:!0,children:["Hint: ",e.hint]}),e.choices&&e.choices.length>0&&Go($c,{flexDirection:"column",children:[Wo(Ko,{children:"Choices:"}),Wo(Ne,{lines:e.choices.map(t=>` ${t.label}`)})]})]});import{useEffect as Kx}from"react";import{Box as Wx,Text as Em,useApp as Gx,useInput as Jx}from"ink";import{Box as zx,Text as Ux}from"ink";import{Box as Fx,Text as jx}from"ink";import{jsx as Sm}from"react/jsx-runtime";var Mx=[" :::::::: "," :::::: ::::::::::: "," :::::: :::::::::: "," :::::: :::::: ::::::: "," ::::: :::::: ::::::::::::::::: "," ::::: ::::: ::::::::::::::::::: "," ::::: ::::: :::::: ::::: ",":::: ::::: ::: ::::: :: ","::::: :::::: :::::::::: ","::::: :::::: ::::::::::: "," ::::: ::: ::::::: "," ::::::: ::: ::::: "," ::::::::::: :::::: :::::"," :::::::::: :::::: :::::"," :: ::::: ::: ::::: ::::"," ::::: :::::: ::::: ::::: ::: "," ::::::::::::::::::: ::::: ::::: "," ::::::::::::::::: ::::: ::::: "," ::::::::: :::::: :::::: "," :::::::::: :::::: "," ::::::::::: :::::: "," :::::::: "],_m=()=>Sm(Fx,{flexDirection:"column",children:Mx.map((e,t)=>Sm(jx,{color:"cyan",children:e},t))});import{Fragment as Vx,jsx as Oc,jsxs as Hx}from"react/jsx-runtime";var ye=({marginBottom:e=0})=>Hx(Vx,{children:[Oc(_m,{}),Oc(zx,{flexDirection:"column",marginTop:1,marginBottom:e,children:Oc(Ux,{bold:!0,color:"cyan",children:"Kizen App Development Toolkit"})})]});import{jsx as qo,jsxs as Im}from"react/jsx-runtime";var Yo=({session:e,children:t})=>Im(Wx,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[qo(ye,{}),e.credentials&&Im(Em,{dimColor:!0,children:["Environment: ",e.credentials.environment," \xB7 Business: ",e.credentials.businessId]}),e.credentialNotices.length>0&&qo(Ne,{lines:e.credentialNotices,color:"yellow"}),e.warnings.length>0&&qo(Em,{dimColor:!0,children:We(e.warnings)}),e.notices.length>0&&qo(Ne,{lines:e.notices}),t]});function Zo(e,t,n){let r=Gx();Kx(()=>{e&&r.exit()},[e,r]),Jx((i,o)=>{o.ctrl&&i==="c"&&!e&&(fm(n,t),r.exit())})}import{Box as Dc,Text as Xo}from"ink";import{jsx as Tm,jsxs as ri}from"react/jsx-runtime";var ar=({issues:e})=>{let t=e.filter(n=>n.severity==="error").length;return ri(Dc,{flexDirection:"column",marginTop:1,children:[ri(Xo,{color:"red",children:["\u2717 ",t," validation ",t===1?"error":"errors"]}),[...Na(e)].map(([n,r])=>ri(Dc,{flexDirection:"column",marginTop:1,children:[Tm(Xo,{bold:!0,children:n}),r.map((i,o)=>Tm(Dc,{paddingLeft:2,children:ri(Xo,{color:i.severity==="error"?"red":"yellow",children:[i.severity==="error"?"\u2717":"\u26A0"," ",i.message," ",ri(Xo,{dimColor:!0,children:["(",i.rule,")"]})]})},`${i.rule}-${String(o)}`))]},n))]})};import{Box as Qx,Text as eP}from"ink";import{useEffect as qx,useState as Yx}from"react";import{Text as Zx}from"ink";import{jsx as Xx}from"react/jsx-runtime";var Nm=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],wt=()=>{let[e,t]=Yx(0);return qx(()=>{let n=setInterval(()=>{t(r=>(r+1)%Nm.length)},80);return()=>{clearInterval(n)}},[]),Xx(Zx,{color:"cyan",children:Nm[e]??"\u280B"})};import{jsx as Rm,jsxs as tP}from"react/jsx-runtime";var cr=({label:e})=>tP(Qx,{gap:1,children:[Rm(wt,{}),Rm(eP,{dimColor:!0,children:e})]});import{jsx as fe,jsxs as ii}from"react/jsx-runtime";var jc=({warnings:e})=>e.length>0?fe(Ne,{lines:Q(e),color:"yellow"}):null,rP=({outcome:e})=>ii(Qo,{flexDirection:"column",gap:1,children:[fe(Fc,{bold:!0,color:e.tone==="success"?"green":"yellow",children:e.title}),e.lines.length>0&&fe(Ne,{lines:e.lines}),fe(jc,{warnings:e.warnings}),e.next!==null&&ii(Fc,{dimColor:!0,children:["Next: ",e.next]})]}),Bc=({phase:e})=>e.type==="done"?fe(rP,{outcome:e.outcome}):ii(Qo,{flexDirection:"column",gap:1,children:[fe(Ne,{lines:e.lines}),fe(jc,{warnings:e.warnings})]}),iP=({view:e})=>e.issues&&e.issues.length>0?fe(ar,{issues:e.issues}):fe(Jo,{view:e}),$m=({request:e,deps:t})=>{let[n,r]=Lc({type:"loading",label:ni}),[i,o]=Lc(Fo),[s]=Lc(()=>vm(e,t,r,o));nP(()=>{s.start()},[s]),Zo(wm(n),t.setExitCode,s.abort);let a=c=>fe(Yo,{session:i,children:c});switch(n.type){case"loading":return a(fe(cr,{label:n.label}));case"environment-select":return a(fe(sr,{title:"Environment",choices:n.choices,onPick:c=>{s.pickEnvironment(n,c)},onCancel:s.cancel},"environment"));case"report":return a(fe(Bc,{phase:n}));case"confirm":return a(ii(Qo,{flexDirection:"column",gap:1,children:[fe(Ne,{lines:n.lines}),fe(jc,{warnings:n.warnings}),fe(Ho,{isProduction:n.isProduction,strict:n.strict===!0,prompt:n.prompt,productionPrompt:n.productionPrompt,onAccept:()=>{s.accept(n)},onCancel:s.cancel})]}));case"choose":return a(ii(Qo,{flexDirection:"column",gap:1,children:[n.above!==void 0&&fe(Bc,{phase:n.above}),n.lines.length>0&&fe(Ne,{lines:n.lines}),n.message!==""&&fe(Fc,{color:"yellow",children:n.message}),fe(sr,{title:n.title,choices:n.choices,onPick:c=>{s.choose(n,c)},onCancel:()=>{s.dismiss(n)},...n.initial!==void 0&&{initial:n.initial},searchable:n.searchable===!0},[n.title,...n.choices.map(c=>c.value)].join("|"))]}));case"done":return a(fe(Bc,{phase:n}));case"error":return a(fe(iP,{view:n.view}))}};var aP=e=>{console.error(`Error: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1},vt=e=>e.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)"),kt=e=>e.option("--json","print a JSON result to stdout (always headless)").option("--no-interactive",mt).option("--env <env>","environment of the `appbuilder login` session to use").option("--business <id-or-name>","use this saved account, by business id or name (ignoring case), instead of the current one (default: $APPBUILDER_BUSINESS)").option("--user <userId>","with --business, use the saved account of this user id (default: $APPBUILDER_USER)"),Mn=(e,t=!0)=>(e.option("--dry-run","show what would change without writing anything").option("--yes","write without asking (without it, the command is a dry run)"),t?e.option("--allow-production","allow writes to go/fmo"):e);async function At(e,t,n){try{let r=sp(process.cwd());if(!pt({json:e.options.json===!0,noInteractive:t})){await n(r);return}let{waitUntilExit:i}=sP(oP($m,{request:e,deps:r}),{exitOnCtrlC:!1});await i()}catch(r){aP(r)}}function cP(e){let t=e.command("actions").description("Link the app's JS actions to objects: list, link and unlink"),n=vt(t.command("list").description("Show the app's JS actions and the objects they're linked to"));kt(n).action(async o=>{let{noInteractive:s,options:a}=Ae(o);await At({command:"actions list",options:a},s,c=>cm(a,c))});let r=vt(t.command("link").description("Link a JS action to an object, or change whether it shows in its menus").argument("[action]","the JS action's api_name (at a terminal, leave it out to pick it)").argument("[object]","the object's api name (like client_client) or id")).option("--menu","show the action in the object's Perform Action menus").option("--no-menu","don't show it there (the default for a new link)");kt(Mn(r)).action(async(o,s,a)=>{let{noInteractive:c,options:l}=Ae(a);await At({command:"actions link",...o!==void 0&&{action:o},...s!==void 0&&{object:s},options:l},c,d=>lm(o,s,l,d))});let i=vt(t.command("unlink").description("Remove a JS action's link to an object").argument("[action]","the JS action's api_name (at a terminal, leave it out to pick a link)").argument("[object]","the object's api name (like client_client) or id"));kt(Mn(i)).action(async(o,s,a)=>{let{noInteractive:c,options:l}=Ae(a);await At({command:"actions unlink",...o!==void 0&&{action:o},...s!==void 0&&{object:s},options:l},c,d=>um(o,s,l,d))})}function lP(e){let t=e.command("preview").description("Manage the app's previews: delete"),n=vt(t.command("delete").description("Delete your preview of the app, or with --owner, another developer's")).option("--owner <userId>","delete this user's preview instead of yours").option("--expect-updated <ts>","delete only if the preview's last update is still <ts> (a dry run prints it)").option("--delete-app","allow deleting the whole app when this preview is its only version (a dry run that says so prints it)");kt(Mn(n)).action(async r=>{let{noInteractive:i,options:o}=Ae(r);await At({command:"preview delete",options:o},i,s=>dm(o,s))})}function Om(e){let t=e.command("app").description("Publish the plugin as a Business App: previews, releases, merges and rollbacks"),n=vt(t.command("versions").description("Show the app's Live, released and preview versions"));kt(n).action(async c=>{let{noInteractive:l,options:d}=Ae(c);await At({command:"versions",options:d},l,u=>tm(d,u))});let r=vt(t.command("push").description("Save this folder as your preview of the app"));kt(Mn(r).option("--force","push even if files still have merge conflict markers").option("--base-from-preview <id>","take this folder's base from your preview, while it's still source package <id> (a base_required choice prints it)")).action(async c=>{let{noInteractive:l,options:d}=Ae(c);await At({command:"push",options:d},l,u=>nm(d,u))});let i=vt(t.command("publish").description("Publish your preview as the next Live version"));kt(Mn(i).option("--force","publish even if Live changed since your preview was based on it, or its base is unknown").option("--expect-preview <id>","publish only if your preview's source package is still <id> (a dry run prints it)")).action(async c=>{let{noInteractive:l,options:d}=Ae(c);await At({command:"publish",options:d},l,u=>rm(d,u))});let o=vt(t.command("merge").description("Merge the Live version (or --release) into this folder")).option("--release <n>","merge release <n> instead of the Live version").option("--base <n>","the release this folder was copied from, when no base is recorded (a wrong one drops the changes made since)").option("--accept-live-base","record Live (or --release) as this folder's base without merging, after merging by hand");kt(Mn(o,!1)).action(async c=>{let{noInteractive:l,options:d}=Ae(c);await At({command:"merge",options:d},l,u=>im(d,u))});let s=vt(t.command("rollback").description("Restore a released version as your preview").argument("<version>","the released version to restore"));kt(Mn(s)).action(async(c,l)=>{let{noInteractive:d,options:u}=Ae(l);await At({command:"rollback",version:c,options:u},d,f=>om(c,u,f))});let a=vt(t.command("pull").description("Download a released version's source, or with --preview your preview's, into a new folder").argument("[version]","the released version to download (or pass --preview instead)")).option("--preview","download your preview instead of a released version").option("--out <dir>","folder to create (default: ../<api_name>-v<version>, or ../<api_name>-preview)");kt(a).action(async(c,l)=>{let{noInteractive:d,options:u}=Ae(l);await At({command:"pull",...c!==void 0&&{version:c},options:u},d,f=>sm(c,u,f))}),cP(t),lP(t)}var uP=async(e,t)=>{let n={json:!0,deps:t},r=i=>Et("appbuilder whoami",[...i.args,...rn(e,t.processEnv)],n);try{let i=bn(e,t.processEnv);if(!i.ok){It(n,me("usage_error",i.message),r);return}let o=await $a(e.env,i.request,{sessions:t.store,connect:(c,l)=>t.identify(t.tokenProvider(c,l===void 0?void 0:{account:l})),processEnv:t.processEnv});if(!o.ok){It(n,o,r);return}let{environment:s,connected:a}=o.value;Pe(n,{ok:!0,environment:s,businessId:a.businessId,businessName:a.businessName??null,userId:a.userId,fullName:a.fullName??null,email:a.email??null},Ri(s,a))}catch(i){It(n,Me(i),r)}},Dm=(e,t)=>e.json===!0?uP(e,t):_u(e,t);import{render as dP}from"ink";import{jsx as pP}from"react/jsx-runtime";var Lm=async(e,t)=>{let n,r=dP(pP(Lt,{title:e,items:t,onSelect:i=>{n=i.key,r.unmount()},onCancel:()=>{r.unmount()}}));return await r.waitUntilExit(),n};var mP=[{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"],["--no-interactive",mt]],run:Cu},{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:Su},{name:"whoami",description:"Show the user and business of the stored session",env:"environment to check (default: the only signed-in one, or with --business the only one where it's saved)",options:[["--business <id-or-name>","check this saved account, by business id or name (ignoring case), instead of the current one (default: $APPBUILDER_BUSINESS)"],["--user <userId>","with --business, check the saved account of this user id (default: $APPBUILDER_USER)"],["--json","print the identity as JSON"]],run:Dm},{name:"auth-header",description:"Print an Authorization header for the stored session as JSON (for a Claude Code MCP headersHelper)",env:"environment to use; must match CLAUDE_CODE_MCP_SERVER_URL when that is set (default: the environment matching it, else the only signed-in one)",options:[["--business <id>","with --user, use this saved account, current or not"],["--user <userId>","with --business, the user id of that account"]],run:Eu}];function Bm(e){for(let{name:t,description:n,env:r,options:i=[],run:o}of mP){let s=e.command(t).description(n).option("--env <env>",r);for(let[a,c]of i)s.option(a,c);s.action(async a=>{let{noInteractive:c,options:l}=Ae(a);await o(l,vu(void 0,Lm,c))})}}import{createElement as IC}from"react";import{render as TC}from"ink";import{PluginValidationError as NC}from"@kizenapps/packager";import{spawn as fP}from"child_process";import{platform as Fm}from"process";function gP(){return Fm==="darwin"?[{cmd:"pbcopy",args:[]}]:Fm==="win32"?[{cmd:"clip",args:[]}]:[{cmd:"wl-copy",args:[]},{cmd:"xclip",args:["-selection","clipboard"]},{cmd:"xsel",args:["--clipboard","--input"]}]}var hP=2e3;function yP(e,{cmd:t,args:n}){return new Promise(r=>{let i;try{i=fP(t,n,{stdio:["pipe","ignore","ignore"]})}catch{r(!1);return}let o=i,s=!1;function a(l){s||(s=!0,clearTimeout(c),r(l))}let c=setTimeout(()=>{o.kill(),a(!1)},hP);c.unref(),o.on("error",()=>{a(!1)}),o.on("close",l=>{a(l===0)}),o.stdin.on("error",()=>{a(!1)});try{o.stdin.end(e)}catch{a(!1)}})}async function es(e){for(let t of gP())if(await yP(e,t))return!0;return!1}import{BLOCKS_DIRECTORY_NAME as OP,CONFIG_FILE_NAME as DP,MANIFEST_FILE_NAME as LP,sanitizeToAPIName as BP}from"@kizenapps/packager";var ts=["min_w","max_w","min_h","max_h","default_w","default_h"];import{createHash as bP}from"crypto";import{mkdir as wP,readFile as vP,writeFile as kP}from"fs/promises";import{dirname as AP,join as zm}from"path";var Mc="appbuilder:",zn=".kizenapp/pushes.json",xP=["environment","businessId","pluginApiName","blockApiName","dashboardId","dashletId","contentHash","pushedAt"];function zc(e){return typeof e=="number"&&Number.isFinite(e)}function ns(e,t,n){return Math.min(Math.max(e,t),n)}function PP(e){let t={...e};return delete t.custom_object,t}function Um(e,t){return`${Mc}${e}/${t}`}function Vm(e){if(!e.startsWith(Mc))return null;let t=e.slice(Mc.length).split("/");if(t.length!==2)return null;let[n,r]=t;return!n||!r?null:{pluginApiName:n,blockApiName:r}}function Hm(e){let t={};for(let n of ts){let r=e[n];zc(r)&&(t[n]=r)}return t}function Km(e){return typeof e.host_chrome=="boolean"?{host_chrome:e.host_chrome}:{}}var Wm=e=>Object.entries(e).map(([t,n])=>({name:t,script:n}));function CP(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:Wm(e.event_scripts)}}function Vc(e){return e.length>0?{views:e.map(CP)}:{}}function Gm(e,t=[]){return{kind:"custom_code",version:1,name:e.name,script:e.script,styles:e.styles,event_scripts:Wm(e.event_scripts),...Hm(e),...Km(e),...Vc(t)}}function SP(e){return{object_id:e.objectId,entity_type:"static_content",report_type:"html",chart_type:"html",content:e.content,fe_extra_info:{}}}function _P(e){let t=0;for(let n of e){let r=n.layout;if(!F(r))continue;let{y:i,h:o}=r;!zc(i)||!zc(o)||(t=Math.max(t,i+o))}return t}function EP(e,t,n){let r=ns(t.default_w??t.min_w??6,t.min_w??1,t.max_w??12),i=ns(t.default_h??t.min_h??3,t.min_h??1,t.max_h??99);return{i:n,x:0,y:_P(e),w:ns(r,2,12),h:ns(i,1,99)}}function Jm(e){return{name:Um(e.pluginApiName,e.blockApiName),layout:EP(e.dashlets,e.content,e.layoutId),config:SP({content:e.content,objectId:e.objectId})}}function qm(e,t){let n=e.config;return{config:{...PP(F(n)?n:{}),content:t}}}function Ym(e){let t=e.config;return F(t)?t.content:void 0}function lr(e){let t=e.config;if(!F(t)||t.chart_type!=="html")return!1;let n=t.content;return F(n)&&n.kind==="custom_code"}function Zm(e){return e.dashlets.filter(lr)}function rs(e){let t=Ym(e);return F(t)&&typeof t.name=="string"?t.name:e.name}var cn=e=>typeof e=="string"?e:"";function Xm(e){return Array.isArray(e)?e.filter(F).map(t=>({name:cn(t.name),script:cn(t.script)})):F(e)?Object.entries(e).map(([t,n])=>({name:t,script:cn(n)})):[]}function Uc(e){if(Array.isArray(e))return e.map(Uc);if(F(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Uc(e[n]);return t}return e}function Qm(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e).trim():""}function IP(e){return Array.isArray(e)?e.filter(F).map(t=>({api_name:cn(t.api_name),name:Qm(t.name),type:cn(t.type),script:cn(t.script),html:cn(t.html),css:cn(t.css),event_scripts:Xm(t.event_scripts)})):[]}function Hc(e){let t=F(e)?e:{},n=IP(t.views),r={name:Qm(t.name),script:typeof t.script=="string"?t.script:"",styles:typeof t.styles=="string"?t.styles:"",event_scripts:Xm(t.event_scripts),...Hm(t),...Km(t),...n.length>0&&{views:n}};return bP("sha256").update(JSON.stringify(Uc(r))).digest("hex")}function ef(e){let{entry:t}=e;if(t?.dashboardId===e.dashboardId){let o=e.dashlets.find(s=>s.id===t.dashletId);if(o&&lr(o))return{kind:"map",dashlet:o,entry:t}}let n=Um(e.pluginApiName,e.blockApiName),r=e.dashlets.filter(o=>o.name===n&&lr(o)),[i]=r;return r.length===1&&i?{kind:"name",dashlet:i}:r.length>1?{kind:"ambiguous",dashlets:r}:{kind:"none"}}function tf(e,t){return t?.dashletId!==e.id?!1:Hc(Ym(e))!==t.contentHash}function Kc(e,t){return e.environment===t.environment&&e.businessId===t.businessId&&e.pluginApiName===t.pluginApiName&&e.blockApiName===t.blockApiName}function Wc(e,t){return e.find(n=>Kc(n,t))}function nf(e,t){let n=e.findIndex(r=>Kc(r,t));return n===-1?[...e,t]:e.map((r,i)=>i===n?t:r)}function rf(e,t){return e.filter(n=>!Kc(n,t))}function TP(e){if(!F(e))return null;for(let n of xP)if(typeof e[n]!="string")return null;let t=e;return{environment:t.environment,businessId:br(t.businessId),pluginApiName:t.pluginApiName,blockApiName:t.blockApiName,dashboardId:t.dashboardId,dashletId:t.dashletId,contentHash:t.contentHash,pushedAt:t.pushedAt}}var jm=e=>Date.parse(e.pushedAt)||0;function NP(e){let t=new Map;for(let n of e){let r=[n.environment,n.businessId,n.pluginApiName,n.blockApiName].join("\0"),i=t.get(r);(i===void 0||jm(n)>jm(i))&&t.set(r,n)}return[...t.values()]}var Mm=e=>e instanceof Error?e.message:String(e);async function of(e){let t;try{t=await vP(zm(e,zn),"utf8")}catch(r){if(tt(r))return[];throw new Error(`Couldn't read ${zn}: ${Mm(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(`${zn} is not valid JSON (${Mm(r)}). Fix it, or delete it to start a fresh push map.`)}if(!Array.isArray(n))throw new Error(`${zn} must contain a JSON array of push entries. Fix it, or delete it to start a fresh push map.`);return NP(n.map(TP).filter(r=>r!==null))}async function sf(e,t){let n=zm(e,zn);await wP(AP(n),{recursive:!0}),await kP(n,`${JSON.stringify(t,null,2)}
|
|
868
|
-
`,"utf8")}var RP={generic_dashboard:"dashboard",homepage:"homepage",chart_group:"chart_group"},$P={dashboard:"generic_dashboard",homepage:"homepage",chart_group:"chart_group"};function Gc(e){return RP[e]}function af(e){return $P[e]}function cf(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}`}var df=["min_w","max_w","min_h","max_h"],pf=[["min_w","max_w"],["min_h","max_h"]],is={default_w:["min_w","max_w"],default_h:["min_h","max_h"]},FP=Object.keys(is),mf=[...ts,"host_chrome"],jP=["\0","{__ref:"],Jc="views",qc=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 MP(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 zP(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 i=n.filter(({block:s})=>s.api_name===t),[o]=i;return o?i.length>1?{ok:!1,reason:"ambiguous",available:i.map(({block:s,pluginApiName:a})=>({pluginApiName:a,apiName:s.api_name}))}:{ok:!0,...o}:{ok:!1,reason:"not_found",available:r}}var lf=e=>typeof e=="number"&&Number.isInteger(e)&&e>0,oi=e=>jP.some(t=>e.includes(t));function UP(e){let t=e,{name:n,script:r,styles:i,event_scripts:o}=t;if(typeof r!="string"||!r.trim())return"script";if(n!==void 0&&typeof n!="string")return"name";if(i!==void 0&&typeof i!="string")return"styles";if(o!==void 0){if(!F(o))return"event_scripts";let d=Object.entries(o).find(([u,f])=>typeof f!="string"||oi(u)||oi(f));if(d)return`event_scripts.${d[0]}`}let s=[["name",n],["script",r],["styles",i]].find(([,d])=>typeof d=="string"&&oi(d));if(s)return s[0];let a=df.find(d=>t[d]!==void 0&&!lf(t[d]));if(a)return a;let c=pf.find(([d,u])=>{let f=t[d],g=t[u];return typeof f=="number"&&typeof g=="number"&&f>g});if(c)return c[0];let l=FP.find(d=>{let u=t[d];if(u===void 0)return!1;if(typeof u!="number"||!lf(u))return!0;let[f,g]=is[d],m=t[f],p=t[g];return typeof m=="number"&&u<m||typeof p=="number"&&u>p});if(l)return l;if(t.host_chrome!==void 0&&typeof t.host_chrome!="boolean")return"host_chrome"}var VP=["api_name","name","script","html","css"],uf=e=>typeof e!="string"||oi(e);function HP(e){for(let t of e){let n=t,r=typeof n.api_name=="string"?n.api_name:String(n.api_name),i=VP.find(a=>uf(n[a]));if(i)return{view:r,field:i};let o=n.event_scripts;if(!F(o))return{view:r,field:"event_scripts"};let s=Object.entries(o).find(([a,c])=>oi(a)||uf(c));if(s)return{view:r,field:`event_scripts.${s[0]}`}}}var KP=({view:e,field:t})=>`views.${e}.${t}`,WP=(e,t)=>`Block "${e}" can't carry view ${JSON.stringify(t.view)}: its ${t.field} must be a string without NUL characters or "{__ref:".`,GP=(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=pf.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(df.includes(t))return`Block "${e}" has an invalid ${t}: it must be a positive integer.`;if(t in is){let[r,i]=is[t];return`Block "${e}" has an invalid ${t}: it must be a positive integer between ${r} and ${i}.`}return`Block "${e}" has an invalid ${t}: it must be a string without NUL characters or "{__ref:".`},JP=({reason:e,available:t},n,r)=>{let i=MP(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: ${i}`:n===void 0?`This plugin has several blocks; pass the api_name of the one to ${r}: ${i}`:`More than one plugin has a block with api_name "${n}": ${i}`},qP=e=>{try{let t=JSON.parse(e);return F(t)?t:void 0}catch{return}},ff=e=>{let t=e.find(o=>o.path===LP),n=t?JSON.parse(t.content):[],r=Array.isArray(n)?n:[n],i=new Map;for(let o of r)F(o)&&typeof o.api_name=="string"&&typeof o.entry=="string"&&i.set(o.api_name,o.entry);return i},gf=(e,t)=>{let n=Ai(e);return n===""?t:`${n}/${t}`},hf=(e,t,n)=>{let r=`${gf(t,n)}/`,i=new Set,o=[];for(let s of e){if(!s.path.startsWith(r)||s.path.endsWith(".DS_Store"))continue;let[a,c,...l]=s.path.slice(r.length).split("/");if(a&&(i.add(a),c===DP&&l.length===0)){let d=qP(s.content);d&&o.push([a,d])}}return{directories:i,configs:o}},yf=(e,t)=>typeof e.api_name=="string"&&e.api_name!==""?e.api_name:BP(t),YP=(e,t)=>{let n=new Map;for(let[r,i]of hf(e,t,OP).configs){let o=yf(i,r),s={};for(let a of mf)i[a]!==void 0&&(s[a]=i[a]);n.set(o,s)}return n},ZP=(e,t={})=>({...Object.fromEntries(Object.entries(e).filter(([r])=>!mf.includes(r))),...t});function XP(e,t){let n=ff(t);return e.map(r=>{let i=n.get(r.api_name),o=i===void 0?new Map:YP(t,i);return{...r,artifacts:{...r.artifacts,custom_blocks:r.artifacts.custom_blocks.map(s=>ZP(s,o.get(s.api_name)))}}})}var bf=(e,t)=>JSON.stringify([String(e),String(t)]),QP=(e,t)=>{let{directories:n,configs:r}=hf(e,t,Jc),i=new Map(r),o=new Set;for(let s of n){let a=i.get(s)??{};o.add(bf(yf(a,s),a.name||s))}return o},eC=(e,t)=>e.api_name.localeCompare(t.api_name)||String(e.name).localeCompare(String(t.name)),tC="appbuilder/views-unmatched";function nC(e,t){let n=ff(t),r={},i=[];for(let o of e){let s=n.get(o.api_name),a=s===void 0?new Set:QP(t,s),c=o.artifacts.routable_pages.filter(l=>a.has(bf(l.api_name,l.name))).sort(eC);c.length!==a.size&&s!==void 0&&i.push({rule:tC,severity:"warning",message:`Found ${String(a.size)} ${Jc}/ components but matched ${String(c.length)} packaged views; the pushed block carries only the matched ones.`,path:gf(s,Jc),pluginApiName:o.api_name}),r[o.api_name]=c}return{views:r,warnings:i}}function rC(e,t){return Object.hasOwn(e,t)?e[t]??[]:[]}function wf(e){return{...e.block,...Vc(e.views)}}async function Yc(e){let{files:t,deployable:n,issues:r}=await Hr(e),i=nC(n,t);return{deployable:XP(n,t),views:i.views,warnings:[...r.filter(o=>o.severity==="warning"),...i.warnings]}}function Zc({deployable:e,views:t,warnings:n},r,i){let o=zP(e,r);if(!o.ok)return{ok:!1,reason:o.reason,message:JP(o,r,i),available:o.available};let s=UP(o.block);if(s!==void 0)return{ok:!1,reason:"invalid_block",message:GP(o.block.api_name,s),available:[],field:s};let a=rC(t,o.pluginApiName),c=HP(a);return c!==void 0?{ok:!1,reason:"invalid_block",message:WP(o.block.api_name,c),available:[],field:KP(c)}:{ok:!0,value:{block:o.block,pluginApiName:o.pluginApiName,views:a,warnings:n}}}async function vf(e,t){let n=Zc(await Yc(e),t,"export");if(!n.ok)throw new qc(n.reason,n.message,n);return n.value}import{randomUUID as iC}from"crypto";function Qc(e){return{...Qi(e),packageBlocks:Yc,readPushMap:of,writePushMap:sf,ensureGitignore:Ze,staleAgentFileWarnings:t=>Yi(t),randomUUID:iC}}var oC=new Set(["owner","admin","edit"]),sC="Chart groups are not listed here; find them with `appbuilder block targets --object <id> --json` and pass --dashboard <id>.",et=me;function aC(e,t){let n=new Set(t.map(r=>r.pluginApiName)).size>1;return t.map(({pluginApiName:r,apiName:i})=>{let o=e.find(a=>a.api_name===r)?.artifacts.custom_blocks.find(a=>a.api_name===i),s=n?`${r}/${i}`:i;return{value:i,label:`${o?.name??i} (${s})`,args:[i]}})}async function el(e,t){let n=await t.packageBlocks(t.cwd),r=Zc(n,e,"push");if(!r.ok){let{reason:l,message:d,field:u}=r;return l==="no_blocks"||l==="invalid_block"?et("invalid_block",d,u===void 0?{}:{field:u}):et("needs_choice",d,{choice:"block",choices:aC(n.deployable,r.available)})}let{block:i,pluginApiName:o,views:s,warnings:a}=r.value,c=Gm(i,s);return I({block:i,pluginApiName:o,content:c,contentHash:Hc(c),warnings:a})}var kf=e=>e==null?null:oC.has(e.toLowerCase());function si(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:kf(e.employee_access)}}var Af=e=>({id:e.id,objectName:e.object_name,fetchUrl:e.fetch_url}),cC="Contacts";async function tl(e){let[t,n]=await Promise.all([e.listCustomObjects(),e.getClientObjectId().catch(()=>null)]),r=t.map(Af).sort((i,o)=>i.objectName.localeCompare(o.objectName));return n!==null&&n!==""&&!r.some(i=>i.id===n)&&r.push({id:n,objectName:cC,fetchUrl:"client"}),r}async function lC(e,t,n){let{environment:r,businessId:i}=t;try{if(n.object!==void 0){let c=n.object,[l,d]=await Promise.all([e.getCustomObject(c).catch(()=>null),e.listDashboards("chart_group",c)]);return I({ok:!0,environment:r,businessId:i,object:l?Af(l):null,surfaces:{chart_group:d.map(u=>si(u,"chart_group"))}})}let[o,s,a]=await Promise.all([e.listDashboards("generic_dashboard"),e.listDashboards("homepage"),tl(e)]);return I({ok:!0,environment:r,businessId:i,surfaces:{dashboard:o.map(c=>si(c,"dashboard")),homepage:s.map(c=>si(c,"homepage"))},customObjects:a})}catch(o){return Me(o)}}var nl=(e,t)=>t.dashboard===e.id;function ss(e,t){return[...Zm(e).filter(r=>nl(e,r)).map(r=>{let i=Vm(r.name);return{value:r.id,label:rs(r),args:["--dashboard",e.id,"--dashlet",r.id],pushKey:i?r.name:null,isFromThisPlugin:i?.pluginApiName===t.pluginApiName}}),{value:"new",label:"Create a new block",args:["--dashboard",e.id,"--create"]}]}var rl=(e,t)=>ef({dashboardId:t.id,dashlets:t.dashlets,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name,entry:e.entry}),xf=(e,t)=>I({dashboard:e,surface:Gc(e.type),action:"create",dashlet:void 0,resolvedBy:t}),os=(e,t,n)=>I({dashboard:e,surface:Gc(e.type),action:"update",dashlet:t,resolvedBy:n});async function uC(e){let[t,n]=await Promise.all([e.client.listDashboards("generic_dashboard"),e.client.listDashboards("homepage")]),r=i=>o=>({value:o.id,label:o.name,args:["--dashboard",o.id],surface:i,canEdit:kf(o.employee_access)});return et("needs_choice",`Choose where to push; pass --dashboard <id>. ${sC}`,{choice:"dashboard",choices:[...t.map(r("dashboard")),...n.map(r("homepage"))]})}async function dC(e,t,n){let r=await e.client.getDashboard(t);if(n.create)return xf(r,"flag");let i=()=>ss(r,e.block);if(n.dashlet!==void 0){let s=n.dashlet,a=r.dashlets.find(c=>c.id===s&&nl(r,c));return a?lr(a)?os(r,a,"flag"):et("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.`):et("not_found",`Dashlet ${s} is not on dashboard "${r.name}" (${r.id}).`,{choice:"target",choices:i()})}let o=rl(e,r);return o.kind==="map"?os(r,o.dashlet,"push_map"):o.kind==="name"?os(r,o.dashlet,"name"):et("needs_choice",o.kind==="ambiguous"?`Dashboard "${r.name}" has ${String(o.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:i()})}async function pC(e,t,n){let r;try{r=await e.client.getDashboard(t.dashboardId)}catch(o){if(o instanceof q&&o.kind==="not_found")return et("remembered_target_missing",`The remembered dashboard ${t.dashboardId} no longer exists. Pass --dashboard <id> to choose another, or --forget to clear it.`);throw o}if(n.create)return xf(r,"remembered");let i=r.dashlets.find(o=>o.id===t.dashletId&&nl(r,o));return i&&lr(i)?os(r,i,"remembered"):et("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:ss(r,e.block)})}async function il(e,t){if(t.dashlet!==void 0&&t.create)return et("usage_error","Pass either --dashlet <id> or --create, not both.");if(t.dashlet!==void 0&&t.dashboard===void 0)return et("usage_error","--dashlet <id> needs --dashboard <id>.");try{return t.dashboard!==void 0?await dC(e,t.dashboard,t):e.entry?await pC(e,e.entry,t):await uC(e)}catch(n){return Me(n)}}async function mC(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:i,fetch_url:o}=r;return typeof o=="string"?{id:i,fetchUrl:o}:{id:i}}if(n!=="chart_group")return{id:r};try{let i=await e.getCustomObject(r);return{id:r,fetchUrl:i.fetch_url}}catch{return{id:r}}}async function ol(e,t,n,r){let{credentials:i,block:o}=e,{dashboard:s,surface:a}=t,c=[],l,d;if(t.action==="update"){let{dashlet:f}=t;if(tf(f,e.entry)){let g=`"${rs(f)}" (dashlet ${f.id}) was changed in Kizen since the last push.`;if(!n.force)return et("drift_detected",`${g} Pushing would overwrite those changes; pass --force to overwrite them.`);c.push(`${g} Overwriting it because of --force.`)}l={action:"update",method:"PATCH",path:Ar(s.id,f.id),body:qm(f,o.content),dashletId:f.id},d=`Update "${rs(f)}" (dashlet ${f.id})`}else l={action:"create",method:"POST",path:Ar(s.id),body:Jm({pluginApiName:o.pluginApiName,blockApiName:o.block.api_name,content:o.content,dashlets:s.dashlets,objectId:r.randomUUID(),layoutId:r.randomUUID()}),dashletId:null},d=`Create a new block on "${s.name}"`;let u=cf({appBaseUrl:Ll[i.environment],surface:a,dashboardId:s.id,customObject:await mC(e.client,s,a)});return I({...l,dashboard:{id:s.id,name:s.name,type:a},url:u,resolvedBy:t.resolvedBy,warnings:c,summary:{environment:i.environment,businessId:i.businessId,isProduction:Kn(i.environment),surface:a,dashboardId:s.id,dashboardName:s.name,action:t.action,actionLine:d,dashletId:l.dashletId,blockName:o.block.name,blockApiName:o.block.api_name,pluginApiName:o.pluginApiName,scriptBytes:Buffer.byteLength(o.content.script,"utf8"),stylesBytes:Buffer.byteLength(o.content.styles,"utf8"),...o.content.views&&{viewsBytes:Buffer.byteLength(JSON.stringify(o.content.views),"utf8")}}})}var sl=e=>({environment:e.credentials.environment,businessId:e.credentials.businessId,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name});async function al(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 et("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 Me(a)}let i=[...t.warnings],o={...sl(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,nf(e.pushMap,o)),s=!0}catch(a){i.push(`The push succeeded, but ${zn} couldn't be written, so this target isn't remembered: ${je(a)}`)}return I({dashletId:r,remembered:s,warnings:i})}var fC=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function cl(e){return fC.test(e)?{dashboardId:e,script:`await window.__kizenCustomBlocks?.refresh('${e}')`}:null}async function gC(e,t){let n=sl(e);if(!Wc(e.pushMap,n))return null;let r=rf(e.pushMap,n);return await t.writePushMap(t.cwd,r),r}async function ll(e,t){let{client:n,credentials:r,block:i}=e,o=await t.readPushMap(t.cwd),s=!1;if(e.forget&&e.isAborted?.()!==!0){let a=await gC({credentials:r,block:i,pushMap:o},t);a&&(o=a,s=!0)}return{context:{client:n,credentials:r,block:i,pushMap:o,entry:Wc(o,sl({credentials:r,block:i}))},forgotten:s}}function ai(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 hC=e=>`${e.path===void 0?"":`${e.path}: `}${e.message} (${e.rule})`;async function yC(e){try{return await e.staleAgentFileWarnings(e.cwd)}catch{return[]}}async function Pf(e,t,n){let r={json:t.json===!0,deps:n},i="appbuilder block push",o=e===void 0?[]:[e],s=Rn(t,n.processEnv),a=(d,u)=>u==="environment"?[...o,...d.args,...rn(t,n.processEnv)]:u==="block"?[...d.args,...s]:[...o,...s,...d.args],c=(d,u)=>Et(i,a(d,u),r),l=d=>{It(r,d,c)};try{let d=await Nn(t,n);if(!d.ok){l(d);return}let{credentials:u,client:f,notices:g}=d.value;s=to(t,u),ze(n,g);let m=await el(e,n);if(!m.ok){l(m);return}let p=m.value;o=[p.block.api_name],p.warnings.length>0&&n.writeStderr(`${We(p.warnings)}
|
|
869
|
-
`);let{context:h,forgotten:b}=await
|
|
870
|
-
`);let y=await
|
|
871
|
-
`),[...ai(x.summary),...
|
|
867
|
+
`);let g=await tm(c.value,d.api_name,t);if(!g.ok){i(g);return}let p=g.value,m=await fo(p,l.value,{force:e.force===!0,...e.baseFromPreview!==void 0&&{baseFromPreview:e.baseFromPreview}},t);if(!m.ok){i(m);return}let h=m.value;ze(t,h.notices);let b=Ye(e,p.credentials.environment);if(!b.ok){i(b);return}let y=Fn(d.artifacts.js_action_templates),C=await vt(t),S=$=>{let V=st($),X=Xr($,o);return ze(t,V),{jsNext:X,warnings:[...u.map(bx),...h.warnings,...Ge($),...C],notices:[...h.notices,...V],jsActions:Lo($,X,o)}},x={...wt(h.summary),source:h.source,thumbnail:h.thumbnail,preview:h.preview,base:h.base,conflictMarkers:h.conflictMarkers};if(b.value.kind==="dry-run"){let $=await ot(p,{kind:"version",templates:y}),{warnings:V,notices:X,jsActions:ve}=S($);jn(r,b.value,{action:"push",...x,jsActions:ve,notices:X,warnings:V},s(a,h.summary.isProduction),Ce(...Qr(h),...Qe($),...ee(V)));return}let v=await go(p,l.value,h,t);if(!v.ok){i(v);return}let k=await Eo(p,y),{jsNext:P,warnings:w,notices:A,jsActions:_}=S(k),T=[...w,...v.value.warnings],L={...h,source:v.value.source};Pe(r,{ok:!0,applied:!0,dryRun:!1,action:"push",...x,jsActions:_,source:v.value.source,previewVersion:v.value.version,apiName:v.value.apiName,sourcePackageId:v.value.sourcePackageId,thumbnailId:v.value.thumbnailId,remembered:v.value.remembered,notices:A,warnings:T,next:[...P,{step:"publish",argv:o(["publish"])}]},Ce(dc(d.name,v.value),...Qr(L),...Qe(k),...ee(T)))}catch(c){i(z(c))}}function vx(e,t){let n=e.reason==="base_unknown"?"your preview's source doesn't say what it's based on":`your preview's base ${ti(e.baseLiveVersion)}, read from its source on the server`;return`Conflict check: ${e.conflict?t?"conflict, overridden by --force":"conflict":"none"} (${n})`}var pc=e=>[...qe(e.summary),`Preview: last updated ${e.previewUpdatedAt??"unknown"}`,vx(e.conflictCheck,e.forced)],mc=e=>`Publish: Live becomes the next release number (at least v${e.nextReleaseAtLeast})`,fc=(e,t)=>`\u2713 Published Live v${t.liveVersion} of ${e.summary.name??e.summary.baseApiName}`;async function sm(e,t){let n=Je("appbuilder app publish",[],e,t),{output:r,fail:i,apply:o,appArgv:s}=n,a=["publish",...e.force===!0?["--force"]:[]];try{let c=await Dt(e,t,n);if(c===null)return;let l=await ho(c,{force:e.force===!0,...e.expectPreview!==void 0&&{expectPreview:e.expectPreview}},t);if(!l.ok){i(l);return}let d=l.value,u=Ye(e,c.credentials.environment);if(!u.ok){i(u);return}let f=pc(d),g=[...d.warnings,...await vt(t)],p={...wt(d.summary),previewUpdatedAt:d.previewUpdatedAt,conflictCheck:d.conflictCheck,forced:d.forced};if(u.value.kind==="dry-run"){let S=await ot(c,{kind:"version",templates:Fn(d.jsActionTemplates)}),x=st(S),v=[...g,...Ge(S)];ze(t,x),jn(r,u.value,{action:"publish",...p,nextReleaseAtLeast:d.nextReleaseAtLeast,jsActions:Lo(S,Xr(S,s),s),notices:x,warnings:v},o([...a,"--expect-preview",d.previewSourcePackageId],d.summary.isProduction),Ce(...f,mc(d),...Qe(S),...ee(v)));return}let m=await yo(c,d,t);if(!m.ok){i(m);return}let h=await ot(c,{kind:"live",version:m.value.liveVersion}),b=st(h),y=Xr(h,s),C=[...g,...m.value.warnings,...Ge(h)];ze(t,b),Pe(r,{ok:!0,applied:!0,dryRun:!1,action:"publish",...p,apiName:m.value.apiName,liveVersion:m.value.liveVersion,previousLiveVersion:m.value.previousLiveVersion,remembered:m.value.remembered,jsActions:Lo(h,y,s),notices:b,warnings:C,next:y},Ce(fc(d,m.value),...f,...Qe(h),...ee(C)))}catch(c){i(z(c))}}var at=(e,t)=>t.length===0?[]:[`${e} (${String(t.length)}):`,...t.map(n=>` ${n}`)];function lc(e){return[...at("Written",e.written),...at("Deleted",e.deleted),...at("Conflicted",e.conflicted),...at("Edited here, deleted on Live (kept)",e.deletedOnLive),...at("Deleted here, changed on Live (restored)",e.deletedLocally),...at("Binary files changed on both sides (yours kept)",e.binaryConflicts),...at("On Live but excluded here (not written)",e.ignoredIncoming)]}var Bo=(e,t)=>t?`Live v${e}`:`v${e}`,kx=e=>`Resolve the conflict markers in the files above: the side marked <<<<<<< HEAD is your file and the side marked >>>>>>> live is ${e}. Then run \`appbuilder app push\` and \`appbuilder app publish\`.`,gc="Merge it into this folder by hand and then record its base, or merge from the release this folder was copied from with --base <n>. Use --base only with the release it was really copied from: a wrong one drops the changes made since then.";function hc(e){let t=e.baseVersion===void 0?"not recorded":ti(e.baseVersion),n=Bo(e.targetVersion,e.targetIsLive);switch(e.kind){case"accept":return[`Base: ${t}`,`Record v${e.targetVersion} as this folder's base without merging.`];case"up_to_date":return[`Base: ${t}`,`This folder already includes v${e.targetVersion}.`,...at("On Live but excluded here (not written)",e.ignoredIncoming)];case"merge":return[`Merge ${n} into this folder (base ${t}).`,...lc(e.plan)];case"fallback":return[`Base: ${t}`,`Can't merge automatically: ${e.detail}`,`${n}'s source goes into ${e.dir}.`]}}function Ax(e){let t={kind:e.kind,targetVersion:e.targetVersion,targetIsLive:e.targetIsLive,baseVersion:e.baseVersion??null,baseSource:e.baseSource,notices:e.notices};switch(e.kind){case"accept":return t;case"up_to_date":return{...t,ignoredIncoming:e.ignoredIncoming};case"merge":{let{written:n,deleted:r,conflicted:i,deletedOnLive:o,deletedLocally:s,binaryConflicts:a,ignoredIncoming:c}=e.plan;return{...t,written:n,deleted:r,conflicted:i,deletedOnLive:o,deletedLocally:s,binaryConflicts:a,ignoredIncoming:c}}case"fallback":return{...t,fallback:{reason:e.reason,detail:e.detail,dir:e.dir}}}}function xx(e){let t=(e.baseSource==="flag"||e.baseSource==="detected")&&typeof e.baseVersion=="string";return["merge","--release",e.targetVersion,...t&&typeof e.baseVersion=="string"?["--base",e.baseVersion]:[],...e.kind==="accept"?["--accept-live-base"]:[]]}function Px(e,t){return e.status!=="merged"&&e.status!=="conflicts"&&e.status!=="accepted"?[]:[...e.markedPaths.length===0?[]:[{step:"resolve",files:e.markedPaths,markers:fx}],{step:"push",argv:t(["push"])},{step:"publish",argv:t(["publish"])}]}function yc(e,t){let{targetVersion:n}=t,r=Bo(e.targetVersion,e.targetIsLive);switch(t.status){case"accepted":return[`\u2713 Recorded v${n} as this folder's base.`];case"up_to_date":return[`\u2713 This folder already includes v${n}.`,...at("On Live but excluded here (not written)",t.lists.ignoredIncoming)];case"merged":return[`\u2713 Merged ${r} into this folder.`,...lc(t.lists),"Run `appbuilder app push`, then `appbuilder app publish`."];case"conflicts":return[`Merged ${r} into this folder with conflicts.`,...lc(t.lists),kx(r)];case"fallback":return[...e.kind==="fallback"?[`Can't merge automatically: ${e.detail}`]:[],`${r}'s source is in ${t.extracted?.dir??""}.`,...at("Left out (safety list)",t.extracted?.skipped??[])]}}async function am(e,t){let n=[...e.release===void 0?[]:["--release",e.release],...e.base===void 0?[]:["--base",e.base],...e.acceptLiveBase===!0?["--accept-live-base"]:[]],r=Je("appbuilder app merge",n,e,t),{output:i,fail:o,runnable:s,appArgv:a,apply:c}=r;try{let l=await Dt(e,t,r);if(l===null)return;let d=await bo(l,{...e.release===void 0?{}:{version:e.release},...e.base===void 0?{}:{base:e.base},...e.acceptLiveBase===!0?{acceptLiveBase:!0}:{}},t);if(!d.ok){o(d);return}let u=d.value;ze(t,u.notices);let f=Ye({dryRun:e.dryRun===!0,yes:e.yes===!0,allowProduction:!0},l.credentials.environment);if(!f.ok){o(f);return}let g=qe(u.summary),p=[...u.warnings,...await vt(t)],m=u.kind==="fallback"?s(u.choices):[],h={...wt(u.summary),...Ax(u),...u.kind==="fallback"?{choices:m}:{}};if(f.value.kind==="dry-run"){jn(i,f.value,{action:"merge",...h,warnings:p},c(xx(u),!1),Ce(...g,...hc(u),...ee(p)));return}let b=await wo(l,u,t);if(!b.ok){o(b);return}let y=b.value,C=[...yc(u,y),...y.status==="fallback"?gx(gc,m):[]];Pe(i,{ok:!0,applied:!0,dryRun:!1,action:"merge",...h,status:y.status,baseLiveVersion:y.baseLiveVersion??null,...y.lists,...y.extracted===void 0?{}:{extracted:y.extracted},remembered:y.remembered,warnings:[...p,...y.warnings],next:Px(y,a)},Ce(...g,...C,...ee([...p,...y.warnings])))}catch(l){o(z(l))}}var bc=e=>[...qe(e.summary),`Rollback: restore v${e.version} as your preview`],wc=e=>`\u2713 Restored v${e.version} as your preview of ${e.summary.name??e.summary.baseApiName}`;async function cm(e,t,n){let r=Je("appbuilder app rollback",[e],t,n),{output:i,fail:o,appArgv:s,apply:a}=r;try{let c=await Dt(t,n,r);if(c===null)return;let l=await vo(c,e,n);if(!l.ok){o(l);return}let d=l.value,u=Ye(t,c.credentials.environment);if(!u.ok){o(u);return}let f=bc(d),g=[...d.warnings,...await vt(n)],p={...wt(d.summary),version:d.version,preview:d.preview};if(u.value.kind==="dry-run"){jn(i,u.value,{action:"rollback",...p,warnings:g},a(["rollback",e],d.summary.isProduction),Ce(...f,...ee(g)));return}let m=await ko(c,d,n);if(!m.ok){o(m);return}let h=[...g,...m.value.warnings];Pe(i,{ok:!0,applied:!0,dryRun:!1,action:"rollback",...p,apiName:m.value.apiName,sourcePackageId:m.value.sourcePackageId,remembered:m.value.remembered,warnings:h,next:[{step:"publish",argv:s(["publish"])}]},Ce(wc(d),...f,...ee(h)))}catch(c){o(z(c))}}var vc=(e,t)=>{let n=e.summary.name??e.summary.baseApiName,r=`(${String(t.written.length)} files)`;return[e.source==="release"?`\u2713 Extracted v${e.version} of ${n} into ${t.dir} ${r}`:`\u2713 Extracted your preview of ${n} into ${t.dir} ${r}`,...t.preview===void 0?[]:[`Folder base: ${rm(t.preview.base)}`],...at("Left out (safety list)",t.skipped)]},Cx=(e,t)=>e.source==="release"?{version:e.version}:{source:"preview",preview:{updated:e.updated,sourcePackageId:t.preview?.sourcePackageId??null},base:t.preview?.base??null};async function lm(e,t,n){let r=Ao(e,t.preview===!0);if(!r.ok){Je("appbuilder app pull",[],t,n).fail(r);return}let i=[...r.value.kind==="release"?[r.value.version]:["--preview"],...t.out===void 0?[]:["--out",t.out]],o=Je("appbuilder app pull",i,t,n),{output:s,fail:a}=o;try{let c=await Dt(t,n,o);if(c===null)return;let l=await xo(c,r.value,t,n);if(!l.ok){a(l);return}let d=l.value,u=await Po(c,d,n);if(!u.ok){a(u);return}let{dir:f,written:g,skipped:p,remembered:m}=u.value,h=[...d.warnings,...u.value.warnings,...await vt(n)];Pe(s,{ok:!0,...wt(d.summary),...Cx(d,u.value),dir:f,written:g,skipped:p,remembered:m,warnings:h,next:[]},Ce(...vc(d,u.value),...ee(h)))}catch(c){a(z(c))}}var kc=(e,t)=>[...qe(e),...t.actions.length===0?["No JS actions."]:Qe(t)],sc=e=>e===!0?"shown in its Perform Action menus":"not shown in its Perform Action menus",Do=e=>`${e.object.label} (${e.object.name})`;function Ac(e){let t=e.action.apiName;switch(e.change){case"create":return[`Link ${t} to ${Do(e)}, ${sc(e.includePerformAction)}.`];case"update":return[`Change ${t}'s link to ${Do(e)}: ${sc(e.includePerformAction)}.`];case"up_to_date":return[`${t} is already linked to ${Do(e)}, ${sc(e.includePerformAction)}.`]}}var xc=e=>[`Unlink ${e.action.apiName} from ${Do(e)}.`],Pc=(e,t)=>t==="updated"?`\u2713 Updated ${e.action.apiName}'s link to ${e.object.label}`:t==="already_linked"?`${e.action.apiName} was already linked to ${e.object.label}`:`\u2713 Linked ${e.action.apiName} to ${e.object.label}`,Cc=e=>`\u2713 Unlinked ${e.action.apiName} from ${e.object.label}`;function um(e,t){let{action:n,object:r}=t;return n!==void 0&&r!==void 0?I({action:n,object:r}):me("usage_error",`Missing argument <${n===void 0?"action":"object"}>. Usage: appbuilder app actions ${e} <action> <object>. A headless run needs both; at a terminal, leave them out to pick them.`)}var ac=e=>({...wt(e.summary),jsAction:{apiName:e.action.apiName,name:e.action.name,hintObjectName:e.action.hintObjectName,inLive:e.action.inLive},object:e.object,change:e.change,includePerformAction:e.includePerformAction,existing:e.existing});async function dm(e,t){let n=Je("appbuilder app actions list",[],e,t),{output:r,fail:i,appArgv:o}=n;try{let s=await Dt(e,t,n);if(s===null)return;let a=await No(s);if(!a.ok){i(a);return}let{summary:c,check:l}=a.value,d=[...Ge(l),...await vt(t)];Pe(r,{ok:!0,...wt(c),published:s.app!==null,status:l.status,actions:nm(l.actions,o),warnings:d,next:Xr(l,o).filter(u=>u.step!=="actions")},Ce(...kc(c,l),...ee(d)))}catch(s){i(z(s))}}async function pm(e,t,n,r){let i=um("link",{action:e,object:t});if(!i.ok){Je("appbuilder app actions link",[],n,r).fail(i);return}let{action:o,object:s}=i.value,a=n.menu===void 0?[]:[n.menu?"--menu":"--no-menu"],c=Je("appbuilder app actions link",[o,s,...a],n,r),{output:l,fail:d,appArgv:u,apply:f}=c,g=p=>["appbuilder","app","actions","link",o,p.id,...a];try{let p=await Dt(n,r,c);if(p===null)return;let m=await qp(p,{action:o,object:s,...n.menu===void 0?{}:{menu:n.menu}},g);if(!m.ok){d(m);return}let h=m.value,b=[...qe(h.summary),...Ac(h)],y=await vt(r),C=[...h.warnings,...y];if(ze(r,h.notices),h.change==="up_to_date"){Pe(l,{ok:!0,applied:!1,dryRun:!1,action:"actions link",...ac(h),status:"up_to_date",notices:h.notices,warnings:C,next:[]},Ce(...b,...ee(C)));return}let S=Ye(n,p.credentials.environment);if(!S.ok){d(S);return}if(S.value.kind==="dry-run"){jn(l,S.value,{action:"actions link",...ac(h),notices:h.notices,warnings:C},f(["actions","link",h.action.apiName,h.object.id,h.includePerformAction===!0?"--menu":"--no-menu"],h.summary.isProduction),Ce(...b,...ee(C)));return}let x=await $o(p,h);if(!x.ok){d(x);return}let v=[...x.value.status==="already_linked"?y:C,...x.value.warnings],k=Pc(h,x.value.status);Pe(l,{ok:!0,applied:x.value.status!=="already_linked",dryRun:!1,action:"actions link",...ac(h),status:x.value.status,notices:h.notices,warnings:v,next:[{step:"actions",argv:u(["actions","list"])}]},Ce(k,...b,...ee(v)))}catch(p){d(z(p))}}async function mm(e,t,n,r){let i=um("unlink",{action:e,object:t});if(!i.ok){Je("appbuilder app actions unlink",[],n,r).fail(i);return}let{action:o,object:s}=i.value,a=Je("appbuilder app actions unlink",[o,s],n,r),{output:c,fail:l,appArgv:d,apply:u}=a,f=g=>["appbuilder","app","actions","unlink",o,g.id];try{let g=await Dt(n,r,a);if(g===null)return;let p=await Zp(g,{action:o,object:s},f);if(!p.ok){l(p);return}let m=p.value,h=Ye(n,g.credentials.environment);if(!h.ok){l(h);return}let b=[...qe(m.summary),...xc(m)],y=[...m.warnings,...await vt(r)],C={...wt(m.summary),jsAction:{apiName:m.action.apiName,name:m.action.name,hintObjectName:m.action.hintObjectName,inLive:m.action.inLive},object:m.object,associationId:m.associationId,includePerformAction:m.includePerformAction};if(h.value.kind==="dry-run"){jn(c,h.value,{action:"actions unlink",...C,warnings:y},u(["actions","unlink",m.action.apiName,m.object.id],m.summary.isProduction),Ce(...b,...ee(y)));return}let S=await Oo(g,m);if(!S.ok){l(S);return}Pe(c,{ok:!0,applied:!0,dryRun:!1,action:"actions unlink",...C,status:S.value.status,warnings:y,next:[{step:"actions",argv:d(["actions","list"])}]},Ce(Cc(m),...b,...ee(y)))}catch(g){l(z(g))}}function ei(e){let{owner:t,preview:n}=e;return[...qe(e.summary),`Preview: ${t.fullName??t.id} (${t.yours?"yours":t.id}), last updated ${n.updated??"unknown"}`,...n.activeUsersCount===null?[]:[`Active users: ${String(n.activeUsersCount)}`],...n.installedCount===null?[]:[`Installs: ${String(n.installedCount)}`],e.deletesApp?"Delete: this preview, and with it the app":"Delete: this preview"]}var Sc=(e,t)=>{let n=e.summary.name??e.summary.baseApiName;return[`\u2713 Deleted ${e.owner.yours?"your":`${e.owner.fullName??e.owner.id}'s`} preview of ${n}`,...t.appDeleted===!0?[`${n} had no other version, so it was deleted from this business.`]:[],...e.deletesApp&&t.appDeleted===!1?[`${n} has another version now, so it wasn't deleted.`]:[]]},cc=(e,t,n)=>e.code==="preview_changed"?{...e,next:[{step:"preview delete",argv:n(["preview","delete","--owner",t])}]}:e,Sx="Kizen reports no last update for this preview, so this dry run can't be pinned to it and has no applyArgv: it can't be applied from this dry run.",Qp=e=>({...wt(e.summary),owner:e.owner,preview:e.preview,deletesApp:e.deletesApp});async function fm(e,t){let n=e.owner===void 0?[]:["--owner",e.owner],r=Je("appbuilder app preview delete",n,e,t),{output:i,fail:o,appArgv:s,apply:a}=r;try{let c=await Dt(e,t,r);if(c===null)return;let l=(e.owner??c.credentials.userId).trim(),d=Co(c,{...e.owner!==void 0&&{owner:e.owner},...e.expectUpdated!==void 0&&{expectUpdated:e.expectUpdated}});if(!d.ok){o(cc(d,l,s));return}let u=d.value,f=Ye(e,c.credentials.environment);if(!f.ok){o(f);return}let g=ei(u),p=[...u.warnings,...await vt(t)];if(f.value.kind==="dry-run"){let{updated:C}=u.preview,S=C===null?[Sx]:[];ze(t,S),jn(i,f.value,{action:"preview delete",...Qp(u),notices:S,warnings:p},C===null?null:a(["preview","delete","--owner",u.owner.id,"--expect-updated",C,...u.deletesApp?["--delete-app"]:[]],u.summary.isProduction),Ce(...g,...ee(p)));return}let m=Mp(u,e.deleteApp===!0);if(m!==null){o(cc(m,u.owner.id,s));return}let h=await So(c,u,t);if(!h.ok){o(cc(h,u.owner.id,s));return}let b=_o(u,h.value),y=[...b.warnings,...p.slice(u.warnings.length),...h.value.warnings];Pe(i,{ok:!0,applied:!0,dryRun:!1,action:"preview delete",...Qp(b),status:h.value.status,appDeleted:h.value.appDeleted,remembered:h.value.remembered,warnings:y,next:u.owner.yours?[{step:"push",argv:s(["push"])}]:[]},Ce(...Sc(u,h.value),...ei(b),...ee(y)))}catch(c){o(z(c))}}import{useEffect as uP,useState as Bc}from"react";import{Box as Qo,Text as jc}from"ink";var Fo={credentials:null,credentialNotices:[],warnings:[],notices:[]},gm=e=>t=>e.length===0?t:{...t,notices:[...t.notices,...e]},ni="Loading credentials\u2026",jo="Dry run: nothing was written.";function hm(e){if(e.login===void 0)return e;let{login:t,...n}=e;return{...n,hint:`Sign in with: ${t.argv.map(ge).join(" ")}`}}function Mo({deps:e,setPhase:t,setSession:n,next:r,toView:i=Me,present:o=s=>s}){let s=!1,a=f=>g=>{s||f(g)},c=a(t),l=a(n),d=f=>{s||(e.setExitCode(1),c({type:"error",view:o(f)}))},u=async f=>{c({type:"loading",label:ni});let g=await Nn(f,e);if(s)return;if(!g.ok){if(g.choice==="environment"&&g.choices){c({type:"environment-select",options:f,choices:g.choices});return}d(g);return}let{environment:p,businessId:m}=g.value.credentials;l(h=>({...h,credentials:{environment:p,businessId:m},credentialNotices:g.value.notices})),await r(f,g.value)};return{load:u,pickEnvironment:(f,g)=>u({...f.options,env:g.value}),fail:d,guard:f=>{f().catch(g=>{d(i(g))})},abort:()=>{s=!0},isAborted:()=>s,whileRunning:a}}function ym(e,t){e(),t(130)}function zo(e,t){if(e.dryRun)return"dry-run";if(e.yes){let n=Ye(e,t);if(n.ok&&n.value.kind==="apply")return"apply"}return"confirm"}var Am=e=>e.type==="done"||e.type==="report"||e.type==="error";function _x(e){let t={dryRun:!1,yes:!1,allowProduction:!1,force:!1};switch(e.command){case"versions":case"pull":case"actions list":return t;case"merge":return{...t,dryRun:e.options.dryRun===!0,yes:e.options.yes===!0};case"push":case"publish":return{dryRun:e.options.dryRun===!0,yes:e.options.yes===!0,allowProduction:e.options.allowProduction===!0,force:e.options.force===!0};case"rollback":case"actions link":case"actions unlink":case"preview delete":return{...t,dryRun:e.options.dryRun===!0,yes:e.options.yes===!0,allowProduction:e.options.allowProduction===!0}}}var Ex={dryRun:!1,yes:!1,allowProduction:!1};function Ix(e){let t=e.argv??[];if(t[0]!=="appbuilder"||t[1]!=="app")return null;let n=o=>{let s=t.indexOf(o);return s===-1?void 0:t[s+1]},r=n("--release"),i=n("--base");if(t[2]==="push"){let o=n("--base-from-preview");return{command:"push",...o!==void 0&&{baseFromPreview:o}}}return t[2]==="actions"&&t[3]==="link"&&t.length===4?{command:"actions link"}:t[2]==="merge"?{command:"merge",options:{...r!==void 0&&{version:r},...i!==void 0&&{base:i},...t.includes("--accept-live-base")&&{acceptLiveBase:!0}}}:null}var bm=e=>e.replace(/ Only if the user explicitly wants[^:]*: pass --force\./g,""),wm={value:"exit",label:"Exit without publishing",args:[]},Tx={value:"merge",label:"Merge Live into this folder",args:[],argv:["appbuilder","app","merge"]},Nx={value:"push",label:"Push this folder as your preview",args:[],argv:["appbuilder","app","push"]},Rx={value:"link-actions",label:"Link JS actions now",args:[],argv:["appbuilder","app","actions","link"]},vm={value:"finish",label:"Done",args:[]},$x=e=>({value:e.id,label:`${e.objectName} (${e.name})`,args:[]}),Ox={linked:"linked",unlinked:"not linked",unknown:"not in Live, links can't be listed"},Dx=e=>({value:e.apiName,label:`${e.apiName} (${e.name}): ${Ox[e.status]}`,args:[]});function km(e,t){if(t===void 0)return I([...e]);let n=To(e,t,()=>[]);if(n.ok)return I([n.value]);if(n.code==="needs_choice"){let r=new Set((n.choices??[]).map(i=>i.value));return I(e.filter(i=>r.has(i.id)))}return n}var Lx=e=>`Conflicted files get git conflict markers: <<<<<<< HEAD is your file and >>>>>>> live is ${e}.`;function xm(e,t,n,r){let i=_x(e),o=e.command==="pull"?Ao(e.version,e.options.preview===!0):null,s=e.command==="publish"?e.options.expectPreview:void 0,a=null,c=Mo({deps:t,setPhase:n,setSession:r,toView:z,present:hm,next:async(E,N)=>{a={credentials:N.credentials,client:N.client},await fr(a)}}),{fail:l}=c,d=c.whileRunning(n),u=c.whileRunning(r),f=()=>!c.isAborted(),g={isAborted:c.isAborted},p=E=>{u(gm(E))},m=E=>{d({type:"loading",label:E})},h=E=>{d({type:"done",outcome:E})},b=(E,N,B)=>{if(Io(B).length===0){d(N);return}d({type:"choose",title:"What next?",message:"",lines:[],above:N,choices:[Rx,vm],run:async R=>{if(R.value===vm.value){d(N);return}await P(E,R,null)},dismissed:N})},y=()=>{l({message:"Cancelled."})},C=E=>["appbuilder","app",...E,...Rn(e.options,t.processEnv)].map(ge).join(" "),S=async(E,N)=>{let B=await qr({...E,baseApiName:N},t);return B.ok?(p(B.value.notices),B.value):(l(B),null)},x=async E=>{if(a===null)return null;m("Loading the app\u2026");let N=await qr({...a,baseApiName:E.baseApiName},t);return N.ok?N.value:(l(N),null)},v=async(E,N,B,R)=>{switch(zo(B,E.credentials.environment)){case"dry-run":h({title:jo,tone:"warning",lines:N.lines,warnings:N.warnings,next:null});return;case"apply":await R();return;case"confirm":d({type:"confirm",...N,apply:R})}},k=(E,N,B,R)=>{if(N.code==="base_required"&&N.choices&&N.choices.length>0){d({type:"choose",title:"Choose how to go on",message:bm(N.message),lines:[],choices:N.choices,run:O=>P(E,O,B,R),dismissed:null});return}if(N.code==="publish_conflict"&&N.conflict?.reason!=="preview_replaced"){let{message:O}=N,D=N.conflict?.reason==="base_unknown";d({type:"choose",title:"What next?",message:bm(O),lines:[],choices:[D?Nx:Tx,wm],run:async M=>{if(M.value===wm.value){l({message:O});return}await P(E,M,D?B:null)},dismissed:null});return}l(N)},P=async(E,N,B,R)=>{let O=Ix(N);if(O===null){l({message:`Can't run "${N.label}" here.`});return}let D=await x(E);if(D!==null){if(O.command==="push"){await A(D,R===void 0?B:R,O.baseFromPreview===void 0?{}:{baseFromPreview:O.baseFromPreview});return}if(O.command==="actions link"){await $e(D,{},Ex);return}await T(D,O.options,O.options.acceptLiveBase===!0?B:null)}},w=async(E,N,B,R)=>{if(!f())return;m("Checking the push\u2026");let O=await fo(E,N,{force:i.force,...R},t);if(!O.ok){k(E,O,async()=>{let J=await x(E);J!==null&&await w(J,N,B,{})},B);return}let D=O.value,M=Fn(N.deployable.artifacts.js_action_templates),Y=await ot(E,{kind:"version",templates:M}),G=[...Qr(D),...Qe(Y)],Z=[...D.warnings,...Ge(Y)];p([...D.notices,...st(Y)]),await v(E,{lines:G,warnings:Z,isProduction:D.summary.isProduction,prompt:"Push? (Y/n)",productionPrompt:"Type y to push to production (y/N)"},i,async()=>{if(!f())return;m(`Saving your preview of ${D.appName}\u2026`);let J=await go(E,N,D,t,g);if(!J.ok){l(J);return}let le=dc(D.appName,J.value);if(B!==null){p([le,...ee([...Z,...J.value.warnings])]),await B();return}m("Checking the JS actions\u2026");let ae=await Eo(E,M);p(st(ae)),b(E,{type:"done",outcome:{title:le,tone:"success",lines:[...Qr(D),...Qe(ae)],warnings:[...D.warnings,...Ge(ae),...J.value.warnings],next:C(["publish"])}},ae)})},A=async(E,N,B)=>{if(!f())return;m("Packaging the app\u2026");let R=await mo(t);if(!R.ok){l(R);return}let{issues:O,source:D,deployable:M}=R.value;u(G=>({...G,warnings:O})),p(D.notice===void 0?[]:[D.notice]);let Y="api"in E?E:await S(E,M.api_name);Y!==null&&await w(Y,R.value,N,B)},_=async E=>{if(!f())return;m("Checking for conflicts\u2026");let N=async()=>{let M=await x(E);M!==null&&await _(M)},B=await ho(E,{force:i.force,...s!==void 0&&{expectPreview:s}},t);if(!B.ok){k(E,B,N);return}let R=B.value,O=pc(R),D=await ot(E,{kind:"version",templates:Fn(R.jsActionTemplates)});p(st(D)),await v(E,{lines:[...O,mc(R),...Qe(D)],warnings:[...R.warnings,...Ge(D)],isProduction:R.summary.isProduction,prompt:"Publish? (Y/n)",productionPrompt:"Type y to publish to production (y/N)"},i,async()=>{if(!f())return;m("Publishing\u2026");let M=await yo(E,R,t,g);if(!M.ok){k(E,M,N);return}let Y=await ot(E,{kind:"live",version:M.value.liveVersion});p(st(Y)),b(E,{type:"done",outcome:{title:fc(R,M.value),tone:"success",lines:[...O,...Qe(Y)],warnings:[...R.warnings,...M.value.warnings,...Ge(Y)],next:null}},Y)})},T=async(E,N,B)=>{if(!f())return;m("Planning the merge\u2026");let R=await bo(E,N,t);if(!R.ok){l(R);return}let O=R.value,D=Bo(O.targetVersion,O.targetIsLive),M=O.kind==="merge"&&O.plan.conflicted.length>0;p(O.notices);let Y=async()=>{if(!f())return;m(O.kind==="fallback"?`Extracting ${D}\u2026`:O.kind==="merge"?"Merging\u2026":"Recording the base\u2026");let G=await wo(E,O,t,g);if(!G.ok){l(G);return}let Z=G.value,[J="",...le]=yc(O,Z),ae=[...O.warnings,...Z.warnings],Fe=Z.status==="accepted"||Z.status==="up_to_date";if(B!==null&&Fe){p([J,...ee(ae)]),await B();return}let Hn={title:J,tone:Z.status==="conflicts"||Z.status==="fallback"?"warning":"success",lines:le,warnings:ae,next:Z.status==="accepted"?C(["push"]):null};if(Z.status==="fallback"&&O.kind==="fallback"){d({type:"choose",title:"Choose how to go on",message:gc,lines:[J,...le],choices:O.choices,run:Rs=>P(E,Rs,null),dismissed:{type:"done",outcome:Hn}});return}h(Hn)};if(O.kind==="up_to_date"&&!O.advancesBase){await Y();return}await v(E,{lines:[...qe(O.summary),...hc(O),...M?[Lx(D)]:[]],warnings:O.warnings,isProduction:!1,prompt:O.kind==="merge"?"Merge? (Y/n)":O.kind==="fallback"?"Extract it? (Y/n)":"Record it? (Y/n)",productionPrompt:""},{dryRun:i.dryRun,yes:i.yes||B!==null&&O.kind==="accept",allowProduction:!0},Y)},L=async(E,N)=>{if(!f())return;m(`Preparing v${N}\u2026`);let B=await vo(E,N,t);if(!B.ok){l(B);return}let R=B.value,O=bc(R);await v(E,{lines:O,warnings:R.warnings,isProduction:R.summary.isProduction,prompt:"Restore it? (Y/n)",productionPrompt:"Type y to restore it on production (y/N)"},i,async()=>{if(!f())return;m(`Restoring v${R.version}\u2026`);let D=await ko(E,R,t,g);if(!D.ok){l(D);return}h({title:wc(R),tone:"success",lines:O,warnings:[...R.warnings,...D.value.warnings],next:C(["publish"])})})},$=async(E,N,B)=>{if(!f())return;m(N.kind==="release"?`Downloading v${N.version}\u2026`:"Downloading your preview\u2026");let R=await xo(E,N,B===void 0?{}:{out:B},t);if(!R.ok){l(R);return}let O=R.value;if(!f())return;let D=await Po(E,O,t,g);if(!D.ok){l(D);return}let[M="",...Y]=vc(O,D.value);h({title:M,tone:"success",lines:Y,warnings:[...O.warnings,...D.value.warnings],next:null})},V=async E=>{m("Reading the JS actions\u2026");let N=await No(E);if(!N.ok){l(N);return}let{summary:B,check:R}=N.value;d({type:"report",lines:kc(B,R),warnings:Ge(R)})},X=async E=>{m("Reading the JS actions\u2026");let N=await tc(E);return N.ok?N.value:(l(N),null)},ve=(E,N)=>{d({type:"choose",message:"",lines:[],...E,run:N,dismissed:null})},Re=async(E,N,B,R)=>{let[O]=N;if(B&&O!==void 0&&N.length===1){await R(O);return}if(O===void 0){l({message:"There's no object on this business that you can see."});return}let D=E.hintObjectName===null?null:To(N,E.hintObjectName,()=>[]);ve({title:`Object for ${E.apiName}`,choices:N.map($x),...D?.ok===!0&&{initial:D.value.id},searchable:!0},async M=>{let Y=N.find(G=>G.id===M.value);Y!==void 0&&await R(Y)})},$e=async(E,N,B)=>{if(!f())return;let R=await X(E);if(R===null)return;let O=km(R.objects,N.object);if(!O.ok){l(O);return}let D=N.action===void 0||N.object===void 0,M=async(J,le)=>{if(N.menu!==void 0||!D){await Te(E,R,J,le,N.menu,B);return}let ae=J.links.find(Fe=>Fe.objectId===le.id);ve({title:`Show ${J.apiName} in the Perform Action menus of ${le.objectName}?`,choices:[{value:"no",label:"No",args:[]},{value:"yes",label:"Yes",args:[]}],initial:ae?.includePerformAction===!0?"yes":"no"},Fe=>Te(E,R,J,le,Fe.value==="yes",B))},Y=J=>Re(J,O.value,N.object!==void 0,le=>M(J,le));if(N.action!==void 0){let J=Ro(E,R,N.action);if(!J.ok){l(J);return}await Y(J.value);return}let{actions:G}=R.check;if(G.length===0){l({message:`${E.baseApiName} has no JS actions to link.`});return}let Z=G.find(J=>J.status!=="linked");ve({title:"JS action to link",choices:G.map(Dx),...Z!==void 0&&{initial:Z.apiName},searchable:!0},async J=>{let le=G.find(ae=>ae.apiName===J.value);le!==void 0&&await Y(le)})},Te=async(E,N,B,R,O,D)=>{if(!f())return;let M=nc(E,N,B,R,{...O!==void 0&&{menu:O}}),Y=[...qe(M.summary),...Ac(M)];if(p(M.notices),M.change==="up_to_date"){h({title:"Nothing to change.",tone:"success",lines:Y,warnings:[],next:null});return}let G=M.change==="create";await v(E,{lines:Y,warnings:M.warnings,isProduction:M.summary.isProduction,prompt:G?"Link it? (Y/n)":"Change it? (Y/n)",productionPrompt:G?"Type y to link it on production (y/N)":"Type y to change it on production (y/N)"},D,async()=>{if(!f())return;m(G?"Linking\u2026":"Changing the link\u2026");let Z=await $o(E,M,g);if(!Z.ok){l(Z);return}h({title:Pc(M,Z.value.status),tone:Z.value.status==="already_linked"?"warning":"success",lines:Y,warnings:[...Z.value.status==="already_linked"?[]:M.warnings,...Z.value.warnings],next:C(["actions","list"])})})},gn=async(E,N,B)=>{if(!f())return;let R=await X(E);if(R===null)return;let O=km(R.objects,N.object);if(!O.ok){l(O);return}let D=N.action===void 0?null:Ro(E,R,N.action);if(D!==null&&!D.ok){l(D);return}if(D!==null&&N.object!==void 0){await Re(D.value,O.value,!0,G=>lt(E,R,D.value,G,B));return}let M=new Set(O.value.map(G=>G.id)),Y=(D===null?R.check.actions:[D.value]).flatMap(G=>G.links.filter(Z=>M.has(Z.objectId)).map(Z=>({action:G,link:Z})));if(Y.length===0){l(D===null?{message:`${E.baseApiName} has no listed JS action links to remove.`}:{message:`${D.value.apiName} isn't linked to any object.`,...!D.value.inLive&&{hint:rc(D.value.apiName)}});return}ve({title:"Link to remove",choices:Y.map(({action:G,link:Z})=>({value:Z.id,label:`${G.apiName} \u2192 ${Z.label} (${Z.objectName})`,args:[]})),searchable:!0},async G=>{let Z=Y.find(({link:Fe})=>Fe.id===G.value);if(Z===void 0)return;let{action:J,link:le}=Z,ae=R.objects.find(Fe=>Fe.id===le.objectId)??{id:le.objectId,name:le.objectName,objectName:le.label,entityName:null};await lt(E,R,J,ae,B)})},lt=async(E,N,B,R,O)=>{if(!f())return;let D=ic(E,N,B,R);if(!D.ok){l(D);return}let M=D.value,Y=[...qe(M.summary),...xc(M)];await v(E,{lines:Y,warnings:M.warnings,isProduction:M.summary.isProduction,prompt:"Unlink it? (Y/n)",productionPrompt:"Type y to unlink it on production (y/N)"},O,async()=>{if(!f())return;m("Unlinking\u2026");let G=await Oo(E,M,g);if(!G.ok){l(G);return}h({title:Cc(M),tone:"success",lines:Y,warnings:M.warnings,next:C(["actions","list"])})})},mr=async(E,N)=>{if(!f())return;let B=Co(E,{...N.owner!==void 0&&{owner:N.owner},...N.expectUpdated!==void 0&&{expectUpdated:N.expectUpdated}});if(!B.ok){l(B);return}let R=B.value,O=ei(R);await v(E,{lines:O,warnings:R.warnings,isProduction:R.summary.isProduction,strict:R.deletesApp,prompt:"Delete it? (Y/n)",productionPrompt:R.deletesApp?`Type y to delete the preview and the whole app${R.summary.isProduction?" on production":""} (y/N)`:"Type y to delete it on production (y/N)"},R.deletesApp&&N.deleteApp!==!0?{...i,yes:!1}:i,async()=>{if(!f())return;m("Deleting the preview\u2026");let D=await So(E,R,t,g);if(!D.ok){l(D);return}let[M="",...Y]=Sc(R,D.value),G=_o(R,D.value);h({title:M,tone:"success",lines:[...Y,...ei(G)],warnings:[...G.warnings,...D.value.warnings],next:R.owner.yours?C(["push"]):null})})},fr=async E=>{if(e.command==="push"){let{baseFromPreview:R}=e.options;await A(E,null,R===void 0?{}:{baseFromPreview:R});return}m("Loading the app\u2026");let N;try{N=await t.readManifestApiName(t.cwd)}catch(R){l(z(R));return}let B=await S(E,N);if(B!==null)switch(e.command){case"versions":{let R=await rr(B);if(!R.ok){l(R);return}let O=po(B,R.value),D=await ot(B,{kind:"app"});p(st(D)),b(B,{type:"report",lines:[...uc(O),...Qe(D)],warnings:[...O.warnings,...Ge(D)]},D);return}case"publish":await _(B);return;case"merge":await T(B,{...e.options.release!==void 0&&{version:e.options.release},...e.options.base!==void 0&&{base:e.options.base},...e.options.acceptLiveBase===!0&&{acceptLiveBase:!0}},null);return;case"rollback":await L(B,e.version);return;case"pull":o?.ok===!0&&await $(B,o.value,e.options.out);return;case"actions list":await V(B);return;case"actions link":await $e(B,{...e.action!==void 0&&{action:e.action},...e.object!==void 0&&{object:e.object},...e.options.menu!==void 0&&{menu:e.options.menu}},i);return;case"actions unlink":await gn(B,{...e.action!==void 0&&{action:e.action},...e.object!==void 0&&{object:e.object}},i);return;case"preview delete":await mr(B,e.options)}},{guard:zt}=c;return{start:()=>{if(o?.ok===!1){l(o);return}zt(()=>c.load(e.options))},pickEnvironment:(E,N)=>{zt(()=>c.pickEnvironment(E,N))},accept:E=>{zt(E.apply)},choose:(E,N)=>{zt(()=>E.run(N))},dismiss:E=>{E.dismissed===null?y():d(E.dismissed)},cancel:y,abort:c.abort}}import{useMemo as Ec,useState as Cm}from"react";import{Box as Ic,Text as Lt,useInput as Bx}from"ink";function _c(e,t){let n=i=>i.normalize("NFD").replace(new RegExp("\\p{Diacritic}","gu"),"").toLowerCase(),r=n(t).split(/\s+/).filter(Boolean);return e.flatMap((i,o)=>{let s=n(`${i.label} ${i.description??""}`);return r.every(a=>s.includes(a))?[{item:i,index:o}]:[]})}var Uo=(e,t,n)=>Math.min(Math.max(e,t),n);function Vo(e,t,n,r={}){if(t<=0)return 0;let i=Uo(Math.trunc(e)||0,0,t-1),o=c=>r.disabled?.[c]!==!0;if(n===0)return i;let s=n>0?1:-1;if(Math.abs(n)===1){for(let c=1;c<=t;c++){let l=((i+s*c)%t+t)%t;if(o(l))return l}return i}let a=Uo(i+Math.trunc(n),0,t-1);for(let c=a;c>=0&&c<t;c+=s)if(o(c))return c;for(let c=a-s;c>=0&&c<t;c-=s)if(o(c))return c;return i}function Pm(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 i=Uo(Math.trunc(e)||0,0,t-1),o=Uo(i-Math.floor(r/2),0,t-r);return{start:o,end:o+r}}import{jsx as Bt,jsxs as Nc}from"react/jsx-runtime";var Fx="\u2191/\u2193 to move, Enter to select, Esc to cancel",jx="Type to filter, \u2191/\u2193 to move, Enter to select, Esc to clear or cancel",Tc=10,Sm=(e,t)=>{let n=e.findIndex(o=>o.key===t&&o.disabled!==!0);if(n!==-1)return n;let r=Vo(0,e.length,0);if(e[r]?.disabled!==!0)return r;let i=e.findIndex(o=>o.disabled!==!0);return i===-1?r:i},Ft=({title:e,items:t,onSelect:n,onCancel:r,hint:i,initialKey:o,searchable:s=!1})=>{let[a,c]=Cm(""),l=Ec(()=>_c(t,s?a:""),[t,s,a]),d=Ec(()=>l.map(({item:C})=>C),[l]),[u,f]=Cm(()=>Sm(t,o)),g=Ec(()=>d.map(C=>C.disabled===!0),[d]),p=Vo(u,d.length,0);Bx((C,S)=>{let x=k=>{f(Vo(p,d.length,k,{disabled:g}))},v=k=>{c(k),f(Sm(_c(t,k).map(({item:P})=>P)))};if(S.upArrow||!s&&C==="k")x(-1);else if(S.downArrow||!s&&C==="j")x(1);else if(S.pageUp)x(-Tc);else if(S.pageDown)x(Tc);else if(S.return){let k=l[p];k!==void 0&&k.item.disabled!==!0&&n(k.item,k.index)}else S.escape?s&&a!==""?v(""):r?.():s&&(S.backspace||S.delete)?v(a.slice(0,-1)):s&&C!==""&&!S.ctrl&&!S.meta&&!S.tab&&v(a+C)});let{start:m,end:h}=Pm(p,d.length,Tc),b=m,y=d.length-h;return Nc(Ic,{flexDirection:"column",gap:1,children:[Bt(Lt,{bold:!0,children:e}),s&&Bt(Lt,{children:`Filter: ${a}`}),Nc(Ic,{flexDirection:"column",children:[b>0&&Bt(Lt,{dimColor:!0,children:` \u2191 ${String(b)} more`}),s&&d.length===0&&Bt(Lt,{dimColor:!0,children:" No matches"}),d.slice(m,h).map((C,S)=>{let v=m+S===p,k=C.disabled===!0,P=v&&!k;return Nc(Ic,{gap:2,children:[Bt(Lt,{...P&&{color:"cyan"},dimColor:k,children:v?"\u276F":" "}),Bt(Lt,{bold:P,dimColor:k,...P&&{color:"cyan"},children:C.label}),C.description!==void 0&&Bt(Lt,{dimColor:!0,children:C.description})]},C.key)}),y>0&&Bt(Lt,{dimColor:!0,children:` \u2193 ${String(y)} more`})]}),Bt(Lt,{dimColor:!0,children:i??(s?jx:Fx)})]})};import{jsx as Mx}from"react/jsx-runtime";function or(e,t){return(n,r)=>{let i=e[r];i!==void 0&&t(i)}}function sr({title:e,choices:t,onPick:n,onCancel:r,initial:i,searchable:o=!1}){return Mx(Ft,{title:e,items:t.map(s=>({key:s.value,label:s.label})),onSelect:or(t,n),onCancel:r,...i!==void 0&&{initialKey:i},searchable:o})}import{Text as _m,useInput as zx}from"ink";import{Fragment as Ux,jsx as Rc,jsxs as Vx}from"react/jsx-runtime";var $c=({prompt:e,strict:t,onAccept:n,onCancel:r})=>(zx((i,o)=>{if(o.ctrl)return;let s=i.toLowerCase();s==="y"||!t&&o.return?n():(t||s==="n"||o.escape)&&r()}),Rc(_m,{bold:!0,children:e})),Ho=({isProduction:e,strict:t=!1,prompt:n,productionPrompt:r,onAccept:i,onCancel:o})=>Vx(Ux,{children:[e&&Rc(_m,{color:"red",bold:!0,children:"PRODUCTION"}),Rc($c,{prompt:e||t?r:n,strict:e||t,onAccept:i,onCancel:o})]});import{Box as Oc,Text as Ko}from"ink";import{Box as Hx,Text as Kx}from"ink";import{jsx as Em}from"react/jsx-runtime";var Ne=({lines:e,color:t})=>Em(Hx,{flexDirection:"column",children:e.map((n,r)=>Em(Kx,{...t&&{color:t},children:n},`${String(r)}-${n}`))});import{jsx as Wo,jsxs as Go}from"react/jsx-runtime";var Jo=({view:e})=>Go(Oc,{flexDirection:"column",gap:1,children:[Go(Oc,{gap:1,children:[Wo(Ko,{color:"red",children:"\u2717"}),Wo(Ko,{color:"red",children:e.issues&&e.issues.length>0?We(e.issues):e.message})]}),e.hint!==void 0&&Go(Ko,{dimColor:!0,children:["Hint: ",e.hint]}),e.choices&&e.choices.length>0&&Go(Oc,{flexDirection:"column",children:[Wo(Ko,{children:"Choices:"}),Wo(Ne,{lines:e.choices.map(t=>` ${t.label}`)})]})]});import{useEffect as Qx}from"react";import{Box as eP,Text as Nm,useApp as tP,useInput as nP}from"ink";import{Box as qx,Text as Yx}from"ink";import{Box as Wx,Text as Gx}from"ink";import{jsx as Im}from"react/jsx-runtime";var Jx=[" :::::::: "," :::::: ::::::::::: "," :::::: :::::::::: "," :::::: :::::: ::::::: "," ::::: :::::: ::::::::::::::::: "," ::::: ::::: ::::::::::::::::::: "," ::::: ::::: :::::: ::::: ",":::: ::::: ::: ::::: :: ","::::: :::::: :::::::::: ","::::: :::::: ::::::::::: "," ::::: ::: ::::::: "," ::::::: ::: ::::: "," ::::::::::: :::::: :::::"," :::::::::: :::::: :::::"," :: ::::: ::: ::::: ::::"," ::::: :::::: ::::: ::::: ::: "," ::::::::::::::::::: ::::: ::::: "," ::::::::::::::::: ::::: ::::: "," ::::::::: :::::: :::::: "," :::::::::: :::::: "," ::::::::::: :::::: "," :::::::: "],Tm=()=>Im(Wx,{flexDirection:"column",children:Jx.map((e,t)=>Im(Gx,{color:"cyan",children:e},t))});import{Fragment as Zx,jsx as Dc,jsxs as Xx}from"react/jsx-runtime";var ye=({marginBottom:e=0})=>Xx(Zx,{children:[Dc(Tm,{}),Dc(qx,{flexDirection:"column",marginTop:1,marginBottom:e,children:Dc(Yx,{bold:!0,color:"cyan",children:"Kizen App Development Toolkit"})})]});import{jsx as qo,jsxs as Rm}from"react/jsx-runtime";var Yo=({session:e,children:t})=>Rm(eP,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[qo(ye,{}),e.credentials&&Rm(Nm,{dimColor:!0,children:["Environment: ",e.credentials.environment," \xB7 Business: ",e.credentials.businessId]}),e.credentialNotices.length>0&&qo(Ne,{lines:e.credentialNotices,color:"yellow"}),e.warnings.length>0&&qo(Nm,{dimColor:!0,children:We(e.warnings)}),e.notices.length>0&&qo(Ne,{lines:e.notices}),t]});function Zo(e,t,n){let r=tP();Qx(()=>{e&&r.exit()},[e,r]),nP((i,o)=>{o.ctrl&&i==="c"&&!e&&(ym(n,t),r.exit())})}import{Box as Lc,Text as Xo}from"ink";import{jsx as $m,jsxs as ri}from"react/jsx-runtime";var ar=({issues:e})=>{let t=e.filter(n=>n.severity==="error").length;return ri(Lc,{flexDirection:"column",marginTop:1,children:[ri(Xo,{color:"red",children:["\u2717 ",t," validation ",t===1?"error":"errors"]}),[...Ra(e)].map(([n,r])=>ri(Lc,{flexDirection:"column",marginTop:1,children:[$m(Xo,{bold:!0,children:n}),r.map((i,o)=>$m(Lc,{paddingLeft:2,children:ri(Xo,{color:i.severity==="error"?"red":"yellow",children:[i.severity==="error"?"\u2717":"\u26A0"," ",i.message," ",ri(Xo,{dimColor:!0,children:["(",i.rule,")"]})]})},`${i.rule}-${String(o)}`))]},n))]})};import{Box as aP,Text as cP}from"ink";import{useEffect as rP,useState as iP}from"react";import{Text as oP}from"ink";import{jsx as sP}from"react/jsx-runtime";var Om=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],kt=()=>{let[e,t]=iP(0);return rP(()=>{let n=setInterval(()=>{t(r=>(r+1)%Om.length)},80);return()=>{clearInterval(n)}},[]),sP(oP,{color:"cyan",children:Om[e]??"\u280B"})};import{jsx as Dm,jsxs as lP}from"react/jsx-runtime";var cr=({label:e})=>lP(aP,{gap:1,children:[Dm(kt,{}),Dm(cP,{dimColor:!0,children:e})]});import{jsx as fe,jsxs as ii}from"react/jsx-runtime";var Mc=({warnings:e})=>e.length>0?fe(Ne,{lines:ee(e),color:"yellow"}):null,dP=({outcome:e})=>ii(Qo,{flexDirection:"column",gap:1,children:[fe(jc,{bold:!0,color:e.tone==="success"?"green":"yellow",children:e.title}),e.lines.length>0&&fe(Ne,{lines:e.lines}),fe(Mc,{warnings:e.warnings}),e.next!==null&&ii(jc,{dimColor:!0,children:["Next: ",e.next]})]}),Fc=({phase:e})=>e.type==="done"?fe(dP,{outcome:e.outcome}):ii(Qo,{flexDirection:"column",gap:1,children:[fe(Ne,{lines:e.lines}),fe(Mc,{warnings:e.warnings})]}),pP=({view:e})=>e.issues&&e.issues.length>0?fe(ar,{issues:e.issues}):fe(Jo,{view:e}),Lm=({request:e,deps:t})=>{let[n,r]=Bc({type:"loading",label:ni}),[i,o]=Bc(Fo),[s]=Bc(()=>xm(e,t,r,o));uP(()=>{s.start()},[s]),Zo(Am(n),t.setExitCode,s.abort);let a=c=>fe(Yo,{session:i,children:c});switch(n.type){case"loading":return a(fe(cr,{label:n.label}));case"environment-select":return a(fe(sr,{title:"Environment",choices:n.choices,onPick:c=>{s.pickEnvironment(n,c)},onCancel:s.cancel},"environment"));case"report":return a(fe(Fc,{phase:n}));case"confirm":return a(ii(Qo,{flexDirection:"column",gap:1,children:[fe(Ne,{lines:n.lines}),fe(Mc,{warnings:n.warnings}),fe(Ho,{isProduction:n.isProduction,strict:n.strict===!0,prompt:n.prompt,productionPrompt:n.productionPrompt,onAccept:()=>{s.accept(n)},onCancel:s.cancel})]}));case"choose":return a(ii(Qo,{flexDirection:"column",gap:1,children:[n.above!==void 0&&fe(Fc,{phase:n.above}),n.lines.length>0&&fe(Ne,{lines:n.lines}),n.message!==""&&fe(jc,{color:"yellow",children:n.message}),fe(sr,{title:n.title,choices:n.choices,onPick:c=>{s.choose(n,c)},onCancel:()=>{s.dismiss(n)},...n.initial!==void 0&&{initial:n.initial},searchable:n.searchable===!0},[n.title,...n.choices.map(c=>c.value)].join("|"))]}));case"done":return a(fe(Fc,{phase:n}));case"error":return a(fe(pP,{view:n.view}))}};var gP=e=>{console.error(`Error: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1},At=e=>e.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)"),xt=e=>e.option("--json","print a JSON result to stdout (always headless)").option("--no-interactive",gt).option("--env <env>","environment of the `appbuilder login` session to use").option("--business <id-or-name>","use this saved account, by business id or name (ignoring case), instead of the current one (default: $APPBUILDER_BUSINESS)").option("--user <userId>","with --business, use the saved account of this user id (default: $APPBUILDER_USER)"),Mn=(e,t=!0)=>(e.option("--dry-run","show what would change without writing anything").option("--yes","write without asking (without it, the command is a dry run)"),t?e.option("--allow-production","allow writes to go/fmo"):e);async function Pt(e,t,n){try{let r=lp(process.cwd());if(!ft({json:e.options.json===!0,noInteractive:t})){await n(r);return}let{waitUntilExit:i}=fP(mP(Lm,{request:e,deps:r}),{exitOnCtrlC:!1});await i()}catch(r){gP(r)}}function hP(e){let t=e.command("actions").description("Link the app's JS actions to objects: list, link and unlink"),n=At(t.command("list").description("Show the app's JS actions and the objects they're linked to"));xt(n).action(async o=>{let{noInteractive:s,options:a}=Ae(o);await Pt({command:"actions list",options:a},s,c=>dm(a,c))});let r=At(t.command("link").description("Link a JS action to an object, or change whether it shows in its menus").argument("[action]","the JS action's api_name (at a terminal, leave it out to pick it)").argument("[object]","the object's api name (like client_client) or id")).option("--menu","show the action in the object's Perform Action menus").option("--no-menu","don't show it there (the default for a new link)");xt(Mn(r)).action(async(o,s,a)=>{let{noInteractive:c,options:l}=Ae(a);await Pt({command:"actions link",...o!==void 0&&{action:o},...s!==void 0&&{object:s},options:l},c,d=>pm(o,s,l,d))});let i=At(t.command("unlink").description("Remove a JS action's link to an object").argument("[action]","the JS action's api_name (at a terminal, leave it out to pick a link)").argument("[object]","the object's api name (like client_client) or id"));xt(Mn(i)).action(async(o,s,a)=>{let{noInteractive:c,options:l}=Ae(a);await Pt({command:"actions unlink",...o!==void 0&&{action:o},...s!==void 0&&{object:s},options:l},c,d=>mm(o,s,l,d))})}function yP(e){let t=e.command("preview").description("Manage the app's previews: delete"),n=At(t.command("delete").description("Delete your preview of the app, or with --owner, another developer's")).option("--owner <userId>","delete this user's preview instead of yours").option("--expect-updated <ts>","delete only if the preview's last update is still <ts> (a dry run prints it)").option("--delete-app","allow deleting the whole app when this preview is its only version (a dry run that says so prints it)");xt(Mn(n)).action(async r=>{let{noInteractive:i,options:o}=Ae(r);await Pt({command:"preview delete",options:o},i,s=>fm(o,s))})}function Bm(e){let t=e.command("app").description("Publish the plugin as a Business App: previews, releases, merges and rollbacks"),n=At(t.command("versions").description("Show the app's Live, released and preview versions"));xt(n).action(async c=>{let{noInteractive:l,options:d}=Ae(c);await Pt({command:"versions",options:d},l,u=>im(d,u))});let r=At(t.command("push").description("Save this folder as your preview of the app"));xt(Mn(r).option("--force","push even if files still have merge conflict markers").option("--base-from-preview <id>","take this folder's base from your preview, while it's still source package <id> (a base_required choice prints it)")).action(async c=>{let{noInteractive:l,options:d}=Ae(c);await Pt({command:"push",options:d},l,u=>om(d,u))});let i=At(t.command("publish").description("Publish your preview as the next Live version"));xt(Mn(i).option("--force","publish even if Live changed since your preview was based on it, or its base is unknown").option("--expect-preview <id>","publish only if your preview's source package is still <id> (a dry run prints it)")).action(async c=>{let{noInteractive:l,options:d}=Ae(c);await Pt({command:"publish",options:d},l,u=>sm(d,u))});let o=At(t.command("merge").description("Merge the Live version (or --release) into this folder")).option("--release <n>","merge release <n> instead of the Live version").option("--base <n>","the release this folder was copied from, when no base is recorded (a wrong one drops the changes made since)").option("--accept-live-base","record Live (or --release) as this folder's base without merging, after merging by hand");xt(Mn(o,!1)).action(async c=>{let{noInteractive:l,options:d}=Ae(c);await Pt({command:"merge",options:d},l,u=>am(d,u))});let s=At(t.command("rollback").description("Restore a released version as your preview").argument("<version>","the released version to restore"));xt(Mn(s)).action(async(c,l)=>{let{noInteractive:d,options:u}=Ae(l);await Pt({command:"rollback",version:c,options:u},d,f=>cm(c,u,f))});let a=At(t.command("pull").description("Download a released version's source, or with --preview your preview's, into a new folder").argument("[version]","the released version to download (or pass --preview instead)")).option("--preview","download your preview instead of a released version").option("--out <dir>","folder to create (default: ../<api_name>-v<version>, or ../<api_name>-preview)");xt(a).action(async(c,l)=>{let{noInteractive:d,options:u}=Ae(l);await Pt({command:"pull",...c!==void 0&&{version:c},options:u},d,f=>lm(c,u,f))}),hP(t),yP(t)}var bP=async(e,t)=>{let n={json:!0,deps:t},r=i=>Tt("appbuilder whoami",[...i.args,...rn(e,t.processEnv)],n);try{let i=bn(e,t.processEnv);if(!i.ok){Nt(n,me("usage_error",i.message),r);return}let o=await Oa(e.env,i.request,{sessions:t.store,connect:(c,l)=>t.identify(t.tokenProvider(c,l===void 0?void 0:{account:l})),processEnv:t.processEnv});if(!o.ok){Nt(n,o,r);return}let{environment:s,connected:a}=o.value;Pe(n,{ok:!0,environment:s,businessId:a.businessId,businessName:a.businessName??null,userId:a.userId,fullName:a.fullName??null,email:a.email??null},Ri(s,a))}catch(i){Nt(n,Me(i),r)}},Fm=(e,t)=>e.json===!0?bP(e,t):Tu(e,t);import{render as wP}from"ink";import{jsx as vP}from"react/jsx-runtime";var jm=async(e,t)=>{let n,r=wP(vP(Ft,{title:e,items:t,onSelect:i=>{n=i.key,r.unmount()},onCancel:()=>{r.unmount()}}));return await r.waitUntilExit(),n};var kP=[{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"],["--no-interactive",gt]],run:Eu},{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:Iu},{name:"whoami",description:"Show the user and business of the stored session",env:"environment to check (default: the only signed-in one, or with --business the only one where it's saved)",options:[["--business <id-or-name>","check this saved account, by business id or name (ignoring case), instead of the current one (default: $APPBUILDER_BUSINESS)"],["--user <userId>","with --business, check the saved account of this user id (default: $APPBUILDER_USER)"],["--json","print the identity as JSON"]],run:Fm},{name:"auth-header",description:"Print an Authorization header for the stored session as JSON (for a Claude Code MCP headersHelper)",env:"environment to use; must match CLAUDE_CODE_MCP_SERVER_URL when that is set (default: the environment matching it, else the only signed-in one)",options:[["--business <id>","with --user, use this saved account, current or not"],["--user <userId>","with --business, the user id of that account"]],run:Nu}];function Mm(e){for(let{name:t,description:n,env:r,options:i=[],run:o}of kP){let s=e.command(t).description(n).option("--env <env>",r);for(let[a,c]of i)s.option(a,c);s.action(async a=>{let{noInteractive:c,options:l}=Ae(a);await o(l,xu(void 0,jm,c))})}}import{createElement as BC}from"react";import{render as FC}from"ink";import{PluginValidationError as jC}from"@kizenapps/packager";import{spawn as AP}from"child_process";import{platform as zm}from"process";function xP(){return zm==="darwin"?[{cmd:"pbcopy",args:[]}]:zm==="win32"?[{cmd:"clip",args:[]}]:[{cmd:"wl-copy",args:[]},{cmd:"xclip",args:["-selection","clipboard"]},{cmd:"xsel",args:["--clipboard","--input"]}]}var PP=2e3;function CP(e,{cmd:t,args:n}){return new Promise(r=>{let i;try{i=AP(t,n,{stdio:["pipe","ignore","ignore"]})}catch{r(!1);return}let o=i,s=!1;function a(l){s||(s=!0,clearTimeout(c),r(l))}let c=setTimeout(()=>{o.kill(),a(!1)},PP);c.unref(),o.on("error",()=>{a(!1)}),o.on("close",l=>{a(l===0)}),o.stdin.on("error",()=>{a(!1)});try{o.stdin.end(e)}catch{a(!1)}})}async function es(e){for(let t of xP())if(await CP(e,t))return!0;return!1}import{BLOCKS_DIRECTORY_NAME as UP,CONFIG_FILE_NAME as VP,MANIFEST_FILE_NAME as HP,sanitizeToAPIName as KP}from"@kizenapps/packager";var ts=["min_w","max_w","min_h","max_h","default_w","default_h"];import{createHash as SP}from"crypto";import{mkdir as _P,readFile as EP,writeFile as IP}from"fs/promises";import{dirname as TP,join as Hm}from"path";var zc="appbuilder:",zn=".kizenapp/pushes.json",NP=["environment","businessId","pluginApiName","blockApiName","dashboardId","dashletId","contentHash","pushedAt"];function Uc(e){return typeof e=="number"&&Number.isFinite(e)}function ns(e,t,n){return Math.min(Math.max(e,t),n)}function RP(e){let t={...e};return delete t.custom_object,t}function Km(e,t){return`${zc}${e}/${t}`}function Wm(e){if(!e.startsWith(zc))return null;let t=e.slice(zc.length).split("/");if(t.length!==2)return null;let[n,r]=t;return!n||!r?null:{pluginApiName:n,blockApiName:r}}function Gm(e){let t={};for(let n of ts){let r=e[n];Uc(r)&&(t[n]=r)}return t}function Jm(e){return typeof e.host_chrome=="boolean"?{host_chrome:e.host_chrome}:{}}var qm=e=>Object.entries(e).map(([t,n])=>({name:t,script:n}));function $P(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:qm(e.event_scripts)}}function Hc(e){return e.length>0?{views:e.map($P)}:{}}function Ym(e,t=[]){return{kind:"custom_code",version:1,name:e.name,script:e.script,styles:e.styles,event_scripts:qm(e.event_scripts),...Gm(e),...Jm(e),...Hc(t)}}function OP(e){return{object_id:e.objectId,entity_type:"static_content",report_type:"html",chart_type:"html",content:e.content,fe_extra_info:{}}}function DP(e){let t=0;for(let n of e){let r=n.layout;if(!F(r))continue;let{y:i,h:o}=r;!Uc(i)||!Uc(o)||(t=Math.max(t,i+o))}return t}function LP(e,t,n){let r=ns(t.default_w??t.min_w??6,t.min_w??1,t.max_w??12),i=ns(t.default_h??t.min_h??3,t.min_h??1,t.max_h??99);return{i:n,x:0,y:DP(e),w:ns(r,2,12),h:ns(i,1,99)}}function Zm(e){return{name:Km(e.pluginApiName,e.blockApiName),layout:LP(e.dashlets,e.content,e.layoutId),config:OP({content:e.content,objectId:e.objectId})}}function Xm(e,t){let n=e.config;return{config:{...RP(F(n)?n:{}),content:t}}}function Qm(e){let t=e.config;return F(t)?t.content:void 0}function lr(e){let t=e.config;if(!F(t)||t.chart_type!=="html")return!1;let n=t.content;return F(n)&&n.kind==="custom_code"}function ef(e){return e.dashlets.filter(lr)}function rs(e){let t=Qm(e);return F(t)&&typeof t.name=="string"?t.name:e.name}var cn=e=>typeof e=="string"?e:"";function tf(e){return Array.isArray(e)?e.filter(F).map(t=>({name:cn(t.name),script:cn(t.script)})):F(e)?Object.entries(e).map(([t,n])=>({name:t,script:cn(n)})):[]}function Vc(e){if(Array.isArray(e))return e.map(Vc);if(F(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Vc(e[n]);return t}return e}function nf(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e).trim():""}function BP(e){return Array.isArray(e)?e.filter(F).map(t=>({api_name:cn(t.api_name),name:nf(t.name),type:cn(t.type),script:cn(t.script),html:cn(t.html),css:cn(t.css),event_scripts:tf(t.event_scripts)})):[]}function Kc(e){let t=F(e)?e:{},n=BP(t.views),r={name:nf(t.name),script:typeof t.script=="string"?t.script:"",styles:typeof t.styles=="string"?t.styles:"",event_scripts:tf(t.event_scripts),...Gm(t),...Jm(t),...n.length>0&&{views:n}};return SP("sha256").update(JSON.stringify(Vc(r))).digest("hex")}function rf(e){let{entry:t}=e;if(t?.dashboardId===e.dashboardId){let o=e.dashlets.find(s=>s.id===t.dashletId);if(o&&lr(o))return{kind:"map",dashlet:o,entry:t}}let n=Km(e.pluginApiName,e.blockApiName),r=e.dashlets.filter(o=>o.name===n&&lr(o)),[i]=r;return r.length===1&&i?{kind:"name",dashlet:i}:r.length>1?{kind:"ambiguous",dashlets:r}:{kind:"none"}}function of(e,t){return t?.dashletId!==e.id?!1:Kc(Qm(e))!==t.contentHash}function Wc(e,t){return e.environment===t.environment&&e.businessId===t.businessId&&e.pluginApiName===t.pluginApiName&&e.blockApiName===t.blockApiName}function Gc(e,t){return e.find(n=>Wc(n,t))}function sf(e,t){let n=e.findIndex(r=>Wc(r,t));return n===-1?[...e,t]:e.map((r,i)=>i===n?t:r)}function af(e,t){return e.filter(n=>!Wc(n,t))}function FP(e){if(!F(e))return null;for(let n of NP)if(typeof e[n]!="string")return null;let t=e;return{environment:t.environment,businessId:br(t.businessId),pluginApiName:t.pluginApiName,blockApiName:t.blockApiName,dashboardId:t.dashboardId,dashletId:t.dashletId,contentHash:t.contentHash,pushedAt:t.pushedAt}}var Um=e=>Date.parse(e.pushedAt)||0;function jP(e){let t=new Map;for(let n of e){let r=[n.environment,n.businessId,n.pluginApiName,n.blockApiName].join("\0"),i=t.get(r);(i===void 0||Um(n)>Um(i))&&t.set(r,n)}return[...t.values()]}var Vm=e=>e instanceof Error?e.message:String(e);async function cf(e){let t;try{t=await EP(Hm(e,zn),"utf8")}catch(r){if(tt(r))return[];throw new Error(`Couldn't read ${zn}: ${Vm(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(`${zn} is not valid JSON (${Vm(r)}). Fix it, or delete it to start a fresh push map.`)}if(!Array.isArray(n))throw new Error(`${zn} must contain a JSON array of push entries. Fix it, or delete it to start a fresh push map.`);return jP(n.map(FP).filter(r=>r!==null))}async function lf(e,t){let n=Hm(e,zn);await _P(TP(n),{recursive:!0}),await IP(n,`${JSON.stringify(t,null,2)}
|
|
868
|
+
`,"utf8")}var MP={generic_dashboard:"dashboard",homepage:"homepage",chart_group:"chart_group"},zP={dashboard:"generic_dashboard",homepage:"homepage",chart_group:"chart_group"};function Jc(e){return MP[e]}function uf(e){return zP[e]}function df(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}`}var ff=["min_w","max_w","min_h","max_h"],gf=[["min_w","max_w"],["min_h","max_h"]],is={default_w:["min_w","max_w"],default_h:["min_h","max_h"]},WP=Object.keys(is),hf=[...ts,"host_chrome"],GP=["\0","{__ref:"],qc="views",Yc=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 JP(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 qP(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 i=n.filter(({block:s})=>s.api_name===t),[o]=i;return o?i.length>1?{ok:!1,reason:"ambiguous",available:i.map(({block:s,pluginApiName:a})=>({pluginApiName:a,apiName:s.api_name}))}:{ok:!0,...o}:{ok:!1,reason:"not_found",available:r}}var pf=e=>typeof e=="number"&&Number.isInteger(e)&&e>0,oi=e=>GP.some(t=>e.includes(t));function YP(e){let t=e,{name:n,script:r,styles:i,event_scripts:o}=t;if(typeof r!="string"||!r.trim())return"script";if(n!==void 0&&typeof n!="string")return"name";if(i!==void 0&&typeof i!="string")return"styles";if(o!==void 0){if(!F(o))return"event_scripts";let d=Object.entries(o).find(([u,f])=>typeof f!="string"||oi(u)||oi(f));if(d)return`event_scripts.${d[0]}`}let s=[["name",n],["script",r],["styles",i]].find(([,d])=>typeof d=="string"&&oi(d));if(s)return s[0];let a=ff.find(d=>t[d]!==void 0&&!pf(t[d]));if(a)return a;let c=gf.find(([d,u])=>{let f=t[d],g=t[u];return typeof f=="number"&&typeof g=="number"&&f>g});if(c)return c[0];let l=WP.find(d=>{let u=t[d];if(u===void 0)return!1;if(typeof u!="number"||!pf(u))return!0;let[f,g]=is[d],p=t[f],m=t[g];return typeof p=="number"&&u<p||typeof m=="number"&&u>m});if(l)return l;if(t.host_chrome!==void 0&&typeof t.host_chrome!="boolean")return"host_chrome"}var ZP=["api_name","name","script","html","css"],mf=e=>typeof e!="string"||oi(e);function XP(e){for(let t of e){let n=t,r=typeof n.api_name=="string"?n.api_name:String(n.api_name),i=ZP.find(a=>mf(n[a]));if(i)return{view:r,field:i};let o=n.event_scripts;if(!F(o))return{view:r,field:"event_scripts"};let s=Object.entries(o).find(([a,c])=>oi(a)||mf(c));if(s)return{view:r,field:`event_scripts.${s[0]}`}}}var QP=({view:e,field:t})=>`views.${e}.${t}`,eC=(e,t)=>`Block "${e}" can't carry view ${JSON.stringify(t.view)}: its ${t.field} must be a string without NUL characters or "{__ref:".`,tC=(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=gf.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(ff.includes(t))return`Block "${e}" has an invalid ${t}: it must be a positive integer.`;if(t in is){let[r,i]=is[t];return`Block "${e}" has an invalid ${t}: it must be a positive integer between ${r} and ${i}.`}return`Block "${e}" has an invalid ${t}: it must be a string without NUL characters or "{__ref:".`},nC=({reason:e,available:t},n,r)=>{let i=JP(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: ${i}`:n===void 0?`This plugin has several blocks; pass the api_name of the one to ${r}: ${i}`:`More than one plugin has a block with api_name "${n}": ${i}`},rC=e=>{try{let t=JSON.parse(e);return F(t)?t:void 0}catch{return}},yf=e=>{let t=e.find(o=>o.path===HP),n=t?JSON.parse(t.content):[],r=Array.isArray(n)?n:[n],i=new Map;for(let o of r)F(o)&&typeof o.api_name=="string"&&typeof o.entry=="string"&&i.set(o.api_name,o.entry);return i},bf=(e,t)=>{let n=Ai(e);return n===""?t:`${n}/${t}`},wf=(e,t,n)=>{let r=`${bf(t,n)}/`,i=new Set,o=[];for(let s of e){if(!s.path.startsWith(r)||s.path.endsWith(".DS_Store"))continue;let[a,c,...l]=s.path.slice(r.length).split("/");if(a&&(i.add(a),c===VP&&l.length===0)){let d=rC(s.content);d&&o.push([a,d])}}return{directories:i,configs:o}},vf=(e,t)=>typeof e.api_name=="string"&&e.api_name!==""?e.api_name:KP(t),iC=(e,t)=>{let n=new Map;for(let[r,i]of wf(e,t,UP).configs){let o=vf(i,r),s={};for(let a of hf)i[a]!==void 0&&(s[a]=i[a]);n.set(o,s)}return n},oC=(e,t={})=>({...Object.fromEntries(Object.entries(e).filter(([r])=>!hf.includes(r))),...t});function sC(e,t){let n=yf(t);return e.map(r=>{let i=n.get(r.api_name),o=i===void 0?new Map:iC(t,i);return{...r,artifacts:{...r.artifacts,custom_blocks:r.artifacts.custom_blocks.map(s=>oC(s,o.get(s.api_name)))}}})}var kf=(e,t)=>JSON.stringify([String(e),String(t)]),aC=(e,t)=>{let{directories:n,configs:r}=wf(e,t,qc),i=new Map(r),o=new Set;for(let s of n){let a=i.get(s)??{};o.add(kf(vf(a,s),a.name||s))}return o},cC=(e,t)=>e.api_name.localeCompare(t.api_name)||String(e.name).localeCompare(String(t.name)),lC="appbuilder/views-unmatched";function uC(e,t){let n=yf(t),r={},i=[];for(let o of e){let s=n.get(o.api_name),a=s===void 0?new Set:aC(t,s),c=o.artifacts.routable_pages.filter(l=>a.has(kf(l.api_name,l.name))).sort(cC);c.length!==a.size&&s!==void 0&&i.push({rule:lC,severity:"warning",message:`Found ${String(a.size)} ${qc}/ components but matched ${String(c.length)} packaged views; the pushed block carries only the matched ones.`,path:bf(s,qc),pluginApiName:o.api_name}),r[o.api_name]=c}return{views:r,warnings:i}}function dC(e,t){return Object.hasOwn(e,t)?e[t]??[]:[]}function Af(e){return{...e.block,...Hc(e.views)}}async function Zc(e){let{files:t,deployable:n,issues:r}=await Hr(e),i=uC(n,t);return{deployable:sC(n,t),views:i.views,warnings:[...r.filter(o=>o.severity==="warning"),...i.warnings]}}function Xc({deployable:e,views:t,warnings:n},r,i){let o=qP(e,r);if(!o.ok)return{ok:!1,reason:o.reason,message:nC(o,r,i),available:o.available};let s=YP(o.block);if(s!==void 0)return{ok:!1,reason:"invalid_block",message:tC(o.block.api_name,s),available:[],field:s};let a=dC(t,o.pluginApiName),c=XP(a);return c!==void 0?{ok:!1,reason:"invalid_block",message:eC(o.block.api_name,c),available:[],field:QP(c)}:{ok:!0,value:{block:o.block,pluginApiName:o.pluginApiName,views:a,warnings:n}}}async function xf(e,t){let n=Xc(await Zc(e),t,"export");if(!n.ok)throw new Yc(n.reason,n.message,n);return n.value}import{randomUUID as pC}from"crypto";function el(e){return{...Qi(e),packageBlocks:Zc,readPushMap:cf,writePushMap:lf,ensureGitignore:Ze,staleAgentFileWarnings:t=>Yi(t),randomUUID:pC}}var mC=new Set(["owner","admin","edit"]),fC="Chart groups are not listed here; find them with `appbuilder block targets --object <id> --json` and pass --dashboard <id>.",et=me;function gC(e,t){let n=new Set(t.map(r=>r.pluginApiName)).size>1;return t.map(({pluginApiName:r,apiName:i})=>{let o=e.find(a=>a.api_name===r)?.artifacts.custom_blocks.find(a=>a.api_name===i),s=n?`${r}/${i}`:i;return{value:i,label:`${o?.name??i} (${s})`,args:[i]}})}async function tl(e,t){let n=await t.packageBlocks(t.cwd),r=Xc(n,e,"push");if(!r.ok){let{reason:l,message:d,field:u}=r;return l==="no_blocks"||l==="invalid_block"?et("invalid_block",d,u===void 0?{}:{field:u}):et("needs_choice",d,{choice:"block",choices:gC(n.deployable,r.available)})}let{block:i,pluginApiName:o,views:s,warnings:a}=r.value,c=Ym(i,s);return I({block:i,pluginApiName:o,content:c,contentHash:Kc(c),warnings:a})}var Pf=e=>e==null?null:mC.has(e.toLowerCase());function si(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:Pf(e.employee_access)}}var Cf=e=>({id:e.id,objectName:e.object_name,fetchUrl:e.fetch_url}),hC="Contacts";async function nl(e){let[t,n]=await Promise.all([e.listCustomObjects(),e.getClientObjectId().catch(()=>null)]),r=t.map(Cf).sort((i,o)=>i.objectName.localeCompare(o.objectName));return n!==null&&n!==""&&!r.some(i=>i.id===n)&&r.push({id:n,objectName:hC,fetchUrl:"client"}),r}async function yC(e,t,n){let{environment:r,businessId:i}=t;try{if(n.object!==void 0){let c=n.object,[l,d]=await Promise.all([e.getCustomObject(c).catch(()=>null),e.listDashboards("chart_group",c)]);return I({ok:!0,environment:r,businessId:i,object:l?Cf(l):null,surfaces:{chart_group:d.map(u=>si(u,"chart_group"))}})}let[o,s,a]=await Promise.all([e.listDashboards("generic_dashboard"),e.listDashboards("homepage"),nl(e)]);return I({ok:!0,environment:r,businessId:i,surfaces:{dashboard:o.map(c=>si(c,"dashboard")),homepage:s.map(c=>si(c,"homepage"))},customObjects:a})}catch(o){return Me(o)}}var rl=(e,t)=>t.dashboard===e.id;function ss(e,t){return[...ef(e).filter(r=>rl(e,r)).map(r=>{let i=Wm(r.name);return{value:r.id,label:rs(r),args:["--dashboard",e.id,"--dashlet",r.id],pushKey:i?r.name:null,isFromThisPlugin:i?.pluginApiName===t.pluginApiName}}),{value:"new",label:"Create a new block",args:["--dashboard",e.id,"--create"]}]}var il=(e,t)=>rf({dashboardId:t.id,dashlets:t.dashlets,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name,entry:e.entry}),Sf=(e,t)=>I({dashboard:e,surface:Jc(e.type),action:"create",dashlet:void 0,resolvedBy:t}),os=(e,t,n)=>I({dashboard:e,surface:Jc(e.type),action:"update",dashlet:t,resolvedBy:n});async function bC(e){let[t,n]=await Promise.all([e.client.listDashboards("generic_dashboard"),e.client.listDashboards("homepage")]),r=i=>o=>({value:o.id,label:o.name,args:["--dashboard",o.id],surface:i,canEdit:Pf(o.employee_access)});return et("needs_choice",`Choose where to push; pass --dashboard <id>. ${fC}`,{choice:"dashboard",choices:[...t.map(r("dashboard")),...n.map(r("homepage"))]})}async function wC(e,t,n){let r=await e.client.getDashboard(t);if(n.create)return Sf(r,"flag");let i=()=>ss(r,e.block);if(n.dashlet!==void 0){let s=n.dashlet,a=r.dashlets.find(c=>c.id===s&&rl(r,c));return a?lr(a)?os(r,a,"flag"):et("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.`):et("not_found",`Dashlet ${s} is not on dashboard "${r.name}" (${r.id}).`,{choice:"target",choices:i()})}let o=il(e,r);return o.kind==="map"?os(r,o.dashlet,"push_map"):o.kind==="name"?os(r,o.dashlet,"name"):et("needs_choice",o.kind==="ambiguous"?`Dashboard "${r.name}" has ${String(o.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:i()})}async function vC(e,t,n){let r;try{r=await e.client.getDashboard(t.dashboardId)}catch(o){if(o instanceof q&&o.kind==="not_found")return et("remembered_target_missing",`The remembered dashboard ${t.dashboardId} no longer exists. Pass --dashboard <id> to choose another, or --forget to clear it.`);throw o}if(n.create)return Sf(r,"remembered");let i=r.dashlets.find(o=>o.id===t.dashletId&&rl(r,o));return i&&lr(i)?os(r,i,"remembered"):et("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:ss(r,e.block)})}async function ol(e,t){if(t.dashlet!==void 0&&t.create)return et("usage_error","Pass either --dashlet <id> or --create, not both.");if(t.dashlet!==void 0&&t.dashboard===void 0)return et("usage_error","--dashlet <id> needs --dashboard <id>.");try{return t.dashboard!==void 0?await wC(e,t.dashboard,t):e.entry?await vC(e,e.entry,t):await bC(e)}catch(n){return Me(n)}}async function kC(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:i,fetch_url:o}=r;return typeof o=="string"?{id:i,fetchUrl:o}:{id:i}}if(n!=="chart_group")return{id:r};try{let i=await e.getCustomObject(r);return{id:r,fetchUrl:i.fetch_url}}catch{return{id:r}}}async function sl(e,t,n,r){let{credentials:i,block:o}=e,{dashboard:s,surface:a}=t,c=[],l,d;if(t.action==="update"){let{dashlet:f}=t;if(of(f,e.entry)){let g=`"${rs(f)}" (dashlet ${f.id}) was changed in Kizen since the last push.`;if(!n.force)return et("drift_detected",`${g} Pushing would overwrite those changes; pass --force to overwrite them.`);c.push(`${g} Overwriting it because of --force.`)}l={action:"update",method:"PATCH",path:Ar(s.id,f.id),body:Xm(f,o.content),dashletId:f.id},d=`Update "${rs(f)}" (dashlet ${f.id})`}else l={action:"create",method:"POST",path:Ar(s.id),body:Zm({pluginApiName:o.pluginApiName,blockApiName:o.block.api_name,content:o.content,dashlets:s.dashlets,objectId:r.randomUUID(),layoutId:r.randomUUID()}),dashletId:null},d=`Create a new block on "${s.name}"`;let u=df({appBaseUrl:jl[i.environment],surface:a,dashboardId:s.id,customObject:await kC(e.client,s,a)});return I({...l,dashboard:{id:s.id,name:s.name,type:a},url:u,resolvedBy:t.resolvedBy,warnings:c,summary:{environment:i.environment,businessId:i.businessId,isProduction:Kn(i.environment),surface:a,dashboardId:s.id,dashboardName:s.name,action:t.action,actionLine:d,dashletId:l.dashletId,blockName:o.block.name,blockApiName:o.block.api_name,pluginApiName:o.pluginApiName,scriptBytes:Buffer.byteLength(o.content.script,"utf8"),stylesBytes:Buffer.byteLength(o.content.styles,"utf8"),...o.content.views&&{viewsBytes:Buffer.byteLength(JSON.stringify(o.content.views),"utf8")}}})}var al=e=>({environment:e.credentials.environment,businessId:e.credentials.businessId,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name});async function cl(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 et("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 Me(a)}let i=[...t.warnings],o={...al(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,sf(e.pushMap,o)),s=!0}catch(a){i.push(`The push succeeded, but ${zn} couldn't be written, so this target isn't remembered: ${je(a)}`)}return I({dashletId:r,remembered:s,warnings:i})}var AC=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ll(e){return AC.test(e)?{dashboardId:e,script:`await window.__kizenCustomBlocks?.refresh('${e}')`}:null}async function xC(e,t){let n=al(e);if(!Gc(e.pushMap,n))return null;let r=af(e.pushMap,n);return await t.writePushMap(t.cwd,r),r}async function ul(e,t){let{client:n,credentials:r,block:i}=e,o=await t.readPushMap(t.cwd),s=!1;if(e.forget&&e.isAborted?.()!==!0){let a=await xC({credentials:r,block:i,pushMap:o},t);a&&(o=a,s=!0)}return{context:{client:n,credentials:r,block:i,pushMap:o,entry:Gc(o,al({credentials:r,block:i}))},forgotten:s}}function ai(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 PC=e=>`${e.path===void 0?"":`${e.path}: `}${e.message} (${e.rule})`;async function CC(e){try{return await e.staleAgentFileWarnings(e.cwd)}catch{return[]}}async function _f(e,t,n){let r={json:t.json===!0,deps:n},i="appbuilder block push",o=e===void 0?[]:[e],s=Rn(t,n.processEnv),a=(d,u)=>u==="environment"?[...o,...d.args,...rn(t,n.processEnv)]:u==="block"?[...d.args,...s]:[...o,...s,...d.args],c=(d,u)=>Tt(i,a(d,u),r),l=d=>{Nt(r,d,c)};try{let d=await Nn(t,n);if(!d.ok){l(d);return}let{credentials:u,client:f,notices:g}=d.value;s=to(t,u),ze(n,g);let p=await tl(e,n);if(!p.ok){l(p);return}let m=p.value;o=[m.block.api_name],m.warnings.length>0&&n.writeStderr(`${We(m.warnings)}
|
|
869
|
+
`);let{context:h,forgotten:b}=await ul({client:f,credentials:u,block:m,forget:t.forget===!0},n);b&&n.writeStderr(`Forgot the remembered target for ${m.block.api_name}.
|
|
870
|
+
`);let y=await ol(h,t);if(!y.ok){l(y);return}let C=Ye(t,u.environment);if(!C.ok){l(C);return}let S=await sl(h,y.value,t,n);if(!S.ok){l(S);return}let x=S.value,v={pluginApiName:m.pluginApiName,apiName:m.block.api_name,name:m.block.name},k={environment:u.environment,businessId:u.businessId,dashboard:x.dashboard},P=[...m.warnings.map(PC),...await CC(n)],w=C.value;if(w.kind==="dry-run"){let V=[...P,...x.warnings],X=x.summary.isProduction,ve=Tt(i,[m.block.api_name,...s,"--dashboard",x.dashboard.id,...x.action==="update"?["--dashlet",x.dashletId]:["--create"],...t.force===!0?["--force"]:[],"--yes",...X?["--allow-production"]:[]],r),Re={ok:!0,applied:!1,dryRun:!0,reason:w.reason,action:x.action,...k,dashletId:x.dashletId,url:x.url,resolvedBy:x.resolvedBy,block:v,method:x.method,path:x.path,body:x.body,warnings:V,...b?{forgotten:!0}:{},applyArgv:ve,requiresProductionConsent:X};Pe(r,Re,[...ai(x.summary),`URL: ${x.url}`,...ee(V),"",`${x.method} ${x.path}`,JSON.stringify(x.body,null,2),""].join(`
|
|
871
|
+
`),[...ai(x.summary),...ee(V),""].join(`
|
|
872
872
|
`)),w.reason==="no_yes"&&n.writeStderr(`${eo}
|
|
873
|
-
`);return}let A=await
|
|
874
|
-
`))}catch(d){l(Me(d))}}var
|
|
873
|
+
`);return}let A=await cl(h,x,n);if(!A.ok){l(A);return}let _=A.value,T=[...P,..._.warnings],L=ll(x.dashboard.id),$={ok:!0,applied:!0,dryRun:!1,action:x.action==="create"?"created":"updated",...k,dashletId:_.dashletId,url:x.url,...L?{refresh:L}:{},resolvedBy:x.resolvedBy,block:v,remembered:_.remembered,warnings:T,...b?{forgotten:!0}:{}};Pe(r,$,[`\u2713 ${$.action==="created"?"Created":"Updated"} ${m.block.name} on "${x.dashboard.name}" (dashlet ${_.dashletId})`,...ai(x.summary),`URL: ${x.url}`,...L?[`Refresh an open tab: ${L.script}`]:[],...ee(T),""].join(`
|
|
874
|
+
`))}catch(d){l(Me(d))}}var SC=(e,t)=>e.padEnd(t);function Qc(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)":""}`]),i=n.map((s,a)=>Math.max(s.length,...r.map(c=>(c[a]??"").length))),o=s=>` ${s.map((a,c)=>SC(a,i[c]??0)).join(" ")}`.trimEnd();return[e,o(n),...r.map(o)]}function _C(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})`,"",...Qc("Chart groups",e.surfaces.chart_group)):t.push(...Qc("Dashboards",e.surfaces.dashboard),"",...Qc("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(`
|
|
875
875
|
`)}
|
|
876
|
-
`}async function
|
|
877
|
-
`:wC(u.value))}catch(a){s(Me(a))}}import{useEffect as vC,useState as as}from"react";import{Box as ln,Text as at}from"ink";import{Fragment as EC,jsx as ce,jsxs as Ue}from"react/jsx-runtime";var Sf=[{key:"dashboard",label:"Dashboard"},{key:"homepage",label:"Homepage"},{key:"chart_group",label:"Chart group"}],kC={dashboard:"dashboard",homepage:"homepage",chart_group:"chart group"},ul="\u2191/\u2193 to move, Enter to select, Esc to go back",AC="The block was edited in Kizen since your last push. Overwriting discards those edits.",cs=e=>e.args.includes("--create");function _f(e,t){let n=e.filter(o=>o.value===t),r=e.filter(cs),i=e.filter(o=>o.value!==t&&!cs(o));return n.length>0?[...n,...i,...r]:[...r,...i]}function xC(e,t){if(cs(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 PC(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 CC(e,t,n){let r={...e,dashboard:t};return delete r.dashlet,delete r.create,cs(n)?{...r,create:!0}:{...r,dashlet:n.value}}function SC(e,t,n,r){let i=Mo({deps:t,setPhase:n,setSession:r,next:(p,h)=>g(p,h,e)}),{fail:o,guard:s}=i,a=i.whileRunning(n),c=i.whileRunning(r),l=async(p,h)=>{if(i.isAborted())return;a({type:"applying",plan:h});let b=await al(p,h,t);if(!b.ok){o(b);return}a({type:"done",plan:h,applied:b.value})},d=async(p,h,b)=>{a({type:"loading",label:"Preparing the push\u2026"});let y=await ol(p,h,b,t);if(!y.ok){if(y.code==="drift_detected"){a({type:"confirm",kind:"drift",message:y.message,target:h,options:b,context:p});return}o(y);return}switch(zo(b,p.credentials.environment)){case"dry-run":a({type:"done",plan:y.value,applied:null});return;case"apply":await l(p,y.value);return;case"confirm":a({type:"confirm",kind:"push",plan:y.value,options:b,context:p})}},u=async(p,h,b)=>{a({type:"loading",label:"Resolving the target\u2026"});let y=await il(p,h);if(y.ok){await d(p,y.value,h);return}let C=h.dashboard??p.entry?.dashboardId;if((y.code==="needs_choice"&&y.choice==="target"||y.code==="remembered_target_missing")&&y.choices&&y.choices.length>0&&C!==void 0){a({type:"target-select",dashboardId:C,title:"Choose a block to update, or create a new one",message:y.message,choices:_f(y.choices,null),matchedId:null,back:b,options:h,context:p});return}o(y)},f=async(p,{credentials:h,client:b},y)=>{if(i.isAborted())return;let{context:C,forgotten:S}=await ll({client:b,credentials:h,block:y,forget:p.forget===!0,isAborted:i.isAborted},t);if(S&&c(x=>({...x,notices:[...x.notices,`Forgot the remembered target for ${y.block.api_name}.`]})),p.dashboard!==void 0||C.entry){await u(C,p,null);return}a({type:"surface-select",options:p,context:C})},g=async(p,h,b)=>{a({type:"packaging"});let y=await el(b,t);if(!y.ok){if(y.choice==="block"&&y.choices){a({type:"block-select",options:p,resolved:h,choices:y.choices});return}o(y);return}c(C=>({...C,warnings:y.value.warnings})),await f(p,h,y.value)},m=async({options:p,context:h},b,y,C)=>{let S=kC[b];a({type:"loading",label:`Loading ${S}s\u2026`});let v=(await h.client.listDashboards(af(b),y?.id)).map(w=>si(w,b)),{environment:k,businessId:P}=h.credentials;if(v.length===0){o({message:`No ${S}s found${y?` on ${y.objectName}`:""} for business ${P} (${k}).`});return}a({type:"dashboard-select",surface:b,objectId:y?.id??null,title:y?`Choose a chart group on ${y.objectName}`:`Choose a ${S}`,rows:v,back:C,options:p,context:h})};return{start:p=>{s(()=>i.load(p))},pickEnvironment:(p,h)=>{s(()=>i.pickEnvironment(p,h))},pickBlock:(p,h)=>{s(()=>g(p.options,p.resolved,h.value))},pickSurface:(p,h)=>{s(async()=>{if(h!=="chart_group"){await m(p,h,null,p);return}a({type:"loading",label:"Loading custom objects\u2026"});let b=await tl(p.context.client);if(b.length===0){o({message:"No custom objects found, so there are no chart groups to push to."});return}a({type:"object-select",objects:b,back:p,options:p.options,context:p.context})})},pickObject:(p,h)=>{s(()=>m(p,"chart_group",h,p))},pickDashboard:(p,h)=>{s(async()=>{let{context:b}=p,y={...p.options,dashboard:h.id};if(y.dashlet!==void 0||y.create){await u(b,y,p);return}a({type:"loading",label:`Loading "${h.name}"\u2026`});let C=await b.client.getDashboard(h.id),S=rl(b,C),x=S.kind==="map"||S.kind==="name"?S.dashlet.id:null;a({type:"target-select",dashboardId:C.id,title:`Choose what to push to on "${C.name}"`,message:null,choices:_f(ss(C,b.block),x),matchedId:x,back:p,options:y,context:b})})},pickTarget:(p,h)=>{s(()=>u(p.context,CC(p.options,p.dashboardId,h),p))},acceptDrift:p=>{s(()=>d(p.context,p.target,{...p.options,force:!0}))},acceptPush:p=>{s(()=>l(p.context,p.plan))},cancel:()=>{o({message:"Cancelled."})},abort:i.abort}}var Ef=({plan:e})=>Ue(ln,{flexDirection:"column",children:[ce(Ne,{lines:ai(e.summary)}),Ue(at,{children:["URL: ",e.url]})]}),_C=({plan:e,applied:t})=>{let n=cl(e.dashboard.id);return t===null?Ue(ln,{flexDirection:"column",gap:1,children:[ce(at,{color:"yellow",children:jo}),ce(Ef,{plan:e}),e.warnings.length>0&&ce(Ne,{lines:Q(e.warnings),color:"yellow"}),Ue(ln,{flexDirection:"column",children:[Ue(at,{bold:!0,children:[e.method," ",e.path]}),ce(at,{children:JSON.stringify(e.body,null,2)})]})]}):Ue(ln,{flexDirection:"column",gap:1,children:[Ue(ln,{gap:1,children:[ce(at,{color:"green",children:"\u2713"}),Ue(at,{bold:!0,children:[e.action==="create"?"Created":"Updated"," ",e.summary.blockName,' on "',e.dashboard.name,'"']})]}),Ue(ln,{flexDirection:"column",children:[Ue(at,{children:["URL: ",e.url]}),n&&Ue(at,{dimColor:!0,children:["Refresh an open tab: ",n.script]})]}),t.warnings.length>0&&ce(Ne,{lines:Q(t.warnings),color:"yellow"})]})},If=({apiName:e,options:t,deps:n})=>{let[r,i]=as({type:"loading",label:ni}),[o,s]=as(Fo),[a]=as(()=>SC(e,n,i,s)),[c]=as(t);vC(()=>{a.start(c)},[a,c]),Zo(r.type==="done"||r.type==="error",n.setExitCode,a.abort);let l=d=>ce(Yo,{session:o,children:d});switch(r.type){case"loading":return l(ce(cr,{label:r.label}));case"packaging":return l(ce(cr,{label:"Packaging blocks\u2026"}));case"applying":return l(ce(cr,{label:`Pushing ${r.plan.summary.blockName} to "${r.plan.dashboard.name}"\u2026`}));case"environment-select":return l(ce(sr,{title:"Environment",choices:r.choices,onPick:d=>{a.pickEnvironment(r,d)},onCancel:a.cancel},"environment"));case"block-select":return l(ce(sr,{title:"Block to push",choices:r.choices,onPick:d=>{a.pickBlock(r,d)},onCancel:a.cancel},"block"));case"surface-select":return l(ce(Lt,{title:"Where should the block go?",items:Sf,onSelect:or(Sf,d=>{a.pickSurface(r,d.key)}),onCancel:a.cancel},"surface"));case"object-select":return l(ce(Lt,{title:"Custom object",items:r.objects.map(d=>({key:d.id,label:d.objectName})),onSelect:or(r.objects,d=>{a.pickObject(r,d)}),onCancel:()=>{i(r.back)},hint:ul},"object"));case"dashboard-select":return l(ce(Lt,{title:r.title,items:r.rows.map(PC),onSelect:or(r.rows,d=>{a.pickDashboard(r,d)}),onCancel:()=>{i(r.back)},hint:ul},`dashboards-${r.surface}-${r.objectId??""}`));case"target-select":{let{back:d}=r;return l(Ue(EC,{children:[r.message!==null&&ce(at,{color:"yellow",children:r.message}),ce(Lt,{title:r.title,items:r.choices.map(u=>xC(u,r.matchedId)),onSelect:or(r.choices,u=>{a.pickTarget(r,u)}),onCancel:d?()=>{i(d)}:a.cancel,...d&&{hint:ul}},`targets-${r.dashboardId}`)]}))}case"confirm":return r.kind==="drift"?l(Ue(ln,{flexDirection:"column",gap:1,children:[ce(at,{color:"yellow",children:AC}),ce(at,{dimColor:!0,children:r.message}),ce(Rc,{prompt:"Type y to overwrite (y/N)",strict:!0,onAccept:()=>{a.acceptDrift(r)},onCancel:a.cancel},"drift")]})):l(Ue(ln,{flexDirection:"column",gap:1,children:[ce(Ef,{plan:r.plan}),r.plan.warnings.length>0&&ce(Ne,{lines:Q(r.plan.warnings),color:"yellow"}),ce(Ho,{isProduction:r.plan.summary.isProduction,prompt:"Push? (Y/n)",productionPrompt:"Type y to push to production (y/N)",onAccept:()=>{a.acceptPush(r)},onCancel:a.cancel},"push")]}));case"done":return l(ce(_C,{plan:r.plan,applied:r.applied}));case"error":return l(ce(Jo,{view:r.view}))}};var Nf=e=>`Error: ${e instanceof Error?e.message:String(e)}`,RC=e=>e instanceof NC?We(e.issues):Nf(e),Tf=e=>{console.error(Nf(e)),process.exitCode=1};function Rf(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 i=await vf(process.cwd(),n),{block:o,warnings:s}=i;s.length>0&&console.error(We(s));let a=JSON.stringify(wf(i),null,2);console.log(a),r.copy&&console.error(await es(a)?`Copied block "${o.api_name}" to the clipboard.`:"Couldn't copy to the clipboard; use the JSON printed to stdout instead.")}catch(i){console.error(RC(i)),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("--no-interactive",mt).option("--env <env>","environment of the `appbuilder login` session to use").option("--business <id-or-name>","use this saved account, by business id or name (ignoring case), instead of the current one (default: $APPBUILDER_BUSINESS)").option("--user <userId>","with --business, use the saved account of this user id (default: $APPBUILDER_USER)").action(async(n,r)=>{try{let i=Qc(process.cwd()),{noInteractive:o,options:s}=Ae(r);if(!pt({json:s.json===!0,noInteractive:o})){await Pf(n,s,i);return}let{waitUntilExit:a}=TC(IC(If,{...n!==void 0&&{apiName:n},options:s,deps:i}),{exitOnCtrlC:!1});await a()}catch(i){Tf(i)}}),t.command("targets").description("List the dashboards, homepages and chart groups a block can be pushed to").option("-c, --credentials <path>","path to an API-key credentials JSON file (deprecated; replaces the sign-in session)").option("--profile <name>","stored API-key credential profile to use (deprecated; replaces the sign-in session)").option("--object <id>","list the chart groups of this custom object").option("--json","print a JSON result to stdout").option("--env <env>","environment of the `appbuilder login` session to use").option("--business <id-or-name>","use this saved account, by business id or name (ignoring case), instead of the current one (default: $APPBUILDER_BUSINESS)").option("--user <userId>","with --business, use the saved account of this user id (default: $APPBUILDER_USER)").action(async n=>{try{await Cf(n,Qc(process.cwd()))}catch(r){Tf(r)}})}import{createElement as LC}from"react";import{render as BC}from"ink";import{useEffect as $f,useState as li}from"react";import{Box as ui,Text as ur,useApp as $C}from"ink";import{PluginValidationError as OC}from"@kizenapps/packager";function ci(e){return e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}import{Fragment as DC,jsx as un,jsxs as Un}from"react/jsx-runtime";var Of=["creating-dir","reading-files","validating","minifying","packaging","writing-bundle"],ls={"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"},Df=({outputDir:e,pluginDir:t})=>{let n=$C(),[r,i]=li("creating-dir"),[o,s]=li(!1),[a,c]=li(null),[l,d]=li(null),[u,f]=li(null);$f(()=>{io(t,e,i).then(({bundleSize:p})=>{f(p),i("done")}).catch(p=>{p instanceof OC?c(p.issues):d(p instanceof Error?p.message:String(p)),s(!0),process.exitCode=1})},[e,t]),$f(()=>{(r==="done"||o)&&n.exit()},[r,o,n]);let g=Of.indexOf(r),m=r==="done";return Un(ui,{flexDirection:"column",paddingY:1,paddingX:2,children:[un(ye,{marginBottom:1}),Un(ui,{flexDirection:"column",gap:0,children:[Of.map((p,h)=>{let b=r===p,y=m||g>h;return un(ui,{gap:1,children:o&&h===g?Un(ur,{color:"red",children:["\u2717 ",ls[p]]}):y?Un(ur,{color:"green",children:["\u2713 ",ls[p]]}):b?Un(DC,{children:[un(wt,{}),un(ur,{children:ls[p]})]}):Un(ur,{dimColor:!0,children:[" ",ls[p]]})},p)}),m&&u!==null&&un(ui,{marginTop:1,gap:1,children:Un(ur,{color:"green",children:["\u2713 bundle \u2014 ",ci(u)]})}),a!==null&&un(ar,{issues:a}),l!==null&&un(ui,{marginTop:1,borderStyle:"single",borderColor:"red",paddingX:1,children:un(ur,{color:"red",children:l})})]})]})};function Lf(e){e.command("build").description("Bundle the plugin app into .kizenapp directory").action(async()=>{let t=process.cwd(),n=`${t}/.kizenapp`;Ze(t);let{waitUntilExit:r}=BC(LC(Df,{outputDir:n,pluginDir:t}));await r()})}import{createElement as IS}from"react";import{render as TS}from"ink";import{useCallback as ys,useState as dr}from"react";import{Box as de,Text as K,useApp as xS,useInput as PS}from"ink";import{join as bs}from"path";import{access as wS,mkdir as ps,writeFile as gl}from"fs/promises";import{dirname as vS,join as Bt}from"path";var Bf=`{
|
|
876
|
+
`}async function Ef(e,t){let n={json:e.json===!0,deps:t},r="appbuilder block targets",i=e.object===void 0?[]:["--object",e.object],o=a=>Tt(r,[...a.args,...rn(e,t.processEnv),...i],n),s=a=>{Nt(n,a,o)};try{let a=await Nn(e,t);if(!a.ok){s(a);return}let{credentials:c,client:l,notices:d}=a.value;ze(t,d);let u=await yC(l,c,e.object===void 0?{}:{object:e.object});if(!u.ok){s(u);return}t.writeStdout(n.json?`${JSON.stringify(u.value,null,2)}
|
|
877
|
+
`:_C(u.value))}catch(a){s(Me(a))}}import{useEffect as EC,useState as as}from"react";import{Box as ln,Text as ct}from"ink";import{Fragment as LC,jsx as ce,jsxs as Ue}from"react/jsx-runtime";var If=[{key:"dashboard",label:"Dashboard"},{key:"homepage",label:"Homepage"},{key:"chart_group",label:"Chart group"}],IC={dashboard:"dashboard",homepage:"homepage",chart_group:"chart group"},dl="\u2191/\u2193 to move, Enter to select, Esc to go back",TC="The block was edited in Kizen since your last push. Overwriting discards those edits.",cs=e=>e.args.includes("--create");function Tf(e,t){let n=e.filter(o=>o.value===t),r=e.filter(cs),i=e.filter(o=>o.value!==t&&!cs(o));return n.length>0?[...n,...i,...r]:[...r,...i]}function NC(e,t){if(cs(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 RC(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 $C(e,t,n){let r={...e,dashboard:t};return delete r.dashlet,delete r.create,cs(n)?{...r,create:!0}:{...r,dashlet:n.value}}function OC(e,t,n,r){let i=Mo({deps:t,setPhase:n,setSession:r,next:(m,h)=>g(m,h,e)}),{fail:o,guard:s}=i,a=i.whileRunning(n),c=i.whileRunning(r),l=async(m,h)=>{if(i.isAborted())return;a({type:"applying",plan:h});let b=await cl(m,h,t);if(!b.ok){o(b);return}a({type:"done",plan:h,applied:b.value})},d=async(m,h,b)=>{a({type:"loading",label:"Preparing the push\u2026"});let y=await sl(m,h,b,t);if(!y.ok){if(y.code==="drift_detected"){a({type:"confirm",kind:"drift",message:y.message,target:h,options:b,context:m});return}o(y);return}switch(zo(b,m.credentials.environment)){case"dry-run":a({type:"done",plan:y.value,applied:null});return;case"apply":await l(m,y.value);return;case"confirm":a({type:"confirm",kind:"push",plan:y.value,options:b,context:m})}},u=async(m,h,b)=>{a({type:"loading",label:"Resolving the target\u2026"});let y=await ol(m,h);if(y.ok){await d(m,y.value,h);return}let C=h.dashboard??m.entry?.dashboardId;if((y.code==="needs_choice"&&y.choice==="target"||y.code==="remembered_target_missing")&&y.choices&&y.choices.length>0&&C!==void 0){a({type:"target-select",dashboardId:C,title:"Choose a block to update, or create a new one",message:y.message,choices:Tf(y.choices,null),matchedId:null,back:b,options:h,context:m});return}o(y)},f=async(m,{credentials:h,client:b},y)=>{if(i.isAborted())return;let{context:C,forgotten:S}=await ul({client:b,credentials:h,block:y,forget:m.forget===!0,isAborted:i.isAborted},t);if(S&&c(x=>({...x,notices:[...x.notices,`Forgot the remembered target for ${y.block.api_name}.`]})),m.dashboard!==void 0||C.entry){await u(C,m,null);return}a({type:"surface-select",options:m,context:C})},g=async(m,h,b)=>{a({type:"packaging"});let y=await tl(b,t);if(!y.ok){if(y.choice==="block"&&y.choices){a({type:"block-select",options:m,resolved:h,choices:y.choices});return}o(y);return}c(C=>({...C,warnings:y.value.warnings})),await f(m,h,y.value)},p=async({options:m,context:h},b,y,C)=>{let S=IC[b];a({type:"loading",label:`Loading ${S}s\u2026`});let v=(await h.client.listDashboards(uf(b),y?.id)).map(w=>si(w,b)),{environment:k,businessId:P}=h.credentials;if(v.length===0){o({message:`No ${S}s found${y?` on ${y.objectName}`:""} for business ${P} (${k}).`});return}a({type:"dashboard-select",surface:b,objectId:y?.id??null,title:y?`Choose a chart group on ${y.objectName}`:`Choose a ${S}`,rows:v,back:C,options:m,context:h})};return{start:m=>{s(()=>i.load(m))},pickEnvironment:(m,h)=>{s(()=>i.pickEnvironment(m,h))},pickBlock:(m,h)=>{s(()=>g(m.options,m.resolved,h.value))},pickSurface:(m,h)=>{s(async()=>{if(h!=="chart_group"){await p(m,h,null,m);return}a({type:"loading",label:"Loading custom objects\u2026"});let b=await nl(m.context.client);if(b.length===0){o({message:"No custom objects found, so there are no chart groups to push to."});return}a({type:"object-select",objects:b,back:m,options:m.options,context:m.context})})},pickObject:(m,h)=>{s(()=>p(m,"chart_group",h,m))},pickDashboard:(m,h)=>{s(async()=>{let{context:b}=m,y={...m.options,dashboard:h.id};if(y.dashlet!==void 0||y.create){await u(b,y,m);return}a({type:"loading",label:`Loading "${h.name}"\u2026`});let C=await b.client.getDashboard(h.id),S=il(b,C),x=S.kind==="map"||S.kind==="name"?S.dashlet.id:null;a({type:"target-select",dashboardId:C.id,title:`Choose what to push to on "${C.name}"`,message:null,choices:Tf(ss(C,b.block),x),matchedId:x,back:m,options:y,context:b})})},pickTarget:(m,h)=>{s(()=>u(m.context,$C(m.options,m.dashboardId,h),m))},acceptDrift:m=>{s(()=>d(m.context,m.target,{...m.options,force:!0}))},acceptPush:m=>{s(()=>l(m.context,m.plan))},cancel:()=>{o({message:"Cancelled."})},abort:i.abort}}var Nf=({plan:e})=>Ue(ln,{flexDirection:"column",children:[ce(Ne,{lines:ai(e.summary)}),Ue(ct,{children:["URL: ",e.url]})]}),DC=({plan:e,applied:t})=>{let n=ll(e.dashboard.id);return t===null?Ue(ln,{flexDirection:"column",gap:1,children:[ce(ct,{color:"yellow",children:jo}),ce(Nf,{plan:e}),e.warnings.length>0&&ce(Ne,{lines:ee(e.warnings),color:"yellow"}),Ue(ln,{flexDirection:"column",children:[Ue(ct,{bold:!0,children:[e.method," ",e.path]}),ce(ct,{children:JSON.stringify(e.body,null,2)})]})]}):Ue(ln,{flexDirection:"column",gap:1,children:[Ue(ln,{gap:1,children:[ce(ct,{color:"green",children:"\u2713"}),Ue(ct,{bold:!0,children:[e.action==="create"?"Created":"Updated"," ",e.summary.blockName,' on "',e.dashboard.name,'"']})]}),Ue(ln,{flexDirection:"column",children:[Ue(ct,{children:["URL: ",e.url]}),n&&Ue(ct,{dimColor:!0,children:["Refresh an open tab: ",n.script]})]}),t.warnings.length>0&&ce(Ne,{lines:ee(t.warnings),color:"yellow"})]})},Rf=({apiName:e,options:t,deps:n})=>{let[r,i]=as({type:"loading",label:ni}),[o,s]=as(Fo),[a]=as(()=>OC(e,n,i,s)),[c]=as(t);EC(()=>{a.start(c)},[a,c]),Zo(r.type==="done"||r.type==="error",n.setExitCode,a.abort);let l=d=>ce(Yo,{session:o,children:d});switch(r.type){case"loading":return l(ce(cr,{label:r.label}));case"packaging":return l(ce(cr,{label:"Packaging blocks\u2026"}));case"applying":return l(ce(cr,{label:`Pushing ${r.plan.summary.blockName} to "${r.plan.dashboard.name}"\u2026`}));case"environment-select":return l(ce(sr,{title:"Environment",choices:r.choices,onPick:d=>{a.pickEnvironment(r,d)},onCancel:a.cancel},"environment"));case"block-select":return l(ce(sr,{title:"Block to push",choices:r.choices,onPick:d=>{a.pickBlock(r,d)},onCancel:a.cancel},"block"));case"surface-select":return l(ce(Ft,{title:"Where should the block go?",items:If,onSelect:or(If,d=>{a.pickSurface(r,d.key)}),onCancel:a.cancel},"surface"));case"object-select":return l(ce(Ft,{title:"Custom object",items:r.objects.map(d=>({key:d.id,label:d.objectName})),onSelect:or(r.objects,d=>{a.pickObject(r,d)}),onCancel:()=>{i(r.back)},hint:dl},"object"));case"dashboard-select":return l(ce(Ft,{title:r.title,items:r.rows.map(RC),onSelect:or(r.rows,d=>{a.pickDashboard(r,d)}),onCancel:()=>{i(r.back)},hint:dl},`dashboards-${r.surface}-${r.objectId??""}`));case"target-select":{let{back:d}=r;return l(Ue(LC,{children:[r.message!==null&&ce(ct,{color:"yellow",children:r.message}),ce(Ft,{title:r.title,items:r.choices.map(u=>NC(u,r.matchedId)),onSelect:or(r.choices,u=>{a.pickTarget(r,u)}),onCancel:d?()=>{i(d)}:a.cancel,...d&&{hint:dl}},`targets-${r.dashboardId}`)]}))}case"confirm":return r.kind==="drift"?l(Ue(ln,{flexDirection:"column",gap:1,children:[ce(ct,{color:"yellow",children:TC}),ce(ct,{dimColor:!0,children:r.message}),ce($c,{prompt:"Type y to overwrite (y/N)",strict:!0,onAccept:()=>{a.acceptDrift(r)},onCancel:a.cancel},"drift")]})):l(Ue(ln,{flexDirection:"column",gap:1,children:[ce(Nf,{plan:r.plan}),r.plan.warnings.length>0&&ce(Ne,{lines:ee(r.plan.warnings),color:"yellow"}),ce(Ho,{isProduction:r.plan.summary.isProduction,prompt:"Push? (Y/n)",productionPrompt:"Type y to push to production (y/N)",onAccept:()=>{a.acceptPush(r)},onCancel:a.cancel},"push")]}));case"done":return l(ce(DC,{plan:r.plan,applied:r.applied}));case"error":return l(ce(Jo,{view:r.view}))}};var Of=e=>`Error: ${e instanceof Error?e.message:String(e)}`,MC=e=>e instanceof jC?We(e.issues):Of(e),$f=e=>{console.error(Of(e)),process.exitCode=1};function Df(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 i=await xf(process.cwd(),n),{block:o,warnings:s}=i;s.length>0&&console.error(We(s));let a=JSON.stringify(Af(i),null,2);console.log(a),r.copy&&console.error(await es(a)?`Copied block "${o.api_name}" to the clipboard.`:"Couldn't copy to the clipboard; use the JSON printed to stdout instead.")}catch(i){console.error(MC(i)),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("--no-interactive",gt).option("--env <env>","environment of the `appbuilder login` session to use").option("--business <id-or-name>","use this saved account, by business id or name (ignoring case), instead of the current one (default: $APPBUILDER_BUSINESS)").option("--user <userId>","with --business, use the saved account of this user id (default: $APPBUILDER_USER)").action(async(n,r)=>{try{let i=el(process.cwd()),{noInteractive:o,options:s}=Ae(r);if(!ft({json:s.json===!0,noInteractive:o})){await _f(n,s,i);return}let{waitUntilExit:a}=FC(BC(Rf,{...n!==void 0&&{apiName:n},options:s,deps:i}),{exitOnCtrlC:!1});await a()}catch(i){$f(i)}}),t.command("targets").description("List the dashboards, homepages and chart groups a block can be pushed to").option("-c, --credentials <path>","path to an API-key credentials JSON file (deprecated; replaces the sign-in session)").option("--profile <name>","stored API-key credential profile to use (deprecated; replaces the sign-in session)").option("--object <id>","list the chart groups of this custom object").option("--json","print a JSON result to stdout").option("--env <env>","environment of the `appbuilder login` session to use").option("--business <id-or-name>","use this saved account, by business id or name (ignoring case), instead of the current one (default: $APPBUILDER_BUSINESS)").option("--user <userId>","with --business, use the saved account of this user id (default: $APPBUILDER_USER)").action(async n=>{try{await Ef(n,el(process.cwd()))}catch(r){$f(r)}})}import{createElement as HC}from"react";import{render as KC}from"ink";import{useEffect as Lf,useState as li}from"react";import{Box as ui,Text as ur,useApp as zC}from"ink";import{PluginValidationError as UC}from"@kizenapps/packager";function ci(e){return e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}import{Fragment as VC,jsx as un,jsxs as Un}from"react/jsx-runtime";var Bf=["creating-dir","reading-files","validating","minifying","packaging","writing-bundle"],ls={"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"},Ff=({outputDir:e,pluginDir:t})=>{let n=zC(),[r,i]=li("creating-dir"),[o,s]=li(!1),[a,c]=li(null),[l,d]=li(null),[u,f]=li(null);Lf(()=>{io(t,e,i).then(({bundleSize:m})=>{f(m),i("done")}).catch(m=>{m instanceof UC?c(m.issues):d(m instanceof Error?m.message:String(m)),s(!0),process.exitCode=1})},[e,t]),Lf(()=>{(r==="done"||o)&&n.exit()},[r,o,n]);let g=Bf.indexOf(r),p=r==="done";return Un(ui,{flexDirection:"column",paddingY:1,paddingX:2,children:[un(ye,{marginBottom:1}),Un(ui,{flexDirection:"column",gap:0,children:[Bf.map((m,h)=>{let b=r===m,y=p||g>h;return un(ui,{gap:1,children:o&&h===g?Un(ur,{color:"red",children:["\u2717 ",ls[m]]}):y?Un(ur,{color:"green",children:["\u2713 ",ls[m]]}):b?Un(VC,{children:[un(kt,{}),un(ur,{children:ls[m]})]}):Un(ur,{dimColor:!0,children:[" ",ls[m]]})},m)}),p&&u!==null&&un(ui,{marginTop:1,gap:1,children:Un(ur,{color:"green",children:["\u2713 bundle \u2014 ",ci(u)]})}),a!==null&&un(ar,{issues:a}),l!==null&&un(ui,{marginTop:1,borderStyle:"single",borderColor:"red",paddingX:1,children:un(ur,{color:"red",children:l})})]})]})};function jf(e){e.command("build").description("Bundle the plugin app into .kizenapp directory").action(async()=>{let t=process.cwd(),n=`${t}/.kizenapp`;Ze(t);let{waitUntilExit:r}=KC(HC(Ff,{outputDir:n,pluginDir:t}));await r()})}import{createElement as BS}from"react";import{render as FS}from"ink";import{useCallback as ys,useState as dr}from"react";import{Box as de,Text as K,useApp as NS,useInput as RS}from"ink";import{join as bs}from"path";import{access as _S,mkdir as ps,writeFile as hl}from"fs/promises";import{dirname as ES,join as jt}from"path";var Mf=`{
|
|
878
878
|
"name": "Hello Frame",
|
|
879
879
|
"api_name": "hello_frame",
|
|
880
880
|
"title": "Hello Frame",
|
|
@@ -883,13 +883,13 @@ export const sumBy = (records, name, valueOf) =>
|
|
|
883
883
|
"height": 320,
|
|
884
884
|
"width": 280
|
|
885
885
|
}
|
|
886
|
-
`;var
|
|
886
|
+
`;var zf=`this.outputUI(\`
|
|
887
887
|
<div class="hello-frame">
|
|
888
888
|
<h2 class="hello-frame__title">Hello from a floating frame</h2>
|
|
889
889
|
<p class="hello-frame__body">Edit src/floatingFrames/helloFrame/script.js to change this.</p>
|
|
890
890
|
</div>
|
|
891
891
|
\`);
|
|
892
|
-
`;var
|
|
892
|
+
`;var Uf=`.hello-frame {
|
|
893
893
|
padding: 16px;
|
|
894
894
|
font-family: system-ui, sans-serif;
|
|
895
895
|
}
|
|
@@ -903,18 +903,18 @@ export const sumBy = (records, name, valueOf) =>
|
|
|
903
903
|
margin: 0;
|
|
904
904
|
color: #555;
|
|
905
905
|
}
|
|
906
|
-
`;var
|
|
906
|
+
`;var Vf=`{
|
|
907
907
|
"name": "Hello Block",
|
|
908
908
|
"api_name": "hello_block",
|
|
909
909
|
"types": ["dashboards"]
|
|
910
910
|
}
|
|
911
|
-
`;var
|
|
911
|
+
`;var Hf=`this.outputUI(\`
|
|
912
912
|
<div class="hello-block">
|
|
913
913
|
<h2 class="hello-block__title">Hello from a block</h2>
|
|
914
914
|
<p class="hello-block__body">Edit src/blocks/helloBlock/script.js to change this.</p>
|
|
915
915
|
</div>
|
|
916
916
|
\`);
|
|
917
|
-
`;var
|
|
917
|
+
`;var Kf=`.hello-block {
|
|
918
918
|
padding: 16px;
|
|
919
919
|
font-family: system-ui, sans-serif;
|
|
920
920
|
background: #f8fafc;
|
|
@@ -930,25 +930,25 @@ export const sumBy = (records, name, valueOf) =>
|
|
|
930
930
|
margin: 0;
|
|
931
931
|
color: #555;
|
|
932
932
|
}
|
|
933
|
-
`;var
|
|
933
|
+
`;var Wf=`{
|
|
934
934
|
"icon": "phone",
|
|
935
935
|
"color": "#0ea5e9",
|
|
936
936
|
"tooltip": "Hello adornment",
|
|
937
937
|
"field_type": "phonenumber"
|
|
938
938
|
}
|
|
939
|
-
`;var
|
|
940
|
-
`;var
|
|
939
|
+
`;var Gf=`this.showToast('Hello from a data adornment.', { variant: 'success' });
|
|
940
|
+
`;var Jf=`{
|
|
941
941
|
"name": "Hello Page",
|
|
942
942
|
"api_name": "hello_page"
|
|
943
943
|
}
|
|
944
|
-
`;var
|
|
944
|
+
`;var qf=`this.outputUI(\`
|
|
945
945
|
<div class="hello-page">
|
|
946
946
|
<p class="hello-page__loading">Loading\u2026</p>
|
|
947
947
|
</div>
|
|
948
948
|
\`);
|
|
949
949
|
|
|
950
950
|
this.runEventScript('greet');
|
|
951
|
-
`;var
|
|
951
|
+
`;var Yf=`.hello-page {
|
|
952
952
|
padding: 24px;
|
|
953
953
|
font-family: system-ui, sans-serif;
|
|
954
954
|
}
|
|
@@ -986,7 +986,7 @@ this.runEventScript('greet');
|
|
|
986
986
|
.hello-page__button:hover {
|
|
987
987
|
background: #cbd5e1;
|
|
988
988
|
}
|
|
989
|
-
`;var
|
|
989
|
+
`;var Zf=`const tone = this.args?.formData?.tone?.[0] ?? 'plain';
|
|
990
990
|
|
|
991
991
|
const greeting = tone === 'cheer' ? 'Hello, and good to see you!' : 'Hello from a routable page.';
|
|
992
992
|
|
|
@@ -1009,32 +1009,32 @@ this.outputUI(\`
|
|
|
1009
1009
|
</div>
|
|
1010
1010
|
</div>
|
|
1011
1011
|
\`);
|
|
1012
|
-
`;var
|
|
1012
|
+
`;var Xf=`{
|
|
1013
1013
|
"api_name": "hello_toolbar_item",
|
|
1014
1014
|
"label": "Hello Toolbar Item",
|
|
1015
1015
|
"icon": "star",
|
|
1016
1016
|
"color": "#0ea5e9"
|
|
1017
1017
|
}
|
|
1018
|
-
`;var
|
|
1019
|
-
`;var
|
|
1018
|
+
`;var Qf=`this.showToast('Hello from a toolbar item.', { variant: 'success' });
|
|
1019
|
+
`;var eg=`{
|
|
1020
1020
|
"api_name": "hello_object_settings_item",
|
|
1021
1021
|
"label": "Hello Object Settings"
|
|
1022
1022
|
}
|
|
1023
|
-
`;var
|
|
1024
|
-
`;var
|
|
1023
|
+
`;var tg=`this.showToast('Hello from an object settings item.', { variant: 'success' });
|
|
1024
|
+
`;var ng=`{
|
|
1025
1025
|
"name": "Hello Action",
|
|
1026
1026
|
"api_name": "hello_action",
|
|
1027
1027
|
"hint_object_name": "client_client"
|
|
1028
1028
|
}
|
|
1029
|
-
`;var
|
|
1030
|
-
`;var Be=["floatingFrame","block","dataAdornment","page","toolbarItem","objectSettingsItem","jsAction"],
|
|
1031
|
-
`,"utf-8"),await ps(Bt(e.targetDir,"src"),{recursive:!0}),await ps(Bt(e.targetDir,"releaseNotes"),{recursive:!0}),await Promise.all([ds(e.targetDir,tg(e.artifacts??[])),ds(e.targetDir,Ki()),ds(e.targetDir,zd(e.includeLib===!0?["src"]:[])),ds(e.targetDir,Ud()),gl(Bt(e.targetDir,...kS.split("/")),rg(e.apiName))]),Ze(e.targetDir)}var pn=["name","apiName","externalLink","description","developerBusinessId"],gs={name:"Name",apiName:"API name",externalLink:"External link",description:"Description",developerBusinessId:"Business ID"},yl=["name","apiName","description"],bl=/^[a-z_][a-z0-9_]+$/,wl="must start with a letter or underscore and contain only lowercase letters, numbers, or underscores (minimum 2 characters)";function hs(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}function og(e){return{name:"",apiName:"",externalLink:"",description:"",developerBusinessId:e}}function sg(e,t){let n=t.trim();if(yl.includes(e)&&!n)return`${gs[e]} is required`;if(e==="apiName"&&!bl.test(n))return`${gs[e]} ${wl}`}function ag(e,t){return e==="description"?t:t.trim()}function cg(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),Be.filter(r=>n.has(r))}import{jsx as U,jsxs as ee}from"react/jsx-runtime";var Vn=({text:e})=>U(K,{dimColor:!0,children:e}),lg=({parentDir:e,defaultBusinessId:t,defaultEnvironment:n,includeLib:r=!1})=>{let i=xS(),[o,s]=dr({type:"target-select",cursor:0}),[a,c]=dr("in-place"),[l,d]=dr(()=>og(t)),[u,f]=dr(()=>[...Be]),[g,m]=dr(""),[p,h]=dr(e),b=ys((x,v)=>{c(x),m(v.name),s({type:"field-entry",field:0,values:v})},[]),y=ys(async x=>{let v=await dn(x);if(v!=="ok"){s({type:"precheck-error",targetDir:x,reason:v});return}h(x),b("in-place",l)},[l,b]),C=ys(async(x,v)=>{try{let k=await ig(e,x.apiName);h(k),s({type:"confirm",values:x,artifacts:v})}catch(k){s({type:"error",message:k instanceof Error?k.message:String(k)})}},[e]),S=ys(async(x,v,k)=>{try{await fs({targetDir:v,name:x.name,apiName:x.apiName,externalLink:x.externalLink,description:x.description,developerBusinessId:x.developerBusinessId,developerEnvironment:n,artifacts:k,includeLib:r}),s({type:"done",targetDir:v})}catch(P){s({type:"error",message:P instanceof Error?P.message:String(P)})}},[n,r]);if(PS((x,v)=>{if(v.ctrl&&x==="c"){i.exit();return}if(o.type==="target-select"){v.upArrow?s({type:"target-select",cursor:0}):v.downArrow?s({type:"target-select",cursor:1}):v.return?o.cursor===0?y(e):b("sub-dir",l):v.escape&&i.exit();return}if(o.type==="precheck-error"){(v.return||v.escape)&&i.exit();return}if(o.type==="field-entry"){let{field:k,values:P}=o,w=pn[k];if(!w)return;if(v.escape){i.exit();return}if(v.backspace||v.delete){m(A=>A.slice(0,-1));return}if(v.upArrow&&k>0){let A={...P,[w]:g},_=k-1,T=pn[_];s({type:"field-entry",field:_,values:A}),d(A),m(T?A[T]:"");return}if(v.return||v.tab||v.downArrow){let A=sg(w,g);if(A!==void 0){s({type:"field-entry",field:k,values:P,fieldError:A});return}let _=ag(w,g),T={...P,[w]:_};d(T);let L=k+1;if(L>=pn.length)m(""),s({type:"artifact-select",values:T,cursor:0,selected:u});else{let $=pn[L],V=$?T[$]:"",X=$==="apiName"&&!V?hs(T.name):V;s({type:"field-entry",field:L,values:T}),m(X)}return}x&&!v.ctrl&&!v.meta&&m(A=>A+x);return}if(o.type==="artifact-select"){let{cursor:k,selected:P,values:w}=o;if(v.escape){let A=pn.length-1,_=pn[A];s({type:"field-entry",field:A,values:w}),m(_?w[_]:"");return}if(v.upArrow){s({...o,cursor:Math.max(0,k-1)});return}if(v.downArrow){s({...o,cursor:Math.min(Be.length-1,k+1)});return}if(x===" "){let A=Be[k];if(A){let _=cg(P,A);f(_),s({...o,selected:_})}return}if(x==="a"){f([...Be]),s({...o,selected:[...Be]});return}if(x==="n"){f([]),s({...o,selected:[]});return}v.return&&(a==="sub-dir"?(s({type:"resolving-target"}),C(w,P)):s({type:"confirm",values:w,artifacts:P}));return}if(o.type==="confirm"){if(v.escape){s({type:"artifact-select",values:o.values,cursor:0,selected:o.artifacts});return}v.return&&(s({type:"writing"}),S(o.values,p,o.artifacts));return}(o.type==="done"||o.type==="error")&&(v.return||v.escape)&&i.exit()}),o.type==="target-select"){let x=[{label:"Use current directory",desc:e},{label:"Create new sub-directory",desc:`${e}/<inferred from API name>`}];return ee(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[U(ye,{}),ee(de,{flexDirection:"column",gap:0,children:[U(K,{bold:!0,children:"Where should the new plugin live?"}),x.map((v,k)=>{let P=o.cursor===k;return ee(de,{gap:2,children:[U(K,{...P&&{color:"cyan"},children:P?"\u276F":" "}),U(K,{bold:P,...P&&{color:"cyan"},children:v.label}),U(K,{dimColor:!0,children:v.desc})]},v.label)})]}),U(Vn,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(o.type==="precheck-error"){let{targetDir:x,reason:v}=o;return ee(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[U(ye,{}),U(K,{color:"red",bold:!0,children:"Cannot create plugin"}),ee(de,{flexDirection:"column",gap:0,children:[ee(K,{children:[x," already contains ",U(K,{bold:!0,children:v==="has-manifest"?"kizen.json":".kizenapp/"}),"."]}),U(K,{dimColor:!0,children:"Remove the conflicting file/directory or choose a different target to avoid overwriting an existing plugin."})]}),U(Vn,{text:"Enter or Esc to exit"})]})}if(o.type==="field-entry"){let{field:x,fieldError:v}=o,k=a==="sub-dir"?`Target: sub-directory of ${e} (inferred from API name)`:`Target: ${p}`;return ee(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[U(ye,{}),ee(de,{flexDirection:"column",gap:0,children:[U(K,{bold:!0,children:"Plugin details"}),U(K,{dimColor:!0,children:k})]}),v!==void 0&&ee(K,{color:"red",children:["Error: ",v]}),U(de,{flexDirection:"column",gap:0,children:pn.map((P,w)=>{let A=x===w,_=A?g:l[P],T=yl.includes(P),L=`${gs[P]}${T?"":" (optional)"}`;return ee(de,{gap:2,children:[U(de,{width:24,children:U(K,{bold:A,...A&&{color:"cyan"},children:L})}),U(K,{...A&&{color:"cyan"},children:">"}),U(K,{children:_}),A&&U(K,{color:"cyan",children:"\u2588"})]},P)})}),U(Vn,{text:"Enter/Tab/\u2193 next \xB7 \u2191 previous \xB7 Backspace delete \xB7 Esc cancel"})]})}if(o.type==="artifact-select"){let{cursor:x,selected:v}=o;return ee(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[U(ye,{}),ee(de,{flexDirection:"column",gap:0,children:[U(K,{bold:!0,children:"Which artifacts should we scaffold?"}),U(K,{dimColor:!0,children:"Each one gets a directory with a config.json and a script that runs."})]}),U(de,{flexDirection:"column",gap:0,children:Be.map((k,P)=>{let w=x===P,A=v.includes(k);return ee(de,{gap:1,children:[U(K,{...w&&{color:"cyan"},children:w?"\u276F":" "}),U(K,{...A&&{color:"green"},children:A?"\u25C9":"\u25EF"}),U(K,{bold:w,...w&&{color:"cyan"},children:dl[k]})]},k)})}),U(Vn,{text:"\u2191\u2193 move \xB7 Space toggle \xB7 a all \xB7 n none \xB7 Enter continue \xB7 Esc back"})]})}if(o.type==="confirm"){let x=hl({targetDir:p,name:o.values.name,apiName:o.values.apiName,externalLink:o.values.externalLink,description:o.values.description,developerBusinessId:o.values.developerBusinessId,developerEnvironment:n});return ee(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[U(ye,{}),ee(de,{flexDirection:"column",gap:0,children:[U(K,{bold:!0,children:"Ready to create"}),ee(K,{dimColor:!0,children:["Target: ",p]})]}),ee(de,{flexDirection:"column",gap:0,children:[U(K,{bold:!0,children:"kizen.json preview"}),U(K,{children:JSON.stringify(x,null,2)})]}),ee(de,{flexDirection:"column",gap:0,children:[U(K,{bold:!0,children:"Artifacts"}),o.artifacts.length===0?ee(K,{dimColor:!0,children:[" ","none (src/ will hold only thumbnail.png)"]}):o.artifacts.map(v=>ee(K,{dimColor:!0,children:[" ",dl[v]]},v))]}),ee(de,{flexDirection:"column",gap:0,children:[U(K,{dimColor:!0,children:"Also creates:"}),ee(K,{dimColor:!0,children:[" ",bs(p,"src/")]}),ee(K,{dimColor:!0,children:[" ",bs(p,"src/thumbnail.png")," (generated placeholder)"]}),ee(K,{dimColor:!0,children:[" ",bs(p,"releaseNotes/")]}),ee(K,{dimColor:!0,children:[" ",bs(p,".gitignore")," (adds .kizenapp/)"]})]}),U(Vn,{text:"Enter to create \xB7 Esc to go back"})]})}return o.type==="resolving-target"?U(de,{paddingY:1,paddingX:2,children:U(K,{dimColor:!0,children:"Finding available sub-directory\u2026"})}):o.type==="writing"?U(de,{paddingY:1,paddingX:2,children:U(K,{dimColor:!0,children:"Creating plugin\u2026"})}):o.type==="done"?ee(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[U(ye,{}),ee(K,{color:"green",bold:!0,children:["Plugin created at ",o.targetDir]}),ee(de,{flexDirection:"column",gap:0,children:[U(K,{dimColor:!0,children:"Next steps:"}),ee(K,{children:[" ","cd ",o.targetDir]}),ee(K,{children:[" ","npx --yes @kizenapps/cli dev"]}),ee(K,{dimColor:!0,children:[" ","Replace src/thumbnail.png with real artwork before publishing."]})]}),U(Vn,{text:"Enter or Esc to exit"})]}):ee(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[U(ye,{}),U(K,{color:"red",bold:!0,children:"Failed to create plugin"}),U(K,{children:o.message}),U(Vn,{text:"Enter or Esc to exit"})]})};async function ug(e){let t=await e.listSessions().catch(()=>[]);if(t.length===0){let o=await e.loadGlobalCredentials();return{businessId:o?.businessId??"",environment:o?.environment??"go"}}let n=await Cr(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 CS="A hello-world Kizen plugin.",dg=e=>Object.entries(e).some(([t,n])=>t!=="includeLib"&&n!==void 0);function SS(e){if(e===void 0||e.trim()===""||e.trim()==="all")return[...Be];if(e.trim()==="none")return[];let t=e.split(",").map(r=>r.trim()).filter(r=>r!==""),n=t.filter(r=>!Be.includes(r));if(n.length>0)throw new Error(`Unknown artifact type(s): ${n.join(", ")}. Valid types: ${Be.join(", ")}, or "all" / "none".`);return[...new Set(t)]}function _S(e,t,n){let r=e.name?.trim()??"";if(r==="")throw new Error("--name is required for a non-interactive run.");let i=(e.apiName?.trim()??"")||hs(r);if(!bl.test(i))throw new Error(`api_name "${i}" is invalid: ${wl}. Pass --api-name.`);let o=e.description?.trim(),s=e.businessId?.trim()??t.businessId,a=ES(e,t);return{targetDir:n,name:r,apiName:i,externalLink:e.externalLink?.trim()??"",description:o===void 0||o===""?CS:o,developerBusinessId:s,developerEnvironment:a,artifacts:SS(e.artifacts),includeLib:e.includeLib===!0}}function ES(e,t){let n=e.environment?.trim();if(n!==void 0&&n!==""){if(!vr(n))throw new Error(`Unknown environment "${n}". Valid environments: ${pe.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 pg(e,t,n,r){let i;try{i=_S(e,t,n)}catch(a){r.writeStderr(`Error: ${a instanceof Error?a.message:String(a)}
|
|
1029
|
+
`;var rg=`this.showToast('Hello from a JS action.', { variant: 'success' });
|
|
1030
|
+
`;var Be=["floatingFrame","block","dataAdornment","page","toolbarItem","objectSettingsItem","jsAction"],pl={floatingFrame:"Floating frame",block:"Block",dataAdornment:"Data adornment",page:"Routable page",toolbarItem:"Toolbar item",objectSettingsItem:"Object settings item",jsAction:"JS action"},uS={floatingFrame:{directory:"floatingFrames",component:"helloFrame",files:{"config.json":Mf,"script.js":zf,"styles.css":Uf}},block:{directory:"blocks",component:"helloBlock",files:{"config.json":Vf,"script.js":Hf,"styles.css":Kf}},dataAdornment:{directory:"dataAdornments",component:"helloAdornment",files:{"config.json":Wf,"script.js":Gf}},page:{directory:"pages",component:"helloPage",files:{"config.json":Jf,"script.js":qf,"styles.css":Yf,"eventScripts/greet.js":Zf}},toolbarItem:{directory:"toolbarItems",component:"helloToolbarItem",files:{"config.json":Xf,"script.js":Qf}},objectSettingsItem:{directory:"objectSettingsItems",component:"helloObjectSettingsItem",files:{"config.json":eg,"script.js":tg}},jsAction:{directory:"actions",component:"helloAction",files:{"config.json":ng,"script.js":rg}}};function dS(e,t="src"){let{directory:n,component:r,files:i}=uS[e];return Object.entries(i).map(([o,s])=>({path:`${t}/${n}/${r}/${o}`,content:s}))}function ig(e,t="src"){return[...new Set(e)].flatMap(n=>dS(n,t))}import{deflateSync as pS}from"zlib";var fl=512,mS=150,fS=26,gl=46,og=.6,gS=gl*.55,hS=.55,yS=.47;function bS(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 wS(e){let t=bS(e);return{hue:t%360,quarterTurns:(t>>>16)%4}}function vS(e,t,n){let r=(1-Math.abs(2*n-1))*t,i=e/60,o=r*(1-Math.abs(i%2-1)),s=n-r/2,[a,c,l]=i<1?[r,o,0]:i<2?[o,r,0]:i<3?[0,r,o]:i<4?[0,o,r]:i<5?[o,0,r]:[r,0,o];return[Math.round((a+s)*255),Math.round((c+s)*255),Math.round((l+s)*255)]}function di(e,t,n,r,i){let o=Math.abs(e)-n+i,s=Math.abs(t)-r+i;return Math.hypot(Math.max(o,0),Math.max(s,0))+Math.min(Math.max(o,s),0)-i}function us(e,t,n,r,i){return Math.hypot(e-n,t-r)-i}function kS(e,t){let n=mS,r=gl,i=r*og,o=gS,s=di(e,t,n,n,fS),a=Math.min(us(e,t,0,-n-i,r),di(e,t+n+i/2,o,i/2+1,0)),c=Math.min(us(e,t,n+i,0,r),di(e-n-i/2,t,i/2+1,o,0));s=Math.min(s,a,c);let l=Math.min(us(e,t,0,n-i,r),di(e,t-n+i/2,o,i/2+1,0)),d=Math.min(us(e,t,-n+i,0,r),di(e+n-i/2,t,i/2+1,o,0));return Math.max(s,-l,-d)}function AS(e){let t=fl,n=new Uint8Array(t*t*4),[r,i,o]=vS(e.hue,hS,yS),s=gl*(1+og),a=(t-1)/2,c=s/2;for(let l=0;l<t;l+=1)for(let d=0;d<t;d+=1){let u=d-a,f=l-a;for(let h=0;h<e.quarterTurns;h+=1)[u,f]=[-f,u];let g=kS(u+c,f-c),p=Math.min(1,Math.max(0,.5-g));if(p<=0)continue;let m=(l*t+d)*4;n[m]=r,n[m+1]=i,n[m+2]=o,n[m+3]=Math.round(p*255)}return n}var xS=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 PS(e){let t=4294967295;for(let n of e)t=(xS[(t^n)&255]??0)^t>>>8;return(t^4294967295)>>>0}function ml(e,t){let n=Buffer.from(e,"latin1"),r=Buffer.alloc(4);r.writeUInt32BE(t.length);let i=Buffer.alloc(4);return i.writeUInt32BE(PS(Buffer.concat([n,t]))),Buffer.concat([r,n,t,i])}var CS=Buffer.from([137,80,78,71,13,10,26,10]);function SS(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 i=e*4,o=Buffer.alloc((i+1)*t);for(let s=0;s<t;s+=1)o.set(n.subarray(s*i,(s+1)*i),s*(i+1)+1);return Buffer.concat([CS,ml("IHDR",r),ml("IDAT",pS(o,{level:9})),ml("IEND",new Uint8Array(0))])}function sg(e){return SS(fl,fl,AS(wS(e)))}var IS="src/thumbnail.png",TS=["go","fmo"];async function ms(e){try{return await _S(e),!0}catch{return!1}}async function dn(e){return await ms(jt(e,"kizen.json"))?"has-manifest":await ms(jt(e,".kizenapp"))?"has-kizenapp":"ok"}async function ag(e,t){let n=jt(e,t);if(!await ms(n))return n;for(let r=1;r<1e3;r++){let i=jt(e,`${t}-${String(r)}`);if(!await ms(i))return i}throw new Error(`Could not find an available directory name for "${t}"`)}function yl(e){let t=e.developerBusinessId.trim(),n=t!==""&&!TS.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 ds(e,t){let n=t.map(i=>({fullPath:jt(e,...i.path.split("/")),content:i.content})),r=new Set(n.map(i=>ES(i.fullPath)));await Promise.all([...r].map(i=>ps(i,{recursive:!0}))),await Promise.all(n.map(i=>hl(i.fullPath,i.content,"utf-8")))}async function fs(e){await ps(e.targetDir,{recursive:!0});let t=yl(e);await hl(jt(e.targetDir,"kizen.json"),JSON.stringify(t,null,2)+`
|
|
1031
|
+
`,"utf-8"),await ps(jt(e.targetDir,"src"),{recursive:!0}),await ps(jt(e.targetDir,"releaseNotes"),{recursive:!0}),await Promise.all([ds(e.targetDir,ig(e.artifacts??[])),ds(e.targetDir,Ki()),ds(e.targetDir,Hd(e.includeLib===!0?["src"]:[])),ds(e.targetDir,Kd()),hl(jt(e.targetDir,...IS.split("/")),sg(e.apiName))]),Ze(e.targetDir)}var pn=["name","apiName","externalLink","description","developerBusinessId"],gs={name:"Name",apiName:"API name",externalLink:"External link",description:"Description",developerBusinessId:"Business ID"},bl=["name","apiName","description"],wl=/^[a-z_][a-z0-9_]+$/,vl="must start with a letter or underscore and contain only lowercase letters, numbers, or underscores (minimum 2 characters)";function hs(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}function cg(e){return{name:"",apiName:"",externalLink:"",description:"",developerBusinessId:e}}function lg(e,t){let n=t.trim();if(bl.includes(e)&&!n)return`${gs[e]} is required`;if(e==="apiName"&&!wl.test(n))return`${gs[e]} ${vl}`}function ug(e,t){return e==="description"?t:t.trim()}function dg(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),Be.filter(r=>n.has(r))}import{jsx as U,jsxs as te}from"react/jsx-runtime";var Vn=({text:e})=>U(K,{dimColor:!0,children:e}),pg=({parentDir:e,defaultBusinessId:t,defaultEnvironment:n,includeLib:r=!1})=>{let i=NS(),[o,s]=dr({type:"target-select",cursor:0}),[a,c]=dr("in-place"),[l,d]=dr(()=>cg(t)),[u,f]=dr(()=>[...Be]),[g,p]=dr(""),[m,h]=dr(e),b=ys((x,v)=>{c(x),p(v.name),s({type:"field-entry",field:0,values:v})},[]),y=ys(async x=>{let v=await dn(x);if(v!=="ok"){s({type:"precheck-error",targetDir:x,reason:v});return}h(x),b("in-place",l)},[l,b]),C=ys(async(x,v)=>{try{let k=await ag(e,x.apiName);h(k),s({type:"confirm",values:x,artifacts:v})}catch(k){s({type:"error",message:k instanceof Error?k.message:String(k)})}},[e]),S=ys(async(x,v,k)=>{try{await fs({targetDir:v,name:x.name,apiName:x.apiName,externalLink:x.externalLink,description:x.description,developerBusinessId:x.developerBusinessId,developerEnvironment:n,artifacts:k,includeLib:r}),s({type:"done",targetDir:v})}catch(P){s({type:"error",message:P instanceof Error?P.message:String(P)})}},[n,r]);if(RS((x,v)=>{if(v.ctrl&&x==="c"){i.exit();return}if(o.type==="target-select"){v.upArrow?s({type:"target-select",cursor:0}):v.downArrow?s({type:"target-select",cursor:1}):v.return?o.cursor===0?y(e):b("sub-dir",l):v.escape&&i.exit();return}if(o.type==="precheck-error"){(v.return||v.escape)&&i.exit();return}if(o.type==="field-entry"){let{field:k,values:P}=o,w=pn[k];if(!w)return;if(v.escape){i.exit();return}if(v.backspace||v.delete){p(A=>A.slice(0,-1));return}if(v.upArrow&&k>0){let A={...P,[w]:g},_=k-1,T=pn[_];s({type:"field-entry",field:_,values:A}),d(A),p(T?A[T]:"");return}if(v.return||v.tab||v.downArrow){let A=lg(w,g);if(A!==void 0){s({type:"field-entry",field:k,values:P,fieldError:A});return}let _=ug(w,g),T={...P,[w]:_};d(T);let L=k+1;if(L>=pn.length)p(""),s({type:"artifact-select",values:T,cursor:0,selected:u});else{let $=pn[L],V=$?T[$]:"",X=$==="apiName"&&!V?hs(T.name):V;s({type:"field-entry",field:L,values:T}),p(X)}return}x&&!v.ctrl&&!v.meta&&p(A=>A+x);return}if(o.type==="artifact-select"){let{cursor:k,selected:P,values:w}=o;if(v.escape){let A=pn.length-1,_=pn[A];s({type:"field-entry",field:A,values:w}),p(_?w[_]:"");return}if(v.upArrow){s({...o,cursor:Math.max(0,k-1)});return}if(v.downArrow){s({...o,cursor:Math.min(Be.length-1,k+1)});return}if(x===" "){let A=Be[k];if(A){let _=dg(P,A);f(_),s({...o,selected:_})}return}if(x==="a"){f([...Be]),s({...o,selected:[...Be]});return}if(x==="n"){f([]),s({...o,selected:[]});return}v.return&&(a==="sub-dir"?(s({type:"resolving-target"}),C(w,P)):s({type:"confirm",values:w,artifacts:P}));return}if(o.type==="confirm"){if(v.escape){s({type:"artifact-select",values:o.values,cursor:0,selected:o.artifacts});return}v.return&&(s({type:"writing"}),S(o.values,m,o.artifacts));return}(o.type==="done"||o.type==="error")&&(v.return||v.escape)&&i.exit()}),o.type==="target-select"){let x=[{label:"Use current directory",desc:e},{label:"Create new sub-directory",desc:`${e}/<inferred from API name>`}];return te(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[U(ye,{}),te(de,{flexDirection:"column",gap:0,children:[U(K,{bold:!0,children:"Where should the new plugin live?"}),x.map((v,k)=>{let P=o.cursor===k;return te(de,{gap:2,children:[U(K,{...P&&{color:"cyan"},children:P?"\u276F":" "}),U(K,{bold:P,...P&&{color:"cyan"},children:v.label}),U(K,{dimColor:!0,children:v.desc})]},v.label)})]}),U(Vn,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(o.type==="precheck-error"){let{targetDir:x,reason:v}=o;return te(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[U(ye,{}),U(K,{color:"red",bold:!0,children:"Cannot create plugin"}),te(de,{flexDirection:"column",gap:0,children:[te(K,{children:[x," already contains ",U(K,{bold:!0,children:v==="has-manifest"?"kizen.json":".kizenapp/"}),"."]}),U(K,{dimColor:!0,children:"Remove the conflicting file/directory or choose a different target to avoid overwriting an existing plugin."})]}),U(Vn,{text:"Enter or Esc to exit"})]})}if(o.type==="field-entry"){let{field:x,fieldError:v}=o,k=a==="sub-dir"?`Target: sub-directory of ${e} (inferred from API name)`:`Target: ${m}`;return te(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[U(ye,{}),te(de,{flexDirection:"column",gap:0,children:[U(K,{bold:!0,children:"Plugin details"}),U(K,{dimColor:!0,children:k})]}),v!==void 0&&te(K,{color:"red",children:["Error: ",v]}),U(de,{flexDirection:"column",gap:0,children:pn.map((P,w)=>{let A=x===w,_=A?g:l[P],T=bl.includes(P),L=`${gs[P]}${T?"":" (optional)"}`;return te(de,{gap:2,children:[U(de,{width:24,children:U(K,{bold:A,...A&&{color:"cyan"},children:L})}),U(K,{...A&&{color:"cyan"},children:">"}),U(K,{children:_}),A&&U(K,{color:"cyan",children:"\u2588"})]},P)})}),U(Vn,{text:"Enter/Tab/\u2193 next \xB7 \u2191 previous \xB7 Backspace delete \xB7 Esc cancel"})]})}if(o.type==="artifact-select"){let{cursor:x,selected:v}=o;return te(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[U(ye,{}),te(de,{flexDirection:"column",gap:0,children:[U(K,{bold:!0,children:"Which artifacts should we scaffold?"}),U(K,{dimColor:!0,children:"Each one gets a directory with a config.json and a script that runs."})]}),U(de,{flexDirection:"column",gap:0,children:Be.map((k,P)=>{let w=x===P,A=v.includes(k);return te(de,{gap:1,children:[U(K,{...w&&{color:"cyan"},children:w?"\u276F":" "}),U(K,{...A&&{color:"green"},children:A?"\u25C9":"\u25EF"}),U(K,{bold:w,...w&&{color:"cyan"},children:pl[k]})]},k)})}),U(Vn,{text:"\u2191\u2193 move \xB7 Space toggle \xB7 a all \xB7 n none \xB7 Enter continue \xB7 Esc back"})]})}if(o.type==="confirm"){let x=yl({targetDir:m,name:o.values.name,apiName:o.values.apiName,externalLink:o.values.externalLink,description:o.values.description,developerBusinessId:o.values.developerBusinessId,developerEnvironment:n});return te(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[U(ye,{}),te(de,{flexDirection:"column",gap:0,children:[U(K,{bold:!0,children:"Ready to create"}),te(K,{dimColor:!0,children:["Target: ",m]})]}),te(de,{flexDirection:"column",gap:0,children:[U(K,{bold:!0,children:"kizen.json preview"}),U(K,{children:JSON.stringify(x,null,2)})]}),te(de,{flexDirection:"column",gap:0,children:[U(K,{bold:!0,children:"Artifacts"}),o.artifacts.length===0?te(K,{dimColor:!0,children:[" ","none (src/ will hold only thumbnail.png)"]}):o.artifacts.map(v=>te(K,{dimColor:!0,children:[" ",pl[v]]},v))]}),te(de,{flexDirection:"column",gap:0,children:[U(K,{dimColor:!0,children:"Also creates:"}),te(K,{dimColor:!0,children:[" ",bs(m,"src/")]}),te(K,{dimColor:!0,children:[" ",bs(m,"src/thumbnail.png")," (generated placeholder)"]}),te(K,{dimColor:!0,children:[" ",bs(m,"releaseNotes/")]}),te(K,{dimColor:!0,children:[" ",bs(m,".gitignore")," (adds .kizenapp/)"]})]}),U(Vn,{text:"Enter to create \xB7 Esc to go back"})]})}return o.type==="resolving-target"?U(de,{paddingY:1,paddingX:2,children:U(K,{dimColor:!0,children:"Finding available sub-directory\u2026"})}):o.type==="writing"?U(de,{paddingY:1,paddingX:2,children:U(K,{dimColor:!0,children:"Creating plugin\u2026"})}):o.type==="done"?te(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[U(ye,{}),te(K,{color:"green",bold:!0,children:["Plugin created at ",o.targetDir]}),te(de,{flexDirection:"column",gap:0,children:[U(K,{dimColor:!0,children:"Next steps:"}),te(K,{children:[" ","cd ",o.targetDir]}),te(K,{children:[" ","npx --yes @kizenapps/cli dev"]}),te(K,{dimColor:!0,children:[" ","Replace src/thumbnail.png with real artwork before publishing."]})]}),U(Vn,{text:"Enter or Esc to exit"})]}):te(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[U(ye,{}),U(K,{color:"red",bold:!0,children:"Failed to create plugin"}),U(K,{children:o.message}),U(Vn,{text:"Enter or Esc to exit"})]})};async function mg(e){let t=await e.listSessions().catch(()=>[]);if(t.length===0){let o=await e.loadGlobalCredentials();return{businessId:o?.businessId??"",environment:o?.environment??"go"}}let n=await Cr(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 $S="A hello-world Kizen plugin.",fg=e=>Object.entries(e).some(([t,n])=>t!=="includeLib"&&n!==void 0);function OS(e){if(e===void 0||e.trim()===""||e.trim()==="all")return[...Be];if(e.trim()==="none")return[];let t=e.split(",").map(r=>r.trim()).filter(r=>r!==""),n=t.filter(r=>!Be.includes(r));if(n.length>0)throw new Error(`Unknown artifact type(s): ${n.join(", ")}. Valid types: ${Be.join(", ")}, or "all" / "none".`);return[...new Set(t)]}function DS(e,t,n){let r=e.name?.trim()??"";if(r==="")throw new Error("--name is required for a non-interactive run.");let i=(e.apiName?.trim()??"")||hs(r);if(!wl.test(i))throw new Error(`api_name "${i}" is invalid: ${vl}. Pass --api-name.`);let o=e.description?.trim(),s=e.businessId?.trim()??t.businessId,a=LS(e,t);return{targetDir:n,name:r,apiName:i,externalLink:e.externalLink?.trim()??"",description:o===void 0||o===""?$S:o,developerBusinessId:s,developerEnvironment:a,artifacts:OS(e.artifacts),includeLib:e.includeLib===!0}}function LS(e,t){let n=e.environment?.trim();if(n!==void 0&&n!==""){if(!vr(n))throw new Error(`Unknown environment "${n}". Valid environments: ${pe.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 gg(e,t,n,r){let i;try{i=DS(e,t,n)}catch(a){r.writeStderr(`Error: ${a instanceof Error?a.message:String(a)}
|
|
1032
1032
|
`),r.setExitCode(1);return}let o=await r.precheckTargetDir(n);if(o!=="ok"){let a=o==="has-manifest"?"kizen.json":".kizenapp/";r.writeStderr(`Error: ${n} already contains ${a}. Refusing to overwrite an existing plugin.
|
|
1033
1033
|
`),r.setExitCode(1);return}try{await r.createPlugin(i)}catch(a){r.writeStderr(`Error: ${a instanceof Error?a.message:String(a)}
|
|
1034
1034
|
`),r.setExitCode(1);return}let s=i.artifacts&&i.artifacts.length>0?i.artifacts.join(", "):"none";r.writeStdout(`Created plugin ${i.apiName} at ${n}
|
|
1035
1035
|
`),r.writeStdout(`Artifacts: ${s}
|
|
1036
1036
|
`),r.writeStdout(`Thumbnail: src/thumbnail.png (generated placeholder; replace it before publishing)
|
|
1037
|
-
`),i.developerBusinessId.trim()===""&&r.writeStderr("Warning: no developer_business_id configured, so this plugin can't be preview-published to the marketplace (plugin-wizard) yet. Business Apps (`appbuilder app push`) don't need it.\n")}function
|
|
1037
|
+
`),i.developerBusinessId.trim()===""&&r.writeStderr("Warning: no developer_business_id configured, so this plugin can't be preview-published to the marketplace (plugin-wizard) yet. Business Apps (`appbuilder app push`) don't need it.\n")}function hg(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: ${pe.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: ${Be.join(", ")}`).option("--include-lib","also install the Kizen data helper library (src/lib/kizenData.js)").option("--no-interactive",gt).action(async t=>{let{noInteractive:n,options:r}=Ae(t),i=process.cwd(),o=ht(),{businessId:s,environment:a}=await mg({listSessions:o.listSessions,readSession:o.readSession,loadGlobalCredentials:De,...r.environment!==void 0&&{requestedEnvironment:r.environment}});if(!ft({noInteractive:n})||fg(r)){await gg(r,{businessId:s,environment:a},i,{precheckTargetDir:dn,createPlugin:fs,writeStdout:d=>{process.stdout.write(d)},writeStderr:d=>{process.stderr.write(d)},setExitCode:d=>{process.exitCode=d}});return}let{waitUntilExit:l}=FS(BS(pg,{parentDir:i,defaultBusinessId:s,defaultEnvironment:a,includeLib:r.includeLib===!0}),{exitOnCtrlC:!1});await l()})}import{createElement as Jg}from"react";import{render as qg}from"ink";import{useCallback as pr,useEffect as Ss,useRef as Mt,useState as Ve}from"react";import{Box as Ee,Text as ne,useInput as M_}from"ink";import{PluginValidationError as z_}from"@kizenapps/packager";import{watch as U_}from"fs";import{createServer as V_}from"http";import{join as Kg}from"path";import{WebSocketServer as H_}from"ws";import{createReadStream as Tg,realpathSync as a_}from"fs";import{access as c_,readdir as l_,readFile as u_,realpath as d_,stat as Ng}from"fs/promises";import{dirname as p_,extname as Rg,join as hi,resolve as m_,sep as Tl}from"path";import{fileURLToPath as f_}from"url";var jS=new Set(["set-cookie","strict-transport-security","content-security-policy","content-security-policy-report-only","x-frame-options","content-encoding","content-length"]);function ws(e){let t={};for(let[n,r]of Object.entries(e)){let i=n.toLowerCase();jS.has(i)||i.startsWith("access-control-")||(t[n]=r)}return t}var kl=10*1024*1024,MS=6e4,zS=200,pi=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 Al(e,t){let n=e.body;if(n===null)return Buffer.alloc(0);let r=[],i=0;for await(let o of n){if(i+=o.length,i>t)throw new pi(i,t);r.push(o)}return Buffer.concat(r)}async function yg(e){let t=ws(Object.fromEntries(e.headers)),n=await Al(e,kl);return{status:e.status,headers:t,body:n}}function bg(e={}){let{onChange:t,enabled:n=!0}=e;if(!n)return{async get(s,a){return{response:await yg(await a()),fromCache:!1}},clear(){}};let r=new Map,i=()=>{t?.(r.size)},o=s=>{r.delete(s)&&i()};return{get(s,a){let c=r.get(s);if(c!==void 0){if(Date.now()-c.insertedAt<MS)return c.promise.then(d=>({response:d,fromCache:!0}));o(s)}if(r.size>=zS){let d=r.keys().next().value;d!==void 0&&o(d)}let l=a().then(yg).catch(d=>{throw o(s),d});return r.set(s,{insertedAt:Date.now(),promise:l}),i(),l.then(d=>((d.status<200||d.status>=300)&&o(s),{response:d,fromCache:!1}))},clear(){r.clear(),i()}}}var xl={".html":"text/html; charset=utf-8",".js":"application/javascript; charset=utf-8",".mjs":"application/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".svg":"image/svg+xml",".ico":"image/x-icon",".json":"application/json; charset=utf-8",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".map":"application/json"};import{readFile as KS}from"fs/promises";import{join as WS}from"path";var US=/^\/([^/]+)\/.+/;function VS(e){return US.exec(e)?.[1]}function wg(e){return Array.isArray(e)?e.flatMap(t=>{let n=t?.api_name;return typeof n=="string"?[n]:[]}):[]}function HS(e){try{return new URL(e,"http://localhost").pathname===e}catch{return!1}}function vs(e,t){if(!HS(e))return!1;let n=VS(e);return n!==void 0&&t.includes(n)}async function Pl(e){try{let t=await KS(WS(e,"bundle.json"),"utf-8");return wg(JSON.parse(t))}catch{return[]}}async function Cl(e,t){if(t!==void 0)return vs(t,await Pl(e))?t:void 0}async function vg(e){let t=await rt(e),{lastPath:n}=t;if(n===void 0)return;let r=await Cl(e,n);if(r!==void 0)return r;let i={...t};delete i.lastPath;try{await bt(e,i)}catch{}}var Sl={prod:"https://plugin-wizard.kizen.com",dev:"https://plugin-wizard.kizen.dev",localDev:"http://localhost:9823"};function mi(e){let t=process.env.PLUGIN_WIZARD_URL;return t!==void 0&&t!==""?t:e==="prod"?process.env.PLUGIN_WIZARD_URL_PROD||Sl.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!==""?Sl.localDev:Sl.dev}import{spawn as Cg}from"child_process";import{writeFile as xg,rm as El,mkdtemp as YS,access as ZS}from"fs/promises";import{join as gi}from"path";import{tmpdir as XS}from"os";var kg=`awslambdaric
|
|
1038
1038
|
bcrypt
|
|
1039
1039
|
boto3
|
|
1040
1040
|
fpdf2
|
|
@@ -1052,7 +1052,7 @@ pytz
|
|
|
1052
1052
|
requests
|
|
1053
1053
|
sqlalchemy>=2.0,<2.1
|
|
1054
1054
|
tzdata
|
|
1055
|
-
`;import{AUTOMATION_SCRIPT_RUNTIMES as
|
|
1055
|
+
`;import{AUTOMATION_SCRIPT_RUNTIMES as QS,isSupportedScriptRuntime as e_,scriptRuntimeToApiName as Sg}from"@kizenapps/packager";function JS(e){return e==null||e.trim()===""?null:e}function qS(e){return e==null?null:typeof e=="string"?JS(e):typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):typeof e=="function"||typeof e=="symbol"?null:JSON.stringify(e)}function Ag(e){return e?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,qS(n)])):{}}var t_=`
|
|
1056
1056
|
import sys, json, os, traceback
|
|
1057
1057
|
|
|
1058
1058
|
# --- Inputs proxy (attribute access) ---
|
|
@@ -1212,29 +1212,29 @@ sys.stdout.write('\\n__KIZEN_RESULT_START__\\n')
|
|
|
1212
1212
|
sys.stdout.write(json.dumps(result, ensure_ascii=False))
|
|
1213
1213
|
sys.stdout.write('\\n__KIZEN_RESULT_END__\\n')
|
|
1214
1214
|
sys.stdout.flush()
|
|
1215
|
-
`.trim(),
|
|
1216
|
-
`);for(;g>=0;){let
|
|
1215
|
+
`.trim(),n_=3e4,ks=gi(process.cwd(),".kizenapp","venv"),r_=QS.map(Sg),_g=Du(kg);if(_g.length===0)throw new Error("python-requirements.txt bundled no packages \u2014 check the build output");var fi=null;function Pg(e,t,n){return new Promise((r,i)=>{let o=Cg(e,t,{stdio:["ignore","pipe","pipe"]}),s=(c,l)=>{let d=[],u="";return c.on("data",f=>{u+=f.toString("utf-8");let g=u.indexOf(`
|
|
1216
|
+
`);for(;g>=0;){let p=u.slice(0,g).replace(/\r$/,"");u=u.slice(g+1),d.push(p),n?.(p,l),g=u.indexOf(`
|
|
1217
1217
|
`)}}),c.on("end",()=>{if(u.length>0){let f=u.replace(/\r$/,"");d.push(f),n?.(f,l)}}),d},a=s(o.stderr,"stderr");s(o.stdout,"stdout"),o.on("error",i),o.on("close",c=>{if(c===0)r();else{let l=a.slice(-10).join(`
|
|
1218
|
-
`).trim(),d=l.length>0?`: ${l}`:"";i(new Error(`${e} exited with code ${String(c)}${d}`))}})})}var Pl=null;function KS(e,t){if(fi)return t&&Pl?.add(t),fi;let n=new Set;t&&n.add(t),Pl=n;let r=o=>{for(let s of n)s(o)},i=gi(vs,"bin","python");return fi=(async()=>{try{let o=!1;try{await FS(i);let s=await Oi(i);o=s!==null&&Gs(s,Ir)}catch{o=!1}if(!o){await Cl(vs,{recursive:!0,force:!0}).catch(()=>{});let s=await Ou(e);await wg(s,["-m","venv",vs])}return r({kind:"start"}),await wg(i,["-m","pip","install","--disable-pip-version-check",...Ag],(s,a)=>{r({kind:"log",line:s,stream:a})}),r({kind:"complete"}),i}catch(o){let s=o instanceof Error?o.message:String(o);throw r({kind:"error",message:s}),fi=null,await Cl(vs,{recursive:!0,force:!0}).catch(()=>{}),o}finally{Pl=null}})(),fi}function WS(e){let t="__KIZEN_RESULT_START__",n="__KIZEN_RESULT_END__",r=e.indexOf(t),i=e.indexOf(n);if(r===-1||i===-1)return{userStdout:e,result:null};let o=e.slice(0,r).trimEnd(),s=e.slice(r+t.length,i).trim();try{let a=JSON.parse(s);return{userStdout:o,result:a}}catch{return{userStdout:e,result:null}}}function GS(e){return{success:!1,outputValues:{},logs:[],stdout:"",stderr:"",error:e,exitCode:1,durationMs:0}}async function xg(e){let t=e.timeout??VS;if(!zS(e.scriptRuntime))return GS(`Unsupported runtime "${e.scriptRuntime}". Supported runtimes: ${HS.join(", ")}. Update the step's config.json "runtime" field (e.g. "python 3.13").`);let r=await KS(kg(e.scriptRuntime),e.onInstallProgress),i=Date.now(),o;try{o=await BS(gi(jS(),"kizen-step-"));let s=gi(o,"wrapper.py"),a=gi(o,"script.py");await Promise.all([bg(s,US,"utf-8"),bg(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:l,stdout:d,stderr:u}=await new Promise(h=>{let b=[],y=[],C=!1,S=vg(r,[s],{env:c,cwd:o,stdio:["ignore","pipe","pipe"]}),x=setTimeout(()=>{S.kill("SIGKILL")},t);S.stdout.on("data",k=>{b.push(k)}),S.stderr.on("data",k=>{y.push(k)});let v=k=>{C||(C=!0,clearTimeout(x),h({exitCode:k??1,stdout:Buffer.concat(b).toString("utf-8"),stderr:Buffer.concat(y).toString("utf-8")}))};S.on("close",v),S.on("error",k=>{C||(C=!0,clearTimeout(x),h({exitCode:1,stdout:"",stderr:k.message}))})}),f=Date.now()-i,{userStdout:g,result:m}=WS(d);if(m){let h={success:m.success,outputValues:m.outputValues,logs:m.logs,stdout:g,stderr:u,exitCode:l,durationMs:f};return m.error!==null&&(h.error=m.error),m.httpRequests&&(h.httpRequests=m.httpRequests),h}let p={success:!1,outputValues:{},logs:[],stdout:g,stderr:u,exitCode:l,durationMs:f};return l!==0&&(p.error=`Process exited with code ${String(l)}`),p}finally{o&&Cl(o,{recursive:!0,force:!0})}}var Pg=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 Eg,CRYPTO_VERSION as Ig,DEFAULT_AUTOMATION_RUNTIME as n_,deserializeEnvelope as r_,encrypt as i_,scriptRuntimeToApiName as o_,serializeEnvelope as s_}from"@kizenapps/packager";function Sl(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 a_=2*1024*1024,c_=new Set([".DS_Store",".gitignore"]);function l_(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 $g=["kizen.com","kizen.dev"];function u_(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:$g.some(r=>n===r||n.endsWith("."+r))}function d_(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let n=t.hostname.toLowerCase();return $g.some(r=>n===r||n.endsWith("."+r))}function p_(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 Tg(e,t){if(t.includes("\0"))return null;let n=t.replace(/^\/+/,""),r=e_(e,n);if(r!==e&&!r.startsWith(e+_l))return null;try{let i=await XS(r);return i!==e&&!i.startsWith(e+_l)?null:i}catch{return null}}function Ng(e,t){let n=t===e?"":t.slice(e.length+1);return n===""?!1:n.split(_l).some(i=>no.has(i))}function Og(){let e=t_(import.meta.url);return hi(QS(e),"viewer")}function Rg(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 El(e){try{return await qS(e),!0}catch{return!1}}function Dg(e,t,n,r,i,o,s,a,c,l,d){let u=gg({onChange:a,enabled:d}),f=JS(l);return(g,m)=>{(async()=>{let p=g.url??"/";try{if(!l_(g.headers.host)){m.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Forbidden"}));return}if((g.method==="POST"||g.method==="PATCH"||g.method==="DELETE")&&!p_(g.headers.origin)){m.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Forbidden"}));return}if(t(`Received request: ${p}`),p==="/api/credentials"){m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({credentials:r.current??null,activeProfile:i.current??null}));return}if(p==="/api/credential-profiles"&&g.method==="GET"){let v=await Jt();m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({profiles:v,active:i.current}));return}if(p==="/api/credentials/switch"&&g.method==="POST"){let v=[];for await(let A of g)v.push(A);let P=JSON.parse(Buffer.concat(v).toString("utf-8")||"{}").profile,w=P===void 0||P===""?await De():await Ct(P);if(w!==null){r.current=w,i.current=P??void 0;let A=i.current,_=await ht(o);await nn(o,{..._,credentialMode:"global",...A!==void 0&&{activeCredentialProfile:A}}),s({type:"credentials-updated",credentials:w,activeProfile:i.current??null})}m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({ok:w!==null}));return}if(p==="/api/bundle"){let v=hi(process.cwd(),".kizenapp","bundle.json");try{let k=await ZS(v,"utf-8");m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end(k)}catch{m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end("{}")}return}if(p==="/api/last-path"&&g.method==="POST"){let v=[];for await(let P of g)v.push(P);let k=JSON.parse(Buffer.concat(v).toString("utf-8")||"{}");if(typeof k.path=="string"){c.current=k.path;let P=await ht(o);await nn(o,{...P,lastPath:k.path})}m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end('{"ok":true}');return}if(p==="/api/encryption-target"&&g.method==="GET"){let k=(await ht(o)).encryptionTarget==="dev"?"dev":"prod";m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({target:k}));return}if(p==="/api/encryption-target"&&g.method==="POST"){let v=[];for await(let A of g)v.push(A);let k=JSON.parse(Buffer.concat(v).toString("utf-8")||"{}"),P=k!==null&&typeof k=="object"?k:{};if(P.target!=="dev"&&P.target!=="prod"){m.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"target must be one of: 'dev', 'prod'"}));return}let w=await ht(o);await nn(o,{...w,encryptionTarget:P.target}),m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end('{"ok":true}');return}if(p==="/api/execute-step"&&g.method==="POST"){let v=[];for await(let A of g)v.push(A);let k=JSON.parse(Buffer.concat(v).toString("utf-8")||"{}");if(typeof k.script!="string"){m.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Missing required field: script"}));return}let P={script:k.script,scriptRuntime:k.scriptRuntime??o_(n_),inputs:yg(k.inputs),secrets:k.secrets??{},onInstallProgress:A=>{A.kind==="start"?s({type:"venv-install-start"}):A.kind==="log"?s({type:"venv-install-log",line:A.line,stream:A.stream}):A.kind==="complete"?s({type:"venv-install-complete"}):s({type:"venv-install-error",message:A.message})}};typeof k.timeout=="number"&&k.timeout>0&&(P.timeout=Math.min(k.timeout,300*1e3));let w=await xg(P);m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify(w));return}if(p==="/api/proxy-cache/clear"){u.clear(),n({kind:"info",message:"Proxy cache cleared"}),m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end('{"ok":true}');return}if(p==="/api/local/encrypt"&&g.method==="POST"){let v=[];for await(let P of g)v.push(P);let k=JSON.parse(Buffer.concat(v).toString("utf-8")||"{}");if(typeof k.publicKeyPem!="string"||typeof k.value!="string"){m.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Missing required fields: publicKeyPem, value"}));return}try{let P=i_(k.value,k.publicKeyPem),w=s_(P);m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify(w))}catch(P){m.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:P.message}))}return}if(p==="/api/local/validate"&&g.method==="POST"){let v=[];for await(let T of g)v.push(T);let k=JSON.parse(Buffer.concat(v).toString("utf-8")||"{}");if(typeof k.value!="string"){m.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Missing required field: value"}));return}let P,w;try{P=r_(k.value)}catch(T){w=T.message}if(w!==void 0||P===void 0){m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({valid:!1,checks:[],error:w}));return}let A=T=>Buffer.from(T,"base64").length,_=[{label:"Version",expected:String(Ig),actual:String(P.v),pass:P.v===Ig},{label:"Algorithm",expected:Eg,actual:P.alg,pass:P.alg===Eg},{label:"Wrapped key",expected:"384 bytes (RSA-3072)",actual:`${String(A(P.k))} bytes`,pass:A(P.k)===384},{label:"IV",expected:"12 bytes",actual:`${String(A(P.iv))} bytes`,pass:A(P.iv)===12},{label:"Auth tag",expected:"16 bytes",actual:`${String(A(P.tag))} bytes`,pass:A(P.tag)===16},{label:"Ciphertext",expected:"\u2265 1 byte",actual:`${String(A(P.ct))} bytes`,pass:A(P.ct)>=1}];m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({valid:_.every(T=>T.pass),checks:_}));return}if(p.startsWith("/api/wizard")){let v=g.headers["x-encryption-target"],P=(Array.isArray(v)?v[0]:v)==="dev"?"dev":"prod",w=mi(P);if(!u_(w)){m.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:`Encryption API host is not allowed: ${w}`}));return}let A=p.slice(11)||"/",_=`${w}${A}`,T=g.method??"GET",L=[];for await(let ct of g)L.push(ct);let{host:$,"x-encryption-target":V,...X}=g.headers,ve=L.length>0?Buffer.concat(L):void 0,Re=ve&&ve.length>0?ve:void 0,$e;try{$e=await fetch(_,{method:T,headers:X,...Re!==void 0&&{body:Re}})}catch(ct){let mr=ct.code==="ECONNREFUSED"?`plugin-wizard is not running at ${w}`:`Failed to reach plugin-wizard: ${ct.message}`;m.writeHead(503,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:mr}));return}let Te=ws(Object.fromEntries($e.headers)),gn=await $e.arrayBuffer();m.writeHead($e.status,Te),m.end(Buffer.from(gn));return}if(p.startsWith("/api/proxy")){let v=g.headers["x-proxy-target"];if(typeof v!="string"){m.writeHead(400),m.end("Missing x-proxy-target header");return}if(!d_(v)){m.writeHead(400),m.end("Invalid proxy target");return}let k=p.slice(10)||"/",P=`${v}${k}`,w=g.method??"GET",A=[];for await(let $e of g)A.push($e);let{host:_,"x-proxy-target":T,...L}=g.headers;if(w==="GET"){let $e=`GET::${P}`,{response:Te,fromCache:gn}=await u.get($e,()=>fetch(P,{method:"GET",headers:L}));n({kind:"request",method:"GET",status:Te.status,upstreamStatus:Rg(k,Te.headers,Te.body),fromCache:gn,url:k}),m.writeHead(Te.status,Te.headers),m.end(Te.body);return}let $=A.length>0?Buffer.concat(A):void 0,V=$&&$.length>0?$:void 0,X=await fetch(P,{method:w,headers:L,...V!==void 0&&{body:V}}),ve=ws(Object.fromEntries(X.headers)),Re=await kl(X,vl);n({kind:"request",method:w,status:X.status,upstreamStatus:Rg(k,ve,Re),fromCache:!1,url:k}),m.writeHead(X.status,ve),m.end(Re);return}if(p.startsWith("/api/source/tree")&&g.method==="GET"){let k=new URL(p,"http://localhost").searchParams.get("path")??"",P=await Tg(f,k);if(P===null){m.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Invalid path"}));return}if(Ng(f,P)){m.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Path is excluded"}));return}try{let w=await YS(P,{withFileTypes:!0}),A=await Promise.all(w.filter(T=>T.isDirectory()?!no.has(T.name):T.isFile()?!c_.has(T.name):!1).map(async T=>{let L=T.isDirectory()?"dir":"file",$={name:T.name,kind:L};if(L==="file")try{let V=await Sg(hi(P,T.name));$.size=V.size}catch{}return $}));A.sort((T,L)=>T.kind!==L.kind?T.kind==="dir"?-1:1:T.name.localeCompare(L.name));let _=P===f?"":P.slice(f.length+1);m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({path:_,entries:A}))}catch(w){let A=w instanceof Error?w.message:String(w);t(`source/tree failed (${k}): ${A}`),m.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Not found"}))}return}if(p.startsWith("/api/source/file")&&g.method==="GET"){let k=new URL(p,"http://localhost").searchParams.get("path")??"";if(k===""){m.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Missing path"}));return}let P=await Tg(f,k);if(P===null){m.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Invalid path"}));return}if(Ng(f,P)){m.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Path is excluded"}));return}try{let w=await Sg(P);if(!w.isFile()){m.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Not a file"}));return}if(w.size>a_){m.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"File too large",size:w.size}));return}let A=_g(P).toLowerCase(),_=Al[A],T=Pg.has(A),L=_??(T?"text/plain; charset=utf-8":"application/octet-stream");m.writeHead(200,{"Content-Type":L,"Content-Length":String(w.size)}),Cg(P).pipe(m)}catch(w){let A=w instanceof Error?w.message:String(w);t(`source/file failed (${k}): ${A}`),m.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Not found"}))}return}let y=hi(e,p==="/"?"/index.html":p),C=await El(y)?y:hi(e,"index.html"),S=_g(C),x=Al[S]??"application/octet-stream";m.writeHead(200,{"Content-Type":x}),Cg(C).pipe(m)}catch(h){if(p.startsWith("/api/proxy")){let b=p.slice(10)||"/",y=g.method??"GET";h instanceof pi?n({kind:"info",message:`${y} ${b} \u2192 502 (response exceeded ${String(h.limit)} bytes)`}):n({kind:"request",method:y,status:502,fromCache:!1,url:b})}else n({kind:"info",message:`Error handling ${p}: ${h instanceof Error?h.message:String(h)}`});m.headersSent||(m.writeHead(502),m.end("Bad Gateway"))}})()}}import{launch as m_}from"chrome-launcher";import{createRequire as f_}from"module";import{mkdirSync as g_}from"fs";import{readFile as h_}from"fs/promises";import{dirname as y_,join as b_}from"path";import{fileURLToPath as w_}from"url";var Lg=f_(import.meta.url)("chrome-remote-interface"),v_=new Set(["content-security-policy","content-security-policy-report-only","x-frame-options"]),Fg=["kizen.dev","kizen.com"];function Bg(e){try{let{hostname:t}=new URL(e);return Fg.some(n=>t===n||t.endsWith("."+n))}catch{return!1}}async function k_(e){try{let t=b_(y_(w_(import.meta.url)),"viewer","icon.png"),n=await h_(t);await e.Browser.setDockTile({image:n.toString("base64")})}catch{}}async function jg(e){g_(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,n=await m_({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,i=null,o=null,s=null,a=null,c=0,l=!1,d=C=>{e.debugLog?.(C)},u=C=>{e.verbose&&e.debugLog?.(C)},f=()=>{o!==null&&(clearInterval(o),o=null)},g=C=>C==="chrome://new-tab-page/"||C==="chrome://newtab/",m=async C=>{f(),s=null,await k_(C),await C.Fetch.enable({patterns:Fg.flatMap(x=>[{urlPattern:`*://${x}/*`,requestStage:"Response"},{urlPattern:`*://*.${x}/*`,requestStage:"Response"}])}),C.on("Fetch.requestPaused",x=>{(async()=>{let v=x,{requestId:k,request:P,responseHeaders:w,responseStatusCode:A}=v,_=P.url;u(`Fetch ${String(A??"?")} ${_}`);let T=[],L=!1;for(let $ of w??[])if(!v_.has($.name.toLowerCase()))if($.name.toLowerCase()==="set-cookie"&&Bg(_)){let V=$.value.split(`
|
|
1218
|
+
`).trim(),d=l.length>0?`: ${l}`:"";i(new Error(`${e} exited with code ${String(c)}${d}`))}})})}var _l=null;function i_(e,t){if(fi)return t&&_l?.add(t),fi;let n=new Set;t&&n.add(t),_l=n;let r=o=>{for(let s of n)s(o)},i=gi(ks,"bin","python");return fi=(async()=>{try{let o=!1;try{await ZS(i);let s=await Oi(i);o=s!==null&&Js(s,Ir)}catch{o=!1}if(!o){await El(ks,{recursive:!0,force:!0}).catch(()=>{});let s=await Bu(e);await Pg(s,["-m","venv",ks])}return r({kind:"start"}),await Pg(i,["-m","pip","install","--disable-pip-version-check",..._g],(s,a)=>{r({kind:"log",line:s,stream:a})}),r({kind:"complete"}),i}catch(o){let s=o instanceof Error?o.message:String(o);throw r({kind:"error",message:s}),fi=null,await El(ks,{recursive:!0,force:!0}).catch(()=>{}),o}finally{_l=null}})(),fi}function o_(e){let t="__KIZEN_RESULT_START__",n="__KIZEN_RESULT_END__",r=e.indexOf(t),i=e.indexOf(n);if(r===-1||i===-1)return{userStdout:e,result:null};let o=e.slice(0,r).trimEnd(),s=e.slice(r+t.length,i).trim();try{let a=JSON.parse(s);return{userStdout:o,result:a}}catch{return{userStdout:e,result:null}}}function s_(e){return{success:!1,outputValues:{},logs:[],stdout:"",stderr:"",error:e,exitCode:1,durationMs:0}}async function Eg(e){let t=e.timeout??n_;if(!e_(e.scriptRuntime))return s_(`Unsupported runtime "${e.scriptRuntime}". Supported runtimes: ${r_.join(", ")}. Update the step's config.json "runtime" field (e.g. "python 3.13").`);let r=await i_(Sg(e.scriptRuntime),e.onInstallProgress),i=Date.now(),o;try{o=await YS(gi(XS(),"kizen-step-"));let s=gi(o,"wrapper.py"),a=gi(o,"script.py");await Promise.all([xg(s,t_,"utf-8"),xg(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:l,stdout:d,stderr:u}=await new Promise(h=>{let b=[],y=[],C=!1,S=Cg(r,[s],{env:c,cwd:o,stdio:["ignore","pipe","pipe"]}),x=setTimeout(()=>{S.kill("SIGKILL")},t);S.stdout.on("data",k=>{b.push(k)}),S.stderr.on("data",k=>{y.push(k)});let v=k=>{C||(C=!0,clearTimeout(x),h({exitCode:k??1,stdout:Buffer.concat(b).toString("utf-8"),stderr:Buffer.concat(y).toString("utf-8")}))};S.on("close",v),S.on("error",k=>{C||(C=!0,clearTimeout(x),h({exitCode:1,stdout:"",stderr:k.message}))})}),f=Date.now()-i,{userStdout:g,result:p}=o_(d);if(p){let h={success:p.success,outputValues:p.outputValues,logs:p.logs,stdout:g,stderr:u,exitCode:l,durationMs:f};return p.error!==null&&(h.error=p.error),p.httpRequests&&(h.httpRequests=p.httpRequests),h}let m={success:!1,outputValues:{},logs:[],stdout:g,stderr:u,exitCode:l,durationMs:f};return l!==0&&(m.error=`Process exited with code ${String(l)}`),m}finally{o&&El(o,{recursive:!0,force:!0})}}var Ig=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 $g,CRYPTO_VERSION as Og,DEFAULT_AUTOMATION_RUNTIME as g_,deserializeEnvelope as h_,encrypt as y_,scriptRuntimeToApiName as b_,serializeEnvelope as w_}from"@kizenapps/packager";function Il(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 v_=2*1024*1024,k_=new Set([".DS_Store",".gitignore"]);function A_(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 Fg=["kizen.com","kizen.dev"];function x_(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:Fg.some(r=>n===r||n.endsWith("."+r))}function P_(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let n=t.hostname.toLowerCase();return Fg.some(r=>n===r||n.endsWith("."+r))}function C_(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 Dg(e,t){if(t.includes("\0"))return null;let n=t.replace(/^\/+/,""),r=m_(e,n);if(r!==e&&!r.startsWith(e+Tl))return null;try{let i=await d_(r);return i!==e&&!i.startsWith(e+Tl)?null:i}catch{return null}}function Lg(e,t){let n=t===e?"":t.slice(e.length+1);return n===""?!1:n.split(Tl).some(i=>no.has(i))}function jg(){let e=f_(import.meta.url);return hi(p_(e),"viewer")}function Bg(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 Nl(e){try{return await c_(e),!0}catch{return!1}}function Mg(e,t,n,r,i,o,s,a,c,l,d){let u=bg({onChange:a,enabled:d}),f=a_(l);return(g,p)=>{(async()=>{let m=g.url??"/";try{if(!A_(g.headers.host)){p.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({error:"Forbidden"}));return}if((g.method==="POST"||g.method==="PATCH"||g.method==="DELETE")&&!C_(g.headers.origin)){p.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({error:"Forbidden"}));return}if(t(`Received request: ${m}`),m==="/api/credentials"){p.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({credentials:r.current??null,activeProfile:i.current??null}));return}if(m==="/api/credential-profiles"&&g.method==="GET"){let v=await qt();p.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({profiles:v,active:i.current}));return}if(m==="/api/credentials/switch"&&g.method==="POST"){let v=[];for await(let A of g)v.push(A);let P=JSON.parse(Buffer.concat(v).toString("utf-8")||"{}").profile,w=P===void 0||P===""?await De():await _t(P);if(w!==null){r.current=w,i.current=P??void 0;let A=i.current,_=await rt(o);await bt(o,{..._,credentialMode:"global",...A!==void 0&&{activeCredentialProfile:A}}),s({type:"credentials-updated",credentials:w,activeProfile:i.current??null})}p.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({ok:w!==null}));return}if(m==="/api/bundle"){let v=hi(process.cwd(),".kizenapp","bundle.json");try{let k=await u_(v,"utf-8");p.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),p.end(k)}catch{p.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),p.end("{}")}return}if(m==="/api/last-path"&&g.method==="POST"){let v=[];for await(let P of g)v.push(P);let k=JSON.parse(Buffer.concat(v).toString("utf-8")||"{}");if(typeof k.path=="string"&&vs(k.path,await Pl(o))){c.current=k.path;let P=await rt(o);await bt(o,{...P,lastPath:k.path})}p.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),p.end('{"ok":true}');return}if(m==="/api/encryption-target"&&g.method==="GET"){let k=(await rt(o)).encryptionTarget==="dev"?"dev":"prod";p.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({target:k}));return}if(m==="/api/encryption-target"&&g.method==="POST"){let v=[];for await(let A of g)v.push(A);let k=JSON.parse(Buffer.concat(v).toString("utf-8")||"{}"),P=k!==null&&typeof k=="object"?k:{};if(P.target!=="dev"&&P.target!=="prod"){p.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({error:"target must be one of: 'dev', 'prod'"}));return}let w=await rt(o);await bt(o,{...w,encryptionTarget:P.target}),p.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),p.end('{"ok":true}');return}if(m==="/api/execute-step"&&g.method==="POST"){let v=[];for await(let A of g)v.push(A);let k=JSON.parse(Buffer.concat(v).toString("utf-8")||"{}");if(typeof k.script!="string"){p.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({error:"Missing required field: script"}));return}let P={script:k.script,scriptRuntime:k.scriptRuntime??b_(g_),inputs:Ag(k.inputs),secrets:k.secrets??{},onInstallProgress:A=>{A.kind==="start"?s({type:"venv-install-start"}):A.kind==="log"?s({type:"venv-install-log",line:A.line,stream:A.stream}):A.kind==="complete"?s({type:"venv-install-complete"}):s({type:"venv-install-error",message:A.message})}};typeof k.timeout=="number"&&k.timeout>0&&(P.timeout=Math.min(k.timeout,300*1e3));let w=await Eg(P);p.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify(w));return}if(m==="/api/proxy-cache/clear"){u.clear(),n({kind:"info",message:"Proxy cache cleared"}),p.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),p.end('{"ok":true}');return}if(m==="/api/local/encrypt"&&g.method==="POST"){let v=[];for await(let P of g)v.push(P);let k=JSON.parse(Buffer.concat(v).toString("utf-8")||"{}");if(typeof k.publicKeyPem!="string"||typeof k.value!="string"){p.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({error:"Missing required fields: publicKeyPem, value"}));return}try{let P=y_(k.value,k.publicKeyPem),w=w_(P);p.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify(w))}catch(P){p.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({error:P.message}))}return}if(m==="/api/local/validate"&&g.method==="POST"){let v=[];for await(let T of g)v.push(T);let k=JSON.parse(Buffer.concat(v).toString("utf-8")||"{}");if(typeof k.value!="string"){p.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({error:"Missing required field: value"}));return}let P,w;try{P=h_(k.value)}catch(T){w=T.message}if(w!==void 0||P===void 0){p.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({valid:!1,checks:[],error:w}));return}let A=T=>Buffer.from(T,"base64").length,_=[{label:"Version",expected:String(Og),actual:String(P.v),pass:P.v===Og},{label:"Algorithm",expected:$g,actual:P.alg,pass:P.alg===$g},{label:"Wrapped key",expected:"384 bytes (RSA-3072)",actual:`${String(A(P.k))} bytes`,pass:A(P.k)===384},{label:"IV",expected:"12 bytes",actual:`${String(A(P.iv))} bytes`,pass:A(P.iv)===12},{label:"Auth tag",expected:"16 bytes",actual:`${String(A(P.tag))} bytes`,pass:A(P.tag)===16},{label:"Ciphertext",expected:"\u2265 1 byte",actual:`${String(A(P.ct))} bytes`,pass:A(P.ct)>=1}];p.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({valid:_.every(T=>T.pass),checks:_}));return}if(m.startsWith("/api/wizard")){let v=g.headers["x-encryption-target"],P=(Array.isArray(v)?v[0]:v)==="dev"?"dev":"prod",w=mi(P);if(!x_(w)){p.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({error:`Encryption API host is not allowed: ${w}`}));return}let A=m.slice(11)||"/",_=`${w}${A}`,T=g.method??"GET",L=[];for await(let lt of g)L.push(lt);let{host:$,"x-encryption-target":V,...X}=g.headers,ve=L.length>0?Buffer.concat(L):void 0,Re=ve&&ve.length>0?ve:void 0,$e;try{$e=await fetch(_,{method:T,headers:X,...Re!==void 0&&{body:Re}})}catch(lt){let mr=lt.code==="ECONNREFUSED"?`plugin-wizard is not running at ${w}`:`Failed to reach plugin-wizard: ${lt.message}`;p.writeHead(503,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({error:mr}));return}let Te=ws(Object.fromEntries($e.headers)),gn=await $e.arrayBuffer();p.writeHead($e.status,Te),p.end(Buffer.from(gn));return}if(m.startsWith("/api/proxy")){let v=g.headers["x-proxy-target"];if(typeof v!="string"){p.writeHead(400),p.end("Missing x-proxy-target header");return}if(!P_(v)){p.writeHead(400),p.end("Invalid proxy target");return}let k=m.slice(10)||"/",P=`${v}${k}`,w=g.method??"GET",A=[];for await(let $e of g)A.push($e);let{host:_,"x-proxy-target":T,...L}=g.headers;if(w==="GET"){let $e=`GET::${P}`,{response:Te,fromCache:gn}=await u.get($e,()=>fetch(P,{method:"GET",headers:L}));n({kind:"request",method:"GET",status:Te.status,upstreamStatus:Bg(k,Te.headers,Te.body),fromCache:gn,url:k}),p.writeHead(Te.status,Te.headers),p.end(Te.body);return}let $=A.length>0?Buffer.concat(A):void 0,V=$&&$.length>0?$:void 0,X=await fetch(P,{method:w,headers:L,...V!==void 0&&{body:V}}),ve=ws(Object.fromEntries(X.headers)),Re=await Al(X,kl);n({kind:"request",method:w,status:X.status,upstreamStatus:Bg(k,ve,Re),fromCache:!1,url:k}),p.writeHead(X.status,ve),p.end(Re);return}if(m.startsWith("/api/source/tree")&&g.method==="GET"){let k=new URL(m,"http://localhost").searchParams.get("path")??"",P=await Dg(f,k);if(P===null){p.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({error:"Invalid path"}));return}if(Lg(f,P)){p.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({error:"Path is excluded"}));return}try{let w=await l_(P,{withFileTypes:!0}),A=await Promise.all(w.filter(T=>T.isDirectory()?!no.has(T.name):T.isFile()?!k_.has(T.name):!1).map(async T=>{let L=T.isDirectory()?"dir":"file",$={name:T.name,kind:L};if(L==="file")try{let V=await Ng(hi(P,T.name));$.size=V.size}catch{}return $}));A.sort((T,L)=>T.kind!==L.kind?T.kind==="dir"?-1:1:T.name.localeCompare(L.name));let _=P===f?"":P.slice(f.length+1);p.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({path:_,entries:A}))}catch(w){let A=w instanceof Error?w.message:String(w);t(`source/tree failed (${k}): ${A}`),p.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({error:"Not found"}))}return}if(m.startsWith("/api/source/file")&&g.method==="GET"){let k=new URL(m,"http://localhost").searchParams.get("path")??"";if(k===""){p.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({error:"Missing path"}));return}let P=await Dg(f,k);if(P===null){p.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({error:"Invalid path"}));return}if(Lg(f,P)){p.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({error:"Path is excluded"}));return}try{let w=await Ng(P);if(!w.isFile()){p.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({error:"Not a file"}));return}if(w.size>v_){p.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({error:"File too large",size:w.size}));return}let A=Rg(P).toLowerCase(),_=xl[A],T=Ig.has(A),L=_??(T?"text/plain; charset=utf-8":"application/octet-stream");p.writeHead(200,{"Content-Type":L,"Content-Length":String(w.size)}),Tg(P).pipe(p)}catch(w){let A=w instanceof Error?w.message:String(w);t(`source/file failed (${k}): ${A}`),p.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),p.end(JSON.stringify({error:"Not found"}))}return}let y=hi(e,m==="/"?"/index.html":m),C=await Nl(y)?y:hi(e,"index.html"),S=Rg(C),x=xl[S]??"application/octet-stream";p.writeHead(200,{"Content-Type":x}),Tg(C).pipe(p)}catch(h){if(m.startsWith("/api/proxy")){let b=m.slice(10)||"/",y=g.method??"GET";h instanceof pi?n({kind:"info",message:`${y} ${b} \u2192 502 (response exceeded ${String(h.limit)} bytes)`}):n({kind:"request",method:y,status:502,fromCache:!1,url:b})}else n({kind:"info",message:`Error handling ${m}: ${h instanceof Error?h.message:String(h)}`});p.headersSent||(p.writeHead(502),p.end("Bad Gateway"))}})()}}import{launch as S_}from"chrome-launcher";import{createRequire as __}from"module";import{mkdirSync as E_}from"fs";import{readFile as I_}from"fs/promises";import{dirname as T_,join as N_}from"path";import{fileURLToPath as R_}from"url";var zg=__(import.meta.url)("chrome-remote-interface"),$_=new Set(["content-security-policy","content-security-policy-report-only","x-frame-options"]),Vg=["kizen.dev","kizen.com"];function Ug(e){try{let{hostname:t}=new URL(e);return Vg.some(n=>t===n||t.endsWith("."+n))}catch{return!1}}async function O_(e){try{let t=N_(T_(R_(import.meta.url)),"viewer","icon.png"),n=await I_(t);await e.Browser.setDockTile({image:n.toString("base64")})}catch{}}async function Hg(e){E_(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,n=await S_({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,i=null,o=null,s=null,a=null,c=0,l=!1,d=C=>{e.debugLog?.(C)},u=C=>{e.verbose&&e.debugLog?.(C)},f=()=>{o!==null&&(clearInterval(o),o=null)},g=C=>C==="chrome://new-tab-page/"||C==="chrome://newtab/",p=async C=>{f(),s=null,await O_(C),await C.Fetch.enable({patterns:Vg.flatMap(x=>[{urlPattern:`*://${x}/*`,requestStage:"Response"},{urlPattern:`*://*.${x}/*`,requestStage:"Response"}])}),C.on("Fetch.requestPaused",x=>{(async()=>{let v=x,{requestId:k,request:P,responseHeaders:w,responseStatusCode:A}=v,_=P.url;u(`Fetch ${String(A??"?")} ${_}`);let T=[],L=!1;for(let $ of w??[])if(!$_.has($.name.toLowerCase()))if($.name.toLowerCase()==="set-cookie"&&Ug(_)){let V=$.value.split(`
|
|
1219
1219
|
`).map(X=>/SameSite=/i.test(X)?X.replace(/SameSite=\w+/i,"SameSite=None"):X+"; SameSite=None; Secure").join(`
|
|
1220
|
-
`);T.push({name:$.name,value:V}),L=!0}else T.push($);L&&u(` rewrote Set-Cookie SameSite on ${_}`);try{let{body:$,base64Encoded:V}=await C.Fetch.getResponseBody({requestId:k});await C.Fetch.fulfillRequest({requestId:k,responseCode:A??200,responseHeaders:T,body:$,...V&&{base64Encoded:!0}})}catch($){u(` fulfillRequest failed (${$.message}), falling through`);try{await C.Fetch.continueRequest({requestId:k})}catch(V){u(` continueRequest also failed (${V.message})`)}}})()}),o=setInterval(()=>{(async()=>{try{let{cookies:x}=await C.Network.getAllCookies(),v=0;for(let k of x){if(!Bg(`https://${k.domain??""}`)||k.sameSite==="None")continue;let P=k.domain??"",w=P.startsWith(".")?P.slice(1):P;await C.Network.setCookie({url:`https://${w}`,name:k.name,value:k.value,domain:P,path:k.path??"/",secure:!0,...k.httpOnly!==void 0&&{httpOnly:k.httpOnly},...k.expirationDate!==void 0&&{expires:k.expirationDate},sameSite:"None"}),v++}v>0&&u(`cookie-patch cycle: updated ${String(v)} cookie(s) to SameSite=None`)}catch(x){u(`cookie-patch cycle failed: ${x.message}`)}})()},2e3),await C.Target.setDiscoverTargets({discover:!0});let S=x=>{if(x.type==="page"){if(g(x.url)){d(`closed stray new-tab-page target ${x.targetId}`),s!==null&&C.Target.activateTarget({targetId:s}).catch(()=>{}),C.Target.closeTarget({targetId:x.targetId}).catch(()=>{});return}s===null&&(s=x.targetId,d(`captured main target ${x.targetId} (${x.url})`))}};C.on("Target.targetCreated",x=>{let{targetInfo:v}=x;u(`target +${v.type} ${v.targetId} ${v.url}`),S(v)}),C.on("Target.targetInfoChanged",x=>{let{targetInfo:v}=x;u(`target ~${v.type} ${v.targetId} ${v.url}`),S(v)}),C.on("disconnect",()=>{l||i!==C||(d("CDP disconnected"),i=null,f(),p())})},p=()=>{if(l||a!==null)return;let C=Math.min(1e3*2**c,1e4),S=c+1;c++,d(`CDP reconnect scheduled in ${String(C)}ms (attempt #${String(S)})`),a=setTimeout(()=>{a=null,(async()=>{let x;try{x=await Lg({port:r})}catch{d(`CDP reconnect attempt #${String(S)} failed`),p();return}if(l){try{await x.close()}catch{}return}i=x;try{await m(x),d(`CDP reconnected after ${String(S)} attempt(s)`),c=0}catch{i===x&&(i=null);try{await x.close()}catch{}d(`CDP reconnect attempt #${String(S)} failed during setup`),p()}})()},C)},h=30,b=300;for(let C=0;C<h;C++){await new Promise(S=>setTimeout(S,b)),d(`CDP connect attempt ${String(C+1)}/${String(h)}`);try{let S=await Lg({port:r});i=S,e.path&&S.send("Page.navigate",{url:`${t}${e.path}`});try{await m(S),d("CDP connected")}catch{i===S&&(i=null);try{await S.close()}catch{}d("CDP setup failed after connect")}break}catch{if(C===h-1){let S=`CDP unavailable after ${String(h)} attempts \u2014 viewer running without interception (CSP/cookie rewrites disabled)`;return d(S),e.onWarn?.(S),{kill:()=>{n.kill()}}}}}return i?{kill:()=>{if(d("CDP kill requested \u2014 tearing down"),l=!0,a!==null&&(clearTimeout(a),a=null),f(),i!==null){try{i.close()}catch{}i=null}n.kill()}}:{kill:()=>{n.kill()}}}import{useCallback as A_,useState as x_}from"react";function ks(e){let[t,n]=x_([]),r=A_(i=>{n(o=>[...o,`${new Date().toLocaleTimeString()}: ${i}`].slice(-e))},[e]);return[t,r]}import{useCallback as As,useEffect as Il,useState as xs}from"react";import{Box as we,Text as ie,useInput as P_}from"ink";import{jsx as W,jsxs as Se}from"react/jsx-runtime";var mn=["apiKey","userId","businessId"],C_={apiKey:"API Key",userId:"User ID",businessId:"Business ID"},yi=({text:e})=>W(ie,{dimColor:!0,children:e}),Ps=({initialMode:e,showProfileManager:t,onComplete:n,onCancel:r})=>{let[i,o]=xs(e==="global"&&!t?{type:"loading"}:e==="global"&&t?{type:"profile-loading"}:{type:"mode-select",cursor:0}),[s,a]=xs(""),[c,l]=xs(null),[d,u]=xs(void 0),f=As(x=>{if(x==="local"){n({mode:"local",credentials:null});return}o({type:"profile-loading"})},[n]),g=As(async x=>{if(x===null){o({type:"profile-loading"});let P=await Jt();o({type:"name-entry",nameBuffer:"",existingProfiles:P});return}u(x.isDefault?void 0:x.name),o({type:"loading"});let v=x.isDefault?await De():await Ct(x.name),k=v?Math.max(0,pe.indexOf(v.environment)):0;o({type:"creds-entry",field:0,values:v??{},envCursor:k})},[]),m=As(async(x,v)=>{let k=pe[v]??"go",P={...wr(x),environment:k};o({type:"saving"});try{await tu(d??Wt,P),n({mode:"global",credentials:P,...d!==void 0&&{profileName:d}})}catch(w){l(w instanceof Error?w.message:String(w)),o({type:"creds-entry",field:0,values:x,envCursor:v})}},[n,d]);P_((x,v)=>{if(v.ctrl&&x==="c"&&process.exit(0),v.escape){if((i.type==="creds-entry"||i.type==="name-entry")&&e==="global"&&t){o({type:"profile-loading"}),p();return}r?.();return}if(i.type==="mode-select"){if(v.upArrow)o({type:"mode-select",cursor:0});else if(v.downArrow)o({type:"mode-select",cursor:1});else if(v.return){let k=i.cursor===0?"global":"local";f(k)}return}if(i.type==="profile-select"){let{profiles:k,cursor:P}=i,w=k.length,A=k.length+1;if(v.upArrow)o({...i,cursor:(P-1+A)%A});else if(v.downArrow)o({...i,cursor:(P+1)%A});else if(v.return)if(P===w)o({type:"name-entry",nameBuffer:"",existingProfiles:k});else{let _=k[P]??k[0];_&&g(_)}return}if(i.type==="name-entry"){let{nameBuffer:k,existingProfiles:P}=i;if(v.backspace||v.delete)o({type:"name-entry",nameBuffer:k.slice(0,-1),existingProfiles:P});else if(v.return){let w=k.trim();if(!w){o({...i,nameError:"Name cannot be empty"});return}if(w===Wt){o({...i,nameError:`"${Wt}" is reserved`});return}if(P.some(A=>A.name===w)){o({...i,nameError:`Profile "${w}" already exists`});return}u(w),o({type:"creds-entry",field:0,values:{},envCursor:0}),a("")}else x&&!v.ctrl&&!v.meta&&o({type:"name-entry",nameBuffer:k+x,existingProfiles:P});return}if(i.type==="creds-entry"){let{field:k,values:P,envCursor:w}=i;if(k===mn.length){v.leftArrow?o({...i,envCursor:(w-1+pe.length)%pe.length}):v.rightArrow?o({...i,envCursor:(w+1)%pe.length}):v.upArrow?(o({...i,field:k-1}),a(P[mn[k-1]]??"")):v.return&&m(P,w);return}let _=mn[k];if(!_)return;if(v.backspace||v.delete)a(T=>T.slice(0,-1));else if(v.upArrow&&k>0){let T={...P,[_]:s},L=k-1;o({...i,field:L,values:T}),a(T[mn[L]]??"")}else if(v.return||v.tab||v.downArrow){let T={...P,[_]:s},L=k+1;o({...i,field:L,values:T}),L<mn.length?a(T[mn[L]]??""):a("")}else x&&!v.ctrl&&!v.meta&&a(T=>T+x)}});let p=As(async()=>{let x=await Jt();o({type:"profile-select",profiles:x,cursor:0})},[]);if(Il(()=>{i.type==="profile-loading"&&p()},[i.type,p]),Il(()=>{e==="global"&&!t&&(async()=>{let x=await De(),v=x?Math.max(0,pe.indexOf(x.environment)):0;o({type:"creds-entry",field:0,values:x??{},envCursor:v})})()},[]),Il(()=>{i.type==="creds-entry"&&i.field===0&&a(i.values.apiKey??"")},[i.type]),i.type==="loading"||i.type==="saving"||i.type==="profile-loading"){let x=i.type==="saving"?"Saving credentials\u2026":i.type==="profile-loading"?"Loading profiles\u2026":"Loading credentials\u2026";return W(we,{paddingY:1,paddingX:2,children:W(ie,{dimColor:!0,children:x})})}if(i.type==="done")return null;if(i.type==="mode-select")return Se(we,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[W(ye,{}),Se(we,{flexDirection:"column",gap:0,children:[W(ie,{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((v,k)=>{let P=i.cursor===k;return Se(we,{gap:2,children:[W(ie,{...P&&{color:"cyan"},children:P?"\u276F":" "}),W(ie,{bold:P,...P&&{color:"cyan"},children:v.label}),W(ie,{dimColor:!0,children:v.desc})]},v.mode)})]}),W(yi,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]});if(i.type==="profile-select"){let{profiles:x,cursor:v}=i,k=x.length;return Se(we,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[W(ye,{}),Se(we,{flexDirection:"column",gap:0,children:[W(ie,{bold:!0,children:"Credential profiles"}),x.map((P,w)=>{let A=v===w;return Se(we,{gap:2,children:[W(ie,{...A&&{color:"cyan"},children:A?"\u276F":" "}),W(ie,{bold:A,...A&&{color:"cyan"},children:P.isDefault?"Default":P.name}),W(ie,{dimColor:!0,children:P.path})]},P.name)}),Se(we,{gap:2,children:[W(ie,{...v===k&&{color:"cyan"},children:v===k?"\u276F":" "}),W(ie,{bold:v===k,...v===k&&{color:"cyan"},children:"+ Add new profile"})]})]}),W(yi,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(i.type==="name-entry"){let{nameBuffer:x,nameError:v}=i;return Se(we,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[W(ye,{}),W(we,{flexDirection:"column",gap:0,children:W(ie,{bold:!0,children:"New credential profile"})}),v&&Se(ie,{color:"red",children:["Error: ",v]}),Se(we,{gap:2,children:[W(we,{width:12,children:W(ie,{bold:!0,color:"cyan",children:"Profile name"})}),W(ie,{color:"cyan",children:">"}),W(ie,{children:x}),W(ie,{color:"cyan",children:"\u2588"})]}),W(yi,{text:"Type a name \xB7 Enter to confirm \xB7 Esc to go back"})]})}let{field:h,values:b,envCursor:y}=i,C=h===mn.length,S=d??Wt;return Se(we,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[W(ye,{}),Se(we,{flexDirection:"column",gap:0,children:[W(ie,{bold:!0,children:d!==void 0?`Profile: ${d}`:"Global credentials"}),Se(ie,{dimColor:!0,children:["Saved to:"," ",d!==void 0?`~/.kizenappbuilder/${d}.json`:Kt]})]}),c&&Se(ie,{color:"red",children:["Error: ",c]}),Se(we,{flexDirection:"column",gap:0,children:[mn.map((x,v)=>{let k=h===v,P=k?s:b[x]??"";return Se(we,{gap:2,children:[W(we,{width:12,children:W(ie,{bold:k,...k&&{color:"cyan"},children:C_[x]})}),W(ie,{...k&&{color:"cyan"},children:">"}),W(ie,{children:P}),k&&W(ie,{color:"cyan",children:"\u2588"})]},x)}),Se(we,{gap:2,children:[W(we,{width:12,children:W(ie,{bold:C,...C&&{color:"cyan"},children:"Environment"})}),W(ie,{...C&&{color:"cyan"},children:">"}),W(we,{gap:1,children:pe.map((x,v)=>{let k=v===y;return C?W(ie,{bold:k,...k&&{color:"cyan"},children:k?`[${x}]`:x},x):W(ie,{dimColor:!k,bold:k,children:x},x)})})]})]}),C?W(yi,{text:"\u2190\u2192 to select \xB7 \u2191\u2193 to move \xB7 Enter to save \xB7 Esc to cancel"}):W(yi,{text:"\u2191\u2193 to move \xB7 Backspace to delete \xB7 Esc to cancel"}),Se(ie,{dimColor:!0,children:["Profile: ",S]})]})};import{jsx as ne,jsxs as be}from"react/jsx-runtime";var R_=[".kizenapp",".git"],zg=({port:e,pluginDir:t,outputDir:n,credentials:r,credentialMode:i,activeCredentialProfile:o,lastPath:s,debug:a=!1,verbose:c=!1,autoViewer:l=!0,cacheEnabled:d=!0})=>{let u=Ft(r),f=Ft(o),g=Ft(s),[m,p]=Ve("main"),[h,b]=Ve(i),[y,C]=Ve("starting"),[S,x]=Ve(null),[v,k]=ks(50),[P,w]=ks(50),[A,_]=ks(50),[T,L]=Ve([]),[$,V]=Ve("pending"),[X,ve]=Ve(null),[Re,$e]=Ve(null),[Te,gn]=Ve(null),[ct,mr]=Ve(null),[fr,jt]=Ve(0),[E,N]=Ve(0),[B,R]=Ve(0),[O,D]=Ve(0),M=Ft(!1),Y=Ft(!1),G=Ft(null),Z=Ft(null),J=Ft(new Set),le=Ft([]),se=pr(j=>{let ae=JSON.stringify(j);if(J.current.size===0){le.current=[...le.current,ae].slice(-50);return}let Mt=!1;for(let lt of J.current)if(lt.readyState===1)try{lt.send(ae)}catch{J.current.delete(lt),Mt=!0}Mt&&jt(J.current.size)},[]),Fe=k,Hn=pr(()=>{G.current?.kill(),G.current=null,jg({port:e,userDataDir:Mg(n,".chrome"),broadcast:se,onWarn:j=>{k(`\u26A0 ${j}`)},...g.current!==void 0&&{path:g.current},...a&&{debugLog:_},...c&&{verbose:!0}}).then(j=>{G.current=j})},[e,n,se,a,c,_,k]);Cs(()=>{let j=()=>{G.current?.kill()};return process.on("exit",j),()=>{process.off("exit",j)}},[]),__((j,ae)=>{(j==="q"||ae.ctrl&&j==="c")&&process.exit(0),j==="c"&&p("editing"),j==="v"&&Hn()},{isActive:m==="main"}),Cs(()=>{y!=="running"||Y.current||!l||(Y.current=!0,Hn())},[y,l,Hn]);let Ns=pr(j=>{u.current=j.credentials,f.current=j.profileName,p("main"),b(j.mode);let ae=j.profileName;nn(n,{credentialMode:j.mode,...ae!==void 0&&{activeCredentialProfile:ae}}),se({type:"credentials-updated",credentials:j.credentials})},[n,se]),$l=pr(j=>{L(ae=>[...ae,`${new Date().toLocaleTimeString()}: ${Sl(j)}`].slice(-50)),j.kind==="request"&&(j.fromCache?R(ae=>ae+1):D(ae=>ae+1)),se({type:"proxy-log",entry:j})},[se]),hn=pr(j=>{w(j),se({type:"log",message:j})},[w,se]),Rs=pr(()=>{M.current||(M.current=!0,V("building"),ve(null),$e(null),hn("Build started"),io(t,n).then(({bundleSize:j})=>{hn(`Build finished \u2014 bundle: ${ci(j)}`),V("done"),gn(new Date),mr(j),hn("Notifying viewers to reload"),se({type:"rebuild"})}).catch(j=>{j instanceof E_?($e(j.issues),ve(null)):(ve(j instanceof Error?j.message:String(j)),$e(null)),V("error")}).finally(()=>{M.current=!1}))},[t,n,hn,se]);if(Cs(()=>{Rs();let j=I_(t,{recursive:!0},(ae,Mt)=>{if(!Mt)return;let lt=Mt.replace(/\\/g,"/");R_.some(wi=>lt.startsWith(wi))||(hn(`File change detected: ${Mt}`),Z.current!==null&&clearTimeout(Z.current),Z.current=setTimeout(Rs,150))});return j.on("error",ae=>{hn(`File watcher error \u2014 rebuilds have stopped: ${ae.message}`)}),()=>{j.close(),Z.current!==null&&clearTimeout(Z.current)}},[t,Rs,hn]),Cs(()=>{let j=Og();El(Mg(j,"index.html")).then(ae=>{if(!ae){x("Viewer not built. Run 'pnpm build:viewer' first."),C("error");return}let Mt=Dg(j,Fe,$l,u,f,n,se,N,g,t,d),lt=T_(Mt),wi=new N_({server:lt});return wi.on("connection",yn=>{for(let Oh of le.current)yn.readyState===1&&yn.send(Oh);le.current=[],Fe("Viewer connected for live reload"),J.current.add(yn),jt(J.current.size),yn.on("close",()=>{J.current.delete(yn),jt(J.current.size)})}),lt.listen(e,"127.0.0.1",()=>{C("running"),Fe(`Server started on 127.0.0.1:${String(e)}`)}),lt.on("error",yn=>{x(yn.message),C("error")}),()=>{wi.close(),lt.close()}})},[e,Fe,$l,se,n,t,d]),m==="editing")return ne(Ps,{...h!==void 0&&{initialMode:h},showProfileManager:h==="global",onComplete:Ns,onCancel:()=>{p("main")}});let $s=Te!==null?Math.round((Date.now()-Te.getTime())/1e3):null,$h=$s===null?"":$s<5?" (just now)":` (${String($s)}s ago)`,Ol=Re?.filter(j=>j.severity==="error").length??0;return be(Ee,{flexDirection:"column",paddingY:1,paddingX:2,children:[ne(ye,{marginBottom:1}),be(Ee,{flexDirection:"column",children:[be(Ee,{gap:2,marginBottom:0,children:[ne(te,{bold:!0,dimColor:!0,children:"App Build"}),$==="pending"&&ne(te,{dimColor:!0,children:"waiting\u2026"}),$==="building"&&be(Ee,{gap:1,children:[ne(wt,{}),ne(te,{children:"Building plugin package\u2026"})]}),$==="done"&&be(Ee,{gap:1,children:[ne(te,{color:"green",children:"\u2713 Built"}),Te!==null&&be(te,{dimColor:!0,children:["at ",Te.toLocaleTimeString(),$h]}),ct!==null&&be(te,{dimColor:!0,children:["\xB7 bundle: ",ci(ct)]})]}),$==="error"&&(Re!==null?be(te,{color:"red",children:["\u2717 ",Ol," validation ",Ol===1?"error":"errors"]}):be(te,{color:"red",children:["\u2717 ",X??"unknown error"]}))]}),Re!==null&&ne(ar,{issues:Re}),ne(Ee,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:P.slice(-8).map((j,ae)=>ne(te,{dimColor:!0,wrap:"truncate",children:j},ae))})]}),be(Ee,{marginTop:1,flexDirection:"column",children:[be(Ee,{gap:2,children:[ne(te,{bold:!0,dimColor:!0,children:"Web Server"}),y==="starting"&&ne(te,{dimColor:!0,children:"starting\u2026"}),y==="running"&&be(Ee,{gap:2,children:[ne(te,{color:"green",children:"\u2713 Running"}),be(te,{dimColor:!0,children:["\u25CF ",fr," viewer",fr!==1?"s":""]})]}),y==="error"&&be(te,{color:"red",children:["\u2717 ",S??"Server error"]})]}),ne(Ee,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:v.slice(-8).map((j,ae)=>ne(te,{dimColor:!0,wrap:"truncate",children:j},ae))})]}),be(Ee,{marginTop:1,flexDirection:"column",children:[be(Ee,{gap:2,children:[ne(te,{bold:!0,dimColor:!0,children:"Network Proxy"}),ne(te,{color:"green",children:"\u2713 Active"}),ne(te,{dimColor:!0,children:d?`\u25CF ${String(E)} key${E!==1?"s":""} in the network cache \xB7 ${String(B)} hit \xB7 ${String(O)} miss`:`\u25CF network cache disabled \xB7 ${String(O)} request${O!==1?"s":""}`})]}),ne(Ee,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:T.length===0?ne(te,{dimColor:!0,children:" No requests yet."}):T.slice(-8).map((j,ae)=>ne(te,{dimColor:!0,wrap:"truncate",children:j},ae))})]}),a&&be(Ee,{marginTop:1,flexDirection:"column",children:[be(Ee,{gap:2,children:[ne(te,{bold:!0,dimColor:!0,children:"CDP Debug"}),be(te,{dimColor:!0,children:["\u25CF ",A.length," event(s)"]})]}),ne(Ee,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:A.length===0?ne(te,{dimColor:!0,children:" No CDP events yet."}):A.slice(-8).map((j,ae)=>ne(te,{dimColor:!0,wrap:"truncate",children:j},ae))})]}),be(Ee,{marginTop:1,gap:1,children:[ne(te,{dimColor:!0,children:"["}),ne(te,{children:"q"}),ne(te,{dimColor:!0,children:"] quit ["}),ne(te,{children:"c"}),ne(te,{dimColor:!0,children:"] credentials ["}),ne(te,{children:"v"}),be(te,{dimColor:!0,children:["] ",fr===0?"open viewer":"relaunch viewer"]})]})]})};async function Ug(e){return new Promise(t=>{let n=null,r=o=>{n?.(),t(o)},{unmount:i}=Hg(Vg(Ps,{...e!==void 0&&{initialMode:e},onComplete:r}),{exitOnCtrlC:!1});n=i})}function Kg(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(),i=`${r}/.kizenapp`;Ze(r);let o=null,s,a,{lastPath:c}=await ht(i);if(t.credentials)o=await Gt(t.credentials);else{let m=await ht(i);if(m.credentialMode==="local")s="local";else if(m.credentialMode==="global"){if(s="global",a=m.activeCredentialProfile,a?(o=await Ct(a),o||(o=await De(),a=void 0)):o=await De(),!o){let p=await Ug("global");o=p.credentials,a=p.profileName}}else{let p=await Ug();o=p.credentials,s=p.mode,a=p.profileName;let h=p.profileName;await nn(i,{credentialMode:p.mode,...h!==void 0&&{activeCredentialProfile:h}})}}let l=t.verbose===!0,d=l||t.debug===!0,u=t.viewer!==!1,f=t.cache!==!1,{waitUntilExit:g}=Hg(Vg(zg,{port:n,pluginDir:r,outputDir:i,credentials:o,...s!==void 0&&{credentialMode:s},...a!==void 0&&{activeCredentialProfile:a},...c!==void 0&&{lastPath:c},debug:d,verbose:l,autoViewer:u,cacheEnabled:f}),{exitOnCtrlC:!1});await g()})}import{createElement as K_}from"react";import{render as W_}from"ink";import{useCallback as _s,useEffect as qg,useState as Es}from"react";import{Box as xt,Text as oe,useApp as j_,useInput as M_}from"ink";import{encrypt as $_,serializeEnvelope as O_}from"@kizenapps/packager";function D_(e){let t=e;return t.code==="ECONNREFUSED"||t.cause?.code==="ECONNREFUSED"}function Wg(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 Gg(e,t,n){try{return await fetch(`${e}${t}`,n)}catch(r){throw new Error(D_(r)?`Plugin-wizard is not running at ${e}`:`Failed to reach plugin-wizard: ${r.message}${ki()==="unavailable"?` ${vi}`:""}`)}}async function Jg(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 L_(e,t,n){let r=mi(e.stage),i=await Gg(r,"/get-public-key",{method:"POST",headers:Wg(t),body:JSON.stringify({api_name:n})}),o=await Jg(i);if(!i.ok||typeof o.public_key!="string"){let s=typeof o.error=="string"?o.error:`HTTP ${String(i.status)}`;throw new Error(`Failed to fetch public key: ${s}`)}return o.public_key}function B_(e,t){let n=$_(t,e),r=O_(n);if(typeof r.value!="string")throw new Error("Unexpected serialized envelope shape from @kizenapps/packager");return r.value}async function F_(e,t,n,r){let i=mi(e.stage),o=await Gg(i,"/encrypt",{method:"POST",headers:Wg(t),body:JSON.stringify({api_name:n,value:r})}),s=await Jg(o);if(!o.ok||s.encrypted!==!0||typeof s.value!="string"){let a=typeof s.error=="string"?s.error:`HTTP ${String(o.status)}`;throw new Error(`Encryption via plugin-wizard failed: ${a}`)}return s.value}async function Ss(e,t,n,r,i){if(e.isRemote)return i?.("encrypting"),F_(e,t,n,r);i?.("fetching-key");let o=await L_(e,t,n);return i?.("encrypting"),B_(o,r)}import{Fragment as Is,jsx as re,jsxs as Ie}from"react/jsx-runtime";var Tl=({text:e})=>re(oe,{dimColor:!0,children:e}),Yg=({ctx:e,stageDefaulted:t,credentialsPath:n,initialApiName:r,defaultApiName:i,initialValue:o,onDone:s})=>{let a=j_(),[c,l]=Es({type:"loading"}),[d,u]=Es(null),[f,g]=Es(r??""),[m,p]=Es(o??""),h=_s(k=>{process.exitCode=1,l({type:"error",message:k instanceof Error?k.message:String(k)})},[]),b=_s(async(k,P,w)=>{try{let A=await Ss(e,k,P,w,L=>{l(L==="fetching-key"?{type:"fetching-key"}:{type:"encrypting"})}),_=JSON.stringify({encrypted:!0,value:A},null,2);s?.(A);let T=await es(_);l({type:"done",envelope:_,copied:T})}catch(A){h(A)}},[e,h,s]),y=_s((k,P,w)=>{if(P.trim()===""){l({type:"api-name-entry",buffer:i??""});return}if(w===""){l({type:"value-entry",buffer:""});return}b(k,P.trim(),w)},[i,b]),C=_s(async k=>{try{l({type:"loading"});let P=k.isDefault?await De():await Ct(k.name);if(P===null)throw new Error(`Could not load credential profile: ${k.name}`);u(P),y(P,f,m)}catch(P){h(P)}},[f,m,y,h]);qg(()=>{(async()=>{try{if(n!==void 0){let w;try{w=await Gt(n)}catch(A){throw new Error(`Could not load credentials from ${n}: ${A instanceof Error?A.message:String(A)}`)}u(w),y(w,f,m);return}let k=await Jt();if(k.length===0)throw new Error("No credential profiles found. Create ~/.kizenappbuilder/credentials.json first.");let[P]=k;if(k.length===1&&P!==void 0){let w=P.isDefault?await De():await Ct(P.name);if(w===null)throw new Error(`Could not load credential profile: ${P.name}`);u(w),y(w,f,m);return}l({type:"profile-select",profiles:k,cursor:0})}catch(k){h(k)}})()},[]),qg(()=>{(c.type==="done"||c.type==="error")&&a.exit()},[c,a]),M_((k,P)=>{if(P.ctrl&&k==="c"){process.exitCode=130,a.exit();return}if(c.type==="profile-select"){let{profiles:w,cursor:A}=c;if(P.upArrow)l({...c,cursor:(A-1+w.length)%w.length});else if(P.downArrow)l({...c,cursor:(A+1)%w.length});else if(P.return){let _=w[A];_!==void 0&&C(_)}return}if(c.type==="api-name-entry"){let{buffer:w}=c;if(P.backspace||P.delete)l({type:"api-name-entry",buffer:w.slice(0,-1)});else if(P.return){let A=w.trim();if(A===""){l({type:"api-name-entry",buffer:w,error:"api_name cannot be empty"});return}g(A),d?y(d,A,m):h(new Error("Internal error: credentials were not loaded"))}else k&&!P.ctrl&&!P.meta&&l({type:"api-name-entry",buffer:w+k});return}if(c.type==="value-entry"){let{buffer:w}=c;if(P.backspace||P.delete)l({type:"value-entry",buffer:w.slice(0,-1)});else if(P.return){if(w===""){l({type:"value-entry",buffer:w,error:"secret cannot be empty"});return}p(w),d?y(d,f,w):h(new Error("Internal error: credentials were not loaded"))}else k&&!P.ctrl&&!P.meta&&l({type:"value-entry",buffer:w+k});return}});let S=e.isRemote?"remote Kizen API":"on-machine",x=t===!0?`${e.stage} (default)`:e.stage,v=k=>Ie(xt,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[re(ye,{}),Ie(oe,{dimColor:!0,children:["Mode: ",S," Stage: ",x]}),k]});if(c.type==="loading")return v(Ie(xt,{gap:1,children:[re(wt,{}),re(oe,{dimColor:!0,children:"Loading credentials\u2026"})]}));if(c.type==="profile-select"){let{profiles:k,cursor:P}=c;return v(Ie(Is,{children:[re(oe,{bold:!0,children:"Credential profile"}),re(xt,{flexDirection:"column",children:k.map((w,A)=>{let _=P===A;return Ie(xt,{gap:2,children:[re(oe,{..._&&{color:"cyan"},children:_?"\u276F":" "}),re(oe,{bold:_,..._&&{color:"cyan"},children:w.isDefault?"Default":w.name}),re(oe,{dimColor:!0,children:w.path})]},w.name)})}),re(Tl,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]}))}return c.type==="api-name-entry"?v(Ie(Is,{children:[re(oe,{bold:!0,children:"Plugin api_name"}),c.error!==void 0&&Ie(oe,{color:"red",children:["Error: ",c.error]}),Ie(xt,{gap:1,children:[re(oe,{color:"cyan",children:">"}),re(oe,{children:c.buffer}),re(oe,{color:"cyan",children:"\u2588"})]}),re(Tl,{text:"Type the api_name \xB7 Enter to confirm \xB7 Ctrl+C to quit"})]})):c.type==="value-entry"?v(Ie(Is,{children:[re(oe,{bold:!0,children:"Secret value"}),c.error!==void 0&&Ie(oe,{color:"red",children:["Error: ",c.error]}),Ie(xt,{gap:1,children:[re(oe,{color:"cyan",children:">"}),re(oe,{children:"\u2022".repeat(c.buffer.length)}),re(oe,{color:"cyan",children:"\u2588"})]}),re(Tl,{text:"Input hidden \xB7 Enter to encrypt \xB7 Ctrl+C to quit"})]})):c.type==="fetching-key"?v(Ie(xt,{gap:1,children:[re(wt,{}),Ie(oe,{children:["Fetching ",e.stage," public key for ",re(oe,{bold:!0,children:f}),"\u2026"]})]})):c.type==="encrypting"?v(Ie(xt,{gap:1,children:[re(wt,{}),re(oe,{children:"Encrypting\u2026"})]})):c.type==="error"?v(Ie(xt,{gap:1,children:[re(oe,{color:"red",children:"\u2717"}),re(oe,{color:"red",children:c.message})]})):v(Ie(Is,{children:[Ie(xt,{gap:1,children:[re(oe,{color:"green",children:"\u2713"}),re(oe,{bold:!0,children:"Encrypted secret ready"})]}),c.copied?re(oe,{color:"green",children:"\u2713 Copied to clipboard \u2014 paste it into the secret value in your kizen.json."}):re(oe,{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):"}),re(oe,{children:c.envelope})]}))};import{readFile as z_,writeFile as U_}from"fs/promises";import{join as V_}from"path";function Zg(e){return{encrypted:!0,value:e}}function Xg(e){return JSON.stringify(Zg(e))}async function Nl(e,t){await U_(e,`${JSON.stringify(Zg(t),null,2)}
|
|
1221
|
-
`,"utf-8")}var
|
|
1222
|
-
`}async function
|
|
1223
|
-
`),a=
|
|
1220
|
+
`);T.push({name:$.name,value:V}),L=!0}else T.push($);L&&u(` rewrote Set-Cookie SameSite on ${_}`);try{let{body:$,base64Encoded:V}=await C.Fetch.getResponseBody({requestId:k});await C.Fetch.fulfillRequest({requestId:k,responseCode:A??200,responseHeaders:T,body:$,...V&&{base64Encoded:!0}})}catch($){u(` fulfillRequest failed (${$.message}), falling through`);try{await C.Fetch.continueRequest({requestId:k})}catch(V){u(` continueRequest also failed (${V.message})`)}}})()}),o=setInterval(()=>{(async()=>{try{let{cookies:x}=await C.Network.getAllCookies(),v=0;for(let k of x){if(!Ug(`https://${k.domain??""}`)||k.sameSite==="None")continue;let P=k.domain??"",w=P.startsWith(".")?P.slice(1):P;await C.Network.setCookie({url:`https://${w}`,name:k.name,value:k.value,domain:P,path:k.path??"/",secure:!0,...k.httpOnly!==void 0&&{httpOnly:k.httpOnly},...k.expirationDate!==void 0&&{expires:k.expirationDate},sameSite:"None"}),v++}v>0&&u(`cookie-patch cycle: updated ${String(v)} cookie(s) to SameSite=None`)}catch(x){u(`cookie-patch cycle failed: ${x.message}`)}})()},2e3),await C.Target.setDiscoverTargets({discover:!0});let S=x=>{if(x.type==="page"){if(g(x.url)){d(`closed stray new-tab-page target ${x.targetId}`),s!==null&&C.Target.activateTarget({targetId:s}).catch(()=>{}),C.Target.closeTarget({targetId:x.targetId}).catch(()=>{});return}s===null&&(s=x.targetId,d(`captured main target ${x.targetId} (${x.url})`))}};C.on("Target.targetCreated",x=>{let{targetInfo:v}=x;u(`target +${v.type} ${v.targetId} ${v.url}`),S(v)}),C.on("Target.targetInfoChanged",x=>{let{targetInfo:v}=x;u(`target ~${v.type} ${v.targetId} ${v.url}`),S(v)}),C.on("disconnect",()=>{l||i!==C||(d("CDP disconnected"),i=null,f(),m())})},m=()=>{if(l||a!==null)return;let C=Math.min(1e3*2**c,1e4),S=c+1;c++,d(`CDP reconnect scheduled in ${String(C)}ms (attempt #${String(S)})`),a=setTimeout(()=>{a=null,(async()=>{let x;try{x=await zg({port:r})}catch{d(`CDP reconnect attempt #${String(S)} failed`),m();return}if(l){try{await x.close()}catch{}return}i=x;try{await p(x),d(`CDP reconnected after ${String(S)} attempt(s)`),c=0}catch{i===x&&(i=null);try{await x.close()}catch{}d(`CDP reconnect attempt #${String(S)} failed during setup`),m()}})()},C)},h=30,b=300;for(let C=0;C<h;C++){await new Promise(S=>setTimeout(S,b)),d(`CDP connect attempt ${String(C+1)}/${String(h)}`);try{let S=await zg({port:r});i=S,e.path&&S.send("Page.navigate",{url:`${t}${e.path}`});try{await p(S),d("CDP connected")}catch{i===S&&(i=null);try{await S.close()}catch{}d("CDP setup failed after connect")}break}catch{if(C===h-1){let S=`CDP unavailable after ${String(h)} attempts \u2014 viewer running without interception (CSP/cookie rewrites disabled)`;return d(S),e.onWarn?.(S),{kill:()=>{n.kill()}}}}}return i?{kill:()=>{if(d("CDP kill requested \u2014 tearing down"),l=!0,a!==null&&(clearTimeout(a),a=null),f(),i!==null){try{i.close()}catch{}i=null}n.kill()}}:{kill:()=>{n.kill()}}}import{useCallback as D_,useState as L_}from"react";function As(e){let[t,n]=L_([]),r=D_(i=>{n(o=>[...o,`${new Date().toLocaleTimeString()}: ${i}`].slice(-e))},[e]);return[t,r]}import{useCallback as xs,useEffect as Rl,useState as Ps}from"react";import{Box as we,Text as oe,useInput as B_}from"ink";import{jsx as W,jsxs as Se}from"react/jsx-runtime";var mn=["apiKey","userId","businessId"],F_={apiKey:"API Key",userId:"User ID",businessId:"Business ID"},yi=({text:e})=>W(oe,{dimColor:!0,children:e}),Cs=({initialMode:e,showProfileManager:t,onComplete:n,onCancel:r})=>{let[i,o]=Ps(e==="global"&&!t?{type:"loading"}:e==="global"&&t?{type:"profile-loading"}:{type:"mode-select",cursor:0}),[s,a]=Ps(""),[c,l]=Ps(null),[d,u]=Ps(void 0),f=xs(x=>{if(x==="local"){n({mode:"local",credentials:null});return}o({type:"profile-loading"})},[n]),g=xs(async x=>{if(x===null){o({type:"profile-loading"});let P=await qt();o({type:"name-entry",nameBuffer:"",existingProfiles:P});return}u(x.isDefault?void 0:x.name),o({type:"loading"});let v=x.isDefault?await De():await _t(x.name),k=v?Math.max(0,pe.indexOf(v.environment)):0;o({type:"creds-entry",field:0,values:v??{},envCursor:k})},[]),p=xs(async(x,v)=>{let k=pe[v]??"go",P={...wr(x),environment:k};o({type:"saving"});try{await iu(d??Gt,P),n({mode:"global",credentials:P,...d!==void 0&&{profileName:d}})}catch(w){l(w instanceof Error?w.message:String(w)),o({type:"creds-entry",field:0,values:x,envCursor:v})}},[n,d]);B_((x,v)=>{if(v.ctrl&&x==="c"&&process.exit(0),v.escape){if((i.type==="creds-entry"||i.type==="name-entry")&&e==="global"&&t){o({type:"profile-loading"}),m();return}r?.();return}if(i.type==="mode-select"){if(v.upArrow)o({type:"mode-select",cursor:0});else if(v.downArrow)o({type:"mode-select",cursor:1});else if(v.return){let k=i.cursor===0?"global":"local";f(k)}return}if(i.type==="profile-select"){let{profiles:k,cursor:P}=i,w=k.length,A=k.length+1;if(v.upArrow)o({...i,cursor:(P-1+A)%A});else if(v.downArrow)o({...i,cursor:(P+1)%A});else if(v.return)if(P===w)o({type:"name-entry",nameBuffer:"",existingProfiles:k});else{let _=k[P]??k[0];_&&g(_)}return}if(i.type==="name-entry"){let{nameBuffer:k,existingProfiles:P}=i;if(v.backspace||v.delete)o({type:"name-entry",nameBuffer:k.slice(0,-1),existingProfiles:P});else if(v.return){let w=k.trim();if(!w){o({...i,nameError:"Name cannot be empty"});return}if(w===Gt){o({...i,nameError:`"${Gt}" is reserved`});return}if(P.some(A=>A.name===w)){o({...i,nameError:`Profile "${w}" already exists`});return}u(w),o({type:"creds-entry",field:0,values:{},envCursor:0}),a("")}else x&&!v.ctrl&&!v.meta&&o({type:"name-entry",nameBuffer:k+x,existingProfiles:P});return}if(i.type==="creds-entry"){let{field:k,values:P,envCursor:w}=i;if(k===mn.length){v.leftArrow?o({...i,envCursor:(w-1+pe.length)%pe.length}):v.rightArrow?o({...i,envCursor:(w+1)%pe.length}):v.upArrow?(o({...i,field:k-1}),a(P[mn[k-1]]??"")):v.return&&p(P,w);return}let _=mn[k];if(!_)return;if(v.backspace||v.delete)a(T=>T.slice(0,-1));else if(v.upArrow&&k>0){let T={...P,[_]:s},L=k-1;o({...i,field:L,values:T}),a(T[mn[L]]??"")}else if(v.return||v.tab||v.downArrow){let T={...P,[_]:s},L=k+1;o({...i,field:L,values:T}),L<mn.length?a(T[mn[L]]??""):a("")}else x&&!v.ctrl&&!v.meta&&a(T=>T+x)}});let m=xs(async()=>{let x=await qt();o({type:"profile-select",profiles:x,cursor:0})},[]);if(Rl(()=>{i.type==="profile-loading"&&m()},[i.type,m]),Rl(()=>{e==="global"&&!t&&(async()=>{let x=await De(),v=x?Math.max(0,pe.indexOf(x.environment)):0;o({type:"creds-entry",field:0,values:x??{},envCursor:v})})()},[]),Rl(()=>{i.type==="creds-entry"&&i.field===0&&a(i.values.apiKey??"")},[i.type]),i.type==="loading"||i.type==="saving"||i.type==="profile-loading"){let x=i.type==="saving"?"Saving credentials\u2026":i.type==="profile-loading"?"Loading profiles\u2026":"Loading credentials\u2026";return W(we,{paddingY:1,paddingX:2,children:W(oe,{dimColor:!0,children:x})})}if(i.type==="done")return null;if(i.type==="mode-select")return Se(we,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[W(ye,{}),Se(we,{flexDirection:"column",gap:0,children:[W(oe,{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((v,k)=>{let P=i.cursor===k;return Se(we,{gap:2,children:[W(oe,{...P&&{color:"cyan"},children:P?"\u276F":" "}),W(oe,{bold:P,...P&&{color:"cyan"},children:v.label}),W(oe,{dimColor:!0,children:v.desc})]},v.mode)})]}),W(yi,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]});if(i.type==="profile-select"){let{profiles:x,cursor:v}=i,k=x.length;return Se(we,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[W(ye,{}),Se(we,{flexDirection:"column",gap:0,children:[W(oe,{bold:!0,children:"Credential profiles"}),x.map((P,w)=>{let A=v===w;return Se(we,{gap:2,children:[W(oe,{...A&&{color:"cyan"},children:A?"\u276F":" "}),W(oe,{bold:A,...A&&{color:"cyan"},children:P.isDefault?"Default":P.name}),W(oe,{dimColor:!0,children:P.path})]},P.name)}),Se(we,{gap:2,children:[W(oe,{...v===k&&{color:"cyan"},children:v===k?"\u276F":" "}),W(oe,{bold:v===k,...v===k&&{color:"cyan"},children:"+ Add new profile"})]})]}),W(yi,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(i.type==="name-entry"){let{nameBuffer:x,nameError:v}=i;return Se(we,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[W(ye,{}),W(we,{flexDirection:"column",gap:0,children:W(oe,{bold:!0,children:"New credential profile"})}),v&&Se(oe,{color:"red",children:["Error: ",v]}),Se(we,{gap:2,children:[W(we,{width:12,children:W(oe,{bold:!0,color:"cyan",children:"Profile name"})}),W(oe,{color:"cyan",children:">"}),W(oe,{children:x}),W(oe,{color:"cyan",children:"\u2588"})]}),W(yi,{text:"Type a name \xB7 Enter to confirm \xB7 Esc to go back"})]})}let{field:h,values:b,envCursor:y}=i,C=h===mn.length,S=d??Gt;return Se(we,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[W(ye,{}),Se(we,{flexDirection:"column",gap:0,children:[W(oe,{bold:!0,children:d!==void 0?`Profile: ${d}`:"Global credentials"}),Se(oe,{dimColor:!0,children:["Saved to:"," ",d!==void 0?`~/.kizenappbuilder/${d}.json`:Wt]})]}),c&&Se(oe,{color:"red",children:["Error: ",c]}),Se(we,{flexDirection:"column",gap:0,children:[mn.map((x,v)=>{let k=h===v,P=k?s:b[x]??"";return Se(we,{gap:2,children:[W(we,{width:12,children:W(oe,{bold:k,...k&&{color:"cyan"},children:F_[x]})}),W(oe,{...k&&{color:"cyan"},children:">"}),W(oe,{children:P}),k&&W(oe,{color:"cyan",children:"\u2588"})]},x)}),Se(we,{gap:2,children:[W(we,{width:12,children:W(oe,{bold:C,...C&&{color:"cyan"},children:"Environment"})}),W(oe,{...C&&{color:"cyan"},children:">"}),W(we,{gap:1,children:pe.map((x,v)=>{let k=v===y;return C?W(oe,{bold:k,...k&&{color:"cyan"},children:k?`[${x}]`:x},x):W(oe,{dimColor:!k,bold:k,children:x},x)})})]})]}),C?W(yi,{text:"\u2190\u2192 to select \xB7 \u2191\u2193 to move \xB7 Enter to save \xB7 Esc to cancel"}):W(yi,{text:"\u2191\u2193 to move \xB7 Backspace to delete \xB7 Esc to cancel"}),Se(oe,{dimColor:!0,children:["Profile: ",S]})]})};import{jsx as re,jsxs as be}from"react/jsx-runtime";var K_=[".kizenapp",".git"],Wg=({port:e,pluginDir:t,outputDir:n,credentials:r,credentialMode:i,activeCredentialProfile:o,lastPath:s,debug:a=!1,verbose:c=!1,autoViewer:l=!0,cacheEnabled:d=!0})=>{let u=Mt(r),f=Mt(o),g=Mt(s),[p,m]=Ve("main"),[h,b]=Ve(i),[y,C]=Ve("starting"),[S,x]=Ve(null),[v,k]=As(50),[P,w]=As(50),[A,_]=As(50),[T,L]=Ve([]),[$,V]=Ve("pending"),[X,ve]=Ve(null),[Re,$e]=Ve(null),[Te,gn]=Ve(null),[lt,mr]=Ve(null),[fr,zt]=Ve(0),[E,N]=Ve(0),[B,R]=Ve(0),[O,D]=Ve(0),M=Mt(!1),Y=Mt(!1),G=Mt(null),Z=Mt(null),J=Mt(new Set),le=Mt([]),ae=pr(j=>{let Q=JSON.stringify(j);if(J.current.size===0){le.current=[...le.current,Q].slice(-50);return}let ut=!1;for(let dt of J.current)if(dt.readyState===1)try{dt.send(Q)}catch{J.current.delete(dt),ut=!0}ut&&zt(J.current.size)},[]),Fe=k,Hn=pr(()=>{G.current?.kill(),G.current=null;let j=g.current;Cl(n,j).then(Q=>(Q===void 0&&g.current===j&&(g.current=void 0),Hg({port:e,userDataDir:Kg(n,".chrome"),broadcast:ae,onWarn:ut=>{k(`\u26A0 ${ut}`)},...Q!==void 0&&{path:Q},...a&&{debugLog:_},...c&&{verbose:!0}}))).then(Q=>{G.current=Q})},[e,n,ae,a,c,_,k]);Ss(()=>{let j=()=>{G.current?.kill()};return process.on("exit",j),()=>{process.off("exit",j)}},[]),M_((j,Q)=>{(j==="q"||Q.ctrl&&j==="c")&&process.exit(0),j==="c"&&m("editing"),j==="v"&&Hn()},{isActive:p==="main"}),Ss(()=>{y!=="running"||Y.current||!l||(Y.current=!0,Hn())},[y,l,Hn]);let Rs=pr(j=>{u.current=j.credentials,f.current=j.profileName,m("main"),b(j.mode);let Q=j.profileName;bt(n,{credentialMode:j.mode,...Q!==void 0&&{activeCredentialProfile:Q}}),ae({type:"credentials-updated",credentials:j.credentials})},[n,ae]),Ll=pr(j=>{L(Q=>[...Q,`${new Date().toLocaleTimeString()}: ${Il(j)}`].slice(-50)),j.kind==="request"&&(j.fromCache?R(Q=>Q+1):D(Q=>Q+1)),ae({type:"proxy-log",entry:j})},[ae]),hn=pr(j=>{w(j),ae({type:"log",message:j})},[w,ae]),$s=pr(()=>{M.current||(M.current=!0,V("building"),ve(null),$e(null),hn("Build started"),io(t,n).then(({bundleSize:j})=>{hn(`Build finished \u2014 bundle: ${ci(j)}`),V("done"),gn(new Date),mr(j),hn("Notifying viewers to reload"),ae({type:"rebuild"})}).catch(j=>{j instanceof z_?($e(j.issues),ve(null)):(ve(j instanceof Error?j.message:String(j)),$e(null)),V("error")}).finally(()=>{M.current=!1}))},[t,n,hn,ae]);if(Ss(()=>{$s();let j=U_(t,{recursive:!0},(Q,ut)=>{if(!ut)return;let dt=ut.replace(/\\/g,"/");K_.some(wi=>dt.startsWith(wi))||(hn(`File change detected: ${ut}`),Z.current!==null&&clearTimeout(Z.current),Z.current=setTimeout($s,150))});return j.on("error",Q=>{hn(`File watcher error \u2014 rebuilds have stopped: ${Q.message}`)}),()=>{j.close(),Z.current!==null&&clearTimeout(Z.current)}},[t,$s,hn]),Ss(()=>{let j=jg();Nl(Kg(j,"index.html")).then(Q=>{if(!Q){x("Viewer not built. Run 'pnpm build:viewer' first."),C("error");return}let ut=Mg(j,Fe,Ll,u,f,n,ae,N,g,t,d),dt=V_(ut),wi=new H_({server:dt});return wi.on("connection",yn=>{for(let jh of le.current)yn.readyState===1&&yn.send(jh);le.current=[],Fe("Viewer connected for live reload"),J.current.add(yn),zt(J.current.size),yn.on("close",()=>{J.current.delete(yn),zt(J.current.size)})}),dt.listen(e,"127.0.0.1",()=>{C("running"),Fe(`Server started on 127.0.0.1:${String(e)}`)}),dt.on("error",yn=>{x(yn.message),C("error")}),()=>{wi.close(),dt.close()}})},[e,Fe,Ll,ae,n,t,d]),p==="editing")return re(Cs,{...h!==void 0&&{initialMode:h},showProfileManager:h==="global",onComplete:Rs,onCancel:()=>{m("main")}});let Os=Te!==null?Math.round((Date.now()-Te.getTime())/1e3):null,Fh=Os===null?"":Os<5?" (just now)":` (${String(Os)}s ago)`,Bl=Re?.filter(j=>j.severity==="error").length??0;return be(Ee,{flexDirection:"column",paddingY:1,paddingX:2,children:[re(ye,{marginBottom:1}),be(Ee,{flexDirection:"column",children:[be(Ee,{gap:2,marginBottom:0,children:[re(ne,{bold:!0,dimColor:!0,children:"App Build"}),$==="pending"&&re(ne,{dimColor:!0,children:"waiting\u2026"}),$==="building"&&be(Ee,{gap:1,children:[re(kt,{}),re(ne,{children:"Building plugin package\u2026"})]}),$==="done"&&be(Ee,{gap:1,children:[re(ne,{color:"green",children:"\u2713 Built"}),Te!==null&&be(ne,{dimColor:!0,children:["at ",Te.toLocaleTimeString(),Fh]}),lt!==null&&be(ne,{dimColor:!0,children:["\xB7 bundle: ",ci(lt)]})]}),$==="error"&&(Re!==null?be(ne,{color:"red",children:["\u2717 ",Bl," validation ",Bl===1?"error":"errors"]}):be(ne,{color:"red",children:["\u2717 ",X??"unknown error"]}))]}),Re!==null&&re(ar,{issues:Re}),re(Ee,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:P.slice(-8).map((j,Q)=>re(ne,{dimColor:!0,wrap:"truncate",children:j},Q))})]}),be(Ee,{marginTop:1,flexDirection:"column",children:[be(Ee,{gap:2,children:[re(ne,{bold:!0,dimColor:!0,children:"Web Server"}),y==="starting"&&re(ne,{dimColor:!0,children:"starting\u2026"}),y==="running"&&be(Ee,{gap:2,children:[re(ne,{color:"green",children:"\u2713 Running"}),be(ne,{dimColor:!0,children:["\u25CF ",fr," viewer",fr!==1?"s":""]})]}),y==="error"&&be(ne,{color:"red",children:["\u2717 ",S??"Server error"]})]}),re(Ee,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:v.slice(-8).map((j,Q)=>re(ne,{dimColor:!0,wrap:"truncate",children:j},Q))})]}),be(Ee,{marginTop:1,flexDirection:"column",children:[be(Ee,{gap:2,children:[re(ne,{bold:!0,dimColor:!0,children:"Network Proxy"}),re(ne,{color:"green",children:"\u2713 Active"}),re(ne,{dimColor:!0,children:d?`\u25CF ${String(E)} key${E!==1?"s":""} in the network cache \xB7 ${String(B)} hit \xB7 ${String(O)} miss`:`\u25CF network cache disabled \xB7 ${String(O)} request${O!==1?"s":""}`})]}),re(Ee,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:T.length===0?re(ne,{dimColor:!0,children:" No requests yet."}):T.slice(-8).map((j,Q)=>re(ne,{dimColor:!0,wrap:"truncate",children:j},Q))})]}),a&&be(Ee,{marginTop:1,flexDirection:"column",children:[be(Ee,{gap:2,children:[re(ne,{bold:!0,dimColor:!0,children:"CDP Debug"}),be(ne,{dimColor:!0,children:["\u25CF ",A.length," event(s)"]})]}),re(Ee,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:A.length===0?re(ne,{dimColor:!0,children:" No CDP events yet."}):A.slice(-8).map((j,Q)=>re(ne,{dimColor:!0,wrap:"truncate",children:j},Q))})]}),be(Ee,{marginTop:1,gap:1,children:[re(ne,{dimColor:!0,children:"["}),re(ne,{children:"q"}),re(ne,{dimColor:!0,children:"] quit ["}),re(ne,{children:"c"}),re(ne,{dimColor:!0,children:"] credentials ["}),re(ne,{children:"v"}),be(ne,{dimColor:!0,children:["] ",fr===0?"open viewer":"relaunch viewer"]})]})]})};async function Gg(e){return new Promise(t=>{let n=null,r=o=>{n?.(),t(o)},{unmount:i}=qg(Jg(Cs,{...e!==void 0&&{initialMode:e},onComplete:r}),{exitOnCtrlC:!1});n=i})}function Yg(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(),i=`${r}/.kizenapp`;Ze(r);let o=null,s,a,c=await vg(i);if(t.credentials)o=await Jt(t.credentials);else{let p=await rt(i);if(p.credentialMode==="local")s="local";else if(p.credentialMode==="global"){if(s="global",a=p.activeCredentialProfile,a?(o=await _t(a),o||(o=await De(),a=void 0)):o=await De(),!o){let m=await Gg("global");o=m.credentials,a=m.profileName}}else{let m=await Gg();o=m.credentials,s=m.mode,a=m.profileName;let h=m.profileName;await bt(i,{credentialMode:m.mode,...h!==void 0&&{activeCredentialProfile:h}})}}let l=t.verbose===!0,d=l||t.debug===!0,u=t.viewer!==!1,f=t.cache!==!1,{waitUntilExit:g}=qg(Jg(Wg,{port:n,pluginDir:r,outputDir:i,credentials:o,...s!==void 0&&{credentialMode:s},...a!==void 0&&{activeCredentialProfile:a},...c!==void 0&&{lastPath:c},debug:d,verbose:l,autoViewer:u,cacheEnabled:f}),{exitOnCtrlC:!1});await g()})}import{createElement as iE}from"react";import{render as oE}from"ink";import{useCallback as Es,useEffect as eh,useState as Is}from"react";import{Box as Ct,Text as se,useApp as X_,useInput as Q_}from"ink";import{encrypt as W_,serializeEnvelope as G_}from"@kizenapps/packager";function J_(e){let t=e;return t.code==="ECONNREFUSED"||t.cause?.code==="ECONNREFUSED"}function Zg(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 Xg(e,t,n){try{return await fetch(`${e}${t}`,n)}catch(r){throw new Error(J_(r)?`Plugin-wizard is not running at ${e}`:`Failed to reach plugin-wizard: ${r.message}${ki()==="unavailable"?` ${vi}`:""}`)}}async function Qg(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 q_(e,t,n){let r=mi(e.stage),i=await Xg(r,"/get-public-key",{method:"POST",headers:Zg(t),body:JSON.stringify({api_name:n})}),o=await Qg(i);if(!i.ok||typeof o.public_key!="string"){let s=typeof o.error=="string"?o.error:`HTTP ${String(i.status)}`;throw new Error(`Failed to fetch public key: ${s}`)}return o.public_key}function Y_(e,t){let n=W_(t,e),r=G_(n);if(typeof r.value!="string")throw new Error("Unexpected serialized envelope shape from @kizenapps/packager");return r.value}async function Z_(e,t,n,r){let i=mi(e.stage),o=await Xg(i,"/encrypt",{method:"POST",headers:Zg(t),body:JSON.stringify({api_name:n,value:r})}),s=await Qg(o);if(!o.ok||s.encrypted!==!0||typeof s.value!="string"){let a=typeof s.error=="string"?s.error:`HTTP ${String(o.status)}`;throw new Error(`Encryption via plugin-wizard failed: ${a}`)}return s.value}async function _s(e,t,n,r,i){if(e.isRemote)return i?.("encrypting"),Z_(e,t,n,r);i?.("fetching-key");let o=await q_(e,t,n);return i?.("encrypting"),Y_(o,r)}import{Fragment as Ts,jsx as ie,jsxs as Ie}from"react/jsx-runtime";var $l=({text:e})=>ie(se,{dimColor:!0,children:e}),th=({ctx:e,stageDefaulted:t,credentialsPath:n,initialApiName:r,defaultApiName:i,initialValue:o,onDone:s})=>{let a=X_(),[c,l]=Is({type:"loading"}),[d,u]=Is(null),[f,g]=Is(r??""),[p,m]=Is(o??""),h=Es(k=>{process.exitCode=1,l({type:"error",message:k instanceof Error?k.message:String(k)})},[]),b=Es(async(k,P,w)=>{try{let A=await _s(e,k,P,w,L=>{l(L==="fetching-key"?{type:"fetching-key"}:{type:"encrypting"})}),_=JSON.stringify({encrypted:!0,value:A},null,2);s?.(A);let T=await es(_);l({type:"done",envelope:_,copied:T})}catch(A){h(A)}},[e,h,s]),y=Es((k,P,w)=>{if(P.trim()===""){l({type:"api-name-entry",buffer:i??""});return}if(w===""){l({type:"value-entry",buffer:""});return}b(k,P.trim(),w)},[i,b]),C=Es(async k=>{try{l({type:"loading"});let P=k.isDefault?await De():await _t(k.name);if(P===null)throw new Error(`Could not load credential profile: ${k.name}`);u(P),y(P,f,p)}catch(P){h(P)}},[f,p,y,h]);eh(()=>{(async()=>{try{if(n!==void 0){let w;try{w=await Jt(n)}catch(A){throw new Error(`Could not load credentials from ${n}: ${A instanceof Error?A.message:String(A)}`)}u(w),y(w,f,p);return}let k=await qt();if(k.length===0)throw new Error("No credential profiles found. Create ~/.kizenappbuilder/credentials.json first.");let[P]=k;if(k.length===1&&P!==void 0){let w=P.isDefault?await De():await _t(P.name);if(w===null)throw new Error(`Could not load credential profile: ${P.name}`);u(w),y(w,f,p);return}l({type:"profile-select",profiles:k,cursor:0})}catch(k){h(k)}})()},[]),eh(()=>{(c.type==="done"||c.type==="error")&&a.exit()},[c,a]),Q_((k,P)=>{if(P.ctrl&&k==="c"){process.exitCode=130,a.exit();return}if(c.type==="profile-select"){let{profiles:w,cursor:A}=c;if(P.upArrow)l({...c,cursor:(A-1+w.length)%w.length});else if(P.downArrow)l({...c,cursor:(A+1)%w.length});else if(P.return){let _=w[A];_!==void 0&&C(_)}return}if(c.type==="api-name-entry"){let{buffer:w}=c;if(P.backspace||P.delete)l({type:"api-name-entry",buffer:w.slice(0,-1)});else if(P.return){let A=w.trim();if(A===""){l({type:"api-name-entry",buffer:w,error:"api_name cannot be empty"});return}g(A),d?y(d,A,p):h(new Error("Internal error: credentials were not loaded"))}else k&&!P.ctrl&&!P.meta&&l({type:"api-name-entry",buffer:w+k});return}if(c.type==="value-entry"){let{buffer:w}=c;if(P.backspace||P.delete)l({type:"value-entry",buffer:w.slice(0,-1)});else if(P.return){if(w===""){l({type:"value-entry",buffer:w,error:"secret cannot be empty"});return}m(w),d?y(d,f,w):h(new Error("Internal error: credentials were not loaded"))}else k&&!P.ctrl&&!P.meta&&l({type:"value-entry",buffer:w+k});return}});let S=e.isRemote?"remote Kizen API":"on-machine",x=t===!0?`${e.stage} (default)`:e.stage,v=k=>Ie(Ct,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[ie(ye,{}),Ie(se,{dimColor:!0,children:["Mode: ",S," Stage: ",x]}),k]});if(c.type==="loading")return v(Ie(Ct,{gap:1,children:[ie(kt,{}),ie(se,{dimColor:!0,children:"Loading credentials\u2026"})]}));if(c.type==="profile-select"){let{profiles:k,cursor:P}=c;return v(Ie(Ts,{children:[ie(se,{bold:!0,children:"Credential profile"}),ie(Ct,{flexDirection:"column",children:k.map((w,A)=>{let _=P===A;return Ie(Ct,{gap:2,children:[ie(se,{..._&&{color:"cyan"},children:_?"\u276F":" "}),ie(se,{bold:_,..._&&{color:"cyan"},children:w.isDefault?"Default":w.name}),ie(se,{dimColor:!0,children:w.path})]},w.name)})}),ie($l,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]}))}return c.type==="api-name-entry"?v(Ie(Ts,{children:[ie(se,{bold:!0,children:"Plugin api_name"}),c.error!==void 0&&Ie(se,{color:"red",children:["Error: ",c.error]}),Ie(Ct,{gap:1,children:[ie(se,{color:"cyan",children:">"}),ie(se,{children:c.buffer}),ie(se,{color:"cyan",children:"\u2588"})]}),ie($l,{text:"Type the api_name \xB7 Enter to confirm \xB7 Ctrl+C to quit"})]})):c.type==="value-entry"?v(Ie(Ts,{children:[ie(se,{bold:!0,children:"Secret value"}),c.error!==void 0&&Ie(se,{color:"red",children:["Error: ",c.error]}),Ie(Ct,{gap:1,children:[ie(se,{color:"cyan",children:">"}),ie(se,{children:"\u2022".repeat(c.buffer.length)}),ie(se,{color:"cyan",children:"\u2588"})]}),ie($l,{text:"Input hidden \xB7 Enter to encrypt \xB7 Ctrl+C to quit"})]})):c.type==="fetching-key"?v(Ie(Ct,{gap:1,children:[ie(kt,{}),Ie(se,{children:["Fetching ",e.stage," public key for ",ie(se,{bold:!0,children:f}),"\u2026"]})]})):c.type==="encrypting"?v(Ie(Ct,{gap:1,children:[ie(kt,{}),ie(se,{children:"Encrypting\u2026"})]})):c.type==="error"?v(Ie(Ct,{gap:1,children:[ie(se,{color:"red",children:"\u2717"}),ie(se,{color:"red",children:c.message})]})):v(Ie(Ts,{children:[Ie(Ct,{gap:1,children:[ie(se,{color:"green",children:"\u2713"}),ie(se,{bold:!0,children:"Encrypted secret ready"})]}),c.copied?ie(se,{color:"green",children:"\u2713 Copied to clipboard \u2014 paste it into the secret value in your kizen.json."}):ie(se,{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):"}),ie(se,{children:c.envelope})]}))};import{readFile as eE,writeFile as tE}from"fs/promises";import{join as nE}from"path";function nh(e){return{encrypted:!0,value:e}}function rh(e){return JSON.stringify(nh(e))}async function Ol(e,t){await tE(e,`${JSON.stringify(nh(t),null,2)}
|
|
1221
|
+
`,"utf-8")}var rE="prod";function ih(e){return e==="dev"||e==="prod"}function oh(e){return`Error: --stage must be "dev" or "prod" (got: "${e}")`}function sh(e){return{stage:e==="dev"||e==="prod"?e:rE,wasDefaulted:e===void 0}}function ah(e){return`No --stage given; defaulting to ${e} encryption keys (pass --stage dev to override)
|
|
1222
|
+
`}async function ch(e=process.cwd()){try{let t=await eE(nE(e,"kizen.json"),"utf-8"),n=JSON.parse(t),r=Array.isArray(n)?n[0]:n,i=typeof r.api_name=="string"&&r.api_name!==""?r.api_name:void 0;return{...i!==void 0&&{apiName:i}}}catch{}return{}}function lh(e){return e.replace(/[\r\n]+$/,"")}async function uh(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}async function dh(e,t,n,r,i){let o=t.credentials!==void 0?await i.loadCredentialsFromFile(t.credentials):await i.loadGlobalCredentials();if(o===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&&i.writeStderr(ah(e.stage));let a=t.value;if(a===void 0){if(i.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`).');i.writeStderr(`Reading secret from stdin (pass --value to skip)\u2026
|
|
1223
|
+
`),a=lh(await i.readStdin())}if(a==="")throw new Error("A secret value is required. Pass --value or pipe it via stdin.");let c=await i.encryptSecret(e,o,s.trim(),a);if(i.writeStdout(`${rh(c)}
|
|
1224
1224
|
`),t.out!==void 0)try{await i.writeEnvelopeFile(t.out,c),i.writeStderr(`Wrote encrypted envelope to ${t.out}
|
|
1225
1225
|
`)}catch(l){i.writeStderr(`Error writing ${t.out}: ${l instanceof Error?l.message:String(l)}
|
|
1226
|
-
`),i.setExitCode(1)}}function
|
|
1227
|
-
`)}catch(u){console.error(`Error writing ${r.out}: ${u instanceof Error?u.message:String(u)}`),process.exitCode=1}})}var
|
|
1228
|
-
${
|
|
1229
|
-
`)}var
|
|
1226
|
+
`),i.setExitCode(1)}}function ph(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").option("--no-interactive",gt).action(async t=>{let{noInteractive:n,options:r}=Ae(t);r.stage!==void 0&&!ih(r.stage)&&(console.error(oh(r.stage)),process.exit(1));let o=r.apiName===void 0?await ch():{},{stage:s,wasDefaulted:a}=sh(r.stage),c={isRemote:r.remote===!0,stage:s};if(!ft({noInteractive:n})){try{await dh(c,r,o,a,{loadCredentialsFromFile:Jt,loadGlobalCredentials:De,encryptSecret:_s,readStdin:uh,stdinIsTTY:()=>process.stdin.isTTY,writeStdout:u=>{process.stdout.write(u)},writeStderr:u=>{process.stderr.write(u)},writeEnvelopeFile:Ol,setExitCode:u=>{process.exitCode=u}})}catch(u){console.error(`Error: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}return}let l,{waitUntilExit:d}=oE(iE(th,{ctx:c,stageDefaulted:a,onDone:u=>{l=u},...r.credentials!==void 0&&{credentialsPath:r.credentials},...r.apiName!==void 0&&{initialApiName:r.apiName},...o.apiName!==void 0&&{defaultApiName:o.apiName},...r.value!==void 0&&{initialValue:r.value}}),{exitOnCtrlC:!1});if(await d(),l!==void 0&&r.out!==void 0)try{await Ol(r.out,l),process.stderr.write(`Wrote encrypted envelope to ${r.out}
|
|
1227
|
+
`)}catch(u){console.error(`Error writing ${r.out}: ${u instanceof Error?u.message:String(u)}`),process.exitCode=1}})}var sE=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"]),aE=[...sE].sort(),cE=new Set(["kizen-k","form-entity"]),mh=[...aE,...[...cE].sort()];function fh(e){e.command("icons").description("List all valid icon names accepted by toolbar items, pages, and adornments").action(()=>{for(let t of mh)console.log(t)})}import{mkdir as hE,writeFile as Ch,readFile as yE}from"fs/promises";import{join as Ns}from"path";var lE=new Set(["developer_business_id"]);function uE(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(i=>[i,"*****"]));return{...n,auth_credentials:r}}):e}function hh(e){let t={name:"",children:new Map,isFile:!1,filePath:""};for(let n of e){let r=n.path.split("/"),i=t;r.forEach((o,s)=>{i.children.has(o)||i.children.set(o,{name:o,children:new Map,isFile:s===r.length-1,filePath:r.slice(0,s+1).join("/")});let a=i.children.get(o);a&&(i=a)})}return t}function yh(e){return[...e.children.values()].sort((t,n)=>t.isFile!==n.isFile?t.isFile?1:-1:t.name.localeCompare(n.name))}function Dl(e){return"file-"+e.replace(/[^a-zA-Z0-9]/g,"-")}function St(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function bh(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t).toLowerCase():""}var dE={".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 pE(e){return dE[bh(e)]??""}function gh(e){let t=[...e.matchAll(/`+/g)].reduce((n,r)=>Math.max(n,r[0].length),0);return"`".repeat(Math.max(3,t+1))}function wh(e,t=""){let n=yh(e);return n.map((r,i)=>{let o=i===n.length-1,s=o?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",a=o?" ":"\u2502 ";return r.isFile?`${t}${s}${r.name}`:`${t}${s}${r.name}/
|
|
1228
|
+
${wh(r,t+a)}`}).join(`
|
|
1229
|
+
`)}var mE=/(^|\/)licen[cs]e(\.md|\.txt)?$/i;function vh(e){return e.filter(t=>t.path!=="kizen.json"&&t.path!=="plugin-report.html"&&!mE.test(t.path))}function kh(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!lE.has(t)).map(([t,n])=>[t,t==="services"?uE(n):n]))}var fE={".png":"image/png",".svg":"image/svg+xml",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function Ah(e){return`<ul>${yh(e).map(r=>r.isFile?`<li class="tf"><a href="#${Dl(r.filePath)}" data-id="${Dl(r.filePath)}">${St(r.name)}</a></li>`:`<li class="td"><span class="dn">${St(r.name)}/</span>${Ah(r)}</li>`).join("")}</ul>`}function gE(e){let t;return e.base64Image!==void 0?t=`<img src="data:${fE[bh(e.path)]??"image/png"};base64,${e.base64Image}" alt="${St(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>${St(e.content)}</code></pre>`,`<section id="${Dl(e.path)}"><h2 class="fp">${St(e.path)}</h2><div class="fb">${t}</div></section>`}function xh(e,t){let n=kh(e),r=typeof e.name=="string"?e.name:"Plugin",i=typeof e.version=="string"?e.version:"",o=typeof e.description=="string"?e.description:"",s=vh(t),a=[];a.push(`# ${r}${i?` v${i}`:""}`),o&&a.push("",o);let c=JSON.stringify(n,null,2),l=gh(c);a.push("","## Configuration (`kizen.json`)","",`${l}json`,c,l),a.push("","## File Tree","","```",wh(hh(s)),"```"),a.push("","## Files");for(let d of s)if(a.push("",`### \`${d.path}\``,""),d.base64Image!==void 0)a.push(`[Image file: ${d.path}]`);else if(d.binaryData!==void 0)a.push(`[Binary file: ${String(d.binaryData.length)} bytes]`);else{let u=gh(d.content);a.push(`${u}${pE(d.path)}`,d.content,u)}return a.join(`
|
|
1230
1230
|
`)+`
|
|
1231
|
-
`}function
|
|
1231
|
+
`}function Ph(e,t){let n=kh(e),r=typeof e.name=="string"?e.name:"Plugin",i=typeof e.version=="string"?e.version:"",o=typeof e.description=="string"?e.description:"",s=vh(t),a=Ah(hh(s)),c=s.map(gE).join(`
|
|
1232
1232
|
`);return`<!DOCTYPE html>
|
|
1233
1233
|
<html lang="en">
|
|
1234
1234
|
<head>
|
|
1235
1235
|
<meta charset="UTF-8">
|
|
1236
1236
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
1237
|
-
<title>${
|
|
1237
|
+
<title>${St(r)} \u2014 Plugin Report</title>
|
|
1238
1238
|
<style>
|
|
1239
1239
|
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
|
|
1240
1240
|
:root{
|
|
@@ -1271,8 +1271,8 @@ img{border:1px solid var(--bd);border-radius:4px}
|
|
|
1271
1271
|
</head>
|
|
1272
1272
|
<body>
|
|
1273
1273
|
<header>
|
|
1274
|
-
<h1>${
|
|
1275
|
-
${o?`<p>${
|
|
1274
|
+
<h1>${St(r)}${i?` <span style="color:var(--mu);font-size:.8em">v${St(i)}</span>`:""}</h1>
|
|
1275
|
+
${o?`<p>${St(o)}</p>`:""}
|
|
1276
1276
|
</header>
|
|
1277
1277
|
<div class="layout">
|
|
1278
1278
|
<nav>
|
|
@@ -1280,7 +1280,7 @@ img{border:1px solid var(--bd);border-radius:4px}
|
|
|
1280
1280
|
${a}
|
|
1281
1281
|
</nav>
|
|
1282
1282
|
<main>
|
|
1283
|
-
<section id="config"><h2 class="fp">kizen.json \u2014 Plugin Configuration</h2><div class="fb"><pre><code>${
|
|
1283
|
+
<section id="config"><h2 class="fp">kizen.json \u2014 Plugin Configuration</h2><div class="fb"><pre><code>${St(JSON.stringify(n,null,2))}</code></pre></div></section>
|
|
1284
1284
|
${c}
|
|
1285
1285
|
</main>
|
|
1286
1286
|
</div>
|
|
@@ -1294,10 +1294,10 @@ ${c}
|
|
|
1294
1294
|
})();
|
|
1295
1295
|
</script>
|
|
1296
1296
|
</body>
|
|
1297
|
-
</html>`}var
|
|
1297
|
+
</html>`}var Sh=Ns(nt,"examples");function _h(e){e.command("report").description("Generate a self-contained HTML report of the plugin").option("-o, --output <path>",`output file path (default: ${Sh}/<api_name>.html)`).action(async t=>{let n=process.cwd(),r;try{let c=await yE(Ns(n,"kizen.json"),"utf-8"),l=JSON.parse(c);r=Array.isArray(l)?l[0]:l}catch{console.error("Error: kizen.json not found. Run this command from a plugin directory."),process.exit(1)}let i=typeof r.api_name=="string"?r.api_name:"plugin",o=t.output??Ns(Sh,`${i}.html`),s=o.replace(/\.html$/,".md"),a=await ro(n,{detectBinaryByContent:!0});await hE(Ns(o,".."),{recursive:!0}),await Promise.all([Ch(o,Ph(r,a),"utf-8"),Ch(s,xh(r,a),"utf-8")]),console.log(`Plugin report written to:
|
|
1298
1298
|
${o}
|
|
1299
|
-
${s}`)})}import{spawn as
|
|
1300
|
-
${e.stderr}`),
|
|
1299
|
+
${s}`)})}import{spawn as bE}from"child_process";var o2=Ke.claude.staleWarning,wE=yt;var vE="@kizenapps/cli",kE=6e4,AE=(e,t)=>new Promise((n,r)=>{let i=bE(e,[...t],{stdio:["ignore","pipe","pipe"],timeout:kE}),o="",s="";i.stdout.setEncoding("utf-8"),i.stderr.setEncoding("utf-8"),i.stdout.on("data",a=>{o+=a}),i.stderr.on("data",a=>{s+=a}),i.on("error",r),i.on("close",a=>{n({code:a,stdout:o,stderr:s})})}),Ih=e=>({run:AE,hasOAuthSession:async t=>await ht().readSession(t)!==null,cliVersion:e,fs:wE,log:t=>{console.log(t)},error:t=>{console.error(t)},setExitCode:t=>{process.exitCode=t}});function xE(e,t){let n=`kizen-${e}`,r=`${Vt(e)}/api/mcp`,i=JSON.stringify({type:"http",url:r,headersHelper:`npx -y ${vE}@${t} auth-header`}),o=["mcp","add-json","--scope","user",n,i];return{environment:e,name:n,url:r,addArgs:o,addCommand:["claude",...o].map(ge).join(" ")}}function PE(e){return e.mcp!==!0&&(e.env!==void 0||e.force===!0)?"--env and --force only apply with --mcp.":e.mcp===!0&&e.includeLib===!0?"--mcp and --include-lib can't be combined. Run `appbuilder setup-claude --include-lib` and `appbuilder setup-claude --mcp` separately.":e.env===void 0?void 0:wn(e.env).message}var CE=e=>/already\s+exists/i.test(`${e.stdout}
|
|
1300
|
+
${e.stderr}`),Eh=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 SE(e,t,n){let r=xE(e,n.cliVersion),{name:i}=r,o=!1,s=a=>{n.error(`Error: couldn't register the MCP server ${i}: ${a}`),o&&(n.error(`The old ${i} registration was already removed, so Claude Code has no ${i} 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&&CE(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 ${Eh(c)}`);return}o=!0,a=await n.run("claude",r.addArgs)}if(a.code!==0){s(`claude mcp add-json ${Eh(a)}`);return}}catch(a){if(!o&&He(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(ke(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 \`${pt(e)}\` before using ${r.name}.`)}catch(a){n.log(ke(a))}}async function Th(e,t,n){let r=PE(t);if(r!==void 0){n.error(`Error: ${r}`),n.setExitCode(1);return}let i=t.dryRun===!0;if(t.mcp===!0){await SE((t.env===void 0?void 0:wn(t.env).environment)??Kt,{dryRun:i,force:t.force===!0},n);return}await Zi(e,"claude",{dryRun:i,includeLib:t.includeLib===!0,notFoundHint:", or pass --mcp to only register the MCP server"},n)}function Nh(e,t){e.command("setup-claude").description("Install or refresh the Claude Code files in a plugin, or with --mcp only register the Kizen MCP server").option("--dry-run","report what would change without writing files").option("--include-lib","also install the Kizen data helper library (<entry>/lib/kizenData.js)").option("--mcp","only register the Kizen MCP server in Claude Code (user scope); writes no files, so it works in any directory").option("--env <env>","environment of the MCP server to register (with --mcp; default: go)").option("--force","replace an existing Kizen MCP server registration (with --mcp)").action(async n=>{await Th(process.cwd(),n,Ih(t))})}var m2=`${Ke.codex.skillsDir}/kizen-custom-block/SKILL.md`,f2=Ke.codex.staleWarning,Rh=()=>({fs:yt,log:e=>{console.log(e)},error:e=>{console.error(e)},setExitCode:e=>{process.exitCode=e}});async function $h(e,t,n){await Zi(e,"codex",{dryRun:t.dryRun===!0,includeLib:t.includeLib===!0},n)}function Oh(e){e.command("setup-codex").description("Install or refresh the Codex skills (.agents/skills) in a plugin").option("--dry-run","report what would change without writing files").option("--include-lib","also install the Kizen data helper library (<entry>/lib/kizenData.js)").action(async t=>{await $h(process.cwd(),t,Rh())})}async function Dh(e,t={}){if(await dn(e)!=="has-manifest")throw new Error(`No kizen.json found in ${e}`);let n=t.dryRun===!0,r=await Gi(e,Ki(),{dryRun:n});return n||Ze(e),{files:r}}function Lh(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 dn(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 i=await Dh(n,{dryRun:r});for(let o of i.files)console.log(Ji(o));if(r){console.log(`
|
|
1301
1301
|
Dry run \u2014 no files and no .gitignore entries were written.`);return}console.log(`
|
|
1302
|
-
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(i){console.error(`Error: ${i instanceof Error?i.message:String(i)}`),process.exitCode=1}})}function
|
|
1302
|
+
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(i){console.error(`Error: ${i instanceof Error?i.message:String(i)}`),process.exitCode=1}})}function RE(){let e=IE(EE(TE(import.meta.url)),"..","package.json");return JSON.parse(_E(e,"utf-8")).version}function Bh(){let e=new NE,t=RE();return e.name("appbuilder").description("Kizen plugin app builder").version(t),hg(e),Nh(e,t),Oh(e),Lh(e),jf(e),Yg(e),ph(e),_h(e),fh(e),Df(e),Bm(e),Mm(e),Ku(e),e}Fl({env:process.env,http:$E});Bh().parse();
|
|
1303
1303
|
//# sourceMappingURL=index.js.map
|