@opennextjs/cloudflare 0.0.0-fd3c2b9 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ export * from "./open-next-cache-handler";
@@ -0,0 +1,148 @@
1
+ import type {
2
+ CacheHandler,
3
+ CacheHandlerContext,
4
+ CacheHandlerValue,
5
+ } from "next/dist/server/lib/incremental-cache";
6
+ import {
7
+ NEXT_BODY_SUFFIX,
8
+ NEXT_DATA_SUFFIX,
9
+ NEXT_HTML_SUFFIX,
10
+ RSC_PREFETCH_SUFFIX,
11
+ RSC_SUFFIX,
12
+ SEED_DATA_DIR,
13
+ } from "../../constants/incremental-cache";
14
+ import { getSeedBodyFile, getSeedMetaFile, getSeedTextFile, parseCtx } from "./utils";
15
+ import type { IncrementalCacheValue } from "next/dist/server/response-cache";
16
+ import type { KVNamespace } from "@cloudflare/workers-types";
17
+
18
+ type CacheEntry = {
19
+ lastModified: number;
20
+ value: IncrementalCacheValue | null;
21
+ };
22
+
23
+ export class OpenNextCacheHandler implements CacheHandler {
24
+ protected kv: KVNamespace | undefined;
25
+
26
+ protected debug: boolean = !!process.env.NEXT_PRIVATE_DEBUG_CACHE;
27
+
28
+ constructor(protected ctx: CacheHandlerContext) {
29
+ this.kv = process.env[process.env.__OPENNEXT_KV_BINDING_NAME] as KVNamespace | undefined;
30
+ }
31
+
32
+ async get(...args: Parameters<CacheHandler["get"]>): Promise<CacheHandlerValue | null> {
33
+ const [key, _ctx] = args;
34
+ const ctx = parseCtx(_ctx);
35
+
36
+ if (this.debug) console.log(`cache - get: ${key}, ${ctx?.kind}`);
37
+
38
+ if (this.kv !== undefined) {
39
+ try {
40
+ const value = await this.kv.get<CacheEntry>(key, "json");
41
+ if (value) return value;
42
+ } catch (e) {
43
+ console.error(`Failed to get value for key = ${key}: ${e}`);
44
+ }
45
+ }
46
+
47
+ // Check for seed data from the file-system.
48
+
49
+ // we don't check for seed data for fetch or image cache entries
50
+ if (ctx?.kind === "FETCH" || ctx?.kind === "IMAGE") return null;
51
+
52
+ const seedKey = `http://assets.local/${SEED_DATA_DIR}/${key}`.replace(/\/\//g, "/");
53
+
54
+ if (ctx?.kind === "APP" || ctx?.kind === "APP_ROUTE") {
55
+ const fallbackBody = await getSeedBodyFile(seedKey, NEXT_BODY_SUFFIX);
56
+ if (fallbackBody) {
57
+ const meta = await getSeedMetaFile(seedKey);
58
+ return {
59
+ lastModified: meta?.lastModified,
60
+ value: {
61
+ kind: (ctx.kind === "APP_ROUTE" ? ctx.kind : "ROUTE") as Extract<
62
+ IncrementalCacheValue["kind"],
63
+ "ROUTE"
64
+ >,
65
+ body: fallbackBody,
66
+ status: meta?.status ?? 200,
67
+ headers: meta?.headers ?? {},
68
+ },
69
+ };
70
+ }
71
+
72
+ if (ctx.kind === "APP_ROUTE") {
73
+ return null;
74
+ }
75
+ }
76
+
77
+ const seedHtml = await getSeedTextFile(seedKey, NEXT_HTML_SUFFIX);
78
+ if (!seedHtml) return null; // we're only checking for prerendered routes at the moment
79
+
80
+ if (ctx?.kind === "PAGES" || ctx?.kind === "APP" || ctx?.kind === "APP_PAGE") {
81
+ const metaPromise = getSeedMetaFile(seedKey);
82
+
83
+ let pageDataPromise: Promise<Buffer | string | undefined> = Promise.resolve(undefined);
84
+ if (!ctx.isFallback) {
85
+ const rscSuffix = ctx.isRoutePPREnabled ? RSC_PREFETCH_SUFFIX : RSC_SUFFIX;
86
+
87
+ if (ctx.kind === "APP_PAGE") {
88
+ pageDataPromise = getSeedBodyFile(seedKey, rscSuffix);
89
+ } else {
90
+ pageDataPromise = getSeedTextFile(seedKey, ctx.kind === "APP" ? rscSuffix : NEXT_DATA_SUFFIX);
91
+ }
92
+ }
93
+
94
+ const [meta, pageData] = await Promise.all([metaPromise, pageDataPromise]);
95
+
96
+ return {
97
+ lastModified: meta?.lastModified,
98
+ value: {
99
+ kind: (ctx.kind === "APP_PAGE" ? "APP_PAGE" : "PAGE") as Extract<
100
+ IncrementalCacheValue["kind"],
101
+ "PAGE"
102
+ >,
103
+ html: seedHtml,
104
+ pageData: pageData ?? "",
105
+ ...(ctx.kind === "APP_PAGE" && { rscData: pageData }),
106
+ postponed: meta?.postponed,
107
+ status: meta?.status,
108
+ headers: meta?.headers,
109
+ },
110
+ };
111
+ }
112
+
113
+ return null;
114
+ }
115
+
116
+ async set(...args: Parameters<CacheHandler["set"]>) {
117
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
118
+ const [key, entry, _ctx] = args;
119
+
120
+ if (this.kv === undefined) {
121
+ return;
122
+ }
123
+
124
+ if (this.debug) console.log(`cache - set: ${key}`);
125
+
126
+ const data: CacheEntry = {
127
+ lastModified: Date.now(),
128
+ value: entry,
129
+ };
130
+
131
+ try {
132
+ await this.kv.put(key, JSON.stringify(data));
133
+ } catch (e) {
134
+ console.error(`Failed to set value for key = ${key}: ${e}`);
135
+ }
136
+ }
137
+
138
+ async revalidateTag(...args: Parameters<CacheHandler["revalidateTag"]>) {
139
+ const [tags] = args;
140
+ if (this.kv === undefined) {
141
+ return;
142
+ }
143
+
144
+ if (this.debug) console.log(`cache - revalidateTag: ${JSON.stringify([tags].flat())}`);
145
+ }
146
+
147
+ resetRequestCache(): void {}
148
+ }
@@ -0,0 +1,41 @@
1
+ import type { IncrementalCache } from "next/dist/server/lib/incremental-cache";
2
+ import { NEXT_META_SUFFIX } from "../../constants/incremental-cache";
3
+
4
+ type PrerenderedRouteMeta = {
5
+ lastModified: number;
6
+ status?: number;
7
+ headers?: Record<string, string>;
8
+ postponed?: string;
9
+ };
10
+
11
+ type EntryKind =
12
+ | "APP" // .body, .html - backwards compat
13
+ | "PAGES"
14
+ | "FETCH"
15
+ | "APP_ROUTE" // .body
16
+ | "APP_PAGE" // .html
17
+ | "IMAGE"
18
+ | undefined;
19
+
20
+ async function getAsset<T>(key: string, cb: (resp: Response) => T): Promise<Awaited<T> | undefined> {
21
+ const resp = await process.env.ASSETS.fetch(key);
22
+ return resp.status === 200 ? await cb(resp) : undefined;
23
+ }
24
+
25
+ export function getSeedBodyFile(key: string, suffix: string) {
26
+ return getAsset(key + suffix, (resp) => resp.arrayBuffer() as Promise<Buffer>);
27
+ }
28
+
29
+ export function getSeedTextFile(key: string, suffix: string) {
30
+ return getAsset(key + suffix, (resp) => resp.text());
31
+ }
32
+
33
+ export function getSeedMetaFile(key: string) {
34
+ return getAsset(key + NEXT_META_SUFFIX, (resp) => resp.json<PrerenderedRouteMeta>());
35
+ }
36
+
37
+ export function parseCtx(ctx: Parameters<IncrementalCache["get"]>[1] = {}) {
38
+ return { ...ctx, kind: ctx?.kindHint?.toUpperCase() } as
39
+ | (typeof ctx & { kind?: EntryKind; isFallback?: boolean; isRoutePPREnabled?: boolean })
40
+ | undefined;
41
+ }
@@ -17,7 +17,7 @@ function existsSync(path: string) {
17
17
  return FILES.has(path);
18
18
  }
19
19
 
20
- async function readFile(path: string, options: unknown): Promise<any> {
20
+ async function readFile(path: string, options: unknown): Promise<unknown> {
21
21
  console.log(
22
22
  "readFile",
23
23
  { path, options }
@@ -0,0 +1,156 @@
1
+ import type { ExportedHandler, Fetcher } from "@cloudflare/workers-types";
2
+ import { NodeNextRequest, NodeNextResponse } from "next/dist/server/base-http/node";
3
+ import { AsyncLocalStorage } from "node:async_hooks";
4
+ import type { CloudflareContext } from "../../api";
5
+ import type { IncomingMessage } from "node:http";
6
+ import { MockedResponse } from "next/dist/server/lib/mock-request";
7
+ import type { NextConfig } from "next";
8
+ import type { NodeRequestHandler } from "next/dist/server/next-server";
9
+ import Stream from "node:stream";
10
+
11
+ const NON_BODY_RESPONSES = new Set([101, 204, 205, 304]);
12
+
13
+ const cloudflareContextALS = new AsyncLocalStorage<CloudflareContext>();
14
+
15
+ // Note: this symbol needs to be kept in sync with the one defined in `src/api/get-cloudflare-context.ts`
16
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
17
+ (globalThis as any)[Symbol.for("__cloudflare-context__")] = new Proxy(
18
+ {},
19
+ {
20
+ ownKeys: () => Reflect.ownKeys(cloudflareContextALS.getStore()!),
21
+ getOwnPropertyDescriptor: (_, ...args) =>
22
+ Reflect.getOwnPropertyDescriptor(cloudflareContextALS.getStore()!, ...args),
23
+ get: (_, property) => Reflect.get(cloudflareContextALS.getStore()!, property),
24
+ set: (_, property, value) => Reflect.set(cloudflareContextALS.getStore()!, property, value),
25
+ }
26
+ );
27
+
28
+ // Injected at build time
29
+ const nextConfig: NextConfig = JSON.parse(process.env.__NEXT_PRIVATE_STANDALONE_CONFIG ?? "{}");
30
+
31
+ let requestHandler: NodeRequestHandler | null = null;
32
+
33
+ export default {
34
+ async fetch(request, env, ctx) {
35
+ return cloudflareContextALS.run({ env, ctx, cf: request.cf }, async () => {
36
+ if (requestHandler == null) {
37
+ globalThis.process.env = { ...globalThis.process.env, ...env };
38
+ // Note: "next/dist/server/next-server" is a cjs module so we have to `require` it not to confuse esbuild
39
+ // (since esbuild can run in projects with different module resolutions)
40
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
41
+ const NextNodeServer = require("next/dist/server/next-server")
42
+ .default as typeof import("next/dist/server/next-server").default;
43
+
44
+ requestHandler = new NextNodeServer({
45
+ conf: nextConfig,
46
+ customServer: false,
47
+ dev: false,
48
+ dir: "",
49
+ minimalMode: false,
50
+ }).getRequestHandler();
51
+ }
52
+
53
+ const url = new URL(request.url);
54
+
55
+ if (url.pathname === "/_next/image") {
56
+ const imageUrl =
57
+ url.searchParams.get("url") ?? "https://developers.cloudflare.com/_astro/logo.BU9hiExz.svg";
58
+ if (imageUrl.startsWith("/")) {
59
+ return env.ASSETS.fetch(new URL(imageUrl, request.url));
60
+ }
61
+ return fetch(imageUrl, { cf: { cacheEverything: true } });
62
+ }
63
+
64
+ const { req, res, webResponse } = getWrappedStreams(request, ctx);
65
+
66
+ ctx.waitUntil(Promise.resolve(requestHandler(new NodeNextRequest(req), new NodeNextResponse(res))));
67
+
68
+ return await webResponse();
69
+ });
70
+ },
71
+ } as ExportedHandler<{ ASSETS: Fetcher }>;
72
+
73
+ function getWrappedStreams(request: Request, ctx: ExecutionContext) {
74
+ const url = new URL(request.url);
75
+
76
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
77
+ const reqBody = request.body && Stream.Readable.fromWeb(request.body as any);
78
+ const req = (reqBody ?? Stream.Readable.from([])) as IncomingMessage;
79
+ req.httpVersion = "1.0";
80
+ req.httpVersionMajor = 1;
81
+ req.httpVersionMinor = 0;
82
+ req.url = url.href.slice(url.origin.length);
83
+ req.headers = Object.fromEntries([...request.headers]);
84
+ req.method = request.method;
85
+ Object.defineProperty(req, "__node_stream__", {
86
+ value: true,
87
+ writable: false,
88
+ });
89
+ Object.defineProperty(req, "headersDistinct", {
90
+ get() {
91
+ const headers: Record<string, string[]> = {};
92
+ for (const [key, value] of Object.entries(req.headers)) {
93
+ if (!value) continue;
94
+ headers[key] = Array.isArray(value) ? value : [value];
95
+ }
96
+ return headers;
97
+ },
98
+ });
99
+
100
+ const { readable, writable } = new IdentityTransformStream();
101
+ const resBodyWriter = writable.getWriter();
102
+
103
+ const res = new MockedResponse({
104
+ resWriter: (chunk) => {
105
+ resBodyWriter.write(typeof chunk === "string" ? Buffer.from(chunk) : chunk).catch((err) => {
106
+ if (
107
+ err.message.includes("WritableStream has been closed") ||
108
+ err.message.includes("Network connection lost")
109
+ ) {
110
+ // safe to ignore
111
+ return;
112
+ }
113
+ console.error("Error in resBodyWriter.write");
114
+ console.error(err);
115
+ });
116
+ return true;
117
+ },
118
+ });
119
+
120
+ // It's implemented as a no-op, but really it should mark the headers as done
121
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
122
+ res.flushHeaders = () => (res as any).headPromiseResolve();
123
+
124
+ // Only allow statusCode to be modified if not sent
125
+ let { statusCode } = res;
126
+ Object.defineProperty(res, "statusCode", {
127
+ get: function () {
128
+ return statusCode;
129
+ },
130
+ set: function (val) {
131
+ if (this.finished || this.headersSent) {
132
+ return;
133
+ }
134
+ statusCode = val;
135
+ },
136
+ });
137
+
138
+ // Make sure the writer is eventually closed
139
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
140
+ ctx.waitUntil((res as any).hasStreamed.finally(() => resBodyWriter.close().catch(() => {})));
141
+
142
+ return {
143
+ res,
144
+ req,
145
+ webResponse: async () => {
146
+ await res.headPromise;
147
+ // TODO: remove this once streaming with compression is working nicely
148
+ res.setHeader("content-encoding", "identity");
149
+ return new Response(NON_BODY_RESPONSES.has(res.statusCode) ? null : readable, {
150
+ status: res.statusCode,
151
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
152
+ headers: (res as any).headers,
153
+ });
154
+ },
155
+ };
156
+ }
package/package.json CHANGED
@@ -1,16 +1,24 @@
1
1
  {
2
2
  "name": "@opennextjs/cloudflare",
3
3
  "description": "Cloudflare builder for next apps",
4
- "version": "0.0.0-fd3c2b9",
5
- "bin": "dist/index.mjs",
4
+ "version": "0.1.0",
5
+ "bin": "dist/cli/index.mjs",
6
+ "main": "./dist/api/index.mjs",
7
+ "types": "./dist/api/index.d.mts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/api/index.mjs",
11
+ "types": "./dist/api/index.d.mts"
12
+ }
13
+ },
6
14
  "files": [
7
15
  "README.md",
8
16
  "dist"
9
17
  ],
10
18
  "repository": {
11
19
  "type": "git",
12
- "url": "https://github.com/flarelabs-net/poc-next.git",
13
- "directory": "builder"
20
+ "url": "https://github.com/opennextjs/opennextjs-cloudflare.git",
21
+ "directory": "packages/cloudflare"
14
22
  },
15
23
  "keywords": [
16
24
  "cloudflare",
@@ -19,23 +27,38 @@
19
27
  ],
20
28
  "license": "MIT",
21
29
  "bugs": {
22
- "url": "https://github.com/flarelabs-net/poc-next/issues"
30
+ "url": "https://github.com/opennextjs/opennextjs-cloudflare/issues"
23
31
  },
24
- "homepage": "https://github.com/flarelabs-net/poc-next",
32
+ "homepage": "https://github.com/opennextjs/opennextjs-cloudflare",
25
33
  "devDependencies": {
34
+ "@cloudflare/workers-types": "^4.20240925.0",
35
+ "@eslint/js": "^9.11.1",
36
+ "@tsconfig/strictest": "^2.0.5",
26
37
  "@types/node": "^22.2.0",
27
38
  "esbuild": "^0.23.0",
39
+ "eslint": "^9.11.1",
40
+ "eslint-plugin-unicorn": "^55.0.0",
28
41
  "glob": "^11.0.0",
42
+ "globals": "^15.9.0",
43
+ "next": "14.2.11",
44
+ "package-manager-detector": "^0.2.0",
29
45
  "tsup": "^8.2.4",
30
46
  "typescript": "^5.5.4",
47
+ "typescript-eslint": "^8.7.0",
31
48
  "vitest": "^2.1.1"
32
49
  },
33
50
  "dependencies": {
34
51
  "ts-morph": "^23.0.0"
35
52
  },
53
+ "peerDependencies": {
54
+ "wrangler": "^3.78.10"
55
+ },
36
56
  "scripts": {
37
57
  "build": "tsup",
38
58
  "build:watch": "tsup --watch src",
59
+ "lint:check": "eslint",
60
+ "lint:fix": "eslint --fix",
61
+ "ts:check": "tsc --noEmit",
39
62
  "test": "vitest --run",
40
63
  "test:watch": "vitest"
41
64
  }
@@ -1,128 +0,0 @@
1
- import Stream from "node:stream";
2
- import type { NextConfig } from "next";
3
- import { NodeNextRequest, NodeNextResponse } from "next/dist/server/base-http/node";
4
- import { MockedResponse } from "next/dist/server/lib/mock-request";
5
- import NextNodeServer, { NodeRequestHandler } from "next/dist/server/next-server";
6
- import type { IncomingMessage } from "node:http";
7
-
8
- const NON_BODY_RESPONSES = new Set([101, 204, 205, 304]);
9
-
10
- // Injected at build time
11
- const nextConfig: NextConfig = JSON.parse(process.env.__NEXT_PRIVATE_STANDALONE_CONFIG ?? "{}");
12
-
13
- let requestHandler: NodeRequestHandler | null = null;
14
-
15
- export default {
16
- async fetch(request: Request, env: any, ctx: any) {
17
- if (requestHandler == null) {
18
- globalThis.process.env = { ...globalThis.process.env, ...env };
19
- requestHandler = new NextNodeServer({
20
- conf: { ...nextConfig, env },
21
- customServer: false,
22
- dev: false,
23
- dir: "",
24
- minimalMode: false,
25
- }).getRequestHandler();
26
- }
27
-
28
- const url = new URL(request.url);
29
-
30
- if (url.pathname === "/_next/image") {
31
- let imageUrl =
32
- url.searchParams.get("url") ?? "https://developers.cloudflare.com/_astro/logo.BU9hiExz.svg";
33
- if (imageUrl.startsWith("/")) {
34
- return env.ASSETS.fetch(new URL(imageUrl, request.url));
35
- }
36
- return fetch(imageUrl, { cf: { cacheEverything: true } } as any);
37
- }
38
-
39
- const { req, res, webResponse } = getWrappedStreams(request, ctx);
40
-
41
- ctx.waitUntil(requestHandler(new NodeNextRequest(req), new NodeNextResponse(res)));
42
-
43
- return await webResponse();
44
- },
45
- };
46
-
47
- function getWrappedStreams(request: Request, ctx: any) {
48
- const url = new URL(request.url);
49
-
50
- const req = (
51
- request.body ? Stream.Readable.fromWeb(request.body as any) : Stream.Readable.from([])
52
- ) as IncomingMessage;
53
- req.httpVersion = "1.0";
54
- req.httpVersionMajor = 1;
55
- req.httpVersionMinor = 0;
56
- req.url = url.href.slice(url.origin.length);
57
- req.headers = Object.fromEntries([...request.headers]);
58
- req.method = request.method;
59
- Object.defineProperty(req, "__node_stream__", {
60
- value: true,
61
- writable: false,
62
- });
63
- Object.defineProperty(req, "headersDistinct", {
64
- get() {
65
- const headers: Record<string, string[]> = {};
66
- for (const [key, value] of Object.entries(req.headers)) {
67
- if (!value) continue;
68
- headers[key] = Array.isArray(value) ? value : [value];
69
- }
70
- return headers;
71
- },
72
- });
73
-
74
- const { readable, writable } = new IdentityTransformStream();
75
- const resBodyWriter = writable.getWriter();
76
-
77
- const res = new MockedResponse({
78
- resWriter: (chunk) => {
79
- resBodyWriter.write(typeof chunk === "string" ? Buffer.from(chunk) : chunk).catch((err: any) => {
80
- if (
81
- err.message.includes("WritableStream has been closed") ||
82
- err.message.includes("Network connection lost")
83
- ) {
84
- // safe to ignore
85
- return;
86
- }
87
- console.error("Error in resBodyWriter.write");
88
- console.error(err);
89
- });
90
- return true;
91
- },
92
- });
93
-
94
- // It's implemented as a no-op, but really it should mark the headers as done
95
- res.flushHeaders = () => (res as any).headPromiseResolve();
96
-
97
- // Only allow statusCode to be modified if not sent
98
- let { statusCode } = res;
99
- Object.defineProperty(res, "statusCode", {
100
- get: function () {
101
- return statusCode;
102
- },
103
- set: function (val) {
104
- if (this.finished || this.headersSent) {
105
- console.error("headers already sent");
106
- return;
107
- }
108
- statusCode = val;
109
- },
110
- });
111
-
112
- // Make sure the writer is eventually closed
113
- ctx.waitUntil((res as any).hasStreamed.finally(() => resBodyWriter.close().catch(() => {})));
114
-
115
- return {
116
- res,
117
- req,
118
- webResponse: async () => {
119
- await res.headPromise;
120
- // TODO: remove this once streaming with compression is working nicely
121
- res.setHeader("content-encoding", "identity");
122
- return new Response(NON_BODY_RESPONSES.has(res.statusCode) ? null : readable, {
123
- status: res.statusCode,
124
- headers: (res as any).headers,
125
- });
126
- },
127
- };
128
- }
File without changes