Skip to content
This repository was archived by the owner on Apr 16, 2020. It is now read-only.

Commit 3e26030

Browse files
guybedfordMylesBorins
authored andcommitted
esm: cpp refactoring update not to use uv_fs_realpath
1 parent 98f4d99 commit 3e26030

File tree

6 files changed

+58
-87
lines changed

6 files changed

+58
-87
lines changed

lib/internal/modules/esm/default_resolve.js

Lines changed: 36 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,27 @@
11
'use strict';
22

3+
const internalFS = require('internal/fs/utils');
34
const { NativeModule } = require('internal/bootstrap/loaders');
4-
const { ERR_TYPE_MISMATCH,
5-
ERR_UNKNOWN_FILE_EXTENSION } = require('internal/errors').codes;
5+
const { extname } = require('path');
6+
const { realpathSync } = require('fs');
67
const { getOptionValue } = require('internal/options');
8+
9+
const preserveSymlinks = getOptionValue('--preserve-symlinks');
10+
const preserveSymlinksMain = getOptionValue('--preserve-symlinks-main');
711
const experimentalJsonModules = getOptionValue('--experimental-json-modules');
8-
const { resolve: moduleWrapResolve } = internalBinding('module_wrap');
12+
13+
const { resolve: moduleWrapResolve,
14+
getPackageType } = internalBinding('module_wrap');
915
const { pathToFileURL, fileURLToPath } = require('internal/url');
1016
const asyncESM = require('internal/process/esm_loader');
11-
const preserveSymlinks = getOptionValue('--preserve-symlinks');
12-
const preserveSymlinksMain = getOptionValue('--preserve-symlinks-main');
13-
const { extname } = require('path');
17+
const { ERR_TYPE_MISMATCH,
18+
ERR_UNKNOWN_FILE_EXTENSION } = require('internal/errors').codes;
19+
20+
const realpathCache = new Map();
21+
22+
// const TYPE_NONE = 0;
23+
const TYPE_COMMONJS = 1;
24+
const TYPE_MODULE = 2;
1425

1526
const extensionFormatMap = {
1627
'__proto__': null,
@@ -50,13 +61,24 @@ function resolve(specifier, parentURL) {
5061
if (isMain)
5162
parentURL = pathToFileURL(`${process.cwd()}/`).href;
5263

53-
const { url, type } =
54-
moduleWrapResolve(specifier, parentURL,
55-
isMain ? !preserveSymlinksMain : !preserveSymlinks);
64+
let url = moduleWrapResolve(specifier, parentURL);
65+
66+
if (isMain ? !preserveSymlinksMain : !preserveSymlinks) {
67+
const real = realpathSync(fileURLToPath(url), {
68+
[internalFS.realpathCacheKey]: realpathCache
69+
});
70+
const old = url;
71+
url = pathToFileURL(real);
72+
url.search = old.search;
73+
url.hash = old.hash;
74+
}
75+
76+
const type = getPackageType(url.href);
5677

5778
const ext = extname(url.pathname);
58-
let format =
59-
(type !== 2 ? legacyExtensionFormatMap : extensionFormatMap)[ext];
79+
const extMap =
80+
type !== TYPE_MODULE ? legacyExtensionFormatMap : extensionFormatMap;
81+
let format = extMap[ext];
6082

6183
if (isMain && asyncESM.typeFlag) {
6284
// Conflict between explicit extension (.mjs, .cjs) and --type
@@ -68,8 +90,8 @@ function resolve(specifier, parentURL) {
6890

6991
// Conflict between package scope type and --type
7092
if (ext === '.js') {
71-
if (type === 2 && asyncESM.typeFlag === 'commonjs' ||
72-
type === 1 && asyncESM.typeFlag === 'module') {
93+
if (type === TYPE_MODULE && asyncESM.typeFlag === 'commonjs' ||
94+
type === TYPE_COMMONJS && asyncESM.typeFlag === 'module') {
7395
throw new ERR_TYPE_MISMATCH(
7496
fileURLToPath(url), ext, asyncESM.typeFlag, 'scope');
7597
}
@@ -79,7 +101,7 @@ function resolve(specifier, parentURL) {
79101
if (isMain && asyncESM.typeFlag)
80102
format = asyncESM.typeFlag;
81103
else if (isMain)
82-
format = type === 2 ? 'module' : 'commonjs';
104+
format = type === TYPE_MODULE ? 'module' : 'commonjs';
83105
else
84106
throw new ERR_UNKNOWN_FILE_EXTENSION(fileURLToPath(url),
85107
fileURLToPath(parentURL));

src/env.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ struct PackageConfig {
8686
enum Bool { No, Yes };
8787
};
8888
struct PackageType {
89-
enum Type : uint32_t { None, CommonJS, Module };
89+
enum Type : uint32_t { None = 0, CommonJS, Module };
9090
};
9191
const Exists::Bool exists;
9292
const IsValid::Bool is_valid;

src/module_wrap.cc

Lines changed: 19 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -476,17 +476,6 @@ std::string ReadFile(uv_file file) {
476476
return contents;
477477
}
478478

479-
Maybe<std::string> RealPath(const std::string& path) {
480-
uv_fs_t fs_req;
481-
const int r = uv_fs_realpath(nullptr, &fs_req, path.c_str(), nullptr);
482-
if (r < 0) {
483-
return Nothing<std::string>();
484-
}
485-
std::string link_path = std::string(static_cast<const char*>(fs_req.ptr));
486-
uv_fs_req_cleanup(&fs_req);
487-
return Just(link_path);
488-
}
489-
490479
enum DescriptorType {
491480
FILE,
492481
DIRECTORY,
@@ -895,21 +884,11 @@ Maybe<URL> Resolve(Environment* env,
895884
return FinalizeResolution(env, resolved, base);
896885
}
897886

898-
Maybe<PackageType::Type> GetPackageType(Environment* env,
899-
const URL& resolved) {
900-
Maybe<const PackageConfig*> pcfg =
901-
GetPackageScopeConfig(env, resolved, resolved);
902-
if (pcfg.IsNothing()) {
903-
return Nothing<PackageType::Type>();
904-
}
905-
return Just(pcfg.FromJust()->type);
906-
}
907-
908887
void ModuleWrap::Resolve(const FunctionCallbackInfo<Value>& args) {
909888
Environment* env = Environment::GetCurrent(args);
910889

911-
// module.resolve(specifier, url, realpath)
912-
CHECK_EQ(args.Length(), 3);
890+
// module.resolve(specifier, url)
891+
CHECK_EQ(args.Length(), 2);
913892

914893
CHECK(args[0]->IsString());
915894
Utf8Value specifier_utf8(env->isolate(), args[0]);
@@ -919,9 +898,6 @@ void ModuleWrap::Resolve(const FunctionCallbackInfo<Value>& args) {
919898
Utf8Value url_utf8(env->isolate(), args[1]);
920899
URL url(*url_utf8, url_utf8.length());
921900

922-
CHECK(args[2]->IsBoolean());
923-
bool realpath = args[2]->IsTrue();
924-
925901
if (url.flags() & URL_FLAGS_FAILED) {
926902
return node::THROW_ERR_INVALID_ARG_TYPE(
927903
env, "second argument is not a URL string");
@@ -942,47 +918,27 @@ void ModuleWrap::Resolve(const FunctionCallbackInfo<Value>& args) {
942918
URL resolution = result.FromJust();
943919
CHECK(!(resolution.flags() & URL_FLAGS_FAILED));
944920

945-
if (realpath) {
946-
Maybe<std::string> real_resolution =
947-
node::loader::RealPath(resolution.ToFilePath());
948-
// Note: Ensure module resolve FS error handling consistency
949-
if (real_resolution.IsNothing()) {
950-
std::string msg = "realpath error resolving " + resolution.ToFilePath();
951-
env->ThrowError(msg.c_str());
952-
try_catch.ReThrow();
953-
return;
954-
}
955-
std::string fragment = resolution.fragment();
956-
std::string query = resolution.query();
957-
resolution = URL::FromFilePath(real_resolution.FromJust());
958-
resolution.set_fragment(fragment);
959-
resolution.set_query(query);
960-
}
921+
args.GetReturnValue().Set(resolution.ToObject(env).ToLocalChecked());
922+
}
961923

962-
Maybe<PackageType::Type> pkg_type =
963-
node::loader::GetPackageType(env, resolution);
964-
if (result.IsNothing()) {
965-
CHECK(try_catch.HasCaught());
966-
try_catch.ReThrow();
967-
return;
968-
}
969-
CHECK(!try_catch.HasCaught());
924+
void ModuleWrap::GetPackageType(const FunctionCallbackInfo<Value>& args) {
925+
Environment* env = Environment::GetCurrent(args);
970926

971-
Local<Object> resolved = Object::New(env->isolate());
927+
// module.getPackageType(url)
928+
CHECK_EQ(args.Length(), 1);
972929

973-
resolved->DefineOwnProperty(
974-
env->context(),
975-
env->type_string(),
976-
Integer::New(env->isolate(), pkg_type.FromJust()),
977-
v8::ReadOnly).FromJust();
930+
CHECK(args[0]->IsString());
931+
Utf8Value url_utf8(env->isolate(), args[0]);
932+
URL url(*url_utf8, url_utf8.length());
978933

979-
resolved->DefineOwnProperty(
980-
env->context(),
981-
env->url_string(),
982-
resolution.ToObject(env).ToLocalChecked(),
983-
v8::ReadOnly).FromJust();
934+
PackageType::Type pkg_type = PackageType::None;
935+
Maybe<const PackageConfig*> pcfg =
936+
GetPackageScopeConfig(env, url, url);
937+
if (!pcfg.IsNothing()) {
938+
pkg_type = pcfg.FromJust()->type;
939+
}
984940

985-
args.GetReturnValue().Set(resolved);
941+
args.GetReturnValue().Set(Integer::New(env->isolate(), pkg_type));
986942
}
987943

988944
static MaybeLocal<Promise> ImportModuleDynamically(
@@ -1118,6 +1074,7 @@ void ModuleWrap::Initialize(Local<Object> target,
11181074
target->Set(env->context(), FIXED_ONE_BYTE_STRING(isolate, "ModuleWrap"),
11191075
tpl->GetFunction(context).ToLocalChecked()).FromJust();
11201076
env->SetMethod(target, "resolve", Resolve);
1077+
env->SetMethod(target, "getPackageType", GetPackageType);
11211078
env->SetMethod(target,
11221079
"setImportModuleDynamicallyCallback",
11231080
SetImportModuleDynamicallyCallback);

src/module_wrap.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ class ModuleWrap : public BaseObject {
6565
const v8::FunctionCallbackInfo<v8::Value>& args);
6666

6767
static void Resolve(const v8::FunctionCallbackInfo<v8::Value>& args);
68-
static void SetScopeType(const v8::FunctionCallbackInfo<v8::Value>& args);
68+
static void GetPackageType(const v8::FunctionCallbackInfo<v8::Value>& args);
6969
static void SetImportModuleDynamicallyCallback(
7070
const v8::FunctionCallbackInfo<v8::Value>& args);
7171
static void SetInitializeImportMetaObjectCallback(

src/node_url.h

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -153,14 +153,6 @@ class URL {
153153
return context_.fragment;
154154
}
155155

156-
void set_fragment(const std::string& fragment) {
157-
context_.fragment = fragment;
158-
}
159-
160-
void set_query(const std::string& query) {
161-
context_.query = query;
162-
}
163-
164156
std::string path() const {
165157
std::string ret;
166158
for (const std::string& element : context_.path) {

test/es-module/test-esm-symlink-type.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ symlinks.forEach((symlink) => {
6464
stdout.includes(symlink.prints)) return;
6565
assert.fail(`For ${JSON.stringify(symlink)}, ${
6666
(symlink.errorsWithPreserveSymlinksMain) ?
67-
'failed to error' : `errored unexpectedly\n${err}`
67+
'failed to error' : 'errored unexpectedly'
6868
} with --preserve-symlinks-main`);
6969
} else {
7070
if (stdout.includes(symlink.prints)) return;

0 commit comments

Comments
 (0)