@yunuseon/kayra 0.15.0 → 0.16.1

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.
@@ -97,6 +97,14 @@ d="$(mktemp -d)" && (cd "$d" && npm pack @yunuseon/kayra@<version> --silent && t
97
97
 
98
98
  Test-only paths (`test/`, `ci/`) are meant to stay out.
99
99
 
100
+ Look for what must still be there too, not only for what is new: a build
101
+ step can remove files another one made. 0.16.0 shipped without
102
+ `cli/dist/web/*.js`, because the browser build emptied the directory tsc had
103
+ put the server's modules in, and no command started. Listing the new browser
104
+ files did not show that. `release.yml` now runs
105
+ `scripts/local/packed-runs.sh` before `npm publish`: it packs, installs and
106
+ runs the CLI as a fleet would. Run it yourself before opening the bump PR.
107
+
100
108
  ## 5. Afterwards
101
109
 
102
110
  - Remove the worktree and the local branch.
@@ -0,0 +1 @@
1
+ :root{--bg:#f7f7f8;--panel:#fff;--panel-2:#f2f2f4;--line:#e4e4e8;--line-strong:#d4d4da;--fg:#18181b;--fg-2:#52525b;--muted:#8a8a94;--accent:#5b5bd6;--accent-soft:#ededfc;--ok:#18794e;--ok-soft:#e6f6ed;--bad:#ce2c31;--bad-soft:#feebec;--warn:#ab6400;--warn-soft:#fff4d5;--active:#0d74ce;--active-soft:#e6f2fd;--code-bg:#0f0f12;--code-fg:#e4e4e8;--radius:10px;--shadow:0 1px 2px #0000000a, 0 4px 16px #0000000a;--mono:ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;--sans:-apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", system-ui, sans-serif;--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light dark}@media (prefers-color-scheme:dark){:root{--lightningcss-light: ;--lightningcss-dark:initial;--bg:#0e0e11;--panel:#16161a;--panel-2:#1c1c21;--line:#26262c;--line-strong:#33333b;--fg:#ededf0;--fg-2:#b4b4bd;--muted:#7c7c87;--accent:#8b8bf5;--accent-soft:#23234a;--ok:#4cc38a;--ok-soft:#12291d;--bad:#ff6369;--bad-soft:#3b1219;--warn:#f1a10d;--warn-soft:#2e2309;--active:#70b8ff;--active-soft:#0d2847;--code-bg:#0a0a0c;--shadow:0 1px 2px #0000004d, 0 4px 16px #0003}}*{box-sizing:border-box}body{font:14px/1.5 var(--sans);color:var(--fg);background:var(--bg);-webkit-font-smoothing:antialiased;margin:0}a{color:inherit}code,pre,kbd{font-family:var(--mono);font-size:12.5px}h1,h2,h3{letter-spacing:-.01em;margin:0}button,input{font:inherit;color:inherit}.shell{grid-template-columns:248px 1fr;min-height:100vh;display:grid}.sidebar{border-right:1px solid var(--line);background:var(--panel);flex-direction:column;gap:18px;height:100vh;padding:16px 12px;display:flex;position:sticky;top:0;overflow-y:auto}.brand{align-items:center;gap:10px;padding:4px 8px 8px;text-decoration:none;display:flex}.brand strong{font-size:15px;display:block}.brand-sub{color:var(--muted);font-size:12px;display:block}.logo{background:var(--accent);color:#fff;width:30px;height:30px;font-weight:700;font-family:var(--mono);border-radius:8px;place-items:center;display:grid}.nav-title{text-transform:uppercase;letter-spacing:.06em;color:var(--muted);padding:0 10px 4px;font-size:11px;font-weight:600}.nav-item{color:var(--fg-2);border-radius:7px;align-items:center;gap:9px;padding:6px 10px;text-decoration:none;display:flex}.nav-item:hover{background:var(--panel-2);color:var(--fg)}.nav-item.current{background:var(--accent-soft);color:var(--fg);font-weight:550}.nav-meta{color:var(--muted);margin-left:auto;font-size:11px}.sidebar-foot{color:var(--muted);font-size:12px;font-family:var(--mono);margin-top:auto;padding:0 10px}.main{width:100%;max-width:1180px;padding:20px 36px 64px}@media (width<=860px){.shell{grid-template-columns:1fr}.sidebar{height:auto;position:static}.main{padding:16px}}.topbar{justify-content:flex-end;gap:10px;margin-bottom:18px;display:flex}.search{border:1px solid var(--line);background:var(--panel);min-width:260px;color:var(--muted);cursor:pointer;border-radius:8px;align-items:center;gap:24px;padding:6px 8px 6px 12px;display:flex}.search kbd{border:1px solid var(--line-strong);border-radius:5px;margin-left:auto;padding:1px 6px;font-size:11px}.page-header{justify-content:space-between;align-items:flex-end;gap:16px;margin:8px 0 22px;display:flex}.page-header h1{align-items:center;gap:10px;font-size:24px;font-weight:650;display:flex}.page-header .sub,.sub{color:var(--muted);margin-top:4px}.actions,.inline{align-items:center;gap:8px;display:flex}.card{background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);box-shadow:var(--shadow);margin-bottom:16px;padding:16px 18px}.card h2{color:var(--fg-2);margin-bottom:10px;font-size:13px;font-weight:600}.cards{grid-template-columns:repeat(auto-fill,minmax(310px,1fr));gap:16px;display:grid}.columns{grid-template-columns:1fr 1fr;gap:16px;display:grid}@media (width<=860px){.columns{grid-template-columns:1fr}}.card-head{align-items:center;gap:8px;margin-bottom:6px;display:flex}.card-head h2{color:var(--fg);margin:0;font-size:16px}.server-card{text-decoration:none;transition:border-color .15s,transform .15s;display:block}.server-card:hover{border-color:var(--line-strong);transform:translateY(-1px)}.domain{font-family:var(--mono);color:var(--muted);margin-bottom:12px;font-size:12.5px}.facts{gap:6px;margin:0;display:grid}.fact{grid-template-columns:72px 1fr;align-items:center;display:grid}.fact dt{color:var(--muted);font-size:12.5px}.fact dd{font-family:var(--mono);align-items:center;gap:7px;margin:0;font-size:12.5px;display:flex}.chips{flex-wrap:wrap;gap:6px;margin-top:12px;display:flex}.grow{flex:1}.pill{background:var(--panel-2);color:var(--fg-2);border:1px solid var(--line);border-radius:999px;align-items:center;padding:1px 8px;font-size:11.5px;font-weight:550;display:inline-flex}.pill-ok{background:var(--ok-soft);color:var(--ok);border-color:#0000}.pill-bad{background:var(--bad-soft);color:var(--bad);border-color:#0000}.pill-warn{background:var(--warn-soft);color:var(--warn);border-color:#0000}.pill-active{background:var(--active-soft);color:var(--active);border-color:#0000}.pill-accent{background:var(--accent-soft);color:var(--accent);border-color:#0000}.pill-muted{color:var(--muted)}.dot{background:var(--muted);border-radius:50%;flex:none;width:8px;height:8px;display:inline-block}.dot-ok{background:var(--ok);box-shadow:0 0 0 3px var(--ok-soft)}.dot-bad{background:var(--bad);box-shadow:0 0 0 3px var(--bad-soft)}.dot-warn{background:var(--warn);box-shadow:0 0 0 3px var(--warn-soft)}.dot-active,.dot-accent{background:var(--active)}.dot-waiting{background:var(--active);animation:1.2s ease-in-out infinite breathe}@keyframes breathe{50%{opacity:.25}}.tone-ok{color:var(--ok)}.tone-bad{color:var(--bad)}.tone-warn{color:var(--warn)}.tone-active{color:var(--active)}.tone-muted{color:var(--muted)}.tone-strong{font-weight:600}.tone-accent{color:var(--accent);font-weight:600}.button{border:1px solid var(--line-strong);background:var(--panel);cursor:pointer;border-radius:7px;padding:6px 12px;font-weight:550}.button:hover{background:var(--panel-2)}.button:disabled{opacity:.5;cursor:default}.button.primary{background:var(--accent);border-color:var(--accent);color:#fff}.button.danger{background:var(--bad);border-color:var(--bad);color:#fff}.button.small{padding:2px 8px;font-size:12.5px}.link{cursor:pointer;background:0 0;border:none;padding:0;text-decoration:underline}.danger-link{color:var(--bad)}input{border:1px solid var(--line-strong);background:var(--panel);border-radius:7px;padding:6px 10px}input:focus,button:focus-visible,a:focus-visible{outline:2px solid var(--accent);outline-offset:1px}.action-grid{grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:10px;display:grid}.action{text-align:left;border:1px solid var(--line);background:var(--panel-2);cursor:pointer;border-radius:9px;gap:2px;padding:10px 12px;display:grid}.action strong{font-family:var(--mono);font-size:13px}.action span{color:var(--muted);font-size:12.5px}.action:hover{border-color:var(--accent)}.action.primary{border-color:var(--accent);background:var(--accent-soft)}.action.danger strong{color:var(--bad)}.action:disabled{opacity:.45;cursor:default}.table{border-collapse:collapse;width:100%}.table th{text-align:left;color:var(--muted);border-bottom:1px solid var(--line);padding:6px 8px;font-size:12px;font-weight:550}.table td{border-bottom:1px solid var(--line);padding:8px}.table tr:last-child td{border-bottom:none}.table .narrow{width:20px}.right{text-align:right}.clickable{cursor:pointer}.clickable:hover td{background:var(--panel-2)}.links{gap:4px;margin:0;padding:0;list-style:none;display:grid}.releases{margin:0;padding:0;list-style:none}.releases li{border-bottom:1px solid var(--line);align-items:center;gap:14px;padding:8px 0;display:flex}.findings{gap:6px;margin:8px 0 0;padding:0;list-style:none;display:grid}.finding{grid-template-columns:18px 1fr;display:grid}.hint{color:var(--muted);font-size:12.5px;display:block}.empty,.waiting{color:var(--muted)}.waiting{align-items:center;gap:8px;padding:6px 0;display:flex}.small{font-size:12.5px}.notice{background:var(--warn-soft);color:var(--warn);border-radius:8px;margin-bottom:16px;padding:10px 14px}.problem{background:var(--bad-soft);color:var(--bad);border-radius:8px;margin:8px 0;padding:12px 14px}.problem pre{white-space:pre-wrap;color:var(--fg);margin:6px 0 0}.tabs{gap:4px;margin-bottom:10px;display:flex}.tab{cursor:pointer;color:var(--muted);background:0 0;border:none;border-radius:7px;padding:6px 12px;font-weight:550}.tab.current{background:var(--panel);color:var(--fg);box-shadow:var(--shadow)}.log{background:var(--code-bg);max-height:70vh;color:var(--code-fg);border-radius:8px;margin:0;padding:12px;overflow:auto}.spinner{border:2px solid var(--line-strong);border-top-color:var(--active);border-radius:50%;width:12px;height:12px;animation:.7s linear infinite spin;display:inline-block}@keyframes spin{to{transform:rotate(360deg)}}.overlay{z-index:10;-webkit-backdrop-filter:blur(2px);backdrop-filter:blur(2px);background:#00000059;justify-content:center;align-items:flex-start;padding:8vh 16px;display:flex;position:fixed;inset:0}.sheet{background:var(--panel);border:1px solid var(--line);border-radius:14px;flex-direction:column;width:min(760px,100%);max-height:84vh;display:flex;box-shadow:0 24px 64px #00000040}.sheet-head{border-bottom:1px solid var(--line);padding:18px 20px 12px}.sheet-body{padding:6px 20px 12px;overflow-y:auto}.sheet-foot{border-top:1px solid var(--line);gap:12px;padding:14px 20px;display:grid}.command{font-size:15px;font-weight:600}.part{text-transform:uppercase;letter-spacing:.06em;color:var(--accent);margin:14px 0 6px;font-size:11px;font-weight:650}.plan{gap:8px;margin:0;padding:0;list-style:none;display:grid}.plan-step{grid-template-columns:26px 1fr;display:grid}.plan-index{color:var(--muted);font-family:var(--mono);padding-top:2px;font-size:12px}.plan-title{align-items:center;gap:8px;display:flex}.plan-command{color:var(--muted);word-break:break-all;margin-top:3px;font-size:12px;display:block}.confirm{gap:6px;display:grid}.buttons{justify-content:flex-end;gap:8px;display:flex}.timeline{gap:6px;display:grid}.step{border:1px solid var(--line);background:var(--panel);border-radius:9px}.step summary{cursor:pointer;grid-template-columns:22px 1fr auto auto;align-items:center;gap:10px;padding:9px 12px;list-style:none;display:grid}.step summary::-webkit-details-marker{display:none}.step-icon{place-items:center;font-weight:700;display:grid}.step-passed .step-icon{color:var(--ok)}.step-failed .step-icon{color:var(--bad)}.step-stopped .step-icon{color:var(--warn)}.step-waiting,.step-skipped{opacity:.55}.step-failed{border-color:var(--bad)}.step-running{border-color:var(--active)}.step-kind{color:var(--muted);font-size:11px;font-family:var(--mono)}.step-time{font-family:var(--mono);color:var(--muted);text-align:right;min-width:64px;font-size:12px}.output{background:var(--code-bg);max-height:60vh;color:var(--code-fg);font-family:var(--mono);white-space:pre-wrap;word-break:break-word;border-radius:8px;margin:0 12px 12px;padding:10px 12px;font-size:12.5px;overflow:auto}.output .stderr{color:#f0b3b3}.said{color:var(--code-fg)}.said-err{color:#ffb4b4}.run-footer{background:var(--panel);border:1px solid var(--line);font-family:var(--mono);border-radius:10px;margin-top:16px;padding:14px 16px}.tone-border-ok{border-left:4px solid var(--ok)}.tone-border-bad{border-left:4px solid var(--bad)}.tone-border-warn{border-left:4px solid var(--warn)}.tone-border-active{border-left:4px solid var(--active)}.lines div{white-space:pre-wrap}.ask{background:var(--bad-soft);border-radius:10px;flex-wrap:wrap;align-items:center;gap:10px;margin-bottom:14px;padding:14px 16px;display:flex}.sgr-red{color:#ff7b72}.sgr-green{color:#7ee787}.sgr-yellow{color:#f2cc60}.sgr-blue{color:#79c0ff}.sgr-magenta{color:#d2a8ff}.sgr-cyan{color:#76e3ea}.sgr-white,.sgr-bright-white{color:#fff}.sgr-black{color:#8b949e}.sgr-bright-red{color:#ffa198}.sgr-bright-green{color:#56d364}.sgr-bright-yellow{color:#e3b341}.sgr-bright-blue{color:#a5d6ff}.sgr-bright-magenta{color:#e2c5ff}.sgr-bright-cyan{color:#b3f0ff}.sgr-bright-black{color:#8b949e}.sgr-bold{font-weight:700}.sgr-dim{opacity:.6}.palette{background:var(--panel);border:1px solid var(--line);border-radius:14px;width:min(620px,100%);overflow:hidden;box-shadow:0 24px 64px #00000040}.palette input{border:none;border-bottom:1px solid var(--line);background:0 0;border-radius:0;outline:none;width:100%;padding:14px 16px;font-size:15px}.palette ul{max-height:50vh;margin:0;padding:6px;list-style:none;overflow-y:auto}.palette li{cursor:pointer;border-radius:8px;justify-content:space-between;padding:8px 10px;display:flex}.palette li .hint{display:inline}.palette li.selected{background:var(--accent-soft)}
@@ -0,0 +1,2 @@
1
+ (function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h={},g=[],_=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,v=Array.isArray;function y(e,t){for(var n in t)e[n]=t[n];return e}function ee(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function b(t,n,r){var i,a,o,s={};for(o in n)o==`key`?i=n[o]:o==`ref`?a=n[o]:s[o]=n[o];if(arguments.length>2&&(s.children=arguments.length>3?e.call(arguments,2):r),typeof t==`function`&&t.defaultProps!=null)for(o in t.defaultProps)s[o]===void 0&&(s[o]=t.defaultProps[o]);return x(t,s,i,a,null)}function x(e,r,i,a,o){var s={type:e,props:r,key:i,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++n,__i:-1,__u:0};return o==null&&t.vnode!=null&&t.vnode(s),s}function S(e){return e.children}function te(e,t){this.props=e,this.context=t}function C(e,t){if(t==null)return e.__?C(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type==`function`?C(e):null}function w(e){if(e.__P&&e.__d){var n=e.__v,r=n.__e,i=[],a=[],o=y({},n);o.__v=n.__v+1,t.vnode&&t.vnode(o),oe(e.__P,o,n,e.__n,e.__P.namespaceURI,32&n.__u?[r]:null,i,r??C(n),!!(32&n.__u),a),o.__v=n.__v,o.__.__k[o.__i]=o,ce(i,o,a),n.__e=n.__=null,o.__e!=r&&T(o)}}function T(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),T(e)}function E(e){(!e.__d&&(e.__d=!0)&&i.push(e)&&!D.__r++||a!=t.debounceRendering)&&((a=t.debounceRendering)||o)(D)}function D(){try{for(var e,t=1;i.length;)i.length>t&&i.sort(s),e=i.shift(),t=i.length,w(e)}finally{i.length=D.__r=0}}function ne(e,t,n,r,i,a,o,s,c,l,u){var d,f,p,m,_,v,y=r&&r.__k||g,ee=t.length;for(c=O(n,t,y,c,ee),d=0;d<ee;d++)(p=n.__k[d])!=null&&(f=p.__i!=-1&&y[p.__i]||h,p.__i=d,v=oe(e,p,f,i,a,o,s,c,l,u),m=p.__e,p.ref&&f.ref!=p.ref&&(f.ref&&de(f.ref,null,p),u.push(p.ref,p.__c||m,p)),_==null&&m!=null&&(_=m),4&p.__u?(c=re(p,c,e),f.__e&&(f.__e=null)):typeof p.type==`function`&&v!==void 0?c=v:m&&(c=m.nextSibling),p.__u&=-7);return n.__e=_,c}function O(e,t,n,r,i){var a,o,s,c,l,u=n.length,d=u,f=0;for(e.__k=Array(i),a=0;a<i;a++)(o=t[a])!=null&&typeof o!=`boolean`&&typeof o!=`function`?(typeof o==`string`||typeof o==`number`||typeof o==`bigint`||o.constructor==String?o=e.__k[a]=x(null,o,null,null,null):v(o)?o=e.__k[a]=x(S,{children:o},null,null,null):o.constructor===void 0&&o.__b>0?o=e.__k[a]=x(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):e.__k[a]=o,c=a+f,o.__=e,o.__b=e.__b+1,s=null,(l=o.__i=k(o,n,c,d))!=-1&&(d--,(s=n[l])&&(s.__u|=2)),s==null||s.__v==null?(l==-1&&(i>u?f--:i<u&&f++),typeof o.type!=`function`&&(o.__u|=4)):l!=c&&(l==c-1?f--:l==c+1?f++:(l>c?f--:f++,o.__u|=4))):e.__k[a]=null;if(d)for(a=0;a<u;a++)(s=n[a])!=null&&!(2&s.__u)&&(s.__e==r&&(r=C(s)),fe(s,s));return r}function re(e,t,n){var r,i;if(typeof e.type==`function`){for(r=e.__k,i=0;r&&i<r.length;i++)r[i]&&(r[i].__=e,t=re(r[i],t,n));return t}e.__e!=t&&(t&&e.type&&!t.parentNode&&(t=C(e)),t=n.insertBefore(e.__e,t||null));do t&&=t.nextSibling;while(t!=null&&t.nodeType==8);return t}function k(e,t,n,r){var i,a,o,s=e.key,c=e.type,l=t[n],u=l!=null&&!(2&l.__u);if(l===null&&s==null||u&&s==l.key&&c==l.type)return n;if(r>+!!u){for(i=n-1,a=n+1;i>=0||a<t.length;)if((l=t[o=i>=0?i--:a++])!=null&&!(2&l.__u)&&s==l.key&&c==l.type)return o}return-1}function ie(e,t,n){t[0]==`-`?e.setProperty(t,n??``):e[t]=n==null?``:typeof n!=`number`||_.test(t)?n:n+`px`}function A(e,t,n,r,i){var a,o;n:if(t==`style`){if(typeof n==`string`)e.style.cssText=n;else{if(typeof r==`string`&&(e.style.cssText=r=``),r)for(t in r)n&&t in n||ie(e.style,t,``);if(n)for(t in n)r&&n[t]==r[t]||ie(e.style,t,n[t])}}else if(t[0]==`o`&&t[1]==`n`)a=t!=(t=t.replace(d,`$1`)),o=t.toLowerCase(),t=o in e||t==`onFocusOut`||t==`onFocusIn`?o.slice(2):t.slice(2),e.l||={},e.l[t+a]=n,n?r?n[u]=r[u]:(n[u]=f,e.addEventListener(t,a?m:p,a)):e.removeEventListener(t,a?m:p,a);else{if(i==`http://www.w3.org/2000/svg`)t=t.replace(/xlink(H|:h)/,`h`).replace(/sName$/,`s`);else if(t!=`width`&&t!=`height`&&t!=`href`&&t!=`list`&&t!=`form`&&t!=`tabIndex`&&t!=`download`&&t!=`rowSpan`&&t!=`colSpan`&&t!=`role`&&t!=`popover`&&t in e)try{e[t]=n??``;break n}catch{}typeof n==`function`||(n==null||!1===n&&t[4]!=`-`?e.removeAttribute(t):e.setAttribute(t,t==`popover`&&n==1?``:n))}}function ae(e){return function(n){if(this.l){var r=this.l[n.type+e];if(n[l]==null)n[l]=f++;else if(n[l]<r[u])return;return r(t.event?t.event(n):n)}}}function oe(e,n,r,i,a,o,s,c,l,u){var d,f,p,m,h,_,b,x,w,T,E,D,O,re,k,ie,A=n.type;if(n.constructor!==void 0)return null;128&r.__u&&(l=!!(32&r.__u),o=[c=n.__e=r.__e]),(d=t.__b)&&d(n);n:if(typeof A==`function`){f=s.length;try{if(w=n.props,T=A.prototype&&A.prototype.render,E=(d=A.contextType)&&i[d.__c],D=d?E?E.props.value:d.__:i,r.__c?x=(p=n.__c=r.__c).__=p.__E:(T?n.__c=p=new A(w,D):(n.__c=p=new te(w,D),p.constructor=A,p.render=pe),E&&E.sub(p),p.state||(p.state={}),p.__n=i,m=p.__d=!0,p.__h=[],p._sb=[]),T&&p.__s==null&&(p.__s=p.state),T&&A.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=y({},p.__s)),y(p.__s,A.getDerivedStateFromProps(w,p.__s))),h=p.props,_=p.state,p.__v=n,m)T&&A.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),T&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(T&&A.getDerivedStateFromProps==null&&w!==h&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(w,D),n.__v==r.__v||!p.__e&&p.shouldComponentUpdate!=null&&!1===p.shouldComponentUpdate(w,p.__s,D)){n.__v!=r.__v&&(p.props=w,p.state=p.__s,p.__d=!1),n.__e=r.__e,n.__k=r.__k,n.__k.some(function(e){e&&(e.__=n)}),g.push.apply(p.__h,p._sb),p._sb=[],p.__h.length&&s.push(p),c=C(r);break n}p.componentWillUpdate!=null&&p.componentWillUpdate(w,p.__s,D),T&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(h,_,b)})}if(p.context=D,p.props=w,p.__P=e,p.__e=!1,O=t.__r,re=0,T)p.state=p.__s,p.__d=!1,O&&O(n),d=p.render(p.props,p.state,p.context),g.push.apply(p.__h,p._sb),p._sb=[];else do p.__d=!1,O&&O(n),d=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++re<25);p.state=p.__s,p.getChildContext!=null&&(i=y(y({},i),p.getChildContext())),T&&!m&&p.getSnapshotBeforeUpdate!=null&&(b=p.getSnapshotBeforeUpdate(h,_)),k=d!=null&&d.type===S&&d.key==null?le(d.props.children):d,c=ne(e,v(k)?k:[k],n,r,i,a,o,s,c,l,u),p.base=n.__e,n.__u&=-161,p.__h.length&&s.push(p),x&&(p.__E=p.__=null)}catch(e){if(s.length=f,n.__v=null,l||o!=null){if(e.then){for(n.__u|=l?160:128;c&&c.nodeType==8&&c.nextSibling;)c=c.nextSibling;o!=null&&(o[o.indexOf(c)]=null),n.__e=c}else if(o!=null)for(ie=o.length;ie--;)ee(o[ie])}else n.__e=r.__e;n.__k??=r.__k||[],e.then||se(n),t.__e(e,n,r)}}else o==null&&n.__v==r.__v?(n.__k=r.__k,n.__e=r.__e):c=n.__e=ue(r.__e,n,r,i,a,o,s,l,u);return(d=t.diffed)&&d(n),128&n.__u?void 0:c}function se(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(se))}function ce(e,n,r){for(var i=0;i<r.length;i++)de(r[i],r[++i],r[++i]);t.__c&&t.__c(n,e),e.some(function(n){try{e=n.__h,n.__h=[],e.some(function(e){e.call(n)})}catch(e){t.__e(e,n.__v)}})}function le(e){return typeof e!=`object`||!e||e.__b>0?e:v(e)?e.map(le):e.constructor===void 0?y({},e):null}function ue(n,r,i,a,o,s,c,l,u){var d,f,p,m,g,_,y,b=i.props||h,x=r.props,S=r.type;if(S==`svg`?o=`http://www.w3.org/2000/svg`:S==`math`?o=`http://www.w3.org/1998/Math/MathML`:o||=`http://www.w3.org/1999/xhtml`,s!=null){for(d=0;d<s.length;d++)if((g=s[d])&&`setAttribute`in g==!!S&&(S?g.localName==S:g.nodeType==3)){n=g,s[d]=null;break}}if(n==null){if(S==null)return document.createTextNode(x);n=document.createElementNS(o,S,x.is&&x),l&&=(t.__m&&t.__m(r,s),!1),s=null}if(S==null)b===x||l&&n.data==x||(n.data=x);else{if(s=S==`textarea`&&x.defaultValue!=null?null:s&&e.call(n.childNodes),!l&&s!=null)for(b={},d=0;d<n.attributes.length;d++)b[(g=n.attributes[d]).name]=g.value;for(d in b)g=b[d],d==`dangerouslySetInnerHTML`?p=g:d==`children`||d in x||d==`value`&&`defaultValue`in x||d==`checked`&&`defaultChecked`in x||A(n,d,null,g,o);for(d in x)g=x[d],d==`children`?m=g:d==`dangerouslySetInnerHTML`?f=g:d==`value`?_=g:d==`checked`?y=g:l&&typeof g!=`function`||b[d]===g||A(n,d,g,b[d],o);if(f)l||p&&(f.__html==p.__html||f.__html==n.innerHTML)||(n.innerHTML=f.__html),r.__k=[];else if(p&&(n.innerHTML=``),ne(r.type==`template`?n.content:n,v(m)?m:[m],r,i,a,S==`foreignObject`?`http://www.w3.org/1999/xhtml`:o,s,c,s?s[0]:i.__k&&C(i,0),l,u),s!=null)for(d=s.length;d--;)ee(s[d]);l&&S!=`textarea`||(d=`value`,S==`progress`&&_==null?n.removeAttribute(`value`):_!=null&&(_!==n[d]||S==`progress`&&!_||S==`option`&&_!=b[d])&&A(n,d,_,b[d],o),d=`checked`,y!=null&&y!=n[d]&&A(n,d,y,b[d],o))}return n}function de(e,n,r){try{if(typeof e==`function`){var i=typeof e.__u==`function`;i&&e.__u(),i&&n==null||(e.__u=e(n))}else e.current=n}catch(e){t.__e(e,r)}}function fe(e,n,r){var i,a;if(t.unmount&&t.unmount(e),(i=e.ref)&&(i.current&&i.current!=e.__e||de(i,null,n)),(i=e.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(e){t.__e(e,n)}i.base=i.__P=i.__n=null}if(i=e.__k)for(a=0;a<i.length;a++)i[a]&&fe(i[a],n,r||typeof e.type!=`function`);r||ee(e.__e),e.__c=e.__=e.__e=void 0}function pe(e,t,n){return this.constructor(e,n)}function me(n,r,i){var a,o,s,c;r==document&&(r=document.documentElement),t.__&&t.__(n,r),o=(a=typeof i==`function`)?null:i&&i.__k||r.__k,s=[],c=[],oe(r,n=(!a&&i||r).__k=b(S,null,[n]),o||h,h,r.namespaceURI,!a&&i?[i]:o?null:r.firstChild?e.call(r.childNodes):null,s,!a&&i?i:o?o.__e:r.firstChild,a,c),ce(s,n,c),n.props.children=null}e=g.slice,t={__e:function(e,t,n,r){for(var i,a,o;t=t.__;)if((i=t.__c)&&!i.__)try{if((a=i.constructor)&&a.getDerivedStateFromError!=null&&(i.setState(a.getDerivedStateFromError(e)),o=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(e,r||{}),o=i.__d),o)return i.__E=i}catch(t){e=t}throw e}},n=0,r=function(e){return e!=null&&e.constructor===void 0},te.prototype.setState=function(e,t){var n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=y({},this.state);typeof e==`function`&&(e=e(y({},n),this.props)),e&&y(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),E(this))},te.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),E(this))},te.prototype.render=S,i=[],o=typeof Promise==`function`?Promise.prototype.then.bind(Promise.resolve()):setTimeout,s=function(e,t){return e.__v.__b-t.__v.__b},D.__r=0,c=Math.random().toString(8),l=`__d`+c,u=`__a`+c,d=/(PointerCapture)$|Capture$/i,f=0,p=ae(!1),m=ae(!0);var he,j,ge,_e,ve=0,ye=[],M=t,be=M.__b,xe=M.__r,Se=M.diffed,Ce=M.__c,we=M.unmount,Te=M.__;function Ee(e,t){M.__h&&M.__h(j,e,ve||t),ve=0;var n=j.__H||(j.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function N(e){return ve=1,De(Ie,e)}function De(e,t,n){var r=Ee(he++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Ie(void 0,t),function(e){var t=r.__N?r.__N[0]:r.__[0],n=r.t(t,e);t!==n&&(r.__N=[n,r.__[1]],r.__c.setState({}))}],r.__c=j,!j.__f)){var i=function(e,t,n){if(!r.__c.__H)return!0;var i=!1,o=r.__c.props!==e;if(r.__c.__H.__.some(function(e){if(e.__N){i=!0;var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(o=!0)}}),a){var s=a.call(this,e,t,n);return i?s||o:s}return!i||o};j.__f=!0;var a=j.shouldComponentUpdate,o=j.componentWillUpdate;j.componentWillUpdate=function(e,t,n){if(this.__e){var r=a;a=void 0,i(e,t,n),a=r}o&&o.call(this,e,t,n)},j.shouldComponentUpdate=i}return r.__N||r.__}function P(e,t){var n=Ee(he++,3);!M.__s&&Fe(n.__H,t)&&(n.__=e,n.u=t,j.__H.__h.push(n))}function Oe(e){return ve=5,ke(function(){return{current:e}},[])}function ke(e,t){var n=Ee(he++,7);return Fe(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function Ae(){for(var e;e=ye.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(Ne),t.__h.some(Pe),t.__h=[]}catch(n){t.__h=[],M.__e(n,e.__v)}}}M.__b=function(e){j=null,be&&be(e)},M.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Te&&Te(e,t)},M.__r=function(e){xe&&xe(e),he=0;var t=(j=e.__c).__H;t&&(ge===j?(t.__h=[],j.__h=[],t.__.some(function(e){e.__N&&(e.__=e.__N),e.u=e.__N=void 0})):(t.__h.some(Ne),t.__h.some(Pe),t.__h=[],he=0)),ge=j},M.diffed=function(e){Se&&Se(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(ye.push(t)!==1&&_e===M.requestAnimationFrame||((_e=M.requestAnimationFrame)||Me)(Ae)),t.__H.__.some(function(e){e.u&&=(e.__H=e.u,void 0)})),ge=j=null},M.__c=function(e,t){t.some(function(e){try{e.__h.some(Ne),e.__h=e.__h.filter(function(e){return!e.__||Pe(e)})}catch(n){t.some(function(e){e.__h&&=[]}),t=[],M.__e(n,e.__v)}}),Ce&&Ce(e,t)},M.unmount=function(e){we&&we(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(e){try{Ne(e)}catch(e){t=e}}),n.__H=void 0,t&&M.__e(t,n.__v))};var je=typeof requestAnimationFrame==`function`;function Me(e){var t,n=function(){clearTimeout(r),je&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);je&&(t=requestAnimationFrame(n))}function Ne(e){var t=j,n=e.__c;typeof n==`function`&&(e.__c=void 0,n()),j=t}function Pe(e){var t=j;e.__c=e.__(),j=t}function Fe(e,t){return!e||e.length!==t.length||t.some(function(t,n){return t!==e[n]})}function Ie(e,t){return typeof t==`function`?t(e):t}var Le=Symbol.for(`preact-signals`);function Re(){if(I>1)I--;else{var e,t=!1;for((function(){var e=Ke;for(Ke=void 0;e!==void 0;){var t=e.S;if(t.v===e.v)for(var n=t.t;n!==void 0;n=n.x)n.i===e.i&&(n.i=t.i);e=e.o}})();He!==void 0;){var n=He;for(He=void 0,Ue++;n!==void 0;){var r=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&Ye(n))try{n.c()}catch(n){t||=(e=n,!0)}n=r}}if(Ue=0,I--,t)throw e}}function ze(e){if(I>0)return e();Ge=++We,I++;try{return e()}finally{Re()}}var Be,F=void 0;function Ve(e){var t=F,n=Be;F=void 0,Be=void 0;try{return e()}finally{F=t,Be=n}}var He=void 0,I=0,Ue=0,We=0,Ge=0,Ke=void 0,qe=0;function Je(e){if(F!==void 0){var t=e.n;if(t===void 0||t.t!==F)return t={i:0,S:e,p:F.s,n:void 0,t:F,e:void 0,x:void 0,r:t},F.s!==void 0&&(F.s.n=t),F.s=t,e.n=t,32&F.f&&e.S(t),t;if(t.i===-1)return t.i=0,t.n!==void 0&&(t.n.p=t.p,t.p!==void 0&&(t.p.n=t.n),t.p=F.s,t.n=void 0,F.s.n=t,F.s=t),t}}function L(e,t){this.v=e,this.i=0,this.n=void 0,this.t=void 0,this.l=0,this.W=t?.watched,this.Z=t?.unwatched,this.name=t?.name}L.prototype.brand=Le,L.prototype.h=function(){return!0},L.prototype.S=function(e){var t=this,n=this.t;n!==e&&e.e===void 0&&(e.x=n,this.t=e,n===void 0?Ve(function(){var e;(e=t.W)==null||e.call(t)}):n.e=e)},L.prototype.U=function(e){var t=this;if(this.t!==void 0){var n=e.e,r=e.x;n!==void 0&&(n.x=r,e.e=void 0),r!==void 0&&(r.e=n,e.x=void 0),e===this.t&&(this.t=r,r===void 0&&Ve(function(){var e;(e=t.Z)==null||e.call(t)}))}},L.prototype.subscribe=function(e){var t=this;return nt(function(){var n=t.value;Ve(function(){return e(n)})},{name:`sub`})},L.prototype.valueOf=function(){return this.value},L.prototype.toString=function(){return this.value+``},L.prototype.toJSON=function(){return this.value},L.prototype.peek=function(){var e=this;return Ve(function(){return e.value})},Object.defineProperty(L.prototype,"value",{get:function(){var e=Je(this);return e!==void 0&&(e.i=this.i),this.v},set:function(e){if(e!==this.v){if(Ue>100)throw Error(`Cycle detected`);(function(e){I!==0&&Ue===0&&e.l!==Ge&&(e.l=Ge,Ke={S:e,v:e.v,i:e.i,o:Ke})})(this),this.v=e,this.i++,qe++,I++;try{for(var t=this.t;t!==void 0;t=t.x)t.t.N()}finally{Re()}}}});function R(e,t){return new L(e,t)}function Ye(e){for(var t=e.s;t!==void 0;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return!0;return!1}function Xe(e){for(var t=e.s;t!==void 0;t=t.n){var n=t.S.n;if(n!==void 0&&(t.r=n),t.S.n=t,t.i=-1,t.n===void 0){e.s=t;break}}}function Ze(e){for(var t=e.s,n=void 0;t!==void 0;){var r=t.p;t.i===-1?(t.S.U(t),r!==void 0&&(r.n=t.n),t.n!==void 0&&(t.n.p=r)):n=t,t.S.n=t.r,t.r!==void 0&&(t.r=void 0),t=r}e.s=n}function z(e,t){L.call(this,void 0,t),this.x=e,this.s=void 0,this.g=qe-1,this.f=4}z.prototype=new L,z.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===qe))return!0;if(this.g=qe,this.f|=1,this.i>0&&!Ye(this))return this.f&=-2,!0;var e=F;try{Xe(this),F=this;var t=this.x();(16&this.f||this.v!==t||this.i===0)&&(this.v=t,this.f&=-17,this.i++)}catch(e){this.v=e,this.f|=16,this.i++}return F=e,Ze(this),this.f&=-2,!0},z.prototype.S=function(e){if(this.t===void 0){this.f|=36;for(var t=this.s;t!==void 0;t=t.n)t.S.S(t)}L.prototype.S.call(this,e)},z.prototype.U=function(e){if(this.t!==void 0&&(L.prototype.U.call(this,e),this.t===void 0)){this.f&=-33;for(var t=this.s;t!==void 0;t=t.n)t.S.U(t)}},z.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var e=this.t;e!==void 0;e=e.x)e.t.N()}},Object.defineProperty(z.prototype,"value",{get:function(){if(1&this.f)throw Error(`Cycle detected`);var e=Je(this);if(this.h(),e!==void 0&&(e.i=this.i),16&this.f)throw this.v;return this.v}});function Qe(e,t){return new z(e,t)}function $e(e){var t=e.m;if(e.m=void 0,typeof t==`function`){I++;var n=F;F=void 0;try{t()}catch(t){throw e.f&=-2,e.f|=8,et(e),t}finally{F=n,Re()}}}function et(e){for(var t=e.s;t!==void 0;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,$e(e)}function tt(e){if(F!==this)throw Error(`Out-of-order effect`);Ze(this),F=e,this.f&=-2,8&this.f&&et(this),Re()}function B(e,t){this.x=e,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=t?.name,Be&&Be.push(this)}B.prototype.c=function(){var e=this.S();try{if(8&this.f||this.x===void 0)return;var t=this.x();typeof t==`function`&&(this.m=t)}finally{e()}},B.prototype.S=function(){if(1&this.f)throw Error(`Cycle detected`);this.f|=1,this.f&=-9,$e(this),Xe(this),I++;var e=F;return F=this,tt.bind(this,e)},B.prototype.N=function(){2&this.f||(this.f|=2,this.u=He,He=this)},B.prototype.d=function(){this.f|=8,1&this.f||et(this)},B.prototype.dispose=function(){this.d()};function nt(e,t){var n=new B(e,t);try{n.c()}catch(e){throw n.d(),e}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var rt,it,at=typeof window<`u`&&!!window.__PREACT_SIGNALS_DEVTOOLS__,ot=[];nt(function(){rt=this.N})();function V(e,n){t[e]=n.bind(null,t[e]||function(){})}function st(e){if(it){var t=it;it=void 0,t()}it=e&&e.S()}function ct(e){var t=this,n=e.data,i=ut(n);i.name=`ReactiveDom`,i.value=n;var a=ke(function(){for(var e=t,n=t.__v;n=n.__;)if(n.__c){n.__c.__$f|=4;break}var a=Qe(function(){var e=i.value.value;return e===0?0:!0===e?``:e||``}),o=Qe(function(){return!Array.isArray(a.value)&&!r(a.value)}),s=nt(function(){if(this.N=pt,o.value){var t=a.value;e.__v&&e.__v.__e&&e.__v.__e.nodeType===3&&(e.__v.__e.data=t)}}),c=t.__$u.d;return t.__$u.d=function(){s(),c.call(this)},[o,a]},[]),o=a[0],s=a[1];return o.value?s.peek():s.value}ct.displayName=`ReactiveTextNode`,Object.defineProperties(L.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:ct},props:{configurable:!0,get:function(){var e=this;return{data:{get value(){return e.value}}}}},__b:{configurable:!0,value:1}}),V(`__b`,function(e,t){if(st(),typeof t.type==`string`){var n,r=t.props;for(var i in r)if(i!==`children`){var a=r[i];a instanceof L&&(n||(t.__np=n={}),n[i]=a,r[i]=a.peek())}}e(t)}),V(`__r`,function(e,t){if(e(t),t.type!==S){st();var n,r=t.__c;r&&(r.__$f&=-2,(n=r.__$u)===void 0&&(r.__$u=n=function(e,t){var n;return nt(function(){n=this},{name:t}),n.c=e,n}(function(e){return function(){var t;at&&((t=this.y)==null||t.call(this)),e.__$f|=1,e.setState({})}}(r),typeof t.type==`function`?t.type.displayName||t.type.name:``))),st(n)}}),V(`__e`,function(e,t,n,r){st(),e(t,n,r)}),V(`diffed`,function(e,t){st();var n;if(typeof t.type==`string`&&(n=t.__e)){var r=t.__np,i=t.props,a=n.U;if(a)for(var o in a){var s=a[o];s===void 0||r&&o in r||(s.d(),a[o]=void 0)}if(r)for(var c in a||(a={},n.U=a),r){var l=a[c],u=r[c];l===void 0?(l=lt(n,c,u,i),a[c]=l):l.o(u,i)}}e(t)});function lt(e,t,n,r){var i=t in e&&e.ownerSVGElement===void 0,a=R(n);return{o:function(e,t){a.value=e,r=t},d:nt(function(){this.N=pt;var n=a.value.value;r[t]!==n&&(r[t]=n,i?e[t]=n:n!=null&&(!1!==n||t[4]===`-`)?e.setAttribute(t,n):e.removeAttribute(t))})}}V(`unmount`,function(e,t){if(typeof t.type==`string`){var n=t.__e;if(n){var r=n.U;if(r)for(var i in n.U=void 0,r){var a=r[i];a&&a.d()}}var o=t.__np;if(o){var s=t.props;for(var c in o)s[c]=o[c]}t.__np=void 0}else{var l=t.__c;if(l){l.__$f|=8;var u=l.__$u;u&&(l.__$u=void 0,u.d())}}e(t)}),V(`__h`,function(e,t,n,r){r<3&&(t.__$f|=2),e(t,n,r)}),te.prototype.shouldComponentUpdate=function(e,t){if(this.__R)return!0;var n=this.__$u,r=n&&n.s!==void 0;for(var i in t)return!0;if(this.__f||typeof this.u==`boolean`&&!0===this.u){var a=2&this.__$f;if(!(r||a||4&this.__$f)||1&this.__$f)return!0}else if(!(r||4&this.__$f)||3&this.__$f)return!0;for(var o in e)if(o!==`__source`&&e[o]!==this.props[o])return!0;for(var s in this.props)if(!(s in e))return!0;return!1};function ut(e,t){return ke(function(){return R(e,t)},[])}var dt=function(e){queueMicrotask(function(){queueMicrotask(e)})};function ft(){ze(function(){for(var e;e=ot.shift();)rt.call(e)})}function pt(){ot.push(this)===1&&(t.requestAnimationFrame||dt)(ft)}var mt=(e,t)=>{let n=t.toLowerCase().replace(/\s+/g,``);if(n===``)return 0;let r=e.toLowerCase(),i=Array.from(n).reduce((e,t)=>{if(e===void 0)return;let n=r.indexOf(t,e.at);return n===-1?void 0:{at:n+1,gaps:e.gaps+(e.first===-1?0:n-e.at),first:e.first===-1?n:e.first}},{at:0,gaps:0,first:-1});return i===void 0?void 0:i.gaps*2+i.first+(r.startsWith(n)?-10:0)},ht=(e,t)=>e.flatMap(e=>{let n=mt(`${e.label} ${e.hint}`,t);return n===void 0?[]:[{choice:e,scored:n}]}).toSorted((e,t)=>e.scored-t.scored).map(e=>e.choice),gt=e=>e,_t=async(e,t)=>e.ok?{ok:!0,value:gt(await t(e))}:{ok:!1,failure:{status:e.status,message:(await e.text()).trim()}},vt=async e=>_t(await fetch(e),e=>e.json()),yt=async e=>_t(await fetch(e),e=>e.text()),bt=async(e,t)=>_t(await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)}),async e=>e.status===204||e.status===202?void 0:e.json()),xt=e=>bt(`/api/plan`,e),St=(e,t)=>bt(`/api/runs`,{command:e,...t===void 0?{}:{confirm:t}}),Ct=(e,t)=>bt(`/api/runs/${encodeURIComponent(e)}/answer`,{text:t}),wt=e=>bt(`/api/runs/${encodeURIComponent(e)}/cancel`,{}),Tt=()=>vt(`/api/runs`),Et=(e,t,n)=>{let r=new EventSource(e),i=()=>{r.close()};return r.addEventListener(`message`,e=>{t(gt(JSON.parse(e.data)))}),r.addEventListener(`end`,()=>{i(),n()}),r.addEventListener(`error`,()=>{i(),n()}),i},Dt=/^[A-Za-z0-9._-]+$/,Ot=e=>{let t=e.split(`/`).filter(e=>e!==``).map(decodeURIComponent);if(!t.every(e=>Dt.test(e)))return{page:`missing`,path:e};let[n,r,i,a]=t;return n===void 0?{page:`fleet`}:n===`runs`&&r===void 0?{page:`runs`}:n===`runs`&&r!==void 0&&i===void 0?{page:`run`,id:r}:n===`validate`&&r===void 0?{page:`validate`}:n===`servers`&&r!==void 0&&i===void 0?{page:`server`,server:r}:n===`servers`&&r!==void 0&&i===`apps`&&a!==void 0&&t.length===4?{page:`app`,server:r,app:a}:{page:`missing`,path:e}},kt=e=>{switch(e.page){case`fleet`:return`/`;case`server`:return`/servers/${encodeURIComponent(e.server)}`;case`app`:return`/servers/${encodeURIComponent(e.server)}/apps/${encodeURIComponent(e.app)}`;case`runs`:return`/runs`;case`run`:return`/runs/${encodeURIComponent(e.id)}`;case`validate`:return`/validate`;case`missing`:return e.path}},At=R(Ot(location.pathname)),jt=e=>{history.pushState(null,``,kt(e)),At.value=e,scrollTo({top:0})};addEventListener(`popstate`,()=>{At.value=Ot(location.pathname)});var H=R({state:`loading`}),U=R({value:void 0,live:!1}),Mt=R({state:`loading`}),Nt=async()=>{let e=await vt(`/api/fleet`);H.value=e.ok?{state:`ready`,value:e.value}:{state:`failed`,failure:e.failure}},Pt=()=>{U.value={value:U.value.value,live:!0},Et(`/api/status`,e=>{U.value={value:e,live:!0}},()=>{U.value={value:U.value.value,live:!1}})},Ft=async()=>{Mt.value={state:`loading`};let e=await vt(`/api/validate`);Mt.value=e.ok?{state:`ready`,value:e.value}:{state:`failed`,failure:e.failure}},It=0;Array.isArray;function W(e,n,r,i,a,o){n||={};var s,c,l=n;if(`ref`in l)for(c in l={},n)c==`ref`?s=n[c]:l[c]=n[c];var u={type:e,props:l,key:r,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--It,__i:-1,__u:0,__source:a,__self:o};if(typeof e==`function`&&(s=e.defaultProps))for(c in s)l[c]===void 0&&(l[c]=s[c]);return t.vnode&&t.vnode(u),u}var Lt=(e,t)=>{if(typeof e==`string`)return e;let n=e.tone===void 0?void 0:`tone-${e.tone}`;return e.href===void 0?W(`span`,{class:n,children:e.text},t):W(`a`,{class:n,href:e.href,target:`_blank`,rel:`noreferrer`,children:e.text},t)},Rt=({text:e})=>W(S,{children:(typeof e==`string`?[e]:e).map(Lt)}),zt=({lines:e})=>W(`div`,{class:`lines`,children:e.map((e,t)=>W(`div`,{children:W(Rt,{text:e})},t))}),G=({tone:e,label:t})=>W(`span`,{class:`dot dot-${e}`,title:t,"aria-label":t,role:t===void 0?void 0:`img`}),K=({children:e,tone:t})=>W(`span`,{class:`pill${t===void 0?``:` pill-${t}`}`,children:e}),q=({label:e,cell:t})=>t===void 0?null:W(`div`,{class:`fact`,children:[W(`dt`,{children:e}),W(`dd`,{title:t.title,children:[W(G,{tone:t.tone}),W(`span`,{class:t.tone===`waiting`?`tone-muted`:`tone-${t.tone}`,children:t.text})]})]}),J=({failure:e})=>W(`div`,{class:`problem`,role:`alert`,children:[W(`strong`,{children:[`kayra ui answered `,e.status]}),W(`pre`,{children:e.message})]}),Y=({what:e})=>W(`div`,{class:`waiting`,children:[W(`span`,{class:`spinner`,"aria-hidden":`true`}),` `,e]}),X=({title:e,sub:t,children:n})=>W(`header`,{class:`page-header`,children:[W(`div`,{children:[W(`h1`,{children:e}),t===void 0?null:W(`div`,{class:`sub`,children:t})]}),n===void 0?null:W(`div`,{class:`actions`,children:n})]}),Bt=R(void 0),Z=e=>{Bt.value=e},Vt=()=>{Bt.value=void 0},Ht=e=>e===`guard`?`warn`:e===`confirm`?`bad`:e===`note`?`muted`:`active`,Ut=({step:e})=>W(`li`,{class:`plan-step`,children:[W(`span`,{class:`plan-index`,children:e.index+1}),W(`div`,{children:[W(`div`,{class:`plan-title`,children:[W(K,{tone:Ht(e.kind),children:e.kind}),` `,e.title]}),e.command===void 0?null:W(`code`,{class:`plan-command`,children:e.command})]})]}),Wt=e=>{if(e.name===`doctor`)return;let t=H.value,n=t.state===`ready`?t.value.servers.find(t=>t.name===e.server):void 0;return n===void 0||n.target===`multipass`?void 0:n.name},Gt=({command:e})=>{let[t,n]=N(void 0),[r,i]=N(``),[a,o]=N(void 0),s=Oe(null),c=t?.ok===!0;if(P(()=>{c&&s.current?.focus()},[c]),P(()=>{xt(e).then(n)},[e]),t===void 0)return W(Y,{what:`Planning`});if(!t.ok)return W(J,{failure:t.failure});let{invocation:l,steps:u,changes:d}=t.value,f=d?Wt(e):void 0,p=f===void 0||r===f,m=async()=>{o(`starting`);let t=await St(e,f===void 0?void 0:r);t.ok?(Vt(),jt({page:`run`,id:t.value.id})):o(t.failure)},h=u.reduce((e,t)=>{let n=e.at(-1);return t.opens!==void 0||n===void 0?[...e,{part:t.opens,steps:[t]}]:[...e.slice(0,-1),{...n,steps:[...n.steps,t]}]},[]);return W(S,{children:[W(`div`,{class:`sheet-head`,children:[W(`code`,{class:`command`,children:l.command}),W(`div`,{class:`sub`,children:[l.about.join(` · `),` · `,u.length,` steps · `,d?`changes things`:`reads only`]})]}),W(`div`,{class:`sheet-body`,children:h.map((e,t)=>W(`section`,{children:[e.part===void 0?null:W(`h3`,{class:`part`,children:e.part}),W(`ol`,{class:`plan`,children:e.steps.map(e=>W(Ut,{step:e},e.index))})]},t))}),W(`form`,{class:`sheet-foot`,onSubmit:e=>{e.preventDefault(),p&&m()},children:[f===void 0?null:W(`label`,{class:`confirm`,children:[W(`span`,{children:[`This changes `,W(`strong`,{children:f}),`, a real server. Type its name to go on:`]}),W(`input`,{ref:s,value:r,onInput:e=>{i(e.currentTarget.value)},placeholder:f,spellcheck:!1})]}),a===void 0||a===`starting`?null:W(J,{failure:a}),W(`div`,{class:`buttons`,children:[W(`button`,{type:`button`,class:`button`,onClick:Vt,children:`Cancel`}),W(`button`,{type:`submit`,class:f===void 0?`button primary`:`button danger`,disabled:!p||a===`starting`,children:a===`starting`?`Starting…`:`Run ${l.command}`})]})]})]})},Kt=()=>{let e=Bt.value;return P(()=>{let e=e=>{e.key===`Escape`&&Vt()};return addEventListener(`keydown`,e),()=>{removeEventListener(`keydown`,e)}},[]),e===void 0?null:W(`div`,{class:`overlay`,onClick:Vt,children:W(`div`,{class:`sheet`,role:`dialog`,"aria-modal":`true`,onClick:e=>{e.stopPropagation()},children:W(Gt,{command:e})})})},Q=R(!1),qt=()=>{let e=H.value;return[{label:`Fleet`,hint:`every server`,go:{page:`fleet`}},{label:`Runs`,hint:`what ran from here`,go:{page:`runs`}},{label:`Validate`,hint:`the fleet beyond its schemas`,go:{page:`validate`}},{label:`doctor`,hint:`can this Mac run everything`,run:{name:`doctor`}},...(e.state===`ready`?e.value.servers:[]).flatMap(e=>[{label:e.name,hint:`${e.kind} on ${e.target}`,go:{page:`server`,server:e.name}},...e.apps.map(t=>({label:`${e.name}/${t}`,hint:`app`,go:{page:`app`,server:e.name,app:t}})),...e.commands.flatMap(t=>t===`job`?[]:[{label:`${t} ${e.name}`,hint:`run`,run:{name:t,server:e.name}}])])]},Jt=e=>{Q.value=!1,`go`in e?jt(e.go):Z(e.run)},Yt=()=>{let[e,t]=N(``),[n,r]=N(0),i=Oe(null),a=Q.value;if(P(()=>{a&&i.current?.focus()},[a]),P(()=>{let e=e=>{(e.metaKey||e.ctrlKey)&&e.key.toLowerCase()===`k`?(e.preventDefault(),Q.value=!Q.value,t(``),r(0)):e.key===`Escape`&&(Q.value=!1)};return addEventListener(`keydown`,e),()=>{removeEventListener(`keydown`,e)}},[]),!Q.value)return null;let o=ht(qt(),e).slice(0,12);return W(`div`,{class:`overlay`,onClick:()=>{Q.value=!1},children:W(`div`,{class:`palette`,role:`dialog`,"aria-modal":`true`,onClick:e=>{e.stopPropagation()},children:[W(`input`,{ref:i,value:e,placeholder:`Go to, or run…`,spellcheck:!1,onInput:e=>{t(e.currentTarget.value),r(0)},onKeyDown:e=>{if(e.key===`ArrowDown`)r(Math.min(n+1,o.length-1));else if(e.key===`ArrowUp`)r(Math.max(n-1,0));else if(e.key===`Enter`){let e=o[n];e!==void 0&&Jt(e)}else return;e.preventDefault()}}),W(`ul`,{children:o.map((e,t)=>W(`li`,{class:t===n?`selected`:void 0,onMouseEnter:()=>{r(t)},onClick:()=>{Jt(e)},children:[W(`span`,{children:e.label}),W(`span`,{class:`hint`,children:e.hint})]},e.label))})]})})},Xt=()=>{Q.value=!0},Zt=e=>e===null?``:` · ${String(e)} ms`,Qt={pending:`asking`,open:`open`,answered:`answered`,refused:`refused`,"no-answer":`no answer`,unreachable:`unreachable`,"unknown-host":`unknown host`,"bad-certificate":`bad certificate`,failed:`failed`,skipped:`not asked`},$t=e=>{let{state:t,address:n,reason:r}=e.machine;switch(t){case`pending`:return{text:`asking OpenTofu`,tone:`waiting`};case`found`:return{text:n??`an address OpenTofu does not give`,tone:n===null?`warn`:`strong`};case`not-provisioned`:return{text:`not provisioned`,tone:`muted`};case`no-machine`:return{text:`no machine in its state`,tone:`muted`};case`unreadable`:return{text:`state unreadable`,tone:`bad`,...r===null?{}:{title:r}}}},en=e=>{let{state:t,error:n}=e.ssh;switch(t){case`pending`:return{text:`connecting`,tone:`waiting`};case`open`:return{text:`port ${String(e.ssh.port)} open${Zt(e.ssh.ms)}`,tone:`ok`};case`refused`:return{text:`off (refused)`,tone:`warn`,title:`Nothing listens: SSH may be on only on demand.`};case`skipped`:return{text:`not asked`,tone:`muted`};case`answered`:case`no-answer`:case`unreachable`:case`unknown-host`:case`bad-certificate`:case`failed`:return{text:Qt[t],tone:`bad`,...n===null?{}:{title:n}}}},tn=e=>{let{https:t}=e;if(t!==null)switch(t.state){case`pending`:return{text:`asking`,tone:`waiting`};case`answered`:return{text:`HTTP ${String(t.status??`?`)}${Zt(t.ms)}`,tone:t.status!==null&&t.status<400?`ok`:`bad`};case`skipped`:return{text:`not asked`,tone:`muted`};case`open`:case`refused`:case`no-answer`:case`unreachable`:case`unknown-host`:case`bad-certificate`:case`failed`:return{text:Qt[t.state],tone:`bad`,...t.error===null?{}:{title:t.error}}}},nn=e=>{if(e===void 0)return`waiting`;let t=[$t(e),en(e),tn(e)].flatMap(e=>e===void 0?[]:[e.tone]);return t.includes(`waiting`)?`waiting`:t.includes(`bad`)?`bad`:t.includes(`warn`)?`warn`:t.includes(`ok`)?`ok`:`muted`},$=({to:e,children:t,class:n})=>W(`a`,{href:kt(e),class:n,onClick:t=>{t.metaKey||t.ctrlKey||t.shiftKey||t.button!==0||(t.preventDefault(),jt(e))},children:t}),rn=(e,t)=>kt(e)===kt(t),an=({to:e,label:t})=>W($,{to:e,class:rn(At.value,e)?`nav-item current`:`nav-item`,children:t}),on=()=>{let e=H.value;if(e.state!==`ready`)return null;let t=At.value;return W(`nav`,{class:`servers`,"aria-label":`Servers`,children:[W(`div`,{class:`nav-title`,children:`Servers`}),e.value.servers.map(e=>W($,{to:{page:`server`,server:e.name},class:`server`in t&&t.server===e.name?`nav-item current`:`nav-item`,children:[W(G,{tone:nn(U.value.value?.servers.find(t=>t.name===e.name))}),W(`span`,{children:e.name}),W(`span`,{class:`nav-meta`,children:e.kind})]},e.name))]})},sn=({children:e})=>{let t=H.value;return W(`div`,{class:`shell`,children:[W(`aside`,{class:`sidebar`,children:[W($,{to:{page:`fleet`},class:`brand`,children:[W(`span`,{class:`logo`,"aria-hidden":`true`,children:`k`}),W(`span`,{children:[W(`strong`,{children:`kayra`}),W(`span`,{class:`brand-sub`,children:t.state===`ready`?t.value.fleet:`…`})]})]}),W(`nav`,{"aria-label":`Pages`,children:[W(an,{to:{page:`fleet`},label:`Fleet`}),W(an,{to:{page:`runs`},label:`Runs`}),W(an,{to:{page:`validate`},label:`Validate`})]}),W(on,{}),W(`div`,{class:`sidebar-foot`,children:t.state===`ready`?`kayra ${t.value.version}`:``})]}),W(`main`,{class:`main`,children:e})]})},cn=e=>{let t=Math.max(0,e)/1e3;if(t<10)return`${(Math.floor(t*10)/10).toFixed(1)}s`;if(t<60)return`${String(Math.floor(t))}s`;let n=Math.floor(t/60);return n<60?`${String(n)}m${String(Math.floor(t%60)).padStart(2,`0`)}s`:`${String(Math.floor(n/60))}h${String(n%60).padStart(2,`0`)}m`},ln=e=>{let t=Math.floor(Math.max(0,e)/1e3);if(t<10)return`just now`;if(t<60)return`${String(t)}s ago`;let n=Math.floor(t/60);if(n<60)return`${String(n)}m ago`;let r=Math.floor(n/60);return r<48?`${String(r)}h ago`:`${String(Math.floor(r/24))}d ago`},un=e=>Date.parse(e),dn=(e,t,n)=>`/api/servers/${encodeURIComponent(e)}/apps/${encodeURIComponent(t)}/${n}`,fn=(e,t)=>{let[n,r]=N(void 0),i=()=>{r(void 0),e().then(r)};return P(i,[t]),[n,i]},pn=e=>e===`success`?`ok`:e===`failure`?`bad`:`waiting`,mn=({server:e,app:t,open:n})=>{let[r]=fn(()=>vt(dn(e,t,`runs`)),`${e}/${t}`);if(r===void 0)return W(Y,{what:`Asking the deployer`});if(!r.ok)return W(J,{failure:r.failure});let i=Date.now(),{live:a,runs:o}=r.value;return W(S,{children:[W(`p`,{class:`sub`,children:a===void 0?`Not deployed yet.`:`Live: ${a.sha.slice(0,7)} since ${ln(i-Date.parse(a.time))}`}),W(`table`,{class:`table`,children:[W(`thead`,{children:W(`tr`,{children:[W(`th`,{}),W(`th`,{children:`Commit`}),W(`th`,{children:`Why`}),W(`th`,{children:`What`}),W(`th`,{class:`right`,children:`When`}),W(`th`,{class:`right`,children:`Took`})]})}),W(`tbody`,{children:o.map(e=>W(`tr`,{class:`clickable`,onClick:()=>{n(e.id)},children:[W(`td`,{class:`narrow`,children:W(G,{tone:pn(e.state),label:e.state})}),W(`td`,{children:W(`code`,{children:e.sha?.slice(0,7)??``})}),W(`td`,{children:e.why}),W(`td`,{children:e.what}),W(`td`,{class:`right tone-muted`,children:ln(i-Date.parse(e.started))}),W(`td`,{class:`right tone-muted`,children:e.finished===void 0?``:cn(Date.parse(e.finished)-Date.parse(e.started))})]},e.id))})]})]})},hn=({server:e,app:t})=>{let[n]=fn(()=>vt(dn(e,t,`releases`)),`${e}/${t}`);if(n===void 0)return W(Y,{what:`Asking the deployer`});if(!n.ok)return W(J,{failure:n.failure});let r=Date.now();return W(`ul`,{class:`releases`,children:n.value.releases.map(n=>W(`li`,{children:[W(`code`,{children:n.sha.slice(0,12)}),W(`span`,{class:`tone-muted`,children:ln(r-Date.parse(n.time))}),n.live?W(K,{tone:`ok`,children:`live`}):W(`button`,{class:`button small`,onClick:()=>{Z({name:`app rollback`,server:e,app:t,sha:n.sha})},children:`Roll back to it`})]},n.sha))})},gn=e=>{if(/\b(error|failed|fatal|refused)\b/i.test(e))return`tone-bad`;if(/\bwarn(ing)?\b/i.test(e))return`tone-warn`},_n=({server:e,app:t,run:n})=>{let[r]=fn(()=>yt(dn(e,t,n===void 0?`logs`:`logs/${encodeURIComponent(n)}`)),`${e}/${t}/${n??``}`);return r===void 0?W(Y,{what:`Fetching the log`}):r.ok?W(`pre`,{class:`log`,children:r.value.split(`
2
+ `).map((e,t)=>W(`div`,{class:gn(e),children:e===``?` `:e},t))}):W(J,{failure:r.failure})},vn=({server:e,app:t})=>{let[n,r]=N(`runs`),[i,a]=N(void 0),[o,s]=N(``);return W(S,{children:[W(X,{title:t,sub:`on ${e}`,children:W(`form`,{class:`inline`,onSubmit:n=>{n.preventDefault(),Z({name:`app deploy`,server:e,app:t,...o.trim()===``?{}:{ref:o.trim()}})},children:[W(`input`,{value:o,onInput:e=>{s(e.currentTarget.value)},placeholder:`its ref`,spellcheck:!1,"aria-label":`Branch, tag or commit`}),W(`button`,{type:`submit`,class:`button primary`,children:`Deploy`})]})}),W(`nav`,{class:`tabs`,role:`tablist`,children:[`runs`,`releases`,`log`].map(e=>W(`button`,{role:`tab`,"aria-selected":n===e,class:n===e?`tab current`:`tab`,onClick:()=>{r(e)},children:[e,e===`log`&&i!==void 0?` · ${i}`:``]},e))}),W(`section`,{class:`card`,children:n===`runs`?W(mn,{server:e,app:t,open:e=>{a(e),r(`log`)}}):n===`releases`?W(hn,{server:e,app:t}):W(_n,{server:e,app:t,run:i})}),W(`p`,{class:`tone-muted small`,children:[`Purging an app's data is irreversible:`,` `,W(`button`,{class:`link danger-link`,onClick:()=>{Z({name:`app purge`,server:e,app:t})},children:[`purge `,t,`'s volumes`]})]})]})},yn=({facts:e,seen:t})=>W($,{to:{page:`server`,server:e.name},class:`card server-card`,children:[W(`div`,{class:`card-head`,children:[W(G,{tone:nn(t)}),W(`h2`,{children:e.name}),W(K,{children:e.kind}),W(K,{tone:e.target===`multipass`?`muted`:e.target===`hetzner`?`accent`:`active`,children:e.target})]}),W(`div`,{class:`domain`,children:e.domain}),t===void 0?W(Y,{what:`asking`}):W(`dl`,{class:`facts`,children:[W(q,{label:`Address`,cell:$t(t)}),W(q,{label:`SSH`,cell:en(t)}),W(q,{label:`Login`,cell:tn(t)})]}),e.apps.length===0?null:W(`div`,{class:`chips`,children:e.apps.map(e=>W(K,{children:e},e))})]}),bn=()=>{let e=H.value;if(e.state===`loading`)return W(Y,{what:`Reading the fleet`});if(e.state===`failed`)return W(J,{failure:e.failure});let{value:t,live:n}=U.value,{servers:r}=e.value,i=r.filter(e=>nn(t?.servers.find(t=>t.name===e.name))===`ok`).length;return W(S,{children:[W(X,{title:`Fleet`,sub:W(S,{children:[r.length,` servers · `,t===void 0?`asking each`:`${String(i)} answering everything they were asked`]}),children:W(`button`,{class:`button`,onClick:Pt,disabled:n,children:n?`Asking…`:`Ask again`})}),W(`div`,{class:`cards`,children:r.map(e=>W(yn,{facts:e,seen:t?.servers.find(t=>t.name===e.name)},e.name))})]})},xn={invocation:void 0,steps:[],current:void 0,asking:void 0,ended:void 0},Sn=(e,t,n)=>t===void 0?e:{...e,steps:e.steps.map((e,r)=>r===t?n(e):e)},Cn=(e,t)=>Sn(e,e.current,e=>({...e,said:[...e.said,t]})),wn=(e,t,n)=>{switch(t.kind){case`plan`:return{...e,invocation:t.invocation,steps:t.steps.map(e=>({listed:e,state:`waiting`,said:[]}))};case`started`:return Sn({...e,current:t.index},t.index,e=>({...e,state:`running`,started:n}));case`done`:return Sn(e,t.index,e=>({...e,state:t.failed?`failed`:t.stopped?`stopped`:`passed`,ms:t.ms,...t.why===void 0?{}:{why:t.why}}));case`ended`:{let n={failures:t.failures,ms:t.ms,footer:t.footer,...t.stop===void 0?{}:{stop:t.stop}};return{...e,asking:void 0,ended:n,steps:e.steps.map((e,n)=>e.state===`running`||t.stop?.why===`interrupted`&&t.stop.index===n?{...e,state:`stopped`}:e.state===`waiting`?{...e,state:`skipped`}:e)}}case`output`:return Cn(e,{kind:`output`,stream:t.stream,chunk:t.chunk});case`said`:return Cn(e,{kind:`said`,stream:t.stream,text:t.text});case`ask`:return{...e,asking:t.prompt};case`answered`:return{...e,asking:void 0}}},Tn=e=>{let{ended:t}=e;return t===void 0?`running`:t.stop?.why===`interrupted`?`interrupted`:t.stop?.why===`declined`?`declined`:t.failures===0?`passed`:`failed`},En={fg:void 0,bold:!1,dim:!1},Dn=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`],On=(e,t)=>{let n=t===``?[0]:t.split(`;`).map(Number),r=(e,t)=>{let[n,...i]=t;return n===void 0?e:n===38||n===48?r(e,i[0]===5?i.slice(2):i[0]===2?i.slice(4):i):r(n===0?En:n===1?{...e,bold:!0}:n===2?{...e,dim:!0}:n===22?{...e,bold:!1,dim:!1}:n===39?{...e,fg:void 0}:n>=30&&n<=37?{...e,fg:Dn[n-30]}:n>=90&&n<=97?{...e,fg:`bright-${Dn[n-90]??`white`}`}:e,i)};return r(e,n)},kn=e=>[e.fg===void 0?``:`sgr-${e.fg}`,e.bold?`sgr-bold`:``,e.dim?`sgr-dim`:``].filter(e=>e!==``).join(` `),An=/\u001b\[([0-9;]*)m|\u001b\[[0-9;?]*[A-Za-z]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g,jn=e=>{let t=[...e.matchAll(An)].reduce((t,n)=>{let r=e.slice(t.at,n.index),i=r===``?t.out:[...t.out,{text:r,classes:kn(t.look)}],a=n[1];return{out:i,look:a===void 0?t.look:On(t.look,a),at:n.index+n[0].length}},{out:[],look:En,at:0}),n=e.slice(t.at);return n===``?t.out:[...t.out,{text:n,classes:kn(t.look)}]},Mn={running:`active`,passed:`ok`,failed:`bad`,interrupted:`warn`,declined:`warn`},Nn={waiting:`○`,running:``,passed:`✓`,failed:`✗`,stopped:`■`,skipped:`–`},Pn=({step:e})=>W(`div`,{class:`output`,children:e.said.map((e,t)=>e.kind===`output`?W(`span`,{class:e.stream===`stderr`?`stderr`:void 0,children:jn(e.chunk).map((e,t)=>W(`span`,{class:e.classes===``?void 0:e.classes,children:e.text},t))},t):W(`div`,{class:e.stream===`err`?`said said-err`:`said`,children:W(Rt,{text:e.text})},t))}),Fn=({step:e,now:t})=>{let n=e.state===`running`||e.state===`failed`,r=e.ms??(e.started===void 0?void 0:t-e.started),i=e.said.length===0?null:W(Pn,{step:e});return W(`details`,{class:`step step-${e.state}`,open:n,children:[W(`summary`,{children:[W(`span`,{class:`step-icon`,children:e.state===`running`?W(`span`,{class:`spinner`}):Nn[e.state]}),W(`span`,{class:`step-title`,children:e.listed.title}),W(`span`,{class:`step-kind`,children:e.listed.kind}),W(`span`,{class:`step-time`,children:[e.why===void 0?``:`${e.why} · `,r===void 0?``:cn(r)]})]}),i]})},In=({id:e,prompt:t})=>{let[n,r]=N(``);return W(`form`,{class:`ask`,onSubmit:t=>{t.preventDefault(),Ct(e,n)},children:[W(Rt,{text:t}),W(`input`,{value:n,onInput:e=>{r(e.currentTarget.value)},autoFocus:!0,spellcheck:!1}),W(`button`,{type:`submit`,class:`button danger`,children:`Answer`}),W(`button`,{type:`button`,class:`button`,onClick:()=>void Ct(e,``),children:`Don't`})]})},Ln=({id:e})=>{let[t,n]=De((e,t)=>wn(e,t,Date.now()),xn),[r,i]=N(Date.now());P(()=>Et(`/api/runs/${encodeURIComponent(e)}/events`,n,()=>void 0),[e]);let a=Tn(t)===`running`;P(()=>{if(!a)return;let e=setInterval(()=>{i(Date.now())},250);return()=>{clearInterval(e)}},[a]);let{invocation:o,steps:s,ended:c,asking:l}=t;if(o===void 0)return W(Y,{what:`Starting`});let u=Tn(t);return W(S,{children:[W(X,{title:W(`code`,{class:`command`,children:o.command}),sub:`${o.about.join(` · `)} · ${String(s.length)} steps`,children:[W(K,{tone:Mn[u],children:u}),a?W(`button`,{class:`button danger`,onClick:()=>void wt(e),children:`Stop`}):null]}),l===void 0?null:W(In,{id:e,prompt:l}),W(`div`,{class:`timeline`,children:s.map(e=>W(`div`,{children:[e.listed.opens===void 0?null:W(`h3`,{class:`part`,children:e.listed.opens}),W(Fn,{step:e,now:r})]},e.listed.index))}),c===void 0?null:W(`footer`,{class:`run-footer tone-border-${Mn[u]}`,children:W(zt,{lines:c.footer})})]})},Rn={running:`waiting`,passed:`ok`,failed:`bad`,interrupted:`warn`,declined:`warn`},zn=({server:e})=>{let[t,n]=N(void 0);if(P(()=>{let e=()=>{Tt().then(n)};e();let t=setInterval(e,3e3);return()=>{clearInterval(t)}},[]),t===void 0)return W(Y,{what:`Reading the runs`});if(!t.ok)return W(J,{failure:t.failure});let r=t.value.filter(t=>e===void 0||t.server===e);if(r.length===0)return W(`p`,{class:`empty`,children:`Nothing run from here yet.`});let i=Date.now();return W(`table`,{class:`table`,children:W(`tbody`,{children:r.map(e=>W(`tr`,{children:[W(`td`,{class:`narrow`,children:W(G,{tone:Rn[e.state],label:e.state})}),W(`td`,{children:W($,{to:{page:`run`,id:e.id},children:W(`code`,{children:e.command})})}),W(`td`,{class:`tone-${Rn[e.state]===`waiting`?`active`:Rn[e.state]}`,children:e.state}),W(`td`,{class:`tone-muted right`,children:ln(i-un(e.started))})]},e.id))})})},Bn=()=>W(S,{children:[W(X,{title:`Runs`,sub:`Every command run from here, recorded in the fleet's .cache/ui/runs`}),W(`section`,{class:`card`,children:W(zn,{})})]}),Vn={deploy:`Host setup and every app, then verify`,apps:`Register every app in server.yml, remove the rest`,verify:`Check it as its users see it`,setup:`The host layer: the playbook for its kind`,plan:`What provision and setup would change, changing nothing`,up:`Provision, set up, every app, /etc/hosts`,provision:`Create or update the machine`,"backup test":`Restore the latest backup to a scratch dir and check it`,adopt:`Once, for a server kayra did not create`,down:`Destroy the machine`},Hn=[`down`,`adopt`,`provision`],Un=({facts:e})=>W(`div`,{class:`action-grid`,children:[e.commands.filter(e=>e!==`job`).map((t,n)=>W(`button`,{class:`action${n===0?` primary`:``}${Hn.includes(t)?` danger`:``}`,disabled:e.needsTerminal&&t!==`plan`&&t!==`verify`,onClick:()=>{Z({name:t,server:e.name})},children:[W(`strong`,{children:t}),W(`span`,{children:Vn[t]})]},t)),e.commands.includes(`job`)?W(S,{children:[W(`button`,{class:`action`,onClick:()=>{Z({name:`job`,server:e.name,job:`gc`,noPrs:!1})},children:[W(`strong`,{children:`job gc`}),W(`span`,{children:`The registry's garbage collection, now`})]}),W(`button`,{class:`action`,onClick:()=>{Z({name:`job`,server:e.name,job:`renovate`,noPrs:!0})},children:[W(`strong`,{children:`job renovate`}),W(`span`,{children:`Renovate now, logging what it would change`})]})]}):null]}),Wn=({name:e})=>{let t=H.value;if(t.state!==`ready`)return W(Y,{what:`Reading the fleet`});let n=t.value.servers.find(t=>t.name===e);if(n===void 0)return W(`p`,{class:`empty`,children:[`No server `,e,` in this fleet.`]});let r=U.value.value?.servers.find(t=>t.name===e);return W(S,{children:[W(X,{title:W(S,{children:[W(G,{tone:nn(r)}),` `,n.name]}),sub:W(S,{children:[W(K,{children:n.kind}),` `,W(K,{children:n.target}),` `,W(`a`,{href:`https://${n.domain}`,target:`_blank`,rel:`noreferrer`,children:n.domain})]})}),n.needsTerminal?W(`div`,{class:`notice`,children:`Its vault password is asked on a terminal: what opens its secrets runs from the command line, or give it a vault_password_file.`}):null,W(`div`,{class:`columns`,children:[W(`section`,{class:`card`,children:[W(`h2`,{children:`Now`}),r===void 0?W(Y,{what:`asking`}):W(`dl`,{class:`facts`,children:[W(q,{label:`Address`,cell:$t(r)}),W(q,{label:`SSH`,cell:en(r)}),W(q,{label:`Login`,cell:tn(r)})]})]}),W(`section`,{class:`card`,children:[W(`h2`,{children:`Apps`}),n.apps.length===0?W(`p`,{class:`empty`,children:n.kind===`platform`?`None in server.yml.`:`A ${n.kind} server runs no apps.`}):W(`ul`,{class:`links`,children:n.apps.map(e=>W(`li`,{children:W($,{to:{page:`app`,server:n.name,app:e},children:e})},e))})]})]}),W(`section`,{class:`card`,children:[W(`h2`,{children:`Commands`}),W(Un,{facts:n})]}),W(`section`,{class:`card`,children:[W(`h2`,{children:`Runs from here`}),W(zn,{server:n.name})]})]})},Gn=e=>e===`problem`?`bad`:e===`unchecked`?`warn`:`ok`,Kn=e=>e===`problem`?`✗`:e===`unchecked`?`·`:`✓`,qn={problem:`problems`,unchecked:`partly checked`,passed:`holds`},Jn=()=>{P(()=>{Ft()},[]);let e=Mt.value;if(e.state===`loading`)return W(Y,{what:`Checking the fleet beyond its schemas`});if(e.state===`failed`)return W(J,{failure:e.failure});let{result:t,servers:n}=e.value,r=e=>n.flatMap(e=>e.findings).filter(t=>t.result===e).length;return W(S,{children:[W(X,{title:`Validate`,sub:`Secrets, apps against their contract, stacks, routes · ${String(r(`problem`))} problems · ${String(r(`unchecked`))} not checked`,children:[W(K,{tone:Gn(t),children:qn[t]}),W(`button`,{class:`button`,onClick:()=>void Ft(),children:`Check again`})]}),n.map(e=>W(`section`,{class:`card`,children:[W(`div`,{class:`card-head`,children:[W(G,{tone:Gn(e.result)}),W(`h2`,{children:e.name}),W(K,{children:e.kind}),W(K,{children:e.target}),W(`span`,{class:`grow`}),W(K,{tone:Gn(e.result),children:qn[e.result]})]}),W(`ul`,{class:`findings`,children:e.findings.map((e,t)=>W(`li`,{class:`finding finding-${e.result}`,children:[W(`span`,{class:`glyph tone-${Gn(e.result)}`,children:Kn(e.result)}),W(`span`,{children:[e.text,e.hint===null?null:W(`span`,{class:`hint`,children:[`→ `,e.hint]})]})]},t))})]},e.name))]})},Yn=()=>{let e=At.value;switch(e.page){case`fleet`:return W(bn,{});case`server`:return W(Wn,{name:e.server});case`app`:return W(vn,{server:e.server,app:e.app});case`runs`:return W(Bn,{});case`run`:return W(Ln,{id:e.id});case`validate`:return W(Jn,{});case`missing`:return W(`p`,{class:`empty`,children:[`Nothing at `,e.path,`.`]})}},Xn=()=>(P(()=>{Nt(),Pt()},[]),W(S,{children:[W(sn,{children:[W(`div`,{class:`topbar`,children:[W(`button`,{class:`search`,onClick:Xt,children:[W(`span`,{children:`Go to, or run…`}),W(`kbd`,{children:`⌘K`})]}),W(`button`,{class:`button`,onClick:()=>{Z({name:`doctor`})},children:`Doctor`})]}),W(Yn,{})]}),W(Kt,{}),W(Yt,{})]})),Zn=document.getElementById(`app`);Zn!==null&&me(W(Xn,{}),Zn);
@@ -0,0 +1,15 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <meta name="color-scheme" content="light dark" />
7
+ <title>kayra</title>
8
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='8' fill='%235b5bd6'/%3E%3Cpath d='M11 8v16M11 16l9-8M14 13l7 11' stroke='white' stroke-width='3' stroke-linecap='round' fill='none'/%3E%3C/svg%3E" />
9
+ <script type="module" crossorigin src="/assets/index-DRFX9Q77.js"></script>
10
+ <link rel="stylesheet" crossorigin href="/assets/index-3W_NFATj.css">
11
+ </head>
12
+ <body>
13
+ <div id="app"></div>
14
+ </body>
15
+ </html>
package/cli/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
- import { command, constant, group, map, merge, multiple, object, option, optional, or } from "@optique/core";
1
+ import { command, constant, group, map, merge, multiple, object, option, optional, or, withDefault } from "@optique/core";
2
2
  import { lineBreak, message, text, url } from "@optique/core/message";
3
3
  import { argument } from "@optique/core/primitives";
4
- import { choice, string } from "@optique/core/valueparser";
4
+ import { choice, integer, string } from "@optique/core/valueparser";
5
5
  import { appNameParser, domainParser, serverNameParser, subdomainParser } from "./brand.js";
6
6
  /** Command lines, each with what it is for, aligned. Plain text: Optique folds an indent that stands alone before a command line. */
7
7
  const examples = (indent, rows) => {
@@ -155,6 +155,14 @@ export const parser = (fleet) => {
155
155
  footer: footer(["kayra validate", "every server"], ["kayra validate shop-prod", "one"]),
156
156
  }), command("doctor", object({ name: constant("doctor") }), {
157
157
  brief: message `Check that this Mac can run every command on every server.`,
158
+ }), command("ui", object({
159
+ name: constant("ui"),
160
+ port: withDefault(option("--port", integer({ min: 0, max: 65_535, metavar: "PORT" }), { description: message `Listen on this port (default: any free one).` }), 0),
161
+ noOpen: option("--no-open", { description: message `Print the URL, open no browser.` }),
162
+ }), {
163
+ brief: message `The web interface on this Mac: the fleet, its servers and apps, every command with its steps live.`,
164
+ description: message `Listens on 127.0.0.1 only. The URL it prints carries this launch's token; nothing else gets in. Runs the same plans as the command line, with the same guards; a change to a real server asks for its name first.`,
165
+ footer: footer(["kayra ui", "open it in the browser"], ["kayra ui --port 7700 --no-open", "for web/'s dev server"]),
158
166
  }), command("certs", object({
159
167
  name: constant("certs"),
160
168
  domain: argument(domainParser, { description: message `The domain the certificates are for.` }),
@@ -0,0 +1,52 @@
1
+ import { serverNamed } from "../fleet.js";
2
+ import { flatMap, ok } from "../result.js";
3
+ import { doctor } from "./doctor.js";
4
+ import * as server from "./server.js";
5
+ const appKinds = { "app runs": "runs", "app logs": "logs", "app deploy": "deploy", "app rollback": "rollback" };
6
+ /** The deployer's commands: their answer is the output, nothing is drawn around it. */
7
+ export const isDeployer = (command) => command.name === "job" || command.name in appKinds;
8
+ const deployerCommand = (command) => command.name === "job"
9
+ ? { kind: "job", job: command.job, noPrs: command.noPrs }
10
+ : { kind: appKinds[command.name], app: command.app, more: "more" in command ? command.more : undefined };
11
+ const onServer = (on, target, command) => {
12
+ switch (command.name) {
13
+ case "up":
14
+ return server.up(on, target);
15
+ case "provision":
16
+ return server.provision(on, target);
17
+ case "deploy":
18
+ return server.deploy(on, target);
19
+ case "setup":
20
+ return server.setup(on, target);
21
+ case "plan":
22
+ return server.preview(on, target);
23
+ case "verify":
24
+ return server.verify(on, target);
25
+ case "apps":
26
+ return server.apps(on, target);
27
+ case "hosts":
28
+ return server.hosts(on, target);
29
+ case "ssh":
30
+ return server.ssh(target, command.remote);
31
+ case "down":
32
+ return server.down(on, target);
33
+ case "adopt":
34
+ return server.adopt(on, target);
35
+ case "backup test":
36
+ return server.backupTest(on, target);
37
+ }
38
+ };
39
+ /** A command as the plan that does it: what kayra runs, --dry-run prints and the web interface shows. */
40
+ export const planFor = (on, fleet, command) => {
41
+ if (command.name === "doctor")
42
+ return ok(doctor(fleet, on.kayra));
43
+ if (command.name === "certs")
44
+ return server.certsFor(on, command.domain, command.subdomains);
45
+ if (command.name === "app purge")
46
+ return flatMap(serverNamed(fleet, command.server), (target) => server.appPurge(on, target, command.app));
47
+ if (isDeployer(command)) {
48
+ const deployerArgs = deployerCommand(command);
49
+ return flatMap(serverNamed(fleet, command.server), (target) => server.deployer(target, deployerArgs));
50
+ }
51
+ return flatMap(serverNamed(fleet, command.server), (target) => onServer(on, target, command));
52
+ };
@@ -4,37 +4,59 @@ import { all, err, flatMap, ok } from "./result.js";
4
4
  import { active, bad, muted, ok as fine, strong } from "./ui/line.js";
5
5
  import { position, silent } from "./ui/progress.js";
6
6
  import { draw } from "./ui/views.js";
7
- const spawned = async (argv, streams, env = {}) => {
7
+ const terminal = {};
8
+ /** A program that ignores SIGINT this long gets SIGTERM. */
9
+ const patience = 10_000;
10
+ const spawned = async (argv, streams, env = {}, plumbing = terminal) => {
8
11
  const [program, ...args] = argv;
12
+ const { output, signal } = plumbing;
13
+ if (signal?.aborted === true)
14
+ return { code: 130, stdout: "", stderr: "", started: false };
15
+ const shown = (stream) => stream === "show" ? (output === undefined ? "inherit" : "pipe") : stream === "capture" ? "pipe" : "ignore";
9
16
  const child = spawn(program, args, {
10
17
  env: { ...process.env, ...env },
11
- stdio: [
12
- "inherit",
13
- streams.stdout === "show" ? "inherit" : streams.stdout === "capture" ? "pipe" : "ignore",
14
- streams.stderr === "show" ? "inherit" : "pipe",
15
- ],
18
+ stdio: [output === undefined ? "inherit" : "ignore", shown(streams.stdout), shown(streams.stderr)],
16
19
  });
17
- const stdout = child.stdout === null ? Promise.resolve("") : text(child.stdout);
18
- const stderr = child.stderr === null ? Promise.resolve("") : text(child.stderr);
20
+ const forward = (from, sink) => {
21
+ child[from]?.setEncoding("utf8").on("data", (chunk) => {
22
+ sink(chunk, from);
23
+ });
24
+ };
25
+ if (output !== undefined && streams.stdout === "show")
26
+ forward("stdout", output);
27
+ if (output !== undefined && streams.stderr === "show")
28
+ forward("stderr", output);
29
+ const read = (from, stream) => {
30
+ const piped = child[from];
31
+ return piped === null || stream !== "capture" ? Promise.resolve("") : text(piped);
32
+ };
33
+ const stdout = read("stdout", streams.stdout);
34
+ const stderr = read("stderr", streams.stderr);
35
+ const stop = () => {
36
+ child.kill("SIGINT");
37
+ setTimeout(() => child.kill("SIGTERM"), patience).unref();
38
+ };
39
+ signal?.addEventListener("abort", stop, { once: true });
19
40
  const exit = await new Promise((resolve) => {
20
41
  child.on("error", resolve);
21
42
  child.on("close", (code) => {
22
43
  resolve(code ?? 1);
23
44
  });
24
45
  });
46
+ signal?.removeEventListener("abort", stop);
25
47
  return exit instanceof Error
26
48
  ? { code: 127, stdout: "", stderr: exit.message, started: false }
27
49
  : { code: exit, stdout: await stdout, stderr: await stderr, started: true };
28
50
  };
29
51
  /** A command's stdout, for kayra to read; its stderr reaches the operator unless captured too. */
30
- export const capture = (argv, stderr = "show", env = {}) => spawned(argv, { stdout: "capture", stderr }, env);
31
- const answer = (probe) => spawned(probe.kind === "on-path" ? ["sh", "-c", 'command -v "$1"', "sh", probe.program] : probe.argv, { stdout: "discard", stderr: "capture" }, probe.kind === "exits-zero" ? probe.env : {});
52
+ export const capture = (argv, stderr = "show", env = {}, plumbing = terminal) => spawned(argv, { stdout: "capture", stderr }, env, plumbing);
53
+ const answer = (probe, plumbing) => spawned(probe.kind === "on-path" ? ["sh", "-c", 'command -v "$1"', "sh", probe.program] : probe.argv, { stdout: "discard", stderr: "capture" }, probe.kind === "exits-zero" ? probe.env : {}, plumbing);
32
54
  /** Each query's answer in place of it, as `$(…)` would: one word, or split into many. */
33
- const resolve = async (argv) => {
55
+ const resolve = async (argv, plumbing) => {
34
56
  const words = await Promise.all(argv.map(async (value) => {
35
57
  if (typeof value === "string")
36
58
  return ok([value]);
37
- const exit = await capture(value.argv, "show", value.env);
59
+ const exit = await capture(value.argv, "show", value.env, plumbing);
38
60
  if (exit.code !== 0)
39
61
  return err(`$(${value.argv.join(" ")}) failed: exit ${String(exit.code)}`);
40
62
  const output = exit.stdout.replace(/\n+$/, "");
@@ -54,8 +76,8 @@ const detail = (line) => [" ", line];
54
76
  const aside = (line) => [" ", muted(line)];
55
77
  const hint = (text) => (text === undefined ? [] : [[" ", active("→"), " ", text]]);
56
78
  const goOn = { failed: false, stopped: false, out: [], err: [] };
57
- const check = async (step) => {
58
- const exit = await answer(step.probe);
79
+ const check = async (step, plumbing) => {
80
+ const exit = await answer(step.probe, plumbing);
59
81
  const said = [...lines(exit.stderr).map(detail), ...hint(step.hint)];
60
82
  if (step.onFailure === "stop")
61
83
  return exit.code === 0 ? goOn : { failed: true, stopped: true, out: [], err: said };
@@ -63,14 +85,14 @@ const check = async (step) => {
63
85
  ? { ...goOn, out: [[fine("✓"), " ", step.label]] }
64
86
  : { failed: true, stopped: false, out: [[bad("✗"), " ", step.label], ...said], err: [] };
65
87
  };
66
- const runStep = async (step) => {
67
- const argv = await resolve(step.argv);
88
+ const runStep = async (step, plumbing) => {
89
+ const argv = await resolve(step.argv, plumbing);
68
90
  if (!argv.ok)
69
91
  return { failed: true, stopped: true, why: "a query failed", out: [], err: [detail(argv.error)] };
70
92
  const { stdout } = step;
71
93
  // A quiet step's stderr waits until it is done, so it cannot tear through a spinner.
72
94
  const quiet = stdout === "discard";
73
- const exit = await spawned(argv.value, { stdout: typeof stdout === "string" ? stdout : "capture", stderr: quiet ? "capture" : "show" }, step.env);
95
+ const exit = await spawned(argv.value, { stdout: typeof stdout === "string" ? stdout : "capture", stderr: quiet ? "capture" : "show" }, step.env, plumbing);
74
96
  if (!exit.started)
75
97
  return { failed: true, stopped: true, why: "not started", out: [], err: [detail(`${argv.value[0]}: ${exit.stderr}`)] };
76
98
  // Whatever it answered is shown, even when it failed: it may say why.
@@ -82,9 +104,9 @@ const runStep = async (step) => {
82
104
  const perform = async (step, io) => {
83
105
  switch (step.kind) {
84
106
  case "run":
85
- return runStep(step);
107
+ return runStep(step, io);
86
108
  case "check":
87
- return check(step);
109
+ return check(step, io);
88
110
  case "confirm": {
89
111
  io.err("");
90
112
  io.err([" ", bad("▲"), " ", strong(step.warning)]);
package/cli/dist/main.js CHANGED
@@ -7,22 +7,23 @@ import { join, resolve } from "node:path";
7
7
  import { absolutePath, fleetRoot, kayraRoot, within } from "./brand.js";
8
8
  import { appCheck } from "./commands/app-check.js";
9
9
  import { parser, runOptions } from "./cli.js";
10
- import { doctor } from "./commands/doctor.js";
11
- import * as server from "./commands/server.js";
10
+ import { isDeployer, planFor } from "./commands/index.js";
11
+ import { verbose } from "./commands/server.js";
12
12
  import { look, opentofu, statusJson, statusView } from "./commands/status.js";
13
13
  import { findings, overall, validateJson, validateView } from "./commands/validate.js";
14
14
  import { gather } from "./gather.js";
15
- import { serverNamed } from "./fleet.js";
16
15
  import { interpret } from "./interpret.js";
17
16
  import { findFleetRoot, loadFleet } from "./load.js";
17
+ import { systemBrowser } from "./web/opener.js";
18
+ import { serveUi } from "./web/server.js";
18
19
  import { network } from "./net.js";
19
20
  import { render } from "./plan.js";
20
21
  import { flatMap, map, ok } from "./result.js";
21
22
  import { explain } from "./ui/explain.js";
22
- import { bad, paint } from "./ui/line.js";
23
+ import { bad, muted, paint, strong } from "./ui/line.js";
23
24
  import { framed, silent } from "./ui/progress.js";
24
25
  import { screen, settle, watch } from "./ui/terminal.js";
25
- import { truncate } from "./ui/text.js";
26
+ import { shortener, truncate } from "./ui/text.js";
26
27
  import { z } from "zod";
27
28
  const here = absolutePath(process.cwd());
28
29
  const engine = absolutePath(import.meta.dirname);
@@ -30,53 +31,6 @@ if (!here.ok || !engine.ok)
30
31
  throw new Error("node reported a relative path");
31
32
  const kayra = kayraRoot(within(engine.value, "..", ".."));
32
33
  const version = z.object({ version: z.string() }).parse(JSON.parse(readFileSync(join(kayra, "package.json"), "utf8"))).version;
33
- const appKinds = { "app runs": "runs", "app logs": "logs", "app deploy": "deploy", "app rollback": "rollback" };
34
- const isDeployer = (command) => command.name === "job" || command.name in appKinds;
35
- const deployerCommand = (command) => command.name === "job"
36
- ? { kind: "job", job: command.job, noPrs: command.noPrs }
37
- : { kind: appKinds[command.name], app: command.app, more: "more" in command ? command.more : undefined };
38
- const onServer = (on, target, command) => {
39
- switch (command.name) {
40
- case "up":
41
- return server.up(on, target);
42
- case "provision":
43
- return server.provision(on, target);
44
- case "deploy":
45
- return server.deploy(on, target);
46
- case "setup":
47
- return server.setup(on, target);
48
- case "plan":
49
- return server.preview(on, target);
50
- case "verify":
51
- return server.verify(on, target);
52
- case "apps":
53
- return server.apps(on, target);
54
- case "hosts":
55
- return server.hosts(on, target);
56
- case "ssh":
57
- return server.ssh(target, command.remote);
58
- case "down":
59
- return server.down(on, target);
60
- case "adopt":
61
- return server.adopt(on, target);
62
- case "backup test":
63
- return server.backupTest(on, target);
64
- }
65
- };
66
- const plan = (fleet, command) => {
67
- const on = { kayra, fleet: fleet.root };
68
- if (command.name === "doctor")
69
- return ok(doctor(fleet, kayra));
70
- if (command.name === "certs")
71
- return server.certsFor(on, command.domain, command.subdomains);
72
- if (command.name === "app purge")
73
- return flatMap(serverNamed(fleet, command.server), (target) => server.appPurge(on, target, command.app));
74
- if (isDeployer(command)) {
75
- const deployerArgs = deployerCommand(command);
76
- return flatMap(serverNamed(fleet, command.server), (target) => server.deployer(target, deployerArgs));
77
- }
78
- return flatMap(serverNamed(fleet, command.server), (target) => onServer(on, target, command));
79
- };
80
34
  const screens = { out: screen(process.stdout, process.env), err: screen(process.stderr, process.env) };
81
35
  const io = {
82
36
  out: (text) => {
@@ -113,8 +67,6 @@ const invocation = (target) => ({
113
67
  ...(target === undefined ? {} : { server: target.name }),
114
68
  about: [...(target === undefined ? [] : [`${target.kind} on ${target.target}`, target.domain]), `kayra ${version}`],
115
69
  });
116
- /** Paths by the root they are under, the longest first: the engine may live inside the fleet. */
117
- const shortener = (roots) => (text) => roots.toSorted(([a], [b]) => b.length - a.length).reduce((short, [path, name]) => short.replaceAll(path, name), text);
118
70
  /** --dry-run: the plan as data, styled on a terminal, plain and copyable for a program. */
119
71
  const show = (steps, about, short) => {
120
72
  (screens.out.live ? explain(about, steps, short, screens.out.columns) : render(steps)).forEach(io.out);
@@ -171,6 +123,19 @@ else {
171
123
  ? [JSON.stringify(statusJson(looks), null, 2)]
172
124
  : statusView(looks, { frame: "", room: screens.out.live ? screens.out.columns : Infinity, offline })).forEach(io.out);
173
125
  }
126
+ else if (args.command.name === "ui") {
127
+ // The browser side: web/dist in a checkout, cli/dist/browser in the package.
128
+ const assets = [join(kayra, "web", "dist"), join(kayra, "cli", "dist", "browser")].find((dir) => existsSync(join(dir, "index.html")));
129
+ const { port, noOpen } = args.command;
130
+ const listening = await serveUi({ kayra, fleet: fleet.value, version, assets, short, network: network(2_000) }, port);
131
+ io.err([strong("kayra ui"), muted(` · ${fleet.value.servers.length.toString()} servers · kayra ${version} · Ctrl-C stops it`)]);
132
+ io.out(listening.url);
133
+ if (!noOpen)
134
+ systemBrowser.open(listening.url);
135
+ process.once("SIGINT", () => {
136
+ void listening.close().then(() => process.exit(0));
137
+ });
138
+ }
174
139
  else if (args.command.name === "validate") {
175
140
  const { server: chosen, json } = args.command;
176
141
  const servers = fleet.value.servers.filter((each) => chosen === undefined || each.name === chosen);
@@ -181,7 +146,7 @@ else {
181
146
  }
182
147
  else {
183
148
  const { command } = args;
184
- const steps = map(plan(fleet.value, command), (each) => (args.verbose ? server.verbose(each) : each));
149
+ const steps = map(planFor({ kayra, fleet: fleet.value.root }, fleet.value, command), (each) => (args.verbose ? verbose(each) : each));
185
150
  const target = "server" in command ? fleet.value.servers.find((each) => each.name === command.server) : undefined;
186
151
  // ssh and the deployer's answers are the output itself: nothing around them.
187
152
  const framing = command.name !== "ssh" && !isDeployer(command);
package/cli/dist/plan.js CHANGED
@@ -60,3 +60,5 @@ const describe = (step) => {
60
60
  };
61
61
  /** The plan as plain lines: --dry-run's output where it is read by a program. */
62
62
  export const render = (plan) => plan.map(describe);
63
+ /** A plan with a step that asks on the terminal (the vault password, typed): it cannot run without one. */
64
+ export const needsTerminal = (plan) => plan.some((step) => step.kind === "run" && step.env["ANSIBLE_ASK_VAULT_PASS"] === "True");
@@ -1,4 +1,4 @@
1
- import { titleOf } from "../plan.js";
1
+ import { commandOf, kindOf, titleOf } from "../plan.js";
2
2
  import { accent, active, bad, muted, ok, paint, strong, warn } from "./line.js";
3
3
  import { escapes, spinner } from "./terminal.js";
4
4
  import { duration, spread, truncate } from "./text.js";
@@ -98,3 +98,47 @@ export const framed = (screen, write, invocation) => {
98
98
  },
99
99
  };
100
100
  };
101
+ /** Every step of a plan, its command's paths named by their root. */
102
+ export const listed = (plan, short) => plan.map((step, index) => {
103
+ const command = commandOf(step);
104
+ const { opens } = position(plan, index);
105
+ return {
106
+ index,
107
+ kind: kindOf(step),
108
+ title: titleOf(step),
109
+ ...(command === undefined ? {} : { command: short(command) }),
110
+ ...(step.part === undefined ? {} : { part: step.part }),
111
+ ...(opens === undefined ? {} : { opens }),
112
+ };
113
+ });
114
+ /** The plan and each step as events: what framed draws on a terminal, as data. */
115
+ export const reporting = (emit, invocation, short) => ({
116
+ plan: async (plan, work) => {
117
+ const started = performance.now();
118
+ emit({ kind: "plan", invocation, steps: listed(plan, short) });
119
+ const ended = await work();
120
+ const ms = performance.now() - started;
121
+ emit({
122
+ kind: "ended",
123
+ failures: ended.failures,
124
+ ...(ended.stop === undefined ? {} : { stop: { index: ended.stop.index, why: ended.stop.why } }),
125
+ ms,
126
+ footer: footer(invocation, plan, ended, ms),
127
+ });
128
+ return ended;
129
+ },
130
+ step: async (_step, at, work) => {
131
+ const started = performance.now();
132
+ emit({ kind: "started", index: at.index });
133
+ const done = await work();
134
+ emit({
135
+ kind: "done",
136
+ index: at.index,
137
+ failed: done.failed,
138
+ stopped: done.stopped,
139
+ ...(done.why === undefined ? {} : { why: done.why }),
140
+ ms: performance.now() - started,
141
+ });
142
+ return done;
143
+ },
144
+ });
@@ -91,3 +91,14 @@ export const watch = async (write, initial, updates, draw) => {
91
91
  };
92
92
  /** What watch() returns, drawn nowhere: for a stream that is no terminal. */
93
93
  export const settle = async (initial, updates) => (await Promise.all(updates)).reduce((state, update) => update(state), initial);
94
+ /** Each state as the updates land, in the order they land: for a viewer elsewhere (the web interface). */
95
+ export const follow = async (initial, updates, each) => {
96
+ const go = async (state, waiting) => {
97
+ each(state);
98
+ if (waiting.length === 0)
99
+ return state;
100
+ const next = await Promise.race(waiting.map((one) => one.landed));
101
+ return go(next.update(state), waiting.filter((one) => one.id !== next.id));
102
+ };
103
+ return go(initial, updates.map((update, id) => ({ id, landed: update.then((done) => ({ id, update: done })) })));
104
+ };
@@ -69,3 +69,5 @@ export const fit = (rows, room, shrink) => {
69
69
  }, { widths, over }).widths;
70
70
  return rows.map((row) => row.map((cell, at) => truncate(cell, cut[at] ?? width(cell))));
71
71
  };
72
+ /** Paths by the root they are under, the longest first: the engine may live inside the fleet. */
73
+ export const shortener = (roots) => (text) => roots.toSorted(([a], [b]) => b.length - a.length).reduce((short, [path, name]) => short.replaceAll(path, name), text);
@@ -2,7 +2,8 @@ import { z } from "zod";
2
2
  import { accent, active, bad, muted, ok, strong, warn } from "./line.js";
3
3
  import { ago, duration, table } from "./text.js";
4
4
  const deployed = z.object({ sha: z.string(), time: z.iso.datetime() });
5
- const runsAnswer = z.object({
5
+ /** `ctl runs <app> --json`, as this kayra reads it. */
6
+ export const runsSchema = z.object({
6
7
  app: z.string(),
7
8
  live: deployed.exactOptional(),
8
9
  runs: z.array(z.object({
@@ -15,12 +16,13 @@ const runsAnswer = z.object({
15
16
  finished: z.iso.datetime().exactOptional(),
16
17
  })),
17
18
  });
18
- const releasesAnswer = z.object({
19
+ /** `ctl rollback <app> --json`, as this kayra reads it. */
20
+ export const releasesSchema = z.object({
19
21
  app: z.string(),
20
22
  releases: z.array(deployed.extend({ live: z.boolean() })),
21
23
  });
22
24
  /** The answer as the schema has it, or nothing: then it is not the answer this kayra expects. */
23
- const parsed = (schema, answer) => {
25
+ export const parsed = (schema, answer) => {
24
26
  try {
25
27
  const json = JSON.parse(answer);
26
28
  const result = schema.safeParse(json);
@@ -103,11 +105,11 @@ export const logView = (log) => linesOf(log).map(logLine);
103
105
  export const draw = (view, answer, now) => {
104
106
  switch (view.view) {
105
107
  case "runs": {
106
- const runs = parsed(runsAnswer, answer);
108
+ const runs = parsed(runsSchema, answer);
107
109
  return runs === undefined ? linesOf(answer) : runsView(view, runs, now);
108
110
  }
109
111
  case "releases": {
110
- const releases = parsed(releasesAnswer, answer);
112
+ const releases = parsed(releasesSchema, answer);
111
113
  return releases === undefined ? linesOf(answer) : releasesView(view, releases, now);
112
114
  }
113
115
  case "log":
@@ -0,0 +1,36 @@
1
+ import { timingSafeEqual } from "node:crypto";
2
+ /** Cookies are shared by every port of a host: the name carries the port, so another local server's cookie is not ours. */
3
+ export const cookieName = (port) => `kayra_ui_${String(port)}`;
4
+ const origins = (port) => [`127.0.0.1:${String(port)}`, `localhost:${String(port)}`];
5
+ const same = (a, b) => {
6
+ const left = Buffer.from(a);
7
+ const right = Buffer.from(b);
8
+ return left.length === right.length && timingSafeEqual(left, right);
9
+ };
10
+ const cookieValue = (header, name) => header
11
+ ?.split(";")
12
+ .map((pair) => pair.trim().split("="))
13
+ .find(([key]) => key === name)?.[1];
14
+ const refuse = (status, why) => ({ admitted: false, status, why });
15
+ /**
16
+ * Whether a request may reach kayra ui. Every request: a Host of this
17
+ * listener (a page elsewhere cannot rebind a name to it). A write: an Origin
18
+ * of this listener (no other site's form posts here). The API: the launch's
19
+ * token, as its cookie.
20
+ */
21
+ export const admit = (asked, port, token) => {
22
+ if (asked.host === undefined || !origins(port).includes(asked.host))
23
+ return refuse(403, "not this listener's host");
24
+ const writes = asked.method !== "GET" && asked.method !== "HEAD";
25
+ if (writes && !origins(port).some((each) => asked.origin === `http://${each}`))
26
+ return refuse(403, "not this listener's origin");
27
+ if (!asked.path.startsWith("/api/"))
28
+ return { admitted: true };
29
+ const presented = cookieValue(asked.cookie, cookieName(port));
30
+ return presented !== undefined && same(presented, token) ? { admitted: true } : refuse(401, "no token: open the URL kayra ui printed");
31
+ };
32
+ /** The token the opened URL carries, if it is this launch's. */
33
+ export const tokenIn = (query, token) => {
34
+ const given = query.get("token");
35
+ return given !== null && same(given, token);
36
+ };
@@ -0,0 +1,102 @@
1
+ import { z } from "zod";
2
+ import { appName } from "../brand.js";
3
+ import { err, flatMap, map, ok } from "../result.js";
4
+ const onServer = z.enum(["up", "provision", "deploy", "setup", "plan", "verify", "apps", "down", "adopt", "backup test"]);
5
+ /** What the browser may send; anything else is refused before the fleet is asked. */
6
+ export const commandInput = z.discriminatedUnion("name", [
7
+ z.object({ name: onServer, server: z.string() }),
8
+ z.object({ name: z.literal("app deploy"), server: z.string(), app: z.string(), ref: z.string().min(1).exactOptional() }),
9
+ z.object({ name: z.literal("app rollback"), server: z.string(), app: z.string(), sha: z.string().regex(/^[0-9a-f]{7,40}$/) }),
10
+ z.object({ name: z.literal("app purge"), server: z.string(), app: z.string() }),
11
+ z.object({ name: z.literal("job"), server: z.string(), job: z.enum(["gc", "renovate"]), noPrs: z.boolean() }),
12
+ z.object({ name: z.literal("doctor") }),
13
+ ]);
14
+ /** The commands that read and change nothing: everything else asks first on a real server. */
15
+ const reading = ["plan", "verify", "doctor"];
16
+ export const changes = (input) => !reading.includes(input.name);
17
+ const serverOf = (fleet, name) => {
18
+ const found = fleet.servers.find((each) => each.name === name);
19
+ return found === undefined ? err(`no server '${name}' in this fleet`) : ok(found);
20
+ };
21
+ /** The server a command acts on, if one. */
22
+ export const targetOf = (fleet, input) => input.name === "doctor" ? ok(undefined) : serverOf(fleet, input.server);
23
+ const appOf = (server, name) => flatMap(appName(name), (app) => server.apps.some((each) => each.name === app) ? ok(app) : err(`'${name}' is not an app of ${server.name}`));
24
+ /** The command as the CLI would have parsed it, checked against the fleet. */
25
+ export const toPlanned = (fleet, input) => {
26
+ if (input.name === "doctor")
27
+ return ok({ name: "doctor" });
28
+ return flatMap(serverOf(fleet, input.server), (server) => {
29
+ switch (input.name) {
30
+ case "app deploy":
31
+ return map(appOf(server, input.app), (app) => ({ name: "app deploy", server: server.name, app, more: input.ref }));
32
+ case "app rollback":
33
+ return map(appOf(server, input.app), (app) => ({ name: "app rollback", server: server.name, app, more: input.sha }));
34
+ case "app purge":
35
+ return map(appOf(server, input.app), (app) => ({ name: "app purge", server: server.name, app }));
36
+ case "job":
37
+ return ok({ name: "job", server: server.name, job: input.job, noPrs: input.noPrs });
38
+ case "up":
39
+ case "provision":
40
+ case "deploy":
41
+ case "setup":
42
+ case "plan":
43
+ case "verify":
44
+ case "apps":
45
+ case "down":
46
+ case "adopt":
47
+ case "backup test":
48
+ return ok({ name: input.name, server: server.name });
49
+ }
50
+ });
51
+ };
52
+ /** The command's words, as typed on the command line. */
53
+ export const words = (input) => {
54
+ const said = (...parts) => ["kayra", ...parts.filter((part) => part !== undefined)].join(" ");
55
+ switch (input.name) {
56
+ case "doctor":
57
+ return said("doctor");
58
+ case "app deploy":
59
+ return said("app", "deploy", input.server, input.app, input.ref);
60
+ case "app rollback":
61
+ return said("app", "rollback", input.server, input.app, input.sha);
62
+ case "app purge":
63
+ return said("app", "purge", input.server, input.app);
64
+ case "job":
65
+ return said("job", input.server, input.job, input.noPrs ? "--no-prs" : undefined);
66
+ case "up":
67
+ case "provision":
68
+ case "deploy":
69
+ case "setup":
70
+ case "plan":
71
+ case "verify":
72
+ case "apps":
73
+ case "down":
74
+ case "adopt":
75
+ case "backup test":
76
+ return said(input.name, input.server);
77
+ }
78
+ };
79
+ /** What the browser offers for a server, the everyday ones first. */
80
+ export const offered = (server) => {
81
+ const creates = server.terraform || server.vm;
82
+ return [
83
+ ...(server.kind === "platform" ? ["deploy", "apps", "verify"] : []),
84
+ "setup",
85
+ "plan",
86
+ ...(server.target === "multipass" && server.kind === "platform" ? ["up"] : []),
87
+ ...(creates ? ["provision"] : []),
88
+ ...(server.backupDir === undefined ? [] : ["backup test"]),
89
+ ...(server.kind === "platform" ? ["job"] : []),
90
+ ...(server.target === "multipass" ? [] : ["adopt"]),
91
+ ...(server.terraform ? ["down"] : []),
92
+ ];
93
+ };
94
+ export const facts = (server) => ({
95
+ name: server.name,
96
+ kind: server.kind,
97
+ target: server.target,
98
+ domain: server.domain,
99
+ apps: server.apps.map((app) => app.name),
100
+ commands: offered(server),
101
+ needsTerminal: server.vault.kind === "ask",
102
+ });
@@ -0,0 +1,7 @@
1
+ /**
2
+ * What kayra ui's server and the browser say to each other. Standalone: web/
3
+ * imports these types and nothing else of the CLI. The server assigns its own
4
+ * values to them, so a change on either side that breaks the other does not
5
+ * compile.
6
+ */
7
+ export {};
@@ -0,0 +1,9 @@
1
+ import { spawn } from "node:child_process";
2
+ /** macOS's open, xdg-open elsewhere; a browser that does not start leaves the printed URL. */
3
+ export const systemBrowser = {
4
+ open: (url) => {
5
+ spawn(process.platform === "darwin" ? "open" : "xdg-open", [url], { stdio: "ignore", detached: true })
6
+ .on("error", () => undefined)
7
+ .unref();
8
+ },
9
+ };
@@ -0,0 +1,49 @@
1
+ /** Sortable by time (an ISO 8601 instant), unique by its tail. */
2
+ export const runId = (iso, random) => `${iso.replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z")}-${random}`;
3
+ export const stateOf = (events) => {
4
+ const ended = events.findLast((event) => event.kind === "ended");
5
+ if (ended?.kind !== "ended")
6
+ return "running";
7
+ if (ended.stop?.why === "interrupted")
8
+ return "interrupted";
9
+ if (ended.stop?.why === "declined")
10
+ return "declined";
11
+ return ended.failures === 0 ? "passed" : "failed";
12
+ };
13
+ export const summary = (run) => ({
14
+ id: run.id,
15
+ command: run.command,
16
+ ...(run.server === undefined ? {} : { server: run.server }),
17
+ started: run.started,
18
+ state: stateOf(run.events),
19
+ });
20
+ /** What a run's record holds: the run, then each event, one JSON value per line. */
21
+ export const recordLine = (value) => `${JSON.stringify(value)}\n`;
22
+ const isObject = (value) => typeof value === "object" && value !== null;
23
+ /** A record as kayra ui wrote it; a run killed mid-write keeps what it had, and what it had says "running". */
24
+ export const readRecord = (text) => {
25
+ const [head, ...rest] = text
26
+ .split("\n")
27
+ .filter((line) => line !== "")
28
+ .flatMap((line) => {
29
+ try {
30
+ return [JSON.parse(line)];
31
+ }
32
+ catch {
33
+ return [];
34
+ }
35
+ });
36
+ if (!isObject(head) || typeof head["id"] !== "string" || typeof head["command"] !== "string" || typeof head["started"] !== "string")
37
+ return undefined;
38
+ // Written by this kayra ui, the lines are its own events.
39
+ const events = rest.filter((each) => isObject(each) && typeof each["kind"] === "string");
40
+ return {
41
+ id: head["id"],
42
+ command: head["command"],
43
+ ...(typeof head["server"] === "string" ? { server: head["server"] } : {}),
44
+ started: head["started"],
45
+ events,
46
+ };
47
+ };
48
+ /** A server is busy while a run on it has not ended: one at a time, as on the command line. */
49
+ export const busy = (runs, server) => server !== undefined && runs.some((run) => run.server === server && stateOf(run.events) === "running");
@@ -0,0 +1,336 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync } from "node:fs";
3
+ import { createServer } from "node:http";
4
+ import { extname, join, normalize, sep } from "node:path";
5
+ import { within } from "../brand.js";
6
+ import { planFor } from "../commands/index.js";
7
+ import { look, opentofu, statusJson } from "../commands/status.js";
8
+ import { findings, validateJson } from "../commands/validate.js";
9
+ import { json, send } from "../deployer/http.js";
10
+ import { gather } from "../gather.js";
11
+ import { capture, interpret } from "../interpret.js";
12
+ import { needsTerminal } from "../plan.js";
13
+ import { err, flatMap, ok } from "../result.js";
14
+ import { listed, reporting } from "../ui/progress.js";
15
+ import { follow } from "../ui/terminal.js";
16
+ import { parsed, releasesSchema, runsSchema } from "../ui/views.js";
17
+ import { admit, cookieName, tokenIn } from "./auth.js";
18
+ import { changes, commandInput, facts, targetOf, toPlanned, words } from "./commands.js";
19
+ import { busy, readRecord, recordLine, runId, stateOf, summary } from "./runs.js";
20
+ /** kayra ui's one mutable cell: the runs it started, swapped whole on every change. */
21
+ // eslint-disable-next-line functional/prefer-immutable-types -- kayra ui's state lives here, nowhere else
22
+ const cell = { live: {} };
23
+ const swap = (id, change) => {
24
+ const current = cell.live[id];
25
+ // eslint-disable-next-line functional/immutable-data -- kayra ui's state lives here, nowhere else
26
+ if (current !== undefined)
27
+ cell.live = { ...cell.live, [id]: change(current) };
28
+ };
29
+ const runsDir = (fleet) => within(fleet.root, ".cache", "ui", "runs");
30
+ const recorded = (fleet) => {
31
+ const dir = runsDir(fleet);
32
+ if (!existsSync(dir))
33
+ return [];
34
+ return readdirSync(dir)
35
+ .filter((name) => name.endsWith(".jsonl"))
36
+ .flatMap((name) => {
37
+ const run = readRecord(readFileSync(join(dir, name), "utf8"));
38
+ return run === undefined ? [] : [run];
39
+ });
40
+ };
41
+ /** Every run kayra ui knows: those it runs now, and those its records keep. */
42
+ const allRuns = (fleet) => {
43
+ const live = Object.values(cell.live).map((each) => each.run);
44
+ return [...live, ...recorded(fleet).filter((run) => !live.some((each) => each.id === run.id))].toSorted((a, b) => b.id.localeCompare(a.id));
45
+ };
46
+ /** Ansible colours its output for a terminal only; the browser draws the colours too. */
47
+ const coloured = (plan) => plan.map((step) => (step.kind === "run" ? { ...step, env: { ...step.env, ANSIBLE_FORCE_COLOR: "1" } } : step));
48
+ /** A server-sent stream; `end` says everything is said, so the browser closes instead of reconnecting. */
49
+ const sse = (response) => {
50
+ response.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" });
51
+ return {
52
+ say: (data) => {
53
+ response.write(`data: ${JSON.stringify(data)}\n\n`);
54
+ },
55
+ end: () => {
56
+ response.end("event: end\ndata: {}\n\n");
57
+ },
58
+ };
59
+ };
60
+ const answerJson = (response, status, value) => {
61
+ send(response, status, JSON.stringify(value), "application/json; charset=utf-8");
62
+ };
63
+ const invocationOf = (ui, input) => flatMap(targetOf(ui.fleet, input), (target) => ok({
64
+ command: words(input),
65
+ ...(target === undefined ? {} : { server: target.name }),
66
+ about: [...(target === undefined ? [] : [`${target.kind} on ${target.target}`, target.domain]), `kayra ${ui.version}`],
67
+ }));
68
+ const planOf = (ui, input) => flatMap(toPlanned(ui.fleet, input), (planned) => planFor({ kayra: ui.kayra, fleet: ui.fleet.root }, ui.fleet, planned));
69
+ const preview = (ui, input) => flatMap(planOf(ui, input), (plan) => flatMap(invocationOf(ui, input), (invocation) => ok({ invocation, steps: listed(plan, ui.short), changes: changes(input) })));
70
+ /** Starts a run, or says why it cannot: one per server, a terminal it needs, a real server not confirmed. */
71
+ const start = (ui, input, confirm) => {
72
+ const target = targetOf(ui.fleet, input);
73
+ const plan = planOf(ui, input);
74
+ const invocation = invocationOf(ui, input);
75
+ if (!target.ok || !plan.ok || !invocation.ok)
76
+ return err([400, [target, plan, invocation].flatMap((each) => (each.ok ? [] : [each.error])).join("; ")]);
77
+ const server = target.value;
78
+ if (needsTerminal(plan.value))
79
+ return err([400, "its vault password is asked on a terminal: run it there, or give the server a vault_password_file"]);
80
+ if (busy(allRuns(ui.fleet), server?.name))
81
+ return err([409, `a run on ${server?.name ?? ""} has not ended`]);
82
+ if (changes(input) && server !== undefined && server.target !== "multipass" && confirm !== server.name)
83
+ return err([403, `this changes ${server.name}: confirm with its name`]);
84
+ const started = new Date().toISOString();
85
+ const id = runId(started, randomBytes(3).toString("hex"));
86
+ const run = { id, command: words(input), ...(server === undefined ? {} : { server: server.name }), started, events: [] };
87
+ const file = join(runsDir(ui.fleet), `${id}.jsonl`);
88
+ mkdirSync(runsDir(ui.fleet), { recursive: true });
89
+ appendFileSync(file, recordLine({ id: run.id, command: run.command, ...(server === undefined ? {} : { server: server.name }), started }));
90
+ // eslint-disable-next-line functional/immutable-data -- kayra ui's state lives here, nowhere else
91
+ cell.live = { ...cell.live, [id]: { run, listeners: [], stop: new AbortController(), answer: undefined } };
92
+ const emit = (event) => {
93
+ appendFileSync(file, recordLine(event));
94
+ swap(id, (live) => ({ ...live, run: { ...live.run, events: [...live.run.events, event] } }));
95
+ cell.live[id]?.listeners.forEach((listener) => {
96
+ listener(event);
97
+ });
98
+ };
99
+ const stop = cell.live[id]?.stop;
100
+ const io = {
101
+ out: (text) => {
102
+ emit({ kind: "said", stream: "out", text });
103
+ },
104
+ err: (text) => {
105
+ emit({ kind: "said", stream: "err", text });
106
+ },
107
+ ask: (prompt) => new Promise((resolve) => {
108
+ swap(id, (live) => ({
109
+ ...live,
110
+ answer: (text) => {
111
+ swap(id, (after) => ({ ...after, answer: undefined }));
112
+ emit({ kind: "answered" });
113
+ resolve(text);
114
+ },
115
+ }));
116
+ emit({ kind: "ask", prompt });
117
+ }),
118
+ output: (chunk, stream) => {
119
+ emit({ kind: "output", stream, chunk });
120
+ },
121
+ ...(stop === undefined ? {} : { signal: stop.signal }),
122
+ };
123
+ void interpret(coloured(plan.value), io, reporting(emit, invocation.value, ui.short), () => stop?.signal.aborted === true);
124
+ return ok(id);
125
+ };
126
+ /** A run's events from the start, then each as it happens, until it has ended. */
127
+ const watchRun = (ui, id, response) => {
128
+ const live = cell.live[id];
129
+ const run = live?.run ?? recorded(ui.fleet).find((each) => each.id === id);
130
+ if (run === undefined) {
131
+ send(response, 404, `no run ${id}\n`);
132
+ return;
133
+ }
134
+ const { say, end } = sse(response);
135
+ run.events.forEach(say);
136
+ if (live === undefined || stateOf(run.events) !== "running") {
137
+ end();
138
+ return;
139
+ }
140
+ const listener = (event) => {
141
+ say(event);
142
+ if (event.kind === "ended")
143
+ end();
144
+ };
145
+ swap(id, (current) => ({ ...current, listeners: [...current.listeners, listener] }));
146
+ response.on("close", () => {
147
+ swap(id, (current) => ({ ...current, listeners: current.listeners.filter((each) => each !== listener) }));
148
+ });
149
+ };
150
+ /** What a deployer's ctl answers, captured over SSH as `kayra app …` asks it. */
151
+ const ctl = async (ui, input) => {
152
+ const server = ui.fleet.servers.find((each) => each.name === input.server);
153
+ if (server === undefined)
154
+ return err(`no server '${input.server}'`);
155
+ const app = server.apps.find((each) => each.name === input.app);
156
+ if (app === undefined)
157
+ return err(`'${input.app}' is not an app of ${server.name}`);
158
+ const plan = planFor({ kayra: ui.kayra, fleet: ui.fleet.root }, ui.fleet, { name: input.name, server: server.name, app: app.name, more: input.more });
159
+ if (!plan.ok)
160
+ return plan;
161
+ const [step] = plan.value;
162
+ if (step?.kind !== "run")
163
+ return err("the deployer's plan has no step");
164
+ const [program, ...args] = step.argv;
165
+ const argv = args.flatMap((arg) => (typeof arg === "string" ? [arg] : []));
166
+ const exit = await capture([program, ...argv], "capture");
167
+ return exit.code === 0 ? ok(exit.stdout) : err(exit.stderr.trim() === "" ? `exit ${String(exit.code)}` : exit.stderr.trim());
168
+ };
169
+ const types = {
170
+ ".html": "text/html; charset=utf-8",
171
+ ".js": "text/javascript; charset=utf-8",
172
+ ".css": "text/css; charset=utf-8",
173
+ ".svg": "image/svg+xml",
174
+ ".png": "image/png",
175
+ ".ico": "image/x-icon",
176
+ ".woff2": "font/woff2",
177
+ ".json": "application/json; charset=utf-8",
178
+ };
179
+ const unbuilt = `<!doctype html><meta charset="utf-8"><title>kayra ui</title>
180
+ <body style="font:15px system-ui;margin:3rem auto;max-width:40rem"><h1>kayra ui</h1>
181
+ <p>The browser side is not built in this checkout:</p><pre>npm --prefix web ci &amp;&amp; npm --prefix web run build</pre>
182
+ <p>The API is up at <code>/api/fleet</code>.</p></body>`;
183
+ /** The built browser side; a path that is no file is the app's own route, answered by its index. */
184
+ const asset = (ui, path, response) => {
185
+ if (ui.assets === undefined) {
186
+ send(response, 200, unbuilt, "text/html; charset=utf-8");
187
+ return;
188
+ }
189
+ const file = normalize(join(ui.assets, decodeURIComponent(path)));
190
+ const inside = file.startsWith(ui.assets + sep) && existsSync(file) && statSync(file).isFile();
191
+ const chosen = inside ? file : join(ui.assets, "index.html");
192
+ response.writeHead(200, {
193
+ "Content-Type": types[extname(chosen)] ?? "application/octet-stream",
194
+ "Cache-Control": chosen.includes(`${sep}assets${sep}`) ? "public, max-age=31536000, immutable" : "no-cache",
195
+ });
196
+ response.end(readFileSync(chosen));
197
+ };
198
+ const route = async (ui, port, token, request, response) => {
199
+ const url = new URL(request.url ?? "/", `http://127.0.0.1:${String(port)}`);
200
+ const path = url.pathname;
201
+ const method = request.method ?? "GET";
202
+ const admission = admit({ method, path, host: request.headers.host, origin: request.headers.origin, cookie: request.headers.cookie }, port, token);
203
+ if (!admission.admitted) {
204
+ send(response, admission.status, `${admission.why}\n`);
205
+ return;
206
+ }
207
+ if (path === "/login") {
208
+ if (!tokenIn(url.searchParams, token)) {
209
+ send(response, 401, "not this launch's token: open the URL kayra ui printed\n");
210
+ return;
211
+ }
212
+ response.writeHead(303, { "Set-Cookie": `${cookieName(port)}=${token}; HttpOnly; SameSite=Strict; Path=/`, Location: "/" });
213
+ response.end();
214
+ return;
215
+ }
216
+ if (!path.startsWith("/api/")) {
217
+ asset(ui, path, response);
218
+ return;
219
+ }
220
+ const app = /^\/api\/servers\/([^/]+)\/apps\/([^/]+)\/(runs|releases|logs)(?:\/([^/]+))?$/.exec(path);
221
+ const runPath = /^\/api\/runs\/([^/]+)\/(events|answer|cancel)$/.exec(path);
222
+ if (method === "GET" && path === "/api/fleet") {
223
+ const fleetFacts = { fleet: ui.fleet.root.split(sep).at(-1) ?? "", version: ui.version, servers: ui.fleet.servers.map(facts) };
224
+ answerJson(response, 200, fleetFacts);
225
+ }
226
+ else if (method === "GET" && path === "/api/status") {
227
+ const { say, end } = sse(response);
228
+ const { initial, updates } = look(ui.fleet, opentofu, ui.network);
229
+ await follow(initial, updates, (looks) => {
230
+ const status = statusJson(looks);
231
+ say(status);
232
+ });
233
+ end();
234
+ }
235
+ else if (method === "GET" && path === "/api/validate") {
236
+ const reports = await Promise.all(ui.fleet.servers.map(async (server) => ({ server, findings: findings(await gather(ui.fleet.root, server)) })));
237
+ const validation = validateJson(reports);
238
+ answerJson(response, 200, validation);
239
+ }
240
+ else if (method === "GET" && app !== null) {
241
+ const [, server = "", name = "", what, more] = app;
242
+ const asked = { server: decodeURIComponent(server), app: decodeURIComponent(name) };
243
+ const answer = await ctl(ui, {
244
+ ...asked,
245
+ name: what === "runs" ? "app runs" : what === "releases" ? "app rollback" : "app logs",
246
+ ...(more === undefined ? {} : { more: decodeURIComponent(more) }),
247
+ });
248
+ if (!answer.ok)
249
+ send(response, 502, `${answer.error}\n`);
250
+ else if (what === "logs")
251
+ send(response, 200, answer.value);
252
+ else {
253
+ const value = what === "runs" ? parsed(runsSchema, answer.value) : parsed(releasesSchema, answer.value);
254
+ if (value === undefined)
255
+ send(response, 502, "the server's deployer answered in a form this kayra does not read: deploy it with this kayra\n");
256
+ else
257
+ answerJson(response, 200, value);
258
+ }
259
+ }
260
+ else if (method === "POST" && path === "/api/plan") {
261
+ const input = commandInput.safeParse(await json(request));
262
+ const shown = input.success ? preview(ui, input.data) : err(input.error.issues.at(0)?.message ?? "not a command");
263
+ if (shown.ok)
264
+ answerJson(response, 200, shown.value);
265
+ else
266
+ send(response, 400, `${shown.error}\n`);
267
+ }
268
+ else if (method === "GET" && path === "/api/runs") {
269
+ const runs = allRuns(ui.fleet).slice(0, 50).map(summary);
270
+ answerJson(response, 200, runs);
271
+ }
272
+ else if (method === "POST" && path === "/api/runs") {
273
+ const body = await json(request);
274
+ const input = commandInput.safeParse(typeof body === "object" && body !== null && "command" in body ? body.command : undefined);
275
+ const confirm = typeof body === "object" && body !== null && "confirm" in body ? body.confirm : undefined;
276
+ const started = input.success ? start(ui, input.data, confirm) : err([400, input.error.issues.at(0)?.message ?? "not a command"]);
277
+ if (started.ok)
278
+ answerJson(response, 201, { id: started.value });
279
+ else
280
+ send(response, started.error[0], `${started.error[1]}\n`);
281
+ }
282
+ else if (runPath !== null) {
283
+ const [, id = "", what] = runPath;
284
+ const live = cell.live[id];
285
+ if (method === "GET" && what === "events")
286
+ watchRun(ui, id, response);
287
+ else if (method === "POST" && what === "cancel" && live !== undefined) {
288
+ live.stop.abort();
289
+ send(response, 202, "stopping\n");
290
+ }
291
+ else if (method === "POST" && what === "answer" && live?.answer !== undefined) {
292
+ const body = await json(request);
293
+ live.answer(typeof body === "object" && body !== null && "text" in body && typeof body.text === "string" ? body.text : "");
294
+ send(response, 204, "");
295
+ }
296
+ else
297
+ send(response, 404, `nothing to ${what ?? ""} for run ${id}\n`);
298
+ }
299
+ else
300
+ send(response, 404, "not found\n");
301
+ };
302
+ /** kayra ui: listens on 127.0.0.1 only; the URL it returns carries this launch's token. */
303
+ export const serveUi = (ui, port) => {
304
+ const token = randomBytes(32).toString("base64url");
305
+ return new Promise((resolve, reject) => {
306
+ const server = createServer((request, response) => {
307
+ route(ui, listening(), token, request, response).catch((error) => {
308
+ if (!response.headersSent)
309
+ send(response, 500, `${error instanceof Error ? error.message : String(error)}\n`);
310
+ else
311
+ response.end();
312
+ });
313
+ });
314
+ const listening = () => {
315
+ const address = server.address();
316
+ return typeof address === "object" && address !== null ? address.port : port;
317
+ };
318
+ server.once("error", reject);
319
+ server.listen(port, "127.0.0.1", () => {
320
+ const actual = listening();
321
+ resolve({
322
+ url: `http://127.0.0.1:${String(actual)}/login?token=${token}`,
323
+ port: actual,
324
+ close: () => new Promise((done) => {
325
+ Object.values(cell.live).forEach((live) => {
326
+ live.stop.abort();
327
+ });
328
+ server.closeAllConnections();
329
+ server.close(() => {
330
+ done();
331
+ });
332
+ }),
333
+ });
334
+ });
335
+ });
336
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yunuseon/kayra",
3
- "version": "0.15.0",
3
+ "version": "0.16.1",
4
4
  "description": "A self-hosted app platform and the CLI that runs it: Traefik, Authelia, a registry, rootless BuildKit and a small deployer per server, set up with OpenTofu and Ansible.",
5
5
  "license": "MIT",
6
6
  "author": "Yunus Öztürk",
@@ -34,7 +34,8 @@
34
34
  "scripts": {
35
35
  "kayra": "node cli/src/main.ts",
36
36
  "build": "tsc -p cli/tsconfig.build.json",
37
- "prepack": "npm run build",
37
+ "build:web": "npm --prefix web ci --silent && npm --prefix web run build -- --outDir ../cli/dist/browser --emptyOutDir",
38
+ "prepack": "npm run build && npm run build:web",
38
39
  "typecheck": "tsc -p cli --noEmit",
39
40
  "lint": "cd cli && eslint --flag unstable_native_nodejs_ts_config .",
40
41
  "test": "node --test 'cli/test/**/*.test.ts'",
@@ -57,6 +57,8 @@ if has "${kayra} +(--[a-z-]+ +)*${verbs}( |$)" && ! has '--dry-run'; then
57
57
  || target="$(sed -n 's/^target: *\([a-z]*\).*/\1/p' "${project}/servers/${server}/server.yml")"
58
58
  [ "$target" = multipass ] || ask "kayra changes ${server:-a server}${target:+ (target ${target})}"
59
59
  fi
60
+ # kayra ui runs any command on any server from a browser, where this guard sees none of them.
61
+ has "${kayra} +(--[a-z-]+ +)*ui( |$)" && ask "kayra ui runs commands on every server from a browser, out of this guard's sight"
60
62
 
61
63
  # ── Ansible and the vaults ──────────────────────────────────────────────────
62
64
  has '(^|[;&|( ])ansible-vault +(decrypt|view|edit|encrypt|encrypt_string|rekey|create)( |$)' \
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env bash
2
+ # Packs kayra as npm publishes it, installs the tarball the way a fleet does,
3
+ # and runs it: its version, its help, and kayra ui answering with its browser
4
+ # side. Run by release.yml before npm publish, and by hand before a release.
5
+ # bash scripts/local/packed-runs.sh
6
+ set -euo pipefail
7
+ here="$(cd "$(dirname "$0")/../.." && pwd)"
8
+ work="$(mktemp -d)"
9
+ trap 'kill "${ui:-}" 2>/dev/null || true; rm -rf "$work"' EXIT
10
+
11
+ tarball="$(cd "$here" && npm pack --silent --pack-destination "$work" | tail -1)"
12
+ mkdir -p "${work}/fleet/servers"
13
+ printf 'acme_email: ops@example.com\n' > "${work}/fleet/servers/defaults.yml"
14
+ (cd "${work}/fleet" && npm init -y >/dev/null && npm install --silent --no-audit --no-fund "${work}/${tarball}")
15
+ kayra="${work}/fleet/node_modules/@yunuseon/kayra/bin/kayra.js"
16
+
17
+ version="$(cd "${work}/fleet" && node "$kayra" --version)"
18
+ expected="$(node -p "require('${here}/package.json').version")"
19
+ [ "$version" = "$expected" ] || { echo "✗ the packed kayra says ${version}, not ${expected}" >&2; exit 1; }
20
+ (cd "${work}/fleet" && node "$kayra" --help >/dev/null)
21
+
22
+ (cd "${work}/fleet" && node "$kayra" ui --no-open --port 0 > "${work}/ui.out" 2>&1) &
23
+ ui=$!
24
+ for _ in $(seq 1 50); do grep -q '/login?token=' "${work}/ui.out" && break; sleep 0.2; done
25
+ url="$(grep -o 'http://127.0.0.1:[0-9]*/login?token=[A-Za-z0-9_-]*' "${work}/ui.out")" || { cat "${work}/ui.out" >&2; echo "✗ kayra ui did not start" >&2; exit 1; }
26
+ page="$(curl -sf -L -c "${work}/jar" -b "${work}/jar" "$url")"
27
+ grep -q '<script type="module"' <<< "$page" || { echo "✗ kayra ui serves no built browser side" >&2; exit 1; }
28
+ echo "✓ the packed kayra ${version} runs, and kayra ui serves its browser side"