Skip to content
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Fixes bug where `esbuild` execution was throwing an error saying "Command line too long" on Windows (https://github.com/firebase/firebase-tools/issues/7250 and https://github.com/firebase/firebase-tools/issues/6193).
2 changes: 1 addition & 1 deletion src/frameworks/next/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export const SERVER_REFERENCE_MANIFEST: `${typeof SERVER_REFERENCE_MANIFEST_TYPE

export const CONFIG_FILES = ["next.config.js", "next.config.mjs"] as const;

export const ESBUILD_VERSION = "0.19.2";
export const ESBUILD_VERSION = "^0.19.2";

// This is copied from Next.js source code to keep WEBPACK_LAYERS in sync with the Next.js definition.
const WEBPACK_LAYERS_NAMES = {
Expand Down
57 changes: 37 additions & 20 deletions src/frameworks/next/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { execSync } from "child_process";
import { spawn, sync as spawnSync } from "cross-spawn";
import { spawn } from "cross-spawn";
import { mkdir, copyFile } from "fs/promises";
import { basename, dirname, join } from "path";
import type { NextConfig } from "next";
Expand Down Expand Up @@ -56,6 +56,8 @@ import {
getRoutesWithServerAction,
getProductionDistDirFiles,
whichNextConfigFile,
installEsbuild,
findEsbuildPath,
} from "./utils";
import { NODE_VERSION, NPM_COMMAND_TIMEOUT_MILLIES, SHARP_VERSION, I18N_ROOT } from "../constants";
import type {
Expand All @@ -66,6 +68,7 @@ import type {
NpmLsDepdendency,
MiddlewareManifest,
ActionManifest,
CustomBuildOptions,
} from "./interfaces";
import {
MIDDLEWARE_MANIFEST,
Expand All @@ -74,8 +77,8 @@ import {
ROUTES_MANIFEST,
APP_PATH_ROUTES_MANIFEST,
APP_PATHS_MANIFEST,
ESBUILD_VERSION,
SERVER_REFERENCE_MANIFEST,
ESBUILD_VERSION,
Comment thread
jamesdaniels marked this conversation as resolved.
Resolved
} from "./constants";
import { getAllSiteDomains, getDeploymentDomain } from "../../hosting/api";
import { logger } from "../../logger";
Expand All @@ -90,7 +93,6 @@ export const support = SupportLevel.Preview;
export const type = FrameworkType.MetaFramework;
export const docsUrl = "https://firebase.google.com/docs/hosting/frameworks/nextjs";

const BUNDLE_NEXT_CONFIG_TIMEOUT = 60_000;
const DEFAULT_NUMBER_OF_REASONS_TO_LIST = 5;

function getReactVersion(cwd: string): string | undefined {
Expand Down Expand Up @@ -572,6 +574,23 @@ export async function ɵcodegenFunctionsDirectory(
const configFile = await whichNextConfigFile(sourceDir);
if (configFile) {
try {
// Check if esbuild is installed using `npx which`, if not, install it
let esbuildPath = findEsbuildPath();
if (!esbuildPath || !pathExistsSync(esbuildPath)) {
console.warn("esbuild not found, installing...");
installEsbuild(ESBUILD_VERSION);
esbuildPath = findEsbuildPath();
if (!esbuildPath || !pathExistsSync(esbuildPath)) {
throw new FirebaseError("Failed to locate esbuild after installation.");
}
}

// Dynamically require esbuild from the found path
const esbuild = require(esbuildPath);
if (!esbuild) {
throw new FirebaseError(`Failed to load esbuild from path: ${esbuildPath}`);
}

const productionDeps = await new Promise<string[]>((resolve) => {
const dependencies: string[] = [];
const npmLs = spawn("npm", ["ls", "--omit=dev", "--all", "--json=true"], {
Expand All @@ -593,29 +612,27 @@ export async function ɵcodegenFunctionsDirectory(
resolve([...new Set(dependencies)]);
});
});

// Mark all production deps as externals, so they aren't bundled
// DevDeps won't be included in the Cloud Function, so they should be bundled
const esbuildArgs = productionDeps
.map((it) => `--external:${it}`)
.concat("--bundle", "--platform=node", `--target=node${NODE_VERSION}`, "--log-level=error");

const esbuildArgs: CustomBuildOptions = {
entryPoints: [join(sourceDir, configFile)],
outfile: join(destDir, configFile),
bundle: true,
platform: "node",
target: `node${NODE_VERSION}`,
logLevel: "error",
external: productionDeps,
};
if (configFile === "next.config.mjs") {
// ensure generated file is .mjs if the config is .mjs
esbuildArgs.push(...[`--outfile=${join(destDir, configFile)}`, "--format=esm"]);
} else {
esbuildArgs.push(`--outfile=${join(destDir, configFile)}`);
esbuildArgs.format = "esm";
}

const bundle = spawnSync(
"npx",
["--yes", `esbuild@${ESBUILD_VERSION}`, configFile, ...esbuildArgs],
{
cwd: sourceDir,
timeout: BUNDLE_NEXT_CONFIG_TIMEOUT,
},
);
if (bundle.status !== 0) {
throw new FirebaseError(bundle.stderr.toString());
const bundle = await esbuild.build(esbuildArgs);

if (bundle.errors && bundle.errors.length > 0) {
throw new FirebaseError(bundle.errors.toString());
}
} catch (e: any) {
console.warn(
Expand Down
11 changes: 11 additions & 0 deletions src/frameworks/next/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,14 @@ type Actions = {
};

export type NextConfigFileName = (typeof CONFIG_FILES)[number];

export type CustomBuildOptions = {
entryPoints: string[];
outfile: string;
bundle: boolean;
platform: "node";
target: string;
logLevel: "silent" | "verbose" | "debug" | "info" | "warning" | "error";
external: string[];
format?: "iife" | "cjs" | "esm";
};
96 changes: 95 additions & 1 deletion src/frameworks/next/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,15 @@ import * as fsPromises from "fs/promises";
import * as fsExtra from "fs-extra";
import * as sinon from "sinon";
import * as glob from "glob";
import * as childProcess from "child_process";
import { FirebaseError } from "../../error";

import { EXPORT_MARKER, IMAGES_MANIFEST, APP_PATH_ROUTES_MANIFEST } from "./constants";
import {
EXPORT_MARKER,
IMAGES_MANIFEST,
APP_PATH_ROUTES_MANIFEST,
ESBUILD_VERSION,
} from "./constants";

import {
cleanEscapedChars,
Expand All @@ -29,6 +36,8 @@ import {
isUsingNextImageInAppDirectory,
getNextVersion,
getRoutesWithServerAction,
findEsbuildPath,
installEsbuild,
} from "./utils";

import * as frameworksUtils from "../utils";
Expand Down Expand Up @@ -529,4 +538,89 @@ describe("Next.js utils", () => {
).to.deep.equal(["/another-s-a", "/server-action", "/server-action/edge"]);
});
});

describe("findEsbuildPath", () => {
let execSyncStub: sinon.SinonStub;

beforeEach(() => {
execSyncStub = sinon.stub(childProcess, "execSync");
});

afterEach(() => {
execSyncStub.restore();
});

it("should return the correct esbuild path when esbuild is found", () => {
const mockBinaryPath = "/path/to/.bin/esbuild";
const expectedResolvedPath = "/path/to/esbuild";
execSyncStub
.withArgs("npx which esbuild", { encoding: "utf8" })
.returns(mockBinaryPath + "\n");

const esbuildPath = findEsbuildPath();

expect(esbuildPath).to.equal(expectedResolvedPath);
});

it("should return null if esbuild is not found", () => {
execSyncStub
.withArgs("npx which esbuild", { encoding: "utf8" })
.throws(new Error("not found"));

const esbuildPath = findEsbuildPath();
expect(esbuildPath).to.be.null;
});

it("should warn if global esbuild version does not match required version", () => {
const mockBinaryPath = "/path/to/.bin/esbuild";
execSyncStub
.withArgs("npx which esbuild", { encoding: "utf8" })
.returns(mockBinaryPath + "\n");
execSyncStub.withArgs("esbuild --version", { encoding: "utf8" }).returns("0.18.0\n");

const consoleWarnStub = sinon.stub(console, "warn");

findEsbuildPath();
expect(
consoleWarnStub.calledWith(
`Warning: Global esbuild version (0.18.0) does not match the required version (${ESBUILD_VERSION}).`,
),
).to.be.true;

consoleWarnStub.restore();
});
});

describe("installEsbuild", () => {
let execSyncStub: sinon.SinonStub;

beforeEach(() => {
execSyncStub = sinon.stub(childProcess, "execSync");
});
afterEach(() => execSyncStub.restore());

it("should successfully install esbuild", () => {
execSyncStub
.withArgs(`npm install esbuild@${ESBUILD_VERSION} --no-save`, { stdio: "inherit" })
.returns("");

installEsbuild(ESBUILD_VERSION);
expect(execSyncStub.calledOnce).to.be.true;
});

it("should throw a FirebaseError if installation fails", () => {
execSyncStub
.withArgs(`npm install esbuild@${ESBUILD_VERSION} --no-save`, { stdio: "inherit" })
.throws(new Error("Installation failed"));

try {
installEsbuild(ESBUILD_VERSION);
expect.fail("Expected installEsbuild to throw");
} catch (error) {
const typedError = error as FirebaseError;
expect(typedError).to.be.instanceOf(FirebaseError);
expect(typedError.message).to.include("Failed to install esbuild");
}
});
});
});
56 changes: 54 additions & 2 deletions src/frameworks/next/utils.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { existsSync } from "fs";
import { pathExists } from "fs-extra";
import { basename, extname, join, posix, sep } from "path";
import { basename, extname, join, posix, sep, resolve, dirname } from "path";
import { readFile } from "fs/promises";
import { glob, sync as globSync } from "glob";
import type { PagesManifest } from "next/dist/build/webpack/plugins/pages-manifest-plugin";
import { coerce } from "semver";
import { coerce, satisfies } from "semver";

import { findDependency, isUrl, readJSON } from "../utils";
import type {
Expand All @@ -31,9 +31,12 @@ import {
MIDDLEWARE_MANIFEST,
WEBPACK_LAYERS,
CONFIG_FILES,
ESBUILD_VERSION,
} from "./constants";
import { dirExistsSync, fileExistsSync } from "../../fsutils";
import { IS_WINDOWS } from "../../utils";
import { execSync } from "child_process";
import { FirebaseError } from "../../error";

export const I18N_SOURCE = /\/:nextInternalLocale(\([^\)]+\))?/;

Expand Down Expand Up @@ -489,3 +492,52 @@ export async function whichNextConfigFile(dir: string): Promise<NextConfigFileNa

return null;
}

/**
* Helper function to find the path of esbuild using `npm which`
*/
export function findEsbuildPath(): string | null {
try {
const esbuildBinPath = execSync("npx which esbuild", { encoding: "utf8" }).trim();
const globalVersion = getGlobalEsbuildVersion();
if (globalVersion && !satisfies(globalVersion, ESBUILD_VERSION)) {
console.warn(
`Warning: Global esbuild version (${globalVersion}) does not match the required version (${ESBUILD_VERSION}).`,
);
}
return resolve(dirname(esbuildBinPath), "../esbuild");
Comment thread
leoortizz marked this conversation as resolved.
Resolved
} catch (error) {
console.error(`Failed to find esbuild with npx which: ${error}`);
return null;
}
}

/**
* Helper function to get the global esbuild version
*/
export function getGlobalEsbuildVersion(): string | null {
try {
const versionOutput = execSync("esbuild --version", { encoding: "utf8" }).trim();
const versionMatch = versionOutput.match(/(\d+\.\d+\.\d+)/);
return versionMatch ? versionMatch[0] : null;
} catch (error) {
console.error(`Failed to get global esbuild version: ${error}`);
return null;
}
}

/**
* Helper function to install esbuild dynamically
*/
export function installEsbuild(version: string): void {
const installCommand = `npm install esbuild@${version} --no-save`;
try {
execSync(installCommand, { stdio: "inherit" });
} catch (error: any) {
if (error instanceof FirebaseError) {
throw error;
} else {
throw new FirebaseError(`Failed to install esbuild: ${error}`, { original: error });
}
}
}