@cedarjs/vite 6.0.0 → 7.0.0-canary.2982

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.
@@ -1,7 +1,12 @@
1
1
  #!/usr/bin/env node
2
+ import http from "node:http";
2
3
  import { createServerAdapter } from "@whatwg-node/server";
3
4
  import express from "express";
4
- import { createServer as createViteServer } from "vite";
5
+ import {
6
+ createServer as createViteServer,
7
+ createServerModuleRunner,
8
+ defaultServerConditions
9
+ } from "vite";
5
10
  import { cjsInterop } from "vite-plugin-cjs-interop";
6
11
  import { getProjectRoutes } from "@cedarjs/internal/dist/routes.js";
7
12
  import { getConfig, getPaths } from "@cedarjs/project-config";
@@ -10,6 +15,10 @@ import { registerFwGlobalsAndShims } from "./lib/registerFwGlobalsAndShims.js";
10
15
  import { invoke } from "./middleware/invokeMiddleware.js";
11
16
  import { createMiddlewareRouter } from "./middleware/register.js";
12
17
  import { rscRoutesAutoLoader } from "./plugins/vite-plugin-rsc-routes-auto-loader.js";
18
+ import { rscRoutesImports } from "./plugins/vite-plugin-rsc-routes-imports.js";
19
+ import { rscSsrRouterImport } from "./plugins/vite-plugin-rsc-ssr-router-import.js";
20
+ import { rscTransformUseServerPlugin } from "./plugins/vite-plugin-rsc-transform-server.js";
21
+ import { createWebSocketServer } from "./rsc/rscWebSocketServer.js";
13
22
  import { collectCssPaths, componentsModules } from "./streaming/collectCss.js";
14
23
  import { createReactStreamingHandler } from "./streaming/createReactStreamingHandler.js";
15
24
  import {
@@ -18,10 +27,13 @@ import {
18
27
  getFullUrl
19
28
  } from "./utils.js";
20
29
  globalThis.__REDWOOD__PRERENDER_PAGES = {};
30
+ globalThis.__cedarjs__vite_ssr_runtime = void 0;
31
+ globalThis.__cedarjs__vite_rsc_runtime = void 0;
21
32
  async function createServer() {
22
33
  ensureProcessDirWeb();
23
34
  registerFwGlobalsAndShims();
24
35
  const app = express();
36
+ const server = http.createServer(app);
25
37
  const rwPaths = getPaths();
26
38
  const rscEnabled = getConfig().experimental.rsc?.enabled ?? false;
27
39
  const serverStorage = createServerStorage();
@@ -44,8 +56,78 @@ async function createServer() {
44
56
  "Vite config not found. Please set up Vite before running the dev server."
45
57
  );
46
58
  }
47
- const vite = await createViteServer({
59
+ const viteSsrDevServer = await createViteServer({
48
60
  configFile: rwPaths.web.viteConfig,
61
+ envFile: false,
62
+ define: {
63
+ "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV)
64
+ },
65
+ ssr: {
66
+ // Inline every file apart from node built-ins. We want vite/rollup to
67
+ // inline dependencies in the server build. This gets round runtime
68
+ // importing of "server-only" and other packages with poisoned imports.
69
+ //
70
+ // Files included in `noExternal` are files we want Vite to analyze
71
+ // As of vite 5.2 `true` here means "all except node built-ins"
72
+ // noExternal: true,
73
+ // TODO (RSC): Other frameworks build for RSC without `noExternal: true`.
74
+ // What are we missing here? When/why is that a better choice? I know
75
+ // we would have to explicitly add a bunch of packages to noExternal, if
76
+ // we wanted to go that route.
77
+ // noExternal: ['@tobbe.dev/rsc-test'],
78
+ // Can't inline prisma client (db calls fail at runtime) or react-dom
79
+ // (css pre-init failure)
80
+ // Server store has to be externalized, because it's a singleton (shared between FW and App)
81
+ external: [
82
+ "@prisma/client",
83
+ "@prisma/adapter-better-sqlite3",
84
+ "@prisma/fetch-engine",
85
+ "@prisma/internals",
86
+ "better-sqlite3",
87
+ "@cedarjs/auth-dbauth-api",
88
+ "@cedarjs/cookie-jar",
89
+ "@cedarjs/server-store",
90
+ "@simplewebauthn/server",
91
+ "graphql-scalars",
92
+ "minimatch",
93
+ "playwright",
94
+ "react-dom"
95
+ ],
96
+ resolve: {
97
+ // These conditions are used in the plugin pipeline, and only affect non-externalized
98
+ // dependencies during the SSR build. Which because of `noExternal: true` means all
99
+ // dependencies apart from node built-ins.
100
+ // TODO (RSC): What's the difference between `conditions` and
101
+ // `externalConditions`? When is one used over the other?
102
+ // conditions: ['react-server'],
103
+ // externalConditions: ['react-server'],
104
+ },
105
+ optimizeDeps: {
106
+ // We need Vite to optimize these dependencies so that they are resolved
107
+ // with the correct conditions. And so that CJS modules work correctly.
108
+ // include: [
109
+ // 'react/**/*',
110
+ // 'react-dom/server',
111
+ // 'react-dom/server.edge',
112
+ // 'rehackt',
113
+ // 'react-server-dom-webpack/server',
114
+ // 'react-server-dom-webpack/client',
115
+ // '@apollo/client/cache/*',
116
+ // '@apollo/client/utilities/*',
117
+ // '@apollo/client/react/hooks/*',
118
+ // 'react-fast-compare',
119
+ // 'invariant',
120
+ // 'shallowequal',
121
+ // 'graphql/language/*',
122
+ // 'stacktracey',
123
+ // 'deepmerge',
124
+ // 'fast-glob',
125
+ // ],
126
+ }
127
+ },
128
+ resolve: {
129
+ // conditions: ['react-server'],
130
+ },
49
131
  plugins: [
50
132
  cjsInterop({
51
133
  dependencies: [
@@ -54,16 +136,186 @@ async function createServer() {
54
136
  "@cedarjs/prerender/*"
55
137
  ]
56
138
  }),
57
- rscEnabled && rscRoutesAutoLoader()
139
+ rscEnabled && rscRoutesAutoLoader(),
140
+ rscEnabled && rscSsrRouterImport()
58
141
  ],
59
142
  server: { middlewareMode: true },
60
143
  logLevel: "info",
61
144
  clearScreen: false,
62
145
  appType: "custom"
63
146
  });
147
+ globalThis.__cedarjs__vite_ssr_runtime = createServerModuleRunner(
148
+ viteSsrDevServer.environments.ssr
149
+ );
150
+ globalThis.__cedarjs__client_references = /* @__PURE__ */ new Set();
151
+ globalThis.__cedarjs__server_references = /* @__PURE__ */ new Set();
152
+ const viteRscServer = await createViteServer({
153
+ envFile: false,
154
+ define: {
155
+ "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV)
156
+ },
157
+ ssr: {
158
+ // Inline every file apart from node built-ins. We want vite/rollup to
159
+ // inline dependencies in the server build. This gets round runtime
160
+ // importing of "server-only" and other packages with poisoned imports.
161
+ //
162
+ // Files included in `noExternal` are files we want Vite to analyze
163
+ // As of vite 5.2 `true` here means "all except node built-ins"
164
+ noExternal: true,
165
+ // TODO (RSC): Other frameworks build for RSC without `noExternal: true`.
166
+ // What are we missing here? When/why is that a better choice? I know
167
+ // we would have to explicitly add a bunch of packages to noExternal, if
168
+ // we wanted to go that route.
169
+ // noExternal: ['@tobbe.dev/rsc-test'],
170
+ // Can't inline prisma client (db calls fail at runtime) or react-dom
171
+ // (css pre-init failure)
172
+ // Server store has to be externalized, because it's a singleton (shared between FW and App)
173
+ external: [
174
+ "@prisma/client",
175
+ "@prisma/adapter-better-sqlite3",
176
+ "@prisma/fetch-engine",
177
+ "@prisma/internals",
178
+ "better-sqlite3",
179
+ "@cedarjs/auth-dbauth-api",
180
+ "@cedarjs/cookie-jar",
181
+ "@cedarjs/server-store",
182
+ "@cedarjs/structure",
183
+ "@simplewebauthn/server",
184
+ "graphql-scalars",
185
+ "minimatch",
186
+ "playwright",
187
+ "react-dom"
188
+ ],
189
+ resolve: {
190
+ // These conditions are used in the plugin pipeline, and only affect non-externalized
191
+ // dependencies during the SSR build. Which because of `noExternal: true` means all
192
+ // dependencies apart from node built-ins.
193
+ // TODO (RSC): What's the difference between `conditions` and
194
+ // `externalConditions`? When is one used over the other?
195
+ // In Vite 6, we must include `defaultServerConditions` alongside
196
+ // `react-server` so that nested condition maps (e.g. the `node`
197
+ // sub-condition inside `react-server-dom-webpack/server`'s exports)
198
+ // can still be resolved. Without `node` (or another environment
199
+ // condition), the resolver throws "No known conditions for
200
+ // './server' specifier in 'react-server-dom-webpack' package".
201
+ conditions: ["react-server", ...defaultServerConditions],
202
+ externalConditions: ["react-server", ...defaultServerConditions]
203
+ },
204
+ optimizeDeps: {
205
+ // We need Vite to optimize these dependencies so that they are resolved
206
+ // with the correct conditions. And so that CJS modules work correctly.
207
+ include: [
208
+ "react/**/*",
209
+ "react-dom/server",
210
+ "react-dom/server.edge",
211
+ "react-server-dom-webpack/server",
212
+ "react-server-dom-webpack/server.edge",
213
+ "react-server-dom-webpack/client",
214
+ "react-server-dom-webpack/client.edge",
215
+ "@apollo/client",
216
+ "@apollo/client/cache",
217
+ "@apollo/client/link/context",
218
+ "@apollo/client/link/persisted-queries",
219
+ "@apollo/client/react",
220
+ "@apollo/client/utilities",
221
+ "rxjs",
222
+ "react-fast-compare",
223
+ "invariant",
224
+ "shallowequal",
225
+ "graphql/language/*",
226
+ "stacktracey",
227
+ "deepmerge",
228
+ "fast-glob",
229
+ "@whatwg-node/fetch",
230
+ "busboy",
231
+ "cookie"
232
+ ],
233
+ // Ensure `util` resolves to Node's built-in module and not to
234
+ // Browserify's `node-util` polyfill (which lacks TextEncoder).
235
+ // The polyfill may be hoisted into node_modules by optional
236
+ // dependencies like `@cedarjs/storybook`.
237
+ exclude: ["util"]
238
+ }
239
+ },
240
+ resolve: {
241
+ // See comment above in ssr.resolve for why we include defaultServerConditions.
242
+ conditions: ["react-server", ...defaultServerConditions]
243
+ },
244
+ plugins: [
245
+ {
246
+ name: "rsc-record-and-tranform-use-client-plugin",
247
+ transform(code, id, _options) {
248
+ globalThis.__cedarjs__client_references?.delete(id);
249
+ if (!/^(["'])use client\1/.test(code)) {
250
+ return void 0;
251
+ }
252
+ console.log(
253
+ "rsc-record-and-transform-use-client-plugin: adding client reference",
254
+ id
255
+ );
256
+ globalThis.__cedarjs__client_references?.add(id);
257
+ const fns = code.matchAll(/export function (\w+)\(/g);
258
+ const consts = code.matchAll(/export const (\w+) = \(/g);
259
+ const names = [...fns, ...consts].map(([, name]) => name);
260
+ const result = [
261
+ `import { registerClientReference } from "react-server-dom-webpack/server.edge";`,
262
+ "",
263
+ ...names.map((name) => {
264
+ return name === "default" ? `export default registerClientReference({}, "${id}", "${name}");` : `export const ${name} = registerClientReference({}, "${id}", "${name}");`;
265
+ })
266
+ ].join("\n");
267
+ console.log("rsc-record-and-transform-use-client-plugin result");
268
+ console.log(
269
+ result.split("\n").map((line, i) => ` ${i + 1}: ${line}`).join("\n")
270
+ );
271
+ return { code: result, map: null };
272
+ }
273
+ },
274
+ rscTransformUseServerPlugin("", {}),
275
+ // The rscTransformUseClientPlugin maps paths like
276
+ // /Users/tobbe/.../rw-app/node_modules/@tobbe.dev/rsc-test/dist/rsc-test.es.js
277
+ // to
278
+ // /Users/tobbe/.../rw-app/web/dist/ssr/assets/rsc0.js
279
+ // That's why it needs the `clientEntryFiles` data
280
+ // (It does other things as well, but that's why it needs clientEntryFiles)
281
+ // rscTransformUseClientPlugin(clientEntryFiles),
282
+ // rscTransformUseServerPlugin(outDir, serverEntryFiles),
283
+ rscRoutesImports(),
284
+ {
285
+ name: "rsc-hot-update",
286
+ handleHotUpdate(ctx) {
287
+ console.log("rsc-hot-update ctx.modules", ctx.modules);
288
+ return [];
289
+ }
290
+ }
291
+ ],
292
+ build: {
293
+ ssr: true
294
+ },
295
+ server: {
296
+ // We never call `viteRscServer.listen()`, so we should run this in
297
+ // middleware mode
298
+ middlewareMode: true,
299
+ // The hmr/fast-refresh websocket in this server collides with the one in
300
+ // the other Vite server. So we can either disable it or run it on a
301
+ // different port.
302
+ // TODO (RSC): Figure out if we should disable or just pick a different
303
+ // port
304
+ ws: false
305
+ // hmr: {
306
+ // port: 24679,
307
+ // },
308
+ },
309
+ appType: "custom",
310
+ // Using a unique cache dir here to not clash with our other vite server
311
+ cacheDir: "../node_modules/.vite-rsc"
312
+ });
313
+ globalThis.__cedarjs__vite_rsc_runtime = createServerModuleRunner(
314
+ viteRscServer.environments.ssr
315
+ );
64
316
  const handleWithMiddleware = (route) => {
65
317
  return createServerAdapter(async (req) => {
66
- const middlewareRouter = await createMiddlewareRouter(vite);
318
+ const middlewareRouter = await createMiddlewareRouter(viteSsrDevServer);
67
319
  const middleware = middlewareRouter.find(
68
320
  req.method,
69
321
  req.url
@@ -73,19 +325,22 @@ async function createServer() {
73
325
  }
74
326
  const [mwRes] = await invoke(req, middleware, {
75
327
  route,
76
- viteDevServer: vite
328
+ viteSsrDevServer
77
329
  });
78
330
  return mwRes.toResponse();
79
331
  });
80
332
  };
81
- app.use(vite.middlewares);
333
+ app.use(viteSsrDevServer.middlewares);
82
334
  if (rscEnabled) {
83
- const { createRscRequestHandler } = await import("./rsc/rscRequestHandler.js");
335
+ createWebSocketServer();
336
+ const { createRscRequestHandler } = await globalThis.__cedarjs__vite_rsc_runtime.import(
337
+ new URL("./rsc/rscRequestHandler.js", import.meta.url).pathname
338
+ );
84
339
  app.use(
85
340
  "/rw-rsc",
86
- createRscRequestHandler({
87
- getMiddlewareRouter: async () => createMiddlewareRouter(vite),
88
- viteDevServer: vite
341
+ await createRscRequestHandler({
342
+ getMiddlewareRouter: async () => createMiddlewareRouter(viteSsrDevServer),
343
+ viteSsrDevServer
89
344
  })
90
345
  );
91
346
  }
@@ -95,18 +350,22 @@ async function createServer() {
95
350
  routes,
96
351
  clientEntryPath: rwPaths.web.entryClient,
97
352
  getStylesheetLinks: (route) => {
98
- return getCssLinks({ rwPaths, route, vite });
353
+ return getCssLinks({
354
+ rwPaths,
355
+ route,
356
+ viteSsrDevServer
357
+ });
99
358
  },
100
359
  // Recreate middleware router on each request in dev
101
- getMiddlewareRouter: async () => createMiddlewareRouter(vite)
360
+ getMiddlewareRouter: async () => createMiddlewareRouter(viteSsrDevServer)
102
361
  },
103
- vite
362
+ viteSsrDevServer
104
363
  );
105
364
  app.get("*", createServerAdapter(routeHandler));
106
365
  app.post("*", handleWithMiddleware());
107
366
  const port = getConfig().web.port;
108
367
  console.log(`Started server on http://localhost:${port}`);
109
- return app.listen(port);
368
+ return server.listen(port);
110
369
  }
111
370
  let devApp = createServer();
112
371
  process.stdin.on("data", async (data) => {
@@ -121,11 +380,11 @@ process.stdin.on("data", async (data) => {
121
380
  function getCssLinks({
122
381
  rwPaths,
123
382
  route,
124
- vite
383
+ viteSsrDevServer
125
384
  }) {
126
385
  const appAndRouteModules = componentsModules(
127
386
  [rwPaths.web.app, route?.filePath].filter(Boolean),
128
- vite
387
+ viteSsrDevServer
129
388
  );
130
389
  const collectedCss = collectCssPaths(appAndRouteModules);
131
390
  const cssLinks = Array.from(collectedCss);
@@ -65,6 +65,15 @@ function registerFwShims() {
65
65
  globalThis.__rw_module_cache__ ||= /* @__PURE__ */ new Map();
66
66
  globalThis.__webpack_chunk_load__ ||= async (id) => {
67
67
  console.log("registerFwShims chunk load id", id);
68
+ if (globalThis.__cedarjs__vite_ssr_runtime) {
69
+ return globalThis.__cedarjs__vite_ssr_runtime?.import(id).then((mod) => {
70
+ console.log("registerFwShims chunk load mod", mod);
71
+ if (mod.default && typeof mod.default === "object") {
72
+ return globalThis.__rw_module_cache__.set(id, mod.default);
73
+ }
74
+ return globalThis.__rw_module_cache__.set(id, mod);
75
+ });
76
+ }
68
77
  return import(id).then((mod) => {
69
78
  console.log("registerFwShims chunk load mod", mod);
70
79
  if (mod.default && typeof mod.default === "object") {
@@ -1 +1 @@
1
- {"version":3,"file":"vite-plugin-rsc-ssr-router-import.d.ts","sourceRoot":"","sources":["../../src/plugins/vite-plugin-rsc-ssr-router-import.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAKlC;;;GAGG;AACH,wBAAgB,kBAAkB,IAAI,MAAM,CAqC3C"}
1
+ {"version":3,"file":"vite-plugin-rsc-ssr-router-import.d.ts","sourceRoot":"","sources":["../../src/plugins/vite-plugin-rsc-ssr-router-import.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAKlC;;;GAGG;AACH,wBAAgB,kBAAkB,IAAI,MAAM,CAsC3C"}
@@ -11,8 +11,8 @@ function rscSsrRouterImport() {
11
11
  const routesFileId = normalizePath(getPaths().web.routes);
12
12
  return {
13
13
  name: "rsc-ssr-router-import",
14
- transform: async function(code, id) {
15
- if (id !== routesFileId) {
14
+ transform: async function(code, id, options) {
15
+ if (!options?.ssr || id !== routesFileId) {
16
16
  return null;
17
17
  }
18
18
  const ext = path.extname(id);
@@ -1 +1 @@
1
- {"version":3,"file":"vite-plugin-rsc-transform-server.d.ts","sourceRoot":"","sources":["../../src/plugins/vite-plugin-rsc-transform-server.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAElC,wBAAgB,2BAA2B,CACzC,MAAM,EAAE,MAAM,EACd,gBAAgB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACvC,MAAM,CA8GR"}
1
+ {"version":3,"file":"vite-plugin-rsc-transform-server.d.ts","sourceRoot":"","sources":["../../src/plugins/vite-plugin-rsc-transform-server.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAElC,wBAAgB,2BAA2B,CACzC,MAAM,EAAE,MAAM,EACd,gBAAgB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACvC,MAAM,CAuHR"}
@@ -8,6 +8,10 @@ function rscTransformUseServerPlugin(outDir, serverEntryFiles) {
8
8
  if (!code.includes("use server")) {
9
9
  return code;
10
10
  }
11
+ if (id.includes("node_modules/.vite") || id.includes("/react-server-dom-webpack/") || id.includes("/react-server-dom-webpack.server")) {
12
+ console.log("vite-plugin-rsc-transform-server.ts: Skipping", id);
13
+ return code;
14
+ }
11
15
  let mod;
12
16
  const isTypescript = id.endsWith(".ts") || id.endsWith(".tsx");
13
17
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"rscRenderer.d.ts","sourceRoot":"","sources":["../../src/rsc/rscRenderer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAWrD,MAAM,MAAM,WAAW,GAAG;IACxB,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC1B,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC1B,IAAI,CAAC,EAAE,OAAO,EAAE,GAAG,SAAS,CAAA;CAC7B,CAAA;AAID,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,WAAW,GAAG,OAAO,CAAC,cAAc,CAAC,CAE7E;AAyBD,wBAAsB,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC,CA2BtD"}
1
+ {"version":3,"file":"rscRenderer.d.ts","sourceRoot":"","sources":["../../src/rsc/rscRenderer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AASrD,MAAM,MAAM,WAAW,GAAG;IACxB,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC1B,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC1B,IAAI,CAAC,EAAE,OAAO,EAAE,GAAG,SAAS,CAAA;CAC7B,CAAA;AAID,wBAAsB,iBAAiB,CACrC,KAAK,EAAE,WAAW,GACjB,OAAO,CAAC,cAAc,CAAC,CAEzB;AAyCD,wBAAsB,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC,CA2BtD"}
@@ -1,18 +1,26 @@
1
1
  import path from "node:path";
2
- import { createElement } from "react";
3
- import { renderToReadableStream } from "react-server-dom-webpack/server.edge";
4
2
  import { getPaths } from "@cedarjs/project-config";
5
3
  import { getEntriesFromDist } from "../lib/entries.js";
6
4
  import { StatusError } from "../lib/StatusError.js";
5
+ import { importRscReact, importRsdwServer } from "./utils.js";
7
6
  let absoluteClientEntries = {};
8
- function renderRscToStream(input) {
7
+ async function renderRscToStream(input) {
9
8
  return input.rscId ? renderRsc(input) : executeRsa(input);
10
9
  }
11
10
  async function loadServerFile(filePath) {
12
11
  console.log("rscRenderer.ts loadServerFile filePath", filePath);
12
+ if (globalThis.__cedarjs__vite_rsc_runtime) {
13
+ const serverMod = await globalThis.__cedarjs__vite_rsc_runtime.import(filePath);
14
+ return serverMod.default ? serverMod.default : serverMod;
15
+ }
13
16
  return import(`file://${filePath}`);
14
17
  }
15
18
  const getRoutesComponent = async () => {
19
+ if (globalThis.__cedarjs__vite_rsc_runtime) {
20
+ const routesPath2 = getPaths().web.routes;
21
+ const routesMod = await globalThis.__cedarjs__vite_rsc_runtime.import(routesPath2);
22
+ return routesMod.default;
23
+ }
16
24
  const serverEntries = await getEntriesFromDist();
17
25
  console.log("rscRenderer.ts serverEntries", serverEntries);
18
26
  const routesPath = path.join(
@@ -53,10 +61,12 @@ function getBundlerConfig() {
53
61
  {},
54
62
  {
55
63
  get(_target, encodedId) {
56
- console.log("Proxy get encodedId", encodedId);
64
+ console.log("rscRenderer.ts Proxy get encodedId", encodedId);
57
65
  const [filePath, name] = encodedId.split("#");
66
+ console.log("filePath", filePath);
67
+ console.log("name", name);
58
68
  const filePathSlash = filePath.replaceAll("\\", "/");
59
- const id = absoluteClientEntries[filePathSlash];
69
+ const id = globalThis.__cedarjs__vite_rsc_runtime ? filePath : absoluteClientEntries[filePathSlash];
60
70
  console.log("absoluteClientEntries", absoluteClientEntries);
61
71
  console.log("filePath", filePathSlash);
62
72
  if (!id) {
@@ -79,6 +89,8 @@ async function renderRsc(input) {
79
89
  throw new Error("Unexpected input. Missing rscId or props.");
80
90
  }
81
91
  console.log("renderRsc input", input);
92
+ const { createElement } = await importRscReact();
93
+ const { renderToReadableStream } = await importRsdwServer();
82
94
  const serverRoutes = await getRoutesComponent();
83
95
  const model = {
84
96
  __cedarjs__Routes: createElement(serverRoutes)
@@ -115,6 +127,8 @@ async function executeRsa(input) {
115
127
  console.log("rscRenderer.ts args", ...input.args);
116
128
  const data = await method(...input.args);
117
129
  console.log("rscRenderer.ts rsa return data", data);
130
+ const { createElement } = await importRscReact();
131
+ const { renderToReadableStream } = await importRsdwServer();
118
132
  const serverRoutes = await getRoutesComponent();
119
133
  console.log("rscRenderer.ts executeRsa serverRoutes", serverRoutes);
120
134
  const model = {
@@ -3,8 +3,8 @@ import type Router from 'find-my-way';
3
3
  import type { ViteDevServer } from 'vite';
4
4
  interface CreateRscRequestHandlerOptions {
5
5
  getMiddlewareRouter: () => Promise<Router.Instance<any>>;
6
- viteDevServer?: ViteDevServer;
6
+ viteSsrDevServer?: ViteDevServer;
7
7
  }
8
- export declare function createRscRequestHandler(options: CreateRscRequestHandlerOptions): (req: ExpressRequest, res: ExpressResponse, next: () => void) => Promise<void>;
8
+ export declare function createRscRequestHandler(options: CreateRscRequestHandlerOptions): Promise<(req: ExpressRequest, res: ExpressResponse, next: () => void) => Promise<void>>;
9
9
  export {};
10
10
  //# sourceMappingURL=rscRequestHandler.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"rscRequestHandler.d.ts","sourceRoot":"","sources":["../../src/rsc/rscRequestHandler.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EACV,OAAO,IAAI,cAAc,EACzB,QAAQ,IAAI,eAAe,EAC5B,MAAM,SAAS,CAAA;AAChB,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AAErC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,MAAM,CAAA;AAgBzC,UAAU,8BAA8B;IACtC,mBAAmB,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAA;IACxD,aAAa,CAAC,EAAE,aAAa,CAAA;CAC9B;AAED,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,8BAA8B,IAMrC,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,MAAM,MAAM,IAAI,mBAqHnB"}
1
+ {"version":3,"file":"rscRequestHandler.d.ts","sourceRoot":"","sources":["../../src/rsc/rscRequestHandler.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EACV,OAAO,IAAI,cAAc,EACzB,QAAQ,IAAI,eAAe,EAC5B,MAAM,SAAS,CAAA;AAChB,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AAErC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,MAAM,CAAA;AAazC,UAAU,8BAA8B;IACtC,mBAAmB,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAA;IACxD,gBAAgB,CAAC,EAAE,aAAa,CAAA;CACjC;AAED,wBAAsB,uBAAuB,CAC3C,OAAO,EAAE,8BAA8B,iBAShC,cAAc,OACd,eAAe,QACd,MAAM,IAAI,oBAqHnB"}
@@ -8,10 +8,10 @@ import {
8
8
  } from "../bundled/react-server-dom-webpack.server.js";
9
9
  import { hasStatusCode } from "../lib/StatusError.js";
10
10
  import { invoke } from "../middleware/invokeMiddleware.js";
11
- import { renderRscToStream } from "./rscRenderer.js";
12
- import { sendRscFlightToStudio } from "./rscStudioHandlers.js";
13
11
  const BASE_PATH = "/rw-rsc/";
14
- function createRscRequestHandler(options) {
12
+ async function createRscRequestHandler(options) {
13
+ const { renderRscToStream } = await import("./rscRenderer.js");
14
+ const { sendRscFlightToStudio } = await import("./rscStudioHandlers.js");
15
15
  return async (req, res, next) => {
16
16
  console.log("BASE_PATH", BASE_PATH);
17
17
  console.log("req.originalUrl", req.originalUrl, "req.url", req.url);
@@ -26,7 +26,7 @@ function createRscRequestHandler(options) {
26
26
  matchedMw?.handler,
27
27
  {
28
28
  params: matchedMw?.params,
29
- viteDevServer: options.viteDevServer
29
+ viteSsrDevServer: options.viteSsrDevServer
30
30
  }
31
31
  );
32
32
  const webRes = mwResponse.toResponse();
@@ -5,13 +5,13 @@ import { createServerAdapter } from "@whatwg-node/server";
5
5
  import { config as loadDotEnv } from "dotenv-defaults";
6
6
  import express from "express";
7
7
  import { createProxyMiddleware } from "http-proxy-middleware";
8
- import WebSocket, { WebSocketServer } from "ws";
9
8
  import { getConfig, getPaths } from "@cedarjs/project-config";
10
9
  import { getRscStylesheetLinkGenerator } from "@cedarjs/router/rscCss";
11
10
  import { createPerRequestMap, createServerStorage } from "@cedarjs/server-store";
12
11
  import { registerFwGlobalsAndShims } from "./lib/registerFwGlobalsAndShims.js";
13
12
  import { invoke } from "./middleware/invokeMiddleware.js";
14
13
  import { createMiddlewareRouter } from "./middleware/register.js";
14
+ import { createWebSocketServer } from "./rsc/rscWebSocketServer.js";
15
15
  import { createReactStreamingHandler } from "./streaming/createReactStreamingHandler.js";
16
16
  import { convertExpressHeaders, getFullUrl } from "./utils.js";
17
17
  loadDotEnv({
@@ -86,7 +86,7 @@ async function runFeServer() {
86
86
  const { createRscRequestHandler } = await import("./rsc/rscRequestHandler.js");
87
87
  app.use(
88
88
  "/rw-rsc",
89
- createRscRequestHandler({
89
+ await createRscRequestHandler({
90
90
  getMiddlewareRouter: async () => middlewareRouter
91
91
  })
92
92
  );
@@ -106,25 +106,6 @@ async function runFeServer() {
106
106
  `Started production FE server on http://localhost:${rwConfig.web.port}`
107
107
  );
108
108
  }
109
- function createWebSocketServer() {
110
- const wsServer = new WebSocketServer({ port: 18998 });
111
- wsServer.on("connection", (ws) => {
112
- console.log("A new client connected.");
113
- ws.on("message", (data) => {
114
- const message = data.toString();
115
- console.log("runFeServer.ts: Received message:");
116
- console.log(message.slice(0, 120) + "...");
117
- wsServer.clients.forEach((client) => {
118
- if (client.readyState === WebSocket.OPEN) {
119
- client.send(message);
120
- }
121
- });
122
- });
123
- ws.on("close", () => {
124
- console.log("A client disconnected.");
125
- });
126
- });
127
- }
128
109
  runFeServer();
129
110
  export {
130
111
  runFeServer
@@ -7,6 +7,6 @@ interface CreateReactStreamingHandlerOptions {
7
7
  getStylesheetLinks: (route?: RWRouteManifestItem | RouteSpec) => string[];
8
8
  getMiddlewareRouter: () => Promise<Router.Instance<any>>;
9
9
  }
10
- export declare const createReactStreamingHandler: ({ routes, clientEntryPath, getStylesheetLinks, getMiddlewareRouter, }: CreateReactStreamingHandlerOptions, viteDevServer?: ViteDevServer) => Promise<(req: Request) => Promise<Response>>;
10
+ export declare const createReactStreamingHandler: ({ routes, clientEntryPath, getStylesheetLinks, getMiddlewareRouter, }: CreateReactStreamingHandlerOptions, viteSsrDevServer?: ViteDevServer) => Promise<(req: Request) => Promise<Response>>;
11
11
  export {};
12
12
  //# sourceMappingURL=createReactStreamingHandler.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"createReactStreamingHandler.d.ts","sourceRoot":"","sources":["../../src/streaming/createReactStreamingHandler.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AAGrC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,MAAM,CAAA;AAIzC,OAAO,KAAK,EAAE,SAAS,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAA;AAoBvE,UAAU,kCAAkC;IAC1C,MAAM,EAAE,mBAAmB,EAAE,CAAA;IAC7B,eAAe,EAAE,MAAM,CAAA;IACvB,kBAAkB,EAAE,CAAC,KAAK,CAAC,EAAE,mBAAmB,GAAG,SAAS,KAAK,MAAM,EAAE,CAAA;IACzE,mBAAmB,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAA;CACzD;AAOD,eAAO,MAAM,2BAA2B,GACtC,uEAKG,kCAAkC,EACrC,gBAAgB,aAAa,mBAuBV,OAAO,uBA8I3B,CAAA"}
1
+ {"version":3,"file":"createReactStreamingHandler.d.ts","sourceRoot":"","sources":["../../src/streaming/createReactStreamingHandler.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AAGrC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,MAAM,CAAA;AAIzC,OAAO,KAAK,EAAE,SAAS,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAA;AAoBvE,UAAU,kCAAkC;IAC1C,MAAM,EAAE,mBAAmB,EAAE,CAAA;IAC7B,eAAe,EAAE,MAAM,CAAA;IACvB,kBAAkB,EAAE,CAAC,KAAK,CAAC,EAAE,mBAAmB,GAAG,SAAS,KAAK,MAAM,EAAE,CAAA;IACzE,mBAAmB,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAA;CACzD;AAOD,eAAO,MAAM,2BAA2B,GACtC,uEAKG,kCAAkC,EACrC,mBAAmB,aAAa,mBAuBb,OAAO,uBAiJ3B,CAAA"}