codecop 0.1.0__py3-none-any.whl
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.
- codecop/__init__.py +7 -0
- codecop/access.py +140 -0
- codecop/access_postgres.py +284 -0
- codecop/advisor.py +1512 -0
- codecop/advisor_bench.py +493 -0
- codecop/advisor_ch.py +2080 -0
- codecop/advisor_view.py +381 -0
- codecop/advisors.py +184 -0
- codecop/agent.py +221 -0
- codecop/agentfacts.py +745 -0
- codecop/apply/__init__.py +327 -0
- codecop/apply/check.py +344 -0
- codecop/apply/cli.py +162 -0
- codecop/apply/clickhouse.py +379 -0
- codecop/apply/common.py +238 -0
- codecop/apply/html.py +264 -0
- codecop/apply/patch.py +213 -0
- codecop/apply/postgres.py +102 -0
- codecop/apply/trial.py +166 -0
- codecop/assemble.py +104 -0
- codecop/baseline.py +1043 -0
- codecop/bench.py +2464 -0
- codecop/blockers.py +935 -0
- codecop/budget.py +980 -0
- codecop/catalog_profile.py +525 -0
- codecop/changed.py +261 -0
- codecop/cicmd.py +1002 -0
- codecop/cli.py +5421 -0
- codecop/client.py +729 -0
- codecop/coverage.py +1067 -0
- codecop/coverage_reasons.py +116 -0
- codecop/crashlog.py +70 -0
- codecop/datagen.py +766 -0
- codecop/datagen_postgres.py +630 -0
- codecop/datagen_sqlite.py +323 -0
- codecop/dbcli.py +885 -0
- codecop/definitions.py +457 -0
- codecop/discover/__init__.py +702 -0
- codecop/discover/arms.py +160 -0
- codecop/discover/base.py +234 -0
- codecop/discover/dialect.py +296 -0
- codecop/discover/elixir.py +64 -0
- codecop/discover/engine_go.py +320 -0
- codecop/discover/go.py +1947 -0
- codecop/discover/java.py +1528 -0
- codecop/discover/loops.py +1671 -0
- codecop/discover/named_go.py +258 -0
- codecop/discover/origins.py +4565 -0
- codecop/discover/origins_ts.py +1584 -0
- codecop/discover/orm_django.py +2772 -0
- codecop/discover/orm_django_models.py +814 -0
- codecop/discover/orm_django_sql.py +662 -0
- codecop/discover/orm_ent.py +565 -0
- codecop/discover/orm_ex_ecto.py +2138 -0
- codecop/discover/orm_go.py +2134 -0
- codecop/discover/orm_go_bun.py +602 -0
- codecop/discover/orm_go_run.py +636 -0
- codecop/discover/orm_go_types.py +1082 -0
- codecop/discover/orm_java.py +1450 -0
- codecop/discover/orm_jdbi.py +743 -0
- codecop/discover/orm_jooq.py +806 -0
- codecop/discover/orm_jpa.py +1307 -0
- codecop/discover/orm_mybatis.py +730 -0
- codecop/discover/orm_py.py +557 -0
- codecop/discover/orm_py_peewee.py +1266 -0
- codecop/discover/orm_py_prisma.py +298 -0
- codecop/discover/orm_rb_activerecord.py +1906 -0
- codecop/discover/orm_rust.py +1248 -0
- codecop/discover/orm_rust_seaorm.py +734 -0
- codecop/discover/orm_sqlalchemy.py +2475 -0
- codecop/discover/orm_stats.py +307 -0
- codecop/discover/orm_tables.py +29 -0
- codecop/discover/orm_ts.py +503 -0
- codecop/discover/orm_ts_drizzle.py +697 -0
- codecop/discover/orm_ts_knex.py +1117 -0
- codecop/discover/orm_ts_kysely.py +861 -0
- codecop/discover/orm_ts_prisma.py +1045 -0
- codecop/discover/orm_ts_schema.py +169 -0
- codecop/discover/orm_ts_sequelize.py +1401 -0
- codecop/discover/orm_ts_typeorm.py +1067 -0
- codecop/discover/probes.py +323 -0
- codecop/discover/python.py +595 -0
- codecop/discover/ruby.py +793 -0
- codecop/discover/rust.py +2378 -0
- codecop/discover/schema.py +520 -0
- codecop/discover/schema_ent.py +145 -0
- codecop/discover/schema_ts.py +420 -0
- codecop/discover/tsresolve.py +257 -0
- codecop/discover/typescript.py +1728 -0
- codecop/discover/xml_mapper.py +526 -0
- codecop/engines/__init__.py +515 -0
- codecop/engines/base.py +498 -0
- codecop/engines/clickhouse.py +1558 -0
- codecop/engines/pg_ddl.py +444 -0
- codecop/engines/pg_hints.py +137 -0
- codecop/engines/postgres.py +1060 -0
- codecop/engines/sqlite.py +742 -0
- codecop/families/__init__.py +3 -0
- codecop/families/build.py +280 -0
- codecop/families/cli.py +177 -0
- codecop/families/coverage_hook.py +62 -0
- codecop/families/driver.py +221 -0
- codecop/families/goslice.py +229 -0
- codecop/families/goslice_tool/go.mod +3 -0
- codecop/families/goslice_tool/main.go +403 -0
- codecop/families/holes.py +451 -0
- codecop/families/images/Dockerfile.go +5 -0
- codecop/families/images/Dockerfile.python +4 -0
- codecop/families/images/Dockerfile.rust +4 -0
- codecop/families/isolate.py +171 -0
- codecop/families/locate.py +270 -0
- codecop/families/model.py +301 -0
- codecop/families/plangate.py +271 -0
- codecop/families/tagpatch.py +174 -0
- codecop/fidelity.py +671 -0
- codecop/fixgroups.py +130 -0
- codecop/formerly.py +91 -0
- codecop/grantscript.py +254 -0
- codecop/groupbench.py +1375 -0
- codecop/groups.py +594 -0
- codecop/groups_view.py +186 -0
- codecop/heat.py +1405 -0
- codecop/heatcli.py +219 -0
- codecop/joins.py +1749 -0
- codecop/joins_view.py +127 -0
- codecop/kinds/__init__.py +507 -0
- codecop/kinds/calls/__init__.py +501 -0
- codecop/kinds/calls/extract.py +1097 -0
- codecop/kinds/calls/harness.py +408 -0
- codecop/kinds/calls/measure.py +342 -0
- codecop/kinds/calls/rules.py +139 -0
- codecop/kinds/calls/runners/RunCalls.java +167 -0
- codecop/kinds/calls/runners/run_go.go +141 -0
- codecop/kinds/calls/runners/run_node.js +186 -0
- codecop/kinds/calls/runners/run_python.py +319 -0
- codecop/kinds/calls/runners/run_rust.rs +200 -0
- codecop/kinds/calls/standin.py +340 -0
- codecop/kinds/pipeline.py +288 -0
- codecop/kinds/regex/__init__.py +1167 -0
- codecop/kinds/regex/engines/RegexHarness.java +129 -0
- codecop/kinds/regex/engines/run_go.go +294 -0
- codecop/kinds/regex/engines/run_node.js +99 -0
- codecop/kinds/regex/engines/run_python.py +295 -0
- codecop/kinds/regex/engines/run_rust.rs +149 -0
- codecop/kinds/regex/extract.py +1438 -0
- codecop/kinds/regex/harness.py +235 -0
- codecop/kinds/regex/measure.py +270 -0
- codecop/kinds/regex/shapes.py +418 -0
- codecop/kinds/regex/syntax.py +1721 -0
- codecop/kinds/testkind.py +107 -0
- codecop/kinds/transaction/__init__.py +228 -0
- codecop/kinds/transaction/bind.py +355 -0
- codecop/kinds/transaction/measure.py +264 -0
- codecop/kinds/transaction/plan.py +462 -0
- codecop/kinds/transaction/rules.py +540 -0
- codecop/kinds/transaction/sandbox.py +94 -0
- codecop/kinds/transaction/scenarios.py +520 -0
- codecop/kinds/transaction/schedule.py +483 -0
- codecop/kinds/transaction/shapes.py +418 -0
- codecop/kinds/transaction/verify.py +293 -0
- codecop/live.py +237 -0
- codecop/loopbench.py +2071 -0
- codecop/loopschema.py +591 -0
- codecop/mcpserver.py +120 -0
- codecop/mechanism.py +214 -0
- codecop/members.py +200 -0
- codecop/multi.py +443 -0
- codecop/observed.py +1868 -0
- codecop/parts.py +102 -0
- codecop/patterns.py +830 -0
- codecop/patterns_view.py +559 -0
- codecop/plangate.py +242 -0
- codecop/profile.py +439 -0
- codecop/prompts/areas.md +19 -0
- codecop/prompts/observed_variants.md +20 -0
- codecop/prompts/profile.md +60 -0
- codecop/prompts/profile_postgres.md +68 -0
- codecop/prompts/profile_sizes.md +26 -0
- codecop/prompts/profile_sqlite.md +69 -0
- codecop/prompts/rank.md +84 -0
- codecop/prompts/rank_postgres.md +96 -0
- codecop/prompts/rank_sqlite.md +94 -0
- codecop/prompts/scenario_variants.md +20 -0
- codecop/rank.py +1473 -0
- codecop/realdb/__init__.py +688 -0
- codecop/realdb/clickhouse.py +1223 -0
- codecop/realdb/facts.py +815 -0
- codecop/realdb/locality.py +964 -0
- codecop/realdb/locks.py +355 -0
- codecop/realdb/match.py +531 -0
- codecop/realdb/postgres.py +643 -0
- codecop/realdb/ratios.py +77 -0
- codecop/realdb/sample.py +126 -0
- codecop/relations.py +227 -0
- codecop/report.py +1854 -0
- codecop/resources.py +332 -0
- codecop/resources_view.py +266 -0
- codecop/rules/entry_points.toml +1013 -0
- codecop/rules/sinks.toml +362 -0
- codecop/runsonce.py +8 -0
- codecop/sandboxschema.py +555 -0
- codecop/scenario_agent.py +172 -0
- codecop/scenario_bind.py +507 -0
- codecop/scenario_sql.py +971 -0
- codecop/scenarios.py +675 -0
- codecop/scenarios_view.py +274 -0
- codecop/schemacli.py +67 -0
- codecop/schemas/areas_output.schema.json +21 -0
- codecop/schemas/profile_output.schema.json +362 -0
- codecop/schemas/rank_output.schema.json +385 -0
- codecop/sizes.py +200 -0
- codecop/sqlinfo.py +558 -0
- codecop/typedparams.py +576 -0
- codecop/verdicts.py +212 -0
- codecop/writebench.py +720 -0
- codecop/writecost.py +440 -0
- codecop/writes.py +1208 -0
- codecop-0.1.0.dist-info/METADATA +42 -0
- codecop-0.1.0.dist-info/RECORD +222 -0
- codecop-0.1.0.dist-info/WHEEL +4 -0
- codecop-0.1.0.dist-info/entry_points.txt +2 -0
- codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
"""Table definitions that TypeScript projects keep outside SQL: Prisma schema files, Drizzle tables
|
|
2
|
+
and TypeORM entities.
|
|
3
|
+
|
|
4
|
+
CREATE TABLE statements (SQL migrations, ClickHouse DDL inside .ts migration files) are already found
|
|
5
|
+
by `schema.find_tables`, which scans raw text. This module adds the declarative sources. Each table
|
|
6
|
+
carries `indexes` ([{name, columns, unique}]) next to the fields every table has.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from .base import read_text
|
|
16
|
+
|
|
17
|
+
from .base import READ # the run's size setting: a file over it is listed as skipped, never dropped silently
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def read_bytes(path: Path) -> bytes | None:
|
|
21
|
+
try:
|
|
22
|
+
if READ.too_large(path, path.stat().st_size):
|
|
23
|
+
return None
|
|
24
|
+
return path.read_bytes()
|
|
25
|
+
except OSError:
|
|
26
|
+
return None
|
|
27
|
+
from .schema import Table
|
|
28
|
+
|
|
29
|
+
PRISMA_SCALARS = {"String", "Int", "BigInt", "Float", "Decimal", "Boolean", "DateTime", "Json", "Bytes"}
|
|
30
|
+
SOURCE_EXTS = (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class TsTable(Table):
|
|
35
|
+
indexes: list[dict] = field(default_factory=list)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _line(text: str, pos: int) -> int:
|
|
39
|
+
return text.count("\n", 0, pos) + 1
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _balanced(text: str, start: int, open_: str = "(", close: str = ")") -> int:
|
|
43
|
+
"""Index just past the bracket that closes the one at `start`, skipping strings and comments. -1 when unbalanced."""
|
|
44
|
+
depth, i, n = 0, start, len(text)
|
|
45
|
+
while i < n:
|
|
46
|
+
c = text[i]
|
|
47
|
+
if c in "'\"`":
|
|
48
|
+
j = i + 1
|
|
49
|
+
while j < n and text[j] != c:
|
|
50
|
+
j += 2 if text[j] == "\\" else 1
|
|
51
|
+
i = j
|
|
52
|
+
elif c == "/" and text.startswith("//", i):
|
|
53
|
+
j = text.find("\n", i)
|
|
54
|
+
i = n if j < 0 else j
|
|
55
|
+
elif c == "/" and text.startswith("/*", i):
|
|
56
|
+
j = text.find("*/", i)
|
|
57
|
+
i = n if j < 0 else j + 1
|
|
58
|
+
elif c == open_:
|
|
59
|
+
depth += 1
|
|
60
|
+
elif c == close:
|
|
61
|
+
depth -= 1
|
|
62
|
+
if depth == 0:
|
|
63
|
+
return i + 1
|
|
64
|
+
i += 1
|
|
65
|
+
return -1
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _split_top(text: str) -> list[str]:
|
|
69
|
+
"""Split on commas that are not inside brackets or strings."""
|
|
70
|
+
parts, depth, cur, i, n = [], 0, [], 0, len(text)
|
|
71
|
+
while i < n:
|
|
72
|
+
c = text[i]
|
|
73
|
+
if c in "'\"`":
|
|
74
|
+
j = i + 1
|
|
75
|
+
while j < n and text[j] != c:
|
|
76
|
+
j += 2 if text[j] == "\\" else 1
|
|
77
|
+
cur.append(text[i: j + 1])
|
|
78
|
+
i = j + 1
|
|
79
|
+
continue
|
|
80
|
+
if c in "([{":
|
|
81
|
+
depth += 1
|
|
82
|
+
elif c in ")]}":
|
|
83
|
+
depth -= 1
|
|
84
|
+
if c == "," and depth == 0:
|
|
85
|
+
parts.append("".join(cur))
|
|
86
|
+
cur = []
|
|
87
|
+
else:
|
|
88
|
+
cur.append(c)
|
|
89
|
+
i += 1
|
|
90
|
+
if "".join(cur).strip():
|
|
91
|
+
parts.append("".join(cur))
|
|
92
|
+
return parts
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
# --------------------------------------------------------------------------------------- Prisma
|
|
96
|
+
|
|
97
|
+
_PRISMA_BLOCK = re.compile(r"(?m)^[ \t]*(model|enum|type|view)\s+(\w+)\s*\{")
|
|
98
|
+
_PRISMA_FIELD = re.compile(r"^\s*(\w+)\s+(Unsupported\(\"[^\"]*\"\)|\w+)(\[\])?(\?)?(.*)$")
|
|
99
|
+
_PRISMA_LIST = re.compile(r"\[([^\]]*)\]")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _prisma_columns(arg: str, colmap: dict[str, str]) -> list[str]:
|
|
103
|
+
m = _PRISMA_LIST.search(arg)
|
|
104
|
+
if not m:
|
|
105
|
+
return []
|
|
106
|
+
out = []
|
|
107
|
+
for part in _split_top(m.group(1)):
|
|
108
|
+
name = re.match(r"\s*(\w+)", part)
|
|
109
|
+
if name:
|
|
110
|
+
out.append(colmap.get(name.group(1), name.group(1)))
|
|
111
|
+
return out
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def prisma_tables(files: dict[str, str]) -> list[TsTable]:
|
|
115
|
+
"""Models of one Prisma schema (possibly several files) as tables: @@map / @map names, @@index, @@unique, @@id."""
|
|
116
|
+
blocks: list[tuple[str, str, str, int, str]] = [] # (kind, name, file, line, body)
|
|
117
|
+
for rel, text in files.items():
|
|
118
|
+
for m in _PRISMA_BLOCK.finditer(text):
|
|
119
|
+
end = text.find("\n}", m.end())
|
|
120
|
+
if end < 0:
|
|
121
|
+
continue
|
|
122
|
+
blocks.append((m.group(1), m.group(2), rel, _line(text, m.start()), text[m.end(): end]))
|
|
123
|
+
enums = {name for kind, name, *_ in blocks if kind == "enum"}
|
|
124
|
+
composites = {name for kind, name, *_ in blocks if kind == "type"}
|
|
125
|
+
out: list[TsTable] = []
|
|
126
|
+
for kind, name, rel, line, body in blocks:
|
|
127
|
+
if kind != "model":
|
|
128
|
+
continue
|
|
129
|
+
table = TsTable(name=name, defined_at=[f"{rel}:{line}"])
|
|
130
|
+
colmap: dict[str, str] = {}
|
|
131
|
+
attrs: list[str] = []
|
|
132
|
+
pk: list[str] = []
|
|
133
|
+
for raw in body.split("\n"):
|
|
134
|
+
text = raw.split("//")[0].strip()
|
|
135
|
+
if not text:
|
|
136
|
+
continue
|
|
137
|
+
if text.startswith("@@"):
|
|
138
|
+
attrs.append(text)
|
|
139
|
+
continue
|
|
140
|
+
m = _PRISMA_FIELD.match(text)
|
|
141
|
+
if not m:
|
|
142
|
+
continue
|
|
143
|
+
fname, ftype, is_list, optional, rest = m.groups()
|
|
144
|
+
base = ftype.split("(")[0]
|
|
145
|
+
if base not in PRISMA_SCALARS and base not in enums and base != "Unsupported" and base not in composites:
|
|
146
|
+
continue # a relation field: no column of its own
|
|
147
|
+
mapped = re.search(r"@map\(\s*\"([^\"]+)\"", rest)
|
|
148
|
+
column = mapped.group(1) if mapped else fname
|
|
149
|
+
colmap[fname] = column
|
|
150
|
+
native = re.search(r"@db\.(\w+(?:\([^)]*\))?)", rest)
|
|
151
|
+
ctype = (native.group(1) if native else ftype) + ("[]" if is_list else "") + ("" if optional or is_list else " NOT NULL")
|
|
152
|
+
table.columns.append({"name": column, "type": ctype})
|
|
153
|
+
if re.search(r"@id\b", rest):
|
|
154
|
+
pk.append(column)
|
|
155
|
+
if re.search(r"@unique\b", rest):
|
|
156
|
+
table.indexes.append({"name": "", "columns": [column], "unique": True})
|
|
157
|
+
schema = ""
|
|
158
|
+
for a in attrs:
|
|
159
|
+
head, _, arg = a.partition("(")
|
|
160
|
+
if head == "@@map":
|
|
161
|
+
mm = re.search(r"\"([^\"]+)\"", arg)
|
|
162
|
+
if mm:
|
|
163
|
+
table.name = mm.group(1)
|
|
164
|
+
elif head == "@@schema":
|
|
165
|
+
mm = re.search(r"\"([^\"]+)\"", arg)
|
|
166
|
+
schema = mm.group(1) if mm else ""
|
|
167
|
+
elif head in ("@@index", "@@unique", "@@fulltext"):
|
|
168
|
+
cols = _prisma_columns(arg, colmap)
|
|
169
|
+
named = re.search(r"\b(?:map|name)\s*:\s*\"([^\"]+)\"", arg)
|
|
170
|
+
if cols:
|
|
171
|
+
table.indexes.append({"name": named.group(1) if named else "", "columns": cols, "unique": head == "@@unique"})
|
|
172
|
+
elif head == "@@id":
|
|
173
|
+
pk = _prisma_columns(arg, colmap)
|
|
174
|
+
table.primary_key = ", ".join(pk)
|
|
175
|
+
if schema and schema != "public":
|
|
176
|
+
table.name = f"{schema}.{table.name}"
|
|
177
|
+
if table.columns:
|
|
178
|
+
out.append(table)
|
|
179
|
+
return out
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
# --------------------------------------------------------------------------------------- Drizzle
|
|
183
|
+
|
|
184
|
+
_DRIZZLE_TABLE = re.compile(
|
|
185
|
+
r"\b(?:pgTable|mysqlTable|sqliteTable|singlestoreTable|\w+[sS]chema\.table|table)\s*\(\s*(['\"`])([\w.$-]+)\1\s*,\s*(?=\{)")
|
|
186
|
+
_DRIZZLE_COLUMN = re.compile(r"^\s*(?:['\"]?)([\w$]+)(?:['\"]?)\s*:\s*([\w.$]+)\s*(?:<[^>]*>)?\(\s*(?:(['\"`])([^'\"`]*)\3)?")
|
|
187
|
+
_DRIZZLE_INDEX = re.compile(
|
|
188
|
+
r"\b(uniqueIndex|index|unique|primaryKey)\s*\(\s*(?:(['\"`])([^'\"`]*)\2)?[^)]*\)\s*(?:\.using\([^)]*\)\s*)?\.on\s*\(")
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def drizzle_tables(rel: str, text: str) -> list[TsTable]:
|
|
192
|
+
"""`pgTable("name", { col: type("db_name") ... }, (t) => [index("i").on(t.col)])`."""
|
|
193
|
+
out: list[TsTable] = []
|
|
194
|
+
if "Table(" not in text and ".table(" not in text:
|
|
195
|
+
return out
|
|
196
|
+
for m in _DRIZZLE_TABLE.finditer(text):
|
|
197
|
+
end = _balanced(text, m.end(), "{", "}")
|
|
198
|
+
if end < 0:
|
|
199
|
+
continue
|
|
200
|
+
table = TsTable(name=m.group(2), defined_at=[f"{rel}:{_line(text, m.start())}"])
|
|
201
|
+
keymap: dict[str, str] = {}
|
|
202
|
+
pk: list[str] = []
|
|
203
|
+
for part in _split_top(text[m.end() + 1: end - 1]):
|
|
204
|
+
part = re.sub(r"^(?:\s*(?://[^\n]*|/\*.*?\*/))+", "", part, flags=re.S)
|
|
205
|
+
cm = _DRIZZLE_COLUMN.match(part)
|
|
206
|
+
if not cm:
|
|
207
|
+
continue
|
|
208
|
+
key, ctype, _, db_name = cm.groups()
|
|
209
|
+
column = db_name if db_name and re.fullmatch(r"[\w$]+", db_name) else key
|
|
210
|
+
keymap[key] = column
|
|
211
|
+
table.columns.append({"name": column, "type": ctype.split(".")[-1]})
|
|
212
|
+
if ".primaryKey(" in part:
|
|
213
|
+
pk.append(column)
|
|
214
|
+
if re.search(r"\.unique\(", part):
|
|
215
|
+
table.indexes.append({"name": "", "columns": [column], "unique": True})
|
|
216
|
+
if not table.columns:
|
|
217
|
+
continue
|
|
218
|
+
# the optional third argument: indexes and constraints
|
|
219
|
+
call_end = _balanced(text, text.find("(", m.start()), "(", ")")
|
|
220
|
+
tail = text[end: call_end] if call_end > end else ""
|
|
221
|
+
for im in _DRIZZLE_INDEX.finditer(tail):
|
|
222
|
+
close = _balanced(tail, im.end() - 1, "(", ")")
|
|
223
|
+
if close < 0:
|
|
224
|
+
continue
|
|
225
|
+
cols = [keymap.get(c, c) for c in re.findall(r"\b\w+\.([\w$]+)", tail[im.end(): close - 1])]
|
|
226
|
+
if not cols:
|
|
227
|
+
continue
|
|
228
|
+
if im.group(1) == "primaryKey":
|
|
229
|
+
pk = cols
|
|
230
|
+
else:
|
|
231
|
+
table.indexes.append({"name": im.group(3) or "", "columns": cols, "unique": im.group(1) in ("uniqueIndex", "unique")})
|
|
232
|
+
pkm = re.search(r"\bprimaryKey\s*\(\s*\{[^}]*columns\s*:\s*\[([^\]]*)\]", tail)
|
|
233
|
+
if pkm:
|
|
234
|
+
pk = [keymap.get(c, c) for c in re.findall(r"\b\w+\.([\w$]+)", pkm.group(1))]
|
|
235
|
+
table.primary_key = ", ".join(pk)
|
|
236
|
+
out.append(table)
|
|
237
|
+
return out
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
# --------------------------------------------------------------------------------------- TypeORM
|
|
241
|
+
|
|
242
|
+
_COLUMN_DECORATORS = {"Column", "PrimaryColumn", "PrimaryGeneratedColumn", "CreateDateColumn", "UpdateDateColumn",
|
|
243
|
+
"DeleteDateColumn", "VersionColumn", "ObjectIdColumn", "Generated"}
|
|
244
|
+
_PRIMARY_DECORATORS = {"PrimaryColumn", "PrimaryGeneratedColumn", "ObjectIdColumn"}
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _snake(name: str) -> str:
|
|
248
|
+
return re.sub(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", "_", name).lower()
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def typeorm_tables(rel: str, text: str) -> list[TsTable]:
|
|
252
|
+
"""`@Entity("name") class X { @Column({ name: "db_name" }) prop: string }` with @Index and @Unique."""
|
|
253
|
+
if "@Entity(" not in text:
|
|
254
|
+
return []
|
|
255
|
+
from tree_sitter import Parser
|
|
256
|
+
|
|
257
|
+
from .typescript import _txt, _unwrap, call_args, decode_string, language_for, object_pairs
|
|
258
|
+
|
|
259
|
+
def dec_parts(dec) -> tuple[str, list, dict]:
|
|
260
|
+
inner = dec.named_children[0] if dec.named_children else None
|
|
261
|
+
if inner is None:
|
|
262
|
+
return "", [], {}
|
|
263
|
+
if inner.type != "call_expression":
|
|
264
|
+
return _txt(inner), [], {}
|
|
265
|
+
args = [_unwrap(a) for a in call_args(inner)]
|
|
266
|
+
kw: dict = {}
|
|
267
|
+
for a in args:
|
|
268
|
+
if a is not None and a.type == "object":
|
|
269
|
+
kw.update(object_pairs(a))
|
|
270
|
+
return _txt(inner.child_by_field_name("function")), args, kw
|
|
271
|
+
|
|
272
|
+
def text_of(node) -> str:
|
|
273
|
+
node = _unwrap(node)
|
|
274
|
+
if node is None:
|
|
275
|
+
return ""
|
|
276
|
+
return decode_string(node) if node.type in ("string", "template_string") else ""
|
|
277
|
+
|
|
278
|
+
def decorators(node) -> list:
|
|
279
|
+
out = [c for c in node.children if c.type == "decorator"]
|
|
280
|
+
prev = node.prev_named_sibling
|
|
281
|
+
while prev is not None and prev.type in ("decorator", "comment"):
|
|
282
|
+
if prev.type == "decorator":
|
|
283
|
+
out.append(prev)
|
|
284
|
+
prev = prev.prev_named_sibling
|
|
285
|
+
return out
|
|
286
|
+
|
|
287
|
+
src = text.encode("utf-8")
|
|
288
|
+
tree = Parser(language_for(rel)).parse(src)
|
|
289
|
+
out: list[TsTable] = []
|
|
290
|
+
stack = [tree.root_node]
|
|
291
|
+
while stack:
|
|
292
|
+
node = stack.pop()
|
|
293
|
+
if node.type not in ("class_declaration", "abstract_class_declaration"):
|
|
294
|
+
if node.type in ("program", "export_statement", "statement_block"):
|
|
295
|
+
stack.extend(node.children)
|
|
296
|
+
continue
|
|
297
|
+
decs = [c for c in node.children if c.type == "decorator"]
|
|
298
|
+
if node.parent is not None and node.parent.type == "export_statement":
|
|
299
|
+
decs += [c for c in node.parent.children if c.type == "decorator"]
|
|
300
|
+
entity = None
|
|
301
|
+
class_indexes: list[tuple[str, list, dict]] = []
|
|
302
|
+
for d in decs:
|
|
303
|
+
name, args, kw = dec_parts(d)
|
|
304
|
+
if name == "Entity":
|
|
305
|
+
entity = (args, kw)
|
|
306
|
+
elif name in ("Index", "Unique"):
|
|
307
|
+
class_indexes.append((name, args, kw))
|
|
308
|
+
if entity is None:
|
|
309
|
+
continue
|
|
310
|
+
args, kw = entity
|
|
311
|
+
cls = _txt(node.child_by_field_name("name"))
|
|
312
|
+
tname = text_of(args[0]) if args and args[0] is not None and args[0].type in ("string", "template_string") else text_of(kw.get("name"))
|
|
313
|
+
table = TsTable(name=tname or _snake(cls), defined_at=[f"{rel}:{node.start_point[0] + 1}"],
|
|
314
|
+
name_basis="sql" if tname else "constant")
|
|
315
|
+
propmap: dict[str, str] = {}
|
|
316
|
+
pk: list[str] = []
|
|
317
|
+
body = node.child_by_field_name("body")
|
|
318
|
+
for member in (body.named_children if body is not None else ()):
|
|
319
|
+
if member.type != "public_field_definition":
|
|
320
|
+
continue
|
|
321
|
+
prop = _txt(member.child_by_field_name("name"))
|
|
322
|
+
column, ctype, is_column, field_indexes = prop, "", False, []
|
|
323
|
+
for d in decorators(member):
|
|
324
|
+
name, dargs, dkw = dec_parts(d)
|
|
325
|
+
if name in _COLUMN_DECORATORS:
|
|
326
|
+
is_column = True
|
|
327
|
+
column = text_of(dkw.get("name")) or column
|
|
328
|
+
ctype = text_of(dkw.get("type")) or (text_of(dargs[0]) if dargs and dargs[0] is not None else "") or ctype
|
|
329
|
+
if name in _PRIMARY_DECORATORS or _txt(dkw.get("primary")) == "true":
|
|
330
|
+
pk.append(prop)
|
|
331
|
+
elif name in ("Index", "Unique"):
|
|
332
|
+
field_indexes.append((name, dargs, dkw))
|
|
333
|
+
if not is_column:
|
|
334
|
+
continue
|
|
335
|
+
if not ctype:
|
|
336
|
+
typ = member.child_by_field_name("type")
|
|
337
|
+
ctype = _txt(typ).lstrip(": ").strip() if typ is not None else ""
|
|
338
|
+
propmap[prop] = column
|
|
339
|
+
table.columns.append({"name": column, "type": ctype[:60]})
|
|
340
|
+
for name, dargs, dkw in field_indexes:
|
|
341
|
+
iname = text_of(dargs[0]) if dargs and dargs[0] is not None else ""
|
|
342
|
+
table.indexes.append({"name": iname, "columns": [column],
|
|
343
|
+
"unique": name == "Unique" or _txt(dkw.get("unique")) == "true"})
|
|
344
|
+
for name, dargs, dkw in class_indexes:
|
|
345
|
+
iname, cols = "", []
|
|
346
|
+
for a in dargs:
|
|
347
|
+
if a is None:
|
|
348
|
+
continue
|
|
349
|
+
if a.type in ("string", "template_string") and not iname:
|
|
350
|
+
iname = text_of(a)
|
|
351
|
+
elif a.type == "array":
|
|
352
|
+
cols = [propmap.get(text_of(e), text_of(e)) for e in a.named_children if text_of(e)]
|
|
353
|
+
if cols:
|
|
354
|
+
table.indexes.append({"name": iname, "columns": cols, "unique": name == "Unique" or _txt(dkw.get("unique")) == "true"})
|
|
355
|
+
table.primary_key = ", ".join(propmap.get(p, p) for p in pk)
|
|
356
|
+
if table.columns:
|
|
357
|
+
out.append(table)
|
|
358
|
+
return out
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
# --------------------------------------------------------------------------------------- driver
|
|
362
|
+
|
|
363
|
+
def find_tables(root: Path, files: list[str]) -> list[TsTable]:
|
|
364
|
+
out: list[TsTable] = []
|
|
365
|
+
# Prisma: the .prisma files of one directory tree form one schema (multi-file schemas)
|
|
366
|
+
groups: dict[str, dict[str, str]] = {}
|
|
367
|
+
for f in files:
|
|
368
|
+
if not f.endswith(".prisma"):
|
|
369
|
+
continue
|
|
370
|
+
text = read_text(root / f)
|
|
371
|
+
if text is None:
|
|
372
|
+
continue
|
|
373
|
+
d = f.rpartition("/")[0]
|
|
374
|
+
home = next((g for g in groups if d == g or d.startswith(g + "/") or g.startswith(d + "/") or (not g and not d)), None)
|
|
375
|
+
groups.setdefault(home if home is not None else d, {})[f] = text
|
|
376
|
+
for schema_files in groups.values():
|
|
377
|
+
try:
|
|
378
|
+
out.extend(prisma_tables(schema_files))
|
|
379
|
+
except Exception: # one odd schema must not stop the inventory
|
|
380
|
+
continue
|
|
381
|
+
from .orm_ts_schema import KyselySchema
|
|
382
|
+
kysely = KyselySchema()
|
|
383
|
+
from . import orm_ts_knex, orm_ts_sequelize
|
|
384
|
+
sequelize = orm_ts_sequelize.Library(None, root, files, None) # Sequelize models: classes, init(), define()
|
|
385
|
+
knex = orm_ts_knex.KnexSchema() # knex.schema.createTable(...) migrations
|
|
386
|
+
for f in files:
|
|
387
|
+
if not f.endswith(SOURCE_EXTS) or f.endswith(".d.ts"):
|
|
388
|
+
continue
|
|
389
|
+
head = read_bytes(root / f) # the existing size setting applies
|
|
390
|
+
if head is None:
|
|
391
|
+
continue
|
|
392
|
+
drizzle = b"drizzle-orm" in head and b"Table(" in head
|
|
393
|
+
typeorm = b"@Entity(" in head
|
|
394
|
+
if kysely.wants(head): # Kysely migrations: db.schema.createTable(...) (orm_ts_schema.py)
|
|
395
|
+
try:
|
|
396
|
+
kysely.add(f, head)
|
|
397
|
+
except Exception:
|
|
398
|
+
pass
|
|
399
|
+
if b"sequelize" in head:
|
|
400
|
+
try:
|
|
401
|
+
sequelize.wants(f, head, frozenset())
|
|
402
|
+
except Exception:
|
|
403
|
+
pass
|
|
404
|
+
if knex.wants(head):
|
|
405
|
+
try:
|
|
406
|
+
knex.add(f, head)
|
|
407
|
+
except Exception:
|
|
408
|
+
pass
|
|
409
|
+
if not drizzle and not typeorm:
|
|
410
|
+
continue
|
|
411
|
+
text = head.decode("utf-8", "replace")
|
|
412
|
+
try:
|
|
413
|
+
if drizzle:
|
|
414
|
+
out.extend(drizzle_tables(f, text))
|
|
415
|
+
if typeorm:
|
|
416
|
+
out.extend(typeorm_tables(f, text))
|
|
417
|
+
except Exception:
|
|
418
|
+
continue
|
|
419
|
+
sequelize.prepare({})
|
|
420
|
+
return out + kysely.tables() + sequelize.tables() + knex.tables()
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""TypeScript / JavaScript module resolution, shared by the call-site extractor and the call graph.
|
|
2
|
+
|
|
3
|
+
Turns an import specifier into a file of the repo: relative paths, `tsconfig.json`
|
|
4
|
+
`paths` and `baseUrl`, and workspace packages (`@acme/shared`, found through the
|
|
5
|
+
`package.json` files of the repo). Nothing outside the repo is resolved, and nothing
|
|
6
|
+
is executed: `package.json` and `tsconfig.json` are read as data.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
EXTS = (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts")
|
|
17
|
+
SOURCE_EXTS = frozenset(EXTS)
|
|
18
|
+
TS_ONLY = (".ts", ".mts", ".cts")
|
|
19
|
+
# `import x from "./a.js"` in a TypeScript ESM project names the compiled file: the source is a.ts
|
|
20
|
+
JS_TO_TS = {".js": (".ts", ".tsx"), ".mjs": (".mts",), ".cjs": (".cts",), ".jsx": (".tsx",)}
|
|
21
|
+
BUILD_DIRS = ("dist", "build", "lib", "out", "esm", "cjs")
|
|
22
|
+
CONFIG_READ_LIMIT = 400_000 # a package.json or tsconfig.json larger than this is not a hand-written one
|
|
23
|
+
|
|
24
|
+
_COMMENT = re.compile(r'("(?:[^"\\]|\\.)*")|//[^\n]*|/\*.*?\*/', re.S)
|
|
25
|
+
_TRAILING_COMMA = re.compile(r",(\s*[}\]])")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def load_json(path: Path) -> dict:
|
|
29
|
+
"""JSON with comments and trailing commas (tsconfig). {} when unreadable."""
|
|
30
|
+
try:
|
|
31
|
+
if path.stat().st_size > CONFIG_READ_LIMIT:
|
|
32
|
+
return {}
|
|
33
|
+
text = path.read_text(encoding="utf-8", errors="replace")
|
|
34
|
+
except OSError:
|
|
35
|
+
return {}
|
|
36
|
+
try:
|
|
37
|
+
data = json.loads(text)
|
|
38
|
+
except ValueError:
|
|
39
|
+
try:
|
|
40
|
+
data = json.loads(_TRAILING_COMMA.sub(r"\1", _COMMENT.sub(lambda m: m.group(1) or "", text)))
|
|
41
|
+
except ValueError:
|
|
42
|
+
return {}
|
|
43
|
+
return data if isinstance(data, dict) else {}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _norm(path: str) -> str:
|
|
47
|
+
out = os.path.normpath(path).replace(os.sep, "/")
|
|
48
|
+
return "" if out == "." else out
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Resolver:
|
|
52
|
+
def __init__(self, root: Path, files: list[str]):
|
|
53
|
+
self.root = root
|
|
54
|
+
self.files = set(files)
|
|
55
|
+
self.dirs: set[str] = {""}
|
|
56
|
+
for f in files:
|
|
57
|
+
d = os.path.dirname(f)
|
|
58
|
+
while d and d not in self.dirs:
|
|
59
|
+
self.dirs.add(d)
|
|
60
|
+
d = os.path.dirname(d)
|
|
61
|
+
self._cache: dict[tuple[str, str], str | None] = {}
|
|
62
|
+
self._tsconfig: dict[str, tuple[str, list[tuple[str, list[str]]]] | None] = {}
|
|
63
|
+
self._pkg_json: dict[str, dict | None] = {}
|
|
64
|
+
self.packages: dict[str, str] = {} # workspace package name -> directory
|
|
65
|
+
for d in sorted(self.dirs):
|
|
66
|
+
name = (self.package_json(d) or {}).get("name")
|
|
67
|
+
if isinstance(name, str) and name:
|
|
68
|
+
self.packages.setdefault(name, d)
|
|
69
|
+
|
|
70
|
+
# ---- configuration files --------------------------------------------------
|
|
71
|
+
def package_json(self, d: str) -> dict | None:
|
|
72
|
+
got = self._pkg_json.get(d, False)
|
|
73
|
+
if got is False:
|
|
74
|
+
p = self.root / d / "package.json"
|
|
75
|
+
got = load_json(p) if p.is_file() else None
|
|
76
|
+
self._pkg_json[d] = got or None
|
|
77
|
+
return got or None
|
|
78
|
+
|
|
79
|
+
def nearest_package(self, rel: str) -> tuple[str, dict] | None:
|
|
80
|
+
d = os.path.dirname(rel)
|
|
81
|
+
while True:
|
|
82
|
+
pkg = self.package_json(d)
|
|
83
|
+
if pkg is not None:
|
|
84
|
+
return d, pkg
|
|
85
|
+
if not d:
|
|
86
|
+
return None
|
|
87
|
+
d = os.path.dirname(d)
|
|
88
|
+
|
|
89
|
+
def _tsconfig_at(self, d: str, depth: int = 0) -> tuple[str, list[tuple[str, list[str]]]] | None:
|
|
90
|
+
"""(base directory, [(pattern, targets)]) of the tsconfig.json / jsconfig.json in `d`, following `extends`."""
|
|
91
|
+
if d in self._tsconfig:
|
|
92
|
+
return self._tsconfig[d]
|
|
93
|
+
self._tsconfig[d] = None
|
|
94
|
+
for name in ("tsconfig.json", "jsconfig.json"):
|
|
95
|
+
p = self.root / d / name
|
|
96
|
+
if not p.is_file():
|
|
97
|
+
continue
|
|
98
|
+
got = self._read_tsconfig(d, name, depth)
|
|
99
|
+
if got is not None:
|
|
100
|
+
self._tsconfig[d] = got
|
|
101
|
+
break
|
|
102
|
+
return self._tsconfig[d]
|
|
103
|
+
|
|
104
|
+
def _read_tsconfig(self, d: str, name: str, depth: int) -> tuple[str, list[tuple[str, list[str]]]] | None:
|
|
105
|
+
data = load_json(self.root / d / name)
|
|
106
|
+
opts = data.get("compilerOptions") if isinstance(data.get("compilerOptions"), dict) else {}
|
|
107
|
+
base = opts.get("baseUrl")
|
|
108
|
+
paths = opts.get("paths") if isinstance(opts.get("paths"), dict) else None
|
|
109
|
+
if paths is None and base is None:
|
|
110
|
+
ext = data.get("extends")
|
|
111
|
+
ext = ext[0] if isinstance(ext, list) and ext else ext
|
|
112
|
+
if isinstance(ext, str) and ext.startswith(".") and depth < 4:
|
|
113
|
+
target = _norm(os.path.join(d, ext))
|
|
114
|
+
if not target.endswith(".json"):
|
|
115
|
+
target += ".json"
|
|
116
|
+
if (self.root / target).is_file():
|
|
117
|
+
return self._read_tsconfig(os.path.dirname(target), os.path.basename(target), depth + 1)
|
|
118
|
+
return None
|
|
119
|
+
base_dir = _norm(os.path.join(d, base)) if isinstance(base, str) else d
|
|
120
|
+
rules: list[tuple[str, list[str]]] = []
|
|
121
|
+
for pattern, targets in (paths or {}).items():
|
|
122
|
+
if isinstance(pattern, str) and isinstance(targets, list):
|
|
123
|
+
rules.append((pattern, [t for t in targets if isinstance(t, str)]))
|
|
124
|
+
rules.sort(key=lambda r: -len(r[0].split("*")[0]))
|
|
125
|
+
if isinstance(base, str):
|
|
126
|
+
rules.append(("*", ["*"])) # baseUrl alone makes `import "lib/x"` resolve from it
|
|
127
|
+
return base_dir, rules
|
|
128
|
+
|
|
129
|
+
# ---- files ------------------------------------------------------------------
|
|
130
|
+
def as_file(self, path: str) -> str | None:
|
|
131
|
+
"""A path without (or with) an extension -> the source file it names."""
|
|
132
|
+
path = _norm(path)
|
|
133
|
+
if path.startswith(".."):
|
|
134
|
+
return None
|
|
135
|
+
if path in self.files:
|
|
136
|
+
return path
|
|
137
|
+
stem, ext = os.path.splitext(path)
|
|
138
|
+
for alt in JS_TO_TS.get(ext, ()):
|
|
139
|
+
if stem + alt in self.files:
|
|
140
|
+
return stem + alt
|
|
141
|
+
for e in EXTS:
|
|
142
|
+
if path + e in self.files:
|
|
143
|
+
return path + e
|
|
144
|
+
if path in self.dirs or path == "":
|
|
145
|
+
for e in EXTS:
|
|
146
|
+
cand = (path + "/" if path else "") + "index" + e
|
|
147
|
+
if cand in self.files:
|
|
148
|
+
return cand
|
|
149
|
+
return None
|
|
150
|
+
|
|
151
|
+
def _package_entry(self, d: str, sub: str) -> str | None:
|
|
152
|
+
pkg = self.package_json(d) or {}
|
|
153
|
+
if sub:
|
|
154
|
+
cands = [sub, "src/" + sub]
|
|
155
|
+
exports = pkg.get("exports")
|
|
156
|
+
if isinstance(exports, dict):
|
|
157
|
+
cands = self._export_targets(exports.get("./" + sub)) + cands
|
|
158
|
+
for key, value in exports.items(): # "./*": "./src/*.ts"
|
|
159
|
+
if isinstance(key, str) and key.endswith("/*") and ("./" + sub).startswith(key[:-1]):
|
|
160
|
+
rest = ("./" + sub)[len(key) - 1:]
|
|
161
|
+
cands = [t.replace("*", rest) for t in self._export_targets(value)] + cands
|
|
162
|
+
else:
|
|
163
|
+
cands = []
|
|
164
|
+
exports = pkg.get("exports")
|
|
165
|
+
if isinstance(exports, dict):
|
|
166
|
+
cands += self._export_targets(exports.get(".", exports))
|
|
167
|
+
elif isinstance(exports, str):
|
|
168
|
+
cands.append(exports)
|
|
169
|
+
cands += [pkg.get(k) for k in ("source", "types", "typings", "module", "main") if isinstance(pkg.get(k), str)]
|
|
170
|
+
cands += ["src/index", "index", "src/main", "lib/index"]
|
|
171
|
+
for c in cands:
|
|
172
|
+
c = c.lstrip("./")
|
|
173
|
+
for variant in self._source_variants(c):
|
|
174
|
+
hit = self.as_file((d + "/" if d else "") + variant)
|
|
175
|
+
if hit is not None:
|
|
176
|
+
return hit
|
|
177
|
+
return None
|
|
178
|
+
|
|
179
|
+
@staticmethod
|
|
180
|
+
def _export_targets(value) -> list[str]:
|
|
181
|
+
if isinstance(value, str):
|
|
182
|
+
return [value]
|
|
183
|
+
out: list[str] = []
|
|
184
|
+
if isinstance(value, dict):
|
|
185
|
+
for key in ("source", "types", "import", "default", "require", "node"):
|
|
186
|
+
out += Resolver._export_targets(value.get(key))
|
|
187
|
+
return out
|
|
188
|
+
|
|
189
|
+
@staticmethod
|
|
190
|
+
def _source_variants(path: str) -> list[str]:
|
|
191
|
+
"""`dist/index.js` is built from `src/index.ts`: try the path as written, then its source."""
|
|
192
|
+
stem = re.sub(r"\.d\.(ts|mts|cts)$", "", path)
|
|
193
|
+
stem = stem if stem != path else os.path.splitext(path)[0] if os.path.splitext(path)[1] in SOURCE_EXTS else path
|
|
194
|
+
out = [path, stem]
|
|
195
|
+
parts = stem.split("/")
|
|
196
|
+
if parts and parts[0] in BUILD_DIRS:
|
|
197
|
+
out += ["/".join(["src"] + parts[1:]), "/".join(parts[1:])]
|
|
198
|
+
if len(parts) > 2 and parts[1] in ("src", "esm", "cjs"):
|
|
199
|
+
out += ["/".join(["src"] + parts[2:])]
|
|
200
|
+
return [o for o in out if o]
|
|
201
|
+
|
|
202
|
+
def resolve(self, from_rel: str, spec: str) -> str | None:
|
|
203
|
+
"""The repo file that `import ... from spec` in `from_rel` names, or None for an outside module."""
|
|
204
|
+
key = (os.path.dirname(from_rel), spec)
|
|
205
|
+
if key in self._cache:
|
|
206
|
+
return self._cache[key]
|
|
207
|
+
got = self._resolve(key[0], spec)
|
|
208
|
+
self._cache[key] = got
|
|
209
|
+
return got
|
|
210
|
+
|
|
211
|
+
def _resolve(self, d: str, spec: str) -> str | None:
|
|
212
|
+
spec = spec.split("?")[0]
|
|
213
|
+
if not spec:
|
|
214
|
+
return None
|
|
215
|
+
if spec.startswith("."):
|
|
216
|
+
return self.as_file(os.path.join(d, spec))
|
|
217
|
+
if spec.startswith("/"):
|
|
218
|
+
return None
|
|
219
|
+
# tsconfig paths of the nearest config that has any
|
|
220
|
+
cur = d
|
|
221
|
+
while True:
|
|
222
|
+
cfg = self._tsconfig_at(cur)
|
|
223
|
+
if cfg is not None:
|
|
224
|
+
base_dir, rules = cfg
|
|
225
|
+
for pattern, targets in rules:
|
|
226
|
+
if "*" in pattern:
|
|
227
|
+
pre, _, post = pattern.partition("*")
|
|
228
|
+
if not (spec.startswith(pre) and spec.endswith(post) and len(spec) >= len(pre) + len(post)):
|
|
229
|
+
continue
|
|
230
|
+
star = spec[len(pre): len(spec) - len(post)] if post else spec[len(pre):]
|
|
231
|
+
elif pattern == spec:
|
|
232
|
+
star = ""
|
|
233
|
+
else:
|
|
234
|
+
continue
|
|
235
|
+
for t in targets:
|
|
236
|
+
hit = self.as_file(os.path.join(base_dir, t.replace("*", star)))
|
|
237
|
+
if hit is not None:
|
|
238
|
+
return hit
|
|
239
|
+
break
|
|
240
|
+
if not cur:
|
|
241
|
+
break
|
|
242
|
+
cur = os.path.dirname(cur)
|
|
243
|
+
# workspace packages: "@acme/shared", "@acme/shared/src/server"
|
|
244
|
+
parts = spec.split("/")
|
|
245
|
+
name = "/".join(parts[:2]) if spec.startswith("@") else parts[0]
|
|
246
|
+
pkg_dir = self.packages.get(name)
|
|
247
|
+
if pkg_dir is not None:
|
|
248
|
+
return self._package_entry(pkg_dir, "/".join(parts[2:] if spec.startswith("@") else parts[1:]))
|
|
249
|
+
# "~/x" and "@/x" without a tsconfig entry: the conventional source roots of the package
|
|
250
|
+
if spec.startswith(("~/", "@/")):
|
|
251
|
+
near = self.nearest_package(d + "/x")
|
|
252
|
+
base = near[0] if near else ""
|
|
253
|
+
for sub in ("src", "", "app"):
|
|
254
|
+
hit = self.as_file(os.path.join(base, sub, spec[2:]))
|
|
255
|
+
if hit is not None:
|
|
256
|
+
return hit
|
|
257
|
+
return None
|