Skip to content

Commit

Permalink
Handle more module declaration cases (#6792)
Browse files Browse the repository at this point in the history
  • Loading branch information
penalosa authored Oct 2, 2024
1 parent b2d094e commit 27e8385
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/popular-horses-hide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"wrangler": patch
---

fix: Handle more module declaration cases
17 changes: 17 additions & 0 deletions packages/wrangler/src/__tests__/type-generation.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as fs from "fs";
import * as TOML from "@iarna/toml";
import {
constructTSModuleGlob,
constructType,
constructTypeKey,
generateImportSpecifier,
Expand Down Expand Up @@ -48,6 +49,22 @@ describe("constructTypeKey", () => {
});
});

describe("constructTSModuleGlob() should return a valid TS glob ", () => {
it.each([
["**/*.wasm", "*.wasm"],
["**/*.txt", "*.txt"],
["**/foo", "*/foo"],
["**/*foo", "*foo"],
["file.foo", "file.foo"],
["folder/file.foo", "folder/file.foo"],
["folder/*", "folder/*"],
["folder/**", "folder/*"],
["folder/**/*", "folder/*"],
])("$1 -> $2", (from, to) => {
expect(constructTSModuleGlob(from)).toBe(to);
});
});

describe("constructType", () => {
it("should return a valid type", () => {
expect(constructType("valid", "string")).toBe("valid: string;");
Expand Down
17 changes: 14 additions & 3 deletions packages/wrangler/src/type-generation/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,19 @@ export function constructTypeKey(key: string) {
return `"${key}"`;
}

export function constructTSModuleGlob(glob: string) {
// Exact module reference, don't transform
if (!glob.includes("*")) {
return glob;
// Usually something like **/*.wasm. Turn into *.wasm
} else if (glob.includes(".")) {
return `*.${glob.split(".").at(-1)}`;
} else {
// Replace common patterns
return glob.replace("**/*", "*").replace("**/", "*/").replace("/**", "/*");
}
}

/**
* Generate a import specifier from one module to another
*/
Expand Down Expand Up @@ -426,9 +439,7 @@ async function generateTypes(
moduleTypeMap[ruleObject.type as keyof typeof moduleTypeMap];
if (typeScriptType !== undefined) {
ruleObject.globs.forEach((glob) => {
modulesTypeStructure.push(`declare module "*.${glob
.split(".")
.at(-1)}" {
modulesTypeStructure.push(`declare module "${constructTSModuleGlob(glob)}" {
const value: ${typeScriptType};
export default value;
}`);
Expand Down

0 comments on commit 27e8385

Please sign in to comment.