Repository: remix-run/remix
Pull request #6181 (2023-04-26 05:12:52)

fix(remix-dev): use correct require context in serverBareModulesPlugin
this fixes the issue with misleading warnings for pnp mentioned in [this comment](https://github.com/remix-run/remix/issues/4106#issuecomment-1239133762) where the compiler in `@remix-run/dev` is attempting to resolve packages against it's own `package.json` rather than the application's `package.json`.

<!--

👋 Hey, thanks for your interest in contributing to Remix!

If this is a simple docs change, go ahead and delete all this.

**Please ask first before starting work on any significant new features.**

It's never a fun experience to have your pull request declined after investing a
lot of time and effort into a new feature. To avoid this from happening, we
request that contributors create a
[Feature Request discussion](https://github.com/remix-run/remix/discussions/new?category=ideas)
to first discuss any significant new features.

https://github.com/remix-run/remix/blob/main/CONTRIBUTING.md

Please fill in or delete each item below:

-->

Closes: #

- [ ] Docs
- [ ] Tests

Testing Strategy:

<!--
Please explain how you tested this. For example:

> This test covers this code: <link to test>

Or

> I opened up my windows machine and ran this script:
>
> ```
> npx create-remix@0.0.0-experimental-7e420ee3 --template remix my-test
> cd my-test
> npm run dev
> ```
-->

Adapted from https://github.com/remix-run/remix/pull/4156

changeset-bot[bot]: ###  🦋  Changeset detected

Latest commit: 57ecccc0e29f76e03f4c4312a87836abc4b5dcc9

**The changes in this PR will be included in the next version bump.**

<details><summary>This PR includes changesets to release 18 packages</summary>

  | Name                          | Type  |
| ----------------------------- | ----- |
| @remix-run/dev                | Patch |
| create-remix                  | Patch |
| @remix-run/css-bundle         | Patch |
| remix                         | Patch |
| @remix-run/architect          | Patch |
| @remix-run/cloudflare         | Patch |
| @remix-run/cloudflare-pages   | Patch |
| @remix-run/cloudflare-workers | Patch |
| @remix-run/deno               | Patch |
| @remix-run/eslint-config      | Patch |
| @remix-run/express            | Patch |
| @remix-run/netlify            | Patch |
| @remix-run/node               | Patch |
| @remix-run/react              | Patch |
| @remix-run/serve              | Patch |
| @remix-run/server-runtime     | Patch |
| @remix-run/testing            | Patch |
| @remix-run/vercel             | Patch |

</details>

Not sure what this means? [Click here  to learn what changesets are](https://github.com/changesets/changesets/blob/main/docs/adding-a-changeset.md).

[Click here if you're a maintainer who wants to add another changeset to this PR](https://github.com/remix-run/remix/new/correct-require-context?filename=.changeset/two-eyes-drop.md&value=---%0A%22remix%22%3A%20patch%0A%22%40remix-run%2Fdev%22%3A%20patch%0A---%0A%0Afix(remix-dev)%3A%20use%20correct%20require%20context%20in%20serverBareModulesPlugin%0A)



Patch:
diff --git a/.changeset/empty-taxis-call.md b/.changeset/empty-taxis-call.md
new file mode 100644
index 000000000..65bfc9b0d
--- /dev/null
+++ b/.changeset/empty-taxis-call.md
@@ -0,0 +1,5 @@
+---
+"@remix-run/dev": patch
+---
+
+Use correct require context in bareImports plugin.
diff --git a/.changeset/twelve-cheetahs-drive.md b/.changeset/twelve-cheetahs-drive.md
new file mode 100644
index 000000000..9b8892eab
--- /dev/null
+++ b/.changeset/twelve-cheetahs-drive.md
@@ -0,0 +1,5 @@
+---
+"@remix-run/server-runtime": patch
+---
+
+pass `AppLoadContext` to `handleRequest`
diff --git a/contributors.yml b/contributors.yml
index 1fe3b0004..fc93ac794 100644
--- a/contributors.yml
+++ b/contributors.yml
@@ -142,6 +142,7 @@
 - F3n67u
 - federicoestevez
 - fergusmeiklejohn
+- fernandojbf
 - fgiuliani
 - fishel-feng
 - francisudeji
diff --git a/packages/remix-dev/compiler/server/plugins/bareImports.ts b/packages/remix-dev/compiler/server/plugins/bareImports.ts
index ba7e78b96..acb4283f4 100644
--- a/packages/remix-dev/compiler/server/plugins/bareImports.ts
+++ b/packages/remix-dev/compiler/server/plugins/bareImports.ts
@@ -86,7 +86,7 @@ export function serverBareModulesPlugin({ config, options }: Context): Plugin {
             (pkgManager === "yarn" && process.versions.pnp == null))
         ) {
           try {
-            require.resolve(path);
+            require.resolve(path, { paths: [importer] });
           } catch (error: unknown) {
             options.onWarning(
               `The path "${path}" is imported in ` +
@@ -117,7 +117,7 @@ export function serverBareModulesPlugin({ config, options }: Context): Plugin {
           kind !== "dynamic-import" &&
           config.serverPlatform === "node"
         ) {
-          warnOnceIfEsmOnlyPackage(packageName, path, options.onWarning);
+          warnOnceIfEsmOnlyPackage(packageName, path, importer, options.onWarning);
         }
 
         // Externalize everything else if we've gotten here.
@@ -148,10 +148,11 @@ function isBareModuleId(id: string): boolean {
 function warnOnceIfEsmOnlyPackage(
   packageName: string,
   fullImportPath: string,
-  onWarning: (msg: string, key: string) => void
+  importer: string,
+  onWarning: (msg: string, key: string) => void,
 ) {
   try {
-    let packageDir = resolveModuleBasePath(packageName, fullImportPath);
+    let packageDir = resolveModuleBasePath(packageName, fullImportPath, importer);
     let packageJsonFile = path.join(packageDir, "package.json");
 
     if (!fs.existsSync(packageJsonFile)) {
@@ -193,8 +194,8 @@ function warnOnceIfEsmOnlyPackage(
 
 // https://github.com/nodejs/node/issues/33460#issuecomment-919184789
 // adapted to use the fullImportPath to resolve sub packages like @heroicons/react/solid
-function resolveModuleBasePath(packageName: string, fullImportPath: string) {
-  let moduleMainFilePath = require.resolve(fullImportPath);
+function resolveModuleBasePath(packageName: string, fullImportPath: string, importer: string) {
+  let moduleMainFilePath = require.resolve(fullImportPath, { paths: [importer] });
 
   let packageNameParts = packageName.split("/");
 
diff --git a/packages/remix-server-runtime/build.ts b/packages/remix-server-runtime/build.ts
index 4a3f666e8..4e1b831b1 100644
--- a/packages/remix-server-runtime/build.ts
+++ b/packages/remix-server-runtime/build.ts
@@ -1,6 +1,7 @@
 import type { DataFunctionArgs } from "./routeModules";
 import type { AssetsManifest, EntryContext, FutureConfig } from "./entry";
 import type { ServerRouteManifest } from "./routes";
+import type { AppLoadContext } from "./data";
 
 /**
  * The output of the compiler for the server build.
@@ -22,7 +23,8 @@ export interface HandleDocumentRequestFunction {
     request: Request,
     responseStatusCode: number,
     responseHeaders: Headers,
-    context: EntryContext
+    context: EntryContext,
+    loadContext: AppLoadContext
   ): Promise<Response> | Response;
 }
 
diff --git a/packages/remix-server-runtime/server.ts b/packages/remix-server-runtime/server.ts
index 8897807b1..97fa3a420 100644
--- a/packages/remix-server-runtime/server.ts
+++ b/packages/remix-server-runtime/server.ts
@@ -281,7 +281,8 @@ async function handleDocumentRequestRR(
       request,
       context.statusCode,
       headers,
-      entryContext
+      entryContext,
+      loadContext
     );
   } catch (error: unknown) {
     // Get a new StaticHandlerContext that contains the error at the right boundary
@@ -320,7 +321,8 @@ async function handleDocumentRequestRR(
         request,
         context.statusCode,
         headers,
-        entryContext
+        entryContext,
+        loadContext
       );
     } catch (error: any) {
       logServerErrorIfNotAborted(error, request, serverMode);


Test patch:
diff --git a/packages/remix-server-runtime/__tests__/server-test.ts b/packages/remix-server-runtime/__tests__/server-test.ts
index 8c1d33708..c0bf55166 100644
--- a/packages/remix-server-runtime/__tests__/server-test.ts
+++ b/packages/remix-server-runtime/__tests__/server-test.ts
@@ -1748,4 +1748,45 @@ describe("shared server runtime", () => {
       expect(spy.console.mock.calls.length).toBe(1 * DATA_CALL_MULTIPIER);
     });
   });
+  test("provides load context to server entrypoint", async () => {
+    let rootLoader = jest.fn(() => {
+      return "root";
+    });
+    let indexLoader = jest.fn(() => {
+      return "index";
+    });
+    let build = mockServerBuild({
+      root: {
+        default: {},
+        loader: rootLoader,
+        ErrorBoundary: {},
+      },
+      "routes/index": {
+        parentId: "root",
+        default: {},
+        loader: indexLoader,
+      },
+    });
+
+    build.entry.module.default = jest.fn(
+      async (
+        request,
+        responseStatusCode,
+        responseHeaders,
+        entryContext,
+        loadContext
+      ) =>
+        new Response(JSON.stringify(loadContext), {
+          status: responseStatusCode,
+          headers: responseHeaders,
+        })
+    );
+
+    let handler = createRequestHandler(build, ServerMode.Development);
+    let request = new Request(`${baseUrl}/`, { method: "get" });
+    let loadContext = { "load-context": "load-value" };
+
+    let result = await handler(request, loadContext);
+    expect(await result.text()).toBe(JSON.stringify(loadContext));
+  });
 });
diff --git a/packages/remix-server-runtime/__tests__/utils.ts b/packages/remix-server-runtime/__tests__/utils.ts
index 541409dce..b8168627b 100644
--- a/packages/remix-server-runtime/__tests__/utils.ts
+++ b/packages/remix-server-runtime/__tests__/utils.ts
@@ -48,7 +48,13 @@ export function mockServerBuild(
     entry: {
       module: {
         default: jest.fn(
-          async (request, responseStatusCode, responseHeaders, entryContext) =>
+          async (
+            request,
+            responseStatusCode,
+            responseHeaders,
+            entryContext,
+            loadContext
+          ) =>
             new Response(null, {
               status: responseStatusCode,
               headers: responseHeaders,