@tsplc/agent 0.5.9 → 0.5.12

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 (51) hide show
  1. package/dist/cli.js +2660 -525
  2. package/dist/cli.js.map +32 -18
  3. package/dist/client.js +262 -37
  4. package/dist/client.js.map +4 -4
  5. package/dist/index.js +2325 -415
  6. package/dist/index.js.map +27 -14
  7. package/package.json +6 -5
  8. package/src/access.ts +276 -0
  9. package/src/agent.ts +130 -29
  10. package/src/audit.ts +64 -0
  11. package/src/cli.ts +81 -5
  12. package/src/client.ts +204 -36
  13. package/src/controller.ts +60 -0
  14. package/src/dashboard/index.ts +118 -0
  15. package/src/dashboard/ui/access.ts +192 -0
  16. package/src/dashboard/ui/actions.ts +192 -0
  17. package/src/dashboard/ui/api.ts +158 -0
  18. package/src/dashboard/ui/app.ts +41 -0
  19. package/src/dashboard/ui/approval.ts +132 -0
  20. package/src/dashboard/ui/audit.ts +115 -0
  21. package/src/dashboard/ui/contract.ts +19 -0
  22. package/src/dashboard/ui/dashboard.css +1332 -0
  23. package/src/dashboard/ui/deployment.ts +432 -0
  24. package/src/dashboard/ui/deployments.ts +317 -0
  25. package/src/dashboard/ui/details.ts +240 -0
  26. package/src/dashboard/ui/dom.ts +91 -0
  27. package/src/dashboard/ui/environment.ts +326 -0
  28. package/src/dashboard/ui/format.ts +118 -0
  29. package/src/dashboard/ui/logs.ts +127 -0
  30. package/src/dashboard/ui/main.ts +86 -0
  31. package/src/dashboard/ui/overlay.ts +146 -0
  32. package/src/dashboard/ui/shell.ts +192 -0
  33. package/src/dashboard/ui/source.ts +144 -0
  34. package/src/deploy.ts +174 -144
  35. package/src/deployments/health.ts +80 -0
  36. package/src/deployments/retention.ts +45 -0
  37. package/src/deployments/routes.ts +273 -0
  38. package/src/deployments/runner.ts +877 -0
  39. package/src/deployments/store.ts +233 -0
  40. package/src/environment.ts +284 -0
  41. package/src/index.ts +4 -0
  42. package/src/login.ts +17 -0
  43. package/src/operations.ts +6 -1
  44. package/src/protocol.ts +259 -2
  45. package/src/releases.ts +73 -1
  46. package/src/routes.ts +52 -0
  47. package/src/secrets.ts +74 -4
  48. package/src/server-process.ts +33 -16
  49. package/src/sessions.ts +58 -0
  50. package/src/state.ts +2 -0
  51. package/src/tailscale.ts +112 -0
@@ -0,0 +1,146 @@
1
+ import { type Child, h, icon, icons } from "./dom";
2
+
3
+ /** A menu item: an action, or a link to follow. */
4
+ export type MenuItem =
5
+ | {
6
+ label: string;
7
+ run: () => void;
8
+ tone?: "danger";
9
+ disabled?: boolean;
10
+ }
11
+ | "separator";
12
+
13
+ let closeOpenMenu: (() => void) | null = null;
14
+
15
+ /** Whether a menu or dialog is open, so a refresh doesn't pull the rows out from under it. */
16
+ export const overlayOpen = () =>
17
+ closeOpenMenu !== null || document.querySelector("dialog[open]") !== null;
18
+
19
+ const openMenu = (anchor: HTMLElement, items: MenuItem[]) => {
20
+ closeOpenMenu?.();
21
+ const menu = h(
22
+ "div",
23
+ { class: "menu", role: "menu" },
24
+ ...items.map((item) =>
25
+ item === "separator"
26
+ ? h("div", { class: "menu-separator" })
27
+ : h(
28
+ "button",
29
+ {
30
+ class: `menu-item${item.tone ? ` ${item.tone}` : ""}`,
31
+ role: "menuitem",
32
+ disabled: item.disabled,
33
+ onclick: (event) => {
34
+ event.stopPropagation();
35
+ close();
36
+ item.run();
37
+ },
38
+ },
39
+ item.label,
40
+ ),
41
+ ),
42
+ );
43
+ const outside = (event: Event) => {
44
+ if (event.target instanceof Node && !menu.contains(event.target)) {
45
+ close();
46
+ }
47
+ };
48
+ const onKey = (event: KeyboardEvent) => {
49
+ if (event.key === "Escape") {
50
+ close();
51
+ }
52
+ };
53
+ const close = () => {
54
+ menu.remove();
55
+ document.removeEventListener("click", outside, true);
56
+ document.removeEventListener("keydown", onKey);
57
+ closeOpenMenu = null;
58
+ };
59
+ document.body.append(menu);
60
+ const box = anchor.getBoundingClientRect();
61
+ menu.style.top = `${box.bottom + window.scrollY + 4}px`;
62
+ menu.style.left = `${Math.max(8, box.right + window.scrollX - menu.offsetWidth)}px`;
63
+ document.addEventListener("click", outside, true);
64
+ document.addEventListener("keydown", onKey);
65
+ closeOpenMenu = close;
66
+ menu.querySelector<HTMLButtonElement>("button:not([disabled])")?.focus();
67
+ };
68
+
69
+ /** The "…" button that opens a row's menu. */
70
+ export const menuButton = (label: string, items: () => MenuItem[]) =>
71
+ h(
72
+ "button",
73
+ {
74
+ class: "icon-button",
75
+ title: label,
76
+ "aria-label": label,
77
+ "aria-haspopup": "menu",
78
+ onclick: (event) => {
79
+ event.stopPropagation();
80
+ if (event.currentTarget instanceof HTMLElement) {
81
+ openMenu(event.currentTarget, items());
82
+ }
83
+ },
84
+ },
85
+ icon(icons.more),
86
+ );
87
+
88
+ /**
89
+ * A modal dialog. `actions` builds its buttons, given `close`; it resolves with what `close` was
90
+ * given, or null when dismissed.
91
+ */
92
+ export const dialog = <T>(options: {
93
+ title: string;
94
+ body: Child[];
95
+ actions: (close: (value: T) => void) => Child[];
96
+ }) =>
97
+ new Promise<T | null>((resolve) => {
98
+ const element = h("dialog", { class: "dialog" });
99
+ let result: T | null = null;
100
+ const close = (value: T) => {
101
+ result = value;
102
+ element.close();
103
+ };
104
+ element.addEventListener("close", () => {
105
+ element.remove();
106
+ resolve(result);
107
+ });
108
+ element.append(
109
+ h("h2", {}, options.title),
110
+ h("div", { class: "dialog-body" }, ...options.body),
111
+ h("div", { class: "dialog-actions" }, ...options.actions(close)),
112
+ );
113
+ document.body.append(element);
114
+ element.showModal();
115
+ });
116
+
117
+ /** Asks to confirm an action: resolves true once confirmed. */
118
+ export const confirm = async (options: {
119
+ title: string;
120
+ body: Child[];
121
+ confirm: string;
122
+ tone: "primary" | "danger";
123
+ }) =>
124
+ (await dialog<boolean>({
125
+ title: options.title,
126
+ body: options.body,
127
+ actions: (close) => [
128
+ h("button", { class: "button", onclick: () => close(false) }, "Cancel"),
129
+ h(
130
+ "button",
131
+ { class: `button ${options.tone}`, onclick: () => close(true) },
132
+ options.confirm,
133
+ ),
134
+ ],
135
+ })) === true;
136
+
137
+ const toasts = () =>
138
+ document.querySelector(".toasts") ??
139
+ document.body.appendChild(h("div", { class: "toasts", role: "status" }));
140
+
141
+ /** A short notice in the corner, gone after a few seconds. */
142
+ export const toast = (message: string, tone: "ok" | "error") => {
143
+ const element = h("div", { class: `toast t-${tone}` }, message);
144
+ toasts().append(element);
145
+ setTimeout(() => element.remove(), tone === "error" ? 8000 : 4000);
146
+ };
@@ -0,0 +1,192 @@
1
+ import { errorMessage } from "../../errors";
2
+ import type { Identity } from "../../protocol";
3
+ import { restartController } from "./actions";
4
+ import { agentVersion, api } from "./api";
5
+ import { type App, attempt } from "./app";
6
+ import { badge, fill, h, icon, icons } from "./dom";
7
+
8
+ /** The top-level pages, by the path that opens them; the debugger is its own app under `/debug/`. */
9
+ const sections = [
10
+ { path: "/deployments", label: "Deployments", role: "viewer" },
11
+ { path: "/environment", label: "Environment", role: "viewer" },
12
+ { path: "/audit", label: "Audit", role: "viewer" },
13
+ { path: "/access", label: "Access", role: "admin" },
14
+ ] as const;
15
+
16
+ const themeKey = "tsplc-theme";
17
+
18
+ /** Light, dark, or the system's, cycled by the header's button and kept in local storage. */
19
+ const themeButton = () => {
20
+ const button = h("button", { class: "icon-button", title: "Theme" });
21
+ const render = () => {
22
+ const theme = document.documentElement.dataset.theme ?? "";
23
+ fill(button, icon(theme === "light" ? icons.sun : icons.moon));
24
+ button.title = `Theme: ${theme || "system"}`;
25
+ };
26
+ button.addEventListener("click", () => {
27
+ const order = ["", "dark", "light"];
28
+ const theme = document.documentElement.dataset.theme ?? "";
29
+ const next = order[(order.indexOf(theme) + 1) % order.length] ?? "";
30
+ document.documentElement.dataset.theme = next;
31
+ localStorage.setItem(themeKey, next);
32
+ render();
33
+ });
34
+ render();
35
+ return button;
36
+ };
37
+
38
+ /** Resets the application and starts it again, from any page; busy until the controller answers. */
39
+ const restartButton = () => {
40
+ const button = h(
41
+ "button",
42
+ {
43
+ class: "button small",
44
+ title: "Reset the application warm or cold, then start it",
45
+ },
46
+ "Reset and start",
47
+ );
48
+ button.addEventListener("click", () => {
49
+ void restartController((busy) => {
50
+ button.disabled = busy;
51
+ button.textContent = busy ? "Restarting…" : "Reset and start";
52
+ });
53
+ });
54
+ return button;
55
+ };
56
+
57
+ /** Whether the identity signed in with a cookie, which signing out clears; Tailscale and the agent's PC can't sign out. */
58
+ const signedInByToken = (identity: Identity) => identity.via === "token";
59
+
60
+ /** The header: the agent and controller, who is signed in, and the pages. */
61
+ export const shell = (app: App) => {
62
+ const where = h("span", { class: "muted mono" });
63
+ const version = h("span", { class: "muted mono version" });
64
+ const nav = h("nav", { class: "nav" });
65
+ void api.status().then(
66
+ (status) => {
67
+ where.textContent = status.target
68
+ ? `${status.target.host}:${status.target.port}`
69
+ : "No controller selected";
70
+ version.textContent = agentVersion() ? `tsPLC ${agentVersion()}` : "";
71
+ },
72
+ () => {
73
+ version.textContent = agentVersion() ? `tsPLC ${agentVersion()}` : "";
74
+ },
75
+ );
76
+
77
+ const setActive = (pathname: string) => {
78
+ const active = pathname === "/" ? "/deployments" : pathname;
79
+ fill(
80
+ nav,
81
+ ...sections
82
+ .filter((section) => app.can(section.role))
83
+ .map((section) =>
84
+ h(
85
+ "a",
86
+ {
87
+ class: `nav-link${active === section.path || active.startsWith(`${section.path}/`) ? " on" : ""}`,
88
+ href: section.path,
89
+ onclick: (event) => {
90
+ event.preventDefault();
91
+ app.navigate(section.path);
92
+ },
93
+ },
94
+ section.label,
95
+ ),
96
+ ),
97
+ h("a", { class: "nav-link", href: "/debug/" }, "Debugger"),
98
+ );
99
+ };
100
+
101
+ const element = h(
102
+ "header",
103
+ { class: "topbar" },
104
+ h(
105
+ "div",
106
+ { class: "topbar-row" },
107
+ h(
108
+ "a",
109
+ {
110
+ class: "brand",
111
+ href: "/deployments",
112
+ onclick: (event) => {
113
+ event.preventDefault();
114
+ app.navigate("/deployments");
115
+ },
116
+ },
117
+ h("span", { class: "logo", "aria-hidden": "true" }),
118
+ h("b", {}, "tsPLC"),
119
+ h("span", { class: "muted" }, "plant agent"),
120
+ ),
121
+ h("span", { class: "slash" }, "/"),
122
+ where,
123
+ app.can("deployer") ? restartButton() : null,
124
+ h(
125
+ "div",
126
+ { class: "topbar-end" },
127
+ version,
128
+ themeButton(),
129
+ h(
130
+ "span",
131
+ { class: "who", title: app.identity.login ?? app.identity.name },
132
+ app.identity.name,
133
+ badge(app.identity.role, "neutral"),
134
+ ),
135
+ signedInByToken(app.identity)
136
+ ? h(
137
+ "button",
138
+ {
139
+ class: "button small",
140
+ onclick: () =>
141
+ void attempt(() => api.signOut(), null).then(() =>
142
+ location.reload(),
143
+ ),
144
+ },
145
+ "Sign out",
146
+ )
147
+ : null,
148
+ ),
149
+ ),
150
+ nav,
151
+ );
152
+ return { element, setActive };
153
+ };
154
+
155
+ /** Asks for the agent's token, which signs this browser in with a cookie. */
156
+ export const signInForm = (onSignedIn: () => void) => {
157
+ const token = h("input", {
158
+ class: "input mono",
159
+ type: "password",
160
+ autocomplete: "current-password",
161
+ placeholder: "Agent token",
162
+ required: true,
163
+ });
164
+ const error = h("p", { class: "error-text" });
165
+ return h(
166
+ "div",
167
+ { class: "sign-in" },
168
+ h(
169
+ "form",
170
+ {
171
+ class: "card",
172
+ onsubmit: (event) => {
173
+ event.preventDefault();
174
+ error.textContent = "";
175
+ api.signIn(token.value).then(onSignedIn, (failure: unknown) => {
176
+ error.textContent = errorMessage(failure);
177
+ });
178
+ },
179
+ },
180
+ h("span", { class: "logo large", "aria-hidden": "true" }),
181
+ h("h1", {}, "Sign in to the plant agent"),
182
+ h(
183
+ "p",
184
+ { class: "muted" },
185
+ "Your Tailscale login has no role on this agent. Sign in with the agent's token, or ask an admin for a role.",
186
+ ),
187
+ token,
188
+ error,
189
+ h("button", { class: "button primary", type: "submit" }, "Sign in"),
190
+ ),
191
+ );
192
+ };
@@ -0,0 +1,144 @@
1
+ import { errorMessage } from "../../errors";
2
+ import { api, type SourceFile } from "./api";
3
+ import { type App, deploymentHref } from "./app";
4
+ import { empty, fill, h, icon, icons } from "./dom";
5
+ import { formatSize } from "./format";
6
+
7
+ interface Folder {
8
+ folders: Map<string, Folder>;
9
+ files: SourceFile[];
10
+ }
11
+
12
+ const tree = (files: readonly SourceFile[]) => {
13
+ const root: Folder = { folders: new Map(), files: [] };
14
+ for (const file of files) {
15
+ const parts = file.path.split("/");
16
+ const folder = parts.slice(0, -1).reduce((parent, name) => {
17
+ const existing = parent.folders.get(name);
18
+ if (existing) {
19
+ return existing;
20
+ }
21
+ const created: Folder = { folders: new Map(), files: [] };
22
+ parent.folders.set(name, created);
23
+ return created;
24
+ }, root);
25
+ folder.files.push(file);
26
+ }
27
+ return root;
28
+ };
29
+
30
+ const fileName = (path: string) => path.slice(path.lastIndexOf("/") + 1);
31
+
32
+ /** The release's files as a tree, and the selected one's text with line numbers. */
33
+ export const sourceView = (app: App, id: string) => {
34
+ const files = h("nav", { class: "file-tree" }, empty("Loading files…"));
35
+ const content = h(
36
+ "div",
37
+ { class: "file-view" },
38
+ empty("Select a file to see its text."),
39
+ );
40
+ const sourceHref = (path: string) =>
41
+ `${deploymentHref(id, "source")}/${path.split("/").map(encodeURIComponent).join("/")}`;
42
+ let selected: string | null = null;
43
+ let listing: SourceFile[] | null = null;
44
+
45
+ const fileLink = (file: SourceFile) =>
46
+ h(
47
+ "a",
48
+ {
49
+ class: `file${file.path === selected ? " on" : ""}`,
50
+ href: sourceHref(file.path),
51
+ title: `${file.path} · ${formatSize(file.size)}`,
52
+ onclick: (event) => {
53
+ event.preventDefault();
54
+ app.navigate(sourceHref(file.path));
55
+ },
56
+ },
57
+ icon(icons.file),
58
+ fileName(file.path),
59
+ );
60
+
61
+ const folderElement = (folder: Folder, path: string): HTMLElement[] => [
62
+ ...[...folder.folders]
63
+ .sort(([a], [b]) => a.localeCompare(b))
64
+ .map(([name, child]) => {
65
+ const childPath = path ? `${path}/${name}` : name;
66
+ return h(
67
+ "details",
68
+ {
69
+ open:
70
+ !selected || selected.startsWith(`${childPath}/`) || path === "",
71
+ },
72
+ h("summary", {}, icon(icons.folder), name),
73
+ h("div", { class: "folder" }, ...folderElement(child, childPath)),
74
+ );
75
+ }),
76
+ ...folder.files
77
+ .slice()
78
+ .sort((a, b) => a.path.localeCompare(b.path))
79
+ .map(fileLink),
80
+ ];
81
+
82
+ const renderTree = () => {
83
+ if (listing) {
84
+ fill(
85
+ files,
86
+ ...(listing.length
87
+ ? folderElement(tree(listing), "")
88
+ : [empty("This release has no files.")]),
89
+ );
90
+ }
91
+ };
92
+
93
+ const show = async (path: string | null) => {
94
+ selected = path;
95
+ renderTree();
96
+ if (!path) {
97
+ fill(content, empty("Select a file to see its text."));
98
+ return;
99
+ }
100
+ const size = listing?.find((file) => file.path === path)?.size;
101
+ fill(content, empty(`Loading ${path}…`));
102
+ try {
103
+ const text = await api.sourceFile(id, path);
104
+ if (selected !== path) {
105
+ return;
106
+ }
107
+ fill(
108
+ content,
109
+ h(
110
+ "div",
111
+ { class: "file-header" },
112
+ h("span", { class: "mono" }, path),
113
+ size === undefined
114
+ ? null
115
+ : h("span", { class: "muted" }, formatSize(size)),
116
+ ),
117
+ h(
118
+ "pre",
119
+ { class: "code" },
120
+ ...text
121
+ .replace(/\n$/, "")
122
+ .split("\n")
123
+ .map((line) => h("span", { class: "code-line" }, line, "\n")),
124
+ ),
125
+ );
126
+ } catch (error) {
127
+ fill(content, h("p", { class: "error-text" }, errorMessage(error)));
128
+ }
129
+ };
130
+
131
+ void api.source(id).then(
132
+ (loaded) => {
133
+ listing = loaded;
134
+ renderTree();
135
+ },
136
+ (error: unknown) =>
137
+ fill(files, h("p", { class: "error-text" }, errorMessage(error))),
138
+ );
139
+
140
+ return {
141
+ element: h("div", { class: "source" }, files, content),
142
+ show,
143
+ };
144
+ };