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 Next.js dynamic and static OG images #6592

Merged
merged 18 commits into from
Dec 8, 2023
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/frameworks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
/**
*
*/
export async function discover(dir: string, warn = true) {

Check warning on line 63 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing return type on function
const allFrameworkTypes = [
...new Set(Object.values(WebFrameworks).map(({ type }) => type)),
].sort();
Expand All @@ -87,20 +87,20 @@
const BUILD_MEMO = new Map<string[], Promise<BuildResult | void>>();

// Memoize the build based on both the dir and the environment variables
function memoizeBuild(

Check warning on line 90 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing return type on function
dir: string,
build: (dir: string, target: string) => Promise<BuildResult | void>,
deps: any[],

Check warning on line 93 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unexpected any. Specify a different type
target: string
) {
const key = [dir, ...deps];

Check warning on line 96 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe spread of an `any` value in an array
for (const existingKey of BUILD_MEMO.keys()) {
if (isDeepStrictEqual(existingKey, key)) {
return BUILD_MEMO.get(existingKey);
}
}
const value = build(dir, target);
BUILD_MEMO.set(key, value);

Check warning on line 103 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe argument of type `any[]` assigned to a parameter of type `string[]`
return value;
}

Expand All @@ -108,7 +108,7 @@
* Use a function to ensure the same codebase name is used here and
* during hosting deploy.
*/
export function generateSSRCodebaseId(site: string) {

Check warning on line 111 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing return type on function
return `firebase-frameworks-${site}`;
}

Expand Down Expand Up @@ -174,7 +174,7 @@
`Hosting config for site ${site} places server-side content in region ${ssrRegion} which is not known. Valid regions are ${validRegions}`
);
}
const getProjectPath = (...args: string[]) => join(projectRoot, source, ...args);

Check warning on line 177 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing return type on function
// Combined traffic tag (19 chars) and functionId cannot exceed 46 characters.
const functionId = `ssr${site.toLowerCase().replace(/-/g, "").substring(0, 20)}`;
const usesFirebaseAdminSdk = !!findDependency("firebase-admin", { cwd: getProjectPath() });
Expand Down Expand Up @@ -210,9 +210,9 @@
if (selectedSite) {
const { appId } = selectedSite;
if (appId) {
firebaseConfig = await getAppConfig(appId, AppPlatform.WEB);

Check warning on line 213 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe assignment of an `any` value
firebaseDefaults ||= {};
firebaseDefaults.config = firebaseConfig;

Check warning on line 215 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe assignment of an `any` value
} else {
const defaultConfig = await implicitInit(options);
if (defaultConfig.json) {
Expand All @@ -221,7 +221,7 @@
You can link a Web app to a Hosting site here https://console.firebase.google.com/project/${project}/settings/general/web`
);
firebaseDefaults ||= {};
firebaseDefaults.config = JSON.parse(defaultConfig.json);

Check warning on line 224 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe assignment of an `any` value
} else {
// N.B. None of us know when this can ever happen and the deploy would
// still succeed. Maaaaybe if someone tried calling firebase serve
Expand Down Expand Up @@ -397,7 +397,11 @@
frameworksEntry = framework,
dotEnv = {},
rewriteSource,
} = await codegenFunctionsDirectory(getProjectPath(), functionsDist, frameworksBuildTarget);
} = await codegenFunctionsDirectory(getProjectPath(), functionsDist, frameworksBuildTarget, {
projectId: project,
site: options.site,
hostingChannel: context?.hostingChannel,
});

const rewrite = {
source: rewriteSource || posix.join(baseUrl, "**"),
Expand Down
4 changes: 3 additions & 1 deletion src/frameworks/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export type FrameworksOptions = HostingOptions &
export type FrameworkContext = {
projectId?: string;
hostingChannel?: string;
site?: string;
};

export interface Framework {
Expand Down Expand Up @@ -80,7 +81,8 @@ export interface Framework {
ɵcodegenFunctionsDirectory?: (
dir: string,
dest: string,
target: string
target: string,
context?: FrameworkContext
) => Promise<{
bootstrapScript?: string;
packageJson: any;
Expand Down
35 changes: 31 additions & 4 deletions src/frameworks/next/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,13 @@ import {
validateLocales,
getNodeModuleBin,
} from "../utils";
import { BuildResult, FrameworkType, SupportLevel } from "../interfaces";
import {
BuildResult,
Framework,
FrameworkContext,
FrameworkType,
SupportLevel,
} from "../interfaces";

import {
cleanEscapedChars,
Expand Down Expand Up @@ -67,7 +73,7 @@ import {
APP_PATHS_MANIFEST,
ESBUILD_VERSION,
} from "./constants";
import { getAllSiteDomains } from "../../hosting/api";
import { getAllSiteDomains, getDeploymentDomain } from "../../hosting/api";
import { logger } from "../../logger";

const DEFAULT_BUILD_SCRIPT = ["next build"];
Expand Down Expand Up @@ -488,7 +494,12 @@ export async function ɵcodegenPublicDirectory(
/**
* Create a directory for SSR content.
*/
export async function ɵcodegenFunctionsDirectory(sourceDir: string, destDir: string) {
export async function ɵcodegenFunctionsDirectory(
sourceDir: string,
destDir: string,
target: string,
context?: FrameworkContext
): ReturnType<NonNullable<Framework["ɵcodegenFunctionsDirectory"]>> {
const { distDir } = await getConfig(sourceDir);
const packageJson = await readJSON(join(sourceDir, "package.json"));
// Bundle their next.config.js with esbuild via NPX, pinned version was having troubles on m1
Expand Down Expand Up @@ -558,9 +569,25 @@ export async function ɵcodegenFunctionsDirectory(sourceDir: string, destDir: st
packageJson.dependencies["sharp"] = SHARP_VERSION;
}

const dotEnv: Record<string, string> = {};
if (context?.projectId && context?.site) {
const deploymentDomain = await getDeploymentDomain(
context.projectId,
context.site,
context.hostingChannel
);

if (deploymentDomain) {
// Add the deployment domain to VERCEL_URL env variable, which is
// required for dynamic OG images to work without manual configuration.
// See: https://nextjs.org/docs/app/api-reference/functions/generate-metadata#default-value
dotEnv["VERCEL_URL"] = deploymentDomain;
}
}

await mkdirp(join(destDir, distDir));
await copy(join(sourceDir, distDir), join(destDir, distDir));
return { packageJson, frameworksEntry: "next.js" };
return { packageJson, frameworksEntry: "next.js", dotEnv };
}

/**
Expand Down
17 changes: 17 additions & 0 deletions src/hosting/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -751,3 +751,20 @@ export async function getAllSiteDomains(projectId: string, siteId: string): Prom

return Array.from(allSiteDomains);
}

/**
* Get the deployment domain.
* If hostingChannel is provided, get the channel url, otherwise get the
* default site url.
*/
export async function getDeploymentDomain(
projectId: string,
siteId: string,
hostingChannel?: string | undefined
): Promise<string | undefined> {
const deploymentUrl = hostingChannel
? await getChannel(projectId, siteId, hostingChannel).then((channel) => channel?.url)
: await getSite(projectId, siteId).then((site) => site.defaultUrl);
leoortizz marked this conversation as resolved.
Show resolved Hide resolved

return deploymentUrl?.replace(/^https?:\/\//, "");
}
52 changes: 52 additions & 0 deletions src/test/hosting/api.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -821,6 +821,58 @@ describe("hosting", () => {
expect(nock.isDone()).to.be.true;
});
});

describe("getDeploymentDomain", () => {
afterEach(nock.cleanAll);

it("should get the default site domain when hostingChannel is omitted", async () => {
const defaultDomain = EXPECTED_DOMAINS_RESPONSE[EXPECTED_DOMAINS_RESPONSE.length - 1];
const defaultUrl = `https://${defaultDomain}`;

nock(hostingApiOrigin)
.get(`/v1beta1/projects/${PROJECT_ID}/sites/${SITE}`)
.reply(200, { defaultUrl });

expect(await hostingApi.getDeploymentDomain(PROJECT_ID, SITE)).to.equal(defaultDomain);
});

it("should get the default site domain when hostingChannel is undefined", async () => {
const defaultDomain = EXPECTED_DOMAINS_RESPONSE[EXPECTED_DOMAINS_RESPONSE.length - 1];
const defaultUrl = `https://${defaultDomain}`;

nock(hostingApiOrigin)
.get(`/v1beta1/projects/${PROJECT_ID}/sites/${SITE}`)
.reply(200, { defaultUrl });

expect(await hostingApi.getDeploymentDomain(PROJECT_ID, SITE, undefined)).to.equal(
defaultDomain
);
});

it("should get the channel domain", async () => {
const channelId = "my-channel";
const channelDomain = `${PROJECT_ID}--${channelId}-123123.web.app`;
const channel = { url: `https://${channelDomain}` };

nock(hostingApiOrigin)
.get(`/v1beta1/projects/${PROJECT_ID}/sites/${SITE}/channels/${channelId}`)
.reply(200, channel);

expect(await hostingApi.getDeploymentDomain(PROJECT_ID, SITE, channelId)).to.equal(
channelDomain
);
});

it("should return undefined if channel not found", async () => {
const channelId = "my-channel";

nock(hostingApiOrigin)
.get(`/v1beta1/projects/${PROJECT_ID}/sites/${SITE}/channels/${channelId}`)
.reply(404, {});

expect(await hostingApi.getDeploymentDomain(PROJECT_ID, SITE, channelId)).to.be.undefined;
});
});
});

describe("normalizeName", () => {
Expand Down