Skip to content

Commit

Permalink
fix lint
Browse files Browse the repository at this point in the history
  • Loading branch information
khuezy committed Aug 29, 2023
1 parent 64b703a commit 73696c5
Show file tree
Hide file tree
Showing 8 changed files with 81 additions and 114 deletions.
13 changes: 7 additions & 6 deletions packages/open-next/src/adapters/event-mapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,16 +63,17 @@ 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;
}

export function convertFrom(
event: APIGatewayProxyEventV2 | APIGatewayProxyEvent | CloudFrontRequestEvent,
buildId: string
buildId: string,
): InternalEvent {
let internalEvent: InternalEvent;
if (isCloudFrontRequestEvent(event)) {
Expand Down Expand Up @@ -101,7 +102,7 @@ export function convertTo(
}

function removeUndefinedFromQuery(
query: Record<string, string | string[] | undefined>
query: Record<string, string | string[] | undefined>,
) {
const newQuery: Record<string, string | string[]> = {};
for (const [key, value] of Object.entries(query)) {
Expand All @@ -112,7 +113,7 @@ function removeUndefinedFromQuery(
return newQuery;
}
function convertFromAPIGatewayProxyEvent(
event: APIGatewayProxyEvent
event: APIGatewayProxyEvent,
): InternalEvent {
const { path, body, httpMethod, requestContext, isBase64Encoded } = event;
return {
Expand All @@ -124,7 +125,7 @@ function convertFromAPIGatewayProxyEvent(
headers: normalizeAPIGatewayProxyEventHeaders(event),
remoteAddress: requestContext.identity.sourceIp,
query: removeUndefinedFromQuery(
event.multiValueQueryStringParameters ?? {}
event.multiValueQueryStringParameters ?? {},
),
};
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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);
Expand All @@ -21,14 +20,15 @@ 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

//#override handler
export const handler: PluginHandler = async (
req: IncomingMessage,
res: ServerResponse,
options: Options
options: Options,
) => {
let { internalEvent } = options;

Expand All @@ -50,7 +50,7 @@ export const handler: PluginHandler = async (
async function handleMiddleware(
req: IncomingMessage,
res: ServerResponse,
rawPath: string
rawPath: string,
): Promise<ServerResponse | undefined> {
const hasMatch = middleMatch.some((r) => r.test(rawPath));
if (!hasMatch) return;
Expand All @@ -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);
Expand Down
3 changes: 1 addition & 2 deletions packages/open-next/src/adapters/plugins/serverHandler.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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);
Expand Down
25 changes: 13 additions & 12 deletions packages/open-next/src/adapters/plugins/util.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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 ?? "");
Expand Down
51 changes: 9 additions & 42 deletions packages/open-next/src/adapters/server-adapter.ts
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand Down
6 changes: 3 additions & 3 deletions packages/open-next/src/adapters/util.ts
Original file line number Diff line number Diff line change
@@ -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";
}
Expand Down
45 changes: 21 additions & 24 deletions packages/open-next/src/build.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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({
Expand Down Expand Up @@ -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
Expand All @@ -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]
}.`,
);
}
}
Expand Down Expand Up @@ -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]
}.`,
);
}
}
Expand Down
Loading

0 comments on commit 73696c5

Please sign in to comment.