From 85ff79377ff1a878d5ba981b1dfd161256a2976e Mon Sep 17 00:00:00 2001 From: Arinjay Wyawhare <72088094+jaywyawhare@users.noreply.github.com> Date: Sat, 5 Dec 2026 11:25:44 +0530 Subject: [PATCH] Resolve a package root's imports of itself, directory imports, and values over same-named types --- src/selfgraph/code/_resolve.py | 56 ++++++++++++++++---- src/selfgraph/code/languages.json | 6 +-- tests/fixtures/code-self/README.md | 4 ++ tests/fixtures/code-self/pkg/__init__.py | 0 tests/fixtures/code-self/pkg/cli/__init__.py | 0 tests/fixtures/code-self/pkg/cli/app.py | 7 +++ tests/fixtures/code-self/pkg/main.py | 7 +++ tests/fixtures/code-self/web/core.ts | 7 +++ tests/fixtures/code-self/web/index.ts | 3 ++ tests/fixtures/code-self/web/sub/index.ts | 3 ++ tests/fixtures/code-self/web/sub/use.ts | 7 +++ tests/test_code_resolve.py | 18 +++++++ typescript/src/code/languages.ts | 1 + typescript/src/code/resolve.ts | 54 +++++++++++++++++-- typescript/test/codeResolve.test.ts | 18 +++++++ typescript/test/conformance/helpers.ts | 1 + typescript/test/conformance/py_side.py | 5 +- typescript/test/conformance/ts_side.ts | 5 +- typescript/test/conformanceCode.test.ts | 13 ++++- 19 files changed, 193 insertions(+), 22 deletions(-) create mode 100644 tests/fixtures/code-self/README.md create mode 100644 tests/fixtures/code-self/pkg/__init__.py create mode 100644 tests/fixtures/code-self/pkg/cli/__init__.py create mode 100644 tests/fixtures/code-self/pkg/cli/app.py create mode 100644 tests/fixtures/code-self/pkg/main.py create mode 100644 tests/fixtures/code-self/web/core.ts create mode 100644 tests/fixtures/code-self/web/index.ts create mode 100644 tests/fixtures/code-self/web/sub/index.ts create mode 100644 tests/fixtures/code-self/web/sub/use.ts diff --git a/src/selfgraph/code/_resolve.py b/src/selfgraph/code/_resolve.py index 742c2d73..bf85f426 100644 --- a/src/selfgraph/code/_resolve.py +++ b/src/selfgraph/code/_resolve.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +import os import posixpath import re from bisect import bisect_right @@ -144,6 +145,21 @@ def _fits(request: Request, method: str, template: tuple[str, ...]) -> bool: return all(t == s or (s != "" and _SLOT.fullmatch(t) is not None) for t, s in zip(template, segs, strict=True)) +def _pick(entries: list[tuple[str, Any]], types: bool) -> Any: + """The declaration a scope binds under a name: the type in a type position, else the value, so a function or + constant wins over an interface or type alias of the same name. + + @param entries (list[tuple[str, Any]]): what the scope binds under the name. + @param types (bool): whether the name is in a type position. + @return (Any): the declaration, or None. + """ + syms = [value for kind, value in entries if kind == "sym"] + for sym in syms: + if sym.kind in TYPE_KINDS if types else sym.kind not in ("interface", "type"): + return sym + return syms[0] if syms else None + + class _Sym: def __init__(self, file: _File, decl: Declaration) -> None: self.file, self.decl, self.kind, self.name, self.id = file, decl, decl.kind, decl.name, decl.id @@ -351,9 +367,9 @@ def _lookup(self, f: _File, offset: int, name: str, types: bool = False) -> tupl while scope is not None: private = scope is not start and scope.decl is not None and scope.decl.kind in TYPE_KINDS entries = [] if private and f.r.get("private_class_scope") else scope.names.get(name, []) - for kind, value in entries: - if kind == "sym": - return "sym", value, "scope" + sym = _pick(entries, types) + if sym is not None: + return "sym", sym, "scope" for kind, value in entries: if kind == "import": found = self._import(f, value) @@ -508,9 +524,9 @@ def _top(self, m: _File, name: str) -> tuple[str, Any] | None: @return (tuple[str, Any] | None): the binding, or None. """ entries = m.top.names.get(name, []) - for kind, value in entries: - if kind == "sym": - return "sym", value + sym = _pick(entries, False) + if sym is not None: + return "sym", sym for kind, value in entries: if kind == "import": return self._import(m, value) @@ -553,7 +569,7 @@ def _files(self, f: _File, text: str, relative: bool) -> list[_File]: return [] bases = [(f.root, "/".join(parts[: len(parts) - dots + 1]))] path = text[dots:].replace(sep, "/") - elif relative or text.startswith(("./", "../")): + elif relative or text.startswith(("./", "../")) or text in (".", ".."): bases = [(f.root, f.dir)] elif m: segs = [s for s in text.split(sep) if s] if sep != "/" else [text] @@ -571,6 +587,7 @@ def _files(self, f: _File, text: str, relative: bool) -> list[_File]: if "root" in search: bases.extend((i, "") for i in range(len(self.roots)) if i != f.root) candidates = [(root, _norm(f"{base}/{path}")) for root, base in bases] + self._configured(f, text) + candidates += self._own(f, text) out: list[_File] = [] for root, full in candidates: if full.startswith(".."): @@ -578,7 +595,7 @@ def _files(self, f: _File, text: str, relative: bool) -> list[_File]: if m.get("directory"): out = [o for o in self.files if o.root == root and o.dir == full and o.r is f.r] else: - names = [full + s for s in m.get("suffixes", [""])] + names = [(full + s).removeprefix("/") for s in m.get("suffixes", [""])] compiled = m.get("compiled") if compiled and re.search(compiled, full): stem = re.sub(compiled, "", full) @@ -589,6 +606,22 @@ def _files(self, f: _File, text: str, relative: bool) -> list[_File]: self.cache[key] = out return out + def _own(self, f: _File, text: str) -> list[tuple[int, str]]: + """The paths a module name maps to when its first segment names a root that is itself a package. + + @param f (_File): the file. + @param text (str): the module name. + @return (list[tuple[int, str]]): (root index, path) pairs to try. + """ + sep = f.m.get("separator", "/") + head, _, rest = text.partition(sep) + return [ + (index, rest.replace(sep, "/")) + for index, root in enumerate(self.roots) + if head == os.path.basename(os.path.normpath(root)) + and any((index, marker) in self.by_path for marker in f.m.get("packages", [])) + ] + def _anchor(self, f: _File, anchor: str) -> str: """The directory a leading path segment such as crate, self, or super stands for. @@ -676,8 +709,11 @@ def _type(self, f: _File, offset: int, text: str) -> tuple[_Sym, str] | None: result = (cls, "member") if cls is not None else None else: found = self._path(f, offset, segs, types=True) - if found is not None and found[0][0] == "sym" and found[0][1].kind in TYPE_KINDS: - result = (found[0][1], found[1]) + sym = found[0][1] if found is not None and found[0][0] == "sym" else None + if sym is not None and sym.parent is None and sym.kind not in TYPE_KINDS: + sym = _pick(sym.file.top.names.get(sym.name, []), True) + if sym is not None and sym.kind in TYPE_KINDS: + result = (sym, found[1]) self.active.discard(key) self.cache[key] = result return result diff --git a/src/selfgraph/code/languages.json b/src/selfgraph/code/languages.json index d4bfaed2..55a96ac5 100644 --- a/src/selfgraph/code/languages.json +++ b/src/selfgraph/code/languages.json @@ -51,7 +51,7 @@ "calls": {"call_expression": null, "new_expression": {"field": "constructor"}}, "imports": {"import_statement": {"steps": [{"field": "source"}]}, "export_statement": {"steps": [{"field": "source"}]}}, "require": {"callees": {"require": false, "import": false}, "argument": "arguments", "types": ["string"]}, - "relative": "^['\"`]\\.\\.?/", + "relative": "^['\"`]\\.\\.?(?:/|['\"`])", "modules": "javascript" }, { @@ -78,7 +78,7 @@ "calls": {"call_expression": null, "new_expression": {"field": "constructor"}}, "imports": {"import_statement": {"steps": [{"field": "source"}]}, "export_statement": {"steps": [{"field": "source"}]}}, "require": {"callees": {"require": false, "import": false}, "argument": "arguments", "types": ["string"]}, - "relative": "^['\"`]\\.\\.?/", + "relative": "^['\"`]\\.\\.?(?:/|['\"`])", "modules": "javascript" }, { @@ -86,7 +86,7 @@ "name": "Python", "extensions": [".py", ".pyi"], "grammar": {"pypi": "tree-sitter-python", "module": "tree_sitter_python", "function": "language", "npm": "tree-sitter-python", "wasm": "tree-sitter-python.wasm", "version": "0.25.0"}, - "resolve": {"queries": ["python"], "self": ["self", "cls"], "split": "\\.", "private_class_scope": true, "modules": {"separator": ".", "relative": "dots", "suffixes": ["/__init__.py", "/__init__.pyi", ".py", ".pyi"], "search": ["ancestors", "root"], "local": "first"}}, + "resolve": {"queries": ["python"], "self": ["self", "cls"], "split": "\\.", "private_class_scope": true, "modules": {"separator": ".", "relative": "dots", "suffixes": ["/__init__.py", "/__init__.pyi", ".py", ".pyi"], "search": ["ancestors", "root"], "local": "first", "packages": ["__init__.py", "__init__.pyi"]}}, "declarations": {"function_definition": "function", "class_definition": "class"}, "calls": {"call": null}, "imports": { diff --git a/tests/fixtures/code-self/README.md b/tests/fixtures/code-self/README.md new file mode 100644 index 00000000..6b1c61cf --- /dev/null +++ b/tests/fixtures/code-self/README.md @@ -0,0 +1,4 @@ +Sources for the self-import and directory-import tests in `tests/test_code_resolve.py` and +`typescript/test/codeResolve.test.ts`, and for the conformance case that compares the graphs both SDKs +build from them. `pkg` is a package root that imports itself by name; `web` imports folders by their index. +Nothing here is run or built. diff --git a/tests/fixtures/code-self/pkg/__init__.py b/tests/fixtures/code-self/pkg/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/fixtures/code-self/pkg/cli/__init__.py b/tests/fixtures/code-self/pkg/cli/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/fixtures/code-self/pkg/cli/app.py b/tests/fixtures/code-self/pkg/cli/app.py new file mode 100644 index 00000000..579851d8 --- /dev/null +++ b/tests/fixtures/code-self/pkg/cli/app.py @@ -0,0 +1,7 @@ +class App: + def run(self): + return 1 + + +def helper(): + return 2 diff --git a/tests/fixtures/code-self/pkg/main.py b/tests/fixtures/code-self/pkg/main.py new file mode 100644 index 00000000..4e00f51b --- /dev/null +++ b/tests/fixtures/code-self/pkg/main.py @@ -0,0 +1,7 @@ +import pkg.cli.app +from pkg.cli.app import App + + +def go(): + App() + return pkg.cli.app.helper() diff --git a/tests/fixtures/code-self/web/core.ts b/tests/fixtures/code-self/web/core.ts new file mode 100644 index 00000000..252786d2 --- /dev/null +++ b/tests/fixtures/code-self/web/core.ts @@ -0,0 +1,7 @@ +export interface Ok { + v: number; +} + +export function Ok(): Ok { + return { v: 1 }; +} diff --git a/tests/fixtures/code-self/web/index.ts b/tests/fixtures/code-self/web/index.ts new file mode 100644 index 00000000..4904dae9 --- /dev/null +++ b/tests/fixtures/code-self/web/index.ts @@ -0,0 +1,3 @@ +export function hello(): number { + return 1; +} diff --git a/tests/fixtures/code-self/web/sub/index.ts b/tests/fixtures/code-self/web/sub/index.ts new file mode 100644 index 00000000..5c6496ee --- /dev/null +++ b/tests/fixtures/code-self/web/sub/index.ts @@ -0,0 +1,3 @@ +export function local(): number { + return 2; +} diff --git a/tests/fixtures/code-self/web/sub/use.ts b/tests/fixtures/code-self/web/sub/use.ts new file mode 100644 index 00000000..c2f91a74 --- /dev/null +++ b/tests/fixtures/code-self/web/sub/use.ts @@ -0,0 +1,7 @@ +import { hello } from ".."; +import { local } from "."; +import * as core from "../core"; + +export function go(): number { + return hello() + local() + core.Ok().v; +} diff --git a/tests/test_code_resolve.py b/tests/test_code_resolve.py index 6e10b710..dd088bd7 100644 --- a/tests/test_code_resolve.py +++ b/tests/test_code_resolve.py @@ -8,6 +8,7 @@ pytest.importorskip("tree_sitter_typescript") RESOLVE = Path(__file__).parent / "fixtures" / "code-resolve" +SELF = Path(__file__).parent / "fixtures" / "code-self" NESTED = ( "def helper():\n return 1\n\n\ndef outer():\n def helper():\n return 2\n\n return helper()\n\n\n" "def run(helper, service):\n service.save()\n return helper()\n" @@ -234,6 +235,23 @@ def test_package_names_tsconfig_paths_and_lua_tables_resolve_across_files(tmp_pa } <= resolved(g) +def test_a_package_root_imports_itself_by_name_and_a_directory_import_reaches_its_index(): + g = fresh_graph("code-self-package") + run(g.code.index([str(SELF / "pkg"), str(SELF / "web")])) + assert resolved(g) == { + "IMPORTS file:pkg/main.py file:pkg/__init__.py path", + "IMPORTS file:pkg/main.py file:pkg/cli/app.py path", + "CONSTRUCTS function:pkg/main.py:go class:pkg/cli/app.py:app import", + "CALLS function:pkg/main.py:go function:pkg/cli/app.py:helper import", + "IMPORTS file:web/sub/use.ts file:web/index.ts path", + "IMPORTS file:web/sub/use.ts file:web/sub/index.ts path", + "IMPORTS file:web/sub/use.ts file:web/core.ts path", + "CALLS function:web/sub/use.ts:go function:web/index.ts:hello import", + "CALLS function:web/sub/use.ts:go function:web/sub/index.ts:local import", + "CALLS function:web/sub/use.ts:go function:web/core.ts:ok import", + } + + def test_receivers_resolve_through_the_types_variables_fields_and_returns_hold(): g = fresh_graph("code-flow") run(g.code.index(str(RESOLVE))) diff --git a/typescript/src/code/languages.ts b/typescript/src/code/languages.ts index f7f548b1..0ea2f571 100644 --- a/typescript/src/code/languages.ts +++ b/typescript/src/code/languages.ts @@ -66,6 +66,7 @@ export interface ModuleSpec { configs?: string[]; anchors?: Record; markers?: string[]; + packages?: string[]; index?: string[]; transitive?: boolean; } diff --git a/typescript/src/code/resolve.ts b/typescript/src/code/resolve.ts index c77dba55..cf26f8db 100644 --- a/typescript/src/code/resolve.ts +++ b/typescript/src/code/resolve.ts @@ -1,3 +1,4 @@ +import { basename, normalize } from "node:path"; import { comparePy, cpLen, isPlainObject, PY_WS_CLASS, pyStrip } from "../internal/py.js"; import { type ModuleSpec, type ResolveSpec, tables } from "./languages.js"; import type { Binding, Declaration, FileModel, ProjectModel, Request, ResolvedEdge } from "./model.js"; @@ -208,6 +209,22 @@ function fits(request: Request, method: string, template: string[]): boolean { return template.every((t, i) => t === segs[i] || (segs[i] !== "" && SLOT.test(t))); } +/** + * The declaration a scope binds under a name: the type in a type position, else the value, so a function or + * constant wins over an interface or type alias of the same name. + * + * @param entries (Entry[]): what the scope binds under the name. + * @param types (boolean): whether the name is in a type position. + * @return (Sym | null): the declaration, or null. + */ +function pick(entries: Entry[], types: boolean): Sym | null { + const syms = entries.filter((entry) => entry[0] === "sym").map(([, value]) => value as Sym); + const wanted = syms.find((sym) => + types ? TYPE_KINDS.has(sym.kind) : sym.kind !== "interface" && sym.kind !== "type", + ); + return wanted ?? syms[0] ?? null; +} + class Sym { readonly id: string; readonly kind: string; @@ -503,7 +520,8 @@ class Resolver { while (scope !== null) { const hidden = scope !== start && scope.decl !== null && TYPE_KINDS.has(scope.decl.kind); const entries = hidden && f.r.private_class_scope ? [] : (scope.names.get(name) ?? []); - for (const [kind, value] of entries) if (kind === "sym") return ["sym", value, "scope"]; + const sym = pick(entries, types); + if (sym !== null) return ["sym", sym, "scope"]; for (const [kind, value] of entries) { if (kind !== "import") continue; const found = this.importOf(f, value); @@ -675,7 +693,8 @@ class Resolver { */ top(m: File, name: string): Value | null { const entries = m.top.names.get(name) ?? []; - for (const [kind, value] of entries) if (kind === "sym") return ["sym", value]; + const sym = pick(entries, false); + if (sym !== null) return ["sym", sym]; for (const [kind, value] of entries) if (kind === "import") return this.importOf(m, value); const held = entries.filter(([kind]) => kind === "var").map(([, value]) => value as Binding); if (held.length) return ["var", [m, held]]; @@ -718,7 +737,7 @@ class Resolver { } bases = [[f.root, parts.slice(0, parts.length - dots + 1).join("/")]]; path = text.slice(dots).split(sep).join("/"); - } else if (relative || text.startsWith("./") || text.startsWith("../")) { + } else if (relative || text.startsWith("./") || text.startsWith("../") || text === "." || text === "..") { bases = [[f.root, f.dir]]; } else if (Object.keys(m).length) { let segs = sep !== "/" ? text.split(sep).filter((s) => s) : [text]; @@ -745,6 +764,7 @@ class Resolver { const candidates: [number, string][] = [ ...bases.map(([root, base]): [number, string] => [root, norm(`${base}/${path}`)]), ...this.configured(f, text), + ...this.own(f, text), ]; let out: File[] = []; for (const [root, full] of candidates) { @@ -753,7 +773,7 @@ class Resolver { out = this.files.filter((o) => o.root === root && o.dir === full && o.r === f.r); } else { const suffixes = m.suffixes ?? [""]; - let names = suffixes.map((s) => full + s); + let names = suffixes.map((s) => (full + s).replace(/^[/]/, "")); if (m.compiled && new RegExp(m.compiled).test(full)) { const base = full.replace(new RegExp(m.compiled), ""); names = [...suffixes.filter((s) => s && !s.includes("/")).map((s) => base + s), ...names]; @@ -769,6 +789,26 @@ class Resolver { return out; } + /** + * The paths a module name maps to when its first segment names a root that is itself a package. + * + * @param f (File): the file. + * @param text (string): the module name. + * @return ([number, string][]): (root index, path) pairs to try. + */ + own(f: File, text: string): [number, string][] { + const sep = f.m.separator ?? "/"; + const [head, , rest] = partition(text, sep); + const out: [number, string][] = []; + this.roots.forEach((root, index) => { + if (head !== basename(normalize(root))) return; + if ((f.m.packages ?? []).some((marker) => this.byPath.has(`${index}\0${marker}`))) { + out.push([index, rest.split(sep).join("/")]); + } + }); + return out; + } + /** * The directory a leading path segment such as crate, self, or super stands for. * @@ -867,7 +907,11 @@ class Resolver { result = cls !== null ? [cls, "member"] : null; } else { const found = this.path(f, offset, segs, true); - if (found !== null && found[0][0] === "sym" && TYPE_KINDS.has(found[0][1].kind)) result = [found[0][1], found[1]]; + let sym = found !== null && found[0][0] === "sym" ? found[0][1] : null; + if (sym !== null && sym.parent === null && !TYPE_KINDS.has(sym.kind)) { + sym = pick(sym.file.top.names.get(sym.name) ?? [], true); + } + if (found !== null && sym !== null && TYPE_KINDS.has(sym.kind)) result = [sym, found[1]]; } this.active.delete(key); this.cache.set(key, result); diff --git a/typescript/test/codeResolve.test.ts b/typescript/test/codeResolve.test.ts index 104c2e95..80b12411 100644 --- a/typescript/test/codeResolve.test.ts +++ b/typescript/test/codeResolve.test.ts @@ -9,6 +9,7 @@ import type { Relation, SelfGraph } from "../src/index.js"; import { freshGraphs, KUZU_SPEC, tempDir } from "./helpers.js"; const RESOLVE = fileURLToPath(new URL("../../tests/fixtures/code-resolve", import.meta.url)); +const SELF = fileURLToPath(new URL("../../tests/fixtures/code-self", import.meta.url)); const NESTED = "def helper():\n return 1\n\n\ndef outer():\n def helper():\n return 2\n\n return helper()\n\n\n" + "def run(helper, service):\n service.save()\n return helper()\n"; @@ -249,6 +250,23 @@ describe.skipIf(!available("python") || !available("typescript"))("code call res ); }); + it("resolves a package root's imports of itself by name and directory imports to their index", async () => { + const g = open(); + await g.code.index([join(SELF, "pkg"), join(SELF, "web")]); + expect((await resolved(g)).sort()).toEqual([ + "CALLS function:pkg/main.py:go function:pkg/cli/app.py:helper import", + "CALLS function:web/sub/use.ts:go function:web/core.ts:ok import", + "CALLS function:web/sub/use.ts:go function:web/index.ts:hello import", + "CALLS function:web/sub/use.ts:go function:web/sub/index.ts:local import", + "CONSTRUCTS function:pkg/main.py:go class:pkg/cli/app.py:app import", + "IMPORTS file:pkg/main.py file:pkg/__init__.py path", + "IMPORTS file:pkg/main.py file:pkg/cli/app.py path", + "IMPORTS file:web/sub/use.ts file:web/core.ts path", + "IMPORTS file:web/sub/use.ts file:web/index.ts path", + "IMPORTS file:web/sub/use.ts file:web/sub/index.ts path", + ]); + }); + it("resolves receivers through the types that variables, fields, and returns hold", async () => { const g = open(); await g.code.index(RESOLVE); diff --git a/typescript/test/conformance/helpers.ts b/typescript/test/conformance/helpers.ts index 415a06f5..bebcc68f 100644 --- a/typescript/test/conformance/helpers.ts +++ b/typescript/test/conformance/helpers.ts @@ -31,6 +31,7 @@ export function py( | "code_resolve" | "code_remote" | "code_endpoints" + | "code_self" | "pinned_unicode" | "kuzu_statements" | "kuzu_cut_update" diff --git a/typescript/test/conformance/py_side.py b/typescript/test/conformance/py_side.py index d33f4bf7..b5a3c2da 100644 --- a/typescript/test/conformance/py_side.py +++ b/typescript/test/conformance/py_side.py @@ -1477,6 +1477,7 @@ def code_facts(): CODE_FIXTURE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "tests", "fixtures", "code") RESOLVE_FIXTURE = CODE_FIXTURE + "-resolve" ENDPOINTS_FIXTURE = CODE_FIXTURE + "-endpoints" +SELF_FIXTURE = [os.path.join(CODE_FIXTURE + "-self", name) for name in ("pkg", "web")] async def code_graph(graph, fixture=CODE_FIXTURE): @@ -1484,7 +1485,7 @@ async def code_graph(graph, fixture=CODE_FIXTURE): evidence. @param graph (SelfGraph): the graph, in a fresh namespace. - @param fixture (str): the fixture folder. + @param fixture (str | list[str]): the fixture folder, or several roots. @return (dict): the index result, the second run's result, the languages it parsed, and the stored graph. """ result = await graph.code.index(fixture) @@ -5628,6 +5629,8 @@ async def main(): result = await code_graph(graph, RESOLVE_FIXTURE) elif cmd == "code_endpoints": result = await code_graph(graph, ENDPOINTS_FIXTURE) + elif cmd == "code_self": + result = await code_graph(graph, SELF_FIXTURE) else: result = await write(graph) if cmd == "write" else await dump(graph, ns) finally: diff --git a/typescript/test/conformance/ts_side.ts b/typescript/test/conformance/ts_side.ts index 65c3b244..ed43b64d 100644 --- a/typescript/test/conformance/ts_side.ts +++ b/typescript/test/conformance/ts_side.ts @@ -1650,15 +1650,16 @@ export async function codeFacts(): Promise { const CODE_FIXTURE = fileURLToPath(new URL("../../../tests/fixtures/code", import.meta.url)); export const RESOLVE_FIXTURE = `${CODE_FIXTURE}-resolve`; export const ENDPOINTS_FIXTURE = `${CODE_FIXTURE}-endpoints`; +export const SELF_FIXTURE = ["pkg", "web"].map((name) => join(`${CODE_FIXTURE}-self`, name)); /** * Index a code fixture twice and read back both results, the languages, every entity, and every relation with evidence. * * @param graph (SelfGraph): the graph, in a fresh namespace. - * @param fixture (string): the fixture folder. + * @param fixture (string | string[]): the fixture folder, or several roots. * @return (Promise): the index result, the second run's result, the languages it parsed, and the stored graph. */ -export async function codeGraph(graph: SelfGraph, fixture = CODE_FIXTURE): Promise { +export async function codeGraph(graph: SelfGraph, fixture: string | string[] = CODE_FIXTURE): Promise { const result = await graph.code.index(fixture); const second = await graph.code.index(fixture); const byId = (a: { id: string }, b: { id: string }) => comparePy(a.id, b.id); diff --git a/typescript/test/conformanceCode.test.ts b/typescript/test/conformanceCode.test.ts index 944801a7..c12cc4bb 100644 --- a/typescript/test/conformanceCode.test.ts +++ b/typescript/test/conformanceCode.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import { live, PY, py, ts } from "./conformance/helpers.js"; -import { codeGraph, codeRemoteGraph, ENDPOINTS_FIXTURE, RESOLVE_FIXTURE } from "./conformance/ts_side.js"; +import { codeGraph, codeRemoteGraph, ENDPOINTS_FIXTURE, RESOLVE_FIXTURE, SELF_FIXTURE } from "./conformance/ts_side.js"; import { uniqueNs } from "./helpers.js"; describe.skipIf(!PY)("cross-language conformance with the Python SDK", () => { @@ -54,4 +54,15 @@ describe.skipIf(!PY)("cross-language conformance with the Python SDK", () => { "REEXPORTS path": 2, }); }); + + it.skipIf(!live.get("kuzu"))( + "kuzu: both languages resolve a package root's imports of itself and directory imports alike", + async () => { + const fromTs = (await ts("kuzu", uniqueNs("conf_self_ts"), (g) => codeGraph(g, SELF_FIXTURE))) as { + relations: [string, string, string, string, { resolution?: string }][]; + }; + expect(fromTs).toEqual(py("code_self", "kuzu", uniqueNs("conf_self_py"))); + expect(fromTs.relations.filter((r) => r[4].resolution).length).toBe(10); + }, + ); });