refactor(web): use real core in demos and tests (#4, #5)

This commit is contained in:
Florian Schmidt
2026-11-16 00:21:03 +01:00
parent 4e79af3e24
commit 08d5441cf2
6 changed files with 8 additions and 237 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
import type { ServerEvent, StartRunRequest } from "@shellbook/core";
import type { Api } from "../api";
import { HttpError } from "../api";
import { parseNotebook, renderStep } from "./core";
import { parseNotebook, renderStep } from "@shellbook/core";
import initial from "./ssh-key.md?raw";
let source = initial;
let version = 1;
-204
View File
@@ -1,204 +0,0 @@
/** TEMPORARY M0 fallback. Demo-only Vite alias; never used in production.
* Remove this file and the alias when core lands. Parser supports the fixture
* body syntax only; frontmatter definitions are fixed to spec §3.1.
*/
import type {
Block,
Notebook,
ParamValues,
RenderedStep,
Step,
StepAttrs,
} from "../../../../packages/core/src/types";
export function shellQuote(value: string): string {
return value && /^[A-Za-z0-9._/@:=+-]+$/.test(value)
? value
: `'${value.replace(/'/g, "'\\''")}'`;
}
export function parseNotebook(source: string): Notebook {
const lines = source
.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, "")
.split(/\r?\n/);
function parse(
start: number,
nested = false,
): { blocks: Block[]; end: number } {
const blocks: Block[] = [];
let prose = "";
const range = { startLine: 1, endLine: 1 };
const flush = () => {
if (prose) blocks.push({ type: "markdown", text: prose, range });
prose = "";
};
for (let i = start; i < lines.length; i++) {
const line = lines[i]!;
if (nested && line === ":::") {
flush();
return { blocks, end: i };
}
const after = line.match(/^:::after\{step=(\S+?)( failed)?\}$/);
if (after) {
flush();
const inner = parse(i + 1, true);
blocks.push({
type: "after",
stepId: after[1]!,
onFailure: !!after[2],
blocks: inner.blocks,
range,
});
i = inner.end;
continue;
}
const fence = line.match(/^```(?:sh|bash) \{(run|check) (.*)\}$/);
if (fence) {
flush();
const raw = fence[2]!;
const attrs = Object.fromEntries(
[...raw.matchAll(/([\w]+)=(?:"([^"]*)"|([^\s]+))/g)].map((m) => [
m[1],
m[2] ?? m[3],
]),
);
const title = attrs.title ?? "Step";
const stepAttrs: StepAttrs = {
id: attrs.id ?? title.toLowerCase().replace(/\s+/g, "-"),
title,
host: attrs.host,
local: attrs.on === "local",
sudo: /(?:^|\s)sudo(?:\s|$)/.test(raw),
confirm: /(?:^|\s)confirm(?:\s|$)/.test(raw),
artifacts: attrs.artifacts?.split(",") ?? [],
uploads: attrs.upload
? attrs.upload.split(",").map((pair: string) => {
const [src, dst] = pair.split(":");
return { src: src!, dst: dst! };
})
: [],
timeoutSec: 30,
capture: attrs.capture,
};
const script: string[] = [];
while (++i < lines.length && lines[i] !== "```") script.push(lines[i]!);
blocks.push({
type: "step",
step: {
kind: fence[1] as Step["kind"],
lang: "sh",
attrs: stepAttrs,
script: script.join("\n"),
range,
},
});
} else prose += line + "\n";
}
flush();
return { blocks, end: lines.length };
}
return {
title: "New server SSH key",
params: [
{ name: "host", type: "host", required: true, label: "Target server" },
{
name: "user",
type: "name",
required: true,
default: "admin",
label: "Login user",
},
{
name: "keyname",
type: "name",
required: false,
default: "id_ed25519_{{host}}",
},
],
blocks: parse(0).blocks,
diagnostics: [
{
severity: "warning",
message:
"Mock demo: frontmatter schema is fixed; prose and step edits are supported. No commands execute.",
},
],
};
}
export function renderText(
text: string,
values: ParamValues,
notebook: Notebook,
): string {
return text.replace(/\{\{(\w+)\}\}/g, (token, name: string) =>
notebook.params.find((p) => p.name === name)?.type === "secret"
? "••••"
: values[name] || token,
);
}
export function resolveParams(
notebook: Notebook,
input: ParamValues,
hosts: readonly string[],
) {
const values = { ...input };
const errors: Record<string, string> = {};
for (let i = 0; i < notebook.params.length; i++)
for (const p of notebook.params)
if (values[p.name] === undefined && p.default !== undefined) {
const expanded = renderText(p.default, values, notebook);
if (!expanded.includes("{{")) values[p.name] = expanded;
}
for (const p of notebook.params) {
const value = values[p.name] ?? "";
if (!value && p.required) errors[p.name] = "Required";
else if (
value &&
((p.type === "host" && !hosts.includes(value)) ||
(p.type === "name" && !/^[A-Za-z0-9._-]+$/.test(value)) ||
(p.type === "choice" && !p.options?.includes(value)))
)
errors[p.name] = "Invalid value";
}
return { values, errors };
}
export function renderStep(
notebook: Notebook,
step: Step,
values: ParamValues,
runtime: ParamValues,
hosts: readonly string[],
): RenderedStep {
const resolved = resolveParams(notebook, values, hosts);
const all = { ...runtime, ...resolved.values };
const missing = notebook.params
.filter((p) => p.required && !all[p.name])
.map((p) => p.name);
const invalid = { ...resolved.errors };
const script = step.script.replace(
/\{\{(\w+)\}\}/g,
(token, name: string) => {
if (notebook.params.find((p) => p.name === name)?.type === "secret") {
invalid[name] = "Use an environment variable for secrets";
return token;
}
if (!all[name]) {
if (!missing.includes(name)) missing.push(name);
return token;
}
return shellQuote(all[name]!);
},
);
return {
stepId: step.attrs.id,
kind: step.kind,
host: renderText(step.attrs.host ?? "", all, notebook),
local: step.attrs.local,
script,
artifacts: step.attrs.artifacts.map((a) => renderText(a, all, notebook)),
uploads: step.attrs.uploads.map((u) => ({
src: renderText(u.src, all, notebook),
dst: renderText(u.dst, all, notebook),
})),
missing,
invalid,
};
}
+1 -2
View File
@@ -7,7 +7,6 @@ import {
within,
} from "@testing-library/react";
import { expect, it, vi } from "vitest";
vi.mock("@shellbook/core", () => import("../mock/core"));
vi.mock("../Editor", () => ({
Editor: ({
source,
@@ -27,7 +26,7 @@ import { App } from "../App";
import { HttpError } from "../api";
import type { Api } from "../api";
import type { ServerEvent, StartRunRequest } from "@shellbook/core";
import { parseNotebook } from "../mock/core";
import { parseNotebook } from "@shellbook/core";
import source from "../mock/ssh-key.md?raw";
function harness() {
-1
View File
@@ -1,6 +1,5 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
vi.mock("@shellbook/core", () => import("../mock/core"));
import { ParamsForm } from "../ParamsForm";
import { StepCard } from "../StepCard";
import type { Notebook, RenderedStep, Step } from "@shellbook/core";
+1 -2
View File
@@ -1,5 +1,4 @@
import { describe, expect, it, vi } from "vitest";
vi.mock("@shellbook/core", () => import("../mock/core"));
import { describe, expect, it } from "vitest";
import { sshCommand } from "../ssh";
const host = {
name: "test",
+3 -25
View File
@@ -1,29 +1,7 @@
import { defineConfig, loadEnv } from "vite";
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { fileURLToPath } from "node:url";
export default defineConfig(({ mode }) => {
const mock =
loadEnv(mode, process.cwd(), "").VITE_MOCK === "1" ||
process.env.VITE_MOCK === "1";
return {
export default defineConfig({
plugins: [react()],
build: { target: "es2022" },
// TEMPORARY: delete this alias and src/mock/core.ts once M0 lands.
resolve: {
alias: mock
? [
{
find: /^@shellbook\/core$/,
replacement: fileURLToPath(
new URL("./src/mock/core.ts", import.meta.url),
),
},
]
: [],
},
server: {
proxy: { "/api": { target: "http://127.0.0.1:8080", ws: true } },
},
};
server: { proxy: { "/api": { target: "http://127.0.0.1:8080", ws: true } } },
});