-
Notifications
You must be signed in to change notification settings - Fork 75
patch node-module-loader dynamic require #431
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
Merged
Merged
Changes from 8 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
2018756
patch node-module-loader dynamic require
HyperKiko f1cc83c
only require javascript files in node module loader patch
HyperKiko 1a073ff
clean up node module loader patch
HyperKiko 4c7b8f4
add pages api route e2e test
HyperKiko 6c84a10
normalize id variable and escape file path
HyperKiko d87c9c1
fix up node module loader rule and merge with require page plugin
HyperKiko 6afac13
pnpm fix and change whitespace in getRequires
HyperKiko 4a30231
fix node module loader rule and add changeset
HyperKiko df638ff
fixup! path separator
vicb File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| --- | ||
| "@opennextjs/cloudflare": patch | ||
| --- | ||
|
|
||
| fix pages api routes | ||
|
|
||
| fixed pages api routes by inlining a dynamic require in the `NodeModuleLoader` class |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| import { expect, test } from "@playwright/test"; | ||
|
|
||
| test("should not fail on an api route", async ({ page }) => { | ||
| const result = await page.goto("/api/hello"); | ||
| expect(result?.status()).toBe(200); | ||
| const body = await result?.json(); | ||
| expect(body).toEqual({ hello: "world" }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
144 changes: 144 additions & 0 deletions
144
packages/cloudflare/src/cli/build/patches/plugins/dynamic-requires.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| import { readFile } from "node:fs/promises"; | ||
| import { join, posix, sep } from "node:path"; | ||
vicb marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| import { type BuildOptions, getPackagePath } from "@opennextjs/aws/build/helper.js"; | ||
| import { getCrossPlatformPathRegex } from "@opennextjs/aws/utils/regex.js"; | ||
| import type { Plugin } from "esbuild"; | ||
|
|
||
| import { normalizePath } from "../../utils/normalize-path.js"; | ||
| import { patchCode, type RuleConfig } from "../ast/util.js"; | ||
| import type { ContentUpdater } from "./content-updater.js"; | ||
|
|
||
| async function getPagesManifests(serverDir: string): Promise<string[]> { | ||
| try { | ||
| return Object.values(JSON.parse(await readFile(join(serverDir, "pages-manifest.json"), "utf-8"))); | ||
| } catch { | ||
| // The file does not exist | ||
| return []; | ||
| } | ||
| } | ||
|
|
||
| async function getAppPathsManifests(serverDir: string): Promise<string[]> { | ||
| try { | ||
| return Object.values(JSON.parse(await readFile(join(serverDir, "app-paths-manifest.json"), "utf-8"))); | ||
| } catch { | ||
| // The file does not exist | ||
| return []; | ||
| } | ||
| } | ||
|
|
||
| function getServerDir(buildOpts: BuildOptions) { | ||
| return join(buildOpts.outputDir, "server-functions/default", getPackagePath(buildOpts), ".next/server"); | ||
| } | ||
|
|
||
| function getRequires(idVariable: string, files: string[], serverDir: string) { | ||
| // Inline fs access and dynamic requires that are not supported by workerd. | ||
| return files | ||
| .map( | ||
| (file) => ` | ||
| if (${idVariable}.replaceAll(${JSON.stringify(sep)}, ${JSON.stringify(posix.sep)}).endsWith(${JSON.stringify(normalizePath(file))})) { | ||
vicb marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return require(${JSON.stringify(join(serverDir, file))}); | ||
| }` | ||
| ) | ||
| .join("\n"); | ||
| } | ||
|
|
||
| export function inlineDynamicRequires(updater: ContentUpdater, buildOpts: BuildOptions): Plugin { | ||
| updater.updateContent( | ||
| "inline-node-module-loader", | ||
| { | ||
| filter: getCrossPlatformPathRegex( | ||
| String.raw`/next/dist/server/lib/module-loader/node-module-loader\.js$`, | ||
| { escape: false } | ||
| ), | ||
| contentFilter: /class NodeModuleLoader {/, | ||
| }, | ||
| async ({ contents }) => patchCode(contents, await getNodeModuleLoaderRule(buildOpts)) | ||
| ); | ||
| updater.updateContent( | ||
| "inline-require-page", | ||
| { | ||
| filter: getCrossPlatformPathRegex(String.raw`/next/dist/server/require\.js$`, { escape: false }), | ||
| contentFilter: /function requirePage\(/, | ||
| }, | ||
| async ({ contents }) => patchCode(contents, await getRequirePageRule(buildOpts)) | ||
| ); | ||
| return { name: "inline-dynamic-requires", setup() {} }; | ||
| } | ||
|
|
||
| async function getNodeModuleLoaderRule(buildOpts: BuildOptions) { | ||
| const serverDir = getServerDir(buildOpts); | ||
|
|
||
| const manifests = await getPagesManifests(serverDir); | ||
|
|
||
| const files = manifests.filter((file) => file.endsWith(".js")); | ||
|
|
||
| return ` | ||
| rule: | ||
| kind: method_definition | ||
| all: | ||
| - has: | ||
| field: name | ||
| regex: ^load$ | ||
| - has: | ||
| field: parameters | ||
| has: | ||
| kind: required_parameter | ||
| pattern: $ID | ||
| inside: | ||
| stopBy: | ||
| kind: class_declaration | ||
| kind: class_declaration | ||
| has: | ||
| field: name | ||
| regex: ^NodeModuleLoader$ | ||
| fix: | | ||
| async load($ID) { | ||
| ${getRequires("$ID", files, serverDir)} | ||
| }`; | ||
| } | ||
|
|
||
| async function getRequirePageRule(buildOpts: BuildOptions) { | ||
| const serverDir = getServerDir(buildOpts); | ||
|
|
||
| const pagesManifests = await getPagesManifests(serverDir); | ||
| const appPathsManifests = await getAppPathsManifests(serverDir); | ||
|
|
||
| const manifests = pagesManifests.concat(appPathsManifests); | ||
|
|
||
| const htmlFiles = manifests.filter((file) => file.endsWith(".html")); | ||
| const jsFiles = manifests.filter((file) => file.endsWith(".js")); | ||
|
|
||
| return { | ||
| rule: { | ||
| pattern: ` | ||
| function requirePage($PAGE, $DIST_DIR, $IS_APP_PATH) { | ||
| const $_ = getPagePath($$$ARGS); | ||
| $$$_BODY | ||
| }`, | ||
| }, // Inline fs access and dynamic require that are not supported by workerd. | ||
| fix: ` | ||
| function requirePage($PAGE, $DIST_DIR, $IS_APP_PATH) { | ||
| const { platform } = require('process'); | ||
| const pagePath = platform === 'win32' ? getPagePath($$$ARGS).replaceAll('\\\\', '/') : getPagePath($$$ARGS); | ||
|
|
||
| // html | ||
| ${( | ||
| await Promise.all( | ||
| htmlFiles.map( | ||
| async (file) => `if (pagePath.endsWith(${JSON.stringify(normalizePath(file))})) { | ||
| return ${JSON.stringify(await readFile(join(serverDir, file), "utf-8"))}; | ||
| }` | ||
| ) | ||
| ) | ||
| ).join("\n")} | ||
| // js | ||
| process.env.__NEXT_PRIVATE_RUNTIME_TYPE = $IS_APP_PATH ? 'app' : 'pages'; | ||
| try { | ||
| ${getRequires("pagePath", jsFiles, serverDir)} | ||
| } finally { | ||
| process.env.__NEXT_PRIVATE_RUNTIME_TYPE = ''; | ||
| } | ||
| }`, | ||
| } satisfies RuleConfig; | ||
| } | ||
92 changes: 0 additions & 92 deletions
92
packages/cloudflare/src/cli/build/patches/plugins/require-page.ts
This file was deleted.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.