@cedarjs/vite 6.0.0-canary.2683 → 6.0.0-canary.2686

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 +1 @@
1
- {"version":3,"file":"apiDevMiddleware.d.ts","sourceRoot":"","sources":["../src/apiDevMiddleware.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAsB,aAAa,EAAE,MAAM,MAAM,CAAA;AA+D7D,wBAAsB,gBAAgB,CAAC,UAAU,EAAE,aAAa,iBAe/D;AA+GD,wBAAsB,mBAAmB,IAAI,OAAO,CAAC,aAAa,CAAC,CA6IlE;AA0BD,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,aAAa,GAAG,IAAI,CA0EhE;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,KAIrB,SAAS,OAAO,KAAG,OAAO,CAAC,QAAQ,CAAC,CAoFnD;AAED,wBAAsB,qBAAqB,IAAI,OAAO,CAAC;IACrD,UAAU,EAAE,aAAa,CAAA;IACzB,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;IAC1B,OAAO,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAA;CACjD,CAAC,CAcD"}
1
+ {"version":3,"file":"apiDevMiddleware.d.ts","sourceRoot":"","sources":["../src/apiDevMiddleware.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAsB,aAAa,EAAE,MAAM,MAAM,CAAA;AAgE7D,wBAAsB,gBAAgB,CAAC,UAAU,EAAE,aAAa,iBAe/D;AA+GD,wBAAsB,mBAAmB,IAAI,OAAO,CAAC,aAAa,CAAC,CA8IlE;AA0BD,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,aAAa,GAAG,IAAI,CA0EhE;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,KAIrB,SAAS,OAAO,KAAG,OAAO,CAAC,QAAQ,CAAC,CAoFnD;AAED,wBAAsB,qBAAqB,IAAI,OAAO,CAAC;IACrD,UAAU,EAAE,aAAa,CAAA;IACzB,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;IAC1B,OAAO,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAA;CACjD,CAAC,CAcD"}
@@ -25,6 +25,7 @@ import { cedarAutoImportsPlugin } from "./plugins/vite-plugin-cedar-auto-import.
25
25
  import { cedarDirectoryNamedImportPlugin } from "./plugins/vite-plugin-cedar-directory-named-import.js";
26
26
  import { applyGraphqlOptionsExtract } from "./plugins/vite-plugin-cedar-graphql-options-extract.js";
27
27
  import { cedarImportDirPlugin } from "./plugins/vite-plugin-cedar-import-dir.js";
28
+ import { cedarApiLogFormatterDevPlugin } from "./plugins/vite-plugin-cedar-log-formatter-dev.js";
28
29
  import { applyOtelWrapping } from "./plugins/vite-plugin-cedar-otel-wrapping.js";
29
30
  import { cedarjsJobPathInjectorPlugin } from "./plugins/vite-plugin-cedarjs-job-path-injector.js";
30
31
  function resolveWithExtensions(id) {
@@ -170,6 +171,7 @@ async function createApiViteServer() {
170
171
  // tsconfigPaths resolves user-defined tsconfig.json `paths` aliases; it
171
172
  // replaces the Babel module-resolver's tsconfig-paths handling for dev.
172
173
  tsconfigPaths(),
174
+ cedarApiLogFormatterDevPlugin(),
173
175
  {
174
176
  name: "cedar-api-src-redirect",
175
177
  enforce: "pre",
@@ -54,6 +54,7 @@ var import_vite_plugin_cedar_auto_import = require("./plugins/vite-plugin-cedar-
54
54
  var import_vite_plugin_cedar_directory_named_import = require("./plugins/vite-plugin-cedar-directory-named-import.js");
55
55
  var import_vite_plugin_cedar_graphql_options_extract = require("./plugins/vite-plugin-cedar-graphql-options-extract.js");
56
56
  var import_vite_plugin_cedar_import_dir = require("./plugins/vite-plugin-cedar-import-dir.js");
57
+ var import_vite_plugin_cedar_log_formatter_dev = require("./plugins/vite-plugin-cedar-log-formatter-dev.js");
57
58
  var import_vite_plugin_cedar_otel_wrapping = require("./plugins/vite-plugin-cedar-otel-wrapping.js");
58
59
  var import_vite_plugin_cedarjs_job_path_injector = require("./plugins/vite-plugin-cedarjs-job-path-injector.js");
59
60
  const tsconfigPaths = (
@@ -204,6 +205,7 @@ async function createApiViteServer() {
204
205
  // tsconfigPaths resolves user-defined tsconfig.json `paths` aliases; it
205
206
  // replaces the Babel module-resolver's tsconfig-paths handling for dev.
206
207
  tsconfigPaths(),
208
+ (0, import_vite_plugin_cedar_log_formatter_dev.cedarApiLogFormatterDevPlugin)(),
207
209
  {
208
210
  name: "cedar-api-src-redirect",
209
211
  enforce: "pre",
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var vite_plugin_cedar_log_formatter_dev_exports = {};
20
+ __export(vite_plugin_cedar_log_formatter_dev_exports, {
21
+ cedarApiLogFormatterDevPlugin: () => cedarApiLogFormatterDevPlugin
22
+ });
23
+ module.exports = __toCommonJS(vite_plugin_cedar_log_formatter_dev_exports);
24
+ const INTERCEPTED_SPECIFIER = "@cedarjs/api/logger";
25
+ const VIRTUAL_MODULE_ID = "virtual:cedar-api-logger-dev";
26
+ const RESOLVED_VIRTUAL_MODULE_ID = "\0" + VIRTUAL_MODULE_ID;
27
+ function cedarApiLogFormatterDevPlugin() {
28
+ return {
29
+ name: "cedar-api-log-formatter-dev",
30
+ enforce: "pre",
31
+ resolveId(id, importer) {
32
+ if (id === INTERCEPTED_SPECIFIER && importer !== RESOLVED_VIRTUAL_MODULE_ID) {
33
+ return RESOLVED_VIRTUAL_MODULE_ID;
34
+ }
35
+ return null;
36
+ },
37
+ load(id) {
38
+ if (id !== RESOLVED_VIRTUAL_MODULE_ID) {
39
+ return null;
40
+ }
41
+ return `
42
+ import * as realLogger from ${JSON.stringify(INTERCEPTED_SPECIFIER)}
43
+ import { LogFormatter } from '@cedarjs/api-server/logFormatter'
44
+
45
+ export * from ${JSON.stringify(INTERCEPTED_SPECIFIER)}
46
+
47
+ function createFormattingDestination() {
48
+ const format = LogFormatter()
49
+ let buffered = ''
50
+
51
+ return {
52
+ write(chunk) {
53
+ buffered += chunk
54
+ const lines = buffered.split('\\n')
55
+ buffered = lines.pop() ?? ''
56
+
57
+ for (const line of lines) {
58
+ if (line.length > 0) {
59
+ process.stdout.write(format(line))
60
+ }
61
+ }
62
+ },
63
+ }
64
+ }
65
+
66
+ export function createLogger(params = {}) {
67
+ if (params.destination) {
68
+ return realLogger.createLogger(params)
69
+ }
70
+
71
+ return realLogger.createLogger({
72
+ ...params,
73
+ destination: createFormattingDestination(),
74
+ })
75
+ }
76
+ `;
77
+ }
78
+ };
79
+ }
80
+ // Annotate the CommonJS export names for ESM import in node:
81
+ 0 && (module.exports = {
82
+ cedarApiLogFormatterDevPlugin
83
+ });
@@ -0,0 +1,21 @@
1
+ import type { Plugin } from 'vite';
2
+ /**
3
+ * Dev-only Vite plugin that makes the api's pino logger pretty-print
4
+ * through the same formatter plain `yarn cedar dev` gets via its
5
+ * `... | cedar-log-formatter` shell pipe.
6
+ *
7
+ * `--ud` mode runs the api in-process as Vite SSR middleware, so there's no
8
+ * separate api process whose stdout a shell pipe could format externally,
9
+ * and pino's default destination writes straight to file descriptor 1
10
+ * (bypassing `process.stdout.write`), so patching stdout wouldn't see the
11
+ * log lines either. Instead, this intercepts resolution of
12
+ * `@cedarjs/api/logger` and swaps in a wrapped `createLogger` that injects
13
+ * a formatting `destination` whenever the caller (the app's own
14
+ * `api/src/lib/logger.ts`) doesn't already supply one.
15
+ *
16
+ * Only registered in `createApiViteServer()`'s dev-only Vite instance —
17
+ * never touched by any production build path — so this has no effect on
18
+ * (and no dependency footprint added to) a deployed api.
19
+ */
20
+ export declare function cedarApiLogFormatterDevPlugin(): Plugin;
21
+ //# sourceMappingURL=vite-plugin-cedar-log-formatter-dev.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vite-plugin-cedar-log-formatter-dev.d.ts","sourceRoot":"","sources":["../../src/plugins/vite-plugin-cedar-log-formatter-dev.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAMlC;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,6BAA6B,IAAI,MAAM,CA6DtD"}
@@ -0,0 +1,59 @@
1
+ const INTERCEPTED_SPECIFIER = "@cedarjs/api/logger";
2
+ const VIRTUAL_MODULE_ID = "virtual:cedar-api-logger-dev";
3
+ const RESOLVED_VIRTUAL_MODULE_ID = "\0" + VIRTUAL_MODULE_ID;
4
+ function cedarApiLogFormatterDevPlugin() {
5
+ return {
6
+ name: "cedar-api-log-formatter-dev",
7
+ enforce: "pre",
8
+ resolveId(id, importer) {
9
+ if (id === INTERCEPTED_SPECIFIER && importer !== RESOLVED_VIRTUAL_MODULE_ID) {
10
+ return RESOLVED_VIRTUAL_MODULE_ID;
11
+ }
12
+ return null;
13
+ },
14
+ load(id) {
15
+ if (id !== RESOLVED_VIRTUAL_MODULE_ID) {
16
+ return null;
17
+ }
18
+ return `
19
+ import * as realLogger from ${JSON.stringify(INTERCEPTED_SPECIFIER)}
20
+ import { LogFormatter } from '@cedarjs/api-server/logFormatter'
21
+
22
+ export * from ${JSON.stringify(INTERCEPTED_SPECIFIER)}
23
+
24
+ function createFormattingDestination() {
25
+ const format = LogFormatter()
26
+ let buffered = ''
27
+
28
+ return {
29
+ write(chunk) {
30
+ buffered += chunk
31
+ const lines = buffered.split('\\n')
32
+ buffered = lines.pop() ?? ''
33
+
34
+ for (const line of lines) {
35
+ if (line.length > 0) {
36
+ process.stdout.write(format(line))
37
+ }
38
+ }
39
+ },
40
+ }
41
+ }
42
+
43
+ export function createLogger(params = {}) {
44
+ if (params.destination) {
45
+ return realLogger.createLogger(params)
46
+ }
47
+
48
+ return realLogger.createLogger({
49
+ ...params,
50
+ destination: createFormattingDestination(),
51
+ })
52
+ }
53
+ `;
54
+ }
55
+ };
56
+ }
57
+ export {
58
+ cedarApiLogFormatterDevPlugin
59
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cedarjs/vite",
3
- "version": "6.0.0-canary.2683",
3
+ "version": "6.0.0-canary.2686",
4
4
  "description": "Vite configuration package for CedarJS",
5
5
  "repository": {
6
6
  "type": "git",
@@ -63,15 +63,16 @@
63
63
  "@babel/parser": "7.29.7",
64
64
  "@babel/traverse": "7.29.7",
65
65
  "@babel/types": "7.29.7",
66
- "@cedarjs/api": "6.0.0-canary.2683",
67
- "@cedarjs/babel-config": "6.0.0-canary.2683",
68
- "@cedarjs/context": "6.0.0-canary.2683",
69
- "@cedarjs/cookie-jar": "6.0.0-canary.2683",
70
- "@cedarjs/graphql-server": "6.0.0-canary.2683",
71
- "@cedarjs/internal": "6.0.0-canary.2683",
72
- "@cedarjs/project-config": "6.0.0-canary.2683",
73
- "@cedarjs/server-store": "6.0.0-canary.2683",
74
- "@cedarjs/testing": "6.0.0-canary.2683",
66
+ "@cedarjs/api": "6.0.0-canary.2686",
67
+ "@cedarjs/api-server": "6.0.0-canary.2686",
68
+ "@cedarjs/babel-config": "6.0.0-canary.2686",
69
+ "@cedarjs/context": "6.0.0-canary.2686",
70
+ "@cedarjs/cookie-jar": "6.0.0-canary.2686",
71
+ "@cedarjs/graphql-server": "6.0.0-canary.2686",
72
+ "@cedarjs/internal": "6.0.0-canary.2686",
73
+ "@cedarjs/project-config": "6.0.0-canary.2686",
74
+ "@cedarjs/server-store": "6.0.0-canary.2686",
75
+ "@cedarjs/testing": "6.0.0-canary.2686",
75
76
  "@fastify/url-data": "6.0.3",
76
77
  "@swc/core": "1.15.41",
77
78
  "@universal-deploy/store": "^0.2.1",
@@ -108,9 +109,9 @@
108
109
  },
109
110
  "devDependencies": {
110
111
  "@arethetypeswrong/cli": "0.18.5",
111
- "@cedarjs/auth": "6.0.0-canary.2683",
112
- "@cedarjs/router": "6.0.0-canary.2683",
113
- "@cedarjs/web": "6.0.0-canary.2683",
112
+ "@cedarjs/auth": "6.0.0-canary.2686",
113
+ "@cedarjs/router": "6.0.0-canary.2686",
114
+ "@cedarjs/web": "6.0.0-canary.2686",
114
115
  "@hyrious/esbuild-plugin-commonjs": "0.2.6",
115
116
  "@jridgewell/trace-mapping": "0.3.31",
116
117
  "@types/aws-lambda": "8.10.162",
@@ -1,413 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") {
11
- for (let key of __getOwnPropNames(from))
12
- if (!__hasOwnProp.call(to, key) && key !== except)
13
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
- }
15
- return to;
16
- };
17
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
- // If the importer is in node compatibility mode or this is not an ESM
19
- // file that has been converted to a CommonJS file using a Babel-
20
- // compatible transform (i.e. "__esModule" has not been set), then set
21
- // "default" to the CommonJS "module.exports" for node compatibility.
22
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
- mod
24
- ));
25
- var import_node_http = __toESM(require("node:http"), 1);
26
- var import_server = require("@whatwg-node/server");
27
- var import_express = __toESM(require("express"), 1);
28
- var import_vite = require("vite");
29
- var import_vite_plugin_cjs_interop = require("vite-plugin-cjs-interop");
30
- var import_routes = require("@cedarjs/internal/dist/routes.js");
31
- var import_project_config = require("@cedarjs/project-config");
32
- var import_server_store = require("@cedarjs/server-store");
33
- var import_registerFwGlobalsAndShims = require("./lib/registerFwGlobalsAndShims.js");
34
- var import_invokeMiddleware = require("./middleware/invokeMiddleware.js");
35
- var import_register = require("./middleware/register.js");
36
- var import_vite_plugin_rsc_routes_auto_loader = require("./plugins/vite-plugin-rsc-routes-auto-loader.js");
37
- var import_vite_plugin_rsc_routes_imports = require("./plugins/vite-plugin-rsc-routes-imports.js");
38
- var import_vite_plugin_rsc_ssr_router_import = require("./plugins/vite-plugin-rsc-ssr-router-import.js");
39
- var import_vite_plugin_rsc_transform_server = require("./plugins/vite-plugin-rsc-transform-server.js");
40
- var import_rscWebSocketServer = require("./rsc/rscWebSocketServer.js");
41
- var import_collectCss = require("./streaming/collectCss.js");
42
- var import_createReactStreamingHandler = require("./streaming/createReactStreamingHandler.js");
43
- var import_utils = require("./utils.js");
44
- const import_meta = {};
45
- globalThis.__REDWOOD__PRERENDER_PAGES = {};
46
- globalThis.__cedarjs__vite_ssr_runtime = void 0;
47
- globalThis.__cedarjs__vite_rsc_runtime = void 0;
48
- async function createServer() {
49
- (0, import_utils.ensureProcessDirWeb)();
50
- (0, import_registerFwGlobalsAndShims.registerFwGlobalsAndShims)();
51
- const app = (0, import_express.default)();
52
- const server = import_node_http.default.createServer(app);
53
- const rwPaths = (0, import_project_config.getPaths)();
54
- const rscEnabled = (0, import_project_config.getConfig)().experimental.rsc?.enabled ?? false;
55
- const serverStorage = (0, import_server_store.createServerStorage)();
56
- app.use("*", (req, _res, next) => {
57
- const fullUrl = (0, import_utils.getFullUrl)(req, rscEnabled);
58
- const perReqStore = (0, import_server_store.createPerRequestMap)({
59
- // Convert express headers to fetch header
60
- headers: (0, import_utils.convertExpressHeaders)(req.headersDistinct),
61
- fullUrl
62
- });
63
- serverStorage.run(perReqStore, next);
64
- });
65
- if (!rwPaths.web.entryServer || !rwPaths.web.entryClient) {
66
- throw new Error(
67
- "Vite entry points not found. Please check that your project has an entry.client.{jsx,tsx} and entry.server.{jsx,tsx} file in the web/src directory."
68
- );
69
- }
70
- if (!rwPaths.web.viteConfig) {
71
- throw new Error(
72
- "Vite config not found. Please set up Vite before running the dev server."
73
- );
74
- }
75
- const viteSsrDevServer = await (0, import_vite.createServer)({
76
- configFile: rwPaths.web.viteConfig,
77
- envFile: false,
78
- define: {
79
- "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV)
80
- },
81
- ssr: {
82
- // Inline every file apart from node built-ins. We want vite/rollup to
83
- // inline dependencies in the server build. This gets round runtime
84
- // importing of "server-only" and other packages with poisoned imports.
85
- //
86
- // Files included in `noExternal` are files we want Vite to analyze
87
- // As of vite 5.2 `true` here means "all except node built-ins"
88
- // noExternal: true,
89
- // TODO (RSC): Other frameworks build for RSC without `noExternal: true`.
90
- // What are we missing here? When/why is that a better choice? I know
91
- // we would have to explicitly add a bunch of packages to noExternal, if
92
- // we wanted to go that route.
93
- // noExternal: ['@tobbe.dev/rsc-test'],
94
- // Can't inline prisma client (db calls fail at runtime) or react-dom
95
- // (css pre-init failure)
96
- // Server store has to be externalized, because it's a singleton (shared between FW and App)
97
- external: [
98
- "@prisma/client",
99
- "@prisma/adapter-better-sqlite3",
100
- "@prisma/fetch-engine",
101
- "@prisma/internals",
102
- "better-sqlite3",
103
- "@cedarjs/auth-dbauth-api",
104
- "@cedarjs/cookie-jar",
105
- "@cedarjs/server-store",
106
- "@simplewebauthn/server",
107
- "graphql-scalars",
108
- "minimatch",
109
- "playwright",
110
- "react-dom"
111
- ],
112
- resolve: {
113
- // These conditions are used in the plugin pipeline, and only affect non-externalized
114
- // dependencies during the SSR build. Which because of `noExternal: true` means all
115
- // dependencies apart from node built-ins.
116
- // TODO (RSC): What's the difference between `conditions` and
117
- // `externalConditions`? When is one used over the other?
118
- // conditions: ['react-server'],
119
- // externalConditions: ['react-server'],
120
- },
121
- optimizeDeps: {
122
- // We need Vite to optimize these dependencies so that they are resolved
123
- // with the correct conditions. And so that CJS modules work correctly.
124
- // include: [
125
- // 'react/**/*',
126
- // 'react-dom/server',
127
- // 'react-dom/server.edge',
128
- // 'rehackt',
129
- // 'react-server-dom-webpack/server',
130
- // 'react-server-dom-webpack/client',
131
- // '@apollo/client/cache/*',
132
- // '@apollo/client/utilities/*',
133
- // '@apollo/client/react/hooks/*',
134
- // 'react-fast-compare',
135
- // 'invariant',
136
- // 'shallowequal',
137
- // 'graphql/language/*',
138
- // 'stacktracey',
139
- // 'deepmerge',
140
- // 'fast-glob',
141
- // ],
142
- }
143
- },
144
- resolve: {
145
- // conditions: ['react-server'],
146
- },
147
- plugins: [
148
- (0, import_vite_plugin_cjs_interop.cjsInterop)({
149
- dependencies: [
150
- // Skip ESM modules: rwjs/auth, rwjs/web, rwjs/auth-*-middleware, rwjs/router
151
- "@cedarjs/forms",
152
- "@cedarjs/prerender/*",
153
- "@cedarjs/auth-*-api",
154
- // Add more to the pattern below as they're converted to dual ESM/CJS
155
- // modules
156
- // '@cedarjs/auth-!(dbauth|auth0|clerk)-web',
157
- "@cedarjs/auth-!(dbauth)-web"
158
- ]
159
- }),
160
- rscEnabled && (0, import_vite_plugin_rsc_routes_auto_loader.rscRoutesAutoLoader)(),
161
- rscEnabled && (0, import_vite_plugin_rsc_ssr_router_import.rscSsrRouterImport)()
162
- ],
163
- server: { middlewareMode: true },
164
- logLevel: "info",
165
- clearScreen: false,
166
- appType: "custom"
167
- });
168
- globalThis.__cedarjs__vite_ssr_runtime = (0, import_vite.createServerModuleRunner)(
169
- viteSsrDevServer.environments.ssr
170
- );
171
- globalThis.__cedarjs__client_references = /* @__PURE__ */ new Set();
172
- globalThis.__cedarjs__server_references = /* @__PURE__ */ new Set();
173
- const viteRscServer = await (0, import_vite.createServer)({
174
- envFile: false,
175
- define: {
176
- "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV)
177
- },
178
- ssr: {
179
- // Inline every file apart from node built-ins. We want vite/rollup to
180
- // inline dependencies in the server build. This gets round runtime
181
- // importing of "server-only" and other packages with poisoned imports.
182
- //
183
- // Files included in `noExternal` are files we want Vite to analyze
184
- // As of vite 5.2 `true` here means "all except node built-ins"
185
- noExternal: true,
186
- // TODO (RSC): Other frameworks build for RSC without `noExternal: true`.
187
- // What are we missing here? When/why is that a better choice? I know
188
- // we would have to explicitly add a bunch of packages to noExternal, if
189
- // we wanted to go that route.
190
- // noExternal: ['@tobbe.dev/rsc-test'],
191
- // Can't inline prisma client (db calls fail at runtime) or react-dom
192
- // (css pre-init failure)
193
- // Server store has to be externalized, because it's a singleton (shared between FW and App)
194
- external: [
195
- "@prisma/client",
196
- "@prisma/adapter-better-sqlite3",
197
- "@prisma/fetch-engine",
198
- "@prisma/internals",
199
- "better-sqlite3",
200
- "@cedarjs/auth-dbauth-api",
201
- "@cedarjs/cookie-jar",
202
- "@cedarjs/server-store",
203
- "@cedarjs/structure",
204
- "@simplewebauthn/server",
205
- "graphql-scalars",
206
- "minimatch",
207
- "playwright",
208
- "react-dom"
209
- ],
210
- resolve: {
211
- // These conditions are used in the plugin pipeline, and only affect non-externalized
212
- // dependencies during the SSR build. Which because of `noExternal: true` means all
213
- // dependencies apart from node built-ins.
214
- // TODO (RSC): What's the difference between `conditions` and
215
- // `externalConditions`? When is one used over the other?
216
- // In Vite 6, we must include `defaultServerConditions` alongside
217
- // `react-server` so that nested condition maps (e.g. the `node`
218
- // sub-condition inside `react-server-dom-webpack/server`'s exports)
219
- // can still be resolved. Without `node` (or another environment
220
- // condition), the resolver throws "No known conditions for
221
- // './server' specifier in 'react-server-dom-webpack' package".
222
- conditions: ["react-server", ...import_vite.defaultServerConditions],
223
- externalConditions: ["react-server", ...import_vite.defaultServerConditions]
224
- },
225
- optimizeDeps: {
226
- // We need Vite to optimize these dependencies so that they are resolved
227
- // with the correct conditions. And so that CJS modules work correctly.
228
- include: [
229
- "react/**/*",
230
- "react-dom/server",
231
- "react-dom/server.edge",
232
- "react-server-dom-webpack/server",
233
- "react-server-dom-webpack/server.edge",
234
- "react-server-dom-webpack/client",
235
- "react-server-dom-webpack/client.edge",
236
- "@apollo/client",
237
- "@apollo/client/cache",
238
- "@apollo/client/link/context",
239
- "@apollo/client/link/persisted-queries",
240
- "@apollo/client/react",
241
- "@apollo/client/utilities",
242
- "rxjs",
243
- "react-fast-compare",
244
- "invariant",
245
- "shallowequal",
246
- "graphql/language/*",
247
- "stacktracey",
248
- "deepmerge",
249
- "fast-glob",
250
- "@whatwg-node/fetch",
251
- "busboy",
252
- "cookie"
253
- ],
254
- // Ensure `util` resolves to Node's built-in module and not to
255
- // Browserify's `node-util` polyfill (which lacks TextEncoder).
256
- // The polyfill may be hoisted into node_modules by optional
257
- // dependencies like `@cedarjs/storybook`.
258
- exclude: ["util"]
259
- }
260
- },
261
- resolve: {
262
- // See comment above in ssr.resolve for why we include defaultServerConditions.
263
- conditions: ["react-server", ...import_vite.defaultServerConditions]
264
- },
265
- plugins: [
266
- {
267
- name: "rsc-record-and-tranform-use-client-plugin",
268
- transform(code, id, _options) {
269
- globalThis.__cedarjs__client_references?.delete(id);
270
- if (!/^(["'])use client\1/.test(code)) {
271
- return void 0;
272
- }
273
- console.log(
274
- "rsc-record-and-transform-use-client-plugin: adding client reference",
275
- id
276
- );
277
- globalThis.__cedarjs__client_references?.add(id);
278
- const fns = code.matchAll(/export function (\w+)\(/g);
279
- const consts = code.matchAll(/export const (\w+) = \(/g);
280
- const names = [...fns, ...consts].map(([, name]) => name);
281
- const result = [
282
- `import { registerClientReference } from "react-server-dom-webpack/server.edge";`,
283
- "",
284
- ...names.map((name) => {
285
- return name === "default" ? `export default registerClientReference({}, "${id}", "${name}");` : `export const ${name} = registerClientReference({}, "${id}", "${name}");`;
286
- })
287
- ].join("\n");
288
- console.log("rsc-record-and-transform-use-client-plugin result");
289
- console.log(
290
- result.split("\n").map((line, i) => ` ${i + 1}: ${line}`).join("\n")
291
- );
292
- return { code: result, map: null };
293
- }
294
- },
295
- (0, import_vite_plugin_rsc_transform_server.rscTransformUseServerPlugin)("", {}),
296
- // The rscTransformUseClientPlugin maps paths like
297
- // /Users/tobbe/.../rw-app/node_modules/@tobbe.dev/rsc-test/dist/rsc-test.es.js
298
- // to
299
- // /Users/tobbe/.../rw-app/web/dist/ssr/assets/rsc0.js
300
- // That's why it needs the `clientEntryFiles` data
301
- // (It does other things as well, but that's why it needs clientEntryFiles)
302
- // rscTransformUseClientPlugin(clientEntryFiles),
303
- // rscTransformUseServerPlugin(outDir, serverEntryFiles),
304
- (0, import_vite_plugin_rsc_routes_imports.rscRoutesImports)(),
305
- {
306
- name: "rsc-hot-update",
307
- handleHotUpdate(ctx) {
308
- console.log("rsc-hot-update ctx.modules", ctx.modules);
309
- return [];
310
- }
311
- }
312
- ],
313
- build: {
314
- ssr: true
315
- },
316
- server: {
317
- // We never call `viteRscServer.listen()`, so we should run this in
318
- // middleware mode
319
- middlewareMode: true,
320
- // The hmr/fast-refresh websocket in this server collides with the one in
321
- // the other Vite server. So we can either disable it or run it on a
322
- // different port.
323
- // TODO (RSC): Figure out if we should disable or just pick a different
324
- // port
325
- ws: false
326
- // hmr: {
327
- // port: 24679,
328
- // },
329
- },
330
- appType: "custom",
331
- // Using a unique cache dir here to not clash with our other vite server
332
- cacheDir: "../node_modules/.vite-rsc"
333
- });
334
- globalThis.__cedarjs__vite_rsc_runtime = (0, import_vite.createServerModuleRunner)(
335
- viteRscServer.environments.ssr
336
- );
337
- const handleWithMiddleware = (route) => {
338
- return (0, import_server.createServerAdapter)(async (req) => {
339
- const middlewareRouter = await (0, import_register.createMiddlewareRouter)(viteSsrDevServer);
340
- const middleware = middlewareRouter.find(
341
- req.method,
342
- req.url
343
- )?.handler;
344
- if (!middleware) {
345
- return new Response("No middleware found", { status: 404 });
346
- }
347
- const [mwRes] = await (0, import_invokeMiddleware.invoke)(req, middleware, {
348
- route,
349
- viteSsrDevServer
350
- });
351
- return mwRes.toResponse();
352
- });
353
- };
354
- app.use(viteSsrDevServer.middlewares);
355
- if (rscEnabled) {
356
- (0, import_rscWebSocketServer.createWebSocketServer)();
357
- const { createRscRequestHandler } = await globalThis.__cedarjs__vite_rsc_runtime.import(
358
- new URL("./rsc/rscRequestHandler.js", import_meta.url).pathname
359
- );
360
- app.use(
361
- "/rw-rsc",
362
- await createRscRequestHandler({
363
- getMiddlewareRouter: async () => (0, import_register.createMiddlewareRouter)(viteSsrDevServer),
364
- viteSsrDevServer
365
- })
366
- );
367
- }
368
- const routes = (0, import_routes.getProjectRoutes)();
369
- const routeHandler = await (0, import_createReactStreamingHandler.createReactStreamingHandler)(
370
- {
371
- routes,
372
- clientEntryPath: rwPaths.web.entryClient,
373
- getStylesheetLinks: (route) => {
374
- return getCssLinks({
375
- rwPaths,
376
- route,
377
- viteSsrDevServer
378
- });
379
- },
380
- // Recreate middleware router on each request in dev
381
- getMiddlewareRouter: async () => (0, import_register.createMiddlewareRouter)(viteSsrDevServer)
382
- },
383
- viteSsrDevServer
384
- );
385
- app.get("*", (0, import_server.createServerAdapter)(routeHandler));
386
- app.post("*", handleWithMiddleware());
387
- const port = (0, import_project_config.getConfig)().web.port;
388
- console.log(`Started server on http://localhost:${port}`);
389
- return server.listen(port);
390
- }
391
- let devApp = createServer();
392
- process.stdin.on("data", async (data) => {
393
- const str = data.toString().trim().toLowerCase();
394
- if (str === "rs" || str === "restart") {
395
- console.log("Restarting dev web server.....");
396
- (await devApp).close(() => {
397
- devApp = createServer();
398
- });
399
- }
400
- });
401
- function getCssLinks({
402
- rwPaths,
403
- route,
404
- viteSsrDevServer
405
- }) {
406
- const appAndRouteModules = (0, import_collectCss.componentsModules)(
407
- [rwPaths.web.app, route?.filePath].filter(Boolean),
408
- viteSsrDevServer
409
- );
410
- const collectedCss = (0, import_collectCss.collectCssPaths)(appAndRouteModules);
411
- const cssLinks = Array.from(collectedCss);
412
- return cssLinks;
413
- }