Skip to content
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

Fix image optimization support for Next 14.1.1 #377

Merged
merged 8 commits into from
Mar 6, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/old-islands-invite.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"open-next": patch
---

Fix Image Optimization Support for [email protected]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We probably don't want to apply the changeset now. We usually let the PR merge into main, run the e2e, and once that passes, we do a separate changeset PR.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It should be fine actually, changesets get merged before release and the changebot don't release until we merge the version packages PR.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh right, I forgot.

26 changes: 7 additions & 19 deletions packages/open-next/src/adapters/image-optimization-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import type {
// @ts-ignore
import { defaultConfig } from "next/dist/server/config-shared";
import {
imageOptimizer,
ImageOptimizerCache,
// @ts-ignore
} from "next/dist/server/image-optimizer";
Expand All @@ -23,6 +22,7 @@ import type { NextUrlWithParsedQuery } from "next/dist/server/request-meta";

import { loadConfig } from "./config/util.js";
import { awsLogger, debug, error } from "./logger.js";
import { optimizeImage } from "./plugins/image-optimization.js";
import { setNodeEnv } from "./util.js";

// Expected environment variables
Expand Down Expand Up @@ -64,7 +64,12 @@ export async function handler(
headers,
queryString === null ? undefined : queryString,
);
const result = await optimizeImage(headers, imageParams);
const result = await optimizeImage(
headers,
imageParams,
nextConfig,
downloadHandler,
);

return buildSuccessResponse(result);
} catch (e: any) {
Expand Down Expand Up @@ -110,23 +115,6 @@ function validateImageParams(
return imageParams;
}

async function optimizeImage(
headers: APIGatewayProxyEventHeaders,
imageParams: any,
) {
const result = await imageOptimizer(
// @ts-ignore
{ headers },
{}, // res object is not necessary as it's not actually used.
imageParams,
nextConfig,
false, // not in dev mode
downloadHandler,
);
debug("optimized result", result);
return result;
}

function buildSuccessResponse(result: any) {
return {
statusCode: 200,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import type { IncomingMessage, ServerResponse } from "node:http";

import type { APIGatewayProxyEventHeaders } from "aws-lambda";
import type { NextConfig } from "next/dist/server/config-shared";
//#override imports
import {
// @ts-ignore
fetchExternalImage,
// @ts-ignore
fetchInternalImage,
imageOptimizer,
} from "next/dist/server/image-optimizer";
//#endOverride
import type { NextUrlWithParsedQuery } from "next/dist/server/request-meta";

import { debug } from "../logger.js";

//#override optimizeImage
export async function optimizeImage(
headers: APIGatewayProxyEventHeaders,
imageParams: any,
nextConfig: NextConfig,
handleRequest: (
newReq: IncomingMessage,
newRes: ServerResponse,
newParsedUrl?: NextUrlWithParsedQuery,
) => Promise<void>,
) {
const { isAbsolute, href } = imageParams;

const imageUpstream = isAbsolute
? await fetchExternalImage(href)
: await fetchInternalImage(
href,
// @ts-ignore
{ headers },
{}, // res object is not necessary as it's not actually used.
handleRequest,
);

// @ts-ignore
const result = await imageOptimizer(
imageUpstream,
imageParams,
nextConfig,
false, // not in dev mode
);
debug("optimized result", result);
return result;
}
//#endOverride
35 changes: 35 additions & 0 deletions packages/open-next/src/adapters/plugins/image-optimization.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { IncomingMessage, ServerResponse } from "node:http";

import { APIGatewayProxyEventHeaders } from "aws-lambda";
import { NextConfig } from "next/dist/server/config-shared";
//#override imports
import { imageOptimizer } from "next/dist/server/image-optimizer";
//#endOverride
import { NextUrlWithParsedQuery } from "next/dist/server/request-meta";

import { debug } from "../logger.js";

//#override optimizeImage
export async function optimizeImage(
headers: APIGatewayProxyEventHeaders,
imageParams: any,
nextConfig: NextConfig,
handleRequest: (
newReq: IncomingMessage,
newRes: ServerResponse,
newParsedUrl: NextUrlWithParsedQuery,
) => Promise<void>,
) {
const result = await imageOptimizer(
// @ts-ignore
{ headers },
{}, // res object is not necessary as it's not actually used.
imageParams,
nextConfig,
false, // not in dev mode
handleRequest,
);
debug("optimized result", result);
return result;
}
//#endOverride
28 changes: 24 additions & 4 deletions packages/open-next/src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ export async function build(opts: BuildOptions = {}) {
}
await createServerBundle(monorepoRoot, options.streaming);
createRevalidationBundle();
createImageOptimizationBundle();
await createImageOptimizationBundle();
createWarmerBundle();
if (options.minify) {
await minifyServerBundle();
Expand Down Expand Up @@ -315,7 +315,7 @@ function createRevalidationBundle() {
);
}

function createImageOptimizationBundle() {
async function createImageOptimizationBundle() {
logger.info(`Bundling image optimization function...`);

const { appPath, appBuildOutputPath, outputDir } = options;
Expand All @@ -324,16 +324,36 @@ function createImageOptimizationBundle() {
const outputPath = path.join(outputDir, "image-optimization-function");
fs.mkdirSync(outputPath, { recursive: true });

const plugins =
compareSemver(options.nextVersion, "14.1.1") >= 0
? [
openNextPlugin({
name: "opennext-14.1.1-image-optimization",
target: /plugins\/image-optimization\.js/g,
replacements: ["./image-optimization.replacement.js"],
}),
]
: undefined;

if (plugins && plugins.length > 0) {
logger.debug(
`Applying plugins:: [${plugins
.map(({ name }) => name)
.join(",")}] for Next version: ${options.nextVersion}`,
);
}

// Build Lambda code (1st pass)
// note: bundle in OpenNext package b/c the adapter relies on the
// "@aws-sdk/client-s3" package which is not a dependency in user's
// Next.js app.
esbuildSync({
await esbuildAsync({
entryPoints: [
path.join(__dirname, "adapters", "image-optimization-adapter.js"),
],
external: ["sharp", "next"],
outfile: path.join(outputPath, "index.mjs"),
plugins,
});

// Build Lambda code (2nd pass)
Expand Down Expand Up @@ -367,7 +387,7 @@ function createImageOptimizationBundle() {
// For SHARP_IGNORE_GLOBAL_LIBVIPS see: https://github.com/lovell/sharp/blob/main/docs/install.md#aws-lambda

const nodeOutputPath = path.resolve(outputPath);
const sharpVersion = process.env.SHARP_VERSION ?? "0.33.2";
const sharpVersion = process.env.SHARP_VERSION ?? "0.32.6";

//check if we are running in Windows environment then set env variables accordingly.
try {
Expand Down