@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,271 @@
|
|
|
1
|
+
import type { Attrs, Batch, Child, Op, Packet, Snapshot, Tree } from "./wire.ts";
|
|
2
|
+
|
|
3
|
+
const SKIPPED = new Set([
|
|
4
|
+
"script",
|
|
5
|
+
"noscript",
|
|
6
|
+
"iframe",
|
|
7
|
+
"frame",
|
|
8
|
+
"object",
|
|
9
|
+
"embed",
|
|
10
|
+
"template",
|
|
11
|
+
"base",
|
|
12
|
+
]);
|
|
13
|
+
const URLS = new Set(["href", "src", "action", "formaction", "xlink:href"]);
|
|
14
|
+
const FLUSH_MS = 500;
|
|
15
|
+
const HTML = "http://www.w3.org/1999/xhtml";
|
|
16
|
+
|
|
17
|
+
const ids = new WeakMap<Node, number>();
|
|
18
|
+
const sent = new WeakMap<HTMLStyleElement, string>();
|
|
19
|
+
let counter = 0;
|
|
20
|
+
|
|
21
|
+
const idOf = (node: Node) => {
|
|
22
|
+
let id = ids.get(node);
|
|
23
|
+
if (id === undefined) ids.set(node, (id = ++counter));
|
|
24
|
+
|
|
25
|
+
return id;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
function skipped(node: Node): boolean {
|
|
29
|
+
if (node.nodeType !== Node.ELEMENT_NODE && node.nodeType !== Node.TEXT_NODE) return true;
|
|
30
|
+
if (!(node instanceof Element)) return false;
|
|
31
|
+
if (SKIPPED.has(node.localName)) return true;
|
|
32
|
+
if (node.localName === "meta" && node.hasAttribute("http-equiv")) return true;
|
|
33
|
+
|
|
34
|
+
return (
|
|
35
|
+
node.localName === "link" &&
|
|
36
|
+
/preload|prefetch|modulepreload/.test(node.getAttribute("rel") ?? "")
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function safe(name: string, value: string): boolean {
|
|
41
|
+
if (name.startsWith("on") || name === "srcdoc") return false;
|
|
42
|
+
|
|
43
|
+
return !(URLS.has(name) && /^\s*javascript:/i.test(value));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function attributeOf(element: Element, name: string): string | null {
|
|
47
|
+
if (element instanceof HTMLInputElement) {
|
|
48
|
+
if (name === "value") return element.type === "password" ? null : element.value;
|
|
49
|
+
if (name === "checked") return element.checked ? "" : null;
|
|
50
|
+
}
|
|
51
|
+
if (element instanceof HTMLOptionElement && name === "selected")
|
|
52
|
+
return element.selected ? "" : null;
|
|
53
|
+
|
|
54
|
+
const value = element.getAttribute(name);
|
|
55
|
+
|
|
56
|
+
return value === null || safe(name, value) ? value : null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function attributesOf(element: Element): Attrs {
|
|
60
|
+
const names = new Set([...element.getAttributeNames()]);
|
|
61
|
+
if (element instanceof HTMLInputElement) names.add("value").add("checked");
|
|
62
|
+
if (element instanceof HTMLOptionElement) names.add("selected");
|
|
63
|
+
|
|
64
|
+
return [...names].flatMap((name) => {
|
|
65
|
+
const value = attributeOf(element, name);
|
|
66
|
+
|
|
67
|
+
return value === null ? [] : [[name, value] as [string, string]];
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function rulesOf(style: HTMLStyleElement): string {
|
|
72
|
+
try {
|
|
73
|
+
return style.sheet ? [...style.sheet.cssRules].map((rule) => rule.cssText).join("\n") : "";
|
|
74
|
+
} catch {
|
|
75
|
+
return style.textContent ?? "";
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function adoptedRules(): string[] {
|
|
80
|
+
return document.adoptedStyleSheets.map((sheet) =>
|
|
81
|
+
[...sheet.cssRules].map((rule) => rule.cssText).join("\n"),
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function canvasImage(canvas: HTMLCanvasElement): Attrs {
|
|
86
|
+
const attrs = attributesOf(canvas);
|
|
87
|
+
try {
|
|
88
|
+
attrs.push(["src", canvas.toDataURL()]);
|
|
89
|
+
} catch {}
|
|
90
|
+
|
|
91
|
+
return attrs;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function tree(node: Node, fresh: Set<Node>): Tree | null {
|
|
95
|
+
if (skipped(node)) return null;
|
|
96
|
+
fresh.add(node);
|
|
97
|
+
|
|
98
|
+
if (node instanceof Text) return { i: idOf(node), x: node.data };
|
|
99
|
+
const element = node as Element;
|
|
100
|
+
|
|
101
|
+
if (element instanceof HTMLStyleElement) {
|
|
102
|
+
const rules = rulesOf(element);
|
|
103
|
+
sent.set(element, rules);
|
|
104
|
+
|
|
105
|
+
return {
|
|
106
|
+
i: idOf(element),
|
|
107
|
+
t: "style",
|
|
108
|
+
a: attributesOf(element),
|
|
109
|
+
c: [{ i: ++counter, x: rules }],
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (element instanceof HTMLCanvasElement) {
|
|
114
|
+
return { i: idOf(element), t: "img", a: canvasImage(element), c: [] };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return {
|
|
118
|
+
i: idOf(element),
|
|
119
|
+
t: element.localName,
|
|
120
|
+
...(element.namespaceURI === HTML ? {} : { n: element.namespaceURI ?? undefined }),
|
|
121
|
+
a: attributesOf(element),
|
|
122
|
+
c: childrenOf(element, fresh).flatMap((child) => ("ref" in child ? [] : [child])),
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function childrenOf(parent: Node, fresh: Set<Node>): Child[] {
|
|
127
|
+
if (parent instanceof HTMLTextAreaElement) {
|
|
128
|
+
return [{ i: ++counter, x: parent.value }];
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
return [...parent.childNodes].flatMap((child): Child[] => {
|
|
132
|
+
if (skipped(child)) return [];
|
|
133
|
+
if (ids.has(child) && !fresh.has(child)) return [{ ref: idOf(child) }];
|
|
134
|
+
|
|
135
|
+
const built = tree(child, fresh);
|
|
136
|
+
|
|
137
|
+
return built ? [built] : [];
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function snapshot(): Snapshot {
|
|
142
|
+
return {
|
|
143
|
+
kind: "snapshot",
|
|
144
|
+
href: location.href,
|
|
145
|
+
root: tree(document.documentElement, new Set())!,
|
|
146
|
+
adopted: adoptedRules(),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export function observe(emit: (packet: Packet) => void): () => void {
|
|
151
|
+
const parents = new Set<Node>();
|
|
152
|
+
const attributes = new Map<Element, Set<string>>();
|
|
153
|
+
const texts = new Set<CharacterData>();
|
|
154
|
+
const styles = new Set<HTMLStyleElement>();
|
|
155
|
+
let adopted = "";
|
|
156
|
+
let scheduled = false;
|
|
157
|
+
|
|
158
|
+
const dirtyAttribute = (element: Element, name: string) =>
|
|
159
|
+
attributes.set(element, (attributes.get(element) ?? new Set()).add(name));
|
|
160
|
+
|
|
161
|
+
const schedule = () => {
|
|
162
|
+
if (scheduled) return;
|
|
163
|
+
scheduled = true;
|
|
164
|
+
requestAnimationFrame(flush);
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
function owner(node: Node): HTMLStyleElement | undefined {
|
|
168
|
+
const style = node instanceof HTMLStyleElement ? node : node.parentNode;
|
|
169
|
+
|
|
170
|
+
return style instanceof HTMLStyleElement ? style : undefined;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function record(records: MutationRecord[]) {
|
|
174
|
+
for (const change of records) {
|
|
175
|
+
const style = owner(change.target);
|
|
176
|
+
if (style) styles.add(style);
|
|
177
|
+
else if (change.type === "childList") parents.add(change.target);
|
|
178
|
+
else if (change.type === "characterData") texts.add(change.target as CharacterData);
|
|
179
|
+
else if (change.target instanceof Element)
|
|
180
|
+
dirtyAttribute(change.target, change.attributeName!);
|
|
181
|
+
}
|
|
182
|
+
schedule();
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function input(event: Event) {
|
|
186
|
+
const target = event.target;
|
|
187
|
+
if (target instanceof HTMLTextAreaElement) parents.add(target);
|
|
188
|
+
else if (target instanceof HTMLInputElement) {
|
|
189
|
+
dirtyAttribute(target, "value");
|
|
190
|
+
dirtyAttribute(target, "checked");
|
|
191
|
+
for (const radio of document.querySelectorAll(
|
|
192
|
+
`input[type=radio][name="${CSS.escape(target.name)}"]`,
|
|
193
|
+
)) {
|
|
194
|
+
dirtyAttribute(radio, "checked");
|
|
195
|
+
}
|
|
196
|
+
} else if (target instanceof HTMLSelectElement) {
|
|
197
|
+
for (const option of target.options) dirtyAttribute(option, "selected");
|
|
198
|
+
}
|
|
199
|
+
schedule();
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function sheets() {
|
|
203
|
+
for (const style of document.querySelectorAll("style")) {
|
|
204
|
+
if (ids.has(style) && sent.get(style) !== rulesOf(style)) styles.add(style);
|
|
205
|
+
}
|
|
206
|
+
if (JSON.stringify(adoptedRules()) !== adopted) schedule();
|
|
207
|
+
if (styles.size) schedule();
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function flush() {
|
|
211
|
+
scheduled = false;
|
|
212
|
+
record(observer.takeRecords());
|
|
213
|
+
|
|
214
|
+
const fresh = new Set<Node>();
|
|
215
|
+
const ops: Op[] = [];
|
|
216
|
+
const known = (node: Node) => ids.has(node) && !fresh.has(node) && node.isConnected;
|
|
217
|
+
|
|
218
|
+
for (const parent of parents) {
|
|
219
|
+
if (known(parent))
|
|
220
|
+
ops.push({ op: "children", i: idOf(parent), list: childrenOf(parent, fresh) });
|
|
221
|
+
}
|
|
222
|
+
for (const style of styles) {
|
|
223
|
+
const rules = rulesOf(style);
|
|
224
|
+
sent.set(style, rules);
|
|
225
|
+
if (known(style)) ops.push({ op: "css", i: idOf(style), x: rules });
|
|
226
|
+
}
|
|
227
|
+
for (const [element, names] of attributes) {
|
|
228
|
+
if (!known(element)) continue;
|
|
229
|
+
for (const name of names) {
|
|
230
|
+
ops.push({ op: "attr", i: idOf(element), name, value: attributeOf(element, name) });
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
for (const text of texts) {
|
|
234
|
+
if (known(text)) ops.push({ op: "text", i: idOf(text), x: text.data });
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const rules = adoptedRules();
|
|
238
|
+
if (JSON.stringify(rules) !== adopted) {
|
|
239
|
+
adopted = JSON.stringify(rules);
|
|
240
|
+
ops.push({ op: "adopted", sheets: rules });
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
parents.clear();
|
|
244
|
+
attributes.clear();
|
|
245
|
+
texts.clear();
|
|
246
|
+
styles.clear();
|
|
247
|
+
if (ops.length) emit({ kind: "batch", ops } satisfies Batch);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const first = snapshot();
|
|
251
|
+
adopted = JSON.stringify(first.adopted);
|
|
252
|
+
emit(first);
|
|
253
|
+
|
|
254
|
+
const observer = new MutationObserver(record);
|
|
255
|
+
observer.observe(document, {
|
|
256
|
+
subtree: true,
|
|
257
|
+
childList: true,
|
|
258
|
+
attributes: true,
|
|
259
|
+
characterData: true,
|
|
260
|
+
});
|
|
261
|
+
addEventListener("input", input, true);
|
|
262
|
+
addEventListener("change", input, true);
|
|
263
|
+
const timer = setInterval(sheets, FLUSH_MS);
|
|
264
|
+
|
|
265
|
+
return () => {
|
|
266
|
+
observer.disconnect();
|
|
267
|
+
removeEventListener("input", input, true);
|
|
268
|
+
removeEventListener("change", input, true);
|
|
269
|
+
clearInterval(timer);
|
|
270
|
+
};
|
|
271
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
|
|
3
|
+
const ENTRY = path.join(import.meta.dir, "entry.ts");
|
|
4
|
+
|
|
5
|
+
let bundled: Promise<string> | undefined;
|
|
6
|
+
|
|
7
|
+
export function observerScript(): Promise<string> {
|
|
8
|
+
bundled ??= Bun.build({ entrypoints: [ENTRY], target: "browser", format: "iife" }).then(
|
|
9
|
+
async ({ outputs, success, logs }) => {
|
|
10
|
+
if (!success || !outputs[0])
|
|
11
|
+
throw new Error(`the observer did not bundle: ${logs.join("\n")}`);
|
|
12
|
+
|
|
13
|
+
return outputs[0].text();
|
|
14
|
+
},
|
|
15
|
+
);
|
|
16
|
+
|
|
17
|
+
return bundled;
|
|
18
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export type Attrs = [name: string, value: string][];
|
|
2
|
+
|
|
3
|
+
export type Tree =
|
|
4
|
+
| { i: number; x: string }
|
|
5
|
+
| { i: number; t: string; n?: string; a: Attrs; c: Tree[] };
|
|
6
|
+
|
|
7
|
+
export type Child = { ref: number } | Tree;
|
|
8
|
+
|
|
9
|
+
export type Op =
|
|
10
|
+
| { op: "attr"; i: number; name: string; value: string | null }
|
|
11
|
+
| { op: "text"; i: number; x: string }
|
|
12
|
+
| { op: "children"; i: number; list: Child[] }
|
|
13
|
+
| { op: "css"; i: number; x: string }
|
|
14
|
+
| { op: "adopted"; sheets: string[] };
|
|
15
|
+
|
|
16
|
+
export type Snapshot = {
|
|
17
|
+
kind: "snapshot";
|
|
18
|
+
href: string;
|
|
19
|
+
root: Tree;
|
|
20
|
+
adopted: string[];
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export type Batch = { kind: "batch"; ops: Op[] };
|
|
24
|
+
|
|
25
|
+
export type Packet = Snapshot | Batch;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { step } from "./step.ts";
|
|
4
|
+
|
|
5
|
+
export const CONFIG = "lienzo.json";
|
|
6
|
+
|
|
7
|
+
// An env name as a shell exports it.
|
|
8
|
+
const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
9
|
+
|
|
10
|
+
const needed = z.strictObject({
|
|
11
|
+
description: z.string().trim().min(1),
|
|
12
|
+
docs: z.url({ protocol: /^https?$/ }).optional(),
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
// A page a person looks at, drawn at one size. `id` names it across commits.
|
|
16
|
+
// `steps` act on the page after it loads; the frame is the state they leave.
|
|
17
|
+
const frame = z.strictObject({
|
|
18
|
+
id: z.string().trim().min(1),
|
|
19
|
+
path: z.string().startsWith("/"),
|
|
20
|
+
steps: z.array(step).default([]),
|
|
21
|
+
width: z.number().int().positive().default(1280),
|
|
22
|
+
height: z.number().int().positive().default(800),
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
const schema = z.strictObject({
|
|
26
|
+
dev: z.string().trim().min(1).default("dev"),
|
|
27
|
+
build: z.string().trim().min(1).default("build"),
|
|
28
|
+
output: z.string().trim().min(1).default("dist"),
|
|
29
|
+
frames: z.array(frame).default([{ id: "home", path: "/", steps: [], width: 1280, height: 800 }]),
|
|
30
|
+
install: z.string().trim().min(1).optional(),
|
|
31
|
+
env: z.record(z.string().regex(NAME, "is not an env name"), needed).default({}),
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
export type Config = z.infer<typeof schema>;
|
|
35
|
+
|
|
36
|
+
function problemOf(error: z.ZodError): string {
|
|
37
|
+
const issue = error.issues[0]!;
|
|
38
|
+
const field = issue.path.join(".");
|
|
39
|
+
// A record key's own message sits one level down.
|
|
40
|
+
const message = issue.code === "invalid_key" ? issue.issues[0]!.message : issue.message;
|
|
41
|
+
|
|
42
|
+
return field ? `${field}: ${message}` : message;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// The config a lienzo.json's text holds. A config that does not parse, or
|
|
46
|
+
// names a field lienzo does not know, is an error rather than a default, so a
|
|
47
|
+
// typo never runs the wrong command.
|
|
48
|
+
export function parseConfig(text: string): Config {
|
|
49
|
+
let json: unknown;
|
|
50
|
+
try {
|
|
51
|
+
json = JSON.parse(text);
|
|
52
|
+
} catch (error) {
|
|
53
|
+
throw new Error(`${CONFIG} is not JSON: ${(error as Error).message}`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const parsed = schema.safeParse(json);
|
|
57
|
+
if (!parsed.success) throw new Error(`${CONFIG}: ${problemOf(parsed.error)}`);
|
|
58
|
+
|
|
59
|
+
return parsed.data;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export type NewFrame = z.input<typeof frame>;
|
|
63
|
+
|
|
64
|
+
// The text of a lienzo.json with one more frame, or the reason it cannot hold
|
|
65
|
+
// it. A file that lists no frames draws the default home frame, so that frame
|
|
66
|
+
// is written out before the new one joins it.
|
|
67
|
+
export function withFrame(
|
|
68
|
+
text: string,
|
|
69
|
+
added: NewFrame,
|
|
70
|
+
): { ok: true; code: string } | { ok: false; reason: string } {
|
|
71
|
+
let json: Record<string, unknown>;
|
|
72
|
+
try {
|
|
73
|
+
json = JSON.parse(text) as Record<string, unknown>;
|
|
74
|
+
} catch (error) {
|
|
75
|
+
return { ok: false, reason: `${CONFIG} is not JSON: ${(error as Error).message}` };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const listed = (json.frames as unknown[] | undefined) ?? schema.parse({}).frames;
|
|
79
|
+
const code = `${JSON.stringify({ ...json, frames: [...listed, added] }, null, 2)}\n`;
|
|
80
|
+
|
|
81
|
+
try {
|
|
82
|
+
const ids = parseConfig(code).frames.map((candidate) => candidate.id);
|
|
83
|
+
if (new Set(ids).size !== ids.length) {
|
|
84
|
+
return { ok: false, reason: `${CONFIG} already has a frame "${added.id}"` };
|
|
85
|
+
}
|
|
86
|
+
} catch (error) {
|
|
87
|
+
return { ok: false, reason: (error as Error).message };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return { ok: true, code };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// The project's config, or the defaults when it has none.
|
|
94
|
+
export async function loadConfig(root: string): Promise<Config> {
|
|
95
|
+
const file = Bun.file(path.join(root, CONFIG));
|
|
96
|
+
|
|
97
|
+
return (await file.exists()) ? parseConfig(await file.text()) : schema.parse({});
|
|
98
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { __unstable__loadDesignSystem } from "@tailwindcss/node";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import type { DesignSystem } from "../source/style.ts";
|
|
4
|
+
import { sourceFiles } from "./files.ts";
|
|
5
|
+
import type { Project } from "./project.ts";
|
|
6
|
+
|
|
7
|
+
const ENTRY = /@import\s+["']tailwindcss["']/;
|
|
8
|
+
|
|
9
|
+
type Stylesheet = { file: string; source: string };
|
|
10
|
+
|
|
11
|
+
async function stylesheets(root: string): Promise<Stylesheet[]> {
|
|
12
|
+
const files = await sourceFiles(root, ".css");
|
|
13
|
+
|
|
14
|
+
return Promise.all(
|
|
15
|
+
files.map(async (file) => ({ file, source: await Bun.file(path.join(root, file)).text() })),
|
|
16
|
+
);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function shared(a: string, b: string): number {
|
|
20
|
+
const left = a.split("/");
|
|
21
|
+
const right = b.split("/");
|
|
22
|
+
let count = 0;
|
|
23
|
+
|
|
24
|
+
while (count < left.length && left[count] === right[count]) count++;
|
|
25
|
+
|
|
26
|
+
return count;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// A design system answers its first canonicalization in seconds, while it
|
|
30
|
+
// indexes every utility, and the next ones in milliseconds. It is kept until
|
|
31
|
+
// any stylesheet of the project changes, since an entry can import the theme
|
|
32
|
+
// from another file.
|
|
33
|
+
const loaded = new Map<string, { stamp: string; design: Promise<DesignSystem> }>();
|
|
34
|
+
|
|
35
|
+
// Tailwind as the stylesheet nearest `file` configures it: its theme, its
|
|
36
|
+
// utilities and its variants.
|
|
37
|
+
//
|
|
38
|
+
// The engine is lienzo's copy of Tailwind; `@import "tailwindcss"` and the
|
|
39
|
+
// project's plugins resolve from the stylesheet's folder, so the theme is the
|
|
40
|
+
// project's.
|
|
41
|
+
export async function designOf(project: Project, file: string): Promise<DesignSystem | undefined> {
|
|
42
|
+
const all = await stylesheets(project.root);
|
|
43
|
+
const found = all.filter((sheet) => ENTRY.test(sheet.source));
|
|
44
|
+
if (found.length === 0) return undefined;
|
|
45
|
+
|
|
46
|
+
const entry = found.reduce((best, next) =>
|
|
47
|
+
shared(next.file, file) > shared(best.file, file) ? next : best,
|
|
48
|
+
);
|
|
49
|
+
const absolute = path.join(project.root, entry.file);
|
|
50
|
+
const stamp = all.map((sheet) => `${sheet.file}\n${sheet.source}`).join("\n");
|
|
51
|
+
|
|
52
|
+
const held = loaded.get(absolute);
|
|
53
|
+
if (held?.stamp === stamp) return held.design;
|
|
54
|
+
|
|
55
|
+
const design = __unstable__loadDesignSystem(entry.source, { base: path.dirname(absolute) });
|
|
56
|
+
loaded.set(absolute, { stamp, design });
|
|
57
|
+
|
|
58
|
+
return design;
|
|
59
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import type { Config } from "./config.ts";
|
|
2
|
+
|
|
3
|
+
// Reads one file of the repository, or returns undefined when it has none.
|
|
4
|
+
// The CLI reads the disk and the edge reads the GitHub contents API, so both
|
|
5
|
+
// preselect from the same answer.
|
|
6
|
+
export type Read = (file: string) => Promise<string | undefined>;
|
|
7
|
+
|
|
8
|
+
export const STACKS = ["vite", "next", "astro", "nuxt", "sveltekit"] as const;
|
|
9
|
+
export type Stack = (typeof STACKS)[number];
|
|
10
|
+
|
|
11
|
+
// The package that names each stack, in the order a manifest is tested: a Next
|
|
12
|
+
// or Nuxt project also depends on packages a bare Vite one does.
|
|
13
|
+
const MARKERS: [Stack, string][] = [
|
|
14
|
+
["next", "next"],
|
|
15
|
+
["nuxt", "nuxt"],
|
|
16
|
+
["astro", "astro"],
|
|
17
|
+
["sveltekit", "@sveltejs/kit"],
|
|
18
|
+
["vite", "vite"],
|
|
19
|
+
];
|
|
20
|
+
|
|
21
|
+
const MANAGERS: [string, string][] = [
|
|
22
|
+
["bun.lock", "bun"],
|
|
23
|
+
["bun.lockb", "bun"],
|
|
24
|
+
["pnpm-lock.yaml", "pnpm"],
|
|
25
|
+
["yarn.lock", "yarn"],
|
|
26
|
+
["package-lock.json", "npm"],
|
|
27
|
+
];
|
|
28
|
+
|
|
29
|
+
// The folder a static build writes, which `lienzo snap` serves.
|
|
30
|
+
const OUTPUT: Record<Stack, string> = {
|
|
31
|
+
vite: "dist",
|
|
32
|
+
next: "out",
|
|
33
|
+
astro: "dist",
|
|
34
|
+
nuxt: ".output/public",
|
|
35
|
+
sveltekit: "build",
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
// How many pages a first frame list holds. A person adds the rest.
|
|
39
|
+
const FIRST_FRAMES = 6;
|
|
40
|
+
|
|
41
|
+
export type Detected = {
|
|
42
|
+
stack: Stack;
|
|
43
|
+
manager: string | undefined;
|
|
44
|
+
config: Pick<Config, "dev" | "build" | "output" | "frames">;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
type Manifest = {
|
|
48
|
+
scripts?: Record<string, unknown>;
|
|
49
|
+
dependencies?: Record<string, string>;
|
|
50
|
+
devDependencies?: Record<string, string>;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
function manifestOf(text: string | undefined): Manifest | undefined {
|
|
54
|
+
try {
|
|
55
|
+
return text === undefined ? undefined : (JSON.parse(text) as Manifest);
|
|
56
|
+
} catch {
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// What a folder holds when it is an app of the stack and not a package that
|
|
62
|
+
// only depends on it, as lienzo's own does for its fixtures: a Nuxt
|
|
63
|
+
// dependency alone draws Nuxt's welcome page, which no source of the project
|
|
64
|
+
// states. Each pattern is relative to the folder.
|
|
65
|
+
const ENTRIES: Record<Stack, RegExp> = {
|
|
66
|
+
next: /^(?:next\.config\.[cm]?[jt]s|(?:src\/)?(?:app|pages)\/.+)$/,
|
|
67
|
+
nuxt: /^(?:nuxt\.config\.[cm]?[jt]s|(?:app\/)?(?:app\.vue|pages\/.+))$/,
|
|
68
|
+
astro: /^(?:astro\.config\.[cm]?[jt]s|src\/pages\/.+)$/,
|
|
69
|
+
sveltekit: /^(?:svelte\.config\.[cm]?[jt]s|src\/routes\/.+)$/,
|
|
70
|
+
vite: /^(?:index\.html|vite\.config\.[cm]?[jt]s)$/,
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
function holds(root: string, paths: string[], stack: Stack): boolean {
|
|
74
|
+
const prefix = root === "" ? "" : `${root}/`;
|
|
75
|
+
|
|
76
|
+
return paths.some(
|
|
77
|
+
(file) => file.startsWith(prefix) && ENTRIES[stack].test(file.slice(prefix.length)),
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function stackNamed(manifestText: string | undefined): Stack | undefined {
|
|
82
|
+
const manifest = manifestOf(manifestText);
|
|
83
|
+
const needs = { ...manifest?.dependencies, ...manifest?.devDependencies };
|
|
84
|
+
|
|
85
|
+
return MARKERS.find(([, name]) => name in needs)?.[0];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function stackOf(manifest: Manifest, root: string, paths: string[]): Stack | undefined {
|
|
89
|
+
const needs = { ...manifest.dependencies, ...manifest.devDependencies };
|
|
90
|
+
|
|
91
|
+
return MARKERS.find(([stack, name]) => name in needs && holds(root, paths, stack))?.[0];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const inside = (root: string, file: string) => (root === "" ? file : `${root}/${file}`);
|
|
95
|
+
|
|
96
|
+
// Every folder of the repository that holds a package.json with a stack
|
|
97
|
+
// lienzo knows, from the repository's file list. A folder under
|
|
98
|
+
// node_modules is never one. The shallowest comes first.
|
|
99
|
+
export async function folders(paths: string[], read: Read): Promise<string[]> {
|
|
100
|
+
const roots = paths
|
|
101
|
+
.filter((file) => !file.includes("node_modules/"))
|
|
102
|
+
.filter((file) => file === "package.json" || file.endsWith("/package.json"))
|
|
103
|
+
.map((file) => file.slice(0, -"package.json".length).replace(/\/$/, ""))
|
|
104
|
+
.sort((a, b) => a.split("/").length - b.split("/").length || a.localeCompare(b));
|
|
105
|
+
|
|
106
|
+
const known: string[] = [];
|
|
107
|
+
for (const root of roots) {
|
|
108
|
+
const manifest = manifestOf(await read(inside(root, "package.json")));
|
|
109
|
+
if (manifest && stackOf(manifest, root, paths)) known.push(root);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return known;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// The pages a file router serves, as URL paths, static ones only: a route with
|
|
116
|
+
// a parameter has no page to draw until a person names one.
|
|
117
|
+
function routesOf(stack: Stack, root: string, paths: string[]): string[] {
|
|
118
|
+
const patterns: Partial<Record<Stack, RegExp[]>> = {
|
|
119
|
+
next: [/^(?:src\/)?app\/(.*?)\/?page\.[jt]sx?$/, /^(?:src\/)?pages\/(.+)\.[jt]sx?$/],
|
|
120
|
+
astro: [/^src\/pages\/(.+)\.(?:astro|md|mdx)$/],
|
|
121
|
+
nuxt: [/^(?:app\/)?pages\/(.+)\.vue$/],
|
|
122
|
+
sveltekit: [/^src\/routes\/(.*?)\/?\+page\.svelte$/],
|
|
123
|
+
};
|
|
124
|
+
const matchers = patterns[stack];
|
|
125
|
+
if (!matchers) return ["/"];
|
|
126
|
+
|
|
127
|
+
const prefix = root === "" ? "" : `${root}/`;
|
|
128
|
+
const routes = new Set<string>();
|
|
129
|
+
for (const file of paths) {
|
|
130
|
+
if (!file.startsWith(prefix)) continue;
|
|
131
|
+
for (const matcher of matchers) {
|
|
132
|
+
const found = matcher.exec(file.slice(prefix.length));
|
|
133
|
+
if (!found) continue;
|
|
134
|
+
|
|
135
|
+
const route = (found[1] ?? "")
|
|
136
|
+
.split("/")
|
|
137
|
+
.filter((part) => part !== "index" && !/^\(.*\)$/.test(part))
|
|
138
|
+
.join("/");
|
|
139
|
+
if (/[[\]$+_]/.test(route) || /(^|\/)(api|404)(\/|$)/.test(route)) continue;
|
|
140
|
+
routes.add(`/${route}`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return [...routes].sort(
|
|
145
|
+
(a, b) => a.split("/").length - b.split("/").length || a.localeCompare(b),
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const idOf = (route: string) => (route === "/" ? "home" : route.slice(1).replaceAll("/", "-"));
|
|
150
|
+
|
|
151
|
+
// The stack, package manager, commands, output folder and first frames of the
|
|
152
|
+
// project in `root` ("" for the repository's top), or undefined when no stack
|
|
153
|
+
// lienzo knows lives there. `paths` is every file of the repository.
|
|
154
|
+
export async function detect(
|
|
155
|
+
root: string,
|
|
156
|
+
paths: string[],
|
|
157
|
+
read: Read,
|
|
158
|
+
): Promise<Detected | undefined> {
|
|
159
|
+
const manifest = manifestOf(await read(inside(root, "package.json")));
|
|
160
|
+
const stack = manifest && stackOf(manifest, root, paths);
|
|
161
|
+
if (!manifest || !stack) return undefined;
|
|
162
|
+
|
|
163
|
+
let manager: string | undefined;
|
|
164
|
+
for (const [lock, name] of MANAGERS) {
|
|
165
|
+
// A workspace keeps its one lockfile at the repository's top.
|
|
166
|
+
if (paths.includes(inside(root, lock)) || paths.includes(lock)) {
|
|
167
|
+
manager = name;
|
|
168
|
+
break;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const scripts = manifest.scripts ?? {};
|
|
173
|
+
const build = stack === "nuxt" && "generate" in scripts ? "generate" : "build";
|
|
174
|
+
const routes = routesOf(stack, root, paths);
|
|
175
|
+
const frames = (routes.length > 0 ? routes : ["/"]).slice(0, FIRST_FRAMES).map((route) => ({
|
|
176
|
+
id: idOf(route),
|
|
177
|
+
path: route,
|
|
178
|
+
steps: [],
|
|
179
|
+
width: 1280,
|
|
180
|
+
height: 800,
|
|
181
|
+
}));
|
|
182
|
+
|
|
183
|
+
return { stack, manager, config: { dev: "dev", build, output: OUTPUT[stack], frames } };
|
|
184
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { readdir } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
// Folders that hold installed or built code, not the project's source.
|
|
5
|
+
const SKIPPED = new Set(["node_modules", "dist", "build", "out", "coverage"]);
|
|
6
|
+
|
|
7
|
+
async function walk(root: string, folder: string, extension: string): Promise<string[]> {
|
|
8
|
+
const entries = await readdir(path.join(root, folder), { withFileTypes: true });
|
|
9
|
+
const found: string[] = [];
|
|
10
|
+
|
|
11
|
+
for (const entry of entries) {
|
|
12
|
+
const relative = path.posix.join(folder, entry.name);
|
|
13
|
+
|
|
14
|
+
if (entry.isDirectory()) {
|
|
15
|
+
const skipped = entry.name.startsWith(".") || SKIPPED.has(entry.name);
|
|
16
|
+
if (!skipped) found.push(...(await walk(root, relative, extension)));
|
|
17
|
+
} else if (entry.name.endsWith(extension)) {
|
|
18
|
+
found.push(relative);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
return found;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// The project's source files with an extension, relative to its root, sorted.
|
|
26
|
+
export async function sourceFiles(root: string, extension: string): Promise<string[]> {
|
|
27
|
+
const found = await walk(root, "", extension);
|
|
28
|
+
|
|
29
|
+
return found.sort();
|
|
30
|
+
}
|