From 6900361d3e0e5075df2788b3519926e4ea8c9c83 Mon Sep 17 00:00:00 2001 From: Khue Nguyen Date: Mon, 28 Aug 2023 17:33:06 -0700 Subject: [PATCH] fix lint --- .../open-next/src/adapters/event-mapper.ts | 13 ++--- .../plugins/serverHandler.replacement.ts | 14 ++--- .../src/adapters/plugins/serverHandler.ts | 3 +- .../open-next/src/adapters/plugins/util.ts | 25 ++++----- .../open-next/src/adapters/server-adapter.ts | 53 ++++--------------- packages/open-next/src/adapters/util.ts | 6 +-- packages/open-next/src/build.ts | 45 ++++++++-------- packages/open-next/src/plugin.ts | 38 ++++++------- 8 files changed, 82 insertions(+), 115 deletions(-) diff --git a/packages/open-next/src/adapters/event-mapper.ts b/packages/open-next/src/adapters/event-mapper.ts index 4278d7c8..1ea42c76 100644 --- a/packages/open-next/src/adapters/event-mapper.ts +++ b/packages/open-next/src/adapters/event-mapper.ts @@ -63,8 +63,9 @@ export function fixDataPage(internalEvent: InternalEvent, buildId: string) { ...internalEvent, rawPath: newPath, query, - url: `${newPath}${query ? `?${new URLSearchParams(urlQuery).toString()}` : "" - }`, + url: `${newPath}${ + query ? `?${new URLSearchParams(urlQuery).toString()}` : "" + }`, }; } return internalEvent; @@ -72,7 +73,7 @@ export function fixDataPage(internalEvent: InternalEvent, buildId: string) { export function convertFrom( event: APIGatewayProxyEventV2 | APIGatewayProxyEvent | CloudFrontRequestEvent, - buildId: string + buildId: string, ): InternalEvent { let internalEvent: InternalEvent; if (isCloudFrontRequestEvent(event)) { @@ -101,7 +102,7 @@ export function convertTo( } function removeUndefinedFromQuery( - query: Record + query: Record, ) { const newQuery: Record = {}; for (const [key, value] of Object.entries(query)) { @@ -112,7 +113,7 @@ function removeUndefinedFromQuery( return newQuery; } function convertFromAPIGatewayProxyEvent( - event: APIGatewayProxyEvent + event: APIGatewayProxyEvent, ): InternalEvent { const { path, body, httpMethod, requestContext, isBase64Encoded } = event; return { @@ -124,7 +125,7 @@ function convertFromAPIGatewayProxyEvent( headers: normalizeAPIGatewayProxyEventHeaders(event), remoteAddress: requestContext.identity.sourceIp, query: removeUndefinedFromQuery( - event.multiValueQueryStringParameters ?? {} + event.multiValueQueryStringParameters ?? {}, ), }; } diff --git a/packages/open-next/src/adapters/plugins/serverHandler.replacement.ts b/packages/open-next/src/adapters/plugins/serverHandler.replacement.ts index 5154d52f..430e91d9 100644 --- a/packages/open-next/src/adapters/plugins/serverHandler.replacement.ts +++ b/packages/open-next/src/adapters/plugins/serverHandler.replacement.ts @@ -1,16 +1,15 @@ -import type { PluginHandler, Options } from "../next-types.js"; - //#override imports import path from "node:path"; + +import type { Options, PluginHandler } from "../next-types.js"; import { IncomingMessage } from "../request.js"; import { ServerResponse } from "../response.js"; import { config, NEXT_DIR } from "../util.js"; import { - requestHandler, getMiddlewareMatch, loadMiddlewareManifest, + requestHandler, setNextjsPrebundledReact, - fixDataPage, } from "./util.js"; const middlewareManifest = loadMiddlewareManifest(NEXT_DIR); @@ -21,6 +20,7 @@ const { getCloneableBody } = require("next/dist/server/body-streams"); const { signalFromNodeResponse, } = require("next/dist/server/web/spec-extension/adapters/next-request"); + const middleMatch = getMiddlewareMatch(middlewareManifest); //#endOverride @@ -28,7 +28,7 @@ const middleMatch = getMiddlewareMatch(middlewareManifest); export const handler: PluginHandler = async ( req: IncomingMessage, res: ServerResponse, - options: Options + options: Options, ) => { let { internalEvent } = options; @@ -50,7 +50,7 @@ export const handler: PluginHandler = async ( async function handleMiddleware( req: IncomingMessage, res: ServerResponse, - rawPath: string + rawPath: string, ): Promise { const hasMatch = middleMatch.some((r) => r.test(rawPath)); if (!hasMatch) return; @@ -60,7 +60,7 @@ async function handleMiddleware( // structure, but as of now, the only useful property on it is the "/" key (ie root). const middlewareInfo = middlewareManifest.middleware["/"]; middlewareInfo.paths = middlewareInfo.files.map((file) => - path.join(NEXT_DIR, file) + path.join(NEXT_DIR, file), ); console.log("~~Running 13.4.13 middleware:", rawPath); diff --git a/packages/open-next/src/adapters/plugins/serverHandler.ts b/packages/open-next/src/adapters/plugins/serverHandler.ts index 778c2022..2bd8670b 100644 --- a/packages/open-next/src/adapters/plugins/serverHandler.ts +++ b/packages/open-next/src/adapters/plugins/serverHandler.ts @@ -1,7 +1,6 @@ import type { Options, PluginHandler } from "../next-types.js"; import type { IncomingMessage } from "../request.js"; import type { ServerResponse } from "../response.js"; - //#override imports import { requestHandler, setNextjsPrebundledReact } from "./util.js"; //#endOverride @@ -10,7 +9,7 @@ import { requestHandler, setNextjsPrebundledReact } from "./util.js"; export const handler: PluginHandler = async ( req: IncomingMessage, res: ServerResponse, - options: Options + options: Options, ) => { setNextjsPrebundledReact(options.internalEvent.rawPath); return requestHandler(req, res); diff --git a/packages/open-next/src/adapters/plugins/util.ts b/packages/open-next/src/adapters/plugins/util.ts index 721ae411..8ff507cf 100644 --- a/packages/open-next/src/adapters/plugins/util.ts +++ b/packages/open-next/src/adapters/plugins/util.ts @@ -1,21 +1,25 @@ import fs from "node:fs"; import path from "node:path"; + +// @ts-ignore +import NextServer from "next/dist/server/next-server.js"; + +import { InternalEvent } from "../event-mapper.js"; +import { debug } from "../logger.js"; +import { MiddlewareManifest } from "../next-types.js"; +import { + applyOverride as applyNextjsRequireHooksOverride, + overrideHooks as overrideNextjsRequireHooks, +} from "../require-hooks.js"; import { config, - loadRoutesManifest, loadAppPathsManifestKeys, + loadRoutesManifest, NEXT_DIR, } from "../util.js"; -import { debug } from "../logger.js"; - -import { MiddlewareManifest } from "../next-types.js"; const routesManifest = loadRoutesManifest(NEXT_DIR); const appPathsManifestKeys = loadAppPathsManifestKeys(NEXT_DIR); -import { - overrideHooks as overrideNextjsRequireHooks, - applyOverride as applyNextjsRequireHooksOverride, -} from "../require-hooks.js"; // WORKAROUND: Set `__NEXT_PRIVATE_PREBUNDLED_REACT` to use prebundled React — https://github.com/serverless-stack/open-next#workaround-set-__next_private_prebundled_react-to-use-prebundled-react // Step 1: Need to override the require hooks for React before Next.js server @@ -25,9 +29,6 @@ import { // override that Next.js does is done at import time overrideNextjsRequireHooks(config); -// @ts-ignore -import NextServer from "next/dist/server/next-server.js"; -import { InternalEvent } from "../event-mapper.js"; applyNextjsRequireHooksOverride(); //#override requestHandler @@ -69,7 +70,7 @@ export function setNextjsPrebundledReact(rawPath: string) { // WORKAROUND: Set `__NEXT_PRIVATE_PREBUNDLED_REACT` to use prebundled React — https://github.com/serverless-stack/open-next#workaround-set-__next_private_prebundled_react-to-use-prebundled-react const route = routesManifest.find((route) => - new RegExp(route.regex).test(rawPath ?? "") + new RegExp(route.regex).test(rawPath ?? ""), ); const isApp = appPathsManifestKeys.includes(route?.page ?? ""); diff --git a/packages/open-next/src/adapters/server-adapter.ts b/packages/open-next/src/adapters/server-adapter.ts index a0f6c918..92cb865c 100644 --- a/packages/open-next/src/adapters/server-adapter.ts +++ b/packages/open-next/src/adapters/server-adapter.ts @@ -1,40 +1,29 @@ import crypto from "node:crypto"; -import path from "node:path"; import { SendMessageCommand, SQSClient } from "@aws-sdk/client-sqs"; - import type { APIGatewayProxyEvent, APIGatewayProxyEventV2, CloudFrontRequestEvent, } from "aws-lambda"; - import { isBinaryContentType } from "./binary.js"; -import { InternalEvent, convertFrom, convertTo } from "./event-mapper.js"; +import { convertFrom, convertTo, InternalEvent } from "./event-mapper.js"; import { awsLogger, debug, error } from "./logger.js"; +import { handler as serverHandler } from "./plugins/serverHandler.js"; import { IncomingMessage } from "./request.js"; -import { - applyOverride as applyNextjsRequireHooksOverride, - overrideHooks as overrideNextjsRequireHooks, -} from "./require-hooks.js"; import { ServerResponse } from "./response.js"; import { - config, generateUniqueId, - loadAppPathsManifestKeys, loadBuildId, loadHtmlPages, loadPublicAssets, - loadRoutesManifest, - setNodeEnv, NEXT_DIR, OPEN_NEXT_DIR, + setNodeEnv, } from "./util.js"; import type { WarmerEvent, WarmerResponse } from "./warmer-function.js"; -import { handler as serverHandler } from "./plugins/serverHandler.js"; - // Expected environment variables const { REVALIDATION_QUEUE_REGION, REVALIDATION_QUEUE_URL } = process.env; @@ -103,7 +92,7 @@ export async function handler( body: internalEvent.body, remoteAddress: internalEvent.remoteAddress, }; - console.log("~~IncomingMessage constructor props", reqProps); + debug("IncomingMessage constructor props", reqProps); const req = new IncomingMessage(reqProps); const res = new ServerResponse({ method: reqProps.method }); await processRequest(req, res, internalEvent); @@ -155,32 +144,10 @@ function setBuildIdEnv() { process.env.NEXT_BUILD_ID = buildId; } -function setNextjsPrebundledReact(rawPath: string) { - // WORKAROUND: Set `__NEXT_PRIVATE_PREBUNDLED_REACT` to use prebundled React — https://github.com/serverless-stack/open-next#workaround-set-__next_private_prebundled_react-to-use-prebundled-react - - const route = routesManifest.find((route) => - new RegExp(route.regex).test(rawPath ?? ""), - ); - - const isApp = appPathsManifestKeys.includes(route?.page ?? ""); - debug("setNextjsPrebundledReact", { url: rawPath, isApp, route }); - - // app routes => use prebundled React - if (isApp) { - process.env.__NEXT_PRIVATE_PREBUNDLED_REACT = config.experimental.serverActions - ? "experimental" - : "next"; - return; - } - - // page routes => use node_modules React - process.env.__NEXT_PRIVATE_PREBUNDLED_REACT = undefined; -} - async function processRequest( req: IncomingMessage, res: ServerResponse, - internalEvent: InternalEvent + internalEvent: InternalEvent, ) { // @ts-ignore // Next.js doesn't parse body if the property exists @@ -255,11 +222,11 @@ async function revalidateIfRequired( const revalidateUrl = internalMeta?._nextDidRewrite ? // When using Pages Router, two requests will be received: - // 1. one for the page: /foo - // 2. one for the json data: /_next/data/BUILD_ID/foo.json - // The rewritten url is correct for 1, but that for the second request - // does not include the "/_next/data/" prefix. Need to add it. - rawPath.startsWith("/_next/data/") + // 1. one for the page: /foo + // 2. one for the json data: /_next/data/BUILD_ID/foo.json + // The rewritten url is correct for 1, but that for the second request + // does not include the "/_next/data/" prefix. Need to add it. + rawPath.startsWith("/_next/data/") ? `/_next/data/${buildId}${internalMeta?._nextRewroteUrl}.json` : internalMeta?._nextRewroteUrl : rawPath; diff --git a/packages/open-next/src/adapters/util.ts b/packages/open-next/src/adapters/util.ts index be4237be..7c016ad7 100644 --- a/packages/open-next/src/adapters/util.ts +++ b/packages/open-next/src/adapters/util.ts @@ -1,13 +1,13 @@ import fs from "node:fs"; import path from "node:path"; +import type { PublicFiles } from "../build.js"; +import type { NextConfig, RoutesManifest } from "./next-types.js"; + export const NEXT_DIR = path.join(__dirname, ".next"); export const OPEN_NEXT_DIR = path.join(__dirname, ".open-next"); export const config = loadConfig(NEXT_DIR); -import type { NextConfig, RoutesManifest } from "./next-types.js"; -import type { PublicFiles } from "../build.js"; - export function setNodeEnv() { process.env.NODE_ENV = process.env.NODE_ENV ?? "production"; } diff --git a/packages/open-next/src/build.ts b/packages/open-next/src/build.ts index 56264552..04943920 100644 --- a/packages/open-next/src/build.ts +++ b/packages/open-next/src/build.ts @@ -1,20 +1,18 @@ import cp from "node:child_process"; import fs from "node:fs"; - +import { createRequire as topLevelCreateRequire } from "node:module"; import path from "node:path"; import url from "node:url"; - - - -import { minifyAll } from "./minimize-js.js"; import { build as buildAsync, - buildSync, BuildOptions as ESBuildOptions, + buildSync, } from "esbuild"; -import { createRequire as topLevelCreateRequire } from "node:module"; + +import { minifyAll } from "./minimize-js.js"; import openNextPlugin from "./plugin.js"; + interface BuildOptions { /** * Minify the server bundle. @@ -408,26 +406,25 @@ async function createServerBundle(monorepoRoot: string) { // note: bundle in OpenNext package b/c the adapter relies on the // "serverless-http" package which is not a dependency in user's // Next.js app. - const plugins = compareSemver(options.nextVersion, "13.4.13") >= 0 ? [ - openNextPlugin({ - target: /plugins\/serverHandler\.js/g, - replacements: ["./serverHandler.replacement.js"], - }), - openNextPlugin({ - target: /plugins\/util\.js/g, - replacements: ["./util.replacement.js"], - }), - ] + openNextPlugin({ + target: /plugins\/serverHandler\.js/g, + replacements: ["./serverHandler.replacement.js"], + }), + openNextPlugin({ + target: /plugins\/util\.js/g, + replacements: ["./util.replacement.js"], + }), + ] : undefined; if (plugins) { console.log( `Applying plugins:: [${plugins .map(({ name }) => name) - .join(",")}] for Next version: ${options.nextVersion}` + .join(",")}] for Next version: ${options.nextVersion}`, ); } await esbuildAsync({ @@ -583,8 +580,6 @@ function esbuildSync(esbuildOptions: ESBuildOptions) { minify: debug ? false : true, sourcemap: debug ? "inline" : false, ...esbuildOptions, - // external: [...(esbuildOptions.external || []), "next", "styled-jsx", "react"], - // "process.env.OPEN_NEXT_DEBUG" determines if the logger writes to console.log define: { ...esbuildOptions.define, "process.env.OPEN_NEXT_DEBUG": process.env.OPEN_NEXT_DEBUG @@ -597,8 +592,9 @@ function esbuildSync(esbuildOptions: ESBuildOptions) { if (result.errors.length > 0) { result.errors.forEach((error) => console.error(error)); throw new Error( - `There was a problem bundling ${(esbuildOptions.entryPoints as string[])[0] - }.` + `There was a problem bundling ${ + (esbuildOptions.entryPoints as string[])[0] + }.`, ); } } @@ -626,8 +622,9 @@ async function esbuildAsync(esbuildOptions: ESBuildOptions) { if (result.errors.length > 0) { result.errors.forEach((error) => console.error(error)); throw new Error( - `There was a problem bundling ${(esbuildOptions.entryPoints as string[])[0] - }.` + `There was a problem bundling ${ + (esbuildOptions.entryPoints as string[])[0] + }.`, ); } } diff --git a/packages/open-next/src/plugin.ts b/packages/open-next/src/plugin.ts index 95adb5ac..a1ec1c64 100644 --- a/packages/open-next/src/plugin.ts +++ b/packages/open-next/src/plugin.ts @@ -1,5 +1,6 @@ -import path from "node:path"; import { readFile } from "node:fs/promises"; +import path from "node:path"; + import { Plugin } from "esbuild"; export interface IPluginSettings { @@ -53,27 +54,28 @@ export default function openNextPlugin({ let contents = await readFile(args.path, "utf-8"); for (const fp of replacements) { - } - await Promise.all(replacements.map(async (fp) => { - const p = path.join(args.path, "..", fp); - const replacementFile = await readFile(p, "utf-8"); - const matches = replacementFile.matchAll(overridePattern); + await Promise.all( + replacements.map(async (fp) => { + const p = path.join(args.path, "..", fp); + const replacementFile = await readFile(p, "utf-8"); + const matches = replacementFile.matchAll(overridePattern); - const importMatch = replacementFile.match(importPattern); - const addedImport = importMatch ? importMatch[0] : ""; + const importMatch = replacementFile.match(importPattern); + const addedImport = importMatch ? importMatch[0] : ""; - contents = `${addedImport}\n${contents}`; + contents = `${addedImport}\n${contents}`; - for (const match of matches) { - const replacement = match[2]; - const id = match[1]; - const pattern = new RegExp( - `\/\/#override (${id})\n([\\s\\S]*?)\n\/\/#endOverride` - ); - contents = contents.replace(pattern, replacement); - } - })) + for (const match of matches) { + const replacement = match[2]; + const id = match[1]; + const pattern = new RegExp( + `\/\/#override (${id})\n([\\s\\S]*?)\n\/\/#endOverride`, + ); + contents = contents.replace(pattern, replacement); + } + }), + ); return { contents,