feat(extract): add EJS (.ejs) template extractor (#3811)
EJS views sat in CODE_EXTENSIONS with no extractor, so an Express/Node app's templates were counted as code and contributed nothing (the #1689 warning). A .ejs file is HTML with <% %> scriptlets and inline <script> blocks, so feeding the whole file to the JS grammar made it one top-level ERROR.
Add extract_ejs: mask the template down to its JS regions (code-tag and <script> bodies), parse them with the TS grammar, and add the two relationships no JS grammar can see - dynamic import('./X') and the EJS <%- include('partial') %> composition edge, resolved to the real partial file. Wire .ejs into the dispatch, the jsts language family, the JS resolve/cache sets, and the hook source extensions.
(cherry picked from commit 3824cda537)
This commit is contained in:
1 parent
4de6ed1eb1
commit
28938a4732
5 files changed
+403
-5
No files matched your search
+1
-1
@@ -69,7 +69,7 @@ _READ_DENY = json.dumps({
|
||||
}
|
||||
}, ensure_ascii=False, separators=(",", ":")) + "\n"
|
||||
_HOOK_SOURCE_EXTS = (
|
||||
'.py', '.js', '.cjs', '.ts', '.tsx', '.jsx', '.astro', '.vue', '.svelte', '.go',
|
||||
'.py', '.js', '.cjs', '.ts', '.tsx', '.jsx', '.astro', '.vue', '.svelte', '.ejs', '.go',
|
||||
'.rs', '.java', '.rb', '.c', '.h', '.cpp', '.hpp', '.cc', '.cs', '.kt',
|
||||
'.swift', '.php', '.scala', '.lua', '.ps1', '.psm1', '.psd1', # #4271: PowerShell sources are graphable too
|
||||
'.sh', '.md', '.rst', '.txt', '.mdx',
|
||||
|
||||
+172
-1
@@ -2734,6 +2734,176 @@ def extract_astro(path: Path) -> dict:
|
||||
return result
|
||||
|
||||
|
||||
# EJS spells a tag `<%` (code), `<%_` (code, whitespace-slurp), `<%=`/`<%-`
|
||||
# (escaped/unescaped output) or `<%#` (comment); `<%%` is an escaped literal
|
||||
# `<%`. Only the code bodies and inline `<script>` bodies are JS statements a
|
||||
# grammar can read — markup and output expressions are not, so a `.ejs` file fed
|
||||
# whole to the JS grammar is one top-level ERROR that loses every symbol (the
|
||||
# `.svelte` lesson of #3928).
|
||||
_EJS_SCRIPT_TAG_RE = _HTML_SCRIPT_TAG_RE
|
||||
_EJS_INCLUDE_RE = re.compile(
|
||||
r"""<%(?:_|[-=])?\s*include\s*\(\s*['"]([^'"]+)['"]"""
|
||||
)
|
||||
|
||||
|
||||
def _ejs_mask_non_script(src: str) -> str:
|
||||
"""Blank an EJS template down to the JavaScript a parser can read.
|
||||
|
||||
Keeps the bodies of code tags (``<% %>`` / ``<%_ %>``) and of JS ``<script>``
|
||||
blocks; markup, ``<%# %>`` comments and ``<%= %>``/``<%- %>`` output
|
||||
expressions become spaces, with ``\\r``/``\\n`` preserved so AST line
|
||||
numbers and byte offsets still match the original file. An output tag inside
|
||||
a ``<script>`` body is replaced by a length-preserving ``0`` so the
|
||||
surrounding statement still parses (``const x = <%- data %>;``).
|
||||
"""
|
||||
n = len(src)
|
||||
keep = bytearray(n) # 1 where the character is JS we want to parse
|
||||
neutralize = bytearray(n) # 1 inside an output tag that sits in kept JS
|
||||
|
||||
for m in _EJS_SCRIPT_TAG_RE.finditer(src):
|
||||
if _NON_JS_SCRIPT_TYPE_RE.search(m.group(1)):
|
||||
continue
|
||||
for p in range(m.start(2), m.end(2)):
|
||||
keep[p] = 1
|
||||
|
||||
i = 0
|
||||
while True:
|
||||
j = src.find("<%", i)
|
||||
if j < 0:
|
||||
break
|
||||
if j + 2 < n and src[j + 2] == "%": # `<%%` — a literal `<%`
|
||||
for p in range(j, min(j + 3, n)):
|
||||
keep[p] = 0
|
||||
i = j + 3
|
||||
continue
|
||||
marker = src[j + 2] if j + 2 < n else ""
|
||||
close = src.find("%>", j + 2)
|
||||
if close < 0:
|
||||
break
|
||||
# The `<%` … `%>` delimiters are never JS, even inside a <script> body.
|
||||
for p in (j, j + 1, close, close + 1):
|
||||
if p < n:
|
||||
keep[p] = 0
|
||||
if marker in ("=", "-"):
|
||||
for p in range(j + 2, close):
|
||||
if keep[p]:
|
||||
neutralize[p] = 1
|
||||
elif marker == "#":
|
||||
for p in range(j, close + 2):
|
||||
keep[p] = 0
|
||||
else:
|
||||
# Code tag (`<%` or `<%_`): its body is real JS.
|
||||
body_start = j + 3 if marker == "_" else j + 2
|
||||
if marker == "_":
|
||||
keep[j + 2] = 0 # the `<%_` whitespace-slurp modifier
|
||||
for p in range(body_start, close):
|
||||
keep[p] = 1
|
||||
i = close + 2
|
||||
|
||||
out: list[str] = []
|
||||
in_output = False
|
||||
for p in range(n):
|
||||
c = src[p]
|
||||
if c in "\r\n":
|
||||
out.append(c)
|
||||
in_output = False
|
||||
elif not keep[p]:
|
||||
out.append(" ")
|
||||
in_output = False
|
||||
elif neutralize[p]:
|
||||
out.append(" " if in_output else "0")
|
||||
in_output = True
|
||||
else:
|
||||
out.append(c)
|
||||
in_output = False
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _emit_ejs_include(
|
||||
result: dict,
|
||||
existing_ids: set,
|
||||
file_node_id: str,
|
||||
path: Path,
|
||||
raw: str,
|
||||
line: int,
|
||||
) -> None:
|
||||
"""Emit the template-composition edge for ``<%- include('partial') %>``.
|
||||
|
||||
EJS resolves an include relative to the including template, so probe the
|
||||
template's own directory through :func:`_resolve_js_import_path` — which,
|
||||
now that ``.ejs`` is a JS resolve extension, appends ``.ejs``/``index.ejs``
|
||||
the way EJS itself does. A relative hit is stamped with ``target_file`` so
|
||||
the #2169 canonicalization pass repoints it at the real template node; a
|
||||
bare/views-root include that cannot be resolved keeps a stub node, so the
|
||||
edge is never dropped.
|
||||
"""
|
||||
base = Path(os.path.normpath(path.parent / raw))
|
||||
resolved = _resolve_js_import_path(base)
|
||||
edge = {
|
||||
"source": file_node_id, "relation": "includes", "confidence": "EXTRACTED",
|
||||
"source_file": str(path), "source_location": f"L{line}",
|
||||
}
|
||||
if resolved.is_file():
|
||||
edge["target"] = _make_id(str(resolved))
|
||||
edge["target_file"] = str(resolved)
|
||||
result.setdefault("edges", []).append(edge)
|
||||
return
|
||||
node_id = _make_id(raw)
|
||||
if node_id not in existing_ids:
|
||||
existing_ids.add(node_id)
|
||||
result.setdefault("nodes", []).append({
|
||||
"id": node_id, "label": raw, "file_type": "code",
|
||||
"source_file": str(path), "source_location": f"L{line}",
|
||||
"confidence": "EXTRACTED",
|
||||
})
|
||||
edge["target"] = node_id
|
||||
result.setdefault("edges", []).append(edge)
|
||||
|
||||
|
||||
def extract_ejs(path: Path) -> dict:
|
||||
"""Extract imports, symbols, and `include()` composition from an EJS template.
|
||||
|
||||
EJS is HTML carrying ``<% %>`` scriptlets and inline ``<script>`` blocks, so
|
||||
the whole file is not JS: fed to the JS grammar it becomes a top-level ERROR
|
||||
and every symbol inside a scriptlet is lost (``_ejs_mask_non_script`` keeps
|
||||
only the JS regions, preserving line numbers). The AST pass then reads the
|
||||
template's real JavaScript — ``require``/``import`` edges, functions,
|
||||
classes — and two regex passes add what no JS grammar can see: dynamic
|
||||
``import('./X')`` calls written in a scriptlet, and the EJS
|
||||
``<%- include('partial') %>`` composition edge an Express view graph is
|
||||
built on (#3811, #2511).
|
||||
"""
|
||||
try:
|
||||
src = _read_source_text(path)
|
||||
except OSError as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
masked = _ejs_mask_non_script(src).encode("utf-8")
|
||||
masked = _normalize_ts_import_types(masked) or masked
|
||||
result = _extract_generic(path, _TS_CONFIG, source_override=masked)
|
||||
|
||||
try:
|
||||
existing_ids = {n["id"] for n in result.get("nodes", [])}
|
||||
file_node_id = _make_id(str(path))
|
||||
aliases = _load_tsconfig_aliases(path.parent)
|
||||
base_url = _load_tsconfig_base_url(path.parent)
|
||||
for m in re.finditer(r"""import\(\s*['"]([^'"]+)['"]\s*\)""", src):
|
||||
if m.group(1):
|
||||
_emit_rescued_import(
|
||||
result, existing_ids, file_node_id, path, m.group(1),
|
||||
"dynamic_import", aliases, base_url,
|
||||
)
|
||||
for m in _EJS_INCLUDE_RE.finditer(src):
|
||||
if m.group(1):
|
||||
_emit_ejs_include(
|
||||
result, existing_ids, file_node_id, path, m.group(1),
|
||||
src.count("\n", 0, m.start()) + 1,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return result
|
||||
|
||||
|
||||
# The open-tag matcher skips over quoted attribute values so a `>` inside one
|
||||
# (e.g. Vue 3.3+ generic components: `<script setup lang="ts"
|
||||
# generic="T extends Record<string, unknown>">`) doesn't prematurely end the tag.
|
||||
@@ -3578,7 +3748,7 @@ _LANG_FAMILY_BY_EXT: dict[str, str] = {
|
||||
# JS/TS module graph (SFCs embed JS/TS)
|
||||
".js": "jsts", ".jsx": "jsts", ".mjs": "jsts", ".cjs": "jsts",
|
||||
".ts": "jsts", ".tsx": "jsts", ".mts": "jsts", ".cts": "jsts",
|
||||
".vue": "jsts", ".svelte": "jsts", ".astro": "jsts",
|
||||
".vue": "jsts", ".svelte": "jsts", ".astro": "jsts", ".ejs": "jsts",
|
||||
# JVM interop
|
||||
".java": "jvm", ".kt": "jvm", ".kts": "jvm",
|
||||
".scala": "jvm", ".groovy": "jvm", ".gradle": "jvm",
|
||||
@@ -7811,6 +7981,7 @@ _DISPATCH: dict[str, Any] = {
|
||||
".vue": extract_vue,
|
||||
".svelte": extract_svelte,
|
||||
".astro": extract_astro,
|
||||
".ejs": extract_ejs,
|
||||
".dart": extract_dart,
|
||||
".ml": extract_ocaml,
|
||||
".mli": extract_ocaml,
|
||||
|
||||
@@ -8,7 +8,7 @@ from dataclasses import dataclass, field
|
||||
|
||||
_WORKSPACE_PACKAGE_CACHE: dict[str, dict[str, Path]] = {}
|
||||
|
||||
_JS_CACHE_BYPASS_SUFFIXES = {".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts", ".vue", ".svelte"}
|
||||
_JS_CACHE_BYPASS_SUFFIXES = {".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts", ".vue", ".svelte", ".ejs"}
|
||||
|
||||
@dataclass
|
||||
class LanguageConfig:
|
||||
|
||||
@@ -33,9 +33,9 @@ _WORKSPACE_MANIFEST_NAMES = ("pnpm-workspace.yaml", "package.json")
|
||||
# mtime component, so extract() clears it per run.
|
||||
_PACKAGE_IMPORTS_CACHE: "dict[str, tuple[Path, dict] | None]" = {}
|
||||
|
||||
_JS_RESOLVE_EXTS = (".ts", ".tsx", ".mts", ".cts", ".svelte", ".js", ".jsx", ".mjs", ".cjs")
|
||||
_JS_RESOLVE_EXTS = (".ts", ".tsx", ".mts", ".cts", ".svelte", ".ejs", ".js", ".jsx", ".mjs", ".cjs")
|
||||
|
||||
_JS_INDEX_FILES = ("index.ts", "index.tsx", "index.svelte", "index.js", "index.jsx", "index.mjs")
|
||||
_JS_INDEX_FILES = ("index.ts", "index.tsx", "index.svelte", "index.ejs", "index.js", "index.jsx", "index.mjs")
|
||||
|
||||
def _declared_language_suffixes(target_exts: tuple[str, ...]) -> tuple[str, ...]:
|
||||
"""Return declared literal suffixes for these languages in deterministic order."""
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
"""Extraction coverage for EJS (Embedded JavaScript) templates (#3811, #2511).
|
||||
|
||||
A `.ejs` file is HTML carrying `<% %>` scriptlets and inline `<script>` blocks,
|
||||
so the file as a whole is not JavaScript: fed to the JS grammar it becomes one
|
||||
top-level ERROR and every symbol inside a scriptlet is lost. `.ejs` sat in
|
||||
`CODE_EXTENSIONS` with no extractor, so an Express/Node app's views were counted
|
||||
as code and silently contributed nothing (the #1689 warning).
|
||||
|
||||
:func:`extract_ejs` masks the template down to its JS regions — the same
|
||||
strategy `.svelte`/`.vue`/`.astro` use — parses them with the TS grammar, and
|
||||
adds the two relationships no JS grammar can see: dynamic `import('./X')` calls
|
||||
written in a scriptlet, and the EJS `<%- include('partial') %>` composition edge.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from graphify.extract import _make_id, extract, extract_ejs
|
||||
|
||||
|
||||
def _write(path: Path, body: str) -> Path:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(body, encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def _labels(result: dict) -> dict[str, str]:
|
||||
"""Label -> source_location for every node except the file node."""
|
||||
file_id = result.get("nodes", [{}])[0].get("id")
|
||||
return {
|
||||
str(n.get("label")): str(n.get("source_location"))
|
||||
for n in result.get("nodes", [])
|
||||
if n.get("id") != file_id
|
||||
}
|
||||
|
||||
|
||||
def _edges(result: dict, relation: str) -> list[dict]:
|
||||
return [e for e in result.get("edges", []) if e.get("relation") == relation]
|
||||
|
||||
|
||||
def test_ejs_registered_as_code():
|
||||
from graphify.detect import CODE_EXTENSIONS
|
||||
assert ".ejs" in CODE_EXTENSIONS
|
||||
|
||||
|
||||
def test_ejs_in_extractor_dispatch():
|
||||
from graphify.extract import _DISPATCH
|
||||
assert _DISPATCH.get(".ejs") is extract_ejs
|
||||
|
||||
|
||||
def test_ejs_in_js_language_families():
|
||||
# Extraction-time family (cross-file call resolution) and the analyze-time
|
||||
# family must both treat a `.ejs` scriptlet as JS.
|
||||
from graphify.analyze import _LANG_FAMILY
|
||||
from graphify.extract import _LANG_FAMILY_BY_EXT
|
||||
assert _LANG_FAMILY_BY_EXT.get(".ejs") == "jsts"
|
||||
assert _LANG_FAMILY.get(".ejs") == "js"
|
||||
|
||||
|
||||
def test_ejs_in_resolution_and_hook_sets():
|
||||
# `.ejs` is a JS resolve extension (so extensionless requires/includes probe
|
||||
# the real template), a cache-bypass suffix (import resolution is
|
||||
# corpus-dependent, like the other JS-family SFCs), and a hook source ext
|
||||
# (editing a view must re-index the graph).
|
||||
from graphify.cli import _HOOK_SOURCE_EXTS
|
||||
from graphify.extract import _JS_CACHE_BYPASS_SUFFIXES, _JS_RESOLVE_EXTS
|
||||
assert ".ejs" in _JS_RESOLVE_EXTS
|
||||
assert ".ejs" in _JS_CACHE_BYPASS_SUFFIXES
|
||||
assert ".ejs" in _HOOK_SOURCE_EXTS
|
||||
|
||||
|
||||
def test_extract_ejs_scriptlet_is_not_a_parse_error(tmp_path):
|
||||
"""Markup is not JS; the scriptlet body is parsed and keeps its line (#3928)."""
|
||||
tpl = _write(
|
||||
tmp_path / "views" / "page.ejs",
|
||||
"<h1><%= title %></h1>\n"
|
||||
"<%\n"
|
||||
"function greet(name) { return name; }\n"
|
||||
"%>\n"
|
||||
"<p><%= greet(user) %></p>\n",
|
||||
)
|
||||
result = extract_ejs(tpl)
|
||||
assert result.get("parse_errors") is None
|
||||
assert _labels(result)["greet()"] == "L3"
|
||||
|
||||
|
||||
def test_extract_ejs_output_tag_in_inline_script_is_not_a_parse_error(tmp_path):
|
||||
"""`const x = <%- data %>` inside `<script>` must not break the JS parse."""
|
||||
tpl = _write(
|
||||
tmp_path / "views" / "inline.ejs",
|
||||
"<script>\n"
|
||||
" const data = <%- JSON.stringify(items) %>;\n"
|
||||
" function boot() { return data; }\n"
|
||||
"</script>\n",
|
||||
)
|
||||
result = extract_ejs(tpl)
|
||||
assert result.get("parse_errors") is None
|
||||
assert "boot()" in _labels(result)
|
||||
|
||||
|
||||
def test_extract_ejs_require_and_import_resolve_to_real_files(tmp_path):
|
||||
tpl = _write(
|
||||
tmp_path / "views" / "page.ejs",
|
||||
"<%\n"
|
||||
"const helpers = require('../lib/helpers');\n"
|
||||
"import { format } from '../lib/format';\n"
|
||||
"%>\n"
|
||||
"<p><%= format(x) %></p>\n",
|
||||
)
|
||||
helpers = _write(tmp_path / "lib" / "helpers.js", "exports.h = {};\n")
|
||||
fmt = _write(tmp_path / "lib" / "format.ts", "export function format() {}\n")
|
||||
|
||||
result = extract_ejs(tpl)
|
||||
targets = {e["target_file"] for e in result["edges"] if e.get("target_file")}
|
||||
assert str(helpers) in targets
|
||||
assert str(fmt) in targets
|
||||
|
||||
|
||||
def test_extract_ejs_include_resolves_to_the_real_partial(tmp_path):
|
||||
"""`<%- include('partials/header') %>` links the view to the partial file.
|
||||
|
||||
This is the relationship an Express view graph is built on (#2511). The
|
||||
include is spelled relative to the view without a leading `./` (as in the
|
||||
issue's example), and must resolve to the actual `.ejs` file on disk.
|
||||
"""
|
||||
tpl = _write(
|
||||
tmp_path / "views" / "inbox.ejs",
|
||||
"<%- include('partials/header') %>\n"
|
||||
"<p>body</p>\n",
|
||||
)
|
||||
partial = _write(
|
||||
tmp_path / "views" / "partials" / "header.ejs",
|
||||
"<header>hi</header>\n",
|
||||
)
|
||||
|
||||
result = extract_ejs(tpl)
|
||||
includes = _edges(result, "includes")
|
||||
assert len(includes) == 1
|
||||
assert includes[0]["target"] == _make_id(str(partial))
|
||||
assert includes[0]["target_file"] == str(partial)
|
||||
assert includes[0]["source_location"] == "L1"
|
||||
|
||||
|
||||
def test_extract_ejs_end_to_end_links_partial_file_node(tmp_path):
|
||||
"""Through `extract` the stamped include edge repoints at the partial's node."""
|
||||
tpl = _write(
|
||||
tmp_path / "views" / "inbox.ejs",
|
||||
"<%- include('partials/header') %>\n",
|
||||
)
|
||||
partial = _write(
|
||||
tmp_path / "views" / "partials" / "header.ejs",
|
||||
"<header>hi</header>\n",
|
||||
)
|
||||
|
||||
result = extract([tpl, partial], cache_root=tmp_path, root=tmp_path)
|
||||
labels = {n["id"]: n["label"] for n in result["nodes"]}
|
||||
targets = {labels.get(e["target"]) for e in _edges(result, "includes")}
|
||||
assert "header.ejs" in targets
|
||||
|
||||
|
||||
def test_extract_ejs_unresolved_include_keeps_a_stub(tmp_path):
|
||||
"""A views-root/bare include that resolves to no file still links something."""
|
||||
tpl = _write(
|
||||
tmp_path / "views" / "inbox.ejs",
|
||||
"<%- include('layouts/app', { title: 'Inbox' }) %>\n",
|
||||
)
|
||||
result = extract_ejs(tpl)
|
||||
includes = _edges(result, "includes")
|
||||
assert len(includes) == 1
|
||||
labels = {n["id"]: n["label"] for n in result["nodes"]}
|
||||
assert labels[includes[0]["target"]] == "layouts/app"
|
||||
|
||||
|
||||
def test_extract_ejs_dynamic_import_in_scriptlet(tmp_path):
|
||||
tpl = _write(
|
||||
tmp_path / "views" / "lazy.ejs",
|
||||
"<% import('./chart.js').then(function(m) { m.init(); }); %>\n",
|
||||
)
|
||||
chart = _write(tmp_path / "views" / "chart.js", "export function init() {}\n")
|
||||
|
||||
result = extract_ejs(tpl)
|
||||
dynamic = _edges(result, "dynamic_import")
|
||||
assert len(dynamic) == 1
|
||||
assert dynamic[0]["target_file"] == str(chart)
|
||||
|
||||
|
||||
def test_extract_ejs_comment_and_escape_tags_are_not_code(tmp_path):
|
||||
"""`<%# … %>` is a comment and `<%%` a literal `<%`; neither is a tag."""
|
||||
tpl = _write(
|
||||
tmp_path / "views" / "quirks.ejs",
|
||||
"<%# a comment %>\n"
|
||||
"<p>literal <%% not a tag %></p>\n"
|
||||
"<% function real() { return 1; } %>\n",
|
||||
)
|
||||
result = extract_ejs(tpl)
|
||||
assert result.get("parse_errors") is None
|
||||
labels = _labels(result)
|
||||
assert "real()" in labels
|
||||
# The escaped literal must not have started a code tag.
|
||||
assert not any("not a tag" in label for label in labels)
|
||||
|
||||
|
||||
def test_extract_ejs_markup_only_does_not_crash(tmp_path):
|
||||
tpl = _write(tmp_path / "views" / "plain.ejs", "<h1>no script here</h1>\n")
|
||||
result = extract_ejs(tpl)
|
||||
assert isinstance(result, dict)
|
||||
assert result.get("parse_errors") is None
|
||||
assert _edges(result, "includes") == []
|
||||
|
||||
|
||||
def test_extract_ejs_unreadable_file_reports_error(tmp_path):
|
||||
result = extract_ejs(tmp_path / "missing" / "Gone.ejs")
|
||||
assert result["nodes"] == [] and result["edges"] == []
|
||||
assert "error" in result
|
||||
|
||||
|
||||
def test_extract_ejs_no_longer_reports_missing_extractor(tmp_path, capsys):
|
||||
"""The #1689 "no AST extractor" warning must be gone now that `.ejs` is wired."""
|
||||
tpl = _write(
|
||||
tmp_path / "views" / "page.ejs",
|
||||
"<% function f() { return 1; } %>\n<p><%= f() %></p>\n",
|
||||
)
|
||||
result = extract([tpl], cache_root=tmp_path, root=tmp_path)
|
||||
err = capsys.readouterr().err
|
||||
assert "no AST extractor" not in err
|
||||
assert any(n.get("label") == "page.ejs" for n in result["nodes"])
|
||||
|
||||
Reference in new issue
Block a user