vinext 0.0.32 → 0.0.34
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.
- package/README.md +7 -6
- package/dist/config/next-config.d.ts +2 -0
- package/dist/config/next-config.js +4 -0
- package/dist/config/next-config.js.map +1 -1
- package/dist/deploy.js +52 -4
- package/dist/deploy.js.map +1 -1
- package/dist/entries/app-browser-entry.js +3 -330
- package/dist/entries/app-browser-entry.js.map +1 -1
- package/dist/entries/app-rsc-entry.js +444 -1265
- package/dist/entries/app-rsc-entry.js.map +1 -1
- package/dist/entries/app-ssr-entry.js +4 -460
- package/dist/entries/app-ssr-entry.js.map +1 -1
- package/dist/entries/pages-server-entry.js +8 -1
- package/dist/entries/pages-server-entry.js.map +1 -1
- package/dist/entries/runtime-entry-module.d.ts +13 -0
- package/dist/entries/runtime-entry-module.js +27 -0
- package/dist/entries/runtime-entry-module.js.map +1 -0
- package/dist/index.js +302 -23
- package/dist/index.js.map +1 -1
- package/dist/plugins/optimize-imports.d.ts +38 -0
- package/dist/plugins/optimize-imports.js +557 -0
- package/dist/plugins/optimize-imports.js.map +1 -0
- package/dist/server/app-browser-entry.d.ts +1 -0
- package/dist/server/app-browser-entry.js +160 -0
- package/dist/server/app-browser-entry.js.map +1 -0
- package/dist/server/app-browser-stream.d.ts +33 -0
- package/dist/server/app-browser-stream.js +54 -0
- package/dist/server/app-browser-stream.js.map +1 -0
- package/dist/server/app-page-boundary-render.d.ts +63 -0
- package/dist/server/app-page-boundary-render.js +182 -0
- package/dist/server/app-page-boundary-render.js.map +1 -0
- package/dist/server/app-page-boundary.d.ts +57 -0
- package/dist/server/app-page-boundary.js +60 -0
- package/dist/server/app-page-boundary.js.map +1 -0
- package/dist/server/app-page-cache.d.ts +61 -0
- package/dist/server/app-page-cache.js +133 -0
- package/dist/server/app-page-cache.js.map +1 -0
- package/dist/server/app-page-execution.d.ts +46 -0
- package/dist/server/app-page-execution.js +109 -0
- package/dist/server/app-page-execution.js.map +1 -0
- package/dist/server/app-page-probe.d.ts +17 -0
- package/dist/server/app-page-probe.js +35 -0
- package/dist/server/app-page-probe.js.map +1 -0
- package/dist/server/app-page-render.d.ts +59 -0
- package/dist/server/app-page-render.js +174 -0
- package/dist/server/app-page-render.js.map +1 -0
- package/dist/server/app-page-request.d.ts +58 -0
- package/dist/server/app-page-request.js +79 -0
- package/dist/server/app-page-request.js.map +1 -0
- package/dist/server/app-page-response.d.ts +51 -0
- package/dist/server/app-page-response.js +90 -0
- package/dist/server/app-page-response.js.map +1 -0
- package/dist/server/app-page-stream.d.ts +55 -0
- package/dist/server/app-page-stream.js +65 -0
- package/dist/server/app-page-stream.js.map +1 -0
- package/dist/server/app-route-handler-cache.d.ts +42 -0
- package/dist/server/app-route-handler-cache.js +69 -0
- package/dist/server/app-route-handler-cache.js.map +1 -0
- package/dist/server/app-route-handler-execution.d.ts +64 -0
- package/dist/server/app-route-handler-execution.js +100 -0
- package/dist/server/app-route-handler-execution.js.map +1 -0
- package/dist/server/app-route-handler-policy.d.ts +51 -0
- package/dist/server/app-route-handler-policy.js +57 -0
- package/dist/server/app-route-handler-policy.js.map +1 -0
- package/dist/server/app-route-handler-response.d.ts +26 -0
- package/dist/server/app-route-handler-response.js +61 -0
- package/dist/server/app-route-handler-response.js.map +1 -0
- package/dist/server/app-route-handler-runtime.d.ts +27 -0
- package/dist/server/app-route-handler-runtime.js +99 -0
- package/dist/server/app-route-handler-runtime.js.map +1 -0
- package/dist/server/app-ssr-entry.d.ts +19 -0
- package/dist/server/app-ssr-entry.js +105 -0
- package/dist/server/app-ssr-entry.js.map +1 -0
- package/dist/server/app-ssr-stream.d.ts +30 -0
- package/dist/server/app-ssr-stream.js +116 -0
- package/dist/server/app-ssr-stream.js.map +1 -0
- package/dist/server/prod-server.d.ts +13 -1
- package/dist/server/prod-server.js +113 -19
- package/dist/server/prod-server.js.map +1 -1
- package/dist/server/worker-utils.d.ts +0 -6
- package/dist/server/worker-utils.js +41 -5
- package/dist/server/worker-utils.js.map +1 -1
- package/dist/shims/error-boundary.js +1 -1
- package/dist/shims/font-google-base.js +1 -1
- package/dist/shims/font-google-base.js.map +1 -1
- package/dist/shims/font-google.d.ts +2 -3
- package/dist/shims/font-google.js +2 -3
- package/dist/shims/metadata.js +3 -3
- package/dist/shims/metadata.js.map +1 -1
- package/dist/shims/request-state-types.d.ts +2 -2
- package/dist/shims/unified-request-context.d.ts +1 -1
- package/package.json +1 -1
- package/dist/shims/font-google.generated.d.ts +0 -1929
- package/dist/shims/font-google.generated.js +0 -1929
- package/dist/shims/font-google.generated.js.map +0 -1
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { resolveRuntimeEntryModule } from "./runtime-entry-module.js";
|
|
1
2
|
//#region src/entries/app-ssr-entry.ts
|
|
2
3
|
/**
|
|
3
4
|
* Generate the virtual SSR entry module.
|
|
@@ -11,468 +12,11 @@
|
|
|
11
12
|
* metadata (including `getStaticPaths`) via `import("./ssr/index.js")`.
|
|
12
13
|
*/
|
|
13
14
|
function generateSsrEntry(hasPagesDir = false) {
|
|
15
|
+
const entryPath = resolveRuntimeEntryModule("app-ssr-entry");
|
|
14
16
|
return `
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
import { setNavigationContext, ServerInsertedHTMLContext } from "next/navigation";
|
|
18
|
-
import { runWithNavigationContext as _runWithNavCtx } from "vinext/navigation-state";
|
|
19
|
-
import { safeJsonStringify } from "vinext/html";
|
|
20
|
-
import { createElement as _ssrCE } from "react";
|
|
21
|
-
import * as _clientRefs from "virtual:vite-rsc/client-references";
|
|
22
|
-
|
|
23
|
-
let _clientRefsPreloaded = false;
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* Collect all chunks from a ReadableStream into an array of text strings.
|
|
27
|
-
* Used to capture the RSC payload for embedding in HTML.
|
|
28
|
-
* The RSC flight protocol is text-based (line-delimited key:value pairs),
|
|
29
|
-
* so we decode to text strings instead of byte arrays — this is dramatically
|
|
30
|
-
* more compact when JSON-serialized into inline <script> tags.
|
|
31
|
-
*/
|
|
32
|
-
async function collectStreamChunks(stream) {
|
|
33
|
-
const reader = stream.getReader();
|
|
34
|
-
const decoder = new TextDecoder();
|
|
35
|
-
const chunks = [];
|
|
36
|
-
while (true) {
|
|
37
|
-
const { done, value } = await reader.read();
|
|
38
|
-
if (done) break;
|
|
39
|
-
// Decode Uint8Array to text string for compact JSON serialization
|
|
40
|
-
chunks.push(decoder.decode(value, { stream: true }));
|
|
41
|
-
}
|
|
42
|
-
return chunks;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
// React 19 dev-mode workaround (see VinextFlightRoot in handleSsr):
|
|
46
|
-
//
|
|
47
|
-
// In dev, Flight error decoding in react-server-dom-webpack/client.edge
|
|
48
|
-
// can hit resolveErrorDev() which (via React's dev error stack capture)
|
|
49
|
-
// expects a non-null hooks dispatcher.
|
|
50
|
-
//
|
|
51
|
-
// Vinext previously called createFromReadableStream() outside of any React render.
|
|
52
|
-
// When an RSC stream contains an error, dev-mode decoding could crash with:
|
|
53
|
-
// - "Invalid hook call"
|
|
54
|
-
// - "Cannot read properties of null (reading 'useContext')"
|
|
55
|
-
//
|
|
56
|
-
// Fix: call createFromReadableStream() lazily inside a React component render.
|
|
57
|
-
// This mirrors Next.js behavior and ensures the dispatcher is set.
|
|
58
|
-
|
|
59
|
-
/**
|
|
60
|
-
* Create a TransformStream that appends RSC chunks as inline <script> tags
|
|
61
|
-
* to the HTML stream. This allows progressive hydration — the browser receives
|
|
62
|
-
* RSC data incrementally as Suspense boundaries resolve, rather than waiting
|
|
63
|
-
* for the entire RSC payload before hydration can begin.
|
|
64
|
-
*
|
|
65
|
-
* Each chunk is written as:
|
|
66
|
-
* <script>self.__VINEXT_RSC_CHUNKS__=self.__VINEXT_RSC_CHUNKS__||[];self.__VINEXT_RSC_CHUNKS__.push("...")<\/script>
|
|
67
|
-
*
|
|
68
|
-
* Chunks are embedded as text strings (not byte arrays) since the RSC flight
|
|
69
|
-
* protocol is text-based. The browser entry encodes them back to Uint8Array.
|
|
70
|
-
* This is ~3x more compact than the previous byte-array format.
|
|
71
|
-
*/
|
|
72
|
-
function createRscEmbedTransform(embedStream) {
|
|
73
|
-
const reader = embedStream.getReader();
|
|
74
|
-
const _decoder = new TextDecoder();
|
|
75
|
-
let done = false;
|
|
76
|
-
let pendingChunks = [];
|
|
77
|
-
let reading = false;
|
|
78
|
-
|
|
79
|
-
// Start reading RSC chunks in the background, accumulating them as text strings.
|
|
80
|
-
// The RSC flight protocol is text-based, so decoding to strings and embedding
|
|
81
|
-
// as JSON strings is ~3x more compact than the byte-array format.
|
|
82
|
-
//
|
|
83
|
-
// Note: Flight HL hint "stylesheet" → "style" rewriting is handled upstream
|
|
84
|
-
// in the renderToReadableStream wrapper (app-rsc-entry.ts), so the stream
|
|
85
|
-
// arriving here is already clean.
|
|
86
|
-
async function pumpReader() {
|
|
87
|
-
if (reading) return;
|
|
88
|
-
reading = true;
|
|
89
|
-
try {
|
|
90
|
-
while (true) {
|
|
91
|
-
const result = await reader.read();
|
|
92
|
-
if (result.done) {
|
|
93
|
-
done = true;
|
|
94
|
-
break;
|
|
95
|
-
}
|
|
96
|
-
const text = _decoder.decode(result.value, { stream: true });
|
|
97
|
-
pendingChunks.push(text);
|
|
98
|
-
}
|
|
99
|
-
} catch (err) {
|
|
100
|
-
if (process.env.NODE_ENV !== "production") {
|
|
101
|
-
console.warn("[vinext] RSC embed stream read error:", err);
|
|
102
|
-
}
|
|
103
|
-
done = true;
|
|
104
|
-
}
|
|
105
|
-
reading = false;
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
// Fire off the background reader immediately
|
|
109
|
-
const pumpPromise = pumpReader();
|
|
110
|
-
|
|
111
|
-
return {
|
|
112
|
-
/**
|
|
113
|
-
* Flush any accumulated RSC chunks as <script> tags.
|
|
114
|
-
* Called after each HTML chunk is enqueued.
|
|
115
|
-
*/
|
|
116
|
-
flush() {
|
|
117
|
-
if (pendingChunks.length === 0) return "";
|
|
118
|
-
const chunks = pendingChunks;
|
|
119
|
-
pendingChunks = [];
|
|
120
|
-
let scripts = "";
|
|
121
|
-
for (const chunk of chunks) {
|
|
122
|
-
scripts += "<script>self.__VINEXT_RSC_CHUNKS__=self.__VINEXT_RSC_CHUNKS__||[];self.__VINEXT_RSC_CHUNKS__.push(" + safeJsonStringify(chunk) + ")<\/script>";
|
|
123
|
-
}
|
|
124
|
-
return scripts;
|
|
125
|
-
},
|
|
126
|
-
|
|
127
|
-
/**
|
|
128
|
-
* Wait for the RSC stream to fully complete and return any final
|
|
129
|
-
* script tags plus the closing signal.
|
|
130
|
-
*/
|
|
131
|
-
async finalize() {
|
|
132
|
-
await pumpPromise;
|
|
133
|
-
let scripts = this.flush();
|
|
134
|
-
// Signal that all RSC chunks have been sent.
|
|
135
|
-
// Params are already embedded in <head> — no need to include here.
|
|
136
|
-
scripts += "<script>self.__VINEXT_RSC_DONE__=true<\/script>";
|
|
137
|
-
return scripts;
|
|
138
|
-
},
|
|
139
|
-
};
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
/**
|
|
143
|
-
* Render the RSC stream to HTML.
|
|
144
|
-
*
|
|
145
|
-
* @param rscStream - The RSC payload stream from the RSC environment
|
|
146
|
-
* @param navContext - Navigation context for client component SSR hooks.
|
|
147
|
-
* "use client" components like those using usePathname() need the current
|
|
148
|
-
* request URL during SSR, and they run in this SSR environment (separate
|
|
149
|
-
* from the RSC environment where the context was originally set).
|
|
150
|
-
* @param fontData - Font links and styles collected from the RSC environment.
|
|
151
|
-
* Fonts are loaded during RSC rendering (when layout calls Geist() etc.),
|
|
152
|
-
* and the data needs to be passed to SSR since they're separate module instances.
|
|
153
|
-
*/
|
|
154
|
-
export async function handleSsr(rscStream, navContext, fontData) {
|
|
155
|
-
// Eagerly preload all client reference modules before SSR rendering.
|
|
156
|
-
// On the first request after server start, client component modules are
|
|
157
|
-
// loaded lazily via async import(). Without this preload, React's
|
|
158
|
-
// renderToReadableStream rejects because the shell can't resolve client
|
|
159
|
-
// components synchronously (there is no Suspense boundary wrapping the
|
|
160
|
-
// root). The memoized require cache ensures this is only async on the
|
|
161
|
-
// very first call; subsequent requests resolve from cache immediately.
|
|
162
|
-
// See: https://github.com/cloudflare/vinext/issues/256
|
|
163
|
-
// _clientRefs.default is the default export from the virtual:vite-rsc/client-references
|
|
164
|
-
// namespace import — a map of client component IDs to their async import functions.
|
|
165
|
-
if (!_clientRefsPreloaded && _clientRefs.default && globalThis.__vite_rsc_client_require__) {
|
|
166
|
-
await Promise.all(
|
|
167
|
-
Object.keys(_clientRefs.default).map((id) =>
|
|
168
|
-
globalThis.__vite_rsc_client_require__(id).catch((err) => {
|
|
169
|
-
if (process.env.NODE_ENV !== "production") {
|
|
170
|
-
console.warn("[vinext] failed to preload client ref:", id, err);
|
|
171
|
-
}
|
|
172
|
-
})
|
|
173
|
-
)
|
|
174
|
-
);
|
|
175
|
-
_clientRefsPreloaded = true;
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
// Wrap in a navigation ALS scope for per-request isolation in the SSR
|
|
179
|
-
// environment. The SSR environment has separate module instances from RSC,
|
|
180
|
-
// so it needs its own ALS scope.
|
|
181
|
-
return _runWithNavCtx(async () => {
|
|
182
|
-
// Set navigation context so hooks like usePathname() work during SSR
|
|
183
|
-
// of "use client" components
|
|
184
|
-
if (navContext) {
|
|
185
|
-
setNavigationContext(navContext);
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
// Clear any stale callbacks from previous requests
|
|
189
|
-
const { clearServerInsertedHTML, flushServerInsertedHTML, useServerInsertedHTML: _addInsertedHTML } = await import("next/navigation");
|
|
190
|
-
clearServerInsertedHTML();
|
|
191
|
-
|
|
192
|
-
try {
|
|
193
|
-
// Tee the RSC stream - one for SSR rendering, one for embedding in HTML.
|
|
194
|
-
// This ensures the browser uses the SAME RSC payload for hydration that
|
|
195
|
-
// was used to generate the HTML, avoiding hydration mismatches (React #418).
|
|
196
|
-
const [ssrStream, embedStream] = rscStream.tee();
|
|
197
|
-
|
|
198
|
-
// Create the progressive RSC embed helper — it reads the embed stream
|
|
199
|
-
// in the background and provides script tags to inject into the HTML stream.
|
|
200
|
-
const rscEmbed = createRscEmbedTransform(embedStream);
|
|
201
|
-
|
|
202
|
-
// Deserialize RSC stream back to React VDOM.
|
|
203
|
-
// IMPORTANT: Do NOT await this — createFromReadableStream returns a thenable
|
|
204
|
-
// that React's renderToReadableStream can consume progressively. By passing
|
|
205
|
-
// the unresolved thenable, React will render Suspense fallbacks (loading.tsx)
|
|
206
|
-
// immediately in the HTML shell, then stream in resolved content as RSC
|
|
207
|
-
// chunks arrive. Awaiting here would block until all async server components
|
|
208
|
-
// complete, collapsing the streaming behavior.
|
|
209
|
-
// Lazily create the Flight root inside render so React's hook dispatcher is set
|
|
210
|
-
// (avoids React 19 dev-mode resolveErrorDev() crash). VinextFlightRoot returns
|
|
211
|
-
// a thenable (not a ReactNode), which React 19 consumes via its internal
|
|
212
|
-
// thenable-as-child suspend/resume behavior. This matches Next.js's approach.
|
|
213
|
-
let flightRoot;
|
|
214
|
-
function VinextFlightRoot() {
|
|
215
|
-
if (!flightRoot) {
|
|
216
|
-
flightRoot = createFromReadableStream(ssrStream);
|
|
217
|
-
}
|
|
218
|
-
return flightRoot;
|
|
219
|
-
}
|
|
220
|
-
const root = _ssrCE(VinextFlightRoot);
|
|
221
|
-
|
|
222
|
-
// Wrap with ServerInsertedHTMLContext.Provider so libraries that use
|
|
223
|
-
// useContext(ServerInsertedHTMLContext) (Apollo Client, styled-components,
|
|
224
|
-
// etc.) get a working callback registration function during SSR.
|
|
225
|
-
// The provider value is useServerInsertedHTML — same function that direct
|
|
226
|
-
// callers use — so both paths push to the same ALS-backed callback array.
|
|
227
|
-
const ssrRoot = ServerInsertedHTMLContext
|
|
228
|
-
? _ssrCE(ServerInsertedHTMLContext.Provider, { value: _addInsertedHTML }, root)
|
|
229
|
-
: root;
|
|
230
|
-
|
|
231
|
-
// Get the bootstrap script content for the browser entry
|
|
232
|
-
const bootstrapScriptContent =
|
|
233
|
-
await import.meta.viteRsc.loadBootstrapScriptContent("index");
|
|
234
|
-
|
|
235
|
-
// djb2 hash for digest generation in the SSR environment.
|
|
236
|
-
// Matches the RSC environment's __errorDigest function.
|
|
237
|
-
function ssrErrorDigest(str) {
|
|
238
|
-
let hash = 5381;
|
|
239
|
-
for (let i = str.length - 1; i >= 0; i--) {
|
|
240
|
-
hash = (hash * 33) ^ str.charCodeAt(i);
|
|
241
|
-
}
|
|
242
|
-
return (hash >>> 0).toString();
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
// Render HTML (streaming SSR)
|
|
246
|
-
// useServerInsertedHTML callbacks are registered during this render.
|
|
247
|
-
// The onError callback preserves the digest for Next.js navigation errors
|
|
248
|
-
// (redirect, notFound, forbidden, unauthorized) thrown inside Suspense
|
|
249
|
-
// boundaries during RSC streaming. Without this, React's default onError
|
|
250
|
-
// returns undefined and the digest is lost in the $RX() call, preventing
|
|
251
|
-
// client-side error boundaries from identifying the error type.
|
|
252
|
-
// In production, non-navigation errors also get a digest hash so they
|
|
253
|
-
// can be correlated with server logs without leaking details to clients.
|
|
254
|
-
const htmlStream = await renderToReadableStream(ssrRoot, {
|
|
255
|
-
bootstrapScriptContent,
|
|
256
|
-
onError(error) {
|
|
257
|
-
if (error && typeof error === "object" && "digest" in error) {
|
|
258
|
-
return String(error.digest);
|
|
259
|
-
}
|
|
260
|
-
// In production, generate a digest hash for non-navigation errors
|
|
261
|
-
if (process.env.NODE_ENV === "production" && error) {
|
|
262
|
-
const msg = error instanceof Error ? error.message : String(error);
|
|
263
|
-
const stack = error instanceof Error ? (error.stack || "") : "";
|
|
264
|
-
return ssrErrorDigest(msg + stack);
|
|
265
|
-
}
|
|
266
|
-
return undefined;
|
|
267
|
-
},
|
|
268
|
-
});
|
|
269
|
-
|
|
270
|
-
// Flush useServerInsertedHTML callbacks (CSS-in-JS style injection)
|
|
271
|
-
const insertedElements = flushServerInsertedHTML();
|
|
272
|
-
|
|
273
|
-
// Render the inserted elements to HTML strings
|
|
274
|
-
const { Fragment } = await import("react");
|
|
275
|
-
let insertedHTML = "";
|
|
276
|
-
for (const el of insertedElements) {
|
|
277
|
-
try {
|
|
278
|
-
insertedHTML += renderToStaticMarkup(_ssrCE(Fragment, null, el));
|
|
279
|
-
} catch {
|
|
280
|
-
// Skip elements that can't be rendered
|
|
281
|
-
}
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
// Escape HTML attribute values (defense-in-depth for font URLs/types).
|
|
285
|
-
function _escAttr(s) { return s.replace(/&/g, "&").replace(/"/g, """); }
|
|
286
|
-
|
|
287
|
-
// Build font HTML from data passed from RSC environment
|
|
288
|
-
// (Fonts are loaded during RSC rendering, and RSC/SSR are separate module instances)
|
|
289
|
-
let fontHTML = "";
|
|
290
|
-
if (fontData) {
|
|
291
|
-
if (fontData.links && fontData.links.length > 0) {
|
|
292
|
-
for (const url of fontData.links) {
|
|
293
|
-
fontHTML += '<link rel="stylesheet" href="' + _escAttr(url) + '" />\\n';
|
|
294
|
-
}
|
|
295
|
-
}
|
|
296
|
-
// Emit <link rel="preload"> for local font files
|
|
297
|
-
if (fontData.preloads && fontData.preloads.length > 0) {
|
|
298
|
-
for (const preload of fontData.preloads) {
|
|
299
|
-
fontHTML += '<link rel="preload" href="' + _escAttr(preload.href) + '" as="font" type="' + _escAttr(preload.type) + '" crossorigin />\\n';
|
|
300
|
-
}
|
|
301
|
-
}
|
|
302
|
-
if (fontData.styles && fontData.styles.length > 0) {
|
|
303
|
-
fontHTML += '<style data-vinext-fonts>' + fontData.styles.join("\\n") + '</style>\\n';
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
// Extract client entry module URL from bootstrapScriptContent to emit
|
|
308
|
-
// a <link rel="modulepreload"> hint. The RSC plugin formats bootstrap
|
|
309
|
-
// content as: import("URL") — we extract the URL so the browser can
|
|
310
|
-
// speculatively fetch and parse the JS module while still processing
|
|
311
|
-
// the HTML body, instead of waiting until it reaches the inline script.
|
|
312
|
-
let modulePreloadHTML = "";
|
|
313
|
-
if (bootstrapScriptContent) {
|
|
314
|
-
const m = bootstrapScriptContent.match(/import\\("([^"]+)"\\)/);
|
|
315
|
-
if (m && m[1]) {
|
|
316
|
-
modulePreloadHTML = '<link rel="modulepreload" href="' + _escAttr(m[1]) + '" />\\n';
|
|
317
|
-
}
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
// Head-injected HTML: server-inserted HTML, font HTML, route params,
|
|
321
|
-
// and modulepreload hints.
|
|
322
|
-
// RSC payload is now embedded progressively via script tags in the body stream.
|
|
323
|
-
// Params are embedded eagerly in <head> so they're available before client
|
|
324
|
-
// hydration starts, avoiding the need for polling on the client.
|
|
325
|
-
const paramsScript = '<script>self.__VINEXT_RSC_PARAMS__=' + safeJsonStringify(navContext?.params || {}) + '<\/script>';
|
|
326
|
-
// Embed the initial navigation context (pathname + searchParams) so the
|
|
327
|
-
// browser useSyncExternalStore getServerSnapshot can return the correct
|
|
328
|
-
// value during hydration. Without this, getServerSnapshot returns "/" and
|
|
329
|
-
// React detects a mismatch against the SSR-rendered HTML.
|
|
330
|
-
// Serialise searchParams as an array of [key, value] pairs to preserve
|
|
331
|
-
// duplicate keys (e.g. ?tag=a&tag=b). Object.fromEntries() would keep
|
|
332
|
-
// only the last value, causing a hydration mismatch for multi-value params.
|
|
333
|
-
const __navPayload = { pathname: navContext?.pathname ?? '/', searchParams: navContext?.searchParams ? [...navContext.searchParams.entries()] : [] };
|
|
334
|
-
const navScript = '<script>self.__VINEXT_RSC_NAV__=' + safeJsonStringify(__navPayload) + '<\/script>';
|
|
335
|
-
const injectHTML = paramsScript + navScript + modulePreloadHTML + insertedHTML + fontHTML;
|
|
336
|
-
|
|
337
|
-
// Inject the collected HTML before </head> and progressively embed RSC
|
|
338
|
-
// chunks as script tags throughout the HTML body stream.
|
|
339
|
-
const decoder = new TextDecoder();
|
|
340
|
-
const encoder = new TextEncoder();
|
|
341
|
-
let injected = false;
|
|
342
|
-
|
|
343
|
-
// Fix invalid preload "as" values in server-rendered HTML.
|
|
344
|
-
// React Fizz emits <link rel="preload" as="stylesheet"> for CSS,
|
|
345
|
-
// but the HTML spec requires as="style" for <link rel="preload">.
|
|
346
|
-
// Note: Flight HL hints are fixed upstream in the renderToReadableStream
|
|
347
|
-
// wrapper (app-rsc-entry.ts); this only handles the Fizz HTML stream.
|
|
348
|
-
// See: https://html.spec.whatwg.org/multipage/links.html#link-type-preload
|
|
349
|
-
function fixPreloadAs(html) {
|
|
350
|
-
// Match <link ...rel="preload"... as="stylesheet"...> in any attribute order
|
|
351
|
-
return html.replace(/<link(?=[^>]*\\srel="preload")[^>]*>/g, function(tag) {
|
|
352
|
-
return tag.replace(' as="stylesheet"', ' as="style"');
|
|
353
|
-
});
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
// Tick-buffered RSC script injection.
|
|
357
|
-
//
|
|
358
|
-
// React's renderToReadableStream (Fizz) flushes chunks synchronously
|
|
359
|
-
// within one microtask — all chunks from a single flushCompletedQueues
|
|
360
|
-
// call arrive in the same macrotask. We buffer HTML chunks as they
|
|
361
|
-
// arrive, then use setTimeout(0) to defer emitting them plus any
|
|
362
|
-
// accumulated RSC scripts to the next macrotask. This guarantees we
|
|
363
|
-
// never inject <script> tags between partial HTML chunks (which would
|
|
364
|
-
// corrupt split elements like "<linearGradi" + "ent>"), while still
|
|
365
|
-
// delivering RSC data progressively as Suspense boundaries resolve.
|
|
366
|
-
//
|
|
367
|
-
// Reference: rsc-html-stream by Devon Govett (credited by Next.js)
|
|
368
|
-
// https://github.com/devongovett/rsc-html-stream
|
|
369
|
-
let buffered = [];
|
|
370
|
-
let timeoutId = null;
|
|
371
|
-
|
|
372
|
-
const transform = new TransformStream({
|
|
373
|
-
transform(chunk, controller) {
|
|
374
|
-
const text = decoder.decode(chunk, { stream: true });
|
|
375
|
-
const fixed = fixPreloadAs(text);
|
|
376
|
-
buffered.push(fixed);
|
|
377
|
-
|
|
378
|
-
if (timeoutId !== null) return;
|
|
379
|
-
|
|
380
|
-
timeoutId = setTimeout(() => {
|
|
381
|
-
// Flush all buffered HTML chunks from this React flush cycle
|
|
382
|
-
for (const buf of buffered) {
|
|
383
|
-
if (!injected) {
|
|
384
|
-
const headEnd = buf.indexOf("</head>");
|
|
385
|
-
if (headEnd !== -1) {
|
|
386
|
-
const before = buf.slice(0, headEnd);
|
|
387
|
-
const after = buf.slice(headEnd);
|
|
388
|
-
controller.enqueue(encoder.encode(before + injectHTML + after));
|
|
389
|
-
injected = true;
|
|
390
|
-
continue;
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
controller.enqueue(encoder.encode(buf));
|
|
394
|
-
}
|
|
395
|
-
buffered = [];
|
|
396
|
-
|
|
397
|
-
// Now safe to inject any accumulated RSC scripts — we're between
|
|
398
|
-
// React flush cycles, so no partial HTML chunks can follow until
|
|
399
|
-
// the next macrotask.
|
|
400
|
-
const rscScripts = rscEmbed.flush();
|
|
401
|
-
if (rscScripts) {
|
|
402
|
-
controller.enqueue(encoder.encode(rscScripts));
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
timeoutId = null;
|
|
406
|
-
}, 0);
|
|
407
|
-
},
|
|
408
|
-
async flush(controller) {
|
|
409
|
-
// Cancel any pending setTimeout callback — flush() drains
|
|
410
|
-
// everything itself, so the callback would be a no-op but
|
|
411
|
-
// cancelling makes the code obviously correct.
|
|
412
|
-
if (timeoutId !== null) {
|
|
413
|
-
clearTimeout(timeoutId);
|
|
414
|
-
timeoutId = null;
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
// Flush any remaining buffered HTML chunks
|
|
418
|
-
for (const buf of buffered) {
|
|
419
|
-
if (!injected) {
|
|
420
|
-
const headEnd = buf.indexOf("</head>");
|
|
421
|
-
if (headEnd !== -1) {
|
|
422
|
-
const before = buf.slice(0, headEnd);
|
|
423
|
-
const after = buf.slice(headEnd);
|
|
424
|
-
controller.enqueue(encoder.encode(before + injectHTML + after));
|
|
425
|
-
injected = true;
|
|
426
|
-
continue;
|
|
427
|
-
}
|
|
428
|
-
}
|
|
429
|
-
controller.enqueue(encoder.encode(buf));
|
|
430
|
-
}
|
|
431
|
-
buffered = [];
|
|
432
|
-
|
|
433
|
-
if (!injected && injectHTML) {
|
|
434
|
-
controller.enqueue(encoder.encode(injectHTML));
|
|
435
|
-
}
|
|
436
|
-
// Finalize: wait for the RSC stream to complete and emit remaining
|
|
437
|
-
// chunks plus the __VINEXT_RSC_DONE__ signal.
|
|
438
|
-
const finalScripts = await rscEmbed.finalize();
|
|
439
|
-
if (finalScripts) {
|
|
440
|
-
controller.enqueue(encoder.encode(finalScripts));
|
|
441
|
-
}
|
|
442
|
-
},
|
|
443
|
-
});
|
|
444
|
-
|
|
445
|
-
return htmlStream.pipeThrough(transform);
|
|
446
|
-
} finally {
|
|
447
|
-
// Clean up so we don't leak context between requests
|
|
448
|
-
setNavigationContext(null);
|
|
449
|
-
clearServerInsertedHTML();
|
|
450
|
-
}
|
|
451
|
-
}); // end _runWithNavCtx
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
export default {
|
|
455
|
-
async fetch(request) {
|
|
456
|
-
const url = new URL(request.url);
|
|
457
|
-
if (url.pathname.startsWith("//")) {
|
|
458
|
-
return new Response("404 Not Found", { status: 404 });
|
|
459
|
-
}
|
|
460
|
-
const rscModule = await import.meta.viteRsc.loadModule("rsc", "index");
|
|
461
|
-
const result = await rscModule.default(request);
|
|
462
|
-
if (result instanceof Response) {
|
|
463
|
-
return result;
|
|
464
|
-
}
|
|
465
|
-
if (result === null || result === undefined) {
|
|
466
|
-
return new Response("Not Found", { status: 404 });
|
|
467
|
-
}
|
|
468
|
-
return new Response(String(result), { status: 200 });
|
|
469
|
-
},
|
|
470
|
-
};
|
|
17
|
+
export * from ${JSON.stringify(entryPath)};
|
|
18
|
+
export { default } from ${JSON.stringify(entryPath)};
|
|
471
19
|
${hasPagesDir ? `
|
|
472
|
-
// Re-export pageRoutes and renderPage from the Pages Router server entry so
|
|
473
|
-
// that the Cloudflare Workers RSC bundle can access Pages Router route metadata
|
|
474
|
-
// (including getStaticPaths) via import("./ssr/index.js").pageRoutes, and can
|
|
475
|
-
// delegate unmatched App Router requests to renderPage for hybrid builds.
|
|
476
20
|
export { pageRoutes, renderPage } from "virtual:vinext-server-entry";
|
|
477
21
|
` : ""}`;
|
|
478
22
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-ssr-entry.js","names":[],"sources":["../../src/entries/app-ssr-entry.ts"],"sourcesContent":["/**\n * Generate the virtual SSR entry module.\n *\n * This runs in the `ssr` Vite environment. It receives an RSC stream,\n * deserializes it to a React tree, and renders to HTML.\n *\n * When `hasPagesDir` is true (hybrid App + Pages Router project), the SSR\n * entry also re-exports `pageRoutes` from `virtual:vinext-server-entry` so\n * that the Cloudflare Workers RSC bundle can access Pages Router route\n * metadata (including `getStaticPaths`) via `import(\"./ssr/index.js\")`.\n */\nexport function generateSsrEntry(hasPagesDir = false): string {\n return `\nimport { createFromReadableStream } from \"@vitejs/plugin-rsc/ssr\";\nimport { renderToReadableStream, renderToStaticMarkup } from \"react-dom/server.edge\";\nimport { setNavigationContext, ServerInsertedHTMLContext } from \"next/navigation\";\nimport { runWithNavigationContext as _runWithNavCtx } from \"vinext/navigation-state\";\nimport { safeJsonStringify } from \"vinext/html\";\nimport { createElement as _ssrCE } from \"react\";\nimport * as _clientRefs from \"virtual:vite-rsc/client-references\";\n\nlet _clientRefsPreloaded = false;\n\n/**\n * Collect all chunks from a ReadableStream into an array of text strings.\n * Used to capture the RSC payload for embedding in HTML.\n * The RSC flight protocol is text-based (line-delimited key:value pairs),\n * so we decode to text strings instead of byte arrays — this is dramatically\n * more compact when JSON-serialized into inline <script> tags.\n */\nasync function collectStreamChunks(stream) {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n const chunks = [];\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n // Decode Uint8Array to text string for compact JSON serialization\n chunks.push(decoder.decode(value, { stream: true }));\n }\n return chunks;\n}\n\n// React 19 dev-mode workaround (see VinextFlightRoot in handleSsr):\n//\n// In dev, Flight error decoding in react-server-dom-webpack/client.edge\n// can hit resolveErrorDev() which (via React's dev error stack capture)\n// expects a non-null hooks dispatcher.\n//\n// Vinext previously called createFromReadableStream() outside of any React render.\n// When an RSC stream contains an error, dev-mode decoding could crash with:\n// - \"Invalid hook call\"\n// - \"Cannot read properties of null (reading 'useContext')\"\n//\n// Fix: call createFromReadableStream() lazily inside a React component render.\n// This mirrors Next.js behavior and ensures the dispatcher is set.\n\n/**\n * Create a TransformStream that appends RSC chunks as inline <script> tags\n * to the HTML stream. This allows progressive hydration — the browser receives\n * RSC data incrementally as Suspense boundaries resolve, rather than waiting\n * for the entire RSC payload before hydration can begin.\n *\n * Each chunk is written as:\n * <script>self.__VINEXT_RSC_CHUNKS__=self.__VINEXT_RSC_CHUNKS__||[];self.__VINEXT_RSC_CHUNKS__.push(\"...\")</script>\n *\n * Chunks are embedded as text strings (not byte arrays) since the RSC flight\n * protocol is text-based. The browser entry encodes them back to Uint8Array.\n * This is ~3x more compact than the previous byte-array format.\n */\nfunction createRscEmbedTransform(embedStream) {\n const reader = embedStream.getReader();\n const _decoder = new TextDecoder();\n let done = false;\n let pendingChunks = [];\n let reading = false;\n\n // Start reading RSC chunks in the background, accumulating them as text strings.\n // The RSC flight protocol is text-based, so decoding to strings and embedding\n // as JSON strings is ~3x more compact than the byte-array format.\n //\n // Note: Flight HL hint \"stylesheet\" → \"style\" rewriting is handled upstream\n // in the renderToReadableStream wrapper (app-rsc-entry.ts), so the stream\n // arriving here is already clean.\n async function pumpReader() {\n if (reading) return;\n reading = true;\n try {\n while (true) {\n const result = await reader.read();\n if (result.done) {\n done = true;\n break;\n }\n const text = _decoder.decode(result.value, { stream: true });\n pendingChunks.push(text);\n }\n } catch (err) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\"[vinext] RSC embed stream read error:\", err);\n }\n done = true;\n }\n reading = false;\n }\n\n // Fire off the background reader immediately\n const pumpPromise = pumpReader();\n\n return {\n /**\n * Flush any accumulated RSC chunks as <script> tags.\n * Called after each HTML chunk is enqueued.\n */\n flush() {\n if (pendingChunks.length === 0) return \"\";\n const chunks = pendingChunks;\n pendingChunks = [];\n let scripts = \"\";\n for (const chunk of chunks) {\n scripts += \"<script>self.__VINEXT_RSC_CHUNKS__=self.__VINEXT_RSC_CHUNKS__||[];self.__VINEXT_RSC_CHUNKS__.push(\" + safeJsonStringify(chunk) + \")</script>\";\n }\n return scripts;\n },\n\n /**\n * Wait for the RSC stream to fully complete and return any final\n * script tags plus the closing signal.\n */\n async finalize() {\n await pumpPromise;\n let scripts = this.flush();\n // Signal that all RSC chunks have been sent.\n // Params are already embedded in <head> — no need to include here.\n scripts += \"<script>self.__VINEXT_RSC_DONE__=true</script>\";\n return scripts;\n },\n };\n}\n\n/**\n * Render the RSC stream to HTML.\n *\n * @param rscStream - The RSC payload stream from the RSC environment\n * @param navContext - Navigation context for client component SSR hooks.\n * \"use client\" components like those using usePathname() need the current\n * request URL during SSR, and they run in this SSR environment (separate\n * from the RSC environment where the context was originally set).\n * @param fontData - Font links and styles collected from the RSC environment.\n * Fonts are loaded during RSC rendering (when layout calls Geist() etc.),\n * and the data needs to be passed to SSR since they're separate module instances.\n */\nexport async function handleSsr(rscStream, navContext, fontData) {\n // Eagerly preload all client reference modules before SSR rendering.\n // On the first request after server start, client component modules are\n // loaded lazily via async import(). Without this preload, React's\n // renderToReadableStream rejects because the shell can't resolve client\n // components synchronously (there is no Suspense boundary wrapping the\n // root). The memoized require cache ensures this is only async on the\n // very first call; subsequent requests resolve from cache immediately.\n // See: https://github.com/cloudflare/vinext/issues/256\n // _clientRefs.default is the default export from the virtual:vite-rsc/client-references\n // namespace import — a map of client component IDs to their async import functions.\n if (!_clientRefsPreloaded && _clientRefs.default && globalThis.__vite_rsc_client_require__) {\n await Promise.all(\n Object.keys(_clientRefs.default).map((id) =>\n globalThis.__vite_rsc_client_require__(id).catch((err) => {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\"[vinext] failed to preload client ref:\", id, err);\n }\n })\n )\n );\n _clientRefsPreloaded = true;\n }\n\n // Wrap in a navigation ALS scope for per-request isolation in the SSR\n // environment. The SSR environment has separate module instances from RSC,\n // so it needs its own ALS scope.\n return _runWithNavCtx(async () => {\n // Set navigation context so hooks like usePathname() work during SSR\n // of \"use client\" components\n if (navContext) {\n setNavigationContext(navContext);\n }\n\n // Clear any stale callbacks from previous requests\n const { clearServerInsertedHTML, flushServerInsertedHTML, useServerInsertedHTML: _addInsertedHTML } = await import(\"next/navigation\");\n clearServerInsertedHTML();\n\n try {\n // Tee the RSC stream - one for SSR rendering, one for embedding in HTML.\n // This ensures the browser uses the SAME RSC payload for hydration that\n // was used to generate the HTML, avoiding hydration mismatches (React #418).\n const [ssrStream, embedStream] = rscStream.tee();\n\n // Create the progressive RSC embed helper — it reads the embed stream\n // in the background and provides script tags to inject into the HTML stream.\n const rscEmbed = createRscEmbedTransform(embedStream);\n\n // Deserialize RSC stream back to React VDOM.\n // IMPORTANT: Do NOT await this — createFromReadableStream returns a thenable\n // that React's renderToReadableStream can consume progressively. By passing\n // the unresolved thenable, React will render Suspense fallbacks (loading.tsx)\n // immediately in the HTML shell, then stream in resolved content as RSC\n // chunks arrive. Awaiting here would block until all async server components\n // complete, collapsing the streaming behavior.\n // Lazily create the Flight root inside render so React's hook dispatcher is set\n // (avoids React 19 dev-mode resolveErrorDev() crash). VinextFlightRoot returns\n // a thenable (not a ReactNode), which React 19 consumes via its internal\n // thenable-as-child suspend/resume behavior. This matches Next.js's approach.\n let flightRoot;\n function VinextFlightRoot() {\n if (!flightRoot) {\n flightRoot = createFromReadableStream(ssrStream);\n }\n return flightRoot;\n }\n const root = _ssrCE(VinextFlightRoot);\n\n // Wrap with ServerInsertedHTMLContext.Provider so libraries that use\n // useContext(ServerInsertedHTMLContext) (Apollo Client, styled-components,\n // etc.) get a working callback registration function during SSR.\n // The provider value is useServerInsertedHTML — same function that direct\n // callers use — so both paths push to the same ALS-backed callback array.\n const ssrRoot = ServerInsertedHTMLContext\n ? _ssrCE(ServerInsertedHTMLContext.Provider, { value: _addInsertedHTML }, root)\n : root;\n\n // Get the bootstrap script content for the browser entry\n const bootstrapScriptContent =\n await import.meta.viteRsc.loadBootstrapScriptContent(\"index\");\n\n // djb2 hash for digest generation in the SSR environment.\n // Matches the RSC environment's __errorDigest function.\n function ssrErrorDigest(str) {\n let hash = 5381;\n for (let i = str.length - 1; i >= 0; i--) {\n hash = (hash * 33) ^ str.charCodeAt(i);\n }\n return (hash >>> 0).toString();\n }\n\n // Render HTML (streaming SSR)\n // useServerInsertedHTML callbacks are registered during this render.\n // The onError callback preserves the digest for Next.js navigation errors\n // (redirect, notFound, forbidden, unauthorized) thrown inside Suspense\n // boundaries during RSC streaming. Without this, React's default onError\n // returns undefined and the digest is lost in the $RX() call, preventing\n // client-side error boundaries from identifying the error type.\n // In production, non-navigation errors also get a digest hash so they\n // can be correlated with server logs without leaking details to clients.\n const htmlStream = await renderToReadableStream(ssrRoot, {\n bootstrapScriptContent,\n onError(error) {\n if (error && typeof error === \"object\" && \"digest\" in error) {\n return String(error.digest);\n }\n // In production, generate a digest hash for non-navigation errors\n if (process.env.NODE_ENV === \"production\" && error) {\n const msg = error instanceof Error ? error.message : String(error);\n const stack = error instanceof Error ? (error.stack || \"\") : \"\";\n return ssrErrorDigest(msg + stack);\n }\n return undefined;\n },\n });\n\n // Flush useServerInsertedHTML callbacks (CSS-in-JS style injection)\n const insertedElements = flushServerInsertedHTML();\n\n // Render the inserted elements to HTML strings\n const { Fragment } = await import(\"react\");\n let insertedHTML = \"\";\n for (const el of insertedElements) {\n try {\n insertedHTML += renderToStaticMarkup(_ssrCE(Fragment, null, el));\n } catch {\n // Skip elements that can't be rendered\n }\n }\n\n // Escape HTML attribute values (defense-in-depth for font URLs/types).\n function _escAttr(s) { return s.replace(/&/g, \"&\").replace(/\"/g, \""\"); }\n\n // Build font HTML from data passed from RSC environment\n // (Fonts are loaded during RSC rendering, and RSC/SSR are separate module instances)\n let fontHTML = \"\";\n if (fontData) {\n if (fontData.links && fontData.links.length > 0) {\n for (const url of fontData.links) {\n fontHTML += '<link rel=\"stylesheet\" href=\"' + _escAttr(url) + '\" />\\\\n';\n }\n }\n // Emit <link rel=\"preload\"> for local font files\n if (fontData.preloads && fontData.preloads.length > 0) {\n for (const preload of fontData.preloads) {\n fontHTML += '<link rel=\"preload\" href=\"' + _escAttr(preload.href) + '\" as=\"font\" type=\"' + _escAttr(preload.type) + '\" crossorigin />\\\\n';\n }\n }\n if (fontData.styles && fontData.styles.length > 0) {\n fontHTML += '<style data-vinext-fonts>' + fontData.styles.join(\"\\\\n\") + '</style>\\\\n';\n }\n }\n\n // Extract client entry module URL from bootstrapScriptContent to emit\n // a <link rel=\"modulepreload\"> hint. The RSC plugin formats bootstrap\n // content as: import(\"URL\") — we extract the URL so the browser can\n // speculatively fetch and parse the JS module while still processing\n // the HTML body, instead of waiting until it reaches the inline script.\n let modulePreloadHTML = \"\";\n if (bootstrapScriptContent) {\n const m = bootstrapScriptContent.match(/import\\\\(\"([^\"]+)\"\\\\)/);\n if (m && m[1]) {\n modulePreloadHTML = '<link rel=\"modulepreload\" href=\"' + _escAttr(m[1]) + '\" />\\\\n';\n }\n }\n\n // Head-injected HTML: server-inserted HTML, font HTML, route params,\n // and modulepreload hints.\n // RSC payload is now embedded progressively via script tags in the body stream.\n // Params are embedded eagerly in <head> so they're available before client\n // hydration starts, avoiding the need for polling on the client.\n const paramsScript = '<script>self.__VINEXT_RSC_PARAMS__=' + safeJsonStringify(navContext?.params || {}) + '</script>';\n // Embed the initial navigation context (pathname + searchParams) so the\n // browser useSyncExternalStore getServerSnapshot can return the correct\n // value during hydration. Without this, getServerSnapshot returns \"/\" and\n // React detects a mismatch against the SSR-rendered HTML.\n // Serialise searchParams as an array of [key, value] pairs to preserve\n // duplicate keys (e.g. ?tag=a&tag=b). Object.fromEntries() would keep\n // only the last value, causing a hydration mismatch for multi-value params.\n const __navPayload = { pathname: navContext?.pathname ?? '/', searchParams: navContext?.searchParams ? [...navContext.searchParams.entries()] : [] };\n const navScript = '<script>self.__VINEXT_RSC_NAV__=' + safeJsonStringify(__navPayload) + '</script>';\n const injectHTML = paramsScript + navScript + modulePreloadHTML + insertedHTML + fontHTML;\n\n // Inject the collected HTML before </head> and progressively embed RSC\n // chunks as script tags throughout the HTML body stream.\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n let injected = false;\n\n // Fix invalid preload \"as\" values in server-rendered HTML.\n // React Fizz emits <link rel=\"preload\" as=\"stylesheet\"> for CSS,\n // but the HTML spec requires as=\"style\" for <link rel=\"preload\">.\n // Note: Flight HL hints are fixed upstream in the renderToReadableStream\n // wrapper (app-rsc-entry.ts); this only handles the Fizz HTML stream.\n // See: https://html.spec.whatwg.org/multipage/links.html#link-type-preload\n function fixPreloadAs(html) {\n // Match <link ...rel=\"preload\"... as=\"stylesheet\"...> in any attribute order\n return html.replace(/<link(?=[^>]*\\\\srel=\"preload\")[^>]*>/g, function(tag) {\n return tag.replace(' as=\"stylesheet\"', ' as=\"style\"');\n });\n }\n\n // Tick-buffered RSC script injection.\n //\n // React's renderToReadableStream (Fizz) flushes chunks synchronously\n // within one microtask — all chunks from a single flushCompletedQueues\n // call arrive in the same macrotask. We buffer HTML chunks as they\n // arrive, then use setTimeout(0) to defer emitting them plus any\n // accumulated RSC scripts to the next macrotask. This guarantees we\n // never inject <script> tags between partial HTML chunks (which would\n // corrupt split elements like \"<linearGradi\" + \"ent>\"), while still\n // delivering RSC data progressively as Suspense boundaries resolve.\n //\n // Reference: rsc-html-stream by Devon Govett (credited by Next.js)\n // https://github.com/devongovett/rsc-html-stream\n let buffered = [];\n let timeoutId = null;\n\n const transform = new TransformStream({\n transform(chunk, controller) {\n const text = decoder.decode(chunk, { stream: true });\n const fixed = fixPreloadAs(text);\n buffered.push(fixed);\n\n if (timeoutId !== null) return;\n\n timeoutId = setTimeout(() => {\n // Flush all buffered HTML chunks from this React flush cycle\n for (const buf of buffered) {\n if (!injected) {\n const headEnd = buf.indexOf(\"</head>\");\n if (headEnd !== -1) {\n const before = buf.slice(0, headEnd);\n const after = buf.slice(headEnd);\n controller.enqueue(encoder.encode(before + injectHTML + after));\n injected = true;\n continue;\n }\n }\n controller.enqueue(encoder.encode(buf));\n }\n buffered = [];\n\n // Now safe to inject any accumulated RSC scripts — we're between\n // React flush cycles, so no partial HTML chunks can follow until\n // the next macrotask.\n const rscScripts = rscEmbed.flush();\n if (rscScripts) {\n controller.enqueue(encoder.encode(rscScripts));\n }\n\n timeoutId = null;\n }, 0);\n },\n async flush(controller) {\n // Cancel any pending setTimeout callback — flush() drains\n // everything itself, so the callback would be a no-op but\n // cancelling makes the code obviously correct.\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n\n // Flush any remaining buffered HTML chunks\n for (const buf of buffered) {\n if (!injected) {\n const headEnd = buf.indexOf(\"</head>\");\n if (headEnd !== -1) {\n const before = buf.slice(0, headEnd);\n const after = buf.slice(headEnd);\n controller.enqueue(encoder.encode(before + injectHTML + after));\n injected = true;\n continue;\n }\n }\n controller.enqueue(encoder.encode(buf));\n }\n buffered = [];\n\n if (!injected && injectHTML) {\n controller.enqueue(encoder.encode(injectHTML));\n }\n // Finalize: wait for the RSC stream to complete and emit remaining\n // chunks plus the __VINEXT_RSC_DONE__ signal.\n const finalScripts = await rscEmbed.finalize();\n if (finalScripts) {\n controller.enqueue(encoder.encode(finalScripts));\n }\n },\n });\n\n return htmlStream.pipeThrough(transform);\n } finally {\n // Clean up so we don't leak context between requests\n setNavigationContext(null);\n clearServerInsertedHTML();\n }\n }); // end _runWithNavCtx\n}\n\nexport default {\n async fetch(request) {\n const url = new URL(request.url);\n if (url.pathname.startsWith(\"//\")) {\n return new Response(\"404 Not Found\", { status: 404 });\n }\n const rscModule = await import.meta.viteRsc.loadModule(\"rsc\", \"index\");\n const result = await rscModule.default(request);\n if (result instanceof Response) {\n return result;\n }\n if (result === null || result === undefined) {\n return new Response(\"Not Found\", { status: 404 });\n }\n return new Response(String(result), { status: 200 });\n },\n};\n${\n hasPagesDir\n ? `\n// Re-export pageRoutes and renderPage from the Pages Router server entry so\n// that the Cloudflare Workers RSC bundle can access Pages Router route metadata\n// (including getStaticPaths) via import(\"./ssr/index.js\").pageRoutes, and can\n// delegate unmatched App Router requests to renderPage for hybrid builds.\nexport { pageRoutes, renderPage } from \"virtual:vinext-server-entry\";\n`\n : \"\"\n}`;\n}\n"],"mappings":";;;;;;;;;;;;AAWA,SAAgB,iBAAiB,cAAc,OAAe;AAC5D,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA0cP,cACI;;;;;;IAOA"}
|
|
1
|
+
{"version":3,"file":"app-ssr-entry.js","names":[],"sources":["../../src/entries/app-ssr-entry.ts"],"sourcesContent":["import { resolveRuntimeEntryModule } from \"./runtime-entry-module.js\";\n\n/**\n * Generate the virtual SSR entry module.\n *\n * This runs in the `ssr` Vite environment. It receives an RSC stream,\n * deserializes it to a React tree, and renders to HTML.\n *\n * When `hasPagesDir` is true (hybrid App + Pages Router project), the SSR\n * entry also re-exports `pageRoutes` from `virtual:vinext-server-entry` so\n * that the Cloudflare Workers RSC bundle can access Pages Router route\n * metadata (including `getStaticPaths`) via `import(\"./ssr/index.js\")`.\n */\nexport function generateSsrEntry(hasPagesDir = false): string {\n const entryPath = resolveRuntimeEntryModule(\"app-ssr-entry\");\n\n return `\nexport * from ${JSON.stringify(entryPath)};\nexport { default } from ${JSON.stringify(entryPath)};\n${\n hasPagesDir\n ? `\nexport { pageRoutes, renderPage } from \"virtual:vinext-server-entry\";\n`\n : \"\"\n}`;\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,SAAgB,iBAAiB,cAAc,OAAe;CAC5D,MAAM,YAAY,0BAA0B,gBAAgB;AAE5D,QAAO;gBACO,KAAK,UAAU,UAAU,CAAC;0BAChB,KAAK,UAAU,UAAU,CAAC;EAElD,cACI;;IAGA"}
|
|
@@ -1038,7 +1038,14 @@ async function _renderPage(request, url, manifest) {
|
|
|
1038
1038
|
if (_fontLinkHeader) {
|
|
1039
1039
|
responseHeaders.set("Link", _fontLinkHeader);
|
|
1040
1040
|
}
|
|
1041
|
-
|
|
1041
|
+
const streamedPageResponse = new Response(compositeStream, {
|
|
1042
|
+
status: finalStatus,
|
|
1043
|
+
headers: responseHeaders,
|
|
1044
|
+
});
|
|
1045
|
+
// Mark the normal streamed HTML render so the Node prod server can strip
|
|
1046
|
+
// stale Content-Length only for this path, not for custom gSSP responses.
|
|
1047
|
+
streamedPageResponse.__vinextStreamedHtmlResponse = true;
|
|
1048
|
+
return streamedPageResponse;
|
|
1042
1049
|
} catch (e) {
|
|
1043
1050
|
console.error("[vinext] SSR error:", e);
|
|
1044
1051
|
_reportRequestError(
|