Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(endo): Add search #353

Merged
merged 2 commits into from
Jul 21, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions packages/endo/src/search.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { relativize } from "./node-module-specifier.js";
import { relative } from "./url.js";

// q, as in quote, for enquoting strings in error messages.
const q = JSON.stringify;

const decoder = new TextDecoder();

// Searches for the first ancestor directory of a module file that contains a
// package.json.
// Probes by attempting to read the file, not stat.
// To avoid duplicate work later, returns the text of the package.json for
// inevitable later use.
export const search = async (read, modulePath) => {
let directory = new URL("./", modulePath).toString();
for (;;) {
const packageDescriptorPath = new URL("package.json", directory).toString();
// eslint-disable-next-line no-await-in-loop
const packageDescriptorBytes = await read(packageDescriptorPath).catch(
() => undefined
);
if (packageDescriptorBytes !== undefined) {
const packageDescriptorText = decoder.decode(packageDescriptorBytes);
return {
packageLocation: directory,
packageDescriptorText,
moduleSpecifier: relativize(relative(directory, modulePath))
};
}
const parentDirectory = new URL("../", directory).toString();
if (parentDirectory === directory) {
throw new Error(
`Cannot find package.json along path to module ${q(modulePath)}`
);
}
directory = parentDirectory;
}
};