@risinghq/lienzo 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.
- package/README.md +82 -2
- package/dist/shell/assets/index-Cna8wlzF.js +4 -0
- package/dist/shell/assets/index-CoJSASvW.css +2 -0
- package/dist/shell/index.html +13 -0
- package/package.json +76 -4
- package/src/bench/bench.ts +132 -0
- package/src/bridge/page.ts +443 -0
- package/src/bridge/protocol.ts +124 -0
- package/src/bridge/record.ts +75 -0
- package/src/bridge/script.ts +24 -0
- package/src/bridge/state.ts +143 -0
- package/src/capture/capture.ts +125 -0
- package/src/capture/compare.ts +46 -0
- package/src/capture/diff.ts +16 -0
- package/src/capture/manifest.ts +60 -0
- package/src/capture/refs.ts +20 -0
- package/src/capture/replay.ts +25 -0
- package/src/capture/review.ts +78 -0
- package/src/capture/serve.ts +32 -0
- package/src/capture/snap.ts +62 -0
- package/src/capture/store.ts +28 -0
- package/src/cli.ts +287 -0
- package/src/cloud/checkout.ts +33 -0
- package/src/cloud/credentials.ts +25 -0
- package/src/cloud/link.ts +60 -0
- package/src/cloud/login.ts +85 -0
- package/src/commands/canvas.ts +46 -0
- package/src/commands/change.ts +218 -0
- package/src/commands/class.ts +66 -0
- package/src/commands/command.ts +27 -0
- package/src/commands/create.ts +95 -0
- package/src/commands/element.ts +118 -0
- package/src/commands/file.ts +96 -0
- package/src/commands/frame.ts +58 -0
- package/src/commands/override.ts +38 -0
- package/src/commands/prop.ts +18 -0
- package/src/commands/registry.ts +76 -0
- package/src/commands/rule.ts +131 -0
- package/src/commands/stage.ts +52 -0
- package/src/commands/story.ts +112 -0
- package/src/commands/style.ts +123 -0
- package/src/commands/text.ts +17 -0
- package/src/commands/token.ts +60 -0
- package/src/commands/transaction.ts +66 -0
- package/src/job/docker.ts +109 -0
- package/src/job/job.ts +125 -0
- package/src/job/server.ts +62 -0
- package/src/mirror/apply.ts +121 -0
- package/src/mirror/entry.ts +7 -0
- package/src/mirror/host.ts +68 -0
- package/src/mirror/observe.ts +271 -0
- package/src/mirror/script.ts +18 -0
- package/src/mirror/transport.ts +7 -0
- package/src/mirror/wire.ts +25 -0
- package/src/project/config.ts +98 -0
- package/src/project/design.ts +59 -0
- package/src/project/detect.ts +184 -0
- package/src/project/files.ts +30 -0
- package/src/project/git.ts +68 -0
- package/src/project/github.ts +42 -0
- package/src/project/history.ts +89 -0
- package/src/project/project.ts +106 -0
- package/src/project/spawn.ts +23 -0
- package/src/project/step.ts +15 -0
- package/src/protocol.ts +125 -0
- package/src/sandbox/forward.ts +73 -0
- package/src/sandbox/install.ts +44 -0
- package/src/sandbox/sandbox.ts +57 -0
- package/src/serve/build.ts +49 -0
- package/src/serve/canvases.ts +65 -0
- package/src/serve/dev.ts +296 -0
- package/src/serve/env.ts +16 -0
- package/src/serve/mcp.ts +65 -0
- package/src/serve/middleware.ts +172 -0
- package/src/serve/next/config.ts +68 -0
- package/src/serve/next/hook.ts +74 -0
- package/src/serve/next/loader.ts +37 -0
- package/src/serve/nuxt.ts +14 -0
- package/src/serve/plugin.ts +95 -0
- package/src/serve/preload.ts +167 -0
- package/src/serve/resend.ts +29 -0
- package/src/serve/running.ts +115 -0
- package/src/serve/screenshot.ts +26 -0
- package/src/serve/sources.ts +46 -0
- package/src/serve/uncached.ts +25 -0
- package/src/serve/vite-build.ts +15 -0
- package/src/serve/vite.ts +19 -0
- package/src/session/session.ts +96 -0
- package/src/share/ask.ts +24 -0
- package/src/share/client.ts +140 -0
- package/src/share/consent.ts +39 -0
- package/src/share/frame.ts +26 -0
- package/src/source/astro/astro.ts +10 -0
- package/src/source/astro/elements.ts +60 -0
- package/src/source/blocks.ts +42 -0
- package/src/source/css.ts +48 -0
- package/src/source/estree.ts +55 -0
- package/src/source/extract.ts +68 -0
- package/src/source/insert.ts +189 -0
- package/src/source/jsx/elements.ts +136 -0
- package/src/source/jsx/jsx.ts +5 -0
- package/src/source/language.ts +176 -0
- package/src/source/location.ts +34 -0
- package/src/source/modules.ts +41 -0
- package/src/source/overrides.ts +35 -0
- package/src/source/page.ts +69 -0
- package/src/source/patch.ts +79 -0
- package/src/source/prop.ts +34 -0
- package/src/source/refusal.ts +7 -0
- package/src/source/rules.ts +298 -0
- package/src/source/stamp.ts +28 -0
- package/src/source/story-file.ts +40 -0
- package/src/source/story.ts +162 -0
- package/src/source/structure.ts +253 -0
- package/src/source/style.ts +143 -0
- package/src/source/svelte/elements.ts +154 -0
- package/src/source/svelte/svelte.ts +11 -0
- package/src/source/tag.ts +99 -0
- package/src/source/tailwind.ts +46 -0
- package/src/source/tokens.ts +56 -0
- package/src/source/vue/elements.ts +236 -0
- package/src/source/vue/vue.ts +11 -0
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { CONFIG, loadConfig } from "../project/config.ts";
|
|
3
|
+
import type { Project } from "../project/project.ts";
|
|
4
|
+
import { BUILD, PROJECT } from "./env.ts";
|
|
5
|
+
|
|
6
|
+
const PRELOAD = path.join(import.meta.dir, "preload.ts");
|
|
7
|
+
const VITE_BUILD = path.join(import.meta.dir, "vite-build.ts");
|
|
8
|
+
|
|
9
|
+
async function scriptOf(root: string, name: string): Promise<string | undefined> {
|
|
10
|
+
const manifest = Bun.file(path.join(root, "package.json"));
|
|
11
|
+
if (!(await manifest.exists())) return undefined;
|
|
12
|
+
|
|
13
|
+
const { scripts } = (await manifest.json()) as { scripts?: Record<string, unknown> };
|
|
14
|
+
const script = scripts?.[name];
|
|
15
|
+
|
|
16
|
+
return typeof script === "string" ? script : undefined;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Builds the project as it ships, with every element stamped with its source
|
|
20
|
+
// location. The project's own `build` script runs, so its own steps run too,
|
|
21
|
+
// and each Vite build in them gets lienzo's plugin. A project with no script
|
|
22
|
+
// of that name builds from its Vite config. The output is the project's own,
|
|
23
|
+
// where its build puts it. Returns the build's exit code.
|
|
24
|
+
export async function build(project: Project): Promise<number> {
|
|
25
|
+
const { build: name } = await loadConfig(project.root);
|
|
26
|
+
const text = await scriptOf(project.root, name);
|
|
27
|
+
if (text === undefined && name !== "build") {
|
|
28
|
+
throw new Error(`${CONFIG} names the script "${name}", which package.json lacks`);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const command =
|
|
32
|
+
text === undefined
|
|
33
|
+
? ["bun", "--no-orphans", VITE_BUILD]
|
|
34
|
+
: ["bun", "--bun", "run", "--no-orphans", name];
|
|
35
|
+
const preload = `--preload=${PRELOAD}`;
|
|
36
|
+
const child = Bun.spawn(command, {
|
|
37
|
+
cwd: project.root,
|
|
38
|
+
env: {
|
|
39
|
+
...process.env,
|
|
40
|
+
NODE_ENV: "production",
|
|
41
|
+
[BUILD]: "1",
|
|
42
|
+
[PROJECT]: JSON.stringify(project),
|
|
43
|
+
BUN_OPTIONS: [process.env.BUN_OPTIONS, preload].filter(Boolean).join(" "),
|
|
44
|
+
},
|
|
45
|
+
stdio: ["inherit", "inherit", "inherit"],
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
return child.exited;
|
|
49
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { ServerResponse } from "node:http";
|
|
2
|
+
import { FILES_CHANGED, type Question, type Result } from "../protocol.ts";
|
|
3
|
+
|
|
4
|
+
// How long a question waits for the canvas, which answers from state it holds.
|
|
5
|
+
const PATIENCE = 5_000;
|
|
6
|
+
|
|
7
|
+
// The canvases open on one dev server, each holding an event stream, and the
|
|
8
|
+
// questions the server has asked them. A command that needs what only the
|
|
9
|
+
// canvas knows, such as the selection, asks through here.
|
|
10
|
+
export function canvases() {
|
|
11
|
+
const open = new Set<ServerResponse>();
|
|
12
|
+
const waiting = new Map<string, (result: Result) => void>();
|
|
13
|
+
|
|
14
|
+
function connect(response: ServerResponse) {
|
|
15
|
+
response.writeHead(200, {
|
|
16
|
+
"content-type": "text/event-stream",
|
|
17
|
+
"cache-control": "no-cache",
|
|
18
|
+
connection: "keep-alive",
|
|
19
|
+
});
|
|
20
|
+
response.write(": open\n\n");
|
|
21
|
+
open.add(response);
|
|
22
|
+
response.on("close", () => open.delete(response));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// One canvas answers. Two would hold two selections, and the question would
|
|
26
|
+
// have no single answer.
|
|
27
|
+
function ask(name: Question["name"]): Promise<Result> {
|
|
28
|
+
const [canvas, ...others] = open;
|
|
29
|
+
if (!canvas) return Promise.resolve({ ok: false, reason: "no canvas is open" });
|
|
30
|
+
if (others.length) {
|
|
31
|
+
return Promise.resolve({
|
|
32
|
+
ok: false,
|
|
33
|
+
reason: `${open.size} canvases are open; close all but one`,
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const id = crypto.randomUUID();
|
|
38
|
+
const answered = Promise.withResolvers<Result>();
|
|
39
|
+
const late = setTimeout(() => {
|
|
40
|
+
answered.resolve({
|
|
41
|
+
ok: false,
|
|
42
|
+
reason: `the canvas did not answer within ${PATIENCE / 1000}s`,
|
|
43
|
+
});
|
|
44
|
+
}, PATIENCE);
|
|
45
|
+
|
|
46
|
+
waiting.set(id, answered.resolve);
|
|
47
|
+
canvas.write(`data: ${JSON.stringify({ id, name } satisfies Question)}\n\n`);
|
|
48
|
+
|
|
49
|
+
return answered.promise.finally(() => {
|
|
50
|
+
clearTimeout(late);
|
|
51
|
+
waiting.delete(id);
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function answer(id: string, result: Result) {
|
|
56
|
+
waiting.get(id)?.(result);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Tells every canvas that a file it shows changed, so it reads it again.
|
|
60
|
+
function changed() {
|
|
61
|
+
for (const canvas of open) canvas.write(`event: ${FILES_CHANGED}\ndata:\n\n`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return { connect, ask, answer, changed };
|
|
65
|
+
}
|
package/src/serve/dev.ts
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
import http from "node:http";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { CONFIG, loadConfig } from "../project/config.ts";
|
|
4
|
+
import type { Project } from "../project/project.ts";
|
|
5
|
+
import { BASE } from "../protocol.ts";
|
|
6
|
+
import { CANVAS, CLOSE, PORT, PROJECT } from "./env.ts";
|
|
7
|
+
import { middleware } from "./middleware.ts";
|
|
8
|
+
import { announce, ensureVacant } from "./running.ts";
|
|
9
|
+
|
|
10
|
+
// A dev server with lienzo added. `exited` settles when the server stops by
|
|
11
|
+
// itself, with its exit code.
|
|
12
|
+
export type Running = {
|
|
13
|
+
site: string;
|
|
14
|
+
canvas: string;
|
|
15
|
+
exited: Promise<number>;
|
|
16
|
+
close(): Promise<void>;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
// Where the pages come from: a Vite server `dev` creates from the project's
|
|
20
|
+
// config, the project's own `dev` script, Nuxt's CLI for a project that
|
|
21
|
+
// depends on Nuxt, which often has no `dev` script of its own, or Next's CLI
|
|
22
|
+
// for a project that depends on Next.
|
|
23
|
+
export type Server = "config" | "script" | "nuxt" | "next";
|
|
24
|
+
|
|
25
|
+
// A character that makes a script run more than one command.
|
|
26
|
+
const SHELL = /[;&|<>()`$]/;
|
|
27
|
+
|
|
28
|
+
// How `dev` serves a project, by its `dev` script and its dependencies. With
|
|
29
|
+
// no script, a Nuxt or Next project gets its framework's CLI and any other
|
|
30
|
+
// project gets a Vite server from its config. Vite's own CLI creates its
|
|
31
|
+
// server where the preload cannot reach it, so `dev` creates that server
|
|
32
|
+
// instead, without the script's options. `nuxt dev` forks a child the preload
|
|
33
|
+
// cannot report from, so `dev` runs Nuxt's CLI itself, unforked, also without
|
|
34
|
+
// the script's options. Next runs no Vite, so `next dev` runs under Node with
|
|
35
|
+
// its options and lienzo's hook. A script on another root, or with more than
|
|
36
|
+
// one command, runs as it is.
|
|
37
|
+
export function serverOf(script: string | undefined, needs: Record<string, string> = {}): Server {
|
|
38
|
+
if (script === undefined) {
|
|
39
|
+
if ("nuxt" in needs) return "nuxt";
|
|
40
|
+
return "next" in needs ? "next" : "config";
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const [command, ...rest] = script.trim().split(/\s+/);
|
|
44
|
+
const first = rest[0] === "dev" || rest[0] === "serve" ? rest[1] : rest[0];
|
|
45
|
+
const options = (first === undefined || first.startsWith("-")) && !SHELL.test(script);
|
|
46
|
+
if (command === "vite" && options) return "config";
|
|
47
|
+
|
|
48
|
+
const dev = rest[0] === "dev" && options;
|
|
49
|
+
if ("nuxt" in needs && (command === "nuxt" || command === "nuxi") && dev) return "nuxt";
|
|
50
|
+
if ("next" in needs && command === "next" && dev) return "next";
|
|
51
|
+
|
|
52
|
+
return "script";
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function manifestOf(root: string): Promise<Record<string, unknown>> {
|
|
56
|
+
const manifest = Bun.file(path.join(root, "package.json"));
|
|
57
|
+
if (!(await manifest.exists())) return {};
|
|
58
|
+
|
|
59
|
+
return (await manifest.json()) as Record<string, unknown>;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function scriptOf(root: string, name: string): Promise<string | undefined> {
|
|
63
|
+
const { scripts } = (await manifestOf(root)) as { scripts?: Record<string, unknown> };
|
|
64
|
+
const script = scripts?.[name];
|
|
65
|
+
|
|
66
|
+
return typeof script === "string" ? script : undefined;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function needsOf(root: string): Promise<Record<string, string>> {
|
|
70
|
+
const manifest = (await manifestOf(root)) as {
|
|
71
|
+
dependencies?: Record<string, string>;
|
|
72
|
+
devDependencies?: Record<string, string>;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
return { ...manifest.dependencies, ...manifest.devDependencies };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const PRELOAD = path.join(import.meta.dir, "preload.ts");
|
|
79
|
+
const VITE = path.join(import.meta.dir, "vite.ts");
|
|
80
|
+
const NUXT = path.join(import.meta.dir, "nuxt.ts");
|
|
81
|
+
const HOOK = path.join(import.meta.dir, "next", "hook.ts");
|
|
82
|
+
|
|
83
|
+
// The entry of the Nuxt CLI the project's Nuxt depends on.
|
|
84
|
+
function nuxtCliOf(root: string): string {
|
|
85
|
+
const nuxt = path.dirname(Bun.resolveSync("nuxt/package.json", root));
|
|
86
|
+
|
|
87
|
+
return Bun.resolveSync("@nuxt/cli", nuxt);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// The nearest directory at or above the project whose manifest declares
|
|
91
|
+
// workspaces, or the project's root when none does.
|
|
92
|
+
async function workspaceOf(root: string, from = root): Promise<string> {
|
|
93
|
+
if ("workspaces" in (await manifestOf(from))) return from;
|
|
94
|
+
|
|
95
|
+
const parent = path.dirname(from);
|
|
96
|
+
|
|
97
|
+
return parent === from ? root : workspaceOf(root, parent);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
type Command = { command: string[]; cwd: string };
|
|
101
|
+
|
|
102
|
+
// The script `dev` serves, by name and by its text, which is absent when the
|
|
103
|
+
// manifest has no script of that name.
|
|
104
|
+
type Script = { name: string; text?: string };
|
|
105
|
+
|
|
106
|
+
// What runs, and where: Vite's server from the project's config, or the
|
|
107
|
+
// project's `dev` script, in the project's root; or the project's Nuxt CLI
|
|
108
|
+
// through lienzo's entry, which adds the module that keeps the frame from
|
|
109
|
+
// showing a cached page. `bun run nuxt` would start the CLI without the IPC
|
|
110
|
+
// channel the preload reports on. The CLI runs unforked so the preload runs in
|
|
111
|
+
// the process that creates the Vite server. A Nuxt app in a monorepo runs from
|
|
112
|
+
// the workspace root with the app as Nuxt's root, as the monorepo's scripts
|
|
113
|
+
// run it, because its server code may resolve paths from the cwd. Next's CLI
|
|
114
|
+
// runs under Node, the runtime Next is built for, with the script's options.
|
|
115
|
+
async function commandOf(
|
|
116
|
+
server: Server,
|
|
117
|
+
root: string,
|
|
118
|
+
script: Script,
|
|
119
|
+
port?: number,
|
|
120
|
+
): Promise<Command> {
|
|
121
|
+
const ported = port === undefined ? [] : ["--port", String(port)];
|
|
122
|
+
|
|
123
|
+
switch (server) {
|
|
124
|
+
case "config":
|
|
125
|
+
return { command: ["bun", "--no-orphans", VITE], cwd: root };
|
|
126
|
+
case "nuxt": {
|
|
127
|
+
const cwd = await workspaceOf(root);
|
|
128
|
+
const command = ["bun", "--bun", "--no-orphans", NUXT, nuxtCliOf(root)];
|
|
129
|
+
if (cwd !== root) command.push(path.relative(cwd, root));
|
|
130
|
+
command.push("--no-fork", ...ported);
|
|
131
|
+
|
|
132
|
+
return { command, cwd };
|
|
133
|
+
}
|
|
134
|
+
case "next": {
|
|
135
|
+
const options = (script.text ?? "").trim().split(/\s+/).slice(2);
|
|
136
|
+
const cli = Bun.resolveSync("next/dist/bin/next", root);
|
|
137
|
+
|
|
138
|
+
return { command: ["node", cli, "dev", ...options, ...ported], cwd: root };
|
|
139
|
+
}
|
|
140
|
+
case "script":
|
|
141
|
+
return { command: ["bun", "--bun", "run", "--no-orphans", script.name], cwd: root };
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function joined(...options: (string | undefined)[]): string {
|
|
146
|
+
return options.filter(Boolean).join(" ");
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// What the server's process gets in its environment: the project, the port,
|
|
150
|
+
// and what loads lienzo into it. Next's gets the address of lienzo's own
|
|
151
|
+
// server, which answers the canvas for it. The server runs in development
|
|
152
|
+
// whatever NODE_ENV lienzo inherits: Astro turns hot updates off under "test"
|
|
153
|
+
// or "production", and the frames would never reload.
|
|
154
|
+
function envOf(project: Project, port?: number, canvas?: string): Record<string, string> {
|
|
155
|
+
const common = {
|
|
156
|
+
NODE_ENV: "development",
|
|
157
|
+
[PROJECT]: JSON.stringify(project),
|
|
158
|
+
...(port === undefined ? {} : { [PORT]: String(port) }),
|
|
159
|
+
};
|
|
160
|
+
if (canvas === undefined) {
|
|
161
|
+
return { ...common, BUN_OPTIONS: joined(process.env.BUN_OPTIONS, `--preload=${PRELOAD}`) };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
return {
|
|
165
|
+
...common,
|
|
166
|
+
[CANVAS]: canvas,
|
|
167
|
+
NODE_OPTIONS: joined(process.env.NODE_OPTIONS, `--import=${HOOK}`),
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// The route on lienzo's own server that Next's server reports its address to.
|
|
172
|
+
const LISTENING = "/listening";
|
|
173
|
+
|
|
174
|
+
async function textOf(request: http.IncomingMessage): Promise<string> {
|
|
175
|
+
let text = "";
|
|
176
|
+
for await (const chunk of request) text += chunk;
|
|
177
|
+
|
|
178
|
+
return text;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// lienzo's own server, for a framework whose server runs under Node and so
|
|
182
|
+
// cannot run lienzo's middleware: it answers the canvas and its API, which
|
|
183
|
+
// that server forwards here, and hears the address that server listens on.
|
|
184
|
+
// Next's pages carry their own client, which reloads them.
|
|
185
|
+
async function canvasServer(project: Project, listening: (site: string) => void) {
|
|
186
|
+
const answer = middleware(project, null);
|
|
187
|
+
const server = http.createServer(async (request, response) => {
|
|
188
|
+
if (request.method === "POST" && request.url === LISTENING) {
|
|
189
|
+
listening((JSON.parse(await textOf(request)) as { site: string }).site);
|
|
190
|
+
return response.end();
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
return answer(request, response, () => {
|
|
194
|
+
response.statusCode = 404;
|
|
195
|
+
response.end();
|
|
196
|
+
});
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
|
200
|
+
const { port } = server.address() as { port: number };
|
|
201
|
+
|
|
202
|
+
return { server, address: `http://127.0.0.1:${port}/` };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// How long `dev` waits for the server to report its address.
|
|
206
|
+
const WAIT = 60_000;
|
|
207
|
+
|
|
208
|
+
// The server runs in the project's root, as `vite dev` does, because a
|
|
209
|
+
// framework's plugin resolves its peers from there; a Nuxt app in a monorepo
|
|
210
|
+
// is the exception `commandOf` names. A Vite server runs under Bun with the
|
|
211
|
+
// preload that adds lienzo to every Vite server it creates, and reports on the
|
|
212
|
+
// IPC channel. Next's server runs under Node with lienzo's hook, and reports
|
|
213
|
+
// to lienzo's own server.
|
|
214
|
+
async function serve(
|
|
215
|
+
project: Project,
|
|
216
|
+
server: Server,
|
|
217
|
+
script: Script,
|
|
218
|
+
port?: number,
|
|
219
|
+
wait = WAIT,
|
|
220
|
+
): Promise<Running> {
|
|
221
|
+
const listening = Promise.withResolvers<string>();
|
|
222
|
+
const canvas = server === "next" ? await canvasServer(project, listening.resolve) : undefined;
|
|
223
|
+
|
|
224
|
+
const { command, cwd } = await commandOf(server, project.root, script, port);
|
|
225
|
+
const child = Bun.spawn(command, {
|
|
226
|
+
cwd,
|
|
227
|
+
env: { ...process.env, ...envOf(project, port, canvas?.address) },
|
|
228
|
+
stdio: ["inherit", "inherit", "inherit"],
|
|
229
|
+
...(canvas ? {} : { ipc: (message: { site: string }) => listening.resolve(message.site) }),
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
void child.exited.then((code) => {
|
|
233
|
+
canvas?.server.close();
|
|
234
|
+
listening.reject(new Error(`the dev server exited with code ${code} before serving ${BASE}`));
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
// `dev` never hangs: a server lienzo cannot reach within the bound fails
|
|
238
|
+
// with what was missing, and the runaway process is stopped.
|
|
239
|
+
const late = setTimeout(() => {
|
|
240
|
+
listening.reject(new Error(`no server serving ${BASE} listened within ${wait / 1000}s`));
|
|
241
|
+
child.kill();
|
|
242
|
+
}, wait);
|
|
243
|
+
const settle = () => clearTimeout(late);
|
|
244
|
+
listening.promise.then(settle, settle);
|
|
245
|
+
|
|
246
|
+
// A signal would end a script with an error code, which `bun run` prints.
|
|
247
|
+
// A stopped server has no channel left to send on. `next dev` stops the
|
|
248
|
+
// server it forks when it gets SIGTERM.
|
|
249
|
+
const close = async () => {
|
|
250
|
+
if (child.exitCode === null && child.signalCode === null) {
|
|
251
|
+
if (canvas) child.kill("SIGTERM");
|
|
252
|
+
else child.send(CLOSE);
|
|
253
|
+
}
|
|
254
|
+
await child.exited;
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
const site = await listening.promise;
|
|
258
|
+
const canvasUrl = new URL(BASE, site).href;
|
|
259
|
+
|
|
260
|
+
let withdraw: () => Promise<void>;
|
|
261
|
+
try {
|
|
262
|
+
withdraw = await announce(project.root, canvasUrl);
|
|
263
|
+
} catch (error) {
|
|
264
|
+
await close();
|
|
265
|
+
throw error;
|
|
266
|
+
}
|
|
267
|
+
const exited = child.exited.then(async (code) => {
|
|
268
|
+
await withdraw();
|
|
269
|
+
return code;
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
return {
|
|
273
|
+
site,
|
|
274
|
+
canvas: canvasUrl,
|
|
275
|
+
exited,
|
|
276
|
+
close: async () => {
|
|
277
|
+
await close();
|
|
278
|
+
await exited;
|
|
279
|
+
},
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// Starts the project's dev server with lienzo added, without a change to its
|
|
284
|
+
// config. The script is the one lienzo.json names, `dev` by default. Only the
|
|
285
|
+
// default may be missing, since a project without it still has a server.
|
|
286
|
+
export async function dev(project: Project, port?: number, wait = WAIT): Promise<Running> {
|
|
287
|
+
const root = project.root;
|
|
288
|
+
const { dev: name } = await loadConfig(root);
|
|
289
|
+
const script: Script = { name, text: await scriptOf(root, name) };
|
|
290
|
+
if (script.text === undefined && name !== "dev") {
|
|
291
|
+
throw new Error(`${CONFIG} names the script "${name}", which package.json lacks`);
|
|
292
|
+
}
|
|
293
|
+
await ensureVacant(root);
|
|
294
|
+
|
|
295
|
+
return serve(project, serverOf(script.text, await needsOf(root)), script, port, wait);
|
|
296
|
+
}
|
package/src/serve/env.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// What `dev` passes to the process that serves a project's pages, in its
|
|
2
|
+
// environment. Code that runs under Node imports these too.
|
|
3
|
+
|
|
4
|
+
export const PROJECT = "LIENZO_PROJECT";
|
|
5
|
+
export const PORT = "LIENZO_PORT";
|
|
6
|
+
|
|
7
|
+
// Set when the process builds the project, not serves it. The preload then
|
|
8
|
+
// adds the stamping plugin to each build and starts no server.
|
|
9
|
+
export const BUILD = "LIENZO_BUILD";
|
|
10
|
+
|
|
11
|
+
// The address of the server in lienzo's own process that answers the canvas
|
|
12
|
+
// and its API, for a framework whose server runs under Node.
|
|
13
|
+
export const CANVAS = "LIENZO_CANVAS";
|
|
14
|
+
|
|
15
|
+
// The message that asks the dev script to stop.
|
|
16
|
+
export const CLOSE = "lienzo:close";
|
package/src/serve/mcp.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import type { Command, Params } from "../commands/command.ts";
|
|
7
|
+
import { commands } from "../commands/registry.ts";
|
|
8
|
+
import type { Result } from "../protocol.ts";
|
|
9
|
+
|
|
10
|
+
export type Runner = (name: string, params: Params) => Promise<Result>;
|
|
11
|
+
|
|
12
|
+
function schemaOf(command: Command) {
|
|
13
|
+
const fields: Record<string, z.ZodString | z.ZodOptional<z.ZodString>> = {};
|
|
14
|
+
|
|
15
|
+
for (const [name, does] of Object.entries(command.params)) {
|
|
16
|
+
fields[name] = z.string().describe(does);
|
|
17
|
+
}
|
|
18
|
+
for (const [name, does] of Object.entries(command.optional ?? {})) {
|
|
19
|
+
fields[name] = z.string().optional().describe(does);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
return fields;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function serverOf(runner: Runner): McpServer {
|
|
26
|
+
const server = new McpServer({ name: "lienzo", version: "0.0.0" });
|
|
27
|
+
|
|
28
|
+
for (const command of commands) {
|
|
29
|
+
const config = { description: command.does, inputSchema: schemaOf(command) };
|
|
30
|
+
|
|
31
|
+
server.registerTool(command.name, config, async (params) => {
|
|
32
|
+
const result = await runner(command.name, params as Params);
|
|
33
|
+
const text = JSON.stringify(result);
|
|
34
|
+
|
|
35
|
+
return { content: [{ type: "text", text }], isError: !result.ok };
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
return server;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Serves every command in the registry as an MCP tool on stdio, so an agent
|
|
43
|
+
// reaches exactly what the CLI and the canvas reach. `runner` says where a call
|
|
44
|
+
// runs: this project's canvas, or a canvas at an address.
|
|
45
|
+
export async function serve(runner: Runner): Promise<void> {
|
|
46
|
+
await serverOf(runner).connect(new StdioServerTransport());
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Answers one MCP request over HTTP with the same tools. It keeps no session:
|
|
50
|
+
// each request gets its own server, so the dev server holds nothing between
|
|
51
|
+
// calls and a restart loses nothing.
|
|
52
|
+
export async function serveHttp(
|
|
53
|
+
runner: Runner,
|
|
54
|
+
request: IncomingMessage,
|
|
55
|
+
response: ServerResponse,
|
|
56
|
+
): Promise<void> {
|
|
57
|
+
const transport = new StreamableHTTPServerTransport({
|
|
58
|
+
sessionIdGenerator: undefined,
|
|
59
|
+
enableJsonResponse: true,
|
|
60
|
+
});
|
|
61
|
+
response.on("close", () => void transport.close());
|
|
62
|
+
|
|
63
|
+
await serverOf(runner).connect(transport);
|
|
64
|
+
await transport.handleRequest(request, response);
|
|
65
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { run } from "../commands/registry.ts";
|
|
4
|
+
import { history } from "../project/history.ts";
|
|
5
|
+
import type { Actor, Project } from "../project/project.ts";
|
|
6
|
+
import { bridgeScript } from "../bridge/script.ts";
|
|
7
|
+
import {
|
|
8
|
+
ACTOR,
|
|
9
|
+
API,
|
|
10
|
+
BASE,
|
|
11
|
+
BRIDGE,
|
|
12
|
+
MCP,
|
|
13
|
+
OVERRIDES,
|
|
14
|
+
type ProjectInfo,
|
|
15
|
+
type Result,
|
|
16
|
+
} from "../protocol.ts";
|
|
17
|
+
import { OVERRIDES_FILE } from "../source/overrides.ts";
|
|
18
|
+
import { canvases } from "./canvases.ts";
|
|
19
|
+
import { serveHttp } from "./mcp.ts";
|
|
20
|
+
import { sources } from "./sources.ts";
|
|
21
|
+
|
|
22
|
+
const SHELL = path.resolve(import.meta.dir, "../../dist/shell");
|
|
23
|
+
|
|
24
|
+
async function bodyOf(request: IncomingMessage): Promise<Record<string, unknown>> {
|
|
25
|
+
let text = "";
|
|
26
|
+
for await (const chunk of request) text += chunk;
|
|
27
|
+
|
|
28
|
+
return text ? (JSON.parse(text) as Record<string, unknown>) : {};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function sendJson(response: ServerResponse, value: unknown) {
|
|
32
|
+
response.setHeader("content-type", "application/json");
|
|
33
|
+
response.end(JSON.stringify(value));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function sendStatus(response: ServerResponse, status: number, text = "") {
|
|
37
|
+
response.statusCode = status;
|
|
38
|
+
response.end(text);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function siteOf(request: IncomingMessage) {
|
|
42
|
+
const encrypted = "encrypted" in request.socket && request.socket.encrypted === true;
|
|
43
|
+
|
|
44
|
+
return `${encrypted ? "https" : "http"}://${request.headers.host}/`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function sendShell(response: ServerResponse, relative: string) {
|
|
48
|
+
const wanted = path.join(SHELL, relative);
|
|
49
|
+
const inside = !path.relative(SHELL, wanted).startsWith("..");
|
|
50
|
+
const found = inside && relative !== "" && (await Bun.file(wanted).exists());
|
|
51
|
+
|
|
52
|
+
// The shell is one page, so an unknown path gets it.
|
|
53
|
+
const served = Bun.file(found ? wanted : path.join(SHELL, "index.html"));
|
|
54
|
+
|
|
55
|
+
if (!(await served.exists())) {
|
|
56
|
+
return sendStatus(response, 503, "The canvas is not built. Run `bun run build` in lienzo.");
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
response.setHeader("content-type", served.type);
|
|
60
|
+
response.end(Buffer.from(await served.arrayBuffer()));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function sendBridge(response: ServerResponse) {
|
|
64
|
+
response.setHeader("content-type", "text/javascript");
|
|
65
|
+
response.end(await bridgeScript());
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function sendOverrides(project: Project, response: ServerResponse) {
|
|
69
|
+
const file = Bun.file(path.join(project.root, OVERRIDES_FILE));
|
|
70
|
+
|
|
71
|
+
response.setHeader("content-type", "text/css");
|
|
72
|
+
response.setHeader("cache-control", "no-store");
|
|
73
|
+
response.end((await file.exists()) ? await file.text() : "");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Runs each task after the one before it settles, failed or not.
|
|
77
|
+
function serial() {
|
|
78
|
+
let last: Promise<unknown> = Promise.resolve();
|
|
79
|
+
|
|
80
|
+
return <T>(task: () => Promise<T>): Promise<T> => {
|
|
81
|
+
const next = last.then(task, task);
|
|
82
|
+
last = next.catch(() => {});
|
|
83
|
+
return next;
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Serves the canvas and its API under /__lienzo/ on the project's dev server,
|
|
88
|
+
// so the canvas shares an origin with the pages it frames and can reach them.
|
|
89
|
+
// `written` hears each file lienzo writes, by absolute path.
|
|
90
|
+
export function middleware(
|
|
91
|
+
project: Project,
|
|
92
|
+
client: string | null,
|
|
93
|
+
written?: (file: string) => void,
|
|
94
|
+
) {
|
|
95
|
+
const past = history(project, written);
|
|
96
|
+
const open = canvases();
|
|
97
|
+
const files = sources(open.changed);
|
|
98
|
+
// Commands run one at a time, so the actor of the command running is the
|
|
99
|
+
// actor of each edit it records.
|
|
100
|
+
let actor: Actor = "human";
|
|
101
|
+
const recording: Project = {
|
|
102
|
+
...project,
|
|
103
|
+
record: (change) => past.record(change, actor),
|
|
104
|
+
follow: files.follow,
|
|
105
|
+
ask: open.ask,
|
|
106
|
+
session: past.session,
|
|
107
|
+
};
|
|
108
|
+
// An edit reads a file, then writes it, and undo checks the file against
|
|
109
|
+
// its record before it writes. Interleaved, two edits lose one and two
|
|
110
|
+
// undos clear the history, so commands and undo/redo run one at a time.
|
|
111
|
+
// `answer` stays outside: a queued command can be waiting on it.
|
|
112
|
+
const queue = serial();
|
|
113
|
+
|
|
114
|
+
function runAs(by: Actor, site: string, name: string, params: unknown): Promise<Result> {
|
|
115
|
+
return queue(() => {
|
|
116
|
+
actor = by;
|
|
117
|
+
|
|
118
|
+
return run({ ...recording, site }, name, (params ?? {}) as Record<string, string>);
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function api(route: string, request: IncomingMessage, response: ServerResponse) {
|
|
123
|
+
if (route === "project") {
|
|
124
|
+
const { name, classAttribute, tailwind } = project;
|
|
125
|
+
const info: ProjectInfo = { name, classAttribute, tailwind, client };
|
|
126
|
+
|
|
127
|
+
return sendJson(response, info);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (route === "events") return open.connect(response);
|
|
131
|
+
|
|
132
|
+
if (request.method !== "POST") return sendStatus(response, 405);
|
|
133
|
+
|
|
134
|
+
if (route === "undo") return sendJson(response, await queue(past.undo));
|
|
135
|
+
if (route === "redo") return sendJson(response, await queue(past.redo));
|
|
136
|
+
|
|
137
|
+
if (route === "answer") {
|
|
138
|
+
const { id, result } = await bodyOf(request);
|
|
139
|
+
open.answer(String(id), result as Result);
|
|
140
|
+
return sendStatus(response, 204);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
if (route === "run") {
|
|
144
|
+
const { name, params } = await bodyOf(request);
|
|
145
|
+
const by = request.headers[ACTOR] === "agent" ? "agent" : "human";
|
|
146
|
+
|
|
147
|
+
return sendJson(response, await runAs(by, siteOf(request), String(name), params));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return sendStatus(response, 404);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return (request: IncomingMessage, response: ServerResponse, next: () => void) => {
|
|
154
|
+
const url = (request.url ?? "").split("?")[0]!;
|
|
155
|
+
|
|
156
|
+
if (!url.startsWith(BASE)) return next();
|
|
157
|
+
if (url === BRIDGE) return void sendBridge(response);
|
|
158
|
+
if (url === OVERRIDES) return void sendOverrides(project, response);
|
|
159
|
+
if (url === MCP) {
|
|
160
|
+
const site = siteOf(request);
|
|
161
|
+
|
|
162
|
+
return void serveHttp(
|
|
163
|
+
(name, params) => runAs("agent", site, name, params),
|
|
164
|
+
request,
|
|
165
|
+
response,
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
if (!url.startsWith(API)) return sendShell(response, url.slice(BASE.length));
|
|
169
|
+
|
|
170
|
+
return api(url.slice(API.length), request, response);
|
|
171
|
+
};
|
|
172
|
+
}
|