@basaltkit/deploy-ui 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,154 @@
1
+ import { confirmDialog } from './dialog.js';
2
+ import { append, button, el, replace } from './dom.js';
3
+ import { banner, describe, diagnosticsBlock, problem } from './reply.js';
4
+ import { ApiError } from './api.js';
5
+ /** Plan & deploy: what a run would do, the questions it would ask, and the `.env` form. */
6
+ export function renderPlan(app) {
7
+ const reply = app.planReply;
8
+ const plan = app.plan;
9
+ const root = el('section', { aria: { labelledby: 'plan-title' } }, el('div', { class: 'row' }, el('h2', { id: 'plan-title' }, 'Plan & deploy'), button(app.planBusy ? 'Planning…' : plan ? 'Plan again' : 'Run plan', () => { void app.runPlan(); }, { disabled: app.planBusy, class: plan ? '' : 'primary' })), el('p', { class: 'muted' }, 'plan changes nothing on the server. Its preflight may reach the git remote, so it can take a while.'));
10
+ if (!reply)
11
+ return root;
12
+ if (!plan) {
13
+ append(root, problem(reply) ?? el('p', {}, 'No plan came back.'));
14
+ return root;
15
+ }
16
+ append(root, ...findings(plan.findings));
17
+ if (plan.lines.length > 0) {
18
+ append(root, el('h3', {}, 'What a run would do'), el('div', { class: 'table-wrap' }, el('table', {}, el('tbody', {}, ...plan.lines.map((line) => el('tr', {}, el('th', { class: 'mono' }, line.step), el('td', {}, line.text)))))));
19
+ }
20
+ if (reply.diagnostics.length > 0)
21
+ append(root, diagnosticsBlock(reply.diagnostics));
22
+ append(root, deployForm(app, plan.questions, plan.blocking));
23
+ return root;
24
+ }
25
+ function findings(list) {
26
+ if (list.length === 0)
27
+ return [banner('ok', 'No problem found.')];
28
+ const sorted = [...list].sort((a, b) => (a.level === b.level ? 0 : a.level === 'error' ? -1 : 1));
29
+ return [el('h3', {}, 'Findings'), el('ul', {}, ...sorted.map((f) => el('li', {}, el('strong', { class: f.level === 'error' ? 'status-err' : 'status-warn' }, f.level === 'error' ? 'Error ' : 'Warning '), el('span', { class: 'muted' }, `[${f.id}] `), f.message, f.fix ? el('div', {}, 'Fix: ', el('code', {}, f.fix)) : null)))];
30
+ }
31
+ function questionField(question, index) {
32
+ const id = `q-${index}`;
33
+ const label = el('label', { for: id }, question.message, question.key ? el('span', { class: 'muted' }, ` (${question.key})`) : null, question.optional ? '' : el('span', { class: 'required' }, ' *'));
34
+ let input;
35
+ if (question.kind === 'secret') {
36
+ // No default, no autocomplete, no spellcheck: a secret is typed, sent once, and the field is emptied.
37
+ input = el('input', { type: 'password', id, autocomplete: 'off', spellcheck: false, required: !question.optional, aria: { describedby: `${id}-error` } });
38
+ }
39
+ else if (question.kind === 'choice') {
40
+ input = el('select', { id, aria: { describedby: `${id}-error` } }, ...(question.optional ? [el('option', { value: '' }, '(none)')] : []), ...(question.choices ?? []).map((c) => el('option', { value: c }, c)));
41
+ if (question.default !== undefined)
42
+ input.value = question.default;
43
+ }
44
+ else if (question.kind === 'confirm') {
45
+ input = el('input', { type: 'checkbox', id, checked: question.default === 'yes' || question.default === 'true', aria: { describedby: `${id}-error` } });
46
+ }
47
+ else {
48
+ input = el('input', { type: 'text', id, value: question.default ?? '', autocomplete: 'off', spellcheck: false, required: !question.optional, aria: { describedby: `${id}-error` } });
49
+ }
50
+ return { node: el('div', { class: 'field' }, label, input, el('span', { id: `${id}-error`, class: 'field-error' })), field: { question, input } };
51
+ }
52
+ /** The answers the operator typed: empty optional fields are left out (the deploy keeps its default or nothing). */
53
+ function collectAnswers(fields) {
54
+ const answers = [];
55
+ for (const { question, input } of fields) {
56
+ const value = question.kind === 'confirm' ? (input.checked ? 'yes' : 'no') : input.value;
57
+ if (value === '' && question.optional)
58
+ continue;
59
+ answers.push({ id: question.id, value });
60
+ }
61
+ return answers;
62
+ }
63
+ /** Every field emptied, so no value lingers in the page after it was sent. */
64
+ function clearFields(fields) {
65
+ for (const { input } of fields) {
66
+ if (input instanceof HTMLInputElement && input.type === 'checkbox')
67
+ input.checked = false;
68
+ else
69
+ input.value = '';
70
+ }
71
+ }
72
+ function deployForm(app, questions, blocking) {
73
+ const t = app.current;
74
+ const fields = [];
75
+ const nodes = questions.map((q, i) => {
76
+ const { node, field } = questionField(q, i);
77
+ fields.push(field);
78
+ return node;
79
+ });
80
+ const message = el('div', { aria: { live: 'polite' } });
81
+ const hold = app.status?.hold;
82
+ const unhold = el('input', { type: 'checkbox', id: 'unhold' });
83
+ const attended = el('input', { type: 'checkbox', id: 'attended' });
84
+ const showFieldError = (id, text) => {
85
+ const index = questions.findIndex((q) => q.id === id);
86
+ const slot = index === -1 ? undefined : app.shell.main.querySelector(`#q-${index}-error`);
87
+ if (slot)
88
+ replace(slot, text);
89
+ };
90
+ const send = async (route) => {
91
+ if (!t)
92
+ return;
93
+ replace(message);
94
+ for (let i = 0; i < questions.length; i++) {
95
+ const slot = app.shell.main.querySelector(`#q-${i}-error`);
96
+ if (slot)
97
+ replace(slot);
98
+ }
99
+ const deploy = route === 'run';
100
+ const ok = await confirmDialog({
101
+ title: deploy ? `Deploy to ${t.name}?` : `Write the .env on ${t.name}?`,
102
+ lines: [
103
+ `${t.ssh} · ${t.dir}${app.hello ? ` · host ${app.hello.host}` : ''}${app.status ? ` · app ${app.status.app}` : ''}`,
104
+ deploy ? 'Fetch, .env, build, migrate, restart, health check — the run goes on on the server if this page closes (unless attended).' : 'The .env and the dedicated infra only; nothing is built or restarted.',
105
+ deploy && app.plan?.lines.some((l) => /migrat/i.test(l.step) || /migrat/i.test(l.text)) ? el('strong', {}, 'This will migrate the database.') : null,
106
+ ],
107
+ confirmLabel: deploy ? 'Deploy' : 'Write .env',
108
+ danger: true,
109
+ ...(t.protected ? { typeToConfirm: t.name } : {}),
110
+ });
111
+ if (!ok)
112
+ return;
113
+ const answers = collectAnswers(fields);
114
+ clearFields(fields);
115
+ const body = { target: t.name, confirm: true, confirmedTarget: t, answers, ...(t.protected ? { confirmName: t.name } : {}) };
116
+ if (!deploy) {
117
+ app.attended(`env on ${t.name}`, 'env', body);
118
+ return;
119
+ }
120
+ if (unhold.checked)
121
+ body['unhold'] = true;
122
+ if (attended.checked) {
123
+ body['attended'] = true;
124
+ app.attended(`run on ${t.name} (attended)`, 'run', body);
125
+ return;
126
+ }
127
+ replace(message, el('p', { class: 'muted' }, 'Starting the run on the server…'));
128
+ let reply;
129
+ try {
130
+ reply = await app.api.post('run', body);
131
+ }
132
+ catch (error) {
133
+ const field = error instanceof ApiError && typeof error.body['field'] === 'string' ? error.body['field'] : undefined;
134
+ if (field)
135
+ showFieldError(field, describe(error));
136
+ replace(message, problem(undefined, error));
137
+ void app.noticeChange(error);
138
+ return;
139
+ }
140
+ const result = reply.result;
141
+ if (reply.ok && result?.runId) {
142
+ replace(message);
143
+ app.watch(result.runId, `run ${result.runId}`);
144
+ return;
145
+ }
146
+ if (reply.error && /^answer-/.test(reply.error.code)) {
147
+ const id = /env\.[A-Z_][A-Z0-9_]*/.exec(reply.error.message)?.[0];
148
+ if (id)
149
+ showFieldError(id, `${reply.error.message} — type it again`);
150
+ }
151
+ replace(message, problem(reply));
152
+ };
153
+ return el('form', { class: 'panel', aria: { label: 'Deploy' }, on: { submit: (event) => { event.preventDefault(); void send('run'); } } }, el('h3', {}, questions.length > 0 ? 'What the run will ask' : 'Deploy'), questions.length > 0 ? el('p', { class: 'muted' }, 'Secrets are sent once, over your ssh, to the deploy on the server; they are never stored here and the fields are emptied after sending.') : el('p', { class: 'muted' }, 'Nothing to answer: the .env is complete.'), ...nodes, hold ? el('div', { class: 'field' }, el('label', { for: 'unhold' }, unhold, ' Deploy anyway: the held commit ', el('code', {}, hold.sha.slice(0, 12)), ' may be deployed (--unhold)')) : null, el('details', {}, el('summary', {}, 'Advanced'), el('div', { class: 'field' }, el('label', { for: 'attended' }, attended, ' Attended: the run stops at its next step if this page closes or the UI quits'))), blocking ? banner('err', 'The plan found problems that stop a run: fix them first.') : null, el('div', { class: 'row' }, el('button', { type: 'submit', class: 'primary', disabled: blocking }, 'Deploy…'), button('Write .env only…', () => { void send('env'); })), message);
154
+ }
@@ -0,0 +1,311 @@
1
+ import { ApiError } from './api.js';
2
+ import { confirmDialog } from './dialog.js';
3
+ import { append, button, el, replace } from './dom.js';
4
+ import { banner, describe, errorBanner, problem } from './reply.js';
5
+ import { clean } from './sanitize.js';
6
+ /** The log lines kept in the page; the full log stays on the server ("Show from the start" replays it). */
7
+ export const MAX_LOG_LINES = 5000;
8
+ const SEQ_KEY = (runId) => `basalt-deploy-ui:seq:${runId}`;
9
+ /**
10
+ * One run, live: steps, findings, the log and a final banner, fed by stream
11
+ * messages. Dispatch is on the event's `type` only — never on its text, so a
12
+ * build that prints a fake `done` is a log line.
13
+ */
14
+ export class RunView {
15
+ app;
16
+ target;
17
+ runId;
18
+ element;
19
+ ended = false;
20
+ following = false;
21
+ /** The run's last seq this view showed (the resume key). */
22
+ lastSeq;
23
+ controller;
24
+ stateLine;
25
+ steps;
26
+ stepNodes = new Map();
27
+ stepTitles = new Map();
28
+ /** The run's own `done` was seen (or attach said it had finished): nothing more will come. */
29
+ runFinished = false;
30
+ findings;
31
+ log;
32
+ outcome;
33
+ actions;
34
+ diagnostics;
35
+ dropped = 0;
36
+ cancels = 0;
37
+ exitCode;
38
+ failed;
39
+ lastError;
40
+ constructor(app, target, title, runId) {
41
+ this.app = app;
42
+ this.target = target;
43
+ this.runId = runId;
44
+ this.stateLine = el('p', { class: 'muted', role: 'status', aria: { live: 'polite' } });
45
+ this.steps = el('ol', { class: 'steps', aria: { label: 'Steps' } });
46
+ this.findings = el('ul', { aria: { label: 'Findings' } });
47
+ this.log = el('ol', { class: 'log', aria: { label: 'Log' } });
48
+ this.outcome = el('div');
49
+ this.actions = el('div', { class: 'row' });
50
+ this.diagnostics = el('pre', { class: 'diagnostics', hidden: true });
51
+ this.element = el('section', { aria: { labelledby: 'run-title' } }, el('h2', { id: 'run-title' }, title), el('p', { class: 'muted' }, `${target.name} · ${target.ssh} · ${target.dir}`), this.stateLine, this.actions, el('h3', {}, 'Steps'), this.steps, this.findings, el('h3', {}, 'Log'), this.log, this.outcome, this.diagnostics);
52
+ this.renderActions();
53
+ }
54
+ /** Where to resume: the seq after the last one this tab saw for this run, kept in sessionStorage (not a secret). */
55
+ resumeSeq() {
56
+ if (!this.runId)
57
+ return 0;
58
+ try {
59
+ const stored = this.app.storage?.getItem(SEQ_KEY(this.runId));
60
+ const seq = stored === null || stored === undefined ? NaN : Number(stored);
61
+ return Number.isSafeInteger(seq) && seq >= 0 ? seq + 1 : 0;
62
+ }
63
+ catch {
64
+ return 0;
65
+ }
66
+ }
67
+ stop() {
68
+ this.controller?.abort();
69
+ this.following = false;
70
+ }
71
+ async attach(fromSeq) {
72
+ if (!this.runId)
73
+ return;
74
+ if (fromSeq > 0)
75
+ this.note(`(resuming from event ${fromSeq}: earlier events were shown before; "Show from the start" replays them)`);
76
+ await this.consume('attach', { target: this.target.name, runId: this.runId, fromSeq });
77
+ }
78
+ async streamAttended(route, body) {
79
+ await this.consume(route, body);
80
+ }
81
+ async consume(route, body) {
82
+ this.controller = new AbortController();
83
+ this.following = true;
84
+ this.ended = false;
85
+ this.failed = undefined;
86
+ this.renderActions();
87
+ try {
88
+ await this.app.api.stream(route, body, (message) => this.handle(message), this.controller.signal);
89
+ }
90
+ catch (error) {
91
+ if (!this.controller.signal.aborted) {
92
+ this.failed = { code: 'local', reason: describe(error) };
93
+ replace(this.outcome, problem(undefined, error));
94
+ void this.app.noticeChange(error);
95
+ }
96
+ }
97
+ finally {
98
+ this.following = false;
99
+ if (!this.ended)
100
+ this.setState(this.controller.signal.aborted ? 'Stopped watching (the run goes on on the server).' : 'The stream ended.');
101
+ this.renderActions();
102
+ }
103
+ }
104
+ handle(message) {
105
+ switch (message.kind) {
106
+ case 'hello':
107
+ this.app.hello = message.hello;
108
+ this.app.renderBar();
109
+ return;
110
+ case 'diagnostic':
111
+ this.diagnostics.hidden = false;
112
+ append(this.diagnostics, `${message.text}\n`);
113
+ return;
114
+ case 'state':
115
+ return this.state(message);
116
+ case 'event':
117
+ return this.event(message.event, message.known);
118
+ }
119
+ }
120
+ state(message) {
121
+ if (message.state === 'connecting')
122
+ return this.setState(`Connecting to ${this.target.ssh}…`);
123
+ if (message.state === 'reconnecting') {
124
+ return this.setState(`Connection lost (${clean(message.reason)}); reconnecting in ${Math.round((message.retryInMs ?? 0) / 1000)} s from event ${this.lastSeq === undefined ? 0 : this.lastSeq + 1}…`);
125
+ }
126
+ this.ended = true;
127
+ if (message.exitCode !== undefined)
128
+ this.exitCode = message.exitCode;
129
+ if (this.runId && message.exitCode !== undefined && !message.code) {
130
+ this.runFinished = true;
131
+ if (message.reason)
132
+ this.note(`(${clean(message.reason)})`);
133
+ }
134
+ if (message.code) {
135
+ this.failed = { code: message.code, ...(message.reason ? { reason: message.reason } : {}), ...(message.hint ? { hint: message.hint } : {}) };
136
+ }
137
+ this.finish();
138
+ }
139
+ event(event, known) {
140
+ this.lastSeq = event.seq;
141
+ if (this.runId) {
142
+ try {
143
+ this.app.storage?.setItem(SEQ_KEY(this.runId), String(event.seq));
144
+ }
145
+ catch {
146
+ // No storage (private mode): resume from 0 instead.
147
+ }
148
+ }
149
+ if (!known)
150
+ return this.line('warn', `an event this UI does not know (${event.type}): ignored`);
151
+ switch (event.type) {
152
+ case 'hello':
153
+ return;
154
+ case 'step-start': {
155
+ const node = el('li', {}, `▸ ${event.title} …`);
156
+ this.stepNodes.set(event.id, node);
157
+ this.stepTitles.set(event.id, event.title);
158
+ this.steps.append(node);
159
+ this.setState(`Step: ${event.title}`);
160
+ return;
161
+ }
162
+ case 'step-end': {
163
+ const node = this.stepNodes.get(event.id) ?? el('li');
164
+ const mark = event.status === 'ok' ? '✓' : event.status === 'skipped' ? '–' : '✗';
165
+ // A step that started before the resume point has no node: its id names it.
166
+ const title = this.stepTitles.get(event.id) ?? event.id;
167
+ replace(node, el('span', { class: event.status === 'ok' ? 'status-ok' : event.status === 'skipped' ? 'muted' : 'status-err' }, `${mark} ${title}`), ` — ${event.status}, ${(event.durationMs / 1000).toFixed(1)} s`);
168
+ if (!node.parentNode)
169
+ this.steps.append(node);
170
+ return;
171
+ }
172
+ case 'log':
173
+ return this.line(event.level, event.text, event.source);
174
+ case 'finding':
175
+ this.findings.append(el('li', {}, el('strong', { class: event.level === 'error' ? 'status-err' : 'status-warn' }, event.level === 'error' ? 'Error ' : 'Warning '), event.message, event.fix ? el('div', {}, 'Fix: ', el('code', {}, event.fix)) : null));
176
+ return;
177
+ case 'prompt':
178
+ return this.line('warn', `the deploy asks: ${event.message} (answer it in the form and run again)`);
179
+ case 'result':
180
+ this.outcome.append(resultBanner(event.command, event.data));
181
+ return;
182
+ case 'error':
183
+ this.lastError = event;
184
+ this.outcome.append(errorBanner(event));
185
+ return;
186
+ case 'done':
187
+ this.exitCode = event.exitCode;
188
+ if (this.runId)
189
+ this.runFinished = true;
190
+ return;
191
+ case 'event':
192
+ // Only the server unwraps attach; a nested wrapper here is a log-worthy oddity.
193
+ return this.line('warn', 'an unexpected wrapped event was ignored');
194
+ }
195
+ }
196
+ line(level, textValue, source) {
197
+ if (this.log.childElementCount >= MAX_LOG_LINES) {
198
+ this.log.firstElementChild?.remove();
199
+ this.dropped++;
200
+ this.setDropped();
201
+ }
202
+ const mark = level === 'error' ? '✗ ' : level === 'warn' ? '! ' : '';
203
+ this.log.append(el('li', { class: level === 'error' || level === 'warn' ? level : '' }, mark, source ? el('span', { class: 'src' }, `[${source}] `) : null, textValue));
204
+ }
205
+ note(textValue) {
206
+ this.log.append(el('li', { class: 'src' }, textValue));
207
+ }
208
+ setDropped() {
209
+ this.stateLine.dataset['dropped'] = String(this.dropped);
210
+ }
211
+ setState(textValue) {
212
+ replace(this.stateLine, textValue, this.dropped > 0 ? ` (${this.dropped} older log lines dropped from the page)` : '');
213
+ }
214
+ finish() {
215
+ // Status is refreshed once after any action (no polling loop).
216
+ void this.app.refreshStatus();
217
+ if (this.failed && this.exitCode === undefined) {
218
+ const reconnectable = this.runId !== undefined;
219
+ this.setState(`Stopped: ${clean(this.failed.reason ?? this.failed.code)}`);
220
+ this.outcome.append(banner('err', this.failed.reason ?? 'the stream ended', [this.failed.hint ?? '', reconnectable ? 'The run may still be going on the server: re-attach to see.' : ''], [], this.failed.code));
221
+ }
222
+ else if (this.exitCode === 0) {
223
+ this.setState('Done.');
224
+ this.outcome.append(banner('ok', 'Finished: exit 0'));
225
+ }
226
+ else {
227
+ this.setState(`Finished with exit ${this.exitCode ?? 'unknown'}`);
228
+ if (!this.lastError)
229
+ this.outcome.append(banner('err', `Finished with exit ${this.exitCode ?? 'unknown'}`));
230
+ }
231
+ this.renderActions();
232
+ }
233
+ renderActions() {
234
+ const buttons = [];
235
+ if (this.runId && !this.ended && this.following) {
236
+ buttons.push(button(this.cancels > 0 ? 'Cancel again (stop now)…' : 'Cancel…', () => { void this.cancel(this.cancels > 0); }, { class: 'danger' }));
237
+ buttons.push(button('Stop watching', () => this.stop()));
238
+ }
239
+ if (this.runId && !this.following) {
240
+ // A finished run has nothing more to attach to: only a replay makes sense.
241
+ if (!this.runFinished)
242
+ buttons.push(button('Re-attach', () => { void this.attach(this.lastSeq === undefined ? 0 : this.lastSeq + 1); }, { class: 'primary' }));
243
+ buttons.push(button('Show from the start', () => { this.app.watch(this.runId, `run ${this.runId}`, true); }, this.runFinished ? { class: 'primary' } : {}));
244
+ }
245
+ if (!this.following)
246
+ buttons.push(button('Refresh status', () => { void this.app.refreshStatus().then(() => this.app.show('status')); }));
247
+ replace(this.actions, ...buttons);
248
+ }
249
+ /** Two separate confirmations: the second one ends the deploy at once. */
250
+ async cancel(second) {
251
+ if (!this.runId)
252
+ return;
253
+ const ok = await confirmDialog(second
254
+ ? {
255
+ title: 'Stop the deploy NOW?',
256
+ lines: [
257
+ 'This ends the deploy at once, mid-step.',
258
+ el('strong', {}, 'A migration may be left half-applied'),
259
+ 'The restore command for the pre-deploy dump is in the log. The lock is left stale.',
260
+ ],
261
+ confirmLabel: 'Stop it now',
262
+ danger: true,
263
+ }
264
+ : {
265
+ title: `Cancel the run on ${this.target.name}?`,
266
+ lines: [
267
+ 'It stops at the next step boundary before the migration; from the migration on, the deploy finishes first.',
268
+ 'A second cancel would stop it at once. If this run was already cancelled once (from a terminal or another session), nothing is sent now: you are asked again first.',
269
+ ],
270
+ confirmLabel: 'Cancel the run',
271
+ danger: true,
272
+ });
273
+ if (!ok)
274
+ return;
275
+ let reply;
276
+ try {
277
+ reply = await this.app.api.post('cancel', { target: this.target.name, runId: this.runId, confirm: true, ...(second ? { second: true } : {}) });
278
+ }
279
+ catch (error) {
280
+ if (error instanceof ApiError && error.body['second'] === true && !second)
281
+ return this.cancel(true);
282
+ this.outcome.append(problem(undefined, error));
283
+ return;
284
+ }
285
+ if (reply.ok) {
286
+ this.cancels++;
287
+ const result = reply.result;
288
+ this.note(result?.second ? 'cancel sent a second time: the deploy stops at once' : 'cancel sent: the deploy stops at its next safe point');
289
+ this.renderActions();
290
+ return;
291
+ }
292
+ this.outcome.append(problem(reply));
293
+ }
294
+ }
295
+ function resultBanner(command, data) {
296
+ const d = (data ?? {});
297
+ if (command === 'run') {
298
+ return banner(d['status'] === 'ok' ? 'ok' : 'err', `Release ${clean(d['sha']).slice(0, 12)}: ${clean(d['status'])}`, [
299
+ d['url'] ? `${clean(d['url'])}` : '',
300
+ Array.isArray(d['migrations']) && d['migrations'].length > 0 ? `migrations: ${d['migrations'].map(clean).join(', ')}` : '',
301
+ d['note'] ? clean(d['note']) : '',
302
+ ]);
303
+ }
304
+ if (command === 'rollback')
305
+ return banner(d['status'] === 'ok' ? 'ok' : 'err', `Rolled back to ${clean(d['to']).slice(0, 12)}: ${clean(d['status'])}`, [`${clean(d['held']).slice(0, 12)} is held`]);
306
+ if (command === 'env') {
307
+ const changes = Array.isArray(d['changes']) ? d['changes'] : [];
308
+ return banner('ok', `.env written (${changes.length} change${changes.length === 1 ? '' : 's'})`, changes.map((c) => `${clean(c['kind'])} ${clean(c['key'])}: ${clean(c['reason'])}`));
309
+ }
310
+ return banner('ok', `${clean(command)} result`);
311
+ }
@@ -0,0 +1,38 @@
1
+ import { button, el, when } from './dom.js';
2
+ import { banner, diagnosticsBlock, problem } from './reply.js';
3
+ import { short } from './sanitize.js';
4
+ /** Status: from `StatusResult` — release, process, lock, active and last run, hold. Refresh is manual (and once after an action). */
5
+ export function renderStatus(app) {
6
+ const reply = app.statusReply;
7
+ const status = app.status;
8
+ return el('section', { aria: { labelledby: 'status-title' } }, el('div', { class: 'row' }, el('h2', { id: 'status-title' }, 'Status'), button(app.statusBusy ? 'Refreshing…' : 'Refresh', () => { void app.refreshStatus(); }, { disabled: app.statusBusy })), !reply && !app.statusBusy ? el('p', { class: 'muted' }, 'Not loaded yet.') : null, reply && !status ? problem(reply) : null, ...(status ? statusPanels(app, status) : []), status && reply?.error ? problem(reply) : null, reply && reply.diagnostics.length > 0 && status ? diagnosticsBlock(reply.diagnostics) : null);
9
+ }
10
+ function statusPanels(app, s) {
11
+ const current = s.releases.find((r) => r.status === 'ok');
12
+ const panels = [];
13
+ panels.push(el('div', { class: 'panel' }, el('h3', {}, 'Current release'), current
14
+ ? el('p', {}, el('code', {}, short(current.sha)), ` · ${when(current.at)} · ${current.actor ?? current.user}${current.via ? ` via ${current.via}` : ''}`)
15
+ : el('p', { class: 'muted' }, 'No healthy release recorded yet.')));
16
+ const process = s.process.kind === 'pm2'
17
+ ? el('p', {}, `pm2 ${s.process.name}: `, el('strong', { class: s.process.running ? 'status-ok' : 'status-err' }, s.process.running ? 'running' : 'not running'), s.process.status ? ` (${s.process.status})` : '')
18
+ : el('pre', { class: 'diagnostics' }, s.process.lines.join('\n'));
19
+ panels.push(el('div', { class: 'panel' }, el('h3', {}, 'Process'), process));
20
+ const lock = s.lock;
21
+ panels.push(el('div', { class: 'panel' }, el('h3', {}, 'Lock'), !lock ? el('p', {}, 'Free.')
22
+ : el('p', {}, lock.corrupt ? el('strong', { class: 'status-err' }, 'Corrupt lock file. ') : null, lock.holder ? `Held by pid ${lock.holder.pid} on ${lock.holder.host} — ${lock.holder.actor}, ${lock.holder.command}, since ${when(lock.holder.startedAt)}` : '', lock.stale ? el('strong', { class: 'status-warn' }, ' (stale: that process is gone)') : null)));
23
+ if (s.activeRun) {
24
+ const run = s.activeRun;
25
+ panels.push(el('div', { class: 'panel' }, el('h3', {}, 'Active run'), el('p', {}, el('code', {}, run.runId), ` · ${run.command} by ${run.actor} since ${when(run.startedAt)} · `, run.alive ? 'alive' : el('strong', { class: 'status-warn' }, 'not seen alive')), el('div', { class: 'row' }, button('Attach', () => { app.watch(run.runId, `${run.command} ${run.runId}`); }, { class: 'primary' }))));
26
+ }
27
+ if (s.lastRun) {
28
+ const run = s.lastRun;
29
+ panels.push(el('div', { class: 'panel' }, el('h3', {}, 'Last run'), el('p', {}, el('code', {}, run.runId), ` · ${run.command || 'unknown command'} · `, run.complete ? el('strong', { class: run.exitCode === 0 ? 'status-ok' : 'status-err' }, `exit ${run.exitCode}`) : el('strong', { class: 'status-warn' }, 'did not end with done'), run.endedAt ? ` · ${when(run.endedAt)}` : ''), el('div', { class: 'row' }, button('Show its log', () => { app.watch(run.runId, `${run.command} ${run.runId}`, true); }))));
30
+ }
31
+ if (s.hold) {
32
+ panels.push(banner('warn', `Commit ${short(s.hold.sha)} is held since ${when(s.hold.at)} by ${s.hold.actor}`, [
33
+ s.hold.note,
34
+ 'A run refuses it until the branch moves on; "Deploy anyway" in Plan & deploy overrides that once.',
35
+ ]));
36
+ }
37
+ return panels;
38
+ }
@@ -0,0 +1,132 @@
1
+ import { ApiError } from './api.js';
2
+ import { confirmDialog } from './dialog.js';
3
+ import { button, el, replace } from './dom.js';
4
+ import { banner, describe, problem } from './reply.js';
5
+ const FIELDS = [
6
+ { key: 'name', label: 'Name', help: 'lowercase letters, digits and -, e.g. staging' },
7
+ { key: 'ssh', label: 'SSH destination', help: '[user@]host, or a Host alias from your ~/.ssh/config (jump hosts and keys go there)' },
8
+ { key: 'port', label: 'Port', help: 'optional; default: your ~/.ssh/config, else 22', type: 'number' },
9
+ { key: 'dir', label: 'Checkout on the server', help: 'absolute path, e.g. /srv/myapp' },
10
+ { key: 'node', label: 'node on the server', help: 'optional absolute path, when a non-interactive shell has no node on PATH' },
11
+ { key: 'config', label: 'Config file', help: 'optional, relative to the checkout (default deploy.config.ts)' },
12
+ { key: 'protected', label: 'Protected: type the name to deploy or roll back', help: '', type: 'checkbox' },
13
+ ];
14
+ /** Targets: list, add/edit/remove, check the connection. */
15
+ export function renderTargets(app) {
16
+ const root = el('section', { aria: { labelledby: 'targets-title' } });
17
+ const checkArea = el('div', { aria: { live: 'polite' } });
18
+ const formArea = el('div');
19
+ const t = app.targets;
20
+ const list = t.targets.length === 0
21
+ ? el('p', {}, 'No target yet. Add the server you already reach with ssh as the app user.')
22
+ : el('div', { class: 'table-wrap' }, el('table', {}, el('thead', {}, el('tr', {}, el('th', {}, 'Name'), el('th', {}, 'SSH'), el('th', {}, 'Checkout'), el('th', {}, ''), el('th', {}, 'Actions'))), el('tbody', {}, ...t.targets.map((target) => el('tr', {}, el('td', {}, target.name), el('td', { class: 'mono' }, `${target.ssh}${target.port ? ` -p ${target.port}` : ''}`), el('td', { class: 'mono' }, target.dir), el('td', {}, target.protected ? 'protected' : ''), el('td', {}, el('div', { class: 'row' }, button('Use', () => { app.select(target.name); app.show('status'); void app.refreshStatus(); }), button('Check connection', () => { void check(app, target, checkArea); }), button('Edit', () => replace(formArea, targetForm(app, target))), button('Remove', () => { void remove(app, target); }, { class: 'danger' }))))))));
23
+ replace(root, el('h2', { id: 'targets-title' }, 'Targets'), el('p', { class: 'muted' }, 'Stored on this machine only, in ', el('code', {}, t.path), ' (0600). They hold no secret.'), t.error ? banner('err', t.error) : null, list, checkArea, actorForm(app), button('Add a target', () => replace(formArea, targetForm(app, undefined)), { class: 'primary' }), formArea);
24
+ if (t.targets.length === 0 && !t.error)
25
+ replace(formArea, targetForm(app, undefined));
26
+ return root;
27
+ }
28
+ async function check(app, target, area) {
29
+ replace(area, el('p', { class: 'muted' }, `Connecting to ${target.ssh}…`));
30
+ let reply;
31
+ try {
32
+ reply = await app.api.post('status', { target: target.name });
33
+ }
34
+ catch (error) {
35
+ replace(area, problem(undefined, error));
36
+ return;
37
+ }
38
+ if (reply.hello?.protocol === 1 && !reply.failure) {
39
+ replace(area, banner('ok', `${target.name} answers: @basaltkit/deploy ${reply.hello.version}, protocol 1, host ${reply.hello.host}`));
40
+ if (app.current?.name === target.name) {
41
+ app.statusReply = reply;
42
+ app.hello = reply.hello;
43
+ app.renderBar();
44
+ }
45
+ return;
46
+ }
47
+ replace(area, problem(reply));
48
+ }
49
+ async function remove(app, target) {
50
+ const ok = await confirmDialog({ title: `Remove ${target.name}?`, lines: ['Only this UI forgets it; nothing changes on the server.'], confirmLabel: 'Remove', danger: true });
51
+ if (!ok)
52
+ return;
53
+ try {
54
+ app.targets = await app.api.post('targets/remove', { name: target.name });
55
+ await app.loadTargets();
56
+ }
57
+ catch (error) {
58
+ app.shell.main.prepend(problem(undefined, error));
59
+ return;
60
+ }
61
+ app.show('targets');
62
+ }
63
+ function actorForm(app) {
64
+ const input = el('input', { type: 'text', id: 'actor', value: app.targets.actor ?? '', autocomplete: 'off', spellcheck: false, aria: { describedby: 'actor-help' } });
65
+ const message = el('span', { id: 'actor-help', class: 'muted' }, 'Recorded with each release as --actor (letters, digits and ._@+-).');
66
+ const form = el('form', { class: 'panel', on: { submit: (event) => {
67
+ event.preventDefault();
68
+ void app.api.post('targets/save', { actor: input.value.trim() === '' ? null : input.value.trim() })
69
+ .then((reply) => { app.targets = reply; replace(message, 'Saved.'); })
70
+ .catch((error) => { replace(message, el('span', { class: 'field-error' }, describe(error))); });
71
+ } } }, el('div', { class: 'field' }, el('label', { for: 'actor' }, 'Your name in the audit (actor)'), input, message), el('button', { type: 'submit' }, 'Save actor'));
72
+ return form;
73
+ }
74
+ function targetForm(app, existing) {
75
+ const inputs = new Map();
76
+ const errors = new Map();
77
+ const general = el('div', { aria: { live: 'polite' } });
78
+ const fields = FIELDS.map((field) => {
79
+ const id = `target-${field.key}`;
80
+ const value = existing?.[field.key];
81
+ const error = el('span', { id: `${id}-error`, class: 'field-error' });
82
+ errors.set(field.key, error);
83
+ const input = field.type === 'checkbox'
84
+ ? el('input', { type: 'checkbox', id, checked: value === true, aria: { describedby: `${id}-error` } })
85
+ : el('input', { type: field.type === 'number' ? 'number' : 'text', id, value: value === undefined ? '' : String(value), autocomplete: 'off', spellcheck: false, required: field.key === 'name' || field.key === 'ssh' || field.key === 'dir', aria: { describedby: `${id}-help ${id}-error` } });
86
+ inputs.set(field.key, input);
87
+ return el('div', { class: 'field' }, el('label', { for: id }, field.label, field.key === 'name' || field.key === 'ssh' || field.key === 'dir' ? el('span', { class: 'required' }, ' *') : null), input, field.help ? el('span', { id: `${id}-help`, class: 'muted' }, field.help) : null, error);
88
+ });
89
+ const submit = async (event) => {
90
+ event.preventDefault();
91
+ for (const error of errors.values())
92
+ replace(error);
93
+ replace(general);
94
+ const target = {};
95
+ for (const field of FIELDS) {
96
+ const input = inputs.get(field.key);
97
+ if (field.type === 'checkbox') {
98
+ if (input.checked)
99
+ target[field.key] = true;
100
+ continue;
101
+ }
102
+ const value = input.value.trim();
103
+ if (value === '')
104
+ continue;
105
+ target[field.key] = field.type === 'number' ? Number(value) : value;
106
+ }
107
+ try {
108
+ app.targets = await app.api.post('targets/save', { target, ...(existing ? { previousName: existing.name } : {}) });
109
+ await app.loadTargets();
110
+ if (!app.current)
111
+ app.select(String(target['name']));
112
+ app.show('targets');
113
+ }
114
+ catch (error) {
115
+ const fieldErrors = error instanceof ApiError ? error.body['errors'] : undefined;
116
+ if (fieldErrors) {
117
+ for (const [key, message] of Object.entries(fieldErrors)) {
118
+ const slot = errors.get(key);
119
+ if (slot)
120
+ replace(slot, message);
121
+ else
122
+ general.append(el('p', { class: 'field-error' }, `${key}: ${message}`));
123
+ }
124
+ ;
125
+ (inputs.get(Object.keys(fieldErrors)[0]) ?? inputs.get('name'))?.focus();
126
+ }
127
+ else
128
+ replace(general, problem(undefined, error));
129
+ }
130
+ };
131
+ return el('form', { class: 'panel', aria: { label: existing ? `Edit ${existing.name}` : 'Add a target' }, on: { submit: (event) => { void submit(event); } } }, el('h3', {}, existing ? `Edit ${existing.name}` : 'Add a target'), ...fields, general, el('div', { class: 'row' }, el('button', { type: 'submit', class: 'primary' }, 'Save'), button('Cancel', () => app.show('targets'))));
132
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @basaltkit/deploy-ui — a local UI for @basaltkit/deploy (RFC 0009). The
3
+ * package is a program (`basalt-deploy-ui`); these exports are its building
4
+ * blocks, for tests and for a wrapper that starts it differently.
5
+ */
6
+ export { main, parseFlags, USAGE, type CliDeps, type CliFlags } from './cli.js';
7
+ export { startUiServer, MAX_SSH_SESSIONS, type UiServer, type UiServerOptions } from './server.js';
8
+ export { checkRequest, SECURITY_HEADERS, type Verdict } from './security.js';
9
+ export { IdleTimer, Session, LAUNCH_TTL_MS } from './session.js';
10
+ export { checkTarget, checkTargetsFile, defaultTargetsPath, readTargets, writeTargets, TargetsFileError, type Target, type TargetsFile } from './targets.js';
11
+ export { classifySshFailure, DEPLOY_BIN, remoteCommand, shQuote, sshArgs, sshProgram, SSH_OPTIONS, type RemoteSpec } from './ssh.js';
12
+ export { ProtocolReader, sanitizeText, MAX_LINE_BYTES } from './stream.js';
13
+ export { execRemote, follow, type SshRunner } from './remote.js';
14
+ export { openerCommand } from './open.js';
15
+ export type { CommandReply, StreamMessage, TargetsReply } from './client/messages.js';