Skip to content

Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.

feat(container): index .vue SFCs via their <script> block (#97)

David Pruñonosa5781dd460bd2
diff --git a/src/graph/build.ts b/src/graph/build.ts
index 8124c7cc..da518c52 100644
--- a/src/graph/build.ts
+++ b/src/graph/build.ts
@@ -19,6 +19,7 @@ import { walkDir } from "../ingest/fs.js";
import { contextDirFor, ensureGitignored, ensureSearchable } from "../context/node-file.js";
import { extractFile, languageLabelOf, languageOf, type RawEdge } from "./extract.js";
import { extractGeneric, genericLangOf, warmGenericGrammars } from "./generic.js";
+import { containerLangOf, extractContainer, warmContainerGrammars } from "./container.js";
import { contentHash } from "../util/id.js";
import { relPosix } from "../util/paths.js";
import { readSourceFile } from "../util/source.js";
@@ -186,6 +187,11 @@ export async function buildGraph(
await warmGenericGrammars(
new Set(files.map((f) => genericLangOf(f.abs)?.name).filter((n): n is string => !!n)),
);
+ // Container tier (.vue and friends) loads its wrapper grammars the same way,
+ // for the same reason: extractContainer runs inside the sync loop below.
+ await warmContainerGrammars(
+ new Set(files.map((f) => containerLangOf(f.abs)?.name).filter((n): n is string => !!n)),
+ );
files.forEach((f, i) => {
const rel = f.rel;
@@ -193,8 +199,12 @@ export async function buildGraph(
// Depth tier (hand-written, native grammar) if a language claims the file;
// otherwise the breadth tier (generic tags.scm over a WASM grammar).
const lang = languageOf(f.abs);
- const generic = lang ? null : genericLangOf(f.abs);
- const label = languageLabelOf(f.abs) ?? generic?.name ?? "unknown";
+ // A container is neither tier: its wrapper grammar only locates the embedded
+ // block, which then goes to the depth-tier extractor. Checked before the
+ // breadth tier so a future grammar claiming .vue can't shadow it.
+ const container = lang ? null : containerLangOf(f.abs);
+ const generic = lang || container ? null : genericLangOf(f.abs);
+ const label = languageLabelOf(f.abs) ?? container?.name ?? generic?.name ?? "unknown";
const cached = priorExtract.files[rel];
// Every file is read and hashed, every build — only the *parse* is memoized.
@@ -243,7 +253,9 @@ export async function buildGraph(
try {
const { nodes: fileNodes, rawEdges: fileEdges } = lang
? extractFile(rel, source, lang)
- : extractGeneric(rel, source, generic!.name);
+ : container
+ ? extractContainer(rel, source, container)
+ : extractGeneric(rel, source, generic!.name);
nodes.push(...fileNodes);
rawEdges.push(...fileEdges);
sources.set(rel, source);
diff --git a/src/graph/container.ts b/src/graph/container.ts
new file mode 100644
index 00000000..3015069e
--- /dev/null
+++ b/src/graph/container.ts
@@ -0,0 +1,208 @@
+/**
+ * Container tier — files that are not a language but a wrapper around one.
+ *
+ * A Vue SFC is the motivating case: `.vue` is HTML-shaped, and everything worth
+ * indexing lives inside its `<script>` block. Registering `tree-sitter-vue` as a
+ * breadth-tier language (generic.ts) would not help — that grammar parses the
+ * shell (`<template>` / `<script>` / `<style>`) and hands back the script body as
+ * one opaque `raw_text` node, so the cards would come out empty.
+ *
+ * So the container grammar is used only to answer "where does the embedded
+ * language start and end", and the block itself goes to the DEPTH-tier extractor
+ * (extract.ts). A `.vue` file therefore gets the same quality of extraction as a
+ * `.ts` file — bindings, imports, resolved calls — not the signature-only output
+ * the breadth tier would give.
+ *
+ * **The span shift is the whole risk here.** `extractFile` numbers its spans from
+ * the start of the string it was handed, so every node comes back pointing at a
+ * line in the script, not in the `.vue`. A span that is off by even one line is
+ * worse than not indexing the file at all: graft's promise is that its
+ * `file:line` is exact, and a plausible-but-wrong line silently sends the reader
+ * to the wrong place. `test/container-extract.test.ts` pins this against
+ * fixtures whose true line numbers are known.
+ */
+import { extractFile, mintId, type ExtractResult, type Language, type RawEdge } from "./extract.js";
+import { loadWasmLanguage, parseWasm, type TsNode } from "./generic.js";
+import { contentHash } from "../util/id.js";
+import type { NodeV1 } from "./types.js";
+
+/** A container language: the wrapper grammar, the node that holds the embedded
+ * source, and which depth-tier extractor to hand that source to. */
+export interface ContainerLang {
+ name: string;
+ exts: string[];
+ /** wasm basename in tree-sitter-wasms/out/tree-sitter-<wasm>.wasm */
+ wasm: string;
+ /** Wrapper node that represents one embedded block (e.g. Vue's script_element). */
+ block: string;
+ /** Child of `block` holding the raw embedded source (e.g. Vue's raw_text). */
+ body: string;
+ /** Depth-tier grammar for the embedded language. TypeScript is a superset of
+ * JavaScript, so it parses both `<script>` and `<script lang="ts">`. */
+ inner: Language;
+}
+
+/** The container registry. Svelte and Astro are the same shape and would be a
+ * row each, but they are left out until someone has a repo to verify them
+ * against — a wrong `body` node type would produce silently misplaced spans. */
+export const CONTAINER_LANGS: readonly ContainerLang[] = [
+ { name: "vue", exts: [".vue"], wasm: "vue", block: "script_element", body: "raw_text", inner: "typescript" },
+];
+
+const byExt = new Map<string, ContainerLang>();
+for (const l of CONTAINER_LANGS) for (const e of l.exts) byExt.set(e, l);
+
+/** The container language for a path, or null if none claims it. */
+export function containerLangOf(path: string): ContainerLang | null {
+ const lower = path.toLowerCase();
+ for (const [ext, l] of byExt) if (lower.endsWith(ext)) return l;
+ return null;
+}
+
+/** Every file extension the container tier claims. */
+export function containerExtensions(): string[] {
+ return CONTAINER_LANGS.flatMap((l) => l.exts);
+}
+
+const loaded = new Map<string, unknown>();
+
+/** Warm the container grammars this repo needs. Same contract as
+ * `warmGenericGrammars`: await once before the synchronous parse loop, and an
+ * unavailable grammar is skipped rather than fatal (its files then extract to a
+ * file node only, exactly as they do today). */
+export async function warmContainerGrammars(langNames: Iterable<string>): Promise<void> {
+ for (const name of new Set(langNames)) {
+ if (loaded.has(name)) continue;
+ const row = CONTAINER_LANGS.find((l) => l.name === name);
+ if (!row) continue;
+ const language = await loadWasmLanguage(row.wasm);
+ if (language) loaded.set(name, language);
+ }
+}
+
+/** True if a container grammar has been warmed (else extraction is file-only). */
+export function isContainerWarm(langName: string): boolean {
+ return loaded.has(langName);
+}
+
+/** `L12-L20` shifted by n lines. The span format is produced in exactly two
+ * places (extract.ts and generic.ts) and is always this shape; anything else is
+ * returned untouched rather than guessed at. */
+function shiftSpan(span: string, lines: number): string {
+ const m = /^L(\d+)-L(\d+)$/.exec(span);
+ if (!m) return span;
+ return `L${Number(m[1]) + lines}-L${Number(m[2]) + lines}`;
+}
+
+/** The `.vue` file's own node. Deliberately describes the whole file — line
+ * count, hash and size of the SFC, not of the script block — because that is
+ * what a reader opening this path will see. */
+function containerFileNode(rel: string, source: string, residual: string): NodeV1 {
+ return {
+ id: rel,
+ name: rel.split("/").pop() ?? rel,
+ kind: "file",
+ path: rel,
+ span: `L1-L${Math.max(1, source.split("\n").length)}`,
+ signature: null,
+ exported: true,
+ // "ast", not "generic": the symbols under this file come from the depth-tier
+ // extractor with real bindings and specifiers. resolve.ts gates a
+ // guess-by-name fallback on `origin === "generic"`, and these nodes must not
+ // take it — they carry the information to resolve properly.
+ origin: "ast",
+ body_hash: contentHash(source),
+ chars: source.length,
+ body_text: residual,
+ summary_state: "pending",
+ summary: null,
+ crux: null,
+ };
+}
+
+/** Every embedded block in document order, as [bodyNode] — an SFC may legally
+ * carry two (`<script>` for options/exports plus `<script setup>`), and each
+ * needs its own offset. */
+function blocks(root: TsNode, lang: ContainerLang): TsNode[] {
+ const out: TsNode[] = [];
+ const n = root.namedChildCount ?? 0;
+ for (let i = 0; i < n; i++) {
+ const child = root.namedChild?.(i);
+ if (!child || child.type !== lang.block) continue;
+ const kids = child.namedChildCount ?? 0;
+ for (let j = 0; j < kids; j++) {
+ const body = child.namedChild?.(j);
+ // An empty `<script></script>` has no body child at all — skipped here, so
+ // the file still gets its file node and nothing else, which is the same
+ // shape as a file whose grammar is missing.
+ if (body && body.type === lang.body) out.push(body);
+ }
+ }
+ return out;
+}
+
+/**
+ * Extract one container file. Synchronous; needs the grammar pre-warmed.
+ *
+ * Never throws: a missing grammar, an unparseable SFC or a script block the
+ * inner extractor chokes on all degrade to "fewer nodes", because a build must
+ * not fail over one component.
+ */
+export function extractContainer(rel: string, source: string, lang: ContainerLang): ExtractResult {
+ const nodes: NodeV1[] = [];
+ const rawEdges: RawEdge[] = [];
+ const residuals: string[] = [];
+
+ const language = loaded.get(lang.name);
+ const root = language ? parseWasm(language, source) : null;
+
+ if (root) {
+ // Ids are minted per file by the inner extractor, so two script blocks that
+ // both define `setup` would collide. Threading one set across the blocks
+ // makes the second one `path#setup~2`, and the rename is applied to that
+ // block's edges too so nothing points at an id that no longer exists.
+ const minted = new Set<string>([rel]);
+
+ for (const body of blocks(root, lang)) {
+ const script = source.slice(body.startIndex, body.endIndex);
+
+ let inner: ExtractResult;
+ try {
+ inner = extractFile(rel, script, lang.inner);
+ } catch {
+ continue; // one bad block, not a bad build
+ }
+
+ // `raw_text` starts immediately after the `>` of the opening tag, so its
+ // row IS the tag's row and the slice begins with that line's newline.
+ // Script line 1 is therefore the tail of the tag line, and script line N
+ // lands on `.vue` line row + N — which is exactly "add the start row to a
+ // 1-based span". Taking the row from the tag node instead would look
+ // equivalent and be right only when the tag has no attributes.
+ const shift = body.startPosition.row;
+
+ // nodes[0] is the script's own file node: it describes the block, not the
+ // file, so it is dropped and its residual folded into the .vue file node.
+ const [scriptFile, ...symbols] = inner.nodes;
+ if (scriptFile?.body_text) residuals.push(scriptFile.body_text);
+
+ const renamed = new Map<string, string>();
+ for (const node of symbols) {
+ const id = mintId(node.id, minted);
+ if (id !== node.id) renamed.set(node.id, id);
+ nodes.push({ ...node, id, span: shiftSpan(node.span, shift) });
+ }
+
+ for (const edge of inner.rawEdges) {
+ const source_ = renamed.get(edge.source) ?? edge.source;
+ const targetId = edge.targetId === undefined ? undefined : (renamed.get(edge.targetId) ?? edge.targetId);
+ rawEdges.push({ ...edge, source: source_, ...(targetId === undefined ? {} : { targetId }) });
+ }
+ }
+ }
+
+ // Built last so it can carry the residual, but unshifted first so the file node
+ // stays at index 0 like every other tier's output.
+ nodes.unshift(containerFileNode(rel, source, residuals.join("\n")));
+ return { nodes, rawEdges };
+}
diff --git a/src/graph/generic.ts b/src/graph/generic.ts
index 41268fdc..f35072d1 100644
--- a/src/graph/generic.ts
+++ b/src/graph/generic.ts
@@ -152,8 +152,45 @@ export function isWarm(langName: string): boolean {
return loaded.has(langName);
}
+/** Load one grammar from the tree-sitter-wasms bundle, initialising
+ * web-tree-sitter on first call. Null when the wasm is missing or won't
+ * instantiate — never throws, so a caller degrades instead of failing the build.
+ *
+ * Shared with the container tier (container.ts), which needs a grammar to find
+ * where an embedded language starts but none of the tags.scm machinery above.
+ * Kept here so web-tree-sitter is initialised exactly once per process. */
+export async function loadWasmLanguage(wasm: string): Promise<unknown | null> {
+ if (!tsMod) {
+ tsMod = await import("web-tree-sitter");
+ initPromise = initPromise ?? tsMod.Parser.init();
+ }
+ await initPromise;
+ const bytes = requireWasm(wasm);
+ if (!bytes) return null;
+ try {
+ return await tsMod.Language.load(bytes);
+ } catch {
+ return null;
+ }
+}
+
const PARSE_CHUNK = 16384; // <32KB slices — same tree-sitter limit workaround as extract.ts
+/** Parse with an already-loaded grammar. Returns the root node, or null if the
+ * grammar was never warmed or the parse blew up. Companion to
+ * `loadWasmLanguage` for callers outside this module. */
+export function parseWasm(language: unknown, source: string): TsNode | null {
+ if (!tsMod) return null;
+ try {
+ const parser = new tsMod.Parser();
+ parser.setLanguage(language as never);
+ const tree = parser.parse((i: number) => source.slice(i, i + PARSE_CHUNK));
+ return (tree?.rootNode as TsNode) ?? null;
+ } catch {
+ return null;
+ }
+}
+
function fileNode(rel: string, source: string): NodeV1 {
return {
id: rel, name: rel.split("/").pop() ?? rel, kind: "file", path: rel,
@@ -429,7 +466,8 @@ function walkExtract(root: TsNode, mkDef: (name: string, kind: Kind, whole: TsNo
visit(root);
}
-interface TsNode {
+/** Minimal structural view of a web-tree-sitter node — shared with container.ts. */
+export interface TsNode {
type: string;
text: string;
startIndex: number;
diff --git a/src/graph/source-files.ts b/src/graph/source-files.ts
index 29939c34..1de39ede 100644
--- a/src/graph/source-files.ts
+++ b/src/graph/source-files.ts
@@ -13,11 +13,12 @@ import { relPosix } from "../util/paths.js";
import { readIncludeDirs } from "../util/state.js";
import { languageOf, depthExtensions } from "./extract.js";
import { genericLangOf, genericExtensions } from "./generic.js";
+import { containerLangOf, containerExtensions } from "./container.js";
-/** Every extension graft has a parser for (depth + breadth), sorted and de-duped —
- * the authoritative answer to "what does `-e` actually support". */
+/** Every extension graft has a parser for (depth + breadth + container), sorted
+ * and de-duped — the authoritative answer to "what does `-e` actually support". */
export function supportedExtensions(): string[] {
- return [...new Set([...depthExtensions(), ...genericExtensions()])].sort();
+ return [...new Set([...depthExtensions(), ...genericExtensions(), ...containerExtensions()])].sort();
}
/** Normalize a user-supplied extension: ensure a leading dot, lower-case. */
@@ -49,11 +50,13 @@ export function listSourceFiles(
outDir: string,
repoFiles: string[] = walkDir(root, readIncludeDirs(resolve(root))),
): string[] {
- // A file is a source file if a depth-tier grammar (languageOf) OR a breadth-tier
- // grammar (genericLangOf) claims its extension. Both must agree here or `build`
- // and `check` would enumerate different sets.
+ // A file is a source file if a depth-tier grammar (languageOf), a breadth-tier
+ // grammar (genericLangOf) or a container (containerLangOf) claims its extension.
+ // All three must agree here or `build` and `check` would enumerate different sets.
return repoFiles.filter(
- (f) => !f.startsWith(outDir) && (languageOf(f) !== null || genericLangOf(f) !== null),
+ (f) =>
+ !f.startsWith(outDir) &&
+ (languageOf(f) !== null || genericLangOf(f) !== null || containerLangOf(f) !== null),
);
}
diff --git a/test/container-extract.test.ts b/test/container-extract.test.ts
new file mode 100644
index 00000000..7bf795cb
--- /dev/null
+++ b/test/container-extract.test.ts
@@ -0,0 +1,248 @@
+/**
+ * The container tier: files that wrap another language, `.vue` being the case
+ * that motivated it.
+ *
+ * The assertion that matters in every test here is the SPAN. Slicing the script
+ * block out is easy; putting its symbols back on the right `.vue` line is where
+ * this can go quietly wrong, and a span that is off by one is worse than no
+ * indexing at all — graft's whole promise is that its `file:line` is exact, so a
+ * plausible-but-wrong line sends the reader somewhere else with full confidence.
+ *
+ * Every fixture below is written as an array of lines and joined, so the
+ * expected line numbers are the array indices + 1 and can be read off the source
+ * rather than counted by hand.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, writeFileSync, mkdirSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import {
+ warmContainerGrammars,
+ extractContainer,
+ containerLangOf,
+ containerExtensions,
+ isContainerWarm,
+} from "../src/graph/container.js";
+import { supportedExtensions } from "../src/graph/source-files.js";
+import { buildGraph } from "../src/graph/build.js";
+import { readGraph, wiringPath } from "../src/graph/write.js";
+
+const VUE = containerLangOf("Any.vue")!;
+
+/** Line N of the fixture is `lines[N - 1]` — that is the whole point. */
+function sfc(lines: string[]): string {
+ return lines.join("\n") + "\n";
+}
+
+function spanOf(nodes: { name: string; span: string }[], name: string): string {
+ const hit = nodes.find((n) => n.name === name);
+ assert.ok(hit, `no node named ${name} (got: ${nodes.map((n) => n.name).join(", ")})`);
+ return hit.span;
+}
+
+test("container: registry claims .vue and reports it as supported", () => {
+ assert.equal(containerLangOf("src/components/Card.vue")?.name, "vue");
+ assert.equal(containerLangOf("src/components/Card.VUE")?.name, "vue", "extension match is case-insensitive");
+ assert.equal(containerLangOf("src/lib/util.ts"), null);
+ assert.ok(containerExtensions().includes(".vue"));
+ // Without this, the -e warning added in #100 would call .vue unsupported at
+ // the very moment it became supported.
+ assert.ok(supportedExtensions().includes(".vue"), ".vue must be in the -e supported set");
+});
+
+test("container: spans point at the .vue line, not the script line", async () => {
+ await warmContainerGrammars(["vue"]);
+ assert.ok(isContainerWarm("vue"), "vue grammar must be available in tree-sitter-wasms");
+
+ const lines = [
+ "<template>", // 1
+ " <p>{{ title }}</p>", // 2
+ "</template>", // 3
+ "", // 4
+ '<script setup lang="ts">', // 5
+ 'import { ref } from "vue";', // 6
+ "", // 7
+ "const title = ref('hi');", // 8
+ "", // 9
+ "export function shout(what: string) {", // 10
+ " return what.toUpperCase();", // 11
+ "}", // 12
+ "</script>", // 13
+ ];
+
+ const { nodes } = extractContainer("Card.vue", sfc(lines), VUE);
+
+ // Line 10 in the file; line 6 inside the script block. Getting 6 here would
+ // be the exact failure this tier exists to avoid.
+ assert.equal(spanOf(nodes, "shout"), "L10-L12");
+});
+
+test("container: a script with nothing above it still lands right", async () => {
+ await warmContainerGrammars(["vue"]);
+
+ const lines = [
+ '<script setup lang="ts">', // 1
+ "export function first() {}", // 2
+ "</script>", // 3
+ "", // 4
+ "<template><b/></template>", // 5
+ ];
+
+ // The offset is 0 here, so this is the case a naive implementation passes and
+ // the previous test catches. Kept because it is also the case a fix for the
+ // previous test could break.
+ assert.equal(spanOf(extractContainer("A.vue", sfc(lines), VUE).nodes, "first"), "L2-L2");
+});
+
+test("container: both script blocks are extracted, each with its own offset", async () => {
+ await warmContainerGrammars(["vue"]);
+
+ const lines = [
+ '<script lang="ts">', // 1
+ "export function onlyInOptions() {}", // 2
+ "</script>", // 3
+ "", // 4
+ '<script setup lang="ts">', // 5
+ "function onlyInSetup() {}", // 6
+ "</script>", // 7
+ ];
+
+ const { nodes } = extractContainer("Two.vue", sfc(lines), VUE);
+ assert.equal(spanOf(nodes, "onlyInOptions"), "L2-L2");
+ assert.equal(spanOf(nodes, "onlyInSetup"), "L6-L6");
+
+ // Whatever the inner extractor does or doesn't emit is its business — the
+ // container's job is only to relocate what comes back. A plain `const` is not
+ // a symbol in the TypeScript tier, and it must not become one here either.
+ assert.equal(nodes.filter((n) => n.kind === "file").length, 1, "exactly one file node");
+});
+
+test("container: a name defined in both blocks gets two nodes, not one", async () => {
+ await warmContainerGrammars(["vue"]);
+
+ const lines = [
+ "<script>", // 1
+ "function dup() {}", // 2
+ "</script>", // 3
+ "<script setup>", // 4
+ "function dup() {}", // 5
+ "</script>", // 6
+ ];
+
+ const { nodes, rawEdges } = extractContainer("Dup.vue", sfc(lines), VUE);
+ const dups = nodes.filter((n) => n.name === "dup");
+
+ assert.equal(dups.length, 2, "both definitions survive");
+ assert.equal(new Set(dups.map((n) => n.id)).size, 2, "ids are distinct");
+ assert.deepEqual(dups.map((n) => n.span).sort(), ["L2-L2", "L5-L5"]);
+
+ // The renamed id must be carried into that block's edges, or the graph points
+ // at a node that does not exist.
+ const ids = new Set(nodes.map((n) => n.id));
+ for (const e of rawEdges) {
+ assert.ok(ids.has(e.source), `edge source ${e.source} has no node`);
+ if (e.targetId) assert.ok(ids.has(e.targetId), `edge target ${e.targetId} has no node`);
+ }
+});
+
+test("container: the file node describes the .vue, not the script block", async () => {
+ await warmContainerGrammars(["vue"]);
+
+ const lines = [
+ "<template>", // 1
+ " <p>hola</p>", // 2
+ "</template>", // 3
+ "<script setup>", // 4
+ "const x = 1;", // 5
+ "</script>", // 6
+ "<style>.a{color:red}</style>", // 7
+ ];
+ const source = sfc(lines);
+
+ const { nodes } = extractContainer("Card.vue", source, VUE);
+ const file = nodes[0];
+
+ assert.equal(file.kind, "file");
+ assert.equal(file.id, "Card.vue");
+ assert.equal(file.span, "L1-L8", "spans the whole SFC, template and style included");
+ assert.equal(file.chars, source.length);
+ // Depth-tier origin: these symbols carry real bindings and import specifiers,
+ // so they must not take resolve.ts's generic guess-by-name path.
+ assert.equal(file.origin, "ast");
+});
+
+test("container: an SFC with no usable script degrades to a file node", async () => {
+ await warmContainerGrammars(["vue"]);
+
+ for (const [label, lines] of [
+ ["no script at all", ["<template>", " <p>static</p>", "</template>"]],
+ ["empty script", ["<script></script>", "<template><p/></template>"]],
+ ] as const) {
+ const { nodes, rawEdges } = extractContainer("Empty.vue", sfc([...lines]), VUE);
+ assert.equal(nodes.length, 1, `${label}: file node only`);
+ assert.equal(nodes[0].kind, "file");
+ assert.equal(rawEdges.length, 0, `${label}: no edges`);
+ }
+});
+
+test("container: multi-byte characters above the script do not shift the spans", async () => {
+ await warmContainerGrammars(["vue"]);
+
+ // Accents and an emoji in the template: if the slice were taken by byte offset
+ // against a UTF-16 string, the script would be cut in the wrong place and the
+ // symbol would move or vanish.
+ const lines = [
+ "<template>", // 1
+ " <p>Configuración 🚚 españolísima</p>", // 2
+ "</template>", // 3
+ '<script setup lang="ts">', // 4
+ "export function envío() { return 1; }", // 5
+ "</script>", // 6
+ ];
+
+ assert.equal(spanOf(extractContainer("Acc.vue", sfc(lines), VUE).nodes, "envío"), "L5-L5");
+});
+
+test("container: a .vue file goes through a real build end to end", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "graft-container-"));
+ mkdirSync(join(dir, "src"), { recursive: true });
+
+ writeFileSync(
+ join(dir, "src", "helper.ts"),
+ "export function greet(name: string) {\n return `hi ${name}`;\n}\n",
+ );
+ writeFileSync(
+ join(dir, "src", "Card.vue"),
+ sfc([
+ "<template>", // 1
+ " <p>{{ label }}</p>", // 2
+ "</template>", // 3
+ "", // 4
+ '<script setup lang="ts">', // 5
+ 'import { greet } from "./helper";', // 6
+ "", // 7
+ "export function label() {", // 8
+ " return greet('world');", // 9
+ "}", // 10
+ "</script>", // 11
+ ]),
+ );
+
+ const outDir = join(dir, "graft");
+ await buildGraph(dir, outDir, { reuse: false });
+ const graph = readGraph(wiringPath(outDir));
+
+ const label = graph.nodes.find((n) => n.name === "label" && n.path.endsWith("Card.vue"));
+ assert.ok(label, "the .vue symbol is in the built graph");
+ assert.equal(label.span, "L8-L10");
+
+ // The payoff of routing through the depth tier rather than a generic grammar:
+ // the import resolves, so the call from the SFC into a .ts module is a real edge.
+ const greet = graph.nodes.find((n) => n.name === "greet");
+ assert.ok(greet, "the .ts target is in the graph");
+ assert.ok(
+ graph.edges.some((e) => e.source === label.id && e.target === greet.id && e.relation === "calls"),
+ "the SFC's call into the .ts helper resolved",
+ );
+});
diff --git a/test/supported-extensions.test.ts b/test/supported-extensions.test.ts
index 1832444f..6bae31bd 100644
--- a/test/supported-extensions.test.ts
+++ b/test/supported-extensions.test.ts
@@ -1,8 +1,13 @@
/**
- * `-e` extension validation (#98): a `graft build -e ".vue"` must not silently index
+ * `-e` extension validation (#98): a `graft build -e "<ext>"` must not silently index
* nothing — the CLI warns on any extension no parser claims. These test the pure helper
- * the warning is built on: the supported set (depth + breadth) and which inputs fall
- * outside it, including normalization (leading dot optional, case-insensitive).
+ * the warning is built on: the supported set (depth + breadth + container) and which
+ * inputs fall outside it, including normalization (leading dot optional, case-insensitive).
+ *
+ * `.vue` was the extension originally reported in #98 and is used below as a
+ * SUPPORTED case: the container tier now claims it (#97). The unsupported side is
+ * carried by `.svelte`, which is the same SFC shape and the natural next request —
+ * the day someone adds it, this file is where the substitution happens again.
*/
import { test } from "node:test";
import assert from "node:assert/strict";
@@ -14,23 +19,26 @@ test("supportedExtensions covers both tiers, sorted and de-duped", () => {
for (const e of [".ts", ".tsx", ".py", ".go", ".java", ".js"]) assert.ok(exts.includes(e), `depth ${e}`);
// breadth tier
for (const e of [".rs", ".rb", ".php", ".c", ".cpp", ".kt", ".swift"]) assert.ok(exts.includes(e), `breadth ${e}`);
+ // container tier
+ assert.ok(exts.includes(".vue"), "container .vue");
// de-duped (.java is in BOTH tiers but must appear once) and sorted
assert.equal(exts.filter((e) => e === ".java").length, 1, ".java de-duped across tiers");
assert.deepEqual(exts, [...exts].sort(), "sorted");
});
test("unsupportedExtensions flags only what has no parser (the #98 repro)", () => {
- // .vue is the reported case — no parser → flagged
- assert.deepEqual(unsupportedExtensions([".vue"]), [".vue"]);
+ // no parser → flagged
+ assert.deepEqual(unsupportedExtensions([".svelte"]), [".svelte"]);
// mixed: supported ones drop out, unsupported stay
- assert.deepEqual(unsupportedExtensions([".ts", ".vue", ".rs", ".svelte"]), [".vue", ".svelte"]);
- // fully-supported input → nothing flagged
- assert.deepEqual(unsupportedExtensions([".ts", ".php", ".c"]), []);
+ assert.deepEqual(unsupportedExtensions([".ts", ".vue", ".rs", ".svelte"]), [".svelte"]);
+ // fully-supported input → nothing flagged, container tier included
+ assert.deepEqual(unsupportedExtensions([".ts", ".php", ".c", ".vue"]), []);
});
test("extension normalization: missing dot and mixed case still match a parser", () => {
// a user typing `-e vue` or `-e .TS` should be judged on the normalized form
assert.deepEqual(unsupportedExtensions(["ts"]), [], "no leading dot still recognized");
assert.deepEqual(unsupportedExtensions([".TS", ".Php"]), [], "case-insensitive");
- assert.deepEqual(unsupportedExtensions(["vue"]), ["vue"], "unsupported without dot still flagged (echoed as given)");
+ assert.deepEqual(unsupportedExtensions(["vue"]), [], "container extension recognized without a dot too");
+ assert.deepEqual(unsupportedExtensions(["Svelte"]), ["Svelte"], "unsupported still flagged, echoed as the user typed it");
});