@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,66 @@
|
|
|
1
|
+
import type { Result } from "../protocol.ts";
|
|
2
|
+
import { need, type Command } from "./command.ts";
|
|
3
|
+
import { commitStaged, digest, stage, type Call, type Dispatch } from "./stage.ts";
|
|
4
|
+
|
|
5
|
+
function callsOf(text: string): Call[] {
|
|
6
|
+
const parsed: unknown = JSON.parse(text);
|
|
7
|
+
if (!Array.isArray(parsed) || parsed.length === 0) {
|
|
8
|
+
throw new Error("calls is a JSON array of one or more { name, params }");
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
return parsed.map((entry) => {
|
|
12
|
+
const { name, params } = entry as { name?: unknown; params?: unknown };
|
|
13
|
+
if (typeof name !== "string" || typeof params !== "object" || params === null) {
|
|
14
|
+
throw new Error("each call is { name, params }");
|
|
15
|
+
}
|
|
16
|
+
if (name === "transaction") throw new Error("a transaction does not hold another");
|
|
17
|
+
|
|
18
|
+
return { name, params: params as Call["params"] };
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// What the edit log keeps of a staged call list: per file, the digest of its
|
|
23
|
+
// text before the first call and after the last.
|
|
24
|
+
function filesOf(changes: { file: string; before: string; after: string }[]) {
|
|
25
|
+
const files = new Map<string, { file: string; before: string; after: string }>();
|
|
26
|
+
for (const change of changes) {
|
|
27
|
+
const known = files.get(change.file);
|
|
28
|
+
files.set(change.file, {
|
|
29
|
+
file: change.file,
|
|
30
|
+
before: known?.before ?? digest(change.before),
|
|
31
|
+
after: digest(change.after),
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return [...files.values()];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const CALLS = "a JSON array of { name, params }, run in order";
|
|
39
|
+
|
|
40
|
+
export function touchesOf(dispatch: Dispatch): Command {
|
|
41
|
+
return {
|
|
42
|
+
name: "touches",
|
|
43
|
+
does: "Runs calls without writing and lists the files they would change, with the digest of each file's text before and after.",
|
|
44
|
+
params: { calls: CALLS },
|
|
45
|
+
async run(project, params): Promise<Result> {
|
|
46
|
+
const staged = await stage(project, callsOf(need(params, "calls")), dispatch);
|
|
47
|
+
if (!staged.ok) return staged;
|
|
48
|
+
|
|
49
|
+
return { ok: true, changed: [], data: filesOf(staged.changes) };
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function transactionOf(dispatch: Dispatch): Command {
|
|
55
|
+
return {
|
|
56
|
+
name: "transaction",
|
|
57
|
+
does: "Runs calls as one edit. If one is refused, nothing is written. Otherwise every file is written and undo steps back over each call.",
|
|
58
|
+
params: { calls: CALLS },
|
|
59
|
+
async run(project, params): Promise<Result> {
|
|
60
|
+
const staged = await stage(project, callsOf(need(params, "calls")), dispatch);
|
|
61
|
+
if (!staged.ok) return staged;
|
|
62
|
+
|
|
63
|
+
return await commitStaged(project, staged.changes);
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { chmod, mkdtemp, rm } from "node:fs/promises";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { diskStore, type Store } from "../capture/manifest.ts";
|
|
5
|
+
import type { Done, Job, Runner } from "./job.ts";
|
|
6
|
+
|
|
7
|
+
type Options = {
|
|
8
|
+
// The image `lienzo job` runs in: the Dockerfile's `job` target, its default.
|
|
9
|
+
image: string;
|
|
10
|
+
|
|
11
|
+
// Stops a job that runs longer, in milliseconds.
|
|
12
|
+
timeout?: number;
|
|
13
|
+
|
|
14
|
+
memory?: string;
|
|
15
|
+
cpus?: string;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
// The arguments of the `docker run` for a job. The container gets no
|
|
19
|
+
// environment, no capabilities and a bounded process count, memory and CPU.
|
|
20
|
+
// It keeps the default network, because install reaches the package registry.
|
|
21
|
+
export function runArgs(
|
|
22
|
+
name: string,
|
|
23
|
+
folder: string,
|
|
24
|
+
job: Job,
|
|
25
|
+
{ image, memory = "4g", cpus = "2" }: Options,
|
|
26
|
+
): string[] {
|
|
27
|
+
return [
|
|
28
|
+
"run",
|
|
29
|
+
"--rm",
|
|
30
|
+
"--name",
|
|
31
|
+
name,
|
|
32
|
+
"--memory",
|
|
33
|
+
memory,
|
|
34
|
+
"--cpus",
|
|
35
|
+
cpus,
|
|
36
|
+
"--pids-limit",
|
|
37
|
+
"1024",
|
|
38
|
+
"--cap-drop",
|
|
39
|
+
"ALL",
|
|
40
|
+
"--security-opt",
|
|
41
|
+
"no-new-privileges",
|
|
42
|
+
"-v",
|
|
43
|
+
`${folder}:/store`,
|
|
44
|
+
image,
|
|
45
|
+
"lienzo",
|
|
46
|
+
"job",
|
|
47
|
+
"--root",
|
|
48
|
+
"/store",
|
|
49
|
+
"--repo",
|
|
50
|
+
job.repo,
|
|
51
|
+
"--sha",
|
|
52
|
+
job.sha,
|
|
53
|
+
"--steps",
|
|
54
|
+
JSON.stringify(job.steps ?? []),
|
|
55
|
+
];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function docker(args: string[]): Promise<{ code: number; out: string; err: string }> {
|
|
59
|
+
const child = Bun.spawn(["docker", ...args], { stdout: "pipe", stderr: "pipe" });
|
|
60
|
+
const [out, err, code] = await Promise.all([
|
|
61
|
+
new Response(child.stdout).text(),
|
|
62
|
+
new Response(child.stderr).text(),
|
|
63
|
+
child.exited,
|
|
64
|
+
]);
|
|
65
|
+
|
|
66
|
+
return { code, out: out.trim(), err: err.trim() };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Copies a manifest and the PNGs it names from one store to another.
|
|
70
|
+
async function copy(from: Store, to: Store, commit: string): Promise<Done> {
|
|
71
|
+
const manifest = await from.getManifest(commit);
|
|
72
|
+
if (!manifest) return { ok: false, reason: `the job left no capture of ${commit}` };
|
|
73
|
+
|
|
74
|
+
for (const frame of Object.values(manifest.frames)) {
|
|
75
|
+
const bytes = await from.getBlob(frame.png);
|
|
76
|
+
if (!bytes) return { ok: false, reason: `the job left no PNG ${frame.png}` };
|
|
77
|
+
await to.putBlob(bytes);
|
|
78
|
+
}
|
|
79
|
+
await to.putManifest(manifest);
|
|
80
|
+
|
|
81
|
+
return { ok: true, manifest };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Runs each job in its own container. The repository must be one the
|
|
85
|
+
// container can clone, such as an https URL.
|
|
86
|
+
export function dockerRunner(options: Options): Runner {
|
|
87
|
+
const { timeout = 15 * 60 * 1000 } = options;
|
|
88
|
+
|
|
89
|
+
return {
|
|
90
|
+
async run(job, store) {
|
|
91
|
+
const folder = await mkdtemp(path.join(os.tmpdir(), "lienzo-job-"));
|
|
92
|
+
// The container's user is not the host's, and the folder holds one job.
|
|
93
|
+
await chmod(folder, 0o777);
|
|
94
|
+
const name = `lienzo-job-${path.basename(folder)}`;
|
|
95
|
+
|
|
96
|
+
try {
|
|
97
|
+
const ran = docker(runArgs(name, folder, job, options));
|
|
98
|
+
const timer = setTimeout(() => void docker(["kill", name]), timeout);
|
|
99
|
+
const { code, out, err } = await ran.finally(() => clearTimeout(timer));
|
|
100
|
+
|
|
101
|
+
if (code !== 0) return { ok: false, reason: err || `docker exited ${code}` };
|
|
102
|
+
|
|
103
|
+
return await copy(diskStore(folder), store, out.split("\n").at(-1)!);
|
|
104
|
+
} finally {
|
|
105
|
+
await rm(folder, { recursive: true, force: true });
|
|
106
|
+
}
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
}
|
package/src/job/job.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { mkdir, mkdtemp, rm } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import type { Params } from "../commands/command.ts";
|
|
4
|
+
import { run } from "../commands/registry.ts";
|
|
5
|
+
import { snap } from "../capture/snap.ts";
|
|
6
|
+
import type { Manifest, Store } from "../capture/manifest.ts";
|
|
7
|
+
import { loadConfig } from "../project/config.ts";
|
|
8
|
+
import { loadProject } from "../project/project.ts";
|
|
9
|
+
import { installOf } from "../sandbox/install.ts";
|
|
10
|
+
|
|
11
|
+
// A command applied to the source before it is captured.
|
|
12
|
+
export type Step = { name: string; params: Params };
|
|
13
|
+
|
|
14
|
+
// What a runner does: the repository at a commit, with the steps applied,
|
|
15
|
+
// built and captured. The same job gives the same capture, so a runner on a
|
|
16
|
+
// laptop, in Docker or in a Cloudflare container is interchangeable.
|
|
17
|
+
export type Job = { repo: string; sha: string; steps?: Step[] };
|
|
18
|
+
|
|
19
|
+
// A file the steps changed, as it reads after them.
|
|
20
|
+
export type Change = { path: string; content: string };
|
|
21
|
+
|
|
22
|
+
// `changed` is what a pull request must commit to reproduce the capture. The
|
|
23
|
+
// Docker runner copies a capture between stores and cannot say, so it omits it.
|
|
24
|
+
export type Done =
|
|
25
|
+
| { ok: true; manifest: Manifest; changed?: Change[] }
|
|
26
|
+
| { ok: false; reason: string };
|
|
27
|
+
|
|
28
|
+
export interface Runner {
|
|
29
|
+
run(job: Job, store: Store): Promise<Done>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
type Options = {
|
|
33
|
+
// Where clones are made. Each job gets a fresh folder and removes it.
|
|
34
|
+
work: string;
|
|
35
|
+
|
|
36
|
+
// Installs the project's dependencies in a clone. Defaults to the project's
|
|
37
|
+
// lockfile install.
|
|
38
|
+
install?: (root: string) => Promise<void>;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
async function exec(cwd: string, command: string[], env: Record<string, string> = {}) {
|
|
42
|
+
const child = Bun.spawn(command, {
|
|
43
|
+
cwd,
|
|
44
|
+
env: { ...process.env, ...env },
|
|
45
|
+
stdout: "ignore",
|
|
46
|
+
stderr: "pipe",
|
|
47
|
+
});
|
|
48
|
+
const [error, code] = await Promise.all([new Response(child.stderr).text(), child.exited]);
|
|
49
|
+
if (code !== 0) throw new Error(`${command.join(" ")} exited ${code}: ${error.trim()}`);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function installFrom(root: string): Promise<void> {
|
|
53
|
+
const { command, cwd } = await installOf(root, (await loadConfig(root)).install);
|
|
54
|
+
// A package registry sometimes serves a truncated tarball; the second try gets a whole one.
|
|
55
|
+
await exec(cwd, ["sh", "-c", command]).catch(() => exec(cwd, ["sh", "-c", command]));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// The files that differ from the checkout, new ones included and ignored ones
|
|
59
|
+
// not, read as text. A deleted file is left out: a proposal commits content.
|
|
60
|
+
export async function changesOf(dir: string): Promise<Change[]> {
|
|
61
|
+
const listing = ["git", "ls-files", "--modified", "--others", "--exclude-standard", "-z"];
|
|
62
|
+
const child = Bun.spawn(listing, { cwd: dir, stdout: "pipe" });
|
|
63
|
+
const names = (await new Response(child.stdout).text()).split("\0").filter(Boolean).sort();
|
|
64
|
+
const files = await Promise.all(
|
|
65
|
+
names.map(async (name) => {
|
|
66
|
+
const file = Bun.file(path.join(dir, name));
|
|
67
|
+
|
|
68
|
+
return (await file.exists()) ? { path: name, content: await file.text() } : undefined;
|
|
69
|
+
}),
|
|
70
|
+
);
|
|
71
|
+
|
|
72
|
+
return files.filter((file) => file !== undefined);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Fixed, so that the same steps on the same commit make the same commit.
|
|
76
|
+
const AUTHOR = {
|
|
77
|
+
GIT_AUTHOR_NAME: "lienzo",
|
|
78
|
+
GIT_AUTHOR_EMAIL: "lienzo@localhost",
|
|
79
|
+
GIT_AUTHOR_DATE: "2000-01-01T00:00:00Z",
|
|
80
|
+
GIT_COMMITTER_NAME: "lienzo",
|
|
81
|
+
GIT_COMMITTER_EMAIL: "lienzo@localhost",
|
|
82
|
+
GIT_COMMITTER_DATE: "2000-01-01T00:00:00Z",
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
// A fresh clone of the repository under `work`, checked out at the commit.
|
|
86
|
+
export async function cloneAt(work: string, repo: string, sha: string): Promise<string> {
|
|
87
|
+
await mkdir(work, { recursive: true });
|
|
88
|
+
const dir = await mkdtemp(path.join(work, "job-"));
|
|
89
|
+
try {
|
|
90
|
+
await exec(work, ["git", "clone", "-q", "--no-checkout", repo, dir]);
|
|
91
|
+
await exec(dir, ["git", "checkout", "-q", "--detach", sha]);
|
|
92
|
+
} catch (error) {
|
|
93
|
+
await rm(dir, { recursive: true, force: true });
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
return dir;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Runs jobs on this machine, in a clone under `work`.
|
|
101
|
+
export function localRunner({ work, install = installFrom }: Options): Runner {
|
|
102
|
+
return {
|
|
103
|
+
async run(job, store) {
|
|
104
|
+
const dir = await cloneAt(work, job.repo, job.sha);
|
|
105
|
+
try {
|
|
106
|
+
const project = await loadProject(dir);
|
|
107
|
+
for (const step of job.steps ?? []) {
|
|
108
|
+
const result = await run(project, step.name, step.params);
|
|
109
|
+
if (!result.ok) return { ok: false, reason: `step ${step.name}: ${result.reason}` };
|
|
110
|
+
}
|
|
111
|
+
const changed = await changesOf(dir);
|
|
112
|
+
if ((job.steps ?? []).length > 0) {
|
|
113
|
+
await exec(dir, ["git", "commit", "-q", "-a", "--allow-empty", "-m", "steps"], AUTHOR);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
await install(dir);
|
|
117
|
+
const snapped = await snap(project, store);
|
|
118
|
+
|
|
119
|
+
return snapped.ok ? { ...snapped, changed } : snapped;
|
|
120
|
+
} finally {
|
|
121
|
+
await rm(dir, { recursive: true, force: true });
|
|
122
|
+
}
|
|
123
|
+
},
|
|
124
|
+
};
|
|
125
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { Manifest, Store } from "../capture/store.ts";
|
|
2
|
+
import type { Job, Runner } from "./job.ts";
|
|
3
|
+
|
|
4
|
+
// A job runner behind HTTP, for a container that holds no credentials:
|
|
5
|
+
//
|
|
6
|
+
// POST /run body: Job JSON -> {ok: true, commit} or {ok: false, reason}
|
|
7
|
+
// GET /manifests/<sha> -> the Manifest the job stored
|
|
8
|
+
// GET /blobs/<hash> -> a PNG the job stored
|
|
9
|
+
//
|
|
10
|
+
// The caller runs the job, then reads the capture out and files it where it
|
|
11
|
+
// keeps captures. Jobs run one at a time.
|
|
12
|
+
export function jobServer(runner: Runner, store: Store, port: number) {
|
|
13
|
+
let running: Promise<unknown> = Promise.resolve();
|
|
14
|
+
|
|
15
|
+
return Bun.serve({
|
|
16
|
+
port,
|
|
17
|
+
idleTimeout: 0,
|
|
18
|
+
async fetch(request) {
|
|
19
|
+
const [, kind, id] = new URL(request.url).pathname.split("/");
|
|
20
|
+
|
|
21
|
+
if (request.method === "POST" && kind === "run") {
|
|
22
|
+
const { token, ...job } = (await request.json()) as Job & { token?: string };
|
|
23
|
+
const authed = token
|
|
24
|
+
? { ...job, repo: job.repo.replace("https://", `https://x-access-token:${token}@`) }
|
|
25
|
+
: job;
|
|
26
|
+
const done = running.then(() => runner.run(authed, store));
|
|
27
|
+
running = done.catch(() => {});
|
|
28
|
+
// Git echoes the clone URL, so a reason must not carry the token out.
|
|
29
|
+
const hide = (reason: string) => (token ? reason.replaceAll(token, "***") : reason);
|
|
30
|
+
const result = await done.catch((error: unknown) => ({
|
|
31
|
+
ok: false as const,
|
|
32
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
33
|
+
}));
|
|
34
|
+
if (!result.ok) result.reason = hide(result.reason);
|
|
35
|
+
|
|
36
|
+
return result.ok
|
|
37
|
+
? Response.json({
|
|
38
|
+
ok: true,
|
|
39
|
+
commit: result.manifest.commit,
|
|
40
|
+
changed: result.changed,
|
|
41
|
+
})
|
|
42
|
+
: Response.json(result, { status: 422 });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
if (request.method === "GET" && kind === "manifests" && id) {
|
|
46
|
+
const manifest: Manifest | undefined = await store.getManifest(id);
|
|
47
|
+
return manifest
|
|
48
|
+
? Response.json(manifest)
|
|
49
|
+
: new Response("no such manifest", { status: 404 });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (request.method === "GET" && kind === "blobs" && id) {
|
|
53
|
+
const bytes = await store.getBlob(id);
|
|
54
|
+
return bytes
|
|
55
|
+
? new Response(new Uint8Array(bytes))
|
|
56
|
+
: new Response("no such blob", { status: 404 });
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return new Response("not found", { status: 404 });
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import type { Attrs, Child, Op, Packet, Snapshot, Tree } from "./wire.ts";
|
|
2
|
+
|
|
3
|
+
export const KEEP = "data-lz-keep";
|
|
4
|
+
const ADOPTED = "data-lz-adopted";
|
|
5
|
+
const XLINK = "http://www.w3.org/1999/xlink";
|
|
6
|
+
|
|
7
|
+
function setAttribute(element: Element, name: string, value: string) {
|
|
8
|
+
if (name.startsWith("xlink:")) element.setAttributeNS(XLINK, name, value);
|
|
9
|
+
else element.setAttribute(name, value);
|
|
10
|
+
|
|
11
|
+
if (element instanceof HTMLInputElement && name === "value") element.value = value;
|
|
12
|
+
if (element instanceof HTMLInputElement && name === "checked") element.checked = true;
|
|
13
|
+
if (element instanceof HTMLOptionElement && name === "selected") element.selected = true;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function removeAttribute(element: Element, name: string) {
|
|
17
|
+
element.removeAttribute(name);
|
|
18
|
+
|
|
19
|
+
if (element instanceof HTMLInputElement && name === "checked") element.checked = false;
|
|
20
|
+
if (element instanceof HTMLOptionElement && name === "selected") element.selected = false;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export class Mirror {
|
|
24
|
+
#nodes = new Map<number, Node>();
|
|
25
|
+
|
|
26
|
+
constructor(private readonly page: Document) {}
|
|
27
|
+
|
|
28
|
+
apply(packet: Packet): void {
|
|
29
|
+
if (packet.kind === "snapshot") this.#snapshot(packet);
|
|
30
|
+
else for (const op of packet.ops) this.#op(op);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
#snapshot({ root, adopted }: Snapshot) {
|
|
34
|
+
const html = this.page.documentElement;
|
|
35
|
+
this.#nodes.clear();
|
|
36
|
+
this.#nodes.set(root.i, html);
|
|
37
|
+
|
|
38
|
+
for (const { name } of [...html.attributes]) html.removeAttribute(name);
|
|
39
|
+
if ("t" in root) {
|
|
40
|
+
this.#attributes(html, root.a);
|
|
41
|
+
for (const part of root.c) this.#part(part);
|
|
42
|
+
}
|
|
43
|
+
this.#adopt(adopted);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
#part(part: Tree) {
|
|
47
|
+
if (!("t" in part)) return;
|
|
48
|
+
const own = part.t === "head" ? this.page.head : part.t === "body" ? this.page.body : undefined;
|
|
49
|
+
if (!own) return;
|
|
50
|
+
|
|
51
|
+
this.#nodes.set(part.i, own);
|
|
52
|
+
for (const { name } of [...own.attributes]) own.removeAttribute(name);
|
|
53
|
+
this.#attributes(own, part.a);
|
|
54
|
+
this.#children(own, part.c);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
#attributes(element: Element, attrs: Attrs) {
|
|
58
|
+
for (const [name, value] of attrs) setAttribute(element, name, value);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
#build(tree: Tree): Node {
|
|
62
|
+
if ("x" in tree) {
|
|
63
|
+
const text = this.page.createTextNode(tree.x);
|
|
64
|
+
this.#nodes.set(tree.i, text);
|
|
65
|
+
|
|
66
|
+
return text;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const element = tree.n
|
|
70
|
+
? this.page.createElementNS(tree.n, tree.t)
|
|
71
|
+
: this.page.createElement(tree.t);
|
|
72
|
+
this.#nodes.set(tree.i, element);
|
|
73
|
+
this.#attributes(element, tree.a);
|
|
74
|
+
element.append(...tree.c.map((child) => this.#build(child)));
|
|
75
|
+
|
|
76
|
+
return element;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
#children(parent: Element, list: Child[]) {
|
|
80
|
+
const kept =
|
|
81
|
+
parent === this.page.head ? [...this.page.head.querySelectorAll(`:scope > [${KEEP}]`)] : [];
|
|
82
|
+
const adopted =
|
|
83
|
+
parent === this.page.head
|
|
84
|
+
? [...this.page.head.querySelectorAll(`:scope > [${ADOPTED}]`)]
|
|
85
|
+
: [];
|
|
86
|
+
|
|
87
|
+
parent.replaceChildren(
|
|
88
|
+
...kept,
|
|
89
|
+
...list
|
|
90
|
+
.map((child) => ("ref" in child ? this.#nodes.get(child.ref) : this.#build(child)))
|
|
91
|
+
.filter((node) => node !== undefined),
|
|
92
|
+
...adopted,
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
#adopt(sheets: string[]) {
|
|
97
|
+
for (const old of this.page.head.querySelectorAll(`:scope > [${ADOPTED}]`)) old.remove();
|
|
98
|
+
for (const rules of sheets) {
|
|
99
|
+
const style = this.page.createElement("style");
|
|
100
|
+
style.setAttribute(ADOPTED, "");
|
|
101
|
+
style.textContent = rules;
|
|
102
|
+
this.page.head.append(style);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
#op(op: Op) {
|
|
107
|
+
if (op.op === "adopted") return this.#adopt(op.sheets);
|
|
108
|
+
|
|
109
|
+
const node = this.#nodes.get(op.i);
|
|
110
|
+
if (!node) return;
|
|
111
|
+
|
|
112
|
+
if (op.op === "children") {
|
|
113
|
+
if (node instanceof Element) this.#children(node, op.list);
|
|
114
|
+
} else if (op.op === "text") node.textContent = op.x;
|
|
115
|
+
else if (op.op === "css") node.textContent = op.x;
|
|
116
|
+
else if (node instanceof Element) {
|
|
117
|
+
if (op.value === null) removeAttribute(node, op.name);
|
|
118
|
+
else setAttribute(node, op.name, op.value);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import type { Browser, Page } from "playwright-core";
|
|
2
|
+
import { launch } from "../capture/capture.ts";
|
|
3
|
+
import { observerScript } from "./script.ts";
|
|
4
|
+
import type { Delivery, Order } from "./transport.ts";
|
|
5
|
+
|
|
6
|
+
export type FrameKey = { path: string; width: number; height: number };
|
|
7
|
+
|
|
8
|
+
const KEY = /^(\d{1,5})x(\d{1,5}):(\/.*)$/;
|
|
9
|
+
|
|
10
|
+
export const keyOf = ({ width, height, path }: FrameKey) => `${width}x${height}:${path}`;
|
|
11
|
+
|
|
12
|
+
export function parseKey(key: string): FrameKey | undefined {
|
|
13
|
+
const match = KEY.exec(key);
|
|
14
|
+
|
|
15
|
+
return match ? { width: Number(match[1]), height: Number(match[2]), path: match[3]! } : undefined;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
type Options = {
|
|
19
|
+
site: string;
|
|
20
|
+
send: (delivery: Delivery) => void;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export class MirrorHost {
|
|
24
|
+
readonly #pages = new Map<string, Promise<Page>>();
|
|
25
|
+
#browser: Promise<Browser> | undefined;
|
|
26
|
+
|
|
27
|
+
constructor(private readonly options: Options) {}
|
|
28
|
+
|
|
29
|
+
order(order: Order): void {
|
|
30
|
+
if ("watch" in order) void this.#watch(order.watch);
|
|
31
|
+
else void this.#unwatch(order.unwatch);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async close(): Promise<void> {
|
|
35
|
+
await Promise.all([...this.#pages.keys()].map((key) => this.#unwatch(key)));
|
|
36
|
+
await (await this.#browser)?.close();
|
|
37
|
+
this.#browser = undefined;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async #watch(key: string) {
|
|
41
|
+
const frame = parseKey(key);
|
|
42
|
+
if (!frame) return;
|
|
43
|
+
await this.#unwatch(key);
|
|
44
|
+
|
|
45
|
+
const opened = this.#open(key, frame);
|
|
46
|
+
this.#pages.set(key, opened);
|
|
47
|
+
await opened.catch(() => this.#pages.delete(key));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async #open(key: string, { path, width, height }: FrameKey): Promise<Page> {
|
|
51
|
+
this.#browser ??= launch();
|
|
52
|
+
const page = await (await this.#browser).newPage({ viewport: { width, height } });
|
|
53
|
+
|
|
54
|
+
await page.exposeFunction("__lzEmit", (packet: string) => {
|
|
55
|
+
this.options.send({ frame: key, packet: JSON.parse(packet) });
|
|
56
|
+
});
|
|
57
|
+
await page.goto(new URL(path, this.options.site).href, { waitUntil: "load" });
|
|
58
|
+
await page.evaluate(await observerScript());
|
|
59
|
+
|
|
60
|
+
return page;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async #unwatch(key: string) {
|
|
64
|
+
const page = this.#pages.get(key);
|
|
65
|
+
this.#pages.delete(key);
|
|
66
|
+
await (await page?.catch(() => undefined))?.close();
|
|
67
|
+
}
|
|
68
|
+
}
|