@eserstack/noskills-web 0.0.0-stage → 5.0.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.
Files changed (41) hide show
  1. package/LICENSE +13 -0
  2. package/README.md +247 -2
  3. package/dist/auth.d.ts +50 -0
  4. package/dist/auth.js +107 -0
  5. package/dist/mod.d.ts +13 -0
  6. package/dist/mod.js +11 -0
  7. package/dist/request-context.d.ts +35 -0
  8. package/dist/request-context.js +19 -0
  9. package/dist/routes/api.d.ts +45 -0
  10. package/dist/routes/api.js +167 -0
  11. package/dist/routes/pages.d.ts +20 -0
  12. package/dist/routes/pages.js +80 -0
  13. package/dist/routes/sse.d.ts +15 -0
  14. package/dist/routes/sse.js +61 -0
  15. package/dist/routes/static.d.ts +10 -0
  16. package/dist/routes/static.js +52 -0
  17. package/dist/server.d.ts +53 -0
  18. package/dist/server.js +228 -0
  19. package/dist/static/client.js +257 -0
  20. package/dist/static/icons/icon.svg +12 -0
  21. package/dist/static/manifest.json +17 -0
  22. package/dist/static/mux-remote.js +192 -0
  23. package/dist/static/mux-render.js +224 -0
  24. package/dist/static/style.css +391 -0
  25. package/dist/static/sw-register.js +31 -0
  26. package/dist/static/sw.js +109 -0
  27. package/dist/templates/components.d.ts +17 -0
  28. package/dist/templates/components.js +89 -0
  29. package/dist/templates/dashboard.d.ts +8 -0
  30. package/dist/templates/dashboard.js +28 -0
  31. package/dist/templates/escape.d.ts +8 -0
  32. package/dist/templates/escape.js +14 -0
  33. package/dist/templates/layout.d.ts +12 -0
  34. package/dist/templates/layout.js +83 -0
  35. package/dist/templates/spec-detail.d.ts +7 -0
  36. package/dist/templates/spec-detail.js +83 -0
  37. package/dist/terminal/mux-host.d.ts +65 -0
  38. package/dist/terminal/mux-host.js +166 -0
  39. package/dist/terminal/ws-bridge.d.ts +9 -0
  40. package/dist/terminal/ws-bridge.js +26 -0
  41. package/package.json +32 -3
@@ -0,0 +1,192 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ // noskills — remote mux client over WebTransport (vanilla, no build step).
3
+ //
4
+ // The counterpart to client.js: instead of a local /mux WebSocket it attaches to
5
+ // a headless noskills-server over HTTP/3 + WebTransport and renders the same mux
6
+ // scene via the shared renderer (mux-render.js). The daemon wraps every mux
7
+ // server→frontend frame as {type:"mux", v, frame, seq}; this unwraps it and
8
+ // wraps outbound frames as {type:"mux", frame}. Tab management uses mux actions
9
+ // (the daemon has no REST tab endpoints).
10
+ //
11
+ // BEST-EFFORT / UNVERIFIED: needs a real noskills-server + a host HTML page that
12
+ // serves xterm + mux-render.js + this file and calls startRemoteMux(...). The
13
+ // daemon wire protocol mirrors @eserstack/noskills-client/attach.ts.
14
+ //
15
+ // Usage from a host page:
16
+ // startRemoteMux({
17
+ // baseUrl: "https://host:4433", slug, sid,
18
+ // certHashes: [ArrayBuffer], // self-signed pinning (optional)
19
+ // token: "<bearer>", // PIN-login token (optional)
20
+ // root: document.getElementById("terminal-container"),
21
+ // tabBar: document.querySelector(".tab-bar"),
22
+ // });
23
+
24
+ (() => {
25
+ "use strict";
26
+
27
+ function startRemoteMux(cfg) {
28
+ // Browser globals come from globalThis; a page can lack WebTransport or
29
+ // MuxRender, which the checks below report.
30
+ const { document, MuxRender, WebTransport } = globalThis;
31
+ if (WebTransport === undefined) {
32
+ throw new Error("WebTransport is not supported in this browser");
33
+ }
34
+ if (MuxRender === undefined) {
35
+ throw new Error("mux-render.js must load first");
36
+ }
37
+
38
+ const root = cfg.root;
39
+ const cell = MuxRender.measureCell(
40
+ MuxRender.FONT_FAMILY,
41
+ MuxRender.FONT_SIZE_PX,
42
+ );
43
+
44
+ let lastSeq = 0;
45
+ let writer = null;
46
+ let closed = false;
47
+ let wt = null;
48
+
49
+ // The renderer emits FrontendToServer frames; wrap each as a mux command.
50
+ const send = (frame) => {
51
+ if (writer === null) return;
52
+ writer
53
+ .write(
54
+ new TextEncoder().encode(
55
+ JSON.stringify({ type: "mux", frame }) + "\n",
56
+ ),
57
+ )
58
+ .catch(() => {});
59
+ };
60
+
61
+ const renderer = MuxRender.createRenderer({
62
+ root,
63
+ cell,
64
+ send,
65
+ tabBar: cfg.tabBar,
66
+ });
67
+
68
+ // ── Tab management via mux actions (no REST on the daemon) ──────────────
69
+ document.addEventListener("click", (e) => {
70
+ const t = e.target;
71
+ // Each tab is a select button and a close button side by side (see
72
+ // mux-render.js); Enter and Space on a button arrive as a click.
73
+ const closeButton = t.closest(".tab-close");
74
+ const tabButton = t.closest(".tab-select");
75
+ if (closeButton !== null && closeButton.dataset.close !== undefined) {
76
+ const scene = renderer.getScene();
77
+ const idx =
78
+ scene !== null && Array.isArray(scene.tabs)
79
+ ? scene.tabs.findIndex(
80
+ (tab) => tab.id === closeButton.dataset.close,
81
+ )
82
+ : -1;
83
+ if (idx !== -1) {
84
+ send({ t: "action", action: { type: "closeTab", index: idx } });
85
+ }
86
+ } else if (tabButton !== null && tabButton.dataset.index !== undefined) {
87
+ send({
88
+ t: "action",
89
+ action: { type: "gotoTab", index: Number(tabButton.dataset.index) },
90
+ });
91
+ } else if (t.closest("#add-tab") !== null) {
92
+ send({ t: "action", action: { type: "newTab" } });
93
+ }
94
+ });
95
+
96
+ let resizeTimer = null;
97
+ globalThis.addEventListener("resize", () => {
98
+ if (resizeTimer !== null) clearTimeout(resizeTimer);
99
+ resizeTimer = setTimeout(() => {
100
+ resizeTimer = null;
101
+ send({ t: "resize", viewport: renderer.viewport() });
102
+ }, 150);
103
+ });
104
+
105
+ // ── Connect (with auto-reconnect that resumes from lastSeq) ──────────────
106
+ const wtOpts = {};
107
+ if (Array.isArray(cfg.certHashes) && cfg.certHashes.length > 0) {
108
+ wtOpts.serverCertificateHashes = cfg.certHashes.map((value) => ({
109
+ algorithm: "sha-256",
110
+ value,
111
+ }));
112
+ }
113
+
114
+ async function connect() {
115
+ if (closed) return;
116
+
117
+ // Build the URL per-attempt so a reconnect resumes from the last seq seen.
118
+ const q = new URLSearchParams({ kind: "mux" });
119
+ if (lastSeq > 0) q.set("after", String(lastSeq));
120
+ if (typeof cfg.token === "string" && cfg.token !== "") {
121
+ q.set("token", cfg.token);
122
+ }
123
+ const url = `${cfg.baseUrl}/attach/${encodeURIComponent(cfg.slug)}/${encodeURIComponent(
124
+ cfg.sid,
125
+ )}?${q.toString()}`;
126
+
127
+ try {
128
+ wt = new WebTransport(url, wtOpts);
129
+ await wt.ready;
130
+
131
+ const stream = await wt.createBidirectionalStream();
132
+ writer = stream.writable.getWriter();
133
+
134
+ // Attach so the server lays panes out for our viewport.
135
+ send({ t: "attach", viewport: renderer.viewport() });
136
+
137
+ const reader = stream.readable.getReader();
138
+ const decoder = new TextDecoder();
139
+ let buf = "";
140
+
141
+ for (;;) {
142
+ // A stream reader yields chunks in order, one read at a time.
143
+ // oxlint-disable-next-line no-await-in-loop
144
+ const { value, done } = await reader.read();
145
+ if (done) break;
146
+ buf += decoder.decode(value, { stream: true });
147
+
148
+ const lines = buf.split("\n");
149
+ buf = lines.pop() ?? "";
150
+ for (const line of lines) {
151
+ const trimmed = line.trim();
152
+ if (trimmed === "") continue;
153
+
154
+ let evt;
155
+ try {
156
+ evt = JSON.parse(trimmed);
157
+ } catch {
158
+ continue;
159
+ }
160
+ if (typeof evt.seq === "number") lastSeq = evt.seq;
161
+ if (evt.type === "mux" && evt.frame instanceof Object) {
162
+ renderer.applyFrame(evt.frame);
163
+ }
164
+ }
165
+ }
166
+ } catch {
167
+ // connection failed / dropped → fall through to reconnect
168
+ }
169
+
170
+ writer = null;
171
+ if (!closed) setTimeout(connect, 1000);
172
+ }
173
+
174
+ void connect();
175
+
176
+ return {
177
+ close() {
178
+ closed = true;
179
+ try {
180
+ wt?.close();
181
+ } catch {
182
+ // already closing
183
+ }
184
+ },
185
+ get lastSeq() {
186
+ return lastSeq;
187
+ },
188
+ };
189
+ }
190
+
191
+ globalThis.startRemoteMux = startRemoteMux;
192
+ })();
@@ -0,0 +1,224 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ // Transport-agnostic mux browser renderer.
3
+ //
4
+ // Shared by the local WebSocket client (client.js) and the remote WebTransport
5
+ // client (mux-remote.js): both feed it neutral mux server→frontend frames
6
+ // (`scene` / `output`) and let it emit frontend→server frames (`action` /
7
+ // `resize`) through a caller-supplied `send`. It knows nothing about the
8
+ // transport, so the exact same rendering drives a local socket or a remote
9
+ // HTTP/3 daemon. Plain browser globals (no build step): exposes `globalThis.MuxRender`.
10
+
11
+ (() => {
12
+ "use strict";
13
+
14
+ // Browser globals come from globalThis, where browser-scripts.test.ts puts
15
+ // its stand-in for the DOM. xterm's Terminal and WebLinksAddon are
16
+ // read when a pane is created, since a page without a terminal has neither.
17
+ const { document } = globalThis;
18
+
19
+ // The terminal font. Callers measure the cell with the same values, so the
20
+ // grid they report matches what xterm draws.
21
+ const FONT_FAMILY = "'SF Mono', 'Cascadia Code', 'Fira Code', monospace";
22
+ const FONT_SIZE_PX = 13;
23
+
24
+ function measureCell(fontFamily, fontSize) {
25
+ const span = document.createElement("span");
26
+ span.style.cssText = `position:absolute;visibility:hidden;white-space:pre;font-family:${fontFamily};font-size:${fontSize}px;line-height:normal;`;
27
+ span.textContent = "W".repeat(50);
28
+ document.body.appendChild(span);
29
+ const rect = span.getBoundingClientRect();
30
+ document.body.removeChild(span);
31
+ return { w: Math.max(1, rect.width / 50), h: Math.max(1, rect.height) };
32
+ }
33
+
34
+ const esc = (s) =>
35
+ String(s)
36
+ .replace(/&/g, "&amp;")
37
+ .replace(/</g, "&lt;")
38
+ .replace(/>/g, "&gt;")
39
+ .replace(/"/g, "&quot;");
40
+
41
+ /**
42
+ * @param {object} opts
43
+ * root: container element panes are positioned within (position:relative)
44
+ * cell: { w, h } pixel size of one character cell
45
+ * send: (frame) => void; sends a FrontendToServer frame ({t:"action"|...})
46
+ * tabBar: optional element to render the tab list into
47
+ * fontFamily, fontSize: xterm font (default FONT_FAMILY, FONT_SIZE_PX)
48
+ */
49
+ function createRenderer(opts) {
50
+ const { root, cell, send } = opts;
51
+ const fontFamily = opts.fontFamily ?? FONT_FAMILY;
52
+ const fontSize = opts.fontSize ?? FONT_SIZE_PX;
53
+
54
+ let scene = null;
55
+ const panes = new Map(); // paneId → { term, el }
56
+ const pending = new Map(); // paneId → string[] (output before pane exists)
57
+
58
+ const sendAction = (action) => send({ t: "action", action });
59
+
60
+ function viewport() {
61
+ return {
62
+ cols: Math.max(20, Math.floor(root.clientWidth / cell.w)),
63
+ rows: Math.max(6, Math.floor(root.clientHeight / cell.h)),
64
+ };
65
+ }
66
+
67
+ function ensurePane(id) {
68
+ let entry = panes.get(id);
69
+ if (entry !== undefined) return entry;
70
+
71
+ const el = document.createElement("div");
72
+ el.className = "mux-pane";
73
+ el.style.position = "absolute";
74
+ el.dataset.pane = id;
75
+ el.addEventListener("mousedown", () => {
76
+ if (scene !== null && scene.focusedPane !== id) {
77
+ sendAction({ type: "focusPane", pane: id });
78
+ }
79
+ });
80
+
81
+ const term = new globalThis.Terminal({
82
+ fontFamily,
83
+ fontSize,
84
+ theme: {
85
+ background: "#000000",
86
+ foreground: "#e6edf3",
87
+ cursor: "#58a6ff",
88
+ selectionBackground: "#264f78",
89
+ },
90
+ allowProposedApi: true,
91
+ scrollback: 5000,
92
+ });
93
+ const { WebLinksAddon } = globalThis;
94
+ if (WebLinksAddon !== undefined) {
95
+ term.loadAddon(new WebLinksAddon.WebLinksAddon());
96
+ }
97
+ term.open(el);
98
+ term.onData((data) => {
99
+ if (scene !== null && scene.focusedPane !== id) {
100
+ sendAction({ type: "focusPane", pane: id });
101
+ }
102
+ sendAction({ type: "writeInput", data });
103
+ });
104
+
105
+ root.appendChild(el);
106
+ entry = { term, el };
107
+ panes.set(id, entry);
108
+
109
+ const buf = pending.get(id);
110
+ if (buf !== undefined) {
111
+ for (const chunk of buf) term.write(chunk);
112
+ pending.delete(id);
113
+ }
114
+ return entry;
115
+ }
116
+
117
+ function renderTabBar() {
118
+ const bar = opts.tabBar;
119
+ if (
120
+ bar === undefined ||
121
+ bar === null ||
122
+ scene === null ||
123
+ !Array.isArray(scene.tabs)
124
+ ) {
125
+ return;
126
+ }
127
+
128
+ // Two sibling buttons per tab, so each takes keyboard focus; a button
129
+ // inside a button is invalid HTML and cannot.
130
+ const items = scene.tabs
131
+ .map((t, i) => {
132
+ const active = i === scene.activeTab ? " active" : "";
133
+ const name = esc(t.name);
134
+ return `<div class="tab${active}" data-tab="${esc(
135
+ t.id,
136
+ )}"><button type="button" class="tab-select" data-index="${i}">${name}</button><button type="button" class="tab-close" data-close="${esc(
137
+ t.id,
138
+ )}" aria-label="Close ${name}">&times;</button></div>`;
139
+ })
140
+ .join("");
141
+ bar.innerHTML = `${items}<button type="button" class="tab-add" id="add-tab" aria-label="New tab">+</button>`;
142
+ }
143
+
144
+ function renderPanes() {
145
+ if (scene === null || !Array.isArray(scene.panes)) return;
146
+ const visible = new Set();
147
+
148
+ for (const p of scene.panes) {
149
+ visible.add(p.id);
150
+ const { term, el } = ensurePane(p.id);
151
+ const wasHidden = el.style.display === "none";
152
+ const g = p.geom;
153
+
154
+ // The server sizes each pane's PTY to (width-2)×(height-2) — the 1-cell
155
+ // frame the TUI draws as a box border. Mirror that here.
156
+ const cols = Math.max(1, g.width - 2);
157
+ const rows = Math.max(1, g.height - 2);
158
+
159
+ el.style.left = `${g.x * cell.w}px`;
160
+ el.style.top = `${g.y * cell.h}px`;
161
+ el.style.width = `${g.width * cell.w}px`;
162
+ el.style.height = `${g.height * cell.h}px`;
163
+ el.style.padding = `${cell.h / 2}px ${cell.w}px`;
164
+ el.style.boxSizing = "border-box";
165
+ el.classList.toggle("focused", p.focused);
166
+ el.classList.toggle("exited", p.exited);
167
+ el.style.display = "block";
168
+
169
+ if (term.cols !== cols || term.rows !== rows) term.resize(cols, rows);
170
+ if (wasHidden) term.refresh(0, term.rows - 1);
171
+ if (p.focused) term.focus();
172
+ }
173
+
174
+ for (const [id, entry] of panes) {
175
+ if (!visible.has(id)) entry.el.style.display = "none";
176
+ }
177
+ }
178
+
179
+ function applyDelta(delta) {
180
+ scene = scene === null ? {} : scene;
181
+ for (const key of Object.keys(delta)) scene[key] = delta[key];
182
+ if (delta.tabs !== undefined || delta.activeTab !== undefined) {
183
+ renderTabBar();
184
+ }
185
+ if (
186
+ delta.panes !== undefined ||
187
+ delta.focusedPane !== undefined ||
188
+ delta.viewport !== undefined
189
+ ) {
190
+ renderPanes();
191
+ }
192
+ }
193
+
194
+ function writeOutput(id, data) {
195
+ const entry = panes.get(id);
196
+ if (entry !== undefined) {
197
+ entry.term.write(data);
198
+ return;
199
+ }
200
+ const buf = pending.get(id);
201
+ if (buf === undefined) pending.set(id, [data]);
202
+ else buf.push(data);
203
+ }
204
+
205
+ function applyFrame(frame) {
206
+ if (frame.t === "scene") applyDelta(frame.delta);
207
+ else if (frame.t === "output") writeOutput(frame.pane, frame.data);
208
+ // frame.t === "exit" → caller decides (transport teardown)
209
+ }
210
+
211
+ return {
212
+ applyFrame,
213
+ viewport,
214
+ getScene: () => scene,
215
+ };
216
+ }
217
+
218
+ globalThis.MuxRender = {
219
+ FONT_FAMILY,
220
+ FONT_SIZE_PX,
221
+ measureCell,
222
+ createRenderer,
223
+ };
224
+ })();