chore: add pnpm monorepo skeleton with core contracts
Shared notebook model (types.ts), HTTP/WebSocket protocol (protocol.ts) and core function signatures (stubs) so core, server and web can be built in parallel. Minimal Fastify server with a health route and test.
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
@@ -0,0 +1,3 @@
|
||||
* text=auto eol=lf
|
||||
*.png binary
|
||||
*.ico binary
|
||||
@@ -0,0 +1,8 @@
|
||||
node_modules/
|
||||
dist/
|
||||
coverage/
|
||||
*.log
|
||||
.env
|
||||
.env.*
|
||||
# runtime data when running from the repo
|
||||
data/
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "@shellbook/server",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/main.ts",
|
||||
"build": "tsc -p tsconfig.json --noEmit",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "vitest run --passWithNoTests"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/websocket": "^11.0.1",
|
||||
"@shellbook/core": "workspace:*",
|
||||
"fastify": "^5.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"tsx": "^4.19.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import Fastify, { type FastifyInstance } from "fastify";
|
||||
import websocket from "@fastify/websocket";
|
||||
|
||||
export interface AppOptions {
|
||||
logger?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the Fastify app. Feature areas live in their own folders and are
|
||||
* registered here as Fastify plugins, one line each:
|
||||
* M2 src/workspace/ (notebooks, hosts.yaml), src/ssh/, src/runs/ (queue, audit, artifacts, /api/events)
|
||||
* M4 src/terminal/ (node-pty + tmux, /api/terminal), src/watch/ (file.changed events)
|
||||
* M5 src/auth/ (login, persistent session secret)
|
||||
*/
|
||||
export async function buildApp(options: AppOptions = {}): Promise<FastifyInstance> {
|
||||
const app = Fastify({ logger: options.logger ?? false });
|
||||
await app.register(websocket);
|
||||
|
||||
app.get("/api/health", async () => ({ ok: true }));
|
||||
|
||||
return app;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { buildApp } from "./app";
|
||||
|
||||
const host = process.env.SHELLBOOK_HOST ?? "127.0.0.1";
|
||||
const port = Number(process.env.SHELLBOOK_PORT ?? 8080);
|
||||
|
||||
const app = await buildApp({ logger: true });
|
||||
await app.listen({ host, port });
|
||||
@@ -0,0 +1,12 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildApp } from "../src/app";
|
||||
|
||||
describe("health", () => {
|
||||
it("answers on /api/health", async () => {
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({ method: "GET", url: "/api/health" });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toEqual({ ok: true });
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src", "test"]
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "shellbook",
|
||||
"private": true,
|
||||
"packageManager": "[email protected]",
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "pnpm -r build",
|
||||
"test": "pnpm -r test",
|
||||
"typecheck": "pnpm -r typecheck",
|
||||
"dev": "pnpm --parallel -r dev"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.9.0",
|
||||
"typescript": "^5.6.3",
|
||||
"vitest": "^2.1.5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "@shellbook/core",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json --noEmit",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "vitest run --passWithNoTests"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// Public API of @shellbook/core. Pure functions, no I/O.
|
||||
// Signatures are a CONTRACT used by server and web; implementations land in M0.
|
||||
|
||||
import type { Notebook, ParamValues, RenderedStep, Step } from "./types";
|
||||
|
||||
export type * from "./types";
|
||||
export type * from "./protocol";
|
||||
|
||||
const notImplemented = (fn: string): never => {
|
||||
throw new Error(`@shellbook/core: ${fn} is not implemented yet (M0)`);
|
||||
};
|
||||
|
||||
/** Parse notebook Markdown (frontmatter, steps, :::after sections). Never throws; problems go to diagnostics. */
|
||||
export function parseNotebook(source: string): Notebook {
|
||||
return notImplemented(`parseNotebook(${source.length} chars)`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Quote a value for POSIX sh. Returns the value unchanged when it only contains
|
||||
* [A-Za-z0-9._/@:=+-] and is non-empty; otherwise single-quoted with ' escaped as '\''.
|
||||
* The ONLY place in the codebase that quotes shell values.
|
||||
*/
|
||||
export function shellQuote(value: string): string {
|
||||
return notImplemented(`shellQuote(${value.length} chars)`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve defaults ({{other}} references) and validate all params by type.
|
||||
* Returns effective values and an error message per invalid/missing-required param.
|
||||
* `hostNames` = names from hosts.yaml (for type "host").
|
||||
*/
|
||||
export function resolveParams(
|
||||
notebook: Notebook,
|
||||
values: ParamValues,
|
||||
hostNames: readonly string[],
|
||||
): { values: ParamValues; errors: Record<string, string> } {
|
||||
return notImplemented(`resolveParams(${notebook.params.length}, ${Object.keys(values).length}, ${hostNames.length})`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Substitute {{name}} in a step: script values are shell-quoted via shellQuote,
|
||||
* attribute values (host, artifacts, uploads) are substituted raw but validated.
|
||||
* Secret params must not be referenced with {{ }} (they are env vars) — reported in `invalid`.
|
||||
*/
|
||||
export function renderStep(
|
||||
notebook: Notebook,
|
||||
step: Step,
|
||||
values: ParamValues,
|
||||
runtime: ParamValues,
|
||||
hostNames: readonly string[],
|
||||
): RenderedStep {
|
||||
return notImplemented(`renderStep(${notebook.title}, ${step.attrs.id}, ${Object.keys(values).length}, ${Object.keys(runtime).length}, ${hostNames.length})`);
|
||||
}
|
||||
|
||||
/** Substitute {{name}} in prose/markdown for display (no quoting; secrets shown as ••••). */
|
||||
export function renderText(text: string, values: ParamValues, notebook: Notebook): string {
|
||||
return notImplemented(`renderText(${text.length}, ${Object.keys(values).length}, ${notebook.title})`);
|
||||
}
|
||||
|
||||
/** Env vars for a run: every `secret` param as NAME=value (exact param name). Server-side only. */
|
||||
export function secretEnv(notebook: Notebook, values: ParamValues): Record<string, string> {
|
||||
return notImplemented(`secretEnv(${notebook.params.length}, ${Object.keys(values).length})`);
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
// HTTP + WebSocket protocol between apps/server and apps/web.
|
||||
// CONTRACT: change only on purpose and update both sides in the same change.
|
||||
// All HTTP routes are under /api and exchange JSON unless noted.
|
||||
|
||||
import type { Notebook, ParamValues } from "./types";
|
||||
|
||||
// ---- hosts -------------------------------------------------------------------
|
||||
|
||||
export interface HostInfo {
|
||||
name: string;
|
||||
address: string;
|
||||
user: string;
|
||||
port: number;
|
||||
tags: string[];
|
||||
}
|
||||
|
||||
// GET /api/hosts
|
||||
export interface HostsResponse {
|
||||
hosts: HostInfo[];
|
||||
}
|
||||
|
||||
// ---- notebooks ---------------------------------------------------------------
|
||||
|
||||
export interface NotebookSummary {
|
||||
/** Path relative to the workspace notebooks/ dir, forward slashes, e.g. "setup/ssh-key.md". */
|
||||
path: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
// GET /api/notebooks
|
||||
export interface NotebookListResponse {
|
||||
notebooks: NotebookSummary[];
|
||||
}
|
||||
|
||||
// GET /api/notebooks/:path (path URL-encoded)
|
||||
export interface NotebookResponse {
|
||||
path: string;
|
||||
source: string;
|
||||
notebook: Notebook;
|
||||
/** Opaque version for optimistic concurrency on save. */
|
||||
version: string;
|
||||
}
|
||||
|
||||
// PUT /api/notebooks/:path
|
||||
export interface SaveNotebookRequest {
|
||||
source: string;
|
||||
/** Version the edit was based on; 409 if the file changed meanwhile. */
|
||||
baseVersion: string;
|
||||
}
|
||||
export interface SaveNotebookResponse {
|
||||
version: string;
|
||||
}
|
||||
|
||||
// ---- runs --------------------------------------------------------------------
|
||||
|
||||
// POST /api/runs
|
||||
export interface StartRunRequest {
|
||||
notebookPath: string;
|
||||
stepId: string;
|
||||
/** Values from the params form, including secrets (only ever sent here). */
|
||||
params: ParamValues;
|
||||
/** Runtime values from earlier `capture` steps in this browser session. */
|
||||
runtime: ParamValues;
|
||||
/** Artifacts from earlier runs this session, for `upload=`: artifact name -> runId. */
|
||||
artifactSources: Record<string, string>;
|
||||
/** Set when the user accepted an unknown host key (SHA256 fingerprint as shown). */
|
||||
acceptHostKey?: string;
|
||||
}
|
||||
export interface StartRunResponse {
|
||||
runId: string;
|
||||
}
|
||||
|
||||
// GET /api/runs/:runId/artifacts/:name -> file download (application/octet-stream)
|
||||
|
||||
// ---- auth --------------------------------------------------------------------
|
||||
|
||||
// POST /api/auth/login {password} -> 204 + session cookie; 401 on failure
|
||||
export interface LoginRequest {
|
||||
password: string;
|
||||
}
|
||||
// POST /api/auth/logout -> 204
|
||||
// GET /api/auth/me -> 200 {authenticated: true} | 401
|
||||
|
||||
// ---- events WebSocket: GET /api/events ---------------------------------------
|
||||
// Server -> client messages (JSON text frames). Client sends nothing.
|
||||
|
||||
export type ServerEvent =
|
||||
| {
|
||||
type: "run.started";
|
||||
runId: string;
|
||||
notebookPath: string;
|
||||
stepId: string;
|
||||
host?: string;
|
||||
/** The exact executed script (same as the client's rendered script). */
|
||||
script: string;
|
||||
}
|
||||
| { type: "run.output"; runId: string; stream: "stdout" | "stderr"; data: string }
|
||||
| {
|
||||
type: "run.finished";
|
||||
runId: string;
|
||||
exitCode: number;
|
||||
durationMs: number;
|
||||
artifacts: string[];
|
||||
captured?: { name: string; value: string };
|
||||
}
|
||||
| {
|
||||
type: "run.hostKeyUnknown";
|
||||
runId: string;
|
||||
host: string;
|
||||
/** e.g. "SHA256:abc..."; client re-POSTs with acceptHostKey after user confirmation. */
|
||||
fingerprint: string;
|
||||
/** True if a DIFFERENT key is already known (possible MITM) — UI must warn loudly. */
|
||||
changed: boolean;
|
||||
}
|
||||
| { type: "run.error"; runId: string; message: string }
|
||||
| { type: "file.changed"; path: string }
|
||||
| { type: "file.deleted"; path: string };
|
||||
|
||||
// ---- terminal WebSocket: GET /api/terminal?session=<name> ---------------------
|
||||
// Client -> server: JSON text frames TerminalClientMessage.
|
||||
// Server -> client: raw terminal output as text frames.
|
||||
|
||||
export type TerminalClientMessage =
|
||||
| { type: "input"; data: string }
|
||||
| { type: "resize"; cols: number; rows: number };
|
||||
@@ -0,0 +1,108 @@
|
||||
// Shared data model for ShellBook notebooks (spec §3).
|
||||
// This file is a CONTRACT between core, server and web. Change it only on purpose,
|
||||
// and update every consumer in the same change.
|
||||
|
||||
export type ParamType = "host" | "name" | "path" | "string" | "choice" | "secret";
|
||||
|
||||
export interface ParamDef {
|
||||
name: string;
|
||||
type: ParamType;
|
||||
required: boolean;
|
||||
/** May reference other params with {{other}}. Never set for `secret`. */
|
||||
default?: string;
|
||||
label?: string;
|
||||
/** Only for type "choice". */
|
||||
options?: string[];
|
||||
}
|
||||
|
||||
/** Param name -> current value. Missing key or "" means "not filled". */
|
||||
export type ParamValues = Record<string, string>;
|
||||
|
||||
export type StepKind = "run" | "check";
|
||||
|
||||
export interface Upload {
|
||||
/** Artifact name from an earlier step (template, may contain {{...}}). */
|
||||
src: string;
|
||||
/** Destination path on the target host (template). */
|
||||
dst: string;
|
||||
}
|
||||
|
||||
export interface StepAttrs {
|
||||
/** Stable id. Explicit `id=` or slug of title; unique per notebook. */
|
||||
id: string;
|
||||
title?: string;
|
||||
/** Raw template from `host="..."`; undefined when `on=local` or not set. */
|
||||
host?: string;
|
||||
/** `on=local`: run on the ShellBook server itself. */
|
||||
local: boolean;
|
||||
sudo: boolean;
|
||||
/** Ask before running. Always false for checks. */
|
||||
confirm: boolean;
|
||||
/** Store trimmed stdout as runtime param with this name. */
|
||||
capture?: string;
|
||||
/** Artifact file name templates (run steps only). */
|
||||
artifacts: string[];
|
||||
uploads: Upload[];
|
||||
timeoutSec: number;
|
||||
}
|
||||
|
||||
/** 1-based, inclusive line range in the notebook source. */
|
||||
export interface SourceRange {
|
||||
startLine: number;
|
||||
endLine: number;
|
||||
}
|
||||
|
||||
export interface Step {
|
||||
kind: StepKind;
|
||||
/** Fence language, e.g. "sh" or "bash". */
|
||||
lang: string;
|
||||
attrs: StepAttrs;
|
||||
/** Raw script template exactly as written (without the fence lines). */
|
||||
script: string;
|
||||
range: SourceRange;
|
||||
}
|
||||
|
||||
export type Block =
|
||||
| { type: "markdown"; text: string; range: SourceRange }
|
||||
| { type: "step"; step: Step }
|
||||
| {
|
||||
type: "after";
|
||||
stepId: string;
|
||||
/** `:::after{step=x failed}` — shown when the step failed. */
|
||||
onFailure: boolean;
|
||||
blocks: Block[];
|
||||
range: SourceRange;
|
||||
};
|
||||
|
||||
export interface Diagnostic {
|
||||
severity: "error" | "warning";
|
||||
message: string;
|
||||
line?: number;
|
||||
}
|
||||
|
||||
export interface Notebook {
|
||||
title: string;
|
||||
params: ParamDef[];
|
||||
blocks: Block[];
|
||||
diagnostics: Diagnostic[];
|
||||
}
|
||||
|
||||
/** A step with all templates resolved for concrete param values. */
|
||||
export interface RenderedStep {
|
||||
stepId: string;
|
||||
kind: StepKind;
|
||||
/** Resolved host name from hosts.yaml; undefined for local steps. */
|
||||
host?: string;
|
||||
local: boolean;
|
||||
/**
|
||||
* The exact script that will run (params substituted, shell-quoted, sudo NOT applied —
|
||||
* sudo wrapping is an execution detail shown as a badge). Display == execution.
|
||||
*/
|
||||
script: string;
|
||||
artifacts: string[];
|
||||
uploads: Upload[];
|
||||
/** Required params (incl. those referenced by this step) that are not filled. Non-empty => cannot run. */
|
||||
missing: string[];
|
||||
/** Validation errors per param name for values this step uses. Non-empty => cannot run. */
|
||||
invalid: Record<string, string>;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": []
|
||||
},
|
||||
"include": ["src", "test"]
|
||||
}
|
||||
Generated
+1646
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,3 @@
|
||||
packages:
|
||||
- "packages/*"
|
||||
- "apps/*"
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2023"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"exactOptionalPropertyTypes": false,
|
||||
"noImplicitOverride": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"isolatedModules": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"resolveJsonModule": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user