-
Notifications
You must be signed in to change notification settings - Fork 723
Playing around with native adapter #456
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
Draft
Yuangwang
wants to merge
5
commits into
main
Choose a base branch
from
adapter-native-weiwng
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
5720b39
native-adapter-playground-weiwng
Yuangwang d1b4d0d
update to newest adapter
Yuangwang 68115bc
Get dynamic content working
Yuangwang d188943
adapter is the same as james but with different serve
Yuangwang 4cb903e
adapter is the same as james but with different serve
Yuangwang File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,80 +1,137 @@ | ||
| #! /usr/bin/env node | ||
| // import { build } from "esbuild"; | ||
| // import { stringify } from "yaml"; | ||
| // import { spawn } from "child_process"; | ||
| // import { join, dirname } from "path"; | ||
| // import fs from "fs-extra"; | ||
| // import { fileURLToPath } from "url"; | ||
| import { | ||
| generateBuildOutput, | ||
| loadConfig, | ||
| populateOutputBundleOptions, | ||
| generateBuildOutput, | ||
| validateOutputDirectory, | ||
| getAdapterMetadata, | ||
| exists, | ||
| checkNextJSVersion, | ||
| } from "../utils.js"; | ||
| import { join } from "path"; | ||
| import { getBuildOptions, runBuild } from "@apphosting/common"; | ||
| import { | ||
| addRouteOverrides, | ||
| overrideNextConfig, | ||
| restoreNextConfig, | ||
| validateNextConfigOverride, | ||
| } from "../overrides.js"; | ||
|
|
||
| const root = process.cwd(); | ||
| const opts = getBuildOptions(); | ||
| // const __filename = fileURLToPath(import.meta.url); | ||
| // const __dirname = dirname(__filename); | ||
| // export async function main() { | ||
| // const root = process.cwd(); | ||
| // console.log(`🏗️ Starting Adapter Build in ${root}...`); | ||
|
|
||
| // // 1. Run Next.js Build | ||
| // const nextBuild = spawn("npx", ["next", "build"], { | ||
| // stdio: "inherit", | ||
| // cwd: root, | ||
| // shell: true, | ||
| // env: { ...process.env, NODE_ENV: "production" }, | ||
| // }); | ||
|
|
||
| // await new Promise<void>((resolve, reject) => { | ||
| // nextBuild.on("close", (code) => { | ||
| // if (code === 0) resolve(); | ||
| // else reject(new Error(`Next.js build failed with code ${code}`)); | ||
| // }); | ||
| // }); | ||
|
|
||
| // // 2. Move Standalone Output to .apphosting | ||
| // const standaloneDir = join(root, ".next", "standalone"); | ||
| // const outputDir = join(root, ".apphosting"); | ||
|
|
||
| // // Clean previous build | ||
| // await fs.remove(outputDir); | ||
| // await fs.ensureDir(outputDir); | ||
|
|
||
| // console.log("📦 Copying standalone server to .apphosting..."); | ||
|
|
||
| // // Copy the standalone directory content to .apphosting | ||
| // // Note: This includes a 'server.js' and 'node_modules' | ||
| // await fs.copy(standaloneDir, outputDir); | ||
|
|
||
| // // Copy the 'public' folder and '.next/static' (Standalone doesn't include these by default!) | ||
| // await fs | ||
| // .copy(join(root, "public"), join(outputDir, "public"), { dereference: true }) | ||
| // .catch(() => {}); | ||
| // await fs.copy(join(root, ".next", "static"), join(outputDir, ".next", "static"), { | ||
| // dereference: true, | ||
| // }); | ||
| // const configSource = join(root, ".next", "firebase-next-config.json"); | ||
| // const configDest = join(outputDir, "firebase-next-config.json"); | ||
|
|
||
| // if (await fs.pathExists(configSource)) { | ||
| // console.log("📦 Copying serialized config..."); | ||
| // await fs.copy(configSource, configDest); | ||
| // } else { | ||
| // console.warn("⚠️ Could not find firebase-next-config.json. Server may fail to start."); | ||
| // } | ||
| // // 3. Bundle OUR Runtime Server | ||
| // // We put our serve.js *next to* the Next.js server.js | ||
| // console.log("📦 Bundling runtime server..."); | ||
| // await build({ | ||
| // entryPoints: [join(__dirname, "serve.js")], | ||
| // bundle: true, | ||
| // platform: "node", | ||
| // format: "cjs", | ||
| // outfile: join(outputDir, "adapter-server.js"), | ||
| // external: ["next", "react", "react-dom"], | ||
| // }); | ||
|
|
||
| // Set standalone mode | ||
| process.env.NEXT_PRIVATE_STANDALONE = "true"; | ||
| // console.log("📦 Generating bundle.yaml..."); | ||
|
|
||
| // const bundle = { | ||
| // version: "v1", | ||
| // runConfig: { | ||
| // // This runs the file we just bundled in step 3 | ||
| // runCommand: "node .apphosting/adapter-server.js", | ||
|
|
||
| // concurrency: 80, | ||
| // cpu: 1, | ||
| // memoryMiB: 512, | ||
| // minInstances: 0, | ||
| // maxInstances: 100, | ||
| // }, | ||
| // metadata: { | ||
| // adapterPackageName: "wei-nextjs-adapter-test", | ||
| // adapterVersion: "15.0.3", | ||
| // frameworkVersion: "16.0.1", | ||
| // framework: "nextjs", | ||
| // }, | ||
| // outputFiles: { | ||
| // serverApp: { | ||
| // include: [".apphosting"], | ||
| // }, | ||
| // }, | ||
| // }; | ||
|
|
||
| // await fs.writeFile(join(outputDir, "bundle.yaml"), stringify(bundle)); | ||
|
|
||
| // console.log("✅ Build complete. Artifacts in .apphosting/"); | ||
| // } | ||
|
|
||
| // main().catch((err) => { | ||
| // console.error(err); | ||
| // process.exit(1); | ||
| // }); | ||
|
|
||
| import { join } from "node:path"; | ||
| // Opt-out sending telemetry to Vercel | ||
| process.env.NEXT_TELEMETRY_DISABLED = "1"; | ||
|
|
||
| checkNextJSVersion(process.env.FRAMEWORK_VERSION); | ||
| process.env.NEXT_ADAPTER_PATH = join(import.meta.dirname, "..", "index.cjs"); | ||
|
|
||
| await runBuild(); | ||
|
|
||
| const opts = getBuildOptions(); | ||
| const root = process.cwd(); | ||
|
|
||
| const nextConfig = await loadConfig(root, opts.projectDirectory); | ||
|
|
||
| /** | ||
| * Override user's Next Config to optimize the app for Firebase App Hosting | ||
| * and validate that the override resulted in a valid config that Next.js can | ||
| * load. | ||
| * | ||
| * We restore the user's Next Config at the end of the build, after the config file has been | ||
| * copied over to the output directory, so that the user's original code is not modified. | ||
| * | ||
| * If the app does not have a next.config.[js|mjs|ts] file in the first place, | ||
| * then can skip config override. | ||
| * | ||
| * Note: loadConfig always returns a fileName (default: next.config.js) even if | ||
| * one does not exist in the app's root: https://github.com/vercel/next.js/blob/23681508ca34b66a6ef55965c5eac57de20eb67f/packages/next/src/server/config.ts#L1115 | ||
| */ | ||
| const nextConfigPath = join(root, nextConfig.configFileName); | ||
| if (await exists(nextConfigPath)) { | ||
| await overrideNextConfig(root, nextConfig.configFileName); | ||
| await validateNextConfigOverride(root, opts.projectDirectory, nextConfig.configFileName); | ||
| } | ||
|
|
||
| try { | ||
| await runBuild(); | ||
|
|
||
| const adapterMetadata = getAdapterMetadata(); | ||
| const nextBuildDirectory = join(opts.projectDirectory, nextConfig.distDir); | ||
| const outputBundleOptions = populateOutputBundleOptions( | ||
| root, | ||
| opts.projectDirectory, | ||
| nextBuildDirectory, | ||
| ); | ||
|
|
||
| await addRouteOverrides( | ||
| outputBundleOptions.outputDirectoryAppPath, | ||
| nextConfig.distDir, | ||
| adapterMetadata, | ||
| ); | ||
|
|
||
| const nextjsVersion = process.env.FRAMEWORK_VERSION || "unspecified"; | ||
| await generateBuildOutput( | ||
| root, | ||
| opts.projectDirectory, | ||
| outputBundleOptions, | ||
| nextBuildDirectory, | ||
| nextjsVersion, | ||
| adapterMetadata, | ||
| ); | ||
| await validateOutputDirectory(outputBundleOptions, nextBuildDirectory); | ||
| } finally { | ||
| await restoreNextConfig(root, nextConfig.configFileName); | ||
| } | ||
| const nextBuildDirectory = join(opts.projectDirectory, nextConfig.distDir); | ||
| const outputBundleOptions = populateOutputBundleOptions( | ||
| root, | ||
| opts.projectDirectory, | ||
| nextBuildDirectory, | ||
| ); | ||
| await generateBuildOutput(root, opts.projectDirectory, outputBundleOptions, nextBuildDirectory); | ||
|
|
||
| await validateOutputDirectory(outputBundleOptions, nextBuildDirectory); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| import { createServer } from "http"; | ||
| import { parse } from "url"; | ||
| import path from "path"; | ||
| import fs from "fs"; | ||
| import { fileURLToPath } from "url"; | ||
| import { createRequire } from "module"; | ||
| import { dirname } from "path"; | ||
| const __filename = fileURLToPath(import.meta.url); | ||
| const require = createRequire(import.meta.url); | ||
| const __dirname = dirname(__filename); | ||
|
|
||
| // 1. SET ENV VARS | ||
| // @ts-ignore | ||
|
Check failure on line 13 in packages/@apphosting/adapter-nextjs/src/bin/serve.ts
|
||
| process.env['NODE_ENV'] = "production"; | ||
| process.env['NEXT_PRIVATE_MINIMAL_MODE'] = "1"; | ||
|
|
||
| async function start() { | ||
| // 1. GET THE APP ROOT | ||
| // The CLI passes the app directory as the first argument (process.argv[2]) | ||
| // If missing, fallback to the current directory (but that usually fails in this setup) | ||
| const serverDir = process.argv[2] || process.cwd(); | ||
|
|
||
| console.log(`> Starting server from: ${serverDir}`); | ||
|
|
||
| // 2. IMPORT NEXT.JS INTERNALS | ||
| const nextMetaPath = require.resolve("next/dist/server/request-meta", { paths: [serverDir] }); | ||
| const { NEXT_REQUEST_META } = require(nextMetaPath); | ||
|
|
||
| let configPath = path.join(serverDir, "output.json"); | ||
|
|
||
| if (!fs.existsSync(configPath)) { | ||
| configPath = path.join(process.cwd(), ".apphosting", "output.json"); | ||
| } | ||
| if (!fs.existsSync(configPath)) { | ||
| console.error(`❌ Config not found at: ${configPath}`); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| const rawConfig = fs.readFileSync(configPath, 'utf-8'); | ||
| const buildContext = JSON.parse(rawConfig); | ||
|
|
||
| // Helper to find the postponed state for a path | ||
| const getPostponedState = (path: string) => { | ||
| let prerender = buildContext.outputs.prerenders.find((it: any) => it.pathname === path); | ||
| if (!prerender) { | ||
| const dynamicMatch = buildContext.routes.dynamicRoutes.find((it: any) => | ||
| path.match(new RegExp(it.sourceRegex)) | ||
| )?.source; | ||
| prerender = buildContext.outputs.prerenders.find((it: any) => it.pathname === dynamicMatch); | ||
| } | ||
| return prerender?.fallback?.postponedState; | ||
| }; | ||
|
|
||
| // 4. SETUP SERVER | ||
| const nextPath = require.resolve("next/dist/server/next-server", { paths: [serverDir] }); | ||
| const NextServer = require(nextPath).default; | ||
|
|
||
| const server = new NextServer({ | ||
| dir: serverDir, | ||
| hostname: '0.0.0.0', | ||
| port: parseInt(process.env.PORT || "8080"), | ||
| conf: buildContext.config, | ||
| }); | ||
|
|
||
| await server.prepare(); | ||
| const requestHandler = server.getRequestHandler(); | ||
|
|
||
| createServer(async (req: any, res: any) => { | ||
| try { | ||
| const parsedUrl = parse(req.url, true); | ||
| const { pathname } = parsedUrl; | ||
|
|
||
| if (req.headers['next-resume'] === '1' && pathname) { | ||
| const postponed = getPostponedState(pathname); | ||
| if (postponed) { | ||
| console.log(`⚡️ Injecting Postponed State for ${pathname}`); | ||
| req[NEXT_REQUEST_META] = { postponed }; | ||
| } | ||
| } | ||
|
|
||
| if (!req.headers['x-matched-path']) { | ||
| req.headers['x-matched-path'] = pathname; | ||
| } | ||
|
|
||
| await requestHandler(req, res, parsedUrl); | ||
| } catch (err) { | ||
| console.error(err); | ||
| res.statusCode = 500; | ||
| res.end("Internal Error"); | ||
| } | ||
| }).listen(parseInt(process.env.PORT || "8080"), () => { | ||
| console.log(`> Ready on http://localhost:${process.env.PORT || 8080}`); | ||
| }); | ||
| } | ||
|
|
||
| start(); | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
fastifydependency was added, but it doesn't appear to be used anywhere in the codebase. The newserve.tsuses Node's built-inhttpmodule. To keep dependencies clean, this unused package should be removed.