@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,189 @@
1
+ import { htmlTagNames } from "html-tag-names";
2
+ import { elementAt, type Element } from "./language.ts";
3
+ import type { Location } from "./location.ts";
4
+ import type { Patch } from "./patch.ts";
5
+ import { refuse, type Refusal } from "./refusal.ts";
6
+ import { childAt, linesOf, reindent } from "./structure.ts";
7
+ import { VOID } from "./tag.ts";
8
+
9
+ // Tags whose content the page does not draw as HTML: the document's frame,
10
+ // scripts and styles, templates, and the roots of SVG and MathML.
11
+ const UNDRAWN = new Set([
12
+ "base",
13
+ "body",
14
+ "head",
15
+ "html",
16
+ "link",
17
+ "math",
18
+ "meta",
19
+ "noscript",
20
+ "script",
21
+ "slot",
22
+ "style",
23
+ "svg",
24
+ "template",
25
+ "title",
26
+ ]);
27
+
28
+ const WRITABLE = new Set(htmlTagNames.filter((name) => !UNDRAWN.has(name)));
29
+
30
+ // Their children are SVG or MathML, where an HTML tag draws nothing.
31
+ const FOREIGN = new Set(["svg", "math"]);
32
+
33
+ // Why lienzo does not write `name` next to the element, or inside it when
34
+ // `inside` is set, if it does not.
35
+ function unwritable(
36
+ name: string,
37
+ element: Element,
38
+ elements: Element[],
39
+ inside: boolean,
40
+ ): Refusal | undefined {
41
+ if (!WRITABLE.has(name)) return refuse(`"${name}" is not an HTML tag the page draws`);
42
+
43
+ const holds = (each: Element) =>
44
+ each.start <= element.start &&
45
+ element.end <= each.end &&
46
+ (inside || each.start < element.start);
47
+ const foreign = elements.find((each) => FOREIGN.has(each.name) && holds(each));
48
+ if (foreign) {
49
+ return refuse(`the new tag would be in an <${foreign.name}>, whose children are not HTML`);
50
+ }
51
+
52
+ return undefined;
53
+ }
54
+
55
+ // The step the file indents a child by: the smallest rise from one line to
56
+ // the next. Comment lines that start with `*` align to their opener instead.
57
+ function unitOf(source: string): string | undefined {
58
+ let unit: string | undefined;
59
+ let last = "";
60
+
61
+ for (const line of source.split("\n")) {
62
+ const trimmed = line.trimStart();
63
+ if (!trimmed || trimmed.startsWith("*")) continue;
64
+
65
+ const indent = line.slice(0, line.length - trimmed.length);
66
+ if (indent.length > last.length && indent.startsWith(last)) {
67
+ const rise = indent.slice(last.length);
68
+ if (!unit || rise.length < unit.length) unit = rise;
69
+ }
70
+ last = indent;
71
+ }
72
+
73
+ return unit;
74
+ }
75
+
76
+ function blank(name: string): string {
77
+ return VOID.has(name) ? `<${name} />` : `<${name}></${name}>`;
78
+ }
79
+
80
+ // Puts the element in a new `name` element, which is selected. An element on
81
+ // lines of its own gets the tags on lines of their own and moves in one
82
+ // indent. Where its text cannot take a new indent, the tags go on its lines.
83
+ export function wrapElement(source: string, at: Location, name: string): Patch {
84
+ const found = childAt(source, at);
85
+ if (!found.ok) return found;
86
+
87
+ const { element, elements } = found;
88
+ const wrong = unwritable(name, element, elements, false);
89
+ if (wrong) return wrong;
90
+ if (VOID.has(name)) return refuse(`<${name}> has no content, so it wraps nothing`);
91
+
92
+ const text = source.slice(element.start, element.end);
93
+ const wrap = (inner: string) => ({
94
+ ok: true as const,
95
+ code: source.slice(0, element.start) + inner + source.slice(element.end),
96
+ select: element.start,
97
+ });
98
+ const inline = wrap(`<${name}>${text}</${name}>`);
99
+
100
+ const lines = linesOf(source, element);
101
+ const unit = unitOf(source);
102
+ if (!lines || !unit) return inline;
103
+
104
+ const inner = lines.indent + unit;
105
+ const shifted = reindent(text, lines.indent, inner, element, elements);
106
+ if (!shifted.ok) return inline;
107
+
108
+ return wrap(`<${name}>\n${inner}${shifted.text}\n${lines.indent}</${name}>`);
109
+ }
110
+
111
+ export type Spot = "before" | "after" | "inside";
112
+
113
+ // Adds an empty `name` element next to the element, or as its last child,
114
+ // and selects it.
115
+ export function insertElement(source: string, at: Location, name: string, spot: Spot): Patch {
116
+ if (spot === "inside") return insertInside(source, at, name);
117
+
118
+ const found = childAt(source, at);
119
+ if (!found.ok) return found;
120
+
121
+ const { element, elements } = found;
122
+ const wrong = unwritable(name, element, elements, false);
123
+ if (wrong) return wrong;
124
+
125
+ const fresh = blank(name);
126
+ const lines = linesOf(source, element);
127
+ const gap = lines ? `\n${lines.indent}` : "";
128
+
129
+ if (spot === "before") {
130
+ return {
131
+ ok: true,
132
+ code: source.slice(0, element.start) + fresh + gap + source.slice(element.start),
133
+ select: element.start,
134
+ };
135
+ }
136
+
137
+ return {
138
+ ok: true,
139
+ code: source.slice(0, element.end) + gap + fresh + source.slice(element.end),
140
+ select: element.end + gap.length,
141
+ };
142
+ }
143
+
144
+ // Offset of the element's closing tag, when it has one.
145
+ function closingOf(source: string, element: Element): number | undefined {
146
+ const close = source.lastIndexOf("</", element.end - 1);
147
+ if (close <= element.start || source[element.end - 1] !== ">") return undefined;
148
+
149
+ return source.slice(close + 2, element.end - 1).trim() === element.name ? close : undefined;
150
+ }
151
+
152
+ // A closing tag on its own line gets the new child on a line before it, one
153
+ // indent in. Otherwise the child goes right before the closing tag.
154
+ function insertInside(source: string, at: Location, name: string): Patch {
155
+ const found = elementAt(source, at);
156
+ if (!found.ok) return found;
157
+
158
+ const { element, elements } = found;
159
+ const tag = `<${element.name}>`;
160
+ if (!element.host) {
161
+ return refuse(`${tag} is a component, whose code decides what its children do`);
162
+ }
163
+
164
+ const wrong = unwritable(name, element, elements, true);
165
+ if (wrong) return wrong;
166
+
167
+ const close = closingOf(source, element);
168
+ if (close === undefined) return refuse(`${tag} has no closing tag to hold a child`);
169
+
170
+ const fresh = blank(name);
171
+ const line = source.lastIndexOf("\n", close - 1) + 1;
172
+ const indent = source.slice(line, close);
173
+ const unit = unitOf(source);
174
+
175
+ if (line > element.start && unit && /^[ \t]*$/.test(indent)) {
176
+ const child = indent + unit;
177
+ return {
178
+ ok: true,
179
+ code: source.slice(0, line) + child + fresh + "\n" + source.slice(line),
180
+ select: line + child.length,
181
+ };
182
+ }
183
+
184
+ return {
185
+ ok: true,
186
+ code: source.slice(0, close) + fresh + source.slice(close),
187
+ select: close,
188
+ };
189
+ }
@@ -0,0 +1,136 @@
1
+ import { parseSync } from "oxc-parser";
2
+ import { defaultImportsOf, isNode, memberOf, walk, type Node } from "../estree.ts";
3
+ import type { Attribute, Element, Span } from "../language.ts";
4
+
5
+ // A string the source states outright: "a b", {"a b"} or {`a b`}.
6
+ function literal(value: Node): string | undefined {
7
+ if (value.type === "Literal") {
8
+ return typeof value.value === "string" ? value.value : undefined;
9
+ }
10
+
11
+ if (value.type !== "JSXExpressionContainer" || !isNode(value.expression)) return undefined;
12
+
13
+ const inner = value.expression;
14
+ if (inner.type === "Literal") return literal(inner);
15
+ if (inner.type !== "TemplateLiteral") return undefined;
16
+
17
+ const quasis = inner.quasis as { value: { cooked: string | null } }[];
18
+ const interpolated = (inner.expressions as unknown[]).length > 0;
19
+ return interpolated ? undefined : (quasis[0]?.value.cooked ?? undefined);
20
+ }
21
+
22
+ const CLASS_HELPERS = new Set(["cn", "clsx", "cx", "classNames", "twMerge"]);
23
+
24
+ function helperStrings(value: Node): Span[] | undefined {
25
+ if (value.type !== "JSXExpressionContainer" || !isNode(value.expression)) return undefined;
26
+
27
+ const call = value.expression;
28
+ if (call.type !== "CallExpression" || !isNode(call.callee)) return undefined;
29
+ if (call.callee.type !== "Identifier" || !CLASS_HELPERS.has(call.callee.name as string)) {
30
+ return undefined;
31
+ }
32
+
33
+ return (call.arguments as Node[])
34
+ .filter((argument) => argument.type === "Literal" && typeof argument.value === "string")
35
+ .map(({ start, end, value: text }) => ({ start, end, value: text as string }));
36
+ }
37
+
38
+ function member(value: Node) {
39
+ if (value.type !== "JSXExpressionContainer" || !isNode(value.expression)) return undefined;
40
+
41
+ return memberOf(value.expression);
42
+ }
43
+
44
+ function attribute(node: Node): Attribute | undefined {
45
+ if (node.type !== "JSXAttribute" || !isNode(node.name)) return undefined;
46
+ if (node.name.type !== "JSXIdentifier") return undefined;
47
+
48
+ const whole = { name: node.name.name as string, start: node.start, end: node.end };
49
+ if (!isNode(node.value)) return whole;
50
+
51
+ const { start, end } = node.value;
52
+ return {
53
+ ...whole,
54
+ value: {
55
+ start,
56
+ end,
57
+ literal: literal(node.value),
58
+ member: member(node.value),
59
+ strings: helperStrings(node.value),
60
+ },
61
+ };
62
+ }
63
+
64
+ // Nodes whose children are a list of siblings, and the key of that list.
65
+ // `AstroRoot` is the top level of an Astro template.
66
+ const LISTS: Record<string, string> = {
67
+ JSXElement: "children",
68
+ JSXFragment: "children",
69
+ AstroRoot: "body",
70
+ };
71
+
72
+ function element(source: string, node: Node, container?: number): Element | undefined {
73
+ const opening = node.openingElement;
74
+ if (!isNode(opening) || !isNode(opening.name)) return undefined;
75
+
76
+ const tag = opening.name;
77
+ const name = source.slice(tag.start, tag.end);
78
+ const parts = opening.attributes as Node[];
79
+
80
+ const closing = node.closingElement;
81
+ const children = node.children as Node[];
82
+ const onlyText = isNode(closing) && children.every((child) => child.type === "JSXText");
83
+
84
+ return {
85
+ name,
86
+ start: opening.start,
87
+ nameEnd: tag.end,
88
+ end: node.end,
89
+ container,
90
+ // React and Solid both read a lowercase tag as a DOM element.
91
+ host: tag.type === "JSXIdentifier" && /^[a-z]/.test(name),
92
+ attributes: parts.flatMap((part) => attribute(part) ?? []),
93
+ spread: parts.some((part) => part.type === "JSXSpreadAttribute"),
94
+ text: onlyText ? { start: opening.end, end: closing.start } : undefined,
95
+ };
96
+ }
97
+
98
+ function parse(file: string, source: string): Node {
99
+ const { program, errors } = parseSync(file, source);
100
+
101
+ const first = errors[0];
102
+ if (first) throw new Error(`${file}: ${first.message}`);
103
+
104
+ return program as unknown as Node;
105
+ }
106
+
107
+ // Every JSX element under the node, in source order.
108
+ export function elementsOf(source: string, root: Node): Element[] {
109
+ const found: Element[] = [];
110
+ const containers = new Map<Node, number>();
111
+ let lists = 0;
112
+
113
+ walk(root, (node) => {
114
+ const key = LISTS[node.type];
115
+ if (key) {
116
+ const list = lists++;
117
+ for (const child of node[key] as Node[]) containers.set(child, list);
118
+ }
119
+
120
+ if (node.type !== "JSXElement") return;
121
+
122
+ const read = element(source, node, containers.get(node));
123
+ if (read) found.push(read);
124
+ });
125
+
126
+ return found;
127
+ }
128
+
129
+ // Every JSX element in the file, in source order. Throws on a syntax error.
130
+ export function elements(file: string, source: string): Element[] {
131
+ return elementsOf(source, parse(file, source));
132
+ }
133
+
134
+ export function defaultImports(file: string, source: string): Map<string, string> {
135
+ return defaultImportsOf(parse(file, source));
136
+ }
@@ -0,0 +1,5 @@
1
+ import type { Language } from "../language.ts";
2
+ import { defaultImports, elements } from "./elements.ts";
3
+
4
+ // JSX in `.jsx` and `.tsx` files, as React and Solid write it.
5
+ export const jsx: Language = { extensions: [".jsx", ".tsx"], elements, defaultImports };
@@ -0,0 +1,176 @@
1
+ import path from "node:path";
2
+ import { astro } from "./astro/astro.ts";
3
+ import type { MemberName } from "./estree.ts";
4
+ import { jsx } from "./jsx/jsx.ts";
5
+ import { offsetOf, type Location } from "./location.ts";
6
+ import { refuse, type Refusal } from "./refusal.ts";
7
+ import { svelte } from "./svelte/svelte.ts";
8
+ import { tagOf } from "./tag.ts";
9
+ import { vue } from "./vue/vue.ts";
10
+
11
+ // The attribute that holds an element's classes. React writes `className`;
12
+ // Solid, Svelte and HTML write `class`.
13
+ export type ClassAttribute = "className" | "class";
14
+
15
+ // A value the source states outright, and the offsets of the span a new value
16
+ // overwrites. For a class list the span holds the quotes or braces too.
17
+ export type Stated = { ok: true; value: string; start: number; end: number };
18
+
19
+ // A class list the source states, and the span of its whole attribute, which
20
+ // an empty list removes.
21
+ export type Listed = Stated & {
22
+ attribute: { start: number; end: number };
23
+ strings?: Span[];
24
+ };
25
+
26
+ // A string literal and its offsets, quotes included. A class helper such as
27
+ // `cn("a", cond && "b")` lends its string arguments as spans.
28
+ export type Span = { start: number; end: number; value: string };
29
+
30
+ // An element with no class attribute, the offset where one goes, and the
31
+ // attribute's name.
32
+ export type Absent = { ok: true; value: ""; insert: number; name: ClassAttribute };
33
+
34
+ // A class attribute that names one member of one object, `styles.card`.
35
+ // `from` is what the file imports that object from, when it is a default
36
+ // import.
37
+ export type Member = { ok: true; object: string; property: string; from?: string };
38
+
39
+ // The element whose opening tag starts at a location.
40
+ export type Tag = {
41
+ ok: true;
42
+
43
+ // The tag as the source writes it: `button`, `Card`, `Menu.Item`.
44
+ name: string;
45
+
46
+ // The text between the tags, whitespace included.
47
+ text: Stated | Refusal;
48
+
49
+ classes(attribute: ClassAttribute): Listed | Absent | Refusal;
50
+ member(attribute: ClassAttribute): Member | Refusal;
51
+ };
52
+
53
+ export type Attribute = {
54
+ name: string;
55
+
56
+ // Offsets of the whole attribute, from its name to the end of its value.
57
+ start: number;
58
+ end: number;
59
+
60
+ // Offsets of the value, quotes or braces included. Absent for `<a disabled>`.
61
+ // `literal` is the value when the source states all of it; `member` is set
62
+ // when the value is one expression like `{styles.card}`.
63
+ value?: {
64
+ start: number;
65
+ end: number;
66
+ literal?: string;
67
+ member?: MemberName;
68
+ strings?: Span[];
69
+ };
70
+ };
71
+
72
+ // One element as a language reads it.
73
+ export type Element = {
74
+ name: string;
75
+
76
+ // Offset of `<`, of the end of the tag name, and after the element's last
77
+ // character: its closing tag, or the opening tag when it has none.
78
+ start: number;
79
+ nameEnd: number;
80
+ end: number;
81
+
82
+ // The list of nodes the element stands in, shared by its siblings: an
83
+ // element's or a fragment's children, a block's, or the template's top
84
+ // level. Absent where the code holds the element as one value, as in
85
+ // `{ok && <b />}` or `return <main />`, where a sibling breaks the code.
86
+ container?: number;
87
+
88
+ // A Vue element with `v-if`, `v-else-if` or `v-else`, whose place in the
89
+ // chain the template fixes.
90
+ chained?: boolean;
91
+
92
+ // An element the browser draws, as opposed to a component or a tag the
93
+ // framework consumes.
94
+ host: boolean;
95
+
96
+ attributes: Attribute[];
97
+ spread: boolean;
98
+
99
+ // The span between the tags when it holds nothing but text. Absent for a
100
+ // tag with no closing tag and for children that are elements, expressions
101
+ // or blocks.
102
+ text?: { start: number; end: number };
103
+ };
104
+
105
+ // A component's style block: its text, the offset in the file where that text
106
+ // starts, and the language its `lang` attribute names, when it has one.
107
+ export type StyleBlock = { start: number; css: string; lang?: string };
108
+
109
+ // A template language: the files it reads and how it reads them. The stamp
110
+ // and the answers of `tagAt` are built from what it reads.
111
+ export type Language = {
112
+ extensions: string[];
113
+
114
+ // The attribute every file of the language writes classes in. JSX leaves
115
+ // it to the project: React writes `className`, Solid `class`.
116
+ classAttribute?: ClassAttribute;
117
+
118
+ // Every element of the file, in source order. Throws on a syntax error.
119
+ elements(file: string, source: string): Element[];
120
+
121
+ // What each default import of the file names. Throws on a syntax error.
122
+ defaultImports(file: string, source: string): Map<string, string>;
123
+
124
+ // The style blocks the compiler serves as the component's CSS, in source
125
+ // order. Absent for a language whose files hold none. Throws on a syntax
126
+ // error.
127
+ styles?(file: string, source: string): StyleBlock[];
128
+ };
129
+
130
+ const languages: Language[] = [jsx, svelte, vue, astro];
131
+
132
+ export function languageOf(file: string): { ok: true; language: Language } | Refusal {
133
+ const extension = path.extname(file);
134
+ const language = languages.find((candidate) => candidate.extensions.includes(extension));
135
+
136
+ if (!language) {
137
+ const files = extension ? `${extension} files` : "a file without an extension";
138
+ return refuse(`no language reads ${files}`);
139
+ }
140
+
141
+ return { ok: true, language };
142
+ }
143
+
144
+ type Found = { ok: true; language: Language; element: Element; elements: Element[] };
145
+
146
+ // The element whose opening tag starts at the location, among every element
147
+ // of its file. Throws on a syntax error.
148
+ export function elementAt(source: string, at: Location): Found | Refusal {
149
+ const found = languageOf(at.file);
150
+ if (!found.ok) return found;
151
+
152
+ const { language } = found;
153
+ const offset = offsetOf(source, at);
154
+ const elements = language.elements(at.file, source);
155
+ const element = elements.find((each) => each.start === offset);
156
+
157
+ if (!element) return refuse(`no element starts at ${at.line}:${at.column}; the file changed`);
158
+
159
+ return { ok: true, language, element, elements };
160
+ }
161
+
162
+ // The element whose opening tag starts at the location. Throws on a syntax
163
+ // error.
164
+ export function tagAt(source: string, at: Location): Tag | Refusal {
165
+ const found = elementAt(source, at);
166
+ if (!found.ok) return found;
167
+
168
+ const { language, element } = found;
169
+
170
+ return tagOf(
171
+ source,
172
+ element,
173
+ () => language.defaultImports(at.file, source),
174
+ language.classAttribute,
175
+ );
176
+ }
@@ -0,0 +1,34 @@
1
+ export type Position = { line: number; column: number };
2
+
3
+ // Where an element's opening tag starts: `src/App.tsx:12:5`. The path is
4
+ // relative to the project root and uses forward slashes.
5
+ export type Location = Position & { file: string };
6
+
7
+ export function formatLocation(at: Location): string {
8
+ return `${at.file}:${at.line}:${at.column}`;
9
+ }
10
+
11
+ export function parseLocation(text: string): Location {
12
+ const match = /^(.+):(\d+):(\d+)$/.exec(text);
13
+ if (!match) throw new Error(`"${text}" is not a location; expected file:line:column`);
14
+ return { file: match[1]!, line: Number(match[2]), column: Number(match[3]) };
15
+ }
16
+
17
+ // Lines and columns count from 1, columns in UTF-16 units, as editors do.
18
+ export function positionOf(source: string, offset: number): Position {
19
+ const before = source.slice(0, offset);
20
+ const line = before.split("\n").length;
21
+
22
+ return { line, column: offset - before.lastIndexOf("\n") };
23
+ }
24
+
25
+ export function offsetOf(source: string, at: Position): number {
26
+ const lines = source.split("\n");
27
+
28
+ let offset = 0;
29
+ for (let index = 0; index < at.line - 1; index++) {
30
+ offset += (lines[index]?.length ?? 0) + 1;
31
+ }
32
+
33
+ return offset + at.column - 1;
34
+ }
@@ -0,0 +1,41 @@
1
+ import path from "node:path";
2
+ import { tagAt, type ClassAttribute } from "./language.ts";
3
+ import type { Location } from "./location.ts";
4
+ import { refuse, type Refusal } from "./refusal.ts";
5
+
6
+ // The rule a class attribute names: the stylesheet, relative to the project
7
+ // root like a location's file, and the selector.
8
+ export type ModuleClass = { ok: true; file: string; selector: string } | Refusal;
9
+
10
+ const MODULE = ".module.css";
11
+
12
+ // A CSS identifier with no escape: what `.card` can name without a backslash.
13
+ const CLASS = /^(--|-?[a-zA-Z_\u0080-￿])[\w\u0080-￿-]*$/;
14
+
15
+ // Resolves `{styles.card}` or `{styles["card"]}`, where `styles` is the
16
+ // default import of a CSS module, to the rule `.card` of that module.
17
+ export function moduleClass(source: string, at: Location, attribute: ClassAttribute): ModuleClass {
18
+ const tag = tagAt(source, at);
19
+ if (!tag.ok) return tag;
20
+
21
+ const member = tag.member(attribute);
22
+ if (!member.ok) return member;
23
+
24
+ // `styles["a.b"]` would read as the selector `.a.b`, a rule for two classes.
25
+ if (!CLASS.test(member.property)) {
26
+ return refuse(`"${member.property}" is not a class name a selector can state as is`);
27
+ }
28
+
29
+ const from = member.from;
30
+ if (from === undefined) return refuse(`${member.object} is not a default import`);
31
+ if (!from.endsWith(MODULE)) {
32
+ return refuse(`${member.object} comes from "${from}", not a ${MODULE}`);
33
+ }
34
+ if (!from.startsWith("./") && !from.startsWith("../")) {
35
+ return refuse(`"${from}" is not a path relative to ${at.file}`);
36
+ }
37
+
38
+ const file = path.posix.join(path.posix.dirname(at.file), from);
39
+
40
+ return { ok: true, file, selector: `.${member.property}` };
41
+ }
@@ -0,0 +1,35 @@
1
+ import { ATTRIBUTE, type StyleDeclaration } from "../protocol.ts";
2
+
3
+ export const OVERRIDES_FILE = "lienzo.overrides.css";
4
+
5
+ function escaped(text: string): string {
6
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7
+ }
8
+
9
+ function lineOf(declaration: Pick<StyleDeclaration, "property" | "value">): string {
10
+ return ` ${declaration.property}: ${declaration.value};`;
11
+ }
12
+
13
+ export function patchOverrides(
14
+ source: string,
15
+ at: string,
16
+ declarations: Pick<StyleDeclaration, "property" | "value">[],
17
+ ): string {
18
+ const selector = `[${ATTRIBUTE}="${at}"]`;
19
+ const block = new RegExp(`^${escaped(selector)} \\{\\n([\\s\\S]*?)^\\}\\n`, "m");
20
+ const held = block.exec(source);
21
+
22
+ const lines = new Map<string, string>();
23
+ for (const line of held?.[1]?.split("\n") ?? []) {
24
+ const property = /^\s*([\w-]+)\s*:/.exec(line)?.[1];
25
+ if (property) lines.set(property, line);
26
+ }
27
+ for (const declaration of declarations) lines.set(declaration.property, lineOf(declaration));
28
+
29
+ const written = `${selector} {\n${[...lines.values()].join("\n")}\n}\n`;
30
+ if (held) return source.replace(block, () => written);
31
+
32
+ const gap = !source || source.endsWith("\n\n") ? "" : source.endsWith("\n") ? "\n" : "\n\n";
33
+
34
+ return source + gap + written;
35
+ }
@@ -0,0 +1,69 @@
1
+ import type { Stack } from "../project/detect.ts";
2
+ import { refuse, type Refusal } from "./refusal.ts";
3
+
4
+ export type NewFile = { ok: true; file: string; code: string };
5
+
6
+ const ROUTE = /^\/(?:[a-z0-9]+(?:-[a-z0-9]+)*(?:\/[a-z0-9]+(?:-[a-z0-9]+)*)*)?$/;
7
+
8
+ function under(route: string): string {
9
+ return route === "/" ? "" : route.slice(1);
10
+ }
11
+
12
+ function join(...parts: string[]): string {
13
+ return parts.filter(Boolean).join("/");
14
+ }
15
+
16
+ // The page file a stack's router serves for a static route, with the markup a
17
+ // first edit starts from. `has` says whether a folder of the project exists,
18
+ // which picks the router a stack with two uses.
19
+ export function pageFile(
20
+ stack: Stack,
21
+ route: string,
22
+ has: (folder: string) => boolean,
23
+ ): NewFile | Refusal {
24
+ if (!ROUTE.test(route)) {
25
+ return refuse(`"${route}" is not a static route: use lowercase words joined by - and /`);
26
+ }
27
+ const path = under(route);
28
+
29
+ switch (stack) {
30
+ case "next": {
31
+ const root = has("src/app") ? "src/app" : has("app") ? "app" : undefined;
32
+ if (root) {
33
+ return {
34
+ ok: true,
35
+ file: join(root, path, "page.tsx"),
36
+ code: "export default function Page() {\n return <main></main>;\n}\n",
37
+ };
38
+ }
39
+ const pages = has("src/pages") ? "src/pages" : has("pages") ? "pages" : undefined;
40
+ if (!pages) return refuse("the project has no app or pages folder to serve the route");
41
+
42
+ return {
43
+ ok: true,
44
+ file: join(pages, path === "" ? "index" : path) + ".tsx",
45
+ code: "export default function Page() {\n return <main></main>;\n}\n",
46
+ };
47
+ }
48
+ case "astro":
49
+ return {
50
+ ok: true,
51
+ file: join("src/pages", path === "" ? "index" : path) + ".astro",
52
+ code: "---\n---\n\n<main></main>\n",
53
+ };
54
+ case "nuxt":
55
+ return {
56
+ ok: true,
57
+ file: join(has("app") ? "app/pages" : "pages", path === "" ? "index" : path) + ".vue",
58
+ code: "<template>\n <main></main>\n</template>\n",
59
+ };
60
+ case "sveltekit":
61
+ return {
62
+ ok: true,
63
+ file: join("src/routes", path, "+page.svelte"),
64
+ code: "<main></main>\n",
65
+ };
66
+ case "vite":
67
+ return refuse("a Vite project has no file router: its routes are declared in code");
68
+ }
69
+ }