Skip to content

Commit e082616

Browse files
committed
chore: port PR #1122 from source repository
opennextjs/opennextjs-cloudflare#1122 Applied bugfixes and improvements to the 'migrate' command: - Fixed extra newlines when appending to files (updated conditionalAppendFileSync signature) - Fixed error when 'public' directory is missing (creates parent directories automatically) - Fixed Next.js config file update to check if the file exists first - Updated checkRunningInsideNextjsApp to accept { appPath: string } instead of full BuildOptions Changesets: - .changeset/port-pr-1122-cloudflare.md - .changeset/port-pr-1122-aws.md
1 parent c8337b0 commit e082616

5 files changed

Lines changed: 68 additions & 26 deletions

File tree

.changeset/port-pr-1122-aws.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
"@opennextjs/aws": patch
3+
---
4+
5+
Ported PR #1122 from source repository
6+
7+
https://github.com/opennextjs/opennextjs-cloudflare/pull/1122
8+
9+
Changed `checkRunningInsideNextjsApp` function signature to accept `{ appPath: string }` instead of full `BuildOptions` object, making it more flexible for use in the migrate command.
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
"@opennextjs/cloudflare": patch
3+
---
4+
5+
Ported PR #1122 from source repository
6+
7+
https://github.com/opennextjs/opennextjs-cloudflare/pull/1122
8+
9+
Applied bugfixes and improvements to the `migrate` command:
10+
- Fixed extra newlines when appending to files (updated `conditionalAppendFileSync` function signature to use options object with `appendIf` and `appendPrefix`)
11+
- Fixed error when `public` directory is missing (now creates parent directories automatically)
12+
- Fixed Next.js config file update to check if the file exists before attempting to update
Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import fs from "node:fs";
2+
import path from "node:path";
23

34
/**
45
* Appends text to a file
@@ -8,16 +9,29 @@ import fs from "node:fs";
89
*
910
* @param filepath The path to the file.
1011
* @param text The text to append to the file.
11-
* @param condition A function that receives the current file content and returns `true` if the text should be appended to it, the condition is skipped when the file is being created.
12+
* @param opts.appendIf A function that receives the current file content and returns `true` if the text should be appended to it, the condition is skipped when the file is being created. Defaults to a function that always returns true.
13+
* @param opts.appendPrefix A string that will be inserted between the pre-existing file's content and the new text in case the file already existed. Defaults to an empty string.
1214
*/
1315
export function conditionalAppendFileSync(
1416
filepath: string,
1517
text: string,
16-
condition: (fileContent: string) => boolean
18+
{
19+
appendIf = () => true,
20+
appendPrefix = "",
21+
}: {
22+
appendIf?: (fileContent: string) => boolean;
23+
appendPrefix?: string;
24+
} = {}
1725
): void {
1826
const fileExists = fs.existsSync(filepath);
27+
const maybeFileContent = fileExists ? fs.readFileSync(filepath, "utf8") : "";
1928

20-
if (!fileExists || condition(fs.readFileSync(filepath, "utf8"))) {
21-
fs.appendFileSync(filepath, text);
29+
if (!fileExists) {
30+
const dir = path.dirname(filepath);
31+
fs.mkdirSync(dir, { recursive: true });
32+
}
33+
34+
if (!fileExists || appendIf(maybeFileContent)) {
35+
fs.appendFileSync(filepath, `${maybeFileContent.length > 0 ? appendPrefix : ""}${text}`);
2236
}
2337
}

packages/cloudflare/src/cli/commands/migrate.ts

Lines changed: 28 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -71,20 +71,22 @@ async function migrateCommand(args: { forceInstall: boolean }): Promise<void> {
7171

7272
const devVarsExists = fs.existsSync(".dev.vars");
7373
printStepTitle(`${devVarsExists ? "Updating" : "Creating"} .dev.vars file`);
74-
conditionalAppendFileSync(
75-
".dev.vars",
76-
"\nNEXTJS_ENV=development\n",
77-
(content) => !/\bNEXTJS_ENV\b/.test(content)
78-
);
74+
conditionalAppendFileSync(".dev.vars", "NEXTJS_ENV=development\n", {
75+
appendIf: (content) => !/\bNEXTJS_ENV\b/.test(content),
76+
appendPrefix: "\n",
77+
});
7978

8079
printStepTitle(`${fs.existsSync("public/_headers") ? "Updating" : "Creating"} public/_headers file`);
8180
conditionalAppendFileSync(
8281
"public/_headers",
83-
"\n\n# https://developers.cloudflare.com/workers/static-assets/headers\n" +
82+
"# https://developers.cloudflare.com/workers/static-assets/headers\n" +
8483
"# https://opennext.js.org/cloudflare/caching#static-assets-caching\n" +
8584
"/_next/static/*\n" +
86-
" Cache-Control: public,max-age=31536000,immutable\n\n",
87-
(content) => !/^\/_next\/static\/*\b/.test(content)
85+
" Cache-Control: public,max-age=31536000,immutable\n",
86+
{
87+
appendIf: (content) => !/^\/_next\/static\/*\b/.test(content),
88+
appendPrefix: "\n\n",
89+
}
8890
);
8991

9092
printStepTitle("Updating package.json scripts");
@@ -114,26 +116,32 @@ async function migrateCommand(args: { forceInstall: boolean }): Promise<void> {
114116
logger.warn(
115117
"\nPlease ensure that your package.json contains the following scripts:\n" +
116118
console.log(
117-
[...Object.entries(openNextScripts)].map(([key, value]) => ` - ${key}: ${value}`).join("\n")
119+
Object.entries(openNextScripts).map(([key, value]) => ` - ${key}: ${value}`).join("\n")
118120
) +
119121
"\n"
120122
);
121123
}
122124

123125
const gitIgnoreExists = fs.existsSync(".gitignore");
124126
printStepTitle(`${gitIgnoreExists ? "Updating" : "Creating"} .gitignore file`);
125-
conditionalAppendFileSync(
126-
".gitignore",
127-
"\n# OpenNext\n.open-next\n",
128-
(content) => !content.includes(".open-next")
129-
);
127+
conditionalAppendFileSync(".gitignore", "# OpenNext\n.open-next\n", {
128+
appendIf: (content) => !content.includes(".open-next"),
129+
appendPrefix: "\n",
130+
});
130131

131-
printStepTitle("Updating Next.js config");
132-
conditionalAppendFileSync(
133-
findNextConfig({ appPath: projectDir })!,
134-
"\nimport('@opennextjs/cloudflare').then(m => m.initOpenNextCloudflareForDev());\n",
135-
(content) => !content.includes("initOpenNextCloudflareForDev")
136-
);
132+
const nextConfig = findNextConfig({ appPath: projectDir });
133+
134+
if (nextConfig) {
135+
printStepTitle("Updating Next.js config");
136+
conditionalAppendFileSync(
137+
nextConfig.path,
138+
"import('@opennextjs/cloudflare').then(m => m.initOpenNextCloudflareForDev());\n",
139+
{
140+
appendIf: (content) => !content.includes("initOpenNextCloudflareForDev"),
141+
appendPrefix: "\n",
142+
}
143+
);
144+
}
137145

138146
printStepTitle("Checking for edge runtime usage");
139147
try {

packages/open-next/src/build/helper.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -337,8 +337,7 @@ export function copyEnvFile(appPath: string, packagePath: string, outputPath: st
337337
/**
338338
* Check we are in a Nextjs app by looking for the Nextjs config file.
339339
*/
340-
export function checkRunningInsideNextjsApp(options: BuildOptions) {
341-
const { appPath } = options;
340+
export function checkRunningInsideNextjsApp({ appPath }: { appPath: string }) {
342341
const extension = ["js", "cjs", "mjs", "ts"].find((ext) =>
343342
fs.existsSync(path.join(appPath, `next.config.${ext}`))
344343
);

0 commit comments

Comments
 (0)