@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,68 @@
|
|
|
1
|
+
import { fileURLToPath } from "node:url";
|
|
2
|
+
import type { Project } from "../../project/project.ts";
|
|
3
|
+
import { PROJECT } from "../env.ts";
|
|
4
|
+
import type { Options } from "./loader.ts";
|
|
5
|
+
|
|
6
|
+
// Adds lienzo's loader to the config Next loads for its dev server, for
|
|
7
|
+
// Turbopack and for webpack, whichever the project runs. The project's own
|
|
8
|
+
// rules and webpack function stay and run after lienzo's loader.
|
|
9
|
+
|
|
10
|
+
const LOADER = fileURLToPath(new URL("./loader.ts", import.meta.url));
|
|
11
|
+
|
|
12
|
+
// Next's name for the phase of `next dev`.
|
|
13
|
+
const DEVELOPMENT = "phase-development-server";
|
|
14
|
+
|
|
15
|
+
const SOURCES = ["*.jsx", "*.tsx"];
|
|
16
|
+
|
|
17
|
+
type Rule = { condition?: unknown; loaders: unknown[] };
|
|
18
|
+
|
|
19
|
+
type WebpackConfig = {
|
|
20
|
+
module: { rules: unknown[] };
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
type Webpack = (config: WebpackConfig, context: unknown) => WebpackConfig;
|
|
24
|
+
|
|
25
|
+
type Config = {
|
|
26
|
+
turbopack?: { rules?: Record<string, Rule | unknown[]> };
|
|
27
|
+
webpack?: Webpack | null;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
type LoadConfig = (phase: string, ...rest: unknown[]) => Promise<Config>;
|
|
31
|
+
|
|
32
|
+
function withLoader(config: Config, options: Options): Config {
|
|
33
|
+
const loader = { loader: LOADER, options };
|
|
34
|
+
const rules = { ...config.turbopack?.rules };
|
|
35
|
+
|
|
36
|
+
// `foreign` is Next's name for node_modules and its own internals.
|
|
37
|
+
const rule: Rule = { condition: { not: "foreign" }, loaders: [loader] };
|
|
38
|
+
for (const glob of SOURCES) {
|
|
39
|
+
const held = rules[glob];
|
|
40
|
+
rules[glob] = held === undefined ? rule : [rule, ...(Array.isArray(held) ? held : [held])];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const webpack: Webpack = (webpackConfig, context) => {
|
|
44
|
+
const out = config.webpack ? config.webpack(webpackConfig, context) : webpackConfig;
|
|
45
|
+
out.module.rules.unshift({
|
|
46
|
+
test: /\.[jt]sx$/,
|
|
47
|
+
exclude: /[\\/]node_modules[\\/]/,
|
|
48
|
+
enforce: "pre",
|
|
49
|
+
use: [loader],
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
return out;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
return { ...config, turbopack: { ...config.turbopack, rules }, webpack };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Next caches the config it loads and hands it out again, so lienzo's copy is
|
|
59
|
+
// made anew from it each time rather than added to it.
|
|
60
|
+
export function withLienzo(loadConfig: LoadConfig): LoadConfig {
|
|
61
|
+
const { root } = JSON.parse(process.env[PROJECT]!) as Project;
|
|
62
|
+
|
|
63
|
+
return async (phase, ...rest) => {
|
|
64
|
+
const config = await loadConfig(phase, ...rest);
|
|
65
|
+
|
|
66
|
+
return phase === DEVELOPMENT ? withLoader(config, { root }) : config;
|
|
67
|
+
};
|
|
68
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import http from "node:http";
|
|
2
|
+
import { registerHooks } from "node:module";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { BASE } from "../../protocol.ts";
|
|
5
|
+
import { CANVAS } from "../env.ts";
|
|
6
|
+
|
|
7
|
+
// Loaded with `node --import` into each process of `next dev`, which passes
|
|
8
|
+
// NODE_OPTIONS on to the server it forks. Next's server gets lienzo's loader
|
|
9
|
+
// in the config it loads, forwards the canvas and its API to lienzo's own
|
|
10
|
+
// server, and tells that server the address it listens on.
|
|
11
|
+
|
|
12
|
+
const CONFIG = fileURLToPath(new URL("./config.ts", import.meta.url));
|
|
13
|
+
|
|
14
|
+
// The module of Next that loads a project's config. It exports `loadConfig`
|
|
15
|
+
// through a getter, so a new value of the binding is what Next's server gets.
|
|
16
|
+
const LOADS_CONFIG = /[\\/]next[\\/]dist[\\/]server[\\/]config\.js$/;
|
|
17
|
+
|
|
18
|
+
registerHooks({
|
|
19
|
+
load(url, context, nextLoad) {
|
|
20
|
+
const loaded = nextLoad(url, context);
|
|
21
|
+
if (!url.startsWith("file:") || !LOADS_CONFIG.test(fileURLToPath(url))) return loaded;
|
|
22
|
+
|
|
23
|
+
const wrap = `\n;loadConfig = require(${JSON.stringify(CONFIG)}).withLienzo(loadConfig);\n`;
|
|
24
|
+
|
|
25
|
+
return { ...loaded, source: `${String(loaded.source)}${wrap}` };
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
const canvas = process.env[CANVAS]!;
|
|
30
|
+
|
|
31
|
+
function forward(request: http.IncomingMessage, response: http.ServerResponse) {
|
|
32
|
+
const out = http.request(
|
|
33
|
+
new URL(request.url!, canvas),
|
|
34
|
+
{ method: request.method, headers: request.headers },
|
|
35
|
+
(reply) => {
|
|
36
|
+
response.writeHead(reply.statusCode ?? 502, reply.headers);
|
|
37
|
+
reply.pipe(response);
|
|
38
|
+
},
|
|
39
|
+
);
|
|
40
|
+
out.on("error", (error) => {
|
|
41
|
+
response.statusCode = 502;
|
|
42
|
+
response.end(String(error));
|
|
43
|
+
});
|
|
44
|
+
request.pipe(out);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function report(server: http.Server) {
|
|
48
|
+
const address = server.address();
|
|
49
|
+
if (typeof address !== "object" || !address) return;
|
|
50
|
+
|
|
51
|
+
// A report that fails leaves `dev` to fail at its bound, not Next's server.
|
|
52
|
+
const site = `http://localhost:${address.port}/`;
|
|
53
|
+
fetch(new URL("listening", canvas), { method: "POST", body: JSON.stringify({ site }) }).catch(
|
|
54
|
+
() => undefined,
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Next's server answers every request it gets, so the canvas is taken before
|
|
59
|
+
// Next sees it.
|
|
60
|
+
const emit = http.Server.prototype.emit;
|
|
61
|
+
|
|
62
|
+
http.Server.prototype.emit = function (this: http.Server, event: string, ...args: unknown[]) {
|
|
63
|
+
if (event === "listening") report(this);
|
|
64
|
+
|
|
65
|
+
if (event === "request") {
|
|
66
|
+
const [request, response] = args as [http.IncomingMessage, http.ServerResponse];
|
|
67
|
+
if (request.url?.startsWith(BASE)) {
|
|
68
|
+
forward(request, response);
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return emit.call(this, event, ...args);
|
|
74
|
+
} as typeof emit;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { jsx } from "../../source/jsx/jsx.ts";
|
|
3
|
+
import { stamp } from "../../source/stamp.ts";
|
|
4
|
+
|
|
5
|
+
// The webpack loader that stamps a Next project's JSX, as lienzo's Vite
|
|
6
|
+
// plugin does. Turbopack runs it in a Node process of its own, so it imports
|
|
7
|
+
// nothing that needs Bun.
|
|
8
|
+
|
|
9
|
+
export type Options = { root: string };
|
|
10
|
+
|
|
11
|
+
type Context = {
|
|
12
|
+
resourcePath: string;
|
|
13
|
+
getOptions(): Options;
|
|
14
|
+
callback(error: Error | null, code: string, map?: object): void;
|
|
15
|
+
emitWarning(warning: Error): void;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export default function lienzo(this: Context, source: string): string | undefined {
|
|
19
|
+
const relative = path
|
|
20
|
+
.relative(this.getOptions().root, this.resourcePath)
|
|
21
|
+
.split(path.sep)
|
|
22
|
+
.join("/");
|
|
23
|
+
if (relative.startsWith("..") || relative.includes("node_modules/")) return source;
|
|
24
|
+
|
|
25
|
+
// A file lienzo cannot read goes to Next as it is, and Next reports the
|
|
26
|
+
// error at its own line.
|
|
27
|
+
try {
|
|
28
|
+
const stamped = stamp(jsx, relative, source);
|
|
29
|
+
if (!stamped) return source;
|
|
30
|
+
|
|
31
|
+
this.callback(null, stamped.code, stamped.map);
|
|
32
|
+
return undefined;
|
|
33
|
+
} catch (error) {
|
|
34
|
+
this.emitWarning(new Error(`left unmarked: ${error instanceof Error ? error.message : error}`));
|
|
35
|
+
return source;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { uncachedModule } from "./uncached.ts";
|
|
2
|
+
|
|
3
|
+
// Runs `nuxt dev` from the project's own Nuxt CLI, whose entry is the first
|
|
4
|
+
// argument, with lienzo's module added to the app's config. The CLI's
|
|
5
|
+
// `--extends` would replace the app's own layers, while an override's modules
|
|
6
|
+
// add to the app's modules.
|
|
7
|
+
type Cli = {
|
|
8
|
+
runCommand(name: string, argv: string[], data: { overrides: object }): Promise<unknown>;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
const [entry, ...argv] = process.argv.slice(2);
|
|
12
|
+
const cli = (await import(entry!)) as Cli;
|
|
13
|
+
|
|
14
|
+
await cli.runCommand("dev", argv, { overrides: { modules: [uncachedModule] } });
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import type { Plugin, ViteDevServer } from "vite";
|
|
3
|
+
import type { Project } from "../project/project.ts";
|
|
4
|
+
import { bridgeScript } from "../bridge/script.ts";
|
|
5
|
+
import { languageOf } from "../source/language.ts";
|
|
6
|
+
import { stamp } from "../source/stamp.ts";
|
|
7
|
+
import { middleware } from "./middleware.ts";
|
|
8
|
+
import { resend } from "./resend.ts";
|
|
9
|
+
|
|
10
|
+
// Stamps source locations on the elements of every file a language reads,
|
|
11
|
+
// while the dev server runs. A build is left alone unless `build` is set. With
|
|
12
|
+
// a project, it also serves the canvas.
|
|
13
|
+
export default function lienzo(project?: Project, { build = false } = {}): Plugin {
|
|
14
|
+
let root = "";
|
|
15
|
+
let server: ViteDevServer | undefined;
|
|
16
|
+
|
|
17
|
+
return {
|
|
18
|
+
name: "lienzo",
|
|
19
|
+
apply: (_, env) => build || env.command === "serve",
|
|
20
|
+
enforce: "pre",
|
|
21
|
+
|
|
22
|
+
// A stylesheet then carries an inline map to its source, which `rule.find`
|
|
23
|
+
// reads to name the rule the browser applies.
|
|
24
|
+
config: () => ({ css: { devSourcemap: true } }),
|
|
25
|
+
|
|
26
|
+
configResolved(config) {
|
|
27
|
+
root = config.root;
|
|
28
|
+
},
|
|
29
|
+
|
|
30
|
+
configureServer(dev) {
|
|
31
|
+
server = dev;
|
|
32
|
+
if (!project) return;
|
|
33
|
+
const client = `${dev.config.base}@vite/client`;
|
|
34
|
+
dev.middlewares.use(middleware(project, client, resend(dev.watcher)));
|
|
35
|
+
},
|
|
36
|
+
|
|
37
|
+
// The page carries the script that answers the canvas, inline, so a build
|
|
38
|
+
// on any origin has it with no request.
|
|
39
|
+
transformIndexHtml: {
|
|
40
|
+
order: "pre",
|
|
41
|
+
async handler() {
|
|
42
|
+
return [
|
|
43
|
+
{
|
|
44
|
+
tag: "script",
|
|
45
|
+
attrs: { "data-lienzo-bridge": "" },
|
|
46
|
+
children: await bridgeScript(),
|
|
47
|
+
injectTo: "head-prepend" as const,
|
|
48
|
+
},
|
|
49
|
+
];
|
|
50
|
+
},
|
|
51
|
+
},
|
|
52
|
+
|
|
53
|
+
// Before the framework's own transforms, which compile the template away:
|
|
54
|
+
// Solid's plugin and Svelte's preprocessor are `pre` too.
|
|
55
|
+
transform: {
|
|
56
|
+
order: "pre",
|
|
57
|
+
handler(code, id) {
|
|
58
|
+
// A query asks for a part of the file, as Svelte asks for a
|
|
59
|
+
// component's style, or for another form of it, as `?raw` does.
|
|
60
|
+
if (id.includes("?") || id.includes("/node_modules/")) return undefined;
|
|
61
|
+
|
|
62
|
+
const found = languageOf(id);
|
|
63
|
+
if (!found.ok) return undefined;
|
|
64
|
+
|
|
65
|
+
// Locations are relative to the project root, which a framework's
|
|
66
|
+
// Vite root may sit under: Nuxt's is the `app/` directory.
|
|
67
|
+
const relative = path
|
|
68
|
+
.relative(project?.root ?? root, id)
|
|
69
|
+
.split(path.sep)
|
|
70
|
+
.join("/");
|
|
71
|
+
if (relative.startsWith("..")) return undefined;
|
|
72
|
+
|
|
73
|
+
// A file lienzo cannot read goes to the framework as it is, and the
|
|
74
|
+
// framework reports the error at its own line.
|
|
75
|
+
try {
|
|
76
|
+
return stamp(found.language, relative, code);
|
|
77
|
+
} catch (error) {
|
|
78
|
+
this.warn(`left unmarked: ${error instanceof Error ? error.message : String(error)}`);
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
},
|
|
82
|
+
},
|
|
83
|
+
|
|
84
|
+
// A page the server renders from a module the browser never loads gets no
|
|
85
|
+
// hot update, so it reloads. Vite has invalidated the module by now.
|
|
86
|
+
hotUpdate(options) {
|
|
87
|
+
if (this.environment.config.consumer !== "server" || options.modules.length === 0) return;
|
|
88
|
+
|
|
89
|
+
const client = server?.environments.client;
|
|
90
|
+
if (!client || client.moduleGraph.getModulesByFile(options.file)?.size) return;
|
|
91
|
+
|
|
92
|
+
client.hot.send({ type: "full-reload", path: "*" });
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { plugin } from "bun";
|
|
2
|
+
import http from "node:http";
|
|
3
|
+
import type { InlineConfig, ViteDevServer } from "vite";
|
|
4
|
+
import type { Project } from "../project/project.ts";
|
|
5
|
+
import { API, type ProjectInfo } from "../protocol.ts";
|
|
6
|
+
import { BUILD, CLOSE, PORT, PROJECT } from "./env.ts";
|
|
7
|
+
import lienzo from "./plugin.ts";
|
|
8
|
+
|
|
9
|
+
// Loaded with `bun --preload` into the process that serves a project's pages:
|
|
10
|
+
// the project's own dev script, or lienzo's `vite.ts`. Every Vite server it
|
|
11
|
+
// creates gets lienzo's plugin, and the HTTP server that serves the plugin's
|
|
12
|
+
// API tells `dev` its address.
|
|
13
|
+
// When `dev` closes, the process closes those servers and exits cleanly.
|
|
14
|
+
|
|
15
|
+
type Vite = typeof import("vite");
|
|
16
|
+
|
|
17
|
+
const servers = new Set<ViteDevServer>();
|
|
18
|
+
|
|
19
|
+
// How long the servers get to close before the process exits anyway. One of
|
|
20
|
+
// the two Vite servers Nuxt creates never resolves `close()`.
|
|
21
|
+
const CLOSING = 2_000;
|
|
22
|
+
|
|
23
|
+
process.on("message", (message) => {
|
|
24
|
+
if (message !== CLOSE) return;
|
|
25
|
+
|
|
26
|
+
const closed = Promise.all([...servers].map((server) => server.close()));
|
|
27
|
+
void Promise.race([closed, Bun.sleep(CLOSING)]).then(() => process.exit(0));
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
// The address `dev` prints comes from the HTTP server that answers lienzo's
|
|
31
|
+
// API, not from Vite: a Vite server in middleware mode, as Nuxt's is, has no
|
|
32
|
+
// `httpServer`, and the server that listens may be the framework's own.
|
|
33
|
+
const listen = http.Server.prototype.listen;
|
|
34
|
+
|
|
35
|
+
if (!process.env[BUILD]) {
|
|
36
|
+
http.Server.prototype.listen = function (this: http.Server, ...args: Parameters<typeof listen>) {
|
|
37
|
+
this.once("listening", () => void report(this));
|
|
38
|
+
return listen.apply(this, args);
|
|
39
|
+
} as typeof listen;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function answers(api: URL): Promise<boolean> {
|
|
43
|
+
try {
|
|
44
|
+
const response = await fetch(api);
|
|
45
|
+
if (!response.ok) return false;
|
|
46
|
+
|
|
47
|
+
const info = (await response.json()) as Partial<ProjectInfo>;
|
|
48
|
+
return typeof info.classAttribute === "string";
|
|
49
|
+
} catch {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// A framework may listen before it mounts Vite's middleware: Nuxt shows a
|
|
55
|
+
// loading page while it builds. So the server is asked until it answers or
|
|
56
|
+
// closes, and `dev` stops a process that never answers in its bound.
|
|
57
|
+
async function report(server: http.Server) {
|
|
58
|
+
const address = server.address();
|
|
59
|
+
if (typeof address !== "object" || !address) return;
|
|
60
|
+
|
|
61
|
+
const site = `http://localhost:${address.port}/`;
|
|
62
|
+
const api = new URL(`${API}project`, site);
|
|
63
|
+
|
|
64
|
+
while (server.listening) {
|
|
65
|
+
if (await answers(api)) return void process.send?.({ site });
|
|
66
|
+
|
|
67
|
+
await Bun.sleep(250);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// The entry of any copy of Vite, so the project's own copy is the one wrapped.
|
|
72
|
+
const ENTRY = /[\\/]node_modules[\\/]vite[\\/]dist[\\/]node[\\/]index\.js$/;
|
|
73
|
+
|
|
74
|
+
export async function createServer(vite: Vite, config: InlineConfig = {}) {
|
|
75
|
+
const project = JSON.parse(process.env[PROJECT]!) as Project;
|
|
76
|
+
const port = process.env[PORT];
|
|
77
|
+
|
|
78
|
+
const server = await vite.createServer({
|
|
79
|
+
...config,
|
|
80
|
+
plugins: [...(config.plugins ?? []), lienzo(project)],
|
|
81
|
+
server:
|
|
82
|
+
port === undefined
|
|
83
|
+
? config.server
|
|
84
|
+
: { ...config.server, port: Number(port), strictPort: true },
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
servers.add(server);
|
|
88
|
+
|
|
89
|
+
return server;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Adds the stamping plugin to a build's config. Vite's CLI builds through
|
|
93
|
+
// `createBuilder`, and a script may call `build` itself.
|
|
94
|
+
export function stamped(config: InlineConfig = {}): InlineConfig {
|
|
95
|
+
const project = JSON.parse(process.env[PROJECT]!) as Project;
|
|
96
|
+
|
|
97
|
+
return { ...config, plugins: [...(config.plugins ?? []), lienzo(project, { build: true })] };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export const build = (vite: Vite, config?: InlineConfig) => vite.build(stamped(config));
|
|
101
|
+
|
|
102
|
+
export const createBuilder = (
|
|
103
|
+
vite: Vite,
|
|
104
|
+
config?: InlineConfig,
|
|
105
|
+
...rest: unknown[]
|
|
106
|
+
): ReturnType<Vite["createBuilder"]> =>
|
|
107
|
+
(vite.createBuilder as (...args: unknown[]) => ReturnType<Vite["createBuilder"]>)(
|
|
108
|
+
stamped(config),
|
|
109
|
+
...rest,
|
|
110
|
+
);
|
|
111
|
+
|
|
112
|
+
// The module the script imports as `vite`: Vite itself, with the function that
|
|
113
|
+
// starts the work this process does replaced. A query makes the import inside
|
|
114
|
+
// it load the real file, which this filter does not match.
|
|
115
|
+
function wrapper(entry: string): string {
|
|
116
|
+
const real = JSON.stringify(`${entry}?lienzo`);
|
|
117
|
+
const here = JSON.stringify(import.meta.path);
|
|
118
|
+
|
|
119
|
+
if (process.env[BUILD]) {
|
|
120
|
+
return [
|
|
121
|
+
`export * from ${real};`,
|
|
122
|
+
`import * as vite from ${real};`,
|
|
123
|
+
`import { build as b, createBuilder as c } from ${here};`,
|
|
124
|
+
`export const build = (config) => b(vite, config);`,
|
|
125
|
+
`export const createBuilder = (config, ...rest) => c(vite, config, ...rest);`,
|
|
126
|
+
].join("\n");
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
return [
|
|
130
|
+
`export * from ${real};`,
|
|
131
|
+
`import * as vite from ${real};`,
|
|
132
|
+
`import { createServer as withLienzo } from ${here};`,
|
|
133
|
+
`export const createServer = (config) => withLienzo(vite, config);`,
|
|
134
|
+
].join("\n");
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Vite's `vite build` command imports `createBuilder` from an inner chunk, not
|
|
138
|
+
// from the entry, so the entry's wrapper never sees it. This rebinds that one
|
|
139
|
+
// import in the CLI module to the stamping version.
|
|
140
|
+
const CLI = /[\\/]node_modules[\\/]vite[\\/]dist[\\/]node[\\/]cli\.js$/;
|
|
141
|
+
const CLI_IMPORT = /\b(\w+) as createBuilder\b/;
|
|
142
|
+
|
|
143
|
+
function cli(source: string): string {
|
|
144
|
+
if (!CLI_IMPORT.test(source))
|
|
145
|
+
throw new Error("lienzo build: Vite's CLI no longer imports createBuilder as expected");
|
|
146
|
+
|
|
147
|
+
const here = JSON.stringify(import.meta.path);
|
|
148
|
+
|
|
149
|
+
return [
|
|
150
|
+
`import { stamped as lienzoStamped } from ${here};`,
|
|
151
|
+
`const createBuilder = (config, ...rest) => lienzoCreateBuilder(lienzoStamped(config), ...rest);`,
|
|
152
|
+
source.replace(CLI_IMPORT, "$1 as lienzoCreateBuilder"),
|
|
153
|
+
].join("\n");
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
plugin({
|
|
157
|
+
name: "lienzo",
|
|
158
|
+
setup(build) {
|
|
159
|
+
build.onLoad({ filter: ENTRY }, ({ path }) => ({ loader: "js", contents: wrapper(path) }));
|
|
160
|
+
if (process.env[BUILD]) {
|
|
161
|
+
build.onLoad({ filter: CLI }, async ({ path }) => ({
|
|
162
|
+
loader: "js",
|
|
163
|
+
contents: cli(await Bun.file(path).text()),
|
|
164
|
+
}));
|
|
165
|
+
}
|
|
166
|
+
},
|
|
167
|
+
});
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { FSWatcher } from "vite";
|
|
2
|
+
|
|
3
|
+
// Long enough for the watcher to report a write it saw.
|
|
4
|
+
const LATE = 100;
|
|
5
|
+
|
|
6
|
+
// Vite's watcher, chokidar, drops a file's change that lands within 50 ms of
|
|
7
|
+
// the one before and never reports it later, so the page would keep the
|
|
8
|
+
// earlier text. Takes each file lienzo writes, by absolute path, and reports
|
|
9
|
+
// the change itself when the watcher stays quiet after the last write. Vite
|
|
10
|
+
// reads a file when it handles the change, so any change heard after the last
|
|
11
|
+
// write already carries that write.
|
|
12
|
+
export function resend(watcher: FSWatcher) {
|
|
13
|
+
const heard = new Map<string, number>();
|
|
14
|
+
const waiting = new Map<string, ReturnType<typeof setTimeout>>();
|
|
15
|
+
|
|
16
|
+
watcher.on("change", (file: string) => heard.set(file, performance.now()));
|
|
17
|
+
|
|
18
|
+
return (file: string) => {
|
|
19
|
+
const wrote = performance.now();
|
|
20
|
+
clearTimeout(waiting.get(file));
|
|
21
|
+
waiting.set(
|
|
22
|
+
file,
|
|
23
|
+
setTimeout(() => {
|
|
24
|
+
waiting.delete(file);
|
|
25
|
+
if ((heard.get(file) ?? -1) < wrote) watcher.emit("change", file);
|
|
26
|
+
}, LATE),
|
|
27
|
+
);
|
|
28
|
+
};
|
|
29
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { mkdir, rm } from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { loadCredentials } from "../cloud/credentials.ts";
|
|
6
|
+
import type { Params } from "../commands/command.ts";
|
|
7
|
+
import { run } from "../commands/registry.ts";
|
|
8
|
+
import type { Actor, Project } from "../project/project.ts";
|
|
9
|
+
import { ACTOR, API, type Result } from "../protocol.ts";
|
|
10
|
+
|
|
11
|
+
// The canvas `dev` serves for a project root, written where the CLI and the
|
|
12
|
+
// MCP server of the same user look for it. A command they run then goes
|
|
13
|
+
// through that server, so it joins the canvas's undo history.
|
|
14
|
+
type Announced = { canvas: string; pid: number };
|
|
15
|
+
|
|
16
|
+
function fileOf(root: string): string {
|
|
17
|
+
const runtime = process.env.XDG_RUNTIME_DIR ?? os.tmpdir();
|
|
18
|
+
const key = createHash("sha256").update(root).digest("hex").slice(0, 16);
|
|
19
|
+
|
|
20
|
+
return path.join(runtime, "lienzo", `${key}.json`);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function alive(pid: number): boolean {
|
|
24
|
+
try {
|
|
25
|
+
process.kill(pid, 0);
|
|
26
|
+
return true;
|
|
27
|
+
} catch {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// The canvas a live `dev` process serves for the root. A file left by a
|
|
33
|
+
// process that died is removed.
|
|
34
|
+
export async function canvasOf(root: string): Promise<string | undefined> {
|
|
35
|
+
const file = Bun.file(fileOf(root));
|
|
36
|
+
if (!(await file.exists())) return undefined;
|
|
37
|
+
|
|
38
|
+
const announced = (await file.json()) as Announced;
|
|
39
|
+
if (alive(announced.pid)) return announced.canvas;
|
|
40
|
+
|
|
41
|
+
await rm(fileOf(root), { force: true });
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// One root has one canvas, so a second `dev` would split the undo history.
|
|
46
|
+
export async function ensureVacant(root: string): Promise<void> {
|
|
47
|
+
const serving = await canvasOf(root);
|
|
48
|
+
if (serving !== undefined) throw new Error(`lienzo already serves ${root} at ${serving}`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Names the canvas for the root until the returned function is called.
|
|
52
|
+
export async function announce(root: string, canvas: string): Promise<() => Promise<void>> {
|
|
53
|
+
await ensureVacant(root);
|
|
54
|
+
|
|
55
|
+
const file = fileOf(root);
|
|
56
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
57
|
+
await Bun.write(file, JSON.stringify({ canvas, pid: process.pid } satisfies Announced));
|
|
58
|
+
|
|
59
|
+
return async () => {
|
|
60
|
+
if ((await canvasOf(root)) === canvas) await rm(file, { force: true });
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// The saved `lienzo login` token, for a canvas on a host beside the edge. A
|
|
65
|
+
// session host opens for its owner's token; no other host sees it.
|
|
66
|
+
async function signedIn(canvas: string, home: string): Promise<Record<string, string>> {
|
|
67
|
+
const credentials = await loadCredentials(home);
|
|
68
|
+
if (!credentials) return {};
|
|
69
|
+
|
|
70
|
+
const site = new URL(credentials.edge).hostname.split(".").slice(1).join(".");
|
|
71
|
+
const host = new URL(canvas).hostname;
|
|
72
|
+
|
|
73
|
+
return site !== "" && host.endsWith(`.${site}`)
|
|
74
|
+
? { authorization: `Bearer ${credentials.token}` }
|
|
75
|
+
: {};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Runs a command on the canvas at this address, so it joins that canvas's undo
|
|
79
|
+
// history and shows in its Changes tab. The canvas may be on another machine,
|
|
80
|
+
// such as a hosted session.
|
|
81
|
+
export async function runOn(
|
|
82
|
+
canvas: string,
|
|
83
|
+
name: string,
|
|
84
|
+
params: Params,
|
|
85
|
+
home = os.homedir(),
|
|
86
|
+
by: Actor = "human",
|
|
87
|
+
): Promise<Result> {
|
|
88
|
+
const response = await fetch(new URL(`${API}run`, canvas), {
|
|
89
|
+
method: "POST",
|
|
90
|
+
headers: {
|
|
91
|
+
"content-type": "application/json",
|
|
92
|
+
...(by === "agent" ? { [ACTOR]: "agent" } : {}),
|
|
93
|
+
...(await signedIn(canvas, home)),
|
|
94
|
+
},
|
|
95
|
+
body: JSON.stringify({ name, params }),
|
|
96
|
+
});
|
|
97
|
+
if (!response.ok) throw new Error(`${canvas} answered ${response.status}`);
|
|
98
|
+
|
|
99
|
+
return (await response.json()) as Result;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Runs a command on the canvas that serves the project, or in this process
|
|
103
|
+
// when none does.
|
|
104
|
+
export async function runCommand(
|
|
105
|
+
project: Project,
|
|
106
|
+
name: string,
|
|
107
|
+
params: Params,
|
|
108
|
+
by: Actor = "human",
|
|
109
|
+
): Promise<Result> {
|
|
110
|
+
const canvas = await canvasOf(project.root);
|
|
111
|
+
|
|
112
|
+
return canvas === undefined
|
|
113
|
+
? run(project, name, params)
|
|
114
|
+
: runOn(canvas, name, params, undefined, by);
|
|
115
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { mkdir } from "node:fs/promises";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import type { FrameData } from "../protocol.ts";
|
|
5
|
+
|
|
6
|
+
// Draws a frame's page in headless Chrome at the frame's size and writes it as
|
|
7
|
+
// a PNG in the system's temporary directory. The page is drawn as it loads, at
|
|
8
|
+
// the top, not as the canvas has scrolled it.
|
|
9
|
+
export async function screenshot(frame: FrameData): Promise<string> {
|
|
10
|
+
const folder = path.join(os.tmpdir(), "lienzo", "screenshots");
|
|
11
|
+
const file = path.join(folder, `${frame.id}-${Date.now()}.png`);
|
|
12
|
+
await mkdir(folder, { recursive: true });
|
|
13
|
+
|
|
14
|
+
// Loaded here, since every command that does not draw would pay for it.
|
|
15
|
+
const { chromium } = await import("playwright-core");
|
|
16
|
+
const browser = await chromium.launch({ channel: "chrome" });
|
|
17
|
+
try {
|
|
18
|
+
const page = await browser.newPage({ viewport: { width: frame.width, height: frame.height } });
|
|
19
|
+
await page.goto(frame.url, { waitUntil: "load" });
|
|
20
|
+
await page.screenshot({ path: file });
|
|
21
|
+
} finally {
|
|
22
|
+
await browser.close();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
return file;
|
|
26
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { watch, type FSWatcher } from "node:fs";
|
|
2
|
+
|
|
3
|
+
// How long a file stays quiet before the canvas hears it changed. A save can
|
|
4
|
+
// write a file in more than one step.
|
|
5
|
+
const QUIET = 50;
|
|
6
|
+
|
|
7
|
+
// Follows the files the commands read, by absolute path, and calls `changed`
|
|
8
|
+
// once they settle after a write, whoever made it. The page cannot tell the
|
|
9
|
+
// canvas: Vite leaves a stylesheet alone when its text is what the page holds,
|
|
10
|
+
// and its watcher drops a write that lands right after another.
|
|
11
|
+
export function sources(changed: () => void) {
|
|
12
|
+
const followed = new Map<string, FSWatcher>();
|
|
13
|
+
let quiet: ReturnType<typeof setTimeout> | undefined;
|
|
14
|
+
|
|
15
|
+
function settle() {
|
|
16
|
+
clearTimeout(quiet);
|
|
17
|
+
quiet = setTimeout(changed, QUIET);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function forget(file: string) {
|
|
21
|
+
followed.get(file)?.close();
|
|
22
|
+
followed.delete(file);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function follow(file: string) {
|
|
26
|
+
if (followed.has(file)) return;
|
|
27
|
+
|
|
28
|
+
// A save that replaces the file leaves the watcher on the old one. The
|
|
29
|
+
// read the change prompts follows the new one.
|
|
30
|
+
let watcher: FSWatcher;
|
|
31
|
+
try {
|
|
32
|
+
watcher = watch(file, (event) => {
|
|
33
|
+
if (event === "rename") forget(file);
|
|
34
|
+
settle();
|
|
35
|
+
});
|
|
36
|
+
} catch {
|
|
37
|
+
// Gone since the command read it. Its next read follows it again.
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
watcher.on("error", () => forget(file));
|
|
41
|
+
watcher.unref();
|
|
42
|
+
followed.set(file, watcher);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return { follow };
|
|
46
|
+
}
|