Repository: nodejs/node
Pull request: module: improve `getPackageType` performance

`packageJsonReader#getPackageType` currently gets the whole package scope config from the C++ binding and then extracts its `type` field, my understanding is that this is wasteful (since the whole object needs to be serialized to cross the C++/JS boundary) and that gathering the type in C++ and returning only that would be more efficient, that's what I'm attempting to do in this PR :slightly_smiling_face: (I hope my C++ makes sense as I am pretty inexperienced with it :crossed_fingers:)


<!--
Before submitting a pull request, please read:

- the CONTRIBUTING guide at https://github.com/nodejs/node/blob/HEAD/CONTRIBUTING.md
- the commit message formatting guidelines at
  https://github.com/nodejs/node/blob/HEAD/doc/contributing/pull-requests.md#commit-message-guidelines

For code changes:
1. Include tests for any bug fixes or new features.
2. Update documentation if relevant.
3. Ensure that `make -j4 test` (UNIX), or `vcbuild test` (Windows) passes.

If you believe this PR should be highlighted in the Node.js CHANGELOG
please add the `notable-change` label.

Developer's Certificate of Origin 1.1

By making a contribution to this project, I certify that:

(a) The contribution was created in whole or in part by me and I
    have the right to submit it under the open source license
    indicated in the file; or

(b) The contribution is based upon previous work that, to the best
    of my knowledge, is covered under an appropriate open source
    license and I have the right under that license to submit that
    work with modifications, whether created in whole or in part
    by me, under the same open source license (unless I am
    permitted to submit under a different license), as indicated
    in the file; or

(c) The contribution was provided directly to me by some other
    person who certified (a), (b) or (c) and I have not modified
    it.

(d) I understand and agree that this project and the contribution
    are public and that a record of the contribution (including all
    personal information I submit with it, including my sign-off) is
    maintained indefinitely and may be redistributed consistent with
    this project or the open source license(s) involved.
-->


Changed files:
filename: lib/internal/modules/package_json_reader.js
patch: @@ -174,8 +174,8 @@ function getPackageScopeConfig(resolved) {
  * @param {URL} url - The URL to get the package type for.
  */
 function getPackageType(url) {
-  // TODO(@anonrig): Write a C++ function that returns only "type".
-  return getPackageScopeConfig(url).type;
+  const type = modulesBinding.getPackageType(`${url}`);
+  return type ?? 'none';
 }
 
 const invalidPackageNameRegEx = /^\.|%|\\/;

filename: src/node_modules.cc
patch: @@ -404,6 +404,7 @@ void BindingData::GetNearestParentPackageJSONType(
   }
 }
 
+template <bool return_only_type>
 void BindingData::GetPackageScopeConfig(
     const FunctionCallbackInfo<Value>& args) {
   CHECK_GE(args.Length(), 1);
@@ -442,7 +443,15 @@ void BindingData::GetPackageScopeConfig(
     error_context.specifier = resolved.ToString();
     auto package_json = GetPackageJSON(realm, *file_url, &error_context);
     if (package_json != nullptr) {
-      return args.GetReturnValue().Set(package_json->Serialize(realm));
+      if constexpr (return_only_type) {
+        Local<Value> value;
+        if (ToV8Value(realm->context(), package_json->type).ToLocal(&value)) {
+          args.GetReturnValue().Set(value);
+        }
+        return;
+      } else {
+        return args.GetReturnValue().Set(package_json->Serialize(realm));
+      }
     }
 
     auto last_href = std::string(package_json_url->get_href());
@@ -460,6 +469,12 @@ void BindingData::GetPackageScopeConfig(
     }
   }
 
+  if constexpr (return_only_type) {
+    return;
+  }
+
+  // If the package.json could not be found return a string containing a path
+  // to the non-existent package.json file in the initial requested location
   auto package_json_url_as_path =
       url::FileURLToPath(realm->env(), *package_json_url);
   CHECK(package_json_url_as_path);
@@ -604,7 +619,9 @@ void BindingData::CreatePerIsolateProperties(IsolateData* isolate_data,
             target,
             "getNearestParentPackageJSON",
             GetNearestParentPackageJSON);
-  SetMethod(isolate, target, "getPackageScopeConfig", GetPackageScopeConfig);
+  SetMethod(
+      isolate, target, "getPackageScopeConfig", GetPackageScopeConfig<false>);
+  SetMethod(isolate, target, "getPackageType", GetPackageScopeConfig<true>);
   SetMethod(isolate, target, "enableCompileCache", EnableCompileCache);
   SetMethod(isolate, target, "getCompileCacheDir", GetCompileCacheDir);
   SetMethod(isolate, target, "flushCompileCache", FlushCompileCache);
@@ -658,7 +675,8 @@ void BindingData::RegisterExternalReferences(
   registry->Register(ReadPackageJSON);
   registry->Register(GetNearestParentPackageJSONType);
   registry->Register(GetNearestParentPackageJSON);
-  registry->Register(GetPackageScopeConfig);
+  registry->Register(GetPackageScopeConfig<false>);
+  registry->Register(GetPackageScopeConfig<true>);
   registry->Register(EnableCompileCache);
   registry->Register(GetCompileCacheDir);
   registry->Register(FlushCompileCache);

filename: src/node_modules.h
patch: @@ -59,6 +59,7 @@ class BindingData : public SnapshotableObject {
       const v8::FunctionCallbackInfo<v8::Value>& args);
   static void GetNearestParentPackageJSONType(
       const v8::FunctionCallbackInfo<v8::Value>& args);
+  template <bool return_only_type>
   static void GetPackageScopeConfig(
       const v8::FunctionCallbackInfo<v8::Value>& args);
   static void GetPackageJSONScripts(

filename: typings/internalBinding/modules.d.ts
patch: @@ -25,6 +25,7 @@ export interface ModulesBinding {
   getNearestParentPackageJSONType(path: string): PackageConfig['type']
   getNearestParentPackageJSON(path: string): SerializedPackageConfig | undefined
   getPackageScopeConfig(path: string): SerializedPackageConfig | undefined
+  getPackageType(path: string): PackageConfig['type'] | undefined
   enableCompileCache(path?: string): { status: number, message?: string, directory?: string }
   getCompileCacheDir(): string | undefined
   flushCompileCache(keepDeserializedCache?: boolean): void