@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
@@ -0,0 +1,218 @@
1
+ import path from "node:path";
2
+ import {
3
+ commitFiles,
4
+ currentBranch,
5
+ diffOf,
6
+ hasBranch,
7
+ hasHead,
8
+ hasRemote,
9
+ headText,
10
+ pushBranch,
11
+ startBranch,
12
+ } from "../project/git.ts";
13
+ import { createPull, defaultBranch, openPull, type Pull } from "../project/github.ts";
14
+ import type { Project, Session, Written } from "../project/project.ts";
15
+ import type { ChangeData, CommitData, ProposeData, Result } from "../protocol.ts";
16
+ import { need, type Command } from "./command.ts";
17
+
18
+ type Listed = { ok: true; changes: ChangeData[] } | { ok: false; reason: string };
19
+
20
+ // Why the file holds more than lienzo wrote, or null when it holds only that.
21
+ function foreignOf(entry: Written, head: string | undefined, now: string): string | null {
22
+ if (head === undefined) return `${entry.file} is not in the last commit`;
23
+ if (head !== entry.base) return `${entry.file} held other changes before lienzo edited it`;
24
+ if (now !== entry.wrote) return `${entry.file} changed outside lienzo since lienzo wrote it`;
25
+
26
+ return null;
27
+ }
28
+
29
+ async function changeOf(root: string, entry: Written): Promise<ChangeData | undefined> {
30
+ const now = await Bun.file(path.join(root, entry.file)).text();
31
+ const head = await headText(root, entry.file);
32
+ if (now === head) return undefined;
33
+
34
+ return {
35
+ file: entry.file,
36
+ diff: await diffOf(root, entry.file),
37
+ foreign: foreignOf(entry, head, now),
38
+ };
39
+ }
40
+
41
+ async function listed(project: Project): Promise<Listed> {
42
+ const session: Session | undefined = project.session;
43
+ if (!session) return { ok: false, reason: "no dev server serves the project; run lienzo dev" };
44
+ if (!(await hasHead(project.root))) {
45
+ return { ok: false, reason: "the project is not in a git repository with a commit" };
46
+ }
47
+
48
+ const found = await Promise.all(session.written().map((entry) => changeOf(project.root, entry)));
49
+ const changes = found.filter((change) => change !== undefined);
50
+
51
+ return { ok: true, changes: changes.sort((a, b) => a.file.localeCompare(b.file)) };
52
+ }
53
+
54
+ export const changeList: Command = {
55
+ name: "change.list",
56
+ does: "Lists each file the running dev server's edits changed since the last commit, with its diff, and why a file holds changes lienzo did not make.",
57
+ params: {},
58
+ async run(project): Promise<Result> {
59
+ const found = await listed(project);
60
+ if (!found.ok) return found;
61
+
62
+ return { ok: true, changed: [], data: found.changes };
63
+ },
64
+ };
65
+
66
+ export const editsList: Command = {
67
+ name: "edits.list",
68
+ does: "Lists the running dev server's edits not undone, oldest first, and whether a person or an agent made each.",
69
+ params: {},
70
+ async run(project): Promise<Result> {
71
+ if (!project.session) {
72
+ return { ok: false, reason: "no dev server serves the project; run lienzo dev" };
73
+ }
74
+
75
+ return { ok: true, changed: [], data: project.session.edits() };
76
+ },
77
+ };
78
+
79
+ const NOTHING = "lienzo changed nothing since the last commit";
80
+
81
+ // The changes a commit may take, or why it may not: a file that holds work
82
+ // lienzo did not make is committed by hand.
83
+ async function committable(project: Project): Promise<Listed> {
84
+ const found = await listed(project);
85
+ if (!found.ok) return found;
86
+
87
+ const foreign = found.changes.find((change) => change.foreign !== null);
88
+ if (foreign) return { ok: false, reason: `${foreign.foreign}; commit it by hand` };
89
+
90
+ return found;
91
+ }
92
+
93
+ async function commit(project: Project, changes: ChangeData[], message: string) {
94
+ const files = changes.map((change) => change.file);
95
+ const made = await commitFiles(project.root, files, message);
96
+ if (made.ok) project.session!.committed(files);
97
+
98
+ return { made, files };
99
+ }
100
+
101
+ function messageOf(params: Record<string, string>): string {
102
+ const message = need(params, "message").trim();
103
+ if (!message) throw new Error("the commit message is empty");
104
+
105
+ return message;
106
+ }
107
+
108
+ export const changeCommit: Command = {
109
+ name: "change.commit",
110
+ does: "Commits the files change.list lists, and nothing else. Refuses when one of them holds changes lienzo did not make.",
111
+ params: { message: "the commit message" },
112
+ async run(project, params): Promise<Result> {
113
+ const message = messageOf(params);
114
+ const found = await committable(project);
115
+ if (!found.ok) return found;
116
+ if (found.changes.length === 0) return { ok: false, reason: NOTHING };
117
+
118
+ const { made, files } = await commit(project, found.changes, message);
119
+ if (!made.ok) return made;
120
+ const data: CommitData = { commit: made.commit, files };
121
+
122
+ return { ok: true, changed: [], data };
123
+ },
124
+ };
125
+
126
+ const REMOTE = "origin";
127
+
128
+ // A branch name from the message's first line, free in the repository.
129
+ async function freeBranch(root: string, title: string): Promise<string> {
130
+ const slug = title
131
+ .toLowerCase()
132
+ .normalize("NFD")
133
+ .replace(/[̀-ͯ]/g, "")
134
+ .replace(/[^a-z0-9]+/g, "-")
135
+ .replace(/^-+|-+$/g, "")
136
+ .slice(0, 48)
137
+ .replace(/-+$/, "");
138
+ const base = `lienzo/${slug || "cambios"}`;
139
+
140
+ let name = base;
141
+ for (let n = 2; await hasBranch(root, name); n++) name = `${base}-${n}`;
142
+
143
+ return name;
144
+ }
145
+
146
+ function bodyOf(message: string, files: string[]): string {
147
+ const rest = message.split("\n").slice(1).join("\n").trim();
148
+ const list = files.map((file) => `- \`${file}\``).join("\n");
149
+ const proposed = `Proposed from the lienzo canvas.${list ? `\n\n${list}` : ""}`;
150
+
151
+ return rest ? `${rest}\n\n${proposed}` : proposed;
152
+ }
153
+
154
+ // The branch's open pull request, or a new one when it has none. A push to a
155
+ // branch with one open already updates it.
156
+ async function pullFrom(
157
+ root: string,
158
+ pull: Pull,
159
+ ): Promise<{ ok: true; url: string; opened: boolean } | { ok: false; reason: string }> {
160
+ const open = await openPull(root, pull.head);
161
+ if (!open.ok) return open;
162
+ if (open.value) return { ok: true, url: open.value, opened: false };
163
+
164
+ const made = await createPull(root, pull);
165
+
166
+ return made.ok ? { ok: true, url: made.value, opened: true } : made;
167
+ }
168
+
169
+ export const changePropose: Command = {
170
+ name: "change.propose",
171
+ does: "Commits the files change.list lists, pushes the branch and opens a pull request with gh. On the default branch it first starts a branch named from the message. With nothing new to commit, it pushes the current branch and opens or finds its pull request.",
172
+ params: { message: "the commit message; its first line is the pull request's title" },
173
+ async run(project, params): Promise<Result> {
174
+ const message = messageOf(params);
175
+ const found = await committable(project);
176
+ if (!found.ok) return found;
177
+
178
+ const root = project.root;
179
+ if (!(await hasRemote(root, REMOTE)))
180
+ return { ok: false, reason: `the repository has no ${REMOTE} remote to push to` };
181
+ const base = await defaultBranch(root);
182
+ if (!base.ok) return { ok: false, reason: `gh could not read the repository: ${base.reason}` };
183
+
184
+ const current = await currentBranch(root);
185
+ const onBase = current === undefined || current === base.value;
186
+ if (onBase && found.changes.length === 0) return { ok: false, reason: NOTHING };
187
+
188
+ const title = message.split("\n")[0]!.trim();
189
+ const branch = current !== undefined && !onBase ? current : await freeBranch(root, title);
190
+ if (onBase) {
191
+ const started = await startBranch(root, branch);
192
+ if (!started.ok) return started;
193
+ }
194
+
195
+ let made: string | null = null;
196
+ let files: string[] = [];
197
+ if (found.changes.length > 0) {
198
+ const done = await commit(project, found.changes, message);
199
+ if (!done.made.ok) return done.made;
200
+ made = done.made.commit;
201
+ files = done.files;
202
+ }
203
+
204
+ const pushed = await pushBranch(root, REMOTE, branch);
205
+ if (!pushed.ok) return { ok: false, reason: `${branch} was not pushed: ${pushed.reason}` };
206
+
207
+ const pull = await pullFrom(root, {
208
+ base: base.value,
209
+ head: branch,
210
+ title,
211
+ body: bodyOf(message, files),
212
+ });
213
+ if (!pull.ok) return pull;
214
+ const data: ProposeData = { branch, commit: made, files, pull: pull.url, opened: pull.opened };
215
+
216
+ return { ok: true, changed: [], data };
217
+ },
218
+ };
@@ -0,0 +1,66 @@
1
+ import type { Project } from "../project/project.ts";
2
+ import { patchClasses } from "../source/patch.ts";
3
+ import { refuse } from "../source/refusal.ts";
4
+ import { withClass, withoutClass, withPlainClass } from "../source/tailwind.ts";
5
+ import { AT, need, type Command } from "./command.ts";
6
+ import { edit } from "./file.ts";
7
+ import { classIsComputed, overrideClass } from "./override.ts";
8
+
9
+ export function editClasses(project: Project, at: string, change: (list: string) => string) {
10
+ return edit(project, at, (source, location) =>
11
+ patchClasses(source, location, project.classAttribute, change),
12
+ );
13
+ }
14
+
15
+ export const classSet: Command = {
16
+ name: "class.set",
17
+ does: "Adds a class to an element. A Tailwind class replaces the classes it overrides.",
18
+ params: { at: AT, class: "the class, for example p-8 or md:gap-4" },
19
+
20
+ async run(project, params) {
21
+ const added = need(params, "class");
22
+ const at = need(params, "at");
23
+ const add = project.tailwind ? withClass : withPlainClass;
24
+
25
+ const edited = await editClasses(project, at, (list) => add(list, added));
26
+ if (edited.ok || !(await classIsComputed(project, at))) return edited;
27
+
28
+ const overridden = await overrideClass(project, at, added);
29
+
30
+ return overridden.ok ? overridden : refuse(`${edited.reason}, and ${overridden.reason}`);
31
+ },
32
+ };
33
+
34
+ const VARIANT = /^[a-z][a-z0-9-]*(?::[a-z][a-z0-9-]*)*$/;
35
+
36
+ export const variantSet: Command = {
37
+ name: "variant.set",
38
+ does: "Sets a class of an element under a Tailwind variant, such as hover or md, replacing the class of that variant it overrides.",
39
+ params: {
40
+ at: AT,
41
+ variant: "the variant, without the colon, for example hover or md:dark",
42
+ class: "the class without the variant, for example bg-blue-600",
43
+ },
44
+
45
+ async run(project, params) {
46
+ const variant = need(params, "variant");
47
+ const added = need(params, "class");
48
+ if (!project.tailwind) return refuse("the project does not declare tailwindcss");
49
+ if (!VARIANT.test(variant)) return refuse(`"${variant}" is not a variant`);
50
+ if (added.includes(":")) return refuse(`"${added}" already holds a variant`);
51
+
52
+ return classSet.run(project, { at: need(params, "at"), class: `${variant}:${added}` });
53
+ },
54
+ };
55
+
56
+ export const classRemove: Command = {
57
+ name: "class.remove",
58
+ does: "Removes a class from an element.",
59
+ params: { at: AT, class: "the class to remove" },
60
+
61
+ run(project, params) {
62
+ const removed = need(params, "class");
63
+
64
+ return editClasses(project, need(params, "at"), (list) => withoutClass(list, removed));
65
+ },
66
+ };
@@ -0,0 +1,27 @@
1
+ import type { Project } from "../project/project.ts";
2
+ import type { Result } from "../protocol.ts";
3
+
4
+ export type Params = Record<string, string>;
5
+
6
+ // One thing lienzo can do. The CLI, the MCP server and the canvas all reach it
7
+ // by name, and `does` and `params` are the help each of them shows.
8
+ export type Command = {
9
+ name: string;
10
+ does: string;
11
+ params: Params;
12
+
13
+ // Parameters a caller may leave out.
14
+ optional?: Params;
15
+
16
+ run(project: Project, params: Params): Promise<Result>;
17
+ };
18
+
19
+ export const AT =
20
+ "location of the element's tag, file:line:column, as its data-lz attribute gives it";
21
+
22
+ export function need(params: Params, name: string): string {
23
+ const value = params[name];
24
+ if (value === undefined) throw new Error(`missing parameter "${name}"`);
25
+
26
+ return value;
27
+ }
@@ -0,0 +1,95 @@
1
+ import { stat } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { stackNamed } from "../project/detect.ts";
4
+ import { declaredAbove, type Project } from "../project/project.ts";
5
+ import { extractElement } from "../source/extract.ts";
6
+ import { parseLocation } from "../source/location.ts";
7
+ import { pageFile } from "../source/page.ts";
8
+ import { refuse } from "../source/refusal.ts";
9
+ import { REACT_FRAMEWORKS, storyFile } from "../source/story-file.ts";
10
+ import { AT, need, type Command } from "./command.ts";
11
+ import { createFile, editFile, exists, read } from "./file.ts";
12
+
13
+ async function manifestText(project: Project): Promise<string | undefined> {
14
+ const file = Bun.file(path.join(project.root, "package.json"));
15
+
16
+ return (await file.exists()) ? file.text() : undefined;
17
+ }
18
+
19
+ async function folders(project: Project): Promise<Set<string>> {
20
+ const found = new Set<string>();
21
+ for (const folder of ["src/app", "app", "src/pages", "pages"]) {
22
+ const info = await stat(path.join(project.root, folder)).catch(() => undefined);
23
+ if (info?.isDirectory()) found.add(folder);
24
+ }
25
+
26
+ return found;
27
+ }
28
+
29
+ export const pageCreate: Command = {
30
+ name: "page.create",
31
+ does: "Creates the page file the project's router serves for a static route, with an empty <main>. Next, Astro, Nuxt and SvelteKit are supported.",
32
+ params: { route: "the route, starting with /, for example /pricing" },
33
+
34
+ async run(project, params) {
35
+ const route = need(params, "route");
36
+ const manifest = await manifestText(project);
37
+ const stack = stackNamed(manifest);
38
+ if (!stack) return refuse("package.json names no stack lienzo knows");
39
+
40
+ const present = await folders(project);
41
+ const page = pageFile(stack, route, (folder) => present.has(folder));
42
+ if (!page.ok) return page;
43
+
44
+ return createFile(project, page.file, page.code);
45
+ },
46
+ };
47
+
48
+ export const storyCreate: Command = {
49
+ name: "story.create",
50
+ does: "Creates a Storybook file with a Default story for the component a file exports.",
51
+ params: { file: "the component's file, for example src/Button.tsx" },
52
+
53
+ async run(project, params) {
54
+ const { source } = await read(project, need(params, "file"));
55
+ let framework: string | undefined;
56
+ for (const name of REACT_FRAMEWORKS) {
57
+ if (await declaredAbove(project.root, name)) {
58
+ framework = name;
59
+ break;
60
+ }
61
+ }
62
+
63
+ const story = storyFile(need(params, "file"), source, framework);
64
+ if (!story.ok) return story;
65
+
66
+ return createFile(project, story.file, story.code);
67
+ },
68
+ };
69
+
70
+ export const componentExtract: Command = {
71
+ name: "component.extract",
72
+ does: "Moves an element into a new component file beside its own and puts <Name /> where it stood. The element must hold no {} expressions.",
73
+ params: { at: AT, name: "the component's name, for example PriceCard" },
74
+
75
+ async run(project, params) {
76
+ const at = need(params, "at");
77
+ const location = parseLocation(at);
78
+ const file = path.join(path.dirname(location.file), `${need(params, "name")}.tsx`);
79
+ if (await exists(project, file)) return refuse(`${file} exists`);
80
+
81
+ let component = "";
82
+ const edited = await editFile(project, location.file, (source) => {
83
+ const moved = extractElement(location.file, source, location, need(params, "name"));
84
+ if (!moved.ok) return moved;
85
+
86
+ component = moved.component;
87
+ return { ok: true, code: moved.source };
88
+ });
89
+ if (!edited.ok) return edited;
90
+
91
+ const created = await createFile(project, file, component);
92
+
93
+ return created.ok ? { ...created, changed: [location.file, file] } : created;
94
+ },
95
+ };
@@ -0,0 +1,118 @@
1
+ import type { ElementData } from "../protocol.ts";
2
+ import { insertElement, wrapElement, type Spot } from "../source/insert.ts";
3
+ import { tagAt } from "../source/language.ts";
4
+ import { parseLocation } from "../source/location.ts";
5
+ import { duplicateElement, moveElement, removeElement, type Place } from "../source/structure.ts";
6
+ import { AT, need, type Command } from "./command.ts";
7
+ import { edit, open } from "./file.ts";
8
+
9
+ export const elementRemove: Command = {
10
+ name: "element.remove",
11
+ does: "Removes an element from source, with its lines when it stands alone on them.",
12
+ params: { at: AT },
13
+
14
+ run(project, params) {
15
+ return edit(project, need(params, "at"), removeElement);
16
+ },
17
+ };
18
+
19
+ const SIDES = ["before", "after", "earlier", "later"] as const;
20
+
21
+ // `before` and `after` take the sibling `to`; `earlier` and `later` step past
22
+ // the neighbour.
23
+ function placeOf(side: string, to: string | undefined): Place {
24
+ if (side === "before" || side === "after") {
25
+ if (to === undefined) throw new Error(`place "${side}" needs the sibling "to"`);
26
+ return { side, to: parseLocation(to) };
27
+ }
28
+ if (side === "earlier" || side === "later") return { side };
29
+
30
+ throw new Error(`place "${side}" is not one of ${SIDES.join(", ")}`);
31
+ }
32
+
33
+ export const elementMove: Command = {
34
+ name: "element.move",
35
+ does: "Moves an element among its siblings and returns its new location as `at`.",
36
+ params: { at: AT, place: SIDES.join(", ") },
37
+ optional: { to: "location of the sibling to move before or after" },
38
+
39
+ run(project, params) {
40
+ const place = placeOf(need(params, "place"), params.to);
41
+
42
+ return edit(project, need(params, "at"), (source, location) =>
43
+ moveElement(source, location, place),
44
+ );
45
+ },
46
+ };
47
+
48
+ const TAG = "an HTML tag the page draws, such as div or section";
49
+
50
+ export const elementWrap: Command = {
51
+ name: "element.wrap",
52
+ does: "Puts an element inside a new element and returns the new one's location as `at`.",
53
+ params: { at: AT, tag: TAG },
54
+
55
+ run(project, params) {
56
+ const tag = need(params, "tag");
57
+
58
+ return edit(project, need(params, "at"), (source, location) =>
59
+ wrapElement(source, location, tag),
60
+ );
61
+ },
62
+ };
63
+
64
+ const SPOTS = ["before", "after", "inside"] as const;
65
+
66
+ function spotOf(spot: string): Spot {
67
+ if ((SPOTS as readonly string[]).includes(spot)) return spot as Spot;
68
+
69
+ throw new Error(`place "${spot}" is not one of ${SPOTS.join(", ")}`);
70
+ }
71
+
72
+ export const elementInsert: Command = {
73
+ name: "element.insert",
74
+ does: "Adds an empty element next to an element or as its last child, and returns its location as `at`.",
75
+ params: { at: AT, tag: TAG, place: SPOTS.join(", ") },
76
+
77
+ run(project, params) {
78
+ const tag = need(params, "tag");
79
+ const spot = spotOf(need(params, "place"));
80
+
81
+ return edit(project, need(params, "at"), (source, location) =>
82
+ insertElement(source, location, tag, spot),
83
+ );
84
+ },
85
+ };
86
+
87
+ export const elementDuplicate: Command = {
88
+ name: "element.duplicate",
89
+ does: "Copies an element right after itself and returns the copy's location as `at`.",
90
+ params: { at: AT },
91
+
92
+ run(project, params) {
93
+ return edit(project, need(params, "at"), duplicateElement);
94
+ },
95
+ };
96
+
97
+ export const elementGet: Command = {
98
+ name: "element.get",
99
+ does: "Reads an element from source: its tag, its class list and its text.",
100
+ params: { at: AT },
101
+
102
+ async run(project, params) {
103
+ const { location, source } = await open(project, need(params, "at"));
104
+
105
+ const tag = tagAt(source, location);
106
+ if (!tag.ok) return tag;
107
+
108
+ const classes = tag.classes(project.classAttribute);
109
+
110
+ const data: ElementData = {
111
+ tag: tag.name,
112
+ classes: classes.ok ? classes.value : null,
113
+ text: tag.text.ok ? tag.text.value.trim() : null,
114
+ };
115
+
116
+ return { ok: true, changed: [], data };
117
+ },
118
+ };
@@ -0,0 +1,96 @@
1
+ import path from "node:path";
2
+ import type { Change, Project } from "../project/project.ts";
3
+ import type { Placed, Result } from "../protocol.ts";
4
+ import { formatLocation, parseLocation, positionOf, type Location } from "../source/location.ts";
5
+ import type { Patch } from "../source/patch.ts";
6
+
7
+ // Reads a file of the project. A path outside the project is an error.
8
+ export async function read(project: Project, relative: string) {
9
+ const file = path.resolve(project.root, relative);
10
+
11
+ if (path.relative(project.root, file).startsWith("..")) {
12
+ throw new Error(`${relative} is outside the project`);
13
+ }
14
+
15
+ const source = project.staged?.get(file) ?? (await Bun.file(file).text());
16
+ project.follow?.(file);
17
+
18
+ return { file, source };
19
+ }
20
+
21
+ // Reads the file a location names.
22
+ export async function open(project: Project, at: string) {
23
+ const location = parseLocation(at);
24
+
25
+ return { location, ...(await read(project, location.file)) };
26
+ }
27
+
28
+ // Applies a patch to a file of the project and records it for undo. `at` is
29
+ // the element selected before the edit, which undo selects again when the
30
+ // patch moves the selection.
31
+ export async function editFile(
32
+ project: Project,
33
+ relative: string,
34
+ patch: (source: string) => Patch,
35
+ at?: string,
36
+ ): Promise<Result> {
37
+ const { file, source } = await read(project, relative);
38
+
39
+ const patched = patch(source);
40
+ if (!patched.ok) return patched;
41
+ if (patched.code === source) return { ok: true, changed: [] };
42
+
43
+ const change: Change = { file: relative, before: source, after: patched.code };
44
+ const { select } = patched;
45
+ let placed: Placed | undefined;
46
+
47
+ if (select !== undefined && at !== undefined) {
48
+ const after =
49
+ select === null
50
+ ? null
51
+ : formatLocation({ file: relative, ...positionOf(patched.code, select) });
52
+
53
+ change.at = { before: at, after };
54
+ placed = { at: after };
55
+ }
56
+
57
+ if (project.staged) project.staged.set(file, patched.code);
58
+ else await Bun.write(file, patched.code);
59
+ project.record?.(change);
60
+
61
+ return { ok: true, changed: [relative], data: placed, rung: patched.rung };
62
+ }
63
+
64
+ export async function exists(project: Project, relative: string): Promise<boolean> {
65
+ const file = path.resolve(project.root, relative);
66
+
67
+ return project.staged?.has(file) || (await Bun.file(file).exists());
68
+ }
69
+
70
+ // Writes a file the project does not have and records it for undo, which
71
+ // leaves it empty.
72
+ export async function createFile(
73
+ project: Project,
74
+ relative: string,
75
+ code: string,
76
+ ): Promise<Result> {
77
+ if (await exists(project, relative)) return { ok: false, reason: `${relative} exists` };
78
+
79
+ const file = path.resolve(project.root, relative);
80
+ if (project.staged) project.staged.set(file, code);
81
+ else await Bun.write(file, code);
82
+ project.record?.({ file: relative, before: "", after: code });
83
+
84
+ return { ok: true, changed: [relative] };
85
+ }
86
+
87
+ // Applies a patch to the file a location names.
88
+ export function edit(
89
+ project: Project,
90
+ at: string,
91
+ patch: (source: string, location: Location) => Patch,
92
+ ): Promise<Result> {
93
+ const location = parseLocation(at);
94
+
95
+ return editFile(project, location.file, (source) => patch(source, location), at);
96
+ }
@@ -0,0 +1,58 @@
1
+ import path from "node:path";
2
+ import { CONFIG, withFrame, type NewFrame } from "../project/config.ts";
3
+ import { need, type Command } from "./command.ts";
4
+ import { editFile } from "./file.ts";
5
+
6
+ export const frameAdd: Command = {
7
+ name: "frame.add",
8
+ does: "Adds a frame to lienzo.json, creating the file when the project has none. A frame is a page path at a size, with the steps that act on it first.",
9
+ params: {
10
+ id: "the frame's name, unique in lienzo.json",
11
+ path: "the page path, starting with /",
12
+ steps: "the interactions that run after the page loads, as a JSON array of steps",
13
+ },
14
+ optional: {
15
+ width: "the width in px, 1280 by default",
16
+ height: "the height in px, 800 by default",
17
+ },
18
+ async run(project, params) {
19
+ let steps: unknown;
20
+ try {
21
+ steps = JSON.parse(need(params, "steps"));
22
+ } catch {
23
+ return { ok: false, reason: "steps is not JSON" };
24
+ }
25
+ const frame = {
26
+ id: need(params, "id"),
27
+ path: need(params, "path"),
28
+ steps,
29
+ ...(params.width && { width: Number(params.width) }),
30
+ ...(params.height && { height: Number(params.height) }),
31
+ } as NewFrame;
32
+
33
+ // A flow that cannot be replayed to the same pixels twice is not saved.
34
+ // The replay needs the page served, so a project with no dev server is
35
+ // saved on trust and `lienzo snap` is the check.
36
+ if (project.site && Array.isArray(steps) && steps.length > 0) {
37
+ const { replay } = await import("../capture/replay.ts");
38
+ const played = await replay(project.site, {
39
+ steps,
40
+ id: frame.id,
41
+ path: frame.path,
42
+ width: frame.width ?? 1280,
43
+ height: frame.height ?? 800,
44
+ });
45
+ if (!played.ok) return played;
46
+ }
47
+
48
+ // An empty object is a config of defaults, so undo of a created file
49
+ // leaves a project that behaves as it did.
50
+ const file = path.join(project.root, CONFIG);
51
+ if (project.staged?.get(file) === undefined && !(await Bun.file(file).exists())) {
52
+ if (project.staged) project.staged.set(file, "{}\n");
53
+ else await Bun.write(file, "{}\n");
54
+ }
55
+
56
+ return editFile(project, CONFIG, (source) => withFrame(source, frame));
57
+ },
58
+ };