Skip to content

Commit

Permalink
feat: updating type directives like @ts-types
Browse files Browse the repository at this point in the history
  • Loading branch information
hasundue committed Jul 29, 2024
1 parent e5865c6 commit 85b303a
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 14 deletions.
29 changes: 15 additions & 14 deletions core/refs.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { init, parseModule } from "@deno/graph";
import type { DependencyJson } from "@deno/graph/types";
import { toUrl } from "@molt/lib/path";
import { distinct, mapNotNullish } from "@std/collections";
import { distinct } from "@std/collections";
import { detect, EOL, format } from "@std/fs/eol";
import { extname } from "@std/path";
import { type DependencySpec, parse, stringify, tryParse } from "./specs.ts";
Expand Down Expand Up @@ -63,26 +63,27 @@ async function fromEsModule(
): Promise<DependencyRef<"esm">[]> {
await init();
const mod = await parseModule(toUrl(path), await Deno.readFile(path));
return mapNotNullish(
mod.dependencies ?? [],
return (mod.dependencies ?? []).flatMap(
(json) => fromDependencyJson(path, json),
).sort(compare);
);
}

function fromDependencyJson(
path: string | URL,
json: DependencyJson,
): DependencyRef<"esm"> | undefined {
const dependency = tryParse(json.specifier);
if (!dependency) return;

const { span } = json.code ?? json.type ?? {};
if (span && json.assertionType !== "json") {
return {
dependency,
source: { path, kind: "esm", span },
};
): DependencyRef<"esm">[] {
const refs: DependencyRef<"esm">[] = [];
for (const dep of [json.code, json.type]) {
if (!dep) continue;
const { span, specifier } = dep;
if (span && specifier) {
const dependency = tryParse(specifier);
if (dependency) {
refs.push({ dependency, source: { path, kind: "esm", span } });
}
}
}
return refs;
}

async function fromImportMap(
Expand Down
43 changes: 43 additions & 0 deletions core/refs_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,49 @@ describe("collect", () => {
assertEquals(actual, []);
});

it("should pick `@deno-types` dependencies from an ES module", async () => {
await Deno.writeTextFile(
"a.ts",
dedent`
// @ts-types="npm:@types/foo@1.2.3"
import { foo } from "npm:foo@1.2.3";
`,
);
const actual = await collect("a.ts");
assertEquals(actual, [
{
dependency: {
kind: "npm",
name: "@types/foo",
constraint: "1.2.3",
},
source: {
kind: "esm",
path: "a.ts",
span: {
start: { line: 0, character: 13 },
end: { line: 0, character: 35 },
},
},
},
{
dependency: {
kind: "npm",
name: "foo",
constraint: "1.2.3",
},
source: {
kind: "esm",
path: "a.ts",
span: {
start: { line: 1, character: 20 },
end: { line: 1, character: 35 },
},
},
},
]);
});

it("should collect dependencies from an import map", async () => {
await Deno.writeTextFile(
"a.json",
Expand Down

0 comments on commit 85b303a

Please sign in to comment.