Skip to content

Commit 9901856

Browse files
committed
refactor: inline readNearestPackageJSON impl
1 parent 1dc1638 commit 9901856

3 files changed

Lines changed: 29 additions & 9 deletions

File tree

‎package.json‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,7 @@
3232
"exsolve": "^1.0.8",
3333
"knitwork": "^1.3.0",
3434
"magic-string": "^1.0.0",
35-
"pathe": "^2.0.3",
36-
"pkg-types": "^2.3.0"
35+
"pathe": "^2.0.3"
3736
},
3837
"devDependencies": {
3938
"@rollup/plugin-node-resolve": "^16.0.3",

‎pnpm-lock.yaml‎

Lines changed: 0 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/plugin/runtime/imports.ts‎

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,40 @@
1-
// TODO: Use normal import in next major with ESM-only dist
2-
// import { readPackageJSON } from "pkg-types";
1+
import { readFile } from "node:fs/promises";
32
import {
43
genSafeVariableName,
54
genObjectFromRaw,
65
genString,
76
genImport,
87
} from "knitwork";
98
import { resolveModulePath } from "exsolve";
9+
import { dirname, join } from "pathe";
1010

1111
import { WasmAsset, UnwasmPluginOptions } from "../shared";
1212

13+
interface PackageJSON {
14+
imports?: Record<string, string | Record<string, string>>;
15+
}
16+
17+
/**
18+
* Read the nearest `package.json` by walking up from `from`.
19+
*
20+
* Returns an empty object if none is found.
21+
*/
22+
async function readNearestPackageJSON(from: string): Promise<PackageJSON> {
23+
let dir = dirname(from);
24+
let lastDir = "";
25+
while (dir !== lastDir) {
26+
const contents = await readFile(join(dir, "package.json"), "utf8").catch(
27+
() => undefined,
28+
);
29+
if (contents !== undefined) {
30+
return JSON.parse(contents) as PackageJSON;
31+
}
32+
lastDir = dir;
33+
dir = dirname(dir);
34+
}
35+
return {};
36+
}
37+
1338
export async function getWasmImports(
1439
asset: WasmAsset,
1540
_opts: UnwasmPluginOptions,
@@ -23,8 +48,7 @@ export async function getWasmImports(
2348
}
2449

2550
// Try to resolve from nearest package.json
26-
const { readPackageJSON } = await import("pkg-types");
27-
const pkg = await readPackageJSON(asset.id);
51+
const pkg = await readNearestPackageJSON(asset.id);
2852

2953
const resolved = true;
3054

0 commit comments

Comments
 (0)