@runic-artifex/vite-plugin-runic 0.19.0 → 0.20.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 +532 -12
- package/dist/access.d.ts +46 -0
- package/dist/access.js +123 -0
- package/dist/calls.d.ts +83 -0
- package/dist/calls.js +140 -0
- package/dist/channel.d.ts +58 -1
- package/dist/channel.js +20 -1
- package/dist/client.js +210 -1
- package/dist/dev-session.d.ts +19 -2
- package/dist/dev-session.js +67 -46
- package/dist/diagnostics.d.ts +2 -0
- package/dist/diagnostics.js +2 -1
- package/dist/handlers.d.ts +140 -0
- package/dist/handlers.js +773 -0
- package/dist/index.d.ts +39 -0
- package/dist/index.js +226 -11
- package/dist/inspect-data.d.ts +268 -0
- package/dist/inspect-data.js +442 -0
- package/dist/inspect-edit.d.ts +164 -0
- package/dist/inspect-edit.js +273 -0
- package/dist/inspect-editor.d.ts +34 -0
- package/dist/inspect-editor.js +282 -0
- package/dist/inspect-frameworks.d.ts +72 -0
- package/dist/inspect-frameworks.js +333 -0
- package/dist/inspect-handlers.d.ts +84 -0
- package/dist/inspect-handlers.js +331 -0
- package/dist/inspect.d.ts +42 -0
- package/dist/inspect.js +783 -0
- package/dist/otlp.d.ts +80 -0
- package/dist/otlp.js +254 -0
- package/dist/requests.d.ts +17 -0
- package/dist/requests.js +67 -0
- package/dist/sources.d.ts +135 -0
- package/dist/sources.js +343 -0
- package/dist/timeline.d.ts +12 -0
- package/dist/timeline.js +14 -0
- package/dist/translations-source.d.ts +36 -0
- package/dist/translations-source.js +109 -0
- package/package.json +12 -6
package/dist/handlers.js
ADDED
|
@@ -0,0 +1,773 @@
|
|
|
1
|
+
// Runic Inspect before the first click (#976): which event handlers of a frontend file reach which generated-client
|
|
2
|
+
// call, found in the file's source. The development server analyzes a file when Runic Inspect asks for it
|
|
3
|
+
// (`/__runic/handlers?file=…`); served modules are not changed, and the build never runs it.
|
|
4
|
+
//
|
|
5
|
+
// Per file, the analysis takes each event binding of the markup (JSX `onClick={…}`, Svelte `onclick={…}` and
|
|
6
|
+
// `on:click={…}`, Vue `@click="…"`, Angular `(click)="…"`) and follows its expression through the file: identifiers
|
|
7
|
+
// to their declarations (variables, functions, destructuring), `this.x` and template names to class members and
|
|
8
|
+
// object methods, into the callbacks of Runic's helpers (`useCommand(() => client.save())`, `injectCommand(…)`, …).
|
|
9
|
+
// Every `x.member(…)` call it reaches is a candidate; `x.command("member")` too. Runic Inspect keeps the candidates
|
|
10
|
+
// that are commands of a ViewModel in the Bridge source map. Names imported from other files are reported, not
|
|
11
|
+
// followed: their commands are learned from the first click, as before.
|
|
12
|
+
import { readFileSync, statSync } from "node:fs";
|
|
13
|
+
import { createRequire } from "node:module";
|
|
14
|
+
import { dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
|
|
15
|
+
import { pathToFileURL } from "node:url";
|
|
16
|
+
import { mayRead as mayReadRequest } from "./requests.js";
|
|
17
|
+
function isNode(value) {
|
|
18
|
+
return typeof value === "object" && value !== null && typeof value.type === "string";
|
|
19
|
+
}
|
|
20
|
+
const skippedKeys = new Set(["type", "start", "end", "loc", "range", "typeAnnotation", "typeArguments", "typeParameters",
|
|
21
|
+
"returnType", "decorators", "superTypeArguments", "implements", "metadata"]);
|
|
22
|
+
function children(node) {
|
|
23
|
+
const result = [];
|
|
24
|
+
for (const key in node) {
|
|
25
|
+
if (skippedKeys.has(key))
|
|
26
|
+
continue;
|
|
27
|
+
const value = node[key];
|
|
28
|
+
if (Array.isArray(value)) {
|
|
29
|
+
for (const item of value)
|
|
30
|
+
if (isNode(item))
|
|
31
|
+
result.push(item);
|
|
32
|
+
}
|
|
33
|
+
else if (isNode(value))
|
|
34
|
+
result.push(value);
|
|
35
|
+
}
|
|
36
|
+
return result;
|
|
37
|
+
}
|
|
38
|
+
/** Runic helpers whose result's methods (`run`, `cancel`, `commit`, `client`) are not commands. */
|
|
39
|
+
const helperNames = new Set([
|
|
40
|
+
"useCommand", "useOperation", "useLatestOperation", "useField", "useTextField", "useForm", "useView", "useViewState",
|
|
41
|
+
"useSuspenseView", "useText", "useQueryCollection", "useCollectionViewport", "useMenuBar",
|
|
42
|
+
"injectCommand", "injectOperation", "injectLatestOperation", "injectField", "injectTextField", "injectForm",
|
|
43
|
+
"injectView", "injectViewResource", "injectText", "injectQueryCollection", "injectCollectionViewport", "injectMenuBar",
|
|
44
|
+
"createCommandController", "createOperationController", "createLatestOperationController", "createFieldController",
|
|
45
|
+
]);
|
|
46
|
+
/** Helpers whose arguments are the callbacks that call the client; the others' arguments are not followed. */
|
|
47
|
+
const callbackHelpers = new Set(["useCommand", "useOperation", "injectCommand", "injectOperation", "createCommandController",
|
|
48
|
+
"createOperationController"]);
|
|
49
|
+
/** Packages whose imports are not application code in another file. */
|
|
50
|
+
function isLibrary(source) {
|
|
51
|
+
return !source.startsWith(".") && !source.startsWith("/") && !source.startsWith("$lib") && !source.startsWith("~")
|
|
52
|
+
&& !source.startsWith("@/") && !/^[a-z]:[\\/]/iu.test(source);
|
|
53
|
+
}
|
|
54
|
+
/** The declarations of a script, by name. Scopes are not separated: the analysis is per file. */
|
|
55
|
+
class Declarations {
|
|
56
|
+
bindings = new Map();
|
|
57
|
+
members = new Map();
|
|
58
|
+
imports = new Map();
|
|
59
|
+
add(program) {
|
|
60
|
+
const visit = (node) => {
|
|
61
|
+
switch (node.type) {
|
|
62
|
+
case "ImportDeclaration": {
|
|
63
|
+
const source = node["source"]?.["value"];
|
|
64
|
+
for (const specifier of node["specifiers"] ?? []) {
|
|
65
|
+
const local = specifier["local"]?.["name"];
|
|
66
|
+
if (typeof local === "string" && typeof source === "string")
|
|
67
|
+
this.imports.set(local, source);
|
|
68
|
+
}
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
case "VariableDeclarator": {
|
|
72
|
+
const init = node["init"];
|
|
73
|
+
if (isNode(init))
|
|
74
|
+
for (const name of patternNames(node["id"]))
|
|
75
|
+
push(this.bindings, name, init);
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
case "FunctionDeclaration": {
|
|
79
|
+
const name = node["id"]?.["name"];
|
|
80
|
+
if (typeof name === "string")
|
|
81
|
+
push(this.bindings, name, node);
|
|
82
|
+
break;
|
|
83
|
+
}
|
|
84
|
+
case "PropertyDefinition":
|
|
85
|
+
case "MethodDefinition":
|
|
86
|
+
case "Property":
|
|
87
|
+
case "AccessorProperty": {
|
|
88
|
+
const name = propertyName(node);
|
|
89
|
+
const value = node["value"];
|
|
90
|
+
if (name !== undefined && isNode(value)
|
|
91
|
+
&& (node.type !== "Property" || isFunction(value) || node["shorthand"] === true))
|
|
92
|
+
push(this.members, name, value);
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
for (const child of children(node))
|
|
97
|
+
visit(child);
|
|
98
|
+
};
|
|
99
|
+
visit(program);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function push(map, name, node) {
|
|
103
|
+
const list = map.get(name);
|
|
104
|
+
if (list === undefined)
|
|
105
|
+
map.set(name, [node]);
|
|
106
|
+
else if (!list.includes(node))
|
|
107
|
+
list.push(node);
|
|
108
|
+
}
|
|
109
|
+
function isFunction(node) {
|
|
110
|
+
return node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression" || node.type === "FunctionDeclaration";
|
|
111
|
+
}
|
|
112
|
+
function propertyName(node) {
|
|
113
|
+
const key = node["key"];
|
|
114
|
+
if (key === undefined)
|
|
115
|
+
return undefined;
|
|
116
|
+
if (node["computed"] === true)
|
|
117
|
+
return typeof key["value"] === "string" ? key["value"] : undefined;
|
|
118
|
+
if (key.type === "Identifier" || key.type === "PrivateIdentifier")
|
|
119
|
+
return key["name"];
|
|
120
|
+
return typeof key["value"] === "string" ? key["value"] : undefined;
|
|
121
|
+
}
|
|
122
|
+
function patternNames(pattern) {
|
|
123
|
+
if (!isNode(pattern))
|
|
124
|
+
return [];
|
|
125
|
+
switch (pattern.type) {
|
|
126
|
+
case "Identifier": return [pattern["name"]];
|
|
127
|
+
case "ObjectPattern": return (pattern["properties"] ?? []).flatMap((property) => property.type === "RestElement" ? patternNames(property["argument"]) : patternNames(property["value"]));
|
|
128
|
+
case "ArrayPattern": return (pattern["elements"] ?? []).flatMap((element) => patternNames(element));
|
|
129
|
+
case "AssignmentPattern": return patternNames(pattern["left"]);
|
|
130
|
+
case "RestElement": return patternNames(pattern["argument"]);
|
|
131
|
+
default: return [];
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/** Strips `(…)`, `!`, `as T`, `?.` wrappers. */
|
|
135
|
+
function unwrap(node) {
|
|
136
|
+
let current = node;
|
|
137
|
+
for (;;) {
|
|
138
|
+
if (current.type === "ParenthesizedExpression" || current.type === "ChainExpression" || current.type === "TSNonNullExpression"
|
|
139
|
+
|| current.type === "TSAsExpression" || current.type === "TSSatisfiesExpression" || current.type === "TSTypeAssertion") {
|
|
140
|
+
current = current["expression"];
|
|
141
|
+
}
|
|
142
|
+
else {
|
|
143
|
+
return current;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
function calleeName(node) {
|
|
148
|
+
const callee = unwrap(node["callee"]);
|
|
149
|
+
if (callee.type === "Identifier")
|
|
150
|
+
return callee["name"];
|
|
151
|
+
if (callee.type === "MemberExpression" && callee["computed"] !== true)
|
|
152
|
+
return callee["property"]["name"];
|
|
153
|
+
return undefined;
|
|
154
|
+
}
|
|
155
|
+
/** Where offsets of the parsed nodes are in the file, and how to turn them into lines and columns. */
|
|
156
|
+
class SourceText {
|
|
157
|
+
file;
|
|
158
|
+
text;
|
|
159
|
+
lineStarts = [0];
|
|
160
|
+
constructor(file, text) {
|
|
161
|
+
this.file = file;
|
|
162
|
+
this.text = text;
|
|
163
|
+
for (let index = 0; index < text.length; index++)
|
|
164
|
+
if (text.charCodeAt(index) === 10)
|
|
165
|
+
this.lineStarts.push(index + 1);
|
|
166
|
+
}
|
|
167
|
+
position(offset) {
|
|
168
|
+
let low = 0, high = this.lineStarts.length - 1;
|
|
169
|
+
while (low < high) {
|
|
170
|
+
const middle = (low + high + 1) >> 1;
|
|
171
|
+
if (this.lineStarts[middle] <= offset)
|
|
172
|
+
low = middle;
|
|
173
|
+
else
|
|
174
|
+
high = middle - 1;
|
|
175
|
+
}
|
|
176
|
+
return { line: low + 1, column: offset - this.lineStarts[low] + 1 };
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
const maximumDepth = 12;
|
|
180
|
+
/**
|
|
181
|
+
* Follows a handler expression through the declarations and returns the calls it reaches. `offset` moves the
|
|
182
|
+
* handler's node positions into `source` (a template expression parsed on its own).
|
|
183
|
+
*/
|
|
184
|
+
function reach(handler, declarations, source, offset, scriptSource, scriptOffset) {
|
|
185
|
+
const calls = new Map();
|
|
186
|
+
const external = new Map();
|
|
187
|
+
const followed = new Set();
|
|
188
|
+
const helperResult = (object) => {
|
|
189
|
+
const target = unwrap(object);
|
|
190
|
+
let definitions;
|
|
191
|
+
if (target.type === "Identifier")
|
|
192
|
+
definitions = declarations.bindings.get(target["name"]) ?? declarations.members.get(target["name"]);
|
|
193
|
+
else if (target.type === "MemberExpression" && unwrap(target["object"]).type === "ThisExpression" && target["computed"] !== true) {
|
|
194
|
+
definitions = declarations.members.get(target["property"]["name"]);
|
|
195
|
+
}
|
|
196
|
+
return definitions !== undefined && definitions.length > 0 && definitions.every((definition) => {
|
|
197
|
+
const value = unwrap(definition);
|
|
198
|
+
return value.type === "CallExpression" && helperNames.has(calleeName(value) ?? "");
|
|
199
|
+
});
|
|
200
|
+
};
|
|
201
|
+
const record = (member, node, inScript, via) => {
|
|
202
|
+
if (calls.has(member))
|
|
203
|
+
return;
|
|
204
|
+
const text = inScript ? scriptSource : source;
|
|
205
|
+
const position = text.position(node.start + (inScript ? scriptOffset : offset));
|
|
206
|
+
calls.set(member, { member, file: text.file, line: position.line, column: position.column, via });
|
|
207
|
+
};
|
|
208
|
+
const follow = (definitions, depth, helper) => {
|
|
209
|
+
for (const definition of definitions ?? []) {
|
|
210
|
+
if (followed.has(definition))
|
|
211
|
+
continue;
|
|
212
|
+
followed.add(definition);
|
|
213
|
+
visit(definition, depth + 1, true, helper);
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
const visit = (node, depth, inScript, helper) => {
|
|
217
|
+
if (depth > maximumDepth)
|
|
218
|
+
return;
|
|
219
|
+
const via = () => depth === 0 ? "direct" : helper ? "helper" : "local";
|
|
220
|
+
switch (node.type) {
|
|
221
|
+
case "CallExpression":
|
|
222
|
+
case "NewExpression": {
|
|
223
|
+
const callee = unwrap(node["callee"]);
|
|
224
|
+
const name = calleeName(node);
|
|
225
|
+
const insideHelper = helper || (name !== undefined && helperNames.has(name));
|
|
226
|
+
// useView(page), useField(view, Fields.step): their arguments reach no command of the handler.
|
|
227
|
+
if (name !== undefined && helperNames.has(name) && !callbackHelpers.has(name))
|
|
228
|
+
return;
|
|
229
|
+
if (callee.type === "MemberExpression") {
|
|
230
|
+
const property = callee["property"];
|
|
231
|
+
const member = callee["computed"] === true ? (typeof property["value"] === "string" ? property["value"] : undefined)
|
|
232
|
+
: property["name"];
|
|
233
|
+
const argument = node["arguments"]?.[0];
|
|
234
|
+
if (member === "command" && argument !== undefined && argument.type === "Literal" && typeof argument["value"] === "string") {
|
|
235
|
+
record(argument["value"], argument, inScript, via());
|
|
236
|
+
}
|
|
237
|
+
else if (member !== undefined && node.type === "CallExpression" && !helperResult(callee["object"])) {
|
|
238
|
+
record(member, property, inScript, via());
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
for (const child of children(node))
|
|
242
|
+
visit(child, depth, inScript, insideHelper);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
case "Identifier": {
|
|
246
|
+
const name = node["name"];
|
|
247
|
+
const bindings = declarations.bindings.get(name);
|
|
248
|
+
if (bindings !== undefined)
|
|
249
|
+
return follow(bindings, depth, helper || bindings.some((binding) => isHelperCall(binding)));
|
|
250
|
+
const members = declarations.members.get(name);
|
|
251
|
+
if (members !== undefined)
|
|
252
|
+
return follow(members, depth, helper || members.some((member) => isHelperCall(member)));
|
|
253
|
+
const imported = declarations.imports.get(name);
|
|
254
|
+
if (imported !== undefined && !isLibrary(imported) && !helperNames.has(name))
|
|
255
|
+
external.set(name, imported);
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
case "MemberExpression": {
|
|
259
|
+
const object = unwrap(node["object"]);
|
|
260
|
+
if (object.type === "ThisExpression" && node["computed"] !== true) {
|
|
261
|
+
const members = declarations.members.get(node["property"]["name"]);
|
|
262
|
+
return follow(members, depth, helper || (members ?? []).some((member) => isHelperCall(member)));
|
|
263
|
+
}
|
|
264
|
+
// A method of an imported object is a candidate itself; the object is not code to follow.
|
|
265
|
+
if (!(object.type === "Identifier" && declarations.imports.has(object["name"]))) {
|
|
266
|
+
visit(node["object"], depth, inScript, helper);
|
|
267
|
+
}
|
|
268
|
+
if (node["computed"] === true)
|
|
269
|
+
visit(node["property"], depth, inScript, helper);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
case "Property": {
|
|
273
|
+
if (node["computed"] === true)
|
|
274
|
+
visit(node["key"], depth, inScript, helper);
|
|
275
|
+
visit(node["value"], depth, inScript, helper);
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
case "PropertyDefinition":
|
|
279
|
+
case "MethodDefinition": {
|
|
280
|
+
if (isNode(node["value"]))
|
|
281
|
+
visit(node["value"], depth, inScript, helper);
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
case "VariableDeclarator": {
|
|
285
|
+
if (isNode(node["init"]))
|
|
286
|
+
visit(node["init"], depth, inScript, helper);
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
case "FunctionDeclaration":
|
|
290
|
+
case "FunctionExpression":
|
|
291
|
+
case "ArrowFunctionExpression": {
|
|
292
|
+
if (isNode(node["body"]))
|
|
293
|
+
visit(node["body"], depth, inScript, helper);
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
case "LabeledStatement":
|
|
297
|
+
case "BreakStatement":
|
|
298
|
+
case "ContinueStatement": {
|
|
299
|
+
if (isNode(node["body"]))
|
|
300
|
+
visit(node["body"], depth, inScript, helper);
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
case "ImportExpression":
|
|
304
|
+
case "TSTypeAliasDeclaration":
|
|
305
|
+
case "TSInterfaceDeclaration": return;
|
|
306
|
+
}
|
|
307
|
+
for (const child of children(node))
|
|
308
|
+
visit(child, depth, inScript, helper);
|
|
309
|
+
};
|
|
310
|
+
visit(handler, 0, false, false);
|
|
311
|
+
return { calls: [...calls.values()], external: [...external].map(([name, from]) => ({ name, source: from })) };
|
|
312
|
+
}
|
|
313
|
+
function isHelperCall(node) {
|
|
314
|
+
const value = unwrap(node);
|
|
315
|
+
return value.type === "CallExpression" && helperNames.has(calleeName(value) ?? "");
|
|
316
|
+
}
|
|
317
|
+
let parser;
|
|
318
|
+
/**
|
|
319
|
+
* Loads the parser, Vite's `parseSync` (oxc). Imported on first use, so that `runicDevSessionProxy()` under a server
|
|
320
|
+
* without Vite plugins loads without it. Returns whether it is available.
|
|
321
|
+
*/
|
|
322
|
+
export async function loadHandlerParser() {
|
|
323
|
+
if (parser !== undefined)
|
|
324
|
+
return true;
|
|
325
|
+
try {
|
|
326
|
+
parser = (await import("vite")).parseSync;
|
|
327
|
+
}
|
|
328
|
+
catch {
|
|
329
|
+
return false;
|
|
330
|
+
}
|
|
331
|
+
return typeof parser === "function";
|
|
332
|
+
}
|
|
333
|
+
/** The program, or undefined when it does not parse (`strict`: with any error). */
|
|
334
|
+
function parseProgram(file, code, lang, strict = false) {
|
|
335
|
+
if (parser === undefined)
|
|
336
|
+
return undefined;
|
|
337
|
+
try {
|
|
338
|
+
const result = parser(file, code, { lang, sourceType: "module" });
|
|
339
|
+
if (result.errors.length > 0 && (strict || result.program.body.length === 0))
|
|
340
|
+
return undefined;
|
|
341
|
+
return result.program;
|
|
342
|
+
}
|
|
343
|
+
catch {
|
|
344
|
+
return undefined;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
/** A template handler (`increment()`, `step.commit`, `a(); b()`), parsed on its own. */
|
|
348
|
+
function parseHandler(code, lang) {
|
|
349
|
+
const program = parseProgram(`handler.${lang}`, code, lang, true);
|
|
350
|
+
if (program === undefined)
|
|
351
|
+
return undefined;
|
|
352
|
+
const body = program["body"];
|
|
353
|
+
return body.length === 1 && body[0].type === "ExpressionStatement" ? body[0]["expression"] : program;
|
|
354
|
+
}
|
|
355
|
+
function shorten(text) {
|
|
356
|
+
const collapsed = text.replace(/\s+/gu, " ").trim();
|
|
357
|
+
return collapsed.length > 160 ? `${collapsed.slice(0, 159)}…` : collapsed;
|
|
358
|
+
}
|
|
359
|
+
function binding(tag, event, element, expression, reached) {
|
|
360
|
+
return { file: element.file, line: element.line, column: element.column, tag, event: event.toLowerCase(),
|
|
361
|
+
expression: shorten(expression), calls: reached.calls, external: reached.external };
|
|
362
|
+
}
|
|
363
|
+
function scriptLang(file, lang) {
|
|
364
|
+
const value = (lang ?? extname(file).slice(1)).toLowerCase();
|
|
365
|
+
if (value === "tsx")
|
|
366
|
+
return "tsx";
|
|
367
|
+
if (value === "ts" || value === "mts" || value === "cts" || value === "typescript")
|
|
368
|
+
return "ts";
|
|
369
|
+
if (value === "jsx")
|
|
370
|
+
return "jsx";
|
|
371
|
+
return "js";
|
|
372
|
+
}
|
|
373
|
+
// React and JSX -----------------------------------------------------------------------------------------------------
|
|
374
|
+
function jsxName(node) {
|
|
375
|
+
switch (node.type) {
|
|
376
|
+
case "JSXIdentifier": return node["name"];
|
|
377
|
+
case "JSXMemberExpression": return `${jsxName(node["object"])}.${jsxName(node["property"])}`;
|
|
378
|
+
case "JSXNamespacedName": return `${jsxName(node["namespace"])}:${jsxName(node["name"])}`;
|
|
379
|
+
default: return "";
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
/** The JSX event bindings of a script (`onClick={…}`), at the opening element's `<`. */
|
|
383
|
+
export function analyzeJsx(file, code) {
|
|
384
|
+
const lang = scriptLang(file, undefined);
|
|
385
|
+
// Plain .js and .ts may hold JSX too (Vite's React plugin accepts it in .js); a type assertion `<T>x` in .ts does not.
|
|
386
|
+
const program = parseProgram(file, code, lang === "js" ? "jsx" : lang === "ts" ? "tsx" : lang) ?? (lang === "ts" ? parseProgram(file, code, "ts") : undefined);
|
|
387
|
+
if (program === undefined)
|
|
388
|
+
return [];
|
|
389
|
+
const declarations = new Declarations();
|
|
390
|
+
declarations.add(program);
|
|
391
|
+
const source = new SourceText(file, code);
|
|
392
|
+
const bindings = [];
|
|
393
|
+
const visit = (node) => {
|
|
394
|
+
if (node.type === "JSXOpeningElement") {
|
|
395
|
+
const tag = jsxName(node["name"]);
|
|
396
|
+
for (const attribute of node["attributes"] ?? []) {
|
|
397
|
+
if (attribute.type !== "JSXAttribute")
|
|
398
|
+
continue;
|
|
399
|
+
const name = jsxName(attribute["name"]);
|
|
400
|
+
const value = attribute["value"];
|
|
401
|
+
if (!/^on[A-Z]/u.test(name) || value?.type !== "JSXExpressionContainer")
|
|
402
|
+
continue;
|
|
403
|
+
const expression = value["expression"];
|
|
404
|
+
if (expression.type === "JSXEmptyExpression")
|
|
405
|
+
continue;
|
|
406
|
+
const position = source.position(node.start);
|
|
407
|
+
bindings.push(binding(tag, name.slice(2).replace(/Capture$/u, ""), { file, ...position }, code.slice(expression.start, expression.end), reach(expression, declarations, source, 0, source, 0)));
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
for (const child of children(node))
|
|
411
|
+
visit(child);
|
|
412
|
+
};
|
|
413
|
+
visit(program);
|
|
414
|
+
return bindings;
|
|
415
|
+
}
|
|
416
|
+
// Angular -----------------------------------------------------------------------------------------------------------
|
|
417
|
+
/** The `(event)="…"` and `on-event="…"` bindings of an Angular template, with their element's tag and position. */
|
|
418
|
+
export function angularTemplateBindings(template) {
|
|
419
|
+
const found = [];
|
|
420
|
+
const tags = /<!--[\s\S]*?-->|<([a-zA-Z][\w.:-]*)/gu;
|
|
421
|
+
for (let match = tags.exec(template); match !== null; match = tags.exec(template)) {
|
|
422
|
+
if (match[1] === undefined)
|
|
423
|
+
continue;
|
|
424
|
+
const tag = match[1];
|
|
425
|
+
const offset = match.index;
|
|
426
|
+
// The attributes up to the tag's `>`, honoring quotes.
|
|
427
|
+
let index = tags.lastIndex;
|
|
428
|
+
let quote;
|
|
429
|
+
for (; index < template.length; index++) {
|
|
430
|
+
const character = template[index];
|
|
431
|
+
if (quote !== undefined) {
|
|
432
|
+
if (character === quote)
|
|
433
|
+
quote = undefined;
|
|
434
|
+
}
|
|
435
|
+
else if (character === "\"" || character === "'")
|
|
436
|
+
quote = character;
|
|
437
|
+
else if (character === ">")
|
|
438
|
+
break;
|
|
439
|
+
}
|
|
440
|
+
const attributes = template.slice(tags.lastIndex, index);
|
|
441
|
+
const attribute = /(?:\(([\w.:-]+)\)|\bon-([\w.:-]+))\s*=\s*(?:"([^"]*)"|'([^']*)')/gu;
|
|
442
|
+
for (let item = attribute.exec(attributes); item !== null; item = attribute.exec(attributes)) {
|
|
443
|
+
const expression = item[3] ?? item[4] ?? "";
|
|
444
|
+
const event = (item[1] ?? item[2] ?? "").split(".", 1)[0];
|
|
445
|
+
const expressionOffset = tags.lastIndex + item.index + item[0].length - expression.length - 1;
|
|
446
|
+
found.push({ tag, event, expression, offset, expressionOffset });
|
|
447
|
+
}
|
|
448
|
+
tags.lastIndex = index;
|
|
449
|
+
}
|
|
450
|
+
return found;
|
|
451
|
+
}
|
|
452
|
+
function stringValue(node) {
|
|
453
|
+
if (node === undefined)
|
|
454
|
+
return undefined;
|
|
455
|
+
if (node.type === "Literal" && typeof node["value"] === "string")
|
|
456
|
+
return { text: node["value"], offset: node.start + 1 };
|
|
457
|
+
if (node.type === "TemplateLiteral" && node["expressions"].length === 0) {
|
|
458
|
+
const quasi = node["quasis"][0];
|
|
459
|
+
const value = quasi["value"];
|
|
460
|
+
// After the backtick; parsers differ in where the template element starts.
|
|
461
|
+
return { text: value.raw, offset: node.start + 1 };
|
|
462
|
+
}
|
|
463
|
+
return undefined;
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* The template bindings of the Angular components of a script: `@Component({ template })` or `templateUrl`, which
|
|
467
|
+
* `readTemplate` reads (relative to the script).
|
|
468
|
+
*/
|
|
469
|
+
export function analyzeAngular(file, code, readTemplate) {
|
|
470
|
+
const program = parseProgram(file, code, "ts");
|
|
471
|
+
if (program === undefined)
|
|
472
|
+
return [];
|
|
473
|
+
const bindings = [];
|
|
474
|
+
const scriptSource = new SourceText(file, code);
|
|
475
|
+
const visit = (node) => {
|
|
476
|
+
if (node.type === "ClassDeclaration" || node.type === "ClassExpression") {
|
|
477
|
+
const decorator = (node["decorators"] ?? []).map((item) => unwrap(item["expression"]))
|
|
478
|
+
.find((expression) => expression.type === "CallExpression" && calleeName(expression) === "Component");
|
|
479
|
+
const metadata = decorator === undefined ? undefined : decorator["arguments"][0];
|
|
480
|
+
if (metadata?.type === "ObjectExpression") {
|
|
481
|
+
const properties = new Map((metadata["properties"] ?? []).flatMap((property) => {
|
|
482
|
+
const name = property.type === "Property" ? propertyName(property) : undefined;
|
|
483
|
+
return name === undefined ? [] : [[name, property["value"]]];
|
|
484
|
+
}));
|
|
485
|
+
let template;
|
|
486
|
+
const inline = stringValue(properties.get("template"));
|
|
487
|
+
if (inline !== undefined)
|
|
488
|
+
template = { ...inline, source: scriptSource };
|
|
489
|
+
const url = stringValue(properties.get("templateUrl"))?.text;
|
|
490
|
+
if (template === undefined && url !== undefined) {
|
|
491
|
+
const path = resolve(dirname(file), url);
|
|
492
|
+
const text = readTemplate(path);
|
|
493
|
+
if (text !== undefined)
|
|
494
|
+
template = { text, offset: 0, source: new SourceText(path, text) };
|
|
495
|
+
}
|
|
496
|
+
if (template !== undefined) {
|
|
497
|
+
const declarations = new Declarations();
|
|
498
|
+
declarations.add(node["body"]);
|
|
499
|
+
const fileDeclarations = new Declarations();
|
|
500
|
+
fileDeclarations.add(program);
|
|
501
|
+
for (const [name, from] of fileDeclarations.imports)
|
|
502
|
+
declarations.imports.set(name, from);
|
|
503
|
+
for (const [name, list] of fileDeclarations.bindings)
|
|
504
|
+
if (!declarations.bindings.has(name))
|
|
505
|
+
declarations.bindings.set(name, list);
|
|
506
|
+
for (const entry of angularTemplateBindings(template.text)) {
|
|
507
|
+
const handler = parseHandler(entry.expression, "ts");
|
|
508
|
+
const position = template.source.position(template.offset + entry.offset);
|
|
509
|
+
const reached = handler === undefined ? { calls: [], external: [] }
|
|
510
|
+
: reach(handler, declarations, template.source, template.offset + entry.expressionOffset, scriptSource, 0);
|
|
511
|
+
bindings.push(binding(entry.tag, entry.event, { file: template.source.file, ...position }, entry.expression, reached));
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
for (const child of children(node))
|
|
517
|
+
visit(child);
|
|
518
|
+
};
|
|
519
|
+
visit(program);
|
|
520
|
+
return bindings;
|
|
521
|
+
}
|
|
522
|
+
/** The event bindings of a Svelte 5 component (`onclick={…}`, `on:click={…}`), at the element's `<`. */
|
|
523
|
+
export function analyzeSvelte(file, code, compiler) {
|
|
524
|
+
let ast;
|
|
525
|
+
try {
|
|
526
|
+
ast = compiler.parse(code, { modern: true, filename: file });
|
|
527
|
+
}
|
|
528
|
+
catch {
|
|
529
|
+
return [];
|
|
530
|
+
}
|
|
531
|
+
const declarations = new Declarations();
|
|
532
|
+
for (const key of ["module", "instance"]) {
|
|
533
|
+
const script = ast[key];
|
|
534
|
+
if (isNode(script?.content))
|
|
535
|
+
declarations.add(script.content);
|
|
536
|
+
}
|
|
537
|
+
const source = new SourceText(file, code);
|
|
538
|
+
const bindings = [];
|
|
539
|
+
const visit = (value) => {
|
|
540
|
+
if (Array.isArray(value)) {
|
|
541
|
+
for (const item of value)
|
|
542
|
+
visit(item);
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
if (typeof value !== "object" || value === null)
|
|
546
|
+
return;
|
|
547
|
+
const node = value;
|
|
548
|
+
if (Array.isArray(node["attributes"]) && typeof node["name"] === "string" && typeof node["start"] === "number") {
|
|
549
|
+
for (const attribute of node["attributes"]) {
|
|
550
|
+
let event;
|
|
551
|
+
let expression;
|
|
552
|
+
if (attribute["type"] === "OnDirective" && isNode(attribute["expression"])) {
|
|
553
|
+
event = attribute["name"];
|
|
554
|
+
expression = attribute["expression"];
|
|
555
|
+
}
|
|
556
|
+
else if (attribute["type"] === "Attribute" && typeof attribute["name"] === "string" && /^on[a-z]/u.test(attribute["name"])) {
|
|
557
|
+
const raw = attribute["value"];
|
|
558
|
+
const tag = (Array.isArray(raw) ? raw.length === 1 ? raw[0] : undefined : raw);
|
|
559
|
+
if (tag?.["type"] === "ExpressionTag" && isNode(tag["expression"])) {
|
|
560
|
+
event = attribute["name"].slice(2);
|
|
561
|
+
expression = tag["expression"];
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
if (event === undefined || expression === undefined)
|
|
565
|
+
continue;
|
|
566
|
+
const position = source.position(node["start"]);
|
|
567
|
+
bindings.push(binding(node["name"], event, { file, ...position }, code.slice(expression.start, expression.end), reach(expression, declarations, source, 0, source, 0)));
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
for (const [key, child] of Object.entries(node)) {
|
|
571
|
+
if (key === "instance" || key === "module" || key === "css" || key === "expression" || key === "attributes")
|
|
572
|
+
continue;
|
|
573
|
+
if (typeof child === "object" && child !== null)
|
|
574
|
+
visit(child);
|
|
575
|
+
}
|
|
576
|
+
};
|
|
577
|
+
visit(ast["fragment"]);
|
|
578
|
+
return bindings;
|
|
579
|
+
}
|
|
580
|
+
/** The `v-on` bindings of a Vue single-file component, at the element's `<`. */
|
|
581
|
+
export function analyzeVue(file, code, compiler) {
|
|
582
|
+
let descriptor;
|
|
583
|
+
try {
|
|
584
|
+
descriptor = compiler.parse(code, { filename: file, sourceMap: false }).descriptor;
|
|
585
|
+
}
|
|
586
|
+
catch {
|
|
587
|
+
return [];
|
|
588
|
+
}
|
|
589
|
+
const source = new SourceText(file, code);
|
|
590
|
+
const declarations = new Declarations();
|
|
591
|
+
let lang = "js";
|
|
592
|
+
// The script blocks parsed in place: a copy of the file with everything else blanked keeps the offsets.
|
|
593
|
+
const blocks = [descriptor.script, descriptor.scriptSetup].filter((block) => block !== null);
|
|
594
|
+
for (const block of blocks) {
|
|
595
|
+
const blockLang = scriptLang(file, block.lang ?? "js");
|
|
596
|
+
if (blockLang === "ts" || blockLang === "tsx")
|
|
597
|
+
lang = "ts";
|
|
598
|
+
const start = block.loc.start.offset;
|
|
599
|
+
const padded = code.slice(0, start).replace(/[^\n]/gu, " ") + block.content;
|
|
600
|
+
const program = parseProgram(`${file}.${blockLang}`, padded, blockLang);
|
|
601
|
+
if (program !== undefined)
|
|
602
|
+
declarations.add(program);
|
|
603
|
+
}
|
|
604
|
+
const bindings = [];
|
|
605
|
+
const visit = (node) => {
|
|
606
|
+
if (node.type === 1 && node.tag !== undefined) {
|
|
607
|
+
for (const prop of node.props ?? []) {
|
|
608
|
+
if (prop.type !== 7 || prop.name !== "on" || prop.arg?.content === undefined || prop.arg.isStatic === false || prop.exp === undefined)
|
|
609
|
+
continue;
|
|
610
|
+
const handler = parseHandler(prop.exp.content, lang);
|
|
611
|
+
const position = source.position(node.loc.start.offset);
|
|
612
|
+
const reached = handler === undefined ? { calls: [], external: [] }
|
|
613
|
+
: reach(handler, declarations, source, prop.exp.loc.start.offset, source, 0);
|
|
614
|
+
bindings.push(binding(node.tag, prop.arg.content, { file, ...position }, prop.exp.content, reached));
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
for (const child of node.children ?? [])
|
|
618
|
+
visit(child);
|
|
619
|
+
for (const branch of node.branches ?? [])
|
|
620
|
+
visit(branch);
|
|
621
|
+
};
|
|
622
|
+
if (descriptor.template?.ast !== undefined)
|
|
623
|
+
visit(descriptor.template.ast);
|
|
624
|
+
return bindings;
|
|
625
|
+
}
|
|
626
|
+
// Files -------------------------------------------------------------------------------------------------------------
|
|
627
|
+
const maximumFileBytes = 2 * 1024 * 1024;
|
|
628
|
+
const analyzedExtensions = new Set([".js", ".jsx", ".mjs", ".ts", ".tsx", ".mts", ".vue", ".svelte"]);
|
|
629
|
+
/** Whether a file may be analyzed: a frontend source file below `root`, outside `node_modules`. */
|
|
630
|
+
export function mayAnalyze(file, root) {
|
|
631
|
+
return isAbsolute(file) && !file.includes("\0") && analyzedExtensions.has(extname(file).toLowerCase()) && mayRead(file, root);
|
|
632
|
+
}
|
|
633
|
+
function readText(path) {
|
|
634
|
+
try {
|
|
635
|
+
const stat = statSync(path);
|
|
636
|
+
return stat.isFile() && stat.size <= maximumFileBytes ? readFileSync(path, "utf8") : undefined;
|
|
637
|
+
}
|
|
638
|
+
catch {
|
|
639
|
+
return undefined;
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
async function loadCompiler(specifier, from) {
|
|
643
|
+
for (const directory of from) {
|
|
644
|
+
try {
|
|
645
|
+
const path = createRequire(join(directory, "package.json")).resolve(specifier);
|
|
646
|
+
return await import(pathToFileURL(path).href);
|
|
647
|
+
}
|
|
648
|
+
catch { /* next */ }
|
|
649
|
+
}
|
|
650
|
+
return undefined;
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* Analyzes files on request, each again only when it (or an Angular component's template) changed. The Svelte and Vue
|
|
654
|
+
* compilers are the application's own (`svelte/compiler`, `vue/compiler-sfc`), loaded from `root`.
|
|
655
|
+
*/
|
|
656
|
+
export function createHandlerAnalyzer(root) {
|
|
657
|
+
const cache = new Map();
|
|
658
|
+
const compilers = new Map();
|
|
659
|
+
const compiler = (specifier, file) => {
|
|
660
|
+
let pending = compilers.get(specifier);
|
|
661
|
+
if (pending === undefined)
|
|
662
|
+
compilers.set(specifier, pending = loadCompiler(specifier, [root(), dirname(file)]));
|
|
663
|
+
return pending;
|
|
664
|
+
};
|
|
665
|
+
const stamp = (path) => {
|
|
666
|
+
try {
|
|
667
|
+
const stat = statSync(path);
|
|
668
|
+
return `${stat.mtimeMs}:${stat.size}`;
|
|
669
|
+
}
|
|
670
|
+
catch {
|
|
671
|
+
return "missing";
|
|
672
|
+
}
|
|
673
|
+
};
|
|
674
|
+
return async (file) => {
|
|
675
|
+
const base = root();
|
|
676
|
+
if (!mayAnalyze(file, base))
|
|
677
|
+
return undefined;
|
|
678
|
+
if (!await loadHandlerParser()) {
|
|
679
|
+
return { format: "runic-handlers/1", file, framework: "unknown", bindings: [], note: "vite (its parser) was not found." };
|
|
680
|
+
}
|
|
681
|
+
const cached = cache.get(file);
|
|
682
|
+
if (cached !== undefined && cached.key === [file, ...cached.templates].map(stamp).join("|"))
|
|
683
|
+
return cached.analysis;
|
|
684
|
+
const code = readText(file);
|
|
685
|
+
if (code === undefined)
|
|
686
|
+
return undefined;
|
|
687
|
+
const templates = [];
|
|
688
|
+
const key = stamp(file);
|
|
689
|
+
const extension = extname(file).toLowerCase();
|
|
690
|
+
const result = (framework, bindings, note) => ({ format: "runic-handlers/1", file, framework, bindings, ...(note === undefined ? {} : { note }) });
|
|
691
|
+
let analysis;
|
|
692
|
+
if (extension === ".svelte") {
|
|
693
|
+
const svelte = await compiler("svelte/compiler", file);
|
|
694
|
+
analysis = svelte === undefined ? result("svelte", [], "svelte/compiler was not found.") : result("svelte", analyzeSvelte(file, code, svelte));
|
|
695
|
+
}
|
|
696
|
+
else if (extension === ".vue") {
|
|
697
|
+
const vue = await compiler("vue/compiler-sfc", file);
|
|
698
|
+
analysis = vue === undefined ? result("vue", [], "vue/compiler-sfc was not found.") : result("vue", analyzeVue(file, code, vue));
|
|
699
|
+
}
|
|
700
|
+
else if (/@Component\s*\(/u.test(code)) {
|
|
701
|
+
const readTemplate = (path) => {
|
|
702
|
+
if (!mayRead(path, base) || !/\.html?$/iu.test(path))
|
|
703
|
+
return undefined;
|
|
704
|
+
templates.push(path);
|
|
705
|
+
return readText(path);
|
|
706
|
+
};
|
|
707
|
+
analysis = result("angular", analyzeAngular(file, code, readTemplate));
|
|
708
|
+
}
|
|
709
|
+
else {
|
|
710
|
+
analysis = result("react", analyzeJsx(file, code));
|
|
711
|
+
}
|
|
712
|
+
cache.set(file, { key: [key, ...templates.map(stamp)].join("|"), templates, analysis });
|
|
713
|
+
if (cache.size > 300)
|
|
714
|
+
cache.delete(cache.keys().next().value);
|
|
715
|
+
return analysis;
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
function mayRead(path, root) {
|
|
719
|
+
const relativePath = relative(root, path);
|
|
720
|
+
return relativePath !== "" && !relativePath.startsWith("..") && !isAbsolute(relativePath)
|
|
721
|
+
&& !relativePath.split(/[\\/]/u).includes("node_modules");
|
|
722
|
+
}
|
|
723
|
+
/**
|
|
724
|
+
* `file` as the analyzer takes it: an absolute path below `root` as it is, a `/@fs/` URL path, a root-relative URL
|
|
725
|
+
* path (`/src/App.tsx`), or a path relative to `root` (`src/app/counter.ts`, as Angular's debug info names it).
|
|
726
|
+
*/
|
|
727
|
+
export function handlerFile(value, root) {
|
|
728
|
+
const path = value.startsWith("/@fs/") ? value.slice(4) : value;
|
|
729
|
+
if (!isAbsolute(path))
|
|
730
|
+
return resolve(root, path);
|
|
731
|
+
if (mayRead(path, root) || !path.startsWith("/"))
|
|
732
|
+
return path;
|
|
733
|
+
return resolve(root, path.slice(1));
|
|
734
|
+
}
|
|
735
|
+
function answerJson(response, status, body) {
|
|
736
|
+
if (response.writableEnded)
|
|
737
|
+
return;
|
|
738
|
+
response.statusCode = status;
|
|
739
|
+
response.setHeader("Cache-Control", "no-store");
|
|
740
|
+
if (body === undefined) {
|
|
741
|
+
response.end();
|
|
742
|
+
return;
|
|
743
|
+
}
|
|
744
|
+
response.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
745
|
+
response.end(JSON.stringify(body));
|
|
746
|
+
}
|
|
747
|
+
/**
|
|
748
|
+
* Answers `GET /__runic/handlers?file=…` with the file's analysis: for a page of this server on this machine or a
|
|
749
|
+
* client the allow list admits (access.ts), and a
|
|
750
|
+
* frontend source file below the root (not `node_modules`); 404 otherwise.
|
|
751
|
+
*/
|
|
752
|
+
export async function answerHandlers(request, response, analyze, root, access) {
|
|
753
|
+
request.resume();
|
|
754
|
+
if (request.method !== "GET" && request.method !== "HEAD") {
|
|
755
|
+
response.setHeader("Allow", "GET, HEAD");
|
|
756
|
+
return answerJson(response, 405);
|
|
757
|
+
}
|
|
758
|
+
if (!(await mayReadRequest(request, access)))
|
|
759
|
+
return answerJson(response, 403);
|
|
760
|
+
let file;
|
|
761
|
+
try {
|
|
762
|
+
file = new URL(request.url ?? "", "http://localhost").searchParams.get("file");
|
|
763
|
+
}
|
|
764
|
+
catch {
|
|
765
|
+
file = null;
|
|
766
|
+
}
|
|
767
|
+
if (file === null || file.length === 0 || file.length > 4096)
|
|
768
|
+
return answerJson(response, 400);
|
|
769
|
+
const analysis = await analyze(handlerFile(file, root));
|
|
770
|
+
if (analysis === undefined)
|
|
771
|
+
return answerJson(response, 404);
|
|
772
|
+
answerJson(response, 200, analysis);
|
|
773
|
+
}
|