@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.
Files changed (122) hide show
  1. package/README.md +82 -2
  2. package/dist/shell/assets/index-Cna8wlzF.js +4 -0
  3. package/dist/shell/assets/index-CoJSASvW.css +2 -0
  4. package/dist/shell/index.html +13 -0
  5. package/package.json +76 -4
  6. package/src/bench/bench.ts +132 -0
  7. package/src/bridge/page.ts +443 -0
  8. package/src/bridge/protocol.ts +124 -0
  9. package/src/bridge/record.ts +75 -0
  10. package/src/bridge/script.ts +24 -0
  11. package/src/bridge/state.ts +143 -0
  12. package/src/capture/capture.ts +125 -0
  13. package/src/capture/compare.ts +46 -0
  14. package/src/capture/diff.ts +16 -0
  15. package/src/capture/manifest.ts +60 -0
  16. package/src/capture/refs.ts +20 -0
  17. package/src/capture/replay.ts +25 -0
  18. package/src/capture/review.ts +78 -0
  19. package/src/capture/serve.ts +32 -0
  20. package/src/capture/snap.ts +62 -0
  21. package/src/capture/store.ts +28 -0
  22. package/src/cli.ts +287 -0
  23. package/src/cloud/checkout.ts +33 -0
  24. package/src/cloud/credentials.ts +25 -0
  25. package/src/cloud/link.ts +60 -0
  26. package/src/cloud/login.ts +85 -0
  27. package/src/commands/canvas.ts +46 -0
  28. package/src/commands/change.ts +218 -0
  29. package/src/commands/class.ts +66 -0
  30. package/src/commands/command.ts +27 -0
  31. package/src/commands/create.ts +95 -0
  32. package/src/commands/element.ts +118 -0
  33. package/src/commands/file.ts +96 -0
  34. package/src/commands/frame.ts +58 -0
  35. package/src/commands/override.ts +38 -0
  36. package/src/commands/prop.ts +18 -0
  37. package/src/commands/registry.ts +76 -0
  38. package/src/commands/rule.ts +131 -0
  39. package/src/commands/stage.ts +52 -0
  40. package/src/commands/story.ts +112 -0
  41. package/src/commands/style.ts +123 -0
  42. package/src/commands/text.ts +17 -0
  43. package/src/commands/token.ts +60 -0
  44. package/src/commands/transaction.ts +66 -0
  45. package/src/job/docker.ts +109 -0
  46. package/src/job/job.ts +125 -0
  47. package/src/job/server.ts +62 -0
  48. package/src/mirror/apply.ts +121 -0
  49. package/src/mirror/entry.ts +7 -0
  50. package/src/mirror/host.ts +68 -0
  51. package/src/mirror/observe.ts +271 -0
  52. package/src/mirror/script.ts +18 -0
  53. package/src/mirror/transport.ts +7 -0
  54. package/src/mirror/wire.ts +25 -0
  55. package/src/project/config.ts +98 -0
  56. package/src/project/design.ts +59 -0
  57. package/src/project/detect.ts +184 -0
  58. package/src/project/files.ts +30 -0
  59. package/src/project/git.ts +68 -0
  60. package/src/project/github.ts +42 -0
  61. package/src/project/history.ts +89 -0
  62. package/src/project/project.ts +106 -0
  63. package/src/project/spawn.ts +23 -0
  64. package/src/project/step.ts +15 -0
  65. package/src/protocol.ts +125 -0
  66. package/src/sandbox/forward.ts +73 -0
  67. package/src/sandbox/install.ts +44 -0
  68. package/src/sandbox/sandbox.ts +57 -0
  69. package/src/serve/build.ts +49 -0
  70. package/src/serve/canvases.ts +65 -0
  71. package/src/serve/dev.ts +296 -0
  72. package/src/serve/env.ts +16 -0
  73. package/src/serve/mcp.ts +65 -0
  74. package/src/serve/middleware.ts +172 -0
  75. package/src/serve/next/config.ts +68 -0
  76. package/src/serve/next/hook.ts +74 -0
  77. package/src/serve/next/loader.ts +37 -0
  78. package/src/serve/nuxt.ts +14 -0
  79. package/src/serve/plugin.ts +95 -0
  80. package/src/serve/preload.ts +167 -0
  81. package/src/serve/resend.ts +29 -0
  82. package/src/serve/running.ts +115 -0
  83. package/src/serve/screenshot.ts +26 -0
  84. package/src/serve/sources.ts +46 -0
  85. package/src/serve/uncached.ts +25 -0
  86. package/src/serve/vite-build.ts +15 -0
  87. package/src/serve/vite.ts +19 -0
  88. package/src/session/session.ts +96 -0
  89. package/src/share/ask.ts +24 -0
  90. package/src/share/client.ts +140 -0
  91. package/src/share/consent.ts +39 -0
  92. package/src/share/frame.ts +26 -0
  93. package/src/source/astro/astro.ts +10 -0
  94. package/src/source/astro/elements.ts +60 -0
  95. package/src/source/blocks.ts +42 -0
  96. package/src/source/css.ts +48 -0
  97. package/src/source/estree.ts +55 -0
  98. package/src/source/extract.ts +68 -0
  99. package/src/source/insert.ts +189 -0
  100. package/src/source/jsx/elements.ts +136 -0
  101. package/src/source/jsx/jsx.ts +5 -0
  102. package/src/source/language.ts +176 -0
  103. package/src/source/location.ts +34 -0
  104. package/src/source/modules.ts +41 -0
  105. package/src/source/overrides.ts +35 -0
  106. package/src/source/page.ts +69 -0
  107. package/src/source/patch.ts +79 -0
  108. package/src/source/prop.ts +34 -0
  109. package/src/source/refusal.ts +7 -0
  110. package/src/source/rules.ts +298 -0
  111. package/src/source/stamp.ts +28 -0
  112. package/src/source/story-file.ts +40 -0
  113. package/src/source/story.ts +162 -0
  114. package/src/source/structure.ts +253 -0
  115. package/src/source/style.ts +143 -0
  116. package/src/source/svelte/elements.ts +154 -0
  117. package/src/source/svelte/svelte.ts +11 -0
  118. package/src/source/tag.ts +99 -0
  119. package/src/source/tailwind.ts +46 -0
  120. package/src/source/tokens.ts +56 -0
  121. package/src/source/vue/elements.ts +236 -0
  122. package/src/source/vue/vue.ts +11 -0
package/src/cli.ts ADDED
@@ -0,0 +1,287 @@
1
+ #!/usr/bin/env bun
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { bench } from "./bench/bench.ts";
5
+ import { askOnTerminal } from "./share/ask.ts";
6
+ import { share } from "./share/client.ts";
7
+ import { checkoutOf } from "./cloud/checkout.ts";
8
+ import { DEFAULT_EDGE, loadCredentials, saveCredentials } from "./cloud/credentials.ts";
9
+ import { choose, describe, link } from "./cloud/link.ts";
10
+ import { login } from "./cloud/login.ts";
11
+ import { diskStore, manifestPath } from "./capture/manifest.ts";
12
+ import { localRunner } from "./job/job.ts";
13
+ import { jobServer } from "./job/server.ts";
14
+ import { review } from "./capture/review.ts";
15
+ import { snap } from "./capture/snap.ts";
16
+ import { commands } from "./commands/registry.ts";
17
+ import { loadProject } from "./project/project.ts";
18
+ import { sandbox } from "./sandbox/sandbox.ts";
19
+ import { sessionServer } from "./session/session.ts";
20
+ import { build } from "./serve/build.ts";
21
+ import { dev } from "./serve/dev.ts";
22
+ import { serve } from "./serve/mcp.ts";
23
+ import { runCommand, runOn } from "./serve/running.ts";
24
+
25
+ function usage(): string {
26
+ const listed = commands.flatMap((command) => [
27
+ ` ${command.name} ${command.does}`,
28
+ ...Object.entries(command.params).map(([name, does]) => ` --${name} ${does}`),
29
+ ...Object.entries(command.optional ?? {}).map(([name, does]) => ` [--${name}] ${does}`),
30
+ ]);
31
+
32
+ return [
33
+ "lienzo <command> [--root DIR] [--class-attribute className|class] [--canvas URL] [--param value]...",
34
+ " --canvas runs a command, or serves mcp, on the canvas at URL (a session's /__lienzo/ page) instead of this project",
35
+ "",
36
+ " dev Starts the project's dev server and the canvas. [--share 1] also opens it to a designer at a link on the edge.",
37
+ " --port port to listen on",
38
+ " bench Opens frames of a page on the canvas, pans and zooms, and prints the frame rate and the work the browser did.",
39
+ " [--frames] frames to open, 12 by default",
40
+ " [--path] page to open, / by default",
41
+ " build Builds the project as it ships, with each element stamped with its source.",
42
+ " snap Builds the project, captures each frame twice, and writes a manifest of PNG hashes.",
43
+ " review Compares this commit's capture with its merge-base's and writes a page of the differences.",
44
+ " --base ref to compare against, origin/HEAD by default",
45
+ " job Clones a repository at a commit, applies steps, installs and snaps into the store under --root.",
46
+ " --repo repository to clone",
47
+ " --sha commit to capture",
48
+ " [--steps] JSON array of {name, params} commands applied before capture",
49
+ " [--work] folder to clone in",
50
+ " job-server Serves jobs over HTTP: POST /run, then GET /manifests/SHA and /blobs/HASH.",
51
+ " [--port] port to listen on, 8080 by default",
52
+ " [--work] folder to clone in",
53
+ " sandbox Installs the project, starts its dev server, and opens it on every interface.",
54
+ " --port port to open",
55
+ " session Serves the control of a hosted authoring session: POST /start clones, installs and opens the dev server on 8080; GET /changed lists the edited files.",
56
+ " [--port] control port, 8081 by default",
57
+ " [--work] folder to clone in",
58
+ " login Signs in with GitHub and keeps a token for ui.rising.sh.",
59
+ " [--edge] the service to sign in to",
60
+ " link Registers this repository and folder as a project on ui.rising.sh and prints its page.",
61
+ " [--yes] 1 to skip the confirmation",
62
+ " mcp Serves the commands below to an agent, as MCP tools on stdio.",
63
+ ...listed,
64
+ ].join("\n");
65
+ }
66
+
67
+ function flagsOf(args: string[]): Record<string, string> {
68
+ const flags: Record<string, string> = {};
69
+
70
+ for (let index = 0; index < args.length; index += 2) {
71
+ const name = args[index]!;
72
+ const value = args[index + 1];
73
+
74
+ if (!name.startsWith("--") || value === undefined) throw new Error(`bad argument "${name}"`);
75
+ flags[name.slice(2)] = value;
76
+ }
77
+
78
+ return flags;
79
+ }
80
+
81
+ function untilClosed(stream: NodeJS.ReadStream): Promise<void> {
82
+ return new Promise((resolve) => stream.on("close", resolve));
83
+ }
84
+
85
+ async function main(): Promise<number> {
86
+ const [name, ...rest] = process.argv.slice(2);
87
+
88
+ if (!name || name === "help" || name === "--help") {
89
+ console.log(usage());
90
+ return 0;
91
+ }
92
+
93
+ const { root = ".", "class-attribute": attribute, canvas, ...params } = flagsOf(rest);
94
+ if (attribute !== undefined && attribute !== "className" && attribute !== "class") {
95
+ throw new Error("--class-attribute is className or class");
96
+ }
97
+
98
+ if (name === "job") {
99
+ if (!params.repo || !params.sha) throw new Error("job needs --repo and --sha");
100
+ const done = await localRunner({ work: params.work ?? os.tmpdir() }).run(
101
+ { repo: params.repo, sha: params.sha, steps: JSON.parse(params.steps ?? "[]") },
102
+ diskStore(root),
103
+ );
104
+ if (!done.ok) {
105
+ console.error(done.reason);
106
+ return 1;
107
+ }
108
+
109
+ console.log(done.manifest.commit);
110
+ return 0;
111
+ }
112
+
113
+ if (name === "job-server") {
114
+ const server = jobServer(
115
+ localRunner({ work: params.work ?? os.tmpdir() }),
116
+ diskStore(root),
117
+ Number(params.port ?? 8080),
118
+ );
119
+ console.log(`jobs ${server.url.href}`);
120
+
121
+ return await new Promise<number>(() => {});
122
+ }
123
+
124
+ if (name === "session") {
125
+ const server = sessionServer(
126
+ async (dir) => {
127
+ const { running } = await sandbox(await loadProject(dir, attribute), 8080);
128
+
129
+ return { canvas: new URL(running.canvas).pathname, close: running.close };
130
+ },
131
+ params.work ?? os.tmpdir(),
132
+ Number(params.port ?? 8081),
133
+ );
134
+ console.log(`session ${server.url.href}`);
135
+
136
+ return await new Promise<number>(() => {});
137
+ }
138
+
139
+ if (name === "login") {
140
+ const credentials = await login(
141
+ params.edge ?? DEFAULT_EDGE,
142
+ {
143
+ fetch,
144
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
145
+ tell: (message) => console.log(message),
146
+ },
147
+ `lienzo cli on ${os.hostname()}`,
148
+ );
149
+ await saveCredentials(credentials);
150
+ console.log(`signed in as ${credentials.login}`);
151
+
152
+ return 0;
153
+ }
154
+
155
+ if (name === "link") {
156
+ const credentials = await loadCredentials();
157
+ if (!credentials) throw new Error("run `lienzo login` first");
158
+
159
+ const checkout = await checkoutOf(root);
160
+ if (!checkout.repo) throw new Error("the `origin` remote is not a GitHub repository");
161
+ const choice = await choose(checkout);
162
+ console.log(describe(checkout.repo, choice));
163
+ if (params.yes !== "1" && prompt("Link this project? [y/N]")?.toLowerCase() !== "y") return 1;
164
+
165
+ console.log(await link(credentials, checkout, choice, fetch));
166
+ return 0;
167
+ }
168
+
169
+ if (canvas !== undefined) {
170
+ if (name === "mcp") {
171
+ await serve((command, given) => runOn(canvas, command, given, undefined, "agent"));
172
+ await untilClosed(process.stdin);
173
+ return 0;
174
+ }
175
+ if (!commands.some((command) => command.name === name)) {
176
+ throw new Error(`--canvas runs a command, and "${name}" is not one`);
177
+ }
178
+
179
+ const result = await runOn(canvas, name, params);
180
+ console.log(JSON.stringify(result));
181
+
182
+ return result.ok ? 0 : 1;
183
+ }
184
+
185
+ const project = await loadProject(root, attribute);
186
+
187
+ if (name === "mcp") {
188
+ await serve((command, given) => runCommand(project, command, given, "agent"));
189
+ await untilClosed(process.stdin);
190
+ return 0;
191
+ }
192
+
193
+ if (name === "dev") {
194
+ const running = await dev(project, params.port ? Number(params.port) : undefined);
195
+ console.log(`site ${running.site}\ncanvas ${running.canvas}`);
196
+
197
+ if (params.share === "1") {
198
+ const credentials = await loadCredentials();
199
+ if (!credentials) throw new Error("run `lienzo login` before --share 1");
200
+ const shared = await share({
201
+ site: running.site,
202
+ edge: params.edge ?? credentials.edge,
203
+ token: credentials.token,
204
+ approve: askOnTerminal(process.stdin, process.stdout),
205
+ name: path.basename(path.resolve(root)),
206
+ });
207
+ console.log(`share ${shared.link}`);
208
+ const viewing = await fetch(
209
+ new URL(`/shares/${shared.id}/link`, params.edge ?? credentials.edge),
210
+ {
211
+ method: "POST",
212
+ headers: { authorization: `Bearer ${credentials.token}` },
213
+ body: JSON.stringify({ role: "viewer" }),
214
+ },
215
+ );
216
+ if (viewing.ok) console.log(`viewer ${((await viewing.json()) as { link: string }).link}`);
217
+ const access = await fetch(new URL("/__lz/agent", shared.link), {
218
+ headers: { authorization: `Bearer ${credentials.token}` },
219
+ });
220
+ if (access.ok) {
221
+ const { mcp, token } = (await access.json()) as { mcp: string; token: string };
222
+ console.log(`mcp ${mcp}\ntoken ${token}`);
223
+ }
224
+ void running.exited.then(shared.close);
225
+ }
226
+
227
+ return await running.exited;
228
+ }
229
+
230
+ if (name === "bench") {
231
+ const running = await dev(project);
232
+ try {
233
+ const result = await bench(running.canvas, params.path ?? "/", Number(params.frames ?? 12));
234
+ console.log(JSON.stringify(result, null, 2));
235
+ } finally {
236
+ await running.close();
237
+ }
238
+
239
+ return 0;
240
+ }
241
+
242
+ if (name === "build") return await build(project);
243
+
244
+ if (name === "snap") {
245
+ const snapped = await snap(project);
246
+ if (!snapped.ok) {
247
+ console.error(snapped.reason);
248
+ return 1;
249
+ }
250
+
251
+ const file = manifestPath(project.root, snapped.manifest.commit);
252
+ console.log(`${Object.keys(snapped.manifest.frames).length} frames ${file}`);
253
+ return 0;
254
+ }
255
+
256
+ if (name === "review") {
257
+ const reviewed = await review(project.root, params.base ?? "origin/HEAD");
258
+ if (!reviewed.ok) {
259
+ console.error(reviewed.reason);
260
+ return 1;
261
+ }
262
+
263
+ console.log(`${reviewed.check.title}\n${reviewed.check.summary}`);
264
+ return 0;
265
+ }
266
+
267
+ if (name === "sandbox") {
268
+ if (!params.port) throw new Error("sandbox needs --port");
269
+ const { running, forwarded } = await sandbox(project, Number(params.port));
270
+ const canvas = new URL(new URL(running.canvas).pathname, `http://localhost:${forwarded.port}`);
271
+ console.log(`canvas ${canvas.href}`);
272
+
273
+ return await running.exited;
274
+ }
275
+
276
+ const result = await runCommand(project, name, params);
277
+ console.log(JSON.stringify(result));
278
+
279
+ return result.ok ? 0 : 1;
280
+ }
281
+
282
+ try {
283
+ process.exit(await main());
284
+ } catch (error) {
285
+ console.error(error instanceof Error ? error.message : error);
286
+ process.exit(2);
287
+ }
@@ -0,0 +1,33 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import type { Checkout } from "./link.ts";
4
+
5
+ async function git(cwd: string, ...args: string[]): Promise<string> {
6
+ const run = Bun.spawn(["git", ...args], { cwd, stdout: "pipe", stderr: "pipe" });
7
+ const [out, code] = await Promise.all([new Response(run.stdout).text(), run.exited]);
8
+
9
+ return code === 0 ? out.trim() : "";
10
+ }
11
+
12
+ // OWNER/NAME of a GitHub remote URL, https or ssh.
13
+ export function repoOf(remote: string): string | undefined {
14
+ return /github\.com[:/]([\w.-]+\/[\w.-]+?)(?:\.git)?\/?$/.exec(remote)?.[1];
15
+ }
16
+
17
+ // The repository around `dir`, read from git and the disk.
18
+ export async function checkoutOf(dir: string): Promise<Checkout> {
19
+ const top = await git(dir, "rev-parse", "--show-toplevel");
20
+ if (!top) throw new Error(`${dir} is not in a git repository`);
21
+
22
+ const read = async (file: string) =>
23
+ readFile(path.join(top, file), "utf8").catch(() => undefined);
24
+ const root = path.relative(top, path.resolve(dir)).split(path.sep).join("/");
25
+
26
+ return {
27
+ repo: repoOf(await git(dir, "remote", "get-url", "origin")),
28
+ root,
29
+ paths: (await git(top, "ls-files", "-z")).split("\0").filter(Boolean),
30
+ read,
31
+ config: await read(root === "" ? "lienzo.json" : `${root}/lienzo.json`),
32
+ };
33
+ }
@@ -0,0 +1,25 @@
1
+ import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ export type Credentials = { edge: string; token: string; login: string };
6
+
7
+ export const DEFAULT_EDGE = "https://ui.rising.sh";
8
+
9
+ const fileOf = (home: string) => path.join(home, ".config", "lienzo", "token");
10
+
11
+ export async function saveCredentials(credentials: Credentials, home = os.homedir()) {
12
+ const file = fileOf(home);
13
+ await mkdir(path.dirname(file), { recursive: true });
14
+ await writeFile(file, JSON.stringify(credentials), { mode: 0o600 });
15
+ // `mode` applies only when the file is new.
16
+ await chmod(file, 0o600);
17
+ }
18
+
19
+ export async function loadCredentials(home = os.homedir()): Promise<Credentials | undefined> {
20
+ try {
21
+ return JSON.parse(await readFile(fileOf(home), "utf8")) as Credentials;
22
+ } catch {
23
+ return undefined;
24
+ }
25
+ }
@@ -0,0 +1,60 @@
1
+ import { parseConfig } from "../project/config.ts";
2
+ import { detect, folders, type Detected, type Read } from "../project/detect.ts";
3
+ import type { Credentials } from "./credentials.ts";
4
+
5
+ export type Checkout = {
6
+ // OWNER/NAME of the `origin` remote, or undefined when it is not on GitHub.
7
+ repo: string | undefined;
8
+ // The working folder relative to the repository's top, "" at the top.
9
+ root: string;
10
+ paths: string[];
11
+ read: Read;
12
+ // The text of the project's lienzo.json, when the folder has one.
13
+ config: string | undefined;
14
+ };
15
+
16
+ export type Choice = { root: string; detected: Detected | undefined };
17
+
18
+ // The folder to offer: the one the person stands in, else the shallowest with
19
+ // a stack lienzo knows.
20
+ export async function choose(checkout: Checkout): Promise<Choice> {
21
+ const here = await detect(checkout.root, checkout.paths, checkout.read);
22
+ if (here) return { root: checkout.root, detected: here };
23
+
24
+ const [first] = await folders(checkout.paths, checkout.read);
25
+ if (first === undefined) return { root: checkout.root, detected: undefined };
26
+
27
+ return { root: first, detected: await detect(first, checkout.paths, checkout.read) };
28
+ }
29
+
30
+ export function describe(repo: string, choice: Choice): string {
31
+ const { root, detected } = choice;
32
+ const where = `${repo}${root === "" ? "" : `/${root}`}`;
33
+ if (!detected) return `${where}: no stack lienzo knows`;
34
+
35
+ const frames = detected.config.frames.map((frame) => frame.path).join(" ");
36
+
37
+ return `${where}: ${detected.stack}${detected.manager ? ` with ${detected.manager}` : ""}, build "${detected.config.build}" to ${detected.config.output}, frames ${frames}`;
38
+ }
39
+
40
+ // POST /projects. A lienzo.json the folder already holds is the project's
41
+ // config as it stands; otherwise the detected one is sent.
42
+ export async function link(
43
+ credentials: Credentials,
44
+ checkout: Checkout,
45
+ choice: Choice,
46
+ fetcher: typeof fetch,
47
+ ): Promise<string> {
48
+ if (!checkout.repo) throw new Error("the `origin` remote is not a GitHub repository");
49
+ const config = checkout.config === undefined ? choice.detected?.config : undefined;
50
+ if (checkout.config !== undefined) parseConfig(checkout.config);
51
+
52
+ const response = await fetcher(`${credentials.edge}/projects`, {
53
+ method: "POST",
54
+ headers: { authorization: `Bearer ${credentials.token}` },
55
+ body: JSON.stringify({ repo: checkout.repo, root: choice.root, config }),
56
+ });
57
+ if (!response.ok) throw new Error(`${response.status} ${await response.text()}`);
58
+
59
+ return ((await response.json()) as { url: string }).url;
60
+ }
@@ -0,0 +1,85 @@
1
+ import type { Credentials } from "./credentials.ts";
2
+
3
+ export type LoginIo = {
4
+ fetch: typeof fetch;
5
+ sleep: (ms: number) => Promise<void>;
6
+ tell: (message: string) => void;
7
+ };
8
+
9
+ type Device = {
10
+ device_code: string;
11
+ user_code: string;
12
+ verification_uri: string;
13
+ interval: number;
14
+ expires_in: number;
15
+ };
16
+
17
+ const GITHUB = "https://github.com";
18
+ const form = (fields: Record<string, string>) => new URLSearchParams(fields);
19
+ const asJson = { accept: "application/json" };
20
+
21
+ async function ok(response: Response, what: string): Promise<Response> {
22
+ if (!response.ok) throw new Error(`${what}: ${response.status} ${await response.text()}`);
23
+
24
+ return response;
25
+ }
26
+
27
+ // Signs in with GitHub's device flow and trades the GitHub token for a Lienzo
28
+ // one. The GitHub token stays in this process: the edge only checks it.
29
+ export async function login(edge: string, io: LoginIo, label: string): Promise<Credentials> {
30
+ const { clientId } = (await (await ok(await io.fetch(`${edge}/cli`), "edge /cli")).json()) as {
31
+ clientId: string;
32
+ };
33
+
34
+ const device = (await (
35
+ await ok(
36
+ await io.fetch(`${GITHUB}/login/device/code`, {
37
+ method: "POST",
38
+ headers: asJson,
39
+ body: form({ client_id: clientId }),
40
+ }),
41
+ "GitHub device code",
42
+ )
43
+ ).json()) as Device;
44
+ io.tell(`Open ${device.verification_uri} and enter ${device.user_code}`);
45
+
46
+ let interval = device.interval * 1000;
47
+ const until = Date.now() + device.expires_in * 1000;
48
+ while (Date.now() < until) {
49
+ await io.sleep(interval);
50
+ const polled = (await (
51
+ await ok(
52
+ await io.fetch(`${GITHUB}/login/oauth/access_token`, {
53
+ method: "POST",
54
+ headers: asJson,
55
+ body: form({
56
+ client_id: clientId,
57
+ device_code: device.device_code,
58
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
59
+ }),
60
+ }),
61
+ "GitHub token",
62
+ )
63
+ ).json()) as { access_token?: string; error?: string };
64
+
65
+ if (polled.access_token) {
66
+ const exchanged = await ok(
67
+ await io.fetch(`${edge}/cli/token`, {
68
+ method: "POST",
69
+ body: JSON.stringify({ accessToken: polled.access_token, label }),
70
+ }),
71
+ "edge /cli/token",
72
+ );
73
+ const { token, login: who } = (await exchanged.json()) as { token: string; login: string };
74
+
75
+ return { edge, token, login: who };
76
+ }
77
+ if (polled.error === "slow_down") interval += 5000;
78
+ else if (polled.error === "access_denied") throw new Error("sign-in was denied");
79
+ else if (polled.error !== "authorization_pending") {
80
+ throw new Error(`GitHub sign-in failed: ${polled.error ?? "no token"}`);
81
+ }
82
+ }
83
+
84
+ throw new Error("the sign-in code expired; run `lienzo login` again");
85
+ }
@@ -0,0 +1,46 @@
1
+ import type { Project } from "../project/project.ts";
2
+ import type { FrameData, Question, Result } from "../protocol.ts";
3
+ import { screenshot } from "../serve/screenshot.ts";
4
+ import { need, type Command } from "./command.ts";
5
+
6
+ // What only the open canvas knows, asked of it through the dev server.
7
+ function asked(project: Project, name: Question["name"]): Promise<Result> {
8
+ if (!project.ask) {
9
+ return Promise.resolve({
10
+ ok: false,
11
+ reason: "no dev server serves the project; run lienzo dev",
12
+ });
13
+ }
14
+
15
+ return project.ask(name);
16
+ }
17
+
18
+ export const selectionGet: Command = {
19
+ name: "selection.get",
20
+ does: "Reads what the person selected on the open canvas: its frame, the location of its element, which of that element's nodes it is, and how many it draws.",
21
+ params: {},
22
+ run: (project) => asked(project, "selection"),
23
+ };
24
+
25
+ export const frameList: Command = {
26
+ name: "frame.list",
27
+ does: "Lists the frames of the open canvas: each one's id, page path, page URL, width and height.",
28
+ params: {},
29
+ run: (project) => asked(project, "frames"),
30
+ };
31
+
32
+ export const frameScreenshot: Command = {
33
+ name: "frame.screenshot",
34
+ does: "Draws a frame's page in headless Chrome at the frame's size and writes a PNG; returns its path.",
35
+ params: { frame: "the frame's id, as frame.list or selection.get gives it" },
36
+ async run(project, params) {
37
+ const id = need(params, "frame");
38
+ const listed = await asked(project, "frames");
39
+ if (!listed.ok) return listed;
40
+
41
+ const frame = (listed.data as FrameData[]).find((candidate) => candidate.id === id);
42
+ if (!frame) return { ok: false, reason: `the canvas has no frame "${id}"` };
43
+
44
+ return { ok: true, changed: [], data: { file: await screenshot(frame) } };
45
+ },
46
+ };