@cedarjs/vite 4.1.1-next.14 → 4.1.1-next.55

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.
Files changed (52) hide show
  1. package/dist/apiDevMiddleware.d.ts +15 -0
  2. package/dist/apiDevMiddleware.d.ts.map +1 -0
  3. package/dist/{apiDevServer.js → apiDevMiddleware.js} +95 -107
  4. package/dist/build/build.d.ts +1 -1
  5. package/dist/build/build.d.ts.map +1 -1
  6. package/dist/build/build.js +2 -0
  7. package/dist/buildApp.d.ts +15 -0
  8. package/dist/buildApp.d.ts.map +1 -0
  9. package/dist/buildApp.js +150 -0
  10. package/dist/buildUDApiServer.d.ts +7 -5
  11. package/dist/buildUDApiServer.d.ts.map +1 -1
  12. package/dist/buildUDApiServer.js +8 -26
  13. package/dist/cedar-unified-dev.js +59 -5
  14. package/dist/cjs/{apiDevServer.js → apiDevMiddleware.js} +102 -110
  15. package/dist/cjs/build/build.js +3 -0
  16. package/dist/cjs/buildApp.js +181 -0
  17. package/dist/cjs/buildUDApiServer.js +8 -26
  18. package/dist/cjs/cedar-unified-dev.js +59 -5
  19. package/dist/cjs/index.js +3 -3
  20. package/dist/cjs/plugins/vite-plugin-cedar-cjs-compat.js +341 -0
  21. package/dist/cjs/plugins/vite-plugin-cedar-universal-deploy.js +114 -19
  22. package/dist/cjs/plugins/vite-plugin-cedar-wait-for-api-server.js +2 -1
  23. package/dist/cjs/ud-handlers/catch-all.js +65 -0
  24. package/dist/cjs/ud-handlers/function.js +47 -0
  25. package/dist/cjs/ud-handlers/graphql.js +59 -0
  26. package/dist/index.d.ts +1 -1
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +2 -2
  29. package/dist/plugins/vite-plugin-cedar-cjs-compat.d.ts +23 -0
  30. package/dist/plugins/vite-plugin-cedar-cjs-compat.d.ts.map +1 -0
  31. package/dist/plugins/vite-plugin-cedar-cjs-compat.js +307 -0
  32. package/dist/plugins/vite-plugin-cedar-universal-deploy.d.ts.map +1 -1
  33. package/dist/plugins/vite-plugin-cedar-universal-deploy.js +105 -20
  34. package/dist/plugins/vite-plugin-cedar-wait-for-api-server.d.ts.map +1 -1
  35. package/dist/plugins/vite-plugin-cedar-wait-for-api-server.js +2 -1
  36. package/dist/ud-handlers/catch-all.d.ts +15 -0
  37. package/dist/ud-handlers/catch-all.d.ts.map +1 -0
  38. package/dist/ud-handlers/catch-all.js +41 -0
  39. package/dist/ud-handlers/function.d.ts +5 -0
  40. package/dist/ud-handlers/function.d.ts.map +1 -0
  41. package/dist/ud-handlers/function.js +23 -0
  42. package/dist/ud-handlers/graphql.d.ts +7 -0
  43. package/dist/ud-handlers/graphql.d.ts.map +1 -0
  44. package/dist/ud-handlers/graphql.js +35 -0
  45. package/package.json +51 -22
  46. package/LICENSE +0 -21
  47. package/dist/apiDevServer.d.ts +0 -18
  48. package/dist/apiDevServer.d.ts.map +0 -1
  49. package/dist/cjs/plugins/vite-plugin-cedar-dev-dispatcher.js +0 -223
  50. package/dist/plugins/vite-plugin-cedar-dev-dispatcher.d.ts +0 -3
  51. package/dist/plugins/vite-plugin-cedar-dev-dispatcher.d.ts.map +0 -1
  52. package/dist/plugins/vite-plugin-cedar-dev-dispatcher.js +0 -189
@@ -1,9 +1,18 @@
1
1
  #!/usr/bin/env node
2
+ import { createServerAdapter } from "@whatwg-node/server";
2
3
  import { createServer } from "vite";
3
4
  import yargsParser from "yargs-parser";
4
5
  import { getPaths, getConfig } from "@cedarjs/project-config";
5
- import { startApiDevServer } from "./apiDevServer.js";
6
+ import { startApiDevMiddleware } from "./apiDevMiddleware.js";
7
+ function isViteInternalRequest(url) {
8
+ const pathname = url.split("?")[0];
9
+ return pathname.startsWith("/@") || pathname.startsWith("/__vite") || pathname.startsWith("/__hmr");
10
+ }
11
+ function isApiRequest(url, apiUrl, apiGqlUrl) {
12
+ return url === apiUrl || url.startsWith(apiUrl + "/") || url.startsWith(apiUrl + "?") || url === apiGqlUrl || url.startsWith(apiGqlUrl + "/") || url.startsWith(apiGqlUrl + "?");
13
+ }
6
14
  const startUnifiedDevServer = async () => {
15
+ process.env.__CEDAR_UNIFIED_DEV = "true";
7
16
  const rwPaths = getPaths();
8
17
  const cedarConfig = getConfig();
9
18
  const configFile = rwPaths.web.viteConfig;
@@ -14,7 +23,7 @@ const startUnifiedDevServer = async () => {
14
23
  force: forceOptimize,
15
24
  debug,
16
25
  port: portArg,
17
- apiPort: apiPortArg,
26
+ apiPort: _apiPortArg,
18
27
  _: _positional,
19
28
  ...serverArgs
20
29
  } = yargsParser(process.argv.slice(2), {
@@ -22,8 +31,8 @@ const startUnifiedDevServer = async () => {
22
31
  number: ["port", "apiPort"]
23
32
  });
24
33
  const webPort = portArg ?? cedarConfig.web.port ?? 8910;
25
- const apiPort = apiPortArg ?? cedarConfig.api.port ?? 8911;
26
- const { close: closeApi } = await startApiDevServer(apiPort);
34
+ const { close: closeApi, handler: apiHandler } = await startApiDevMiddleware();
35
+ const apiAdapter = createServerAdapter(apiHandler);
27
36
  const devServer = await createServer({
28
37
  configFile,
29
38
  // env file is handled by Cedar's plugins
@@ -36,7 +45,52 @@ const startUnifiedDevServer = async () => {
36
45
  port: webPort,
37
46
  ...serverArgs
38
47
  },
39
- logLevel: debug ? "info" : void 0
48
+ logLevel: debug ? "info" : void 0,
49
+ plugins: [
50
+ {
51
+ name: "cedar-api-middleware",
52
+ apply: "serve",
53
+ configureServer(server) {
54
+ const apiUrl = cedarConfig.web.apiUrl.replace(/\/$/, "");
55
+ const apiGqlUrl = cedarConfig.web.apiGraphQLUrl ?? apiUrl + "/graphql";
56
+ server.middlewares.use(
57
+ async (req, res, next) => {
58
+ const url = req.url ?? "/";
59
+ if (isViteInternalRequest(url)) {
60
+ return next();
61
+ }
62
+ if (!isApiRequest(url, apiUrl, apiGqlUrl)) {
63
+ return next();
64
+ }
65
+ try {
66
+ await apiAdapter(req, res);
67
+ } catch (err) {
68
+ console.error(
69
+ "[cedar-api-middleware] Error handling API request:",
70
+ err
71
+ );
72
+ if (!res.headersSent) {
73
+ res.writeHead(500, { "Content-Type": "application/json" });
74
+ }
75
+ res.end(
76
+ JSON.stringify(
77
+ {
78
+ errors: [
79
+ {
80
+ message: err instanceof Error ? err.message : "Internal Server Error"
81
+ }
82
+ ]
83
+ },
84
+ null,
85
+ 2
86
+ )
87
+ );
88
+ }
89
+ }
90
+ );
91
+ }
92
+ }
93
+ ]
40
94
  });
41
95
  await devServer.listen();
42
96
  process.stdin.on("data", async (data) => {
@@ -26,20 +26,21 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
26
26
  mod
27
27
  ));
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var apiDevServer_exports = {};
30
- __export(apiDevServer_exports, {
31
- startApiDevServer: () => startApiDevServer
29
+ var apiDevMiddleware_exports = {};
30
+ __export(apiDevMiddleware_exports, {
31
+ createApiFetchHandler: () => createApiFetchHandler,
32
+ createApiViteServer: () => createApiViteServer,
33
+ loadApiFunctions: () => loadApiFunctions,
34
+ setupHmrHandlers: () => setupHmrHandlers,
35
+ startApiDevMiddleware: () => startApiDevMiddleware
32
36
  });
33
- module.exports = __toCommonJS(apiDevServer_exports);
37
+ module.exports = __toCommonJS(apiDevMiddleware_exports);
34
38
  var import_promises = require("node:fs/promises");
35
39
  var import_node_path = __toESM(require("node:path"), 1);
36
40
  var import_node_url = require("node:url");
37
- var import_url_data = __toESM(require("@fastify/url-data"), 1);
38
41
  var import_ansis = __toESM(require("ansis"), 1);
39
- var import_fastify = __toESM(require("fastify"), 1);
40
- var import_fastify_raw_body = __toESM(require("fastify-raw-body"), 1);
41
42
  var import_vite = require("vite");
42
- var import_requestHandlers = require("@cedarjs/api-server/requestHandlers");
43
+ var import_runtime = require("@cedarjs/api/runtime");
43
44
  var import_babel_config = require("@cedarjs/babel-config");
44
45
  var import_store = require("@cedarjs/context/dist/store");
45
46
  var import_graphql_server = require("@cedarjs/graphql-server");
@@ -86,13 +87,6 @@ async function internalLoadApiFunctions(viteServer) {
86
87
  } catch {
87
88
  srcFunctions = [];
88
89
  }
89
- const graphqlFunctionIndex = srcFunctions.findIndex(
90
- (f) => import_node_path.default.basename(f).startsWith("graphql.")
91
- );
92
- if (graphqlFunctionIndex > 0) {
93
- const [graphqlFn] = srcFunctions.splice(graphqlFunctionIndex, 1);
94
- srcFunctions.unshift(graphqlFn);
95
- }
96
90
  console.log(import_ansis.default.dim.italic("Importing Server Functions... "));
97
91
  const tsImport = Date.now();
98
92
  let extractedGraphqlOptions = null;
@@ -101,24 +95,33 @@ async function internalLoadApiFunctions(viteServer) {
101
95
  const routeName = import_node_path.default.basename(fnPath).replace(/\.(ts|tsx|js|jsx)$/, "");
102
96
  try {
103
97
  const mod = await viteServer.ssrLoadModule((0, import_node_url.pathToFileURL)(fnPath).href);
104
- const handler = (() => {
98
+ const cedarHandler = (() => {
99
+ if ("handleRequest" in mod) {
100
+ return mod.handleRequest;
101
+ }
102
+ if ("default" in mod && mod.default && "handleRequest" in mod.default) {
103
+ return mod.default.handleRequest;
104
+ }
105
+ let legacyHandler;
105
106
  if ("handler" in mod) {
106
- return mod.handler;
107
+ legacyHandler = mod.handler;
108
+ } else if ("default" in mod && mod.default && "handler" in mod.default) {
109
+ legacyHandler = mod.default.handler;
107
110
  }
108
- if ("default" in mod && mod.default && "handler" in mod.default) {
109
- return mod.default.handler;
111
+ if (legacyHandler) {
112
+ return (0, import_runtime.wrapLegacyHandler)(legacyHandler);
110
113
  }
111
114
  return void 0;
112
115
  })();
113
- if (handler) {
114
- LAMBDA_FUNCTIONS[routeName] = handler;
116
+ if (cedarHandler) {
117
+ LAMBDA_FUNCTIONS[routeName] = cedarHandler;
115
118
  console.log(
116
119
  import_ansis.default.magenta("/" + routeName),
117
120
  import_ansis.default.dim.italic(Date.now() - ts + " ms")
118
121
  );
119
122
  } else {
120
123
  console.warn(
121
- `[apiDevServer] No handler export found in function: ${fnPath}`
124
+ `[apiDevMiddleware] No handler or handleRequest export found in function: ${fnPath}`
122
125
  );
123
126
  }
124
127
  if (routeName === "graphql" && "__rw_graphqlOptions" in mod) {
@@ -127,7 +130,7 @@ async function internalLoadApiFunctions(viteServer) {
127
130
  } catch (err) {
128
131
  viteServer.ssrFixStacktrace(err);
129
132
  console.error(
130
- `[apiDevServer] Failed to load function "${routeName}" from ${fnPath}:`,
133
+ `[apiDevMiddleware] Failed to load function "${routeName}" from ${fnPath}:`,
131
134
  err
132
135
  );
133
136
  }
@@ -136,56 +139,29 @@ async function internalLoadApiFunctions(viteServer) {
136
139
  if (extractedGraphqlOptions) {
137
140
  const { yoga } = await (0, import_graphql_server.createGraphQLYoga)(extractedGraphqlOptions);
138
141
  graphqlYoga = yoga;
142
+ } else {
143
+ graphqlYoga = null;
139
144
  }
140
145
  console.log(
141
146
  import_ansis.default.dim.italic("...Done importing in " + (Date.now() - tsImport) + " ms")
142
147
  );
143
148
  }
144
- function createFetchRequestFromFastify(req) {
145
- const requestBody = req.method === "GET" || req.method === "HEAD" ? void 0 : typeof req.body === "string" ? req.body : req.body ? JSON.stringify(req.body) : void 0;
146
- const href = `${req.protocol}://${req.host}${req.raw.url ?? "/"}`;
147
- return new Request(href, {
148
- method: req.method,
149
- headers: req.headers,
150
- body: requestBody
151
- });
152
- }
153
- async function startApiDevServer(port) {
149
+ async function createApiViteServer() {
154
150
  const cedarPaths = (0, import_project_config.getPaths)();
155
151
  const cedarConfig = (0, import_project_config.getConfig)();
156
- const apiPort = port || cedarConfig.api.port || 8911;
157
- const apiHost = cedarConfig.api.host || "::";
158
152
  const isEsm = (0, import_project_config.projectSideIsEsm)("api");
159
153
  const normalizedBase = (0, import_vite.normalizePath)(cedarPaths.base);
160
- const normalizedApiSrc = (0, import_vite.normalizePath)(cedarPaths.api.src);
161
- const normalizedApiBase = (0, import_vite.normalizePath)(cedarPaths.api.base);
162
- const viteServer = await createViteDevServer(
163
- cedarPaths,
164
- cedarConfig,
165
- isEsm,
166
- normalizedBase
167
- );
168
- console.log(import_ansis.default.dim.italic("Starting API dev server..."));
169
- await loadApiFunctions(viteServer);
170
- setupHmrHandlers(viteServer, normalizedApiSrc, normalizedApiBase);
171
- const app = await createFastifyApp(apiPort, apiHost);
172
- const close = async () => {
173
- await app.close();
174
- await viteServer.close();
175
- };
176
- return { viteServer, close };
177
- }
178
- async function createViteDevServer(cedarPaths, cedarConfig, projectIsEsm, normalizedBase) {
179
154
  const babelPlugins = (0, import_babel_config.getApiSideBabelPlugins)({
180
155
  openTelemetry: (cedarConfig.experimental?.opentelemetry?.enabled ?? false) && (cedarConfig.experimental?.opentelemetry?.wrapApi ?? false),
181
- projectIsEsm
156
+ projectIsEsm: isEsm
182
157
  });
183
158
  const workspacePkgSourceMap = Object.fromEntries(
184
159
  Object.entries((0, import_workspacePackageAliases.getWorkspacePackageAliases)(cedarPaths, cedarConfig)).map(
185
160
  ([name, sourceFile]) => [name, (0, import_vite.normalizePath)(sourceFile)]
186
161
  )
187
162
  );
188
- const viteServer = await (0, import_vite.createServer)({
163
+ const { createServer: createViteServer } = await import("vite");
164
+ return createViteServer({
189
165
  configFile: false,
190
166
  root: cedarPaths.api.base,
191
167
  appType: "custom",
@@ -195,10 +171,6 @@ async function createViteDevServer(cedarPaths, cedarConfig, projectIsEsm, normal
195
171
  middlewareMode: true
196
172
  },
197
173
  resolve: {
198
- // Map workspace package names directly to their TypeScript source entry
199
- // files. This is processed by Vite's built-in alias plugin (enforce:
200
- // 'pre') which runs before vite:resolve and correctly intercepts imports
201
- // in the SSR module runner context.
202
174
  alias: workspacePkgSourceMap
203
175
  },
204
176
  plugins: [
@@ -233,7 +205,6 @@ async function createViteDevServer(cedarPaths, cedarConfig, projectIsEsm, normal
233
205
  }
234
206
  ]
235
207
  });
236
- return viteServer;
237
208
  }
238
209
  function invalidateApiModules(viteServer, normalizedApiSrc) {
239
210
  const invalidated = /* @__PURE__ */ new Set();
@@ -253,7 +224,10 @@ function invalidateApiModules(viteServer, normalizedApiSrc) {
253
224
  }
254
225
  }
255
226
  }
256
- function setupHmrHandlers(viteServer, normalizedApiSrc, normalizedApiBase) {
227
+ function setupHmrHandlers(viteServer) {
228
+ const cedarPaths = (0, import_project_config.getPaths)();
229
+ const normalizedApiSrc = (0, import_vite.normalizePath)(cedarPaths.api.src);
230
+ const normalizedApiBase = (0, import_vite.normalizePath)(cedarPaths.api.base);
257
231
  viteServer.watcher.on("change", async (filePath) => {
258
232
  const normalizedFilePath = (0, import_vite.normalizePath)(filePath);
259
233
  if (!normalizedFilePath.startsWith(normalizedApiSrc)) {
@@ -306,61 +280,79 @@ function setupHmrHandlers(viteServer, normalizedApiSrc, normalizedApiBase) {
306
280
  await loadApiFunctions(viteServer);
307
281
  });
308
282
  }
309
- async function createFastifyApp(apiPort, apiHost) {
310
- const logLevel = process.env.NODE_ENV === "development" ? "debug" : "info";
311
- const app = (0, import_fastify.default)({ logger: { level: logLevel } });
312
- await app.register(import_fastify_raw_body.default);
313
- app.register(import_url_data.default);
314
- app.addContentTypeParser(
315
- ["application/x-www-form-urlencoded", "multipart/form-data"],
316
- { parseAs: "string" },
317
- app.defaultTextParser
318
- );
319
- const lambdaRequestHandler = async (req, reply) => {
320
- const { routeName } = req.params;
283
+ function createApiFetchHandler() {
284
+ const cedarConfig = (0, import_project_config.getConfig)();
285
+ const apiUrlPrefix = cedarConfig.web.apiUrl.replace(/\/$/, "");
286
+ return async (request) => {
287
+ const url = new URL(request.url);
288
+ let pathname = url.pathname;
289
+ if (pathname.startsWith(apiUrlPrefix + "/")) {
290
+ pathname = pathname.slice(apiUrlPrefix.length);
291
+ } else if (pathname === apiUrlPrefix) {
292
+ pathname = "/";
293
+ }
294
+ if (pathname === "/graphql" || pathname.startsWith("/graphql/")) {
295
+ if (!graphqlYoga) {
296
+ return new Response(
297
+ JSON.stringify({ error: "GraphQL Yoga instance not initialized" }),
298
+ { status: 503, headers: { "Content-Type": "application/json" } }
299
+ );
300
+ }
301
+ const yoga = graphqlYoga;
302
+ return (0, import_store.getAsyncStoreInstance)().run(/* @__PURE__ */ new Map(), async () => {
303
+ return yoga.handle(request, { request });
304
+ });
305
+ }
306
+ const match = pathname.match(/^\/([^/]+)(?:\/.*)?$/);
307
+ if (!match) {
308
+ return new Response("Not Found", { status: 404 });
309
+ }
310
+ const routeName = match[1];
321
311
  const handler = LAMBDA_FUNCTIONS[routeName];
322
312
  if (!handler) {
323
- const errorMessage = `Function "${routeName}" was not found.`;
324
- req.log.error(errorMessage);
325
- reply.status(404);
326
- reply.send({
327
- error: errorMessage,
328
- availableFunctions: Object.keys(LAMBDA_FUNCTIONS)
313
+ return new Response(
314
+ JSON.stringify({
315
+ error: `Function "${routeName}" was not found.`,
316
+ availableFunctions: Object.keys(LAMBDA_FUNCTIONS)
317
+ }),
318
+ { status: 404, headers: { "Content-Type": "application/json" } }
319
+ );
320
+ }
321
+ try {
322
+ const ctx = await (0, import_runtime.buildCedarContext)(request, {
323
+ params: { routeName }
329
324
  });
330
- return;
325
+ return await handler(request, ctx);
326
+ } catch (err) {
327
+ console.error(
328
+ `[apiDevMiddleware] Error handling function "${routeName}":`,
329
+ err
330
+ );
331
+ return new Response(
332
+ JSON.stringify({
333
+ error: err instanceof Error ? err.message : "Internal Server Error"
334
+ }),
335
+ { status: 500, headers: { "Content-Type": "application/json" } }
336
+ );
331
337
  }
332
- return (0, import_requestHandlers.requestHandler)(req, reply, handler);
333
338
  };
334
- const graphqlHandler = async (req, reply) => {
335
- if (!graphqlYoga) {
336
- return reply.status(503).send({ error: "GraphQL Yoga instance not initialized" });
337
- }
338
- const request = createFetchRequestFromFastify(req);
339
- const yoga = graphqlYoga;
340
- const response = await (0, import_store.getAsyncStoreInstance)().run(/* @__PURE__ */ new Map(), async () => {
341
- return yoga.handle(request, { req, reply });
342
- });
343
- return response;
339
+ }
340
+ async function startApiDevMiddleware() {
341
+ const viteServer = await createApiViteServer();
342
+ console.log(import_ansis.default.dim.italic("Starting API dev server..."));
343
+ await loadApiFunctions(viteServer);
344
+ setupHmrHandlers(viteServer);
345
+ const close = async () => {
346
+ await viteServer.close();
344
347
  };
345
- app.all("/graphql", graphqlHandler);
346
- app.all("/graphql/*", graphqlHandler);
347
- app.all("/:routeName", lambdaRequestHandler);
348
- app.all("/:routeName/*", lambdaRequestHandler);
349
- app.addHook("onListen", (done) => {
350
- const addr = app.server.address();
351
- const listenPort = addr && typeof addr === "object" ? addr.port : apiPort;
352
- console.log(
353
- `API dev server listening at ${import_ansis.default.magenta(`http://localhost:${listenPort}/`)}`
354
- );
355
- console.log(
356
- `GraphQL endpoint at ${import_ansis.default.magenta(`http://localhost:${listenPort}/graphql`)}`
357
- );
358
- done();
359
- });
360
- await app.listen({ port: apiPort, host: apiHost });
361
- return app;
348
+ const handler = createApiFetchHandler();
349
+ return { viteServer, close, handler };
362
350
  }
363
351
  // Annotate the CommonJS export names for ESM import in node:
364
352
  0 && (module.exports = {
365
- startApiDevServer
353
+ createApiFetchHandler,
354
+ createApiViteServer,
355
+ loadApiFunctions,
356
+ setupHmrHandlers,
357
+ startApiDevMiddleware
366
358
  });
@@ -28,10 +28,12 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
  var build_exports = {};
30
30
  __export(build_exports, {
31
+ buildCedarApp: () => import_buildApp.buildCedarApp,
31
32
  buildWeb: () => buildWeb
32
33
  });
33
34
  module.exports = __toCommonJS(build_exports);
34
35
  var import_project_config = require("@cedarjs/project-config");
36
+ var import_buildApp = require("../buildApp.js");
35
37
  const buildWeb = async ({ verbose }) => {
36
38
  const { build } = await import("vite");
37
39
  const viteConfig = (0, import_project_config.getPaths)().web.viteConfig;
@@ -51,5 +53,6 @@ const buildWeb = async ({ verbose }) => {
51
53
  };
52
54
  // Annotate the CommonJS export names for ESM import in node:
53
55
  0 && (module.exports = {
56
+ buildCedarApp,
54
57
  buildWeb
55
58
  });
@@ -0,0 +1,181 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var buildApp_exports = {};
30
+ __export(buildApp_exports, {
31
+ buildCedarApp: () => buildCedarApp
32
+ });
33
+ module.exports = __toCommonJS(buildApp_exports);
34
+ var import_node_fs = __toESM(require("node:fs"), 1);
35
+ var import_node_path = __toESM(require("node:path"), 1);
36
+ var import_vite = require("vite");
37
+ var import_babel_config = require("@cedarjs/babel-config");
38
+ var import_files = require("@cedarjs/internal/dist/files.js");
39
+ var import_project_config = require("@cedarjs/project-config");
40
+ var import_workspacePackageAliases = require("./lib/workspacePackageAliases.js");
41
+ function resolveWithExtensions(id) {
42
+ if (import_node_fs.default.existsSync(id)) {
43
+ return id;
44
+ }
45
+ for (const ext of [".js", ".ts", ".jsx", ".tsx", ".mjs", ".mts"]) {
46
+ const withExt = id + ext;
47
+ if (import_node_fs.default.existsSync(withExt)) {
48
+ return withExt;
49
+ }
50
+ }
51
+ return id;
52
+ }
53
+ async function buildCedarApp({
54
+ verbose = false,
55
+ workspace = ["api", "web"]
56
+ } = {}) {
57
+ const cedarPaths = (0, import_project_config.getPaths)();
58
+ const cedarConfig = (0, import_project_config.getConfig)();
59
+ const environments = {};
60
+ if (workspace.includes("web")) {
61
+ environments.client = {
62
+ build: {
63
+ outDir: cedarPaths.web.dist
64
+ }
65
+ };
66
+ }
67
+ if (workspace.includes("api")) {
68
+ const isEsm = (0, import_project_config.projectSideIsEsm)("api");
69
+ const format = isEsm ? "es" : "cjs";
70
+ const apiFiles = (0, import_files.findApiFiles)();
71
+ const input = {};
72
+ for (const f of apiFiles) {
73
+ const key = import_node_path.default.relative(cedarPaths.api.src, f).replace(/\.(ts|tsx|mts|js|jsx|mjs)$/, "");
74
+ input[key] = f;
75
+ }
76
+ environments.api = {
77
+ build: {
78
+ ssr: true,
79
+ sourcemap: true,
80
+ outDir: cedarPaths.api.dist,
81
+ emptyOutDir: true,
82
+ rollupOptions: {
83
+ input,
84
+ output: {
85
+ format,
86
+ preserveModules: true,
87
+ preserveModulesRoot: cedarPaths.api.src,
88
+ entryFileNames: "[name].js"
89
+ },
90
+ external: (id) => {
91
+ if (id.startsWith("node:")) {
92
+ return true;
93
+ }
94
+ if (!id.startsWith(".") && !import_node_path.default.isAbsolute(id)) {
95
+ return true;
96
+ }
97
+ return false;
98
+ }
99
+ }
100
+ }
101
+ };
102
+ }
103
+ const babelPlugins = workspace.includes("api") ? (0, import_babel_config.getApiSideBabelPlugins)({
104
+ openTelemetry: (cedarConfig.experimental?.opentelemetry?.enabled ?? false) && (cedarConfig.experimental?.opentelemetry?.wrapApi ?? false),
105
+ projectIsEsm: (0, import_project_config.projectSideIsEsm)("api")
106
+ }) : null;
107
+ const workspacePkgSourceMap = workspace.includes("api") ? Object.fromEntries(
108
+ Object.entries((0, import_workspacePackageAliases.getWorkspacePackageAliases)(cedarPaths, cedarConfig)).map(
109
+ ([name, sourceFile]) => [name, (0, import_vite.normalizePath)(sourceFile)]
110
+ )
111
+ ) : {};
112
+ const plugins = [
113
+ {
114
+ name: "cedar-build-app-cleanup",
115
+ configResolved(config) {
116
+ if (!workspace.includes("web") && config.environments.client) {
117
+ delete config.environments.client;
118
+ }
119
+ if (!environments.ssr && config.environments.ssr) {
120
+ delete config.environments.ssr;
121
+ }
122
+ }
123
+ }
124
+ ];
125
+ if (workspace.includes("api")) {
126
+ plugins.push({
127
+ name: "cedar-api-src-redirect",
128
+ enforce: "pre",
129
+ resolveId(id, importer) {
130
+ if (!importer?.startsWith(cedarPaths.api.src)) {
131
+ return null;
132
+ }
133
+ if (id.startsWith("src/")) {
134
+ return resolveWithExtensions(
135
+ import_node_path.default.join(cedarPaths.api.src, id.slice(4))
136
+ );
137
+ }
138
+ return null;
139
+ }
140
+ });
141
+ if (babelPlugins) {
142
+ plugins.push({
143
+ name: "cedar-vite-api-babel-transform",
144
+ async transform(_code, id) {
145
+ if (!/\.(js|ts|tsx|jsx)$/.test(id)) {
146
+ return null;
147
+ }
148
+ if (id.includes("node_modules")) {
149
+ return null;
150
+ }
151
+ if (!(0, import_vite.normalizePath)(id).startsWith((0, import_vite.normalizePath)(cedarPaths.api.base))) {
152
+ return null;
153
+ }
154
+ const transformedCode = await (0, import_babel_config.transformWithBabel)(id, babelPlugins);
155
+ if (transformedCode?.code) {
156
+ return {
157
+ code: transformedCode.code,
158
+ map: transformedCode.map ?? null
159
+ };
160
+ }
161
+ return null;
162
+ }
163
+ });
164
+ }
165
+ }
166
+ const builder = await (0, import_vite.createBuilder)({
167
+ configFile: cedarPaths.web.viteConfig,
168
+ envFile: false,
169
+ logLevel: verbose ? "info" : "warn",
170
+ environments,
171
+ resolve: {
172
+ alias: workspacePkgSourceMap
173
+ },
174
+ plugins
175
+ });
176
+ return builder.buildApp();
177
+ }
178
+ // Annotate the CommonJS export names for ESM import in node:
179
+ 0 && (module.exports = {
180
+ buildCedarApp
181
+ });
@@ -39,23 +39,19 @@ const buildUDApiServer = async ({
39
39
  } = {}) => {
40
40
  const { build } = await import("vite");
41
41
  const { cedarUniversalDeployPlugin } = await import("./plugins/vite-plugin-cedar-universal-deploy.js");
42
- const { node } = await import("@universal-deploy/node/vite");
42
+ const { default: universalDeploy } = await import("@universal-deploy/vite");
43
43
  const rwPaths = (0, import_project_config.getPaths)();
44
44
  const outDir = import_node_path.default.join(rwPaths.api.dist, "ud");
45
45
  await build({
46
- // No configFile — we configure everything inline so this build is
47
- // self-contained and does not require a vite.config.ts in api/.
48
- configFile: false,
49
- envFile: false,
50
46
  logLevel: verbose ? "info" : "warn",
51
47
  plugins: [
52
- // Registers virtual:cedar-api with @universal-deploy/store and resolves
53
- // virtual:ud:catch-all → virtual:cedar-api → Cedar's aggregate fetchable.
48
+ // Registers per-route API entries with @universal-deploy/store.
54
49
  cedarUniversalDeployPlugin({ apiRootPath }),
55
- // Emits a self-contained Node server entry (api/dist/ud/index.js) that
56
- // imports virtual:ud:catch-all and starts an srvx HTTP server.
57
- // This is a Vite server-build concern, not Cedar HTML SSR.
58
- ...node()
50
+ // Includes catchAll(), devServer(), and auto-detection of
51
+ // deployment targets. Enables @universal-deploy/node by default
52
+ // when no other target (Netlify, Vercel, Cloudflare) is detected
53
+ // in the user's Vite config.
54
+ universalDeploy()
59
55
  ],
60
56
  // The ssr environment is the Vite mechanism for server-side builds.
61
57
  // Reminder: "ssr" here means "server-side module execution", NOT
@@ -63,21 +59,7 @@ const buildUDApiServer = async ({
63
59
  environments: {
64
60
  ssr: {
65
61
  build: {
66
- outDir,
67
- // Ensure @universal-deploy/node is bundled into the output so the
68
- // emitted entry is self-contained.
69
- rollupOptions: {
70
- output: {
71
- // Produce a single-file entry where possible; srvx chunks are
72
- // split by the node() plugin automatically.
73
- entryFileNames: "[name].js"
74
- }
75
- }
76
- },
77
- resolve: {
78
- // Do not externalise @universal-deploy/node — the node() plugin
79
- // requires it to be bundled into the server entry.
80
- noExternal: ["@universal-deploy/node"]
62
+ outDir
81
63
  }
82
64
  }
83
65
  },