Skip to content

Commit 5610f65

Browse files
committed
JS: Add PackageJson.getTypingsModule
1 parent a3204f6 commit 5610f65

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

javascript/ql/lib/semmle/javascript/NPM.qll

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,35 @@ class PackageJson extends JsonObject {
180180
Module getMainModule() {
181181
result = min(Module m, int prio | m.getFile() = resolveMainModule(this, prio) | m order by prio)
182182
}
183+
184+
/**
185+
* Gets the `types` or `typings` field of this package.
186+
*/
187+
string getTypings() { result = this.getPropStringValue(["types", "typings"]) }
188+
189+
/**
190+
* Gets the file containing the typings of this package, which can either be from the `types` or
191+
* `typings` field, or derived from the `main` or `module` fields.
192+
*/
193+
File getTypingsFile() {
194+
result =
195+
TypingsModulePathString::of(this).resolve(this.getFile().getParentContainer()).getContainer()
196+
or
197+
not exists(TypingsModulePathString::of(this)) and
198+
exists(File mainFile |
199+
mainFile = this.getMainModule().getFile() and
200+
result =
201+
mainFile
202+
.getParentContainer()
203+
.getFile(mainFile.getStem().regexpReplaceAll("\\.d$", "") + ".d.ts")
204+
)
205+
}
206+
207+
/**
208+
* Gets the module containing the typings of this package, which can either be from the `types` or
209+
* `typings` field, or derived from the `main` or `module` fields.
210+
*/
211+
Module getTypingsModule() { result.getFile() = this.getTypingsFile() }
183212
}
184213

185214
/** DEPRECATED: Alias for PackageJson */

javascript/ql/lib/semmle/javascript/NodeModuleResolutionImpl.qll

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,3 +198,29 @@ private class FilesPath extends PathExpr, @json_string {
198198
private module FilesPath {
199199
FilesPath of(PackageJson pkg) { result.getPackageJson() = pkg }
200200
}
201+
202+
/**
203+
* A JSON string in a `package.json` file specifying the path of the
204+
* TypeScript typings entry point.
205+
*/
206+
class TypingsModulePathString extends PathString {
207+
PackageJson pkg;
208+
209+
TypingsModulePathString() {
210+
this = pkg.getTypings()
211+
or
212+
not exists(pkg.getTypings()) and
213+
this = pkg.getMain().regexpReplaceAll("\\.[mc]?js$", ".d.ts")
214+
}
215+
216+
/** Gets the `package.json` file containing this path. */
217+
PackageJson getPackageJson() { result = pkg }
218+
219+
override Folder getARootFolder() { result = pkg.getFile().getParentContainer() }
220+
}
221+
222+
/** Companion module to the `TypingsModulePathString` class. */
223+
module TypingsModulePathString {
224+
/** Get the typings path for the given `package.json` file. */
225+
TypingsModulePathString of(PackageJson pkg) { result.getPackageJson() = pkg }
226+
}

0 commit comments

Comments
 (0)