vite-react-ssg 0.6.0 → 0.6.2

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/dist/node.cjs CHANGED
@@ -12,16 +12,11 @@ const React = require('react');
12
12
  const reactHelmetAsync = require('react-helmet-async');
13
13
  const node_stream = require('node:stream');
14
14
  const server = require('react-dom/server');
15
- const https = require('node:https');
16
- const express = require('express');
17
- const devcert = require('@childrentime/devcert');
18
15
 
19
16
  function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
20
17
 
21
18
  const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
22
19
  const React__default = /*#__PURE__*/_interopDefaultCompat(React);
23
- const https__default = /*#__PURE__*/_interopDefaultCompat(https);
24
- const express__default = /*#__PURE__*/_interopDefaultCompat(express);
25
20
 
26
21
  function getDefaultExportFromCjs (x) {
27
22
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
@@ -866,13 +861,21 @@ async function routesToPaths(routes) {
866
861
  if (!routes || routes.length === 0)
867
862
  return { paths: ["/"], pathToEntry };
868
863
  const paths = /* @__PURE__ */ new Set();
869
- const lazyPaths = /* @__PURE__ */ new Set();
870
864
  const getPaths = async (routes2, prefix = "") => {
871
865
  prefix = prefix.replace(/\/$/g, "");
872
- for (const route of routes2) {
866
+ for (let route of routes2) {
867
+ if (route.lazy) {
868
+ const lazyData = await route.lazy();
869
+ if (lazyData) {
870
+ route = {
871
+ ...route,
872
+ ...lazyData
873
+ };
874
+ }
875
+ }
873
876
  let path = route.path;
874
877
  path = handlePath(path, prefix, route.entry);
875
- if (route.getStaticPaths && path?.includes(":")) {
878
+ if (route.getStaticPaths && isDynamicSegmentsRoute(path)) {
876
879
  const staticPaths = await route.getStaticPaths();
877
880
  for (let staticPath of staticPaths) {
878
881
  staticPath = handlePath(staticPath, prefix, route.entry);
@@ -880,8 +883,6 @@ async function routesToPaths(routes) {
880
883
  await getPaths(route.children, staticPath);
881
884
  }
882
885
  }
883
- if (route.lazy)
884
- lazyPaths.add(route.index ? prefix : path ?? "");
885
886
  if (route.index)
886
887
  addEntry(prefix, route.entry);
887
888
  if (Array.isArray(route.children))
@@ -889,7 +890,7 @@ async function routesToPaths(routes) {
889
890
  }
890
891
  };
891
892
  await getPaths(routes);
892
- return { paths: Array.from(paths), pathToEntry, lazyPaths: Array.from(lazyPaths) };
893
+ return { paths: Array.from(paths), pathToEntry };
893
894
  function handlePath(path, prefix, entry) {
894
895
  if (path != null) {
895
896
  path = prefix && !path.startsWith("/") ? `${prefix}${path ? `/${path}` : ""}` : path;
@@ -903,31 +904,6 @@ async function routesToPaths(routes) {
903
904
  return path;
904
905
  }
905
906
  }
906
- function createFetchRequest(req) {
907
- const origin = `${req.protocol}://${req.get("host")}`;
908
- const url = new URL(req.originalUrl || req.url, origin);
909
- const controller = new AbortController();
910
- req.on("close", () => controller.abort());
911
- const headers = new Headers();
912
- for (const [key, values] of Object.entries(req.headers)) {
913
- if (values) {
914
- if (Array.isArray(values)) {
915
- for (const value of values)
916
- headers.append(key, value);
917
- } else {
918
- headers.set(key, values);
919
- }
920
- }
921
- }
922
- const init = {
923
- method: req.method,
924
- headers,
925
- signal: controller.signal
926
- };
927
- if (req.method !== "GET" && req.method !== "HEAD")
928
- init.body = req.body;
929
- return new Request(url.href, init);
930
- }
931
907
  async function resolveAlias(config, entry) {
932
908
  const resolver = config.createResolver();
933
909
  const result = await resolver(entry, config.root);
@@ -960,9 +936,11 @@ function withTrailingSlash(path) {
960
936
  return `${path}/`;
961
937
  return path;
962
938
  }
963
- const postfixRE = /[?#].*$/s;
964
- function cleanUrl(url) {
965
- return url.replace(postfixRE, "");
939
+ const dynamicRE = /[:*?]/;
940
+ function isDynamicSegmentsRoute(route) {
941
+ if (!route)
942
+ return false;
943
+ return dynamicRE.test(route);
966
944
  }
967
945
 
968
946
  async function getCritters(outDir, options = {}) {
@@ -1057,17 +1035,6 @@ async function render(routesOrApp, request, styleCollector, basename) {
1057
1035
  const { htmlAttributes, bodyAttributes, metaAttributes, styleTag } = extractHelmet(helmetContext, styleCollector);
1058
1036
  return { appHTML, htmlAttributes, bodyAttributes, metaAttributes, styleTag, routerContext: context };
1059
1037
  }
1060
- async function preLoad(routes, paths) {
1061
- if (!paths || paths.length === 0)
1062
- return routes;
1063
- const { createStaticHandler } = await import('react-router-dom/server.js');
1064
- const { dataRoutes, query } = createStaticHandler(routes);
1065
- await Promise.all(paths.map(async (path) => {
1066
- const request = createRequest(path);
1067
- return query(request);
1068
- }));
1069
- return dataRoutes;
1070
- }
1071
1038
  function extractHelmet(context, styleCollector) {
1072
1039
  const { helmet } = context;
1073
1040
  const htmlAttributes = helmet.htmlAttributes.toString();
@@ -1083,56 +1050,6 @@ function extractHelmet(context, styleCollector) {
1083
1050
  return { htmlAttributes, bodyAttributes, metaAttributes, styleTag };
1084
1051
  }
1085
1052
 
1086
- function renderPreloadLinks(document, modules, ssrManifest) {
1087
- const seen = /* @__PURE__ */ new Set();
1088
- const preloadLinks = [];
1089
- Array.from(modules).forEach((id) => {
1090
- const files = ssrManifest[id] || [];
1091
- files.forEach((file) => {
1092
- if (!preloadLinks.includes(file))
1093
- preloadLinks.push(file);
1094
- });
1095
- });
1096
- if (preloadLinks) {
1097
- preloadLinks.forEach((file) => {
1098
- if (!seen.has(file)) {
1099
- seen.add(file);
1100
- renderPreloadLink(document, file);
1101
- }
1102
- });
1103
- }
1104
- }
1105
- function renderPreloadLink(document, file) {
1106
- if (file.endsWith(".js")) {
1107
- appendLink(document, {
1108
- rel: "modulepreload",
1109
- crossOrigin: "",
1110
- href: file
1111
- });
1112
- } else if (file.endsWith(".css")) {
1113
- appendLink(document, {
1114
- rel: "stylesheet",
1115
- href: file
1116
- });
1117
- }
1118
- }
1119
- function createLink$1(document) {
1120
- return document.createElement("link");
1121
- }
1122
- function setAttrs(el, attrs) {
1123
- const keys = Object.keys(attrs);
1124
- for (const key of keys)
1125
- el.setAttribute(key, attrs[key]);
1126
- }
1127
- function appendLink(document, attrs) {
1128
- const exits = document.head.querySelector(`link[href='${attrs.file}']`);
1129
- if (exits)
1130
- return;
1131
- const link = createLink$1(document);
1132
- setAttrs(link, attrs);
1133
- document.head.appendChild(link);
1134
- }
1135
-
1136
1053
  async function renderHTML({
1137
1054
  rootContainerId,
1138
1055
  indexHTML,
@@ -1186,10 +1103,61 @@ async function detectEntry(root) {
1186
1103
  }) || [];
1187
1104
  return entry || "src/main.ts";
1188
1105
  }
1189
- function createLink(href) {
1106
+ function createLink$1(href) {
1190
1107
  return `<link rel="stylesheet" href="${href}">`;
1191
1108
  }
1192
1109
 
1110
+ function renderPreloadLinks(document, modules, ssrManifest) {
1111
+ const seen = /* @__PURE__ */ new Set();
1112
+ const preloadLinks = [];
1113
+ Array.from(modules).forEach((id) => {
1114
+ const files = ssrManifest[id] || [];
1115
+ files.forEach((file) => {
1116
+ if (!preloadLinks.includes(file))
1117
+ preloadLinks.push(file);
1118
+ });
1119
+ });
1120
+ if (preloadLinks) {
1121
+ preloadLinks.forEach((file) => {
1122
+ if (!seen.has(file)) {
1123
+ seen.add(file);
1124
+ renderPreloadLink(document, file);
1125
+ }
1126
+ });
1127
+ }
1128
+ }
1129
+ function renderPreloadLink(document, file) {
1130
+ if (file.endsWith(".js")) {
1131
+ appendLink(document, {
1132
+ rel: "modulepreload",
1133
+ crossOrigin: "",
1134
+ href: file
1135
+ });
1136
+ } else if (file.endsWith(".css")) {
1137
+ appendLink(document, {
1138
+ rel: "stylesheet",
1139
+ href: file,
1140
+ crossOrigin: ""
1141
+ });
1142
+ }
1143
+ }
1144
+ function createLink(document) {
1145
+ return document.createElement("link");
1146
+ }
1147
+ function setAttrs(el, attrs) {
1148
+ const keys = Object.keys(attrs);
1149
+ for (const key of keys)
1150
+ el.setAttribute(key, attrs[key]);
1151
+ }
1152
+ function appendLink(document, attrs) {
1153
+ const exits = document.head.querySelector(`link[href='${attrs.file}']`);
1154
+ if (exits)
1155
+ return;
1156
+ const link = createLink(document);
1157
+ setAttrs(link, attrs);
1158
+ document.head.appendChild(link);
1159
+ }
1160
+
1193
1161
  function DefaultIncludedRoutes(paths, _routes) {
1194
1162
  return paths.filter((i) => !i.includes(":") && !i.includes("*"));
1195
1163
  }
@@ -1271,9 +1239,7 @@ async function build(ssgOptions = {}, viteConfig = {}) {
1271
1239
  const { createRoot, includedRoutes: serverEntryIncludedRoutes } = format === "esm" ? await import(serverEntry) : _require(serverEntry);
1272
1240
  const includedRoutes = serverEntryIncludedRoutes || configIncludedRoutes;
1273
1241
  const { routes } = await createRoot(false);
1274
- const { lazyPaths } = await routesToPaths(routes);
1275
- const dataRoutes = await preLoad([...routes || []], lazyPaths);
1276
- const { paths, pathToEntry } = await routesToPaths(dataRoutes);
1242
+ const { paths, pathToEntry } = await routesToPaths(routes);
1277
1243
  let routesPaths = includeAllRoutes ? paths : await includedRoutes(paths, routes || []);
1278
1244
  routesPaths = DefaultIncludedRoutes(routesPaths);
1279
1245
  routesPaths = Array.from(new Set(routesPaths));
@@ -1313,8 +1279,10 @@ async function build(ssgOptions = {}, viteConfig = {}) {
1313
1279
  renderPreloadLinks(jsdom.window.document, modules, ssrManifest);
1314
1280
  const html = jsdom.serialize();
1315
1281
  let transformed = await onPageRendered?.(path, html, appCtx) || html;
1316
- if (critters)
1282
+ if (critters) {
1317
1283
  transformed = await crittersQueue.add(() => critters.process(transformed));
1284
+ transformed = transformed.replace(/<link\srel="stylesheet"/g, '<link rel="stylesheet" crossorigin');
1285
+ }
1318
1286
  if (styleTag)
1319
1287
  transformed = transformed.replace("<head>", `<head>${styleTag}`);
1320
1288
  const formatted = await formatHtml(transformed, formatting);
@@ -1364,9 +1332,14 @@ async function formatHtml(html, formatting) {
1364
1332
  minifyCSS: true
1365
1333
  });
1366
1334
  } else if (formatting === "prettify") {
1367
- const prettier = (await import('prettier/esm/standalone.mjs')).default;
1368
- const parserHTML = (await import('prettier/esm/parser-html.mjs')).default;
1369
- return prettier.format(html, { semi: false, parser: "html", plugins: [parserHTML] });
1335
+ try {
1336
+ const prettier = (await import('prettier/esm/standalone.mjs')).default;
1337
+ const parserHTML = (await import('prettier/esm/parser-html.mjs')).default;
1338
+ return prettier.format(html, { semi: false, parser: "html", plugins: [parserHTML] });
1339
+ } catch (e) {
1340
+ console.error(`${kolorist.gray("[vite-react-ssg]")} ${kolorist.red(`Error formatting html: ${e?.message}`)}`);
1341
+ return html;
1342
+ }
1370
1343
  }
1371
1344
  return html;
1372
1345
  }
@@ -1388,114 +1361,48 @@ function collectModules(manifest, entry, mods = /* @__PURE__ */ new Set()) {
1388
1361
  return mods;
1389
1362
  }
1390
1363
 
1391
- const SHORTCUTS = [
1392
- {
1393
- key: "u",
1394
- description: "show server url",
1395
- action(vite, _) {
1396
- vite.config.logger.info("");
1397
- printServerInfo(vite, true);
1398
- }
1399
- },
1400
- {
1401
- key: "c",
1402
- description: "clear console",
1403
- action(vite, _) {
1404
- vite.config.logger.clearScreen("error");
1405
- }
1406
- },
1407
- {
1408
- key: "q",
1409
- description: "quit",
1410
- action(_, server) {
1411
- server.close(() => process.exit());
1412
- }
1364
+ function invariant(value, message) {
1365
+ if (value === false || value === null || typeof value === "undefined") {
1366
+ console.error(
1367
+ "The following error is a bug in Remix; please open an issue! https://github.com/remix-run/remix/issues/new"
1368
+ );
1369
+ throw new Error(message);
1413
1370
  }
1414
- ];
1415
- function bindShortcuts(viteServer, server) {
1416
- if (!process.stdin.isTTY || process.env.CI)
1417
- return;
1418
- viteServer.config.logger.info(
1419
- kolorist.dim(kolorist.green(" \u279C")) + kolorist.dim(" press ") + kolorist.bold("h") + kolorist.dim(" to show help")
1420
- );
1421
- const shortcuts = SHORTCUTS;
1422
- let actionRunning = false;
1423
- const onInput = async (input) => {
1424
- if (input === "" || input === "") {
1425
- try {
1426
- await server.close();
1427
- } finally {
1428
- process.exit(1);
1429
- }
1430
- return;
1431
- }
1432
- if (actionRunning)
1433
- return;
1434
- if (input === "h") {
1435
- viteServer.config.logger.info(
1436
- [
1437
- "",
1438
- kolorist.bold(" Shortcuts"),
1439
- ...shortcuts.map(
1440
- (shortcut2) => kolorist.dim(" press ") + kolorist.bold(shortcut2.key) + kolorist.dim(` to ${shortcut2.description}`)
1441
- )
1442
- ].join("\n")
1443
- );
1444
- }
1445
- const shortcut = shortcuts.find((shortcut2) => shortcut2.key === input);
1446
- if (!shortcut)
1447
- return;
1448
- actionRunning = true;
1449
- await shortcut.action(viteServer, server);
1450
- actionRunning = false;
1451
- };
1452
- process.stdin.setRawMode(true);
1453
- process.stdin.on("data", onInput).setEncoding("utf8").resume();
1454
- server.on("close", () => {
1455
- process.stdin.off("data", onInput).pause();
1456
- });
1457
1371
  }
1458
1372
 
1459
- function baseMiddleware(rawBase) {
1460
- return (req, res, next) => {
1461
- const url = req.url;
1462
- const pathname = cleanUrl(url);
1463
- const base = rawBase;
1464
- if (pathname.startsWith(base))
1465
- return next();
1466
- if (pathname === "/" || pathname === "/index.html") {
1467
- res.writeHead(302, {
1468
- Location: base + url.slice(pathname.length)
1469
- });
1470
- res.end();
1471
- return;
1472
- }
1473
- const redirectPath = withTrailingSlash(url) !== base ? joinUrlSegments(base, url) : base;
1474
- if (req.headers.accept?.includes("text/html")) {
1475
- res.writeHead(404, {
1476
- "Content-Type": "text/html"
1477
- });
1478
- res.end(
1479
- `The server is configured with a public base URL of ${base} - did you mean to visit <a href="${redirectPath}">${redirectPath}</a> instead?`
1480
- );
1481
- } else {
1482
- res.writeHead(404, {
1483
- "Content-Type": "text/plain"
1484
- });
1485
- res.end(
1486
- `The server is configured with a public base URL of ${base} - did you mean to visit ${redirectPath} instead?`
1487
- );
1373
+ function fromNodeHeaders(nodeHeaders) {
1374
+ const headers = new Headers();
1375
+ for (const [key, values] of Object.entries(nodeHeaders)) {
1376
+ if (values) {
1377
+ if (Array.isArray(values)) {
1378
+ for (const value of values)
1379
+ headers.append(key, value);
1380
+ } else {
1381
+ headers.set(key, values);
1382
+ }
1488
1383
  }
1384
+ }
1385
+ return headers;
1386
+ }
1387
+ function fromNodeRequest(nodeReq) {
1388
+ const origin = nodeReq.headers.origin && nodeReq.headers.origin !== "null" ? nodeReq.headers.origin : `http://${nodeReq.headers.host}`;
1389
+ invariant(
1390
+ nodeReq.originalUrl,
1391
+ "Expected `nodeReq.originalUrl` to be defined"
1392
+ );
1393
+ const url = new URL(nodeReq.originalUrl, origin);
1394
+ const init = {
1395
+ method: nodeReq.method,
1396
+ headers: fromNodeHeaders(nodeReq.headers)
1489
1397
  };
1398
+ return new Request(url.href, init);
1490
1399
  }
1491
1400
 
1492
- async function dev(ssgOptions = {}, viteConfig = {}) {
1401
+ async function dev(ssgOptions = {}, viteConfig = {}, customOptions) {
1493
1402
  const mode = process.env.MODE || process.env.NODE_ENV || ssgOptions.mode || "development";
1494
1403
  const config = await vite.resolveConfig(viteConfig, "serve", mode, mode);
1495
1404
  const cwd = process.cwd();
1496
1405
  const root = config.root || cwd;
1497
- const httpsOptions = config.server.https;
1498
- setBase(config.rawBase);
1499
1406
  const {
1500
1407
  entry = await detectEntry(root),
1501
1408
  onBeforePageRender,
@@ -1507,21 +1414,12 @@ async function dev(ssgOptions = {}, viteConfig = {}) {
1507
1414
  const template = await fs__default.readFile(node_path.join(root, "index.html"), "utf-8");
1508
1415
  let viteServer;
1509
1416
  globalThis.__ssr_start_time = performance.now();
1510
- createServer().then(async (app) => {
1511
- const port = viteServer.config.server.port || 5173;
1512
- if (httpsOptions) {
1513
- const localHttpsOptions = typeof httpsOptions === "boolean" ? await devcert.certificateFor(["localhost"]) : httpsOptions;
1514
- const server = https__default.createServer(localHttpsOptions, app);
1515
- server.listen(port, () => {
1516
- printServerInfo(viteServer, false, true);
1517
- bindShortcuts(viteServer, server);
1518
- });
1519
- } else {
1520
- const server = app.listen(port, () => {
1521
- printServerInfo(viteServer);
1522
- bindShortcuts(viteServer, server);
1523
- });
1524
- }
1417
+ createServer().catch((err) => {
1418
+ console.error(
1419
+ `${kolorist.red(`failed to start server. error:`)}
1420
+ ${err.stack}`
1421
+ );
1422
+ process.exit(1);
1525
1423
  });
1526
1424
  async function createServer() {
1527
1425
  process.env.__DEV_MODE_SSR = "true";
@@ -1529,108 +1427,103 @@ async function dev(ssgOptions = {}, viteConfig = {}) {
1529
1427
  const { jsdomGlobal } = await import('./chunks/jsdomGlobal.cjs');
1530
1428
  jsdomGlobal();
1531
1429
  }
1532
- const app = express__default();
1533
1430
  viteServer = await vite.createServer({
1534
- // ...options,
1535
- server: { middlewareMode: true },
1536
- appType: "custom"
1537
- });
1538
- app.use(baseMiddleware(getBase()));
1539
- app.use((req, res, next) => {
1540
- viteServer.middlewares.handle(req, res, next);
1541
- });
1542
- app.use("*", async (req, res) => {
1543
- try {
1544
- const url = req.originalUrl;
1545
- const indexHTML = await viteServer.transformIndexHtml(url, template);
1546
- const createRoot = await viteServer.ssrLoadModule(ssrEntry).then((m) => m.createRoot);
1547
- const appCtx = await createRoot(false, url);
1548
- const { routes, getStyleCollector, base: base2, app: app2 } = appCtx;
1549
- const transformedIndexHTML = await onBeforePageRender?.(url, indexHTML, appCtx) || indexHTML;
1550
- const styleCollector = getStyleCollector ? await getStyleCollector() : null;
1551
- const { appHTML, bodyAttributes, htmlAttributes, metaAttributes, styleTag, routerContext } = await render(app2 ?? [...routes], createFetchRequest(req), styleCollector, base2);
1552
- metaAttributes.push(styleTag);
1553
- const matchesEntries = routerContext?.matches.map((match) => match.route.entry).filter((entry2) => !!entry2).map((entry2) => entry2[0] === "/" ? entry2 : `/${entry2}`) ?? [];
1554
- const mods = await Promise.all(
1555
- [entry, ...matchesEntries].map(async (entry2) => await viteServer.moduleGraph.getModuleByUrl(entry2))
1556
- );
1557
- const assetsUrls = /* @__PURE__ */ new Set();
1558
- const collectAssets = async (mod) => {
1559
- if (!mod || !mod?.ssrTransformResult)
1560
- return;
1561
- const { deps = [], dynamicDeps = [] } = mod?.ssrTransformResult;
1562
- const allDeps = [...deps, ...dynamicDeps];
1563
- for (const dep of allDeps) {
1564
- if (dep.endsWith(".css")) {
1565
- assetsUrls.add(dep);
1566
- } else if (dep.endsWith(".ts") || dep.endsWith(".tsx")) {
1567
- const depModule = await viteServer.moduleGraph.getModuleByUrl(dep);
1568
- depModule && await collectAssets(depModule);
1569
- }
1431
+ ...viteConfig,
1432
+ plugins: [
1433
+ ...viteConfig.plugins ?? [],
1434
+ {
1435
+ name: "vite-react-ssg:dev-server-remix",
1436
+ configureServer(server) {
1437
+ return () => {
1438
+ server.middlewares.use(async (req, res, _next) => {
1439
+ try {
1440
+ const url = req.originalUrl;
1441
+ const indexHTML = await viteServer.transformIndexHtml(url, template);
1442
+ const createRoot = await viteServer.ssrLoadModule(ssrEntry).then((m) => m.createRoot);
1443
+ const appCtx = await createRoot(false, url);
1444
+ const { routes, getStyleCollector, base, app } = appCtx;
1445
+ const transformedIndexHTML = await onBeforePageRender?.(url, indexHTML, appCtx) || indexHTML;
1446
+ const styleCollector = getStyleCollector ? await getStyleCollector() : null;
1447
+ const { appHTML, bodyAttributes, htmlAttributes, metaAttributes, styleTag, routerContext } = await render(app ?? [...routes], fromNodeRequest(req), styleCollector, base);
1448
+ metaAttributes.push(styleTag);
1449
+ const matchesEntries = routerContext?.matches.map((match) => match.route.entry).filter((entry2) => !!entry2).map((entry2) => entry2[0] === "/" ? entry2 : `/${entry2}`) ?? [];
1450
+ const mods = await Promise.all(
1451
+ [ssrEntry, entry, ...matchesEntries].map(async (entry2) => await viteServer.moduleGraph.getModuleByUrl(entry2))
1452
+ );
1453
+ const assetsUrls = /* @__PURE__ */ new Set();
1454
+ const collectAssets = async (mod) => {
1455
+ if (!mod || !mod?.ssrTransformResult)
1456
+ return;
1457
+ const { deps = [], dynamicDeps = [] } = mod?.ssrTransformResult;
1458
+ const allDeps = [...deps, ...dynamicDeps];
1459
+ for (const dep of allDeps) {
1460
+ if (dep.endsWith(".css")) {
1461
+ assetsUrls.add(dep);
1462
+ } else if (dep.endsWith(".ts") || dep.endsWith(".tsx")) {
1463
+ const depModule = await viteServer.moduleGraph.getModuleByUrl(dep);
1464
+ depModule && await collectAssets(depModule);
1465
+ }
1466
+ }
1467
+ };
1468
+ await Promise.all(mods.map(async (mod) => collectAssets(mod)));
1469
+ const preloadLink = [...assetsUrls].map((item) => createLink$1(joinUrlSegments(config.base, item)));
1470
+ metaAttributes.push(...preloadLink);
1471
+ const renderedHTML = await renderHTML({
1472
+ rootContainerId,
1473
+ appHTML,
1474
+ indexHTML: transformedIndexHTML,
1475
+ metaAttributes,
1476
+ bodyAttributes,
1477
+ htmlAttributes,
1478
+ initialState: null
1479
+ });
1480
+ const transformed = await onPageRendered?.(url, renderedHTML, appCtx) || renderedHTML;
1481
+ res.statusCode = 200;
1482
+ res.setHeader("Content-Type", "text/html");
1483
+ res.end(transformed);
1484
+ } catch (e) {
1485
+ viteServer.ssrFixStacktrace(e);
1486
+ console.error(`[vite-react-ssg] error: ${e.stack}`);
1487
+ res.statusCode = 500;
1488
+ res.end(e.stack);
1489
+ }
1490
+ });
1491
+ };
1570
1492
  }
1571
- };
1572
- await Promise.all(mods.map(async (mod) => collectAssets(mod)));
1573
- const preloadLink = [...assetsUrls].map((item) => createLink(item));
1574
- metaAttributes.push(...preloadLink);
1575
- const renderedHTML = await renderHTML({
1576
- rootContainerId,
1577
- appHTML,
1578
- indexHTML: transformedIndexHTML,
1579
- metaAttributes,
1580
- bodyAttributes,
1581
- htmlAttributes,
1582
- initialState: null
1583
- });
1584
- const transformed = await onPageRendered?.(url, renderedHTML, appCtx) || renderedHTML;
1585
- res.status(200).set({ "Content-Type": "text/html" }).end(transformed);
1586
- } catch (e) {
1587
- viteServer.ssrFixStacktrace(e);
1588
- console.error(`[vite-react-ssg] error: ${e.stack}`);
1589
- res.status(500).end(e.stack);
1590
- }
1493
+ }
1494
+ ]
1591
1495
  });
1592
- return app;
1496
+ await viteServer.listen();
1497
+ printServerInfo(viteServer, !!customOptions);
1498
+ viteServer.bindCLIShortcuts({ print: true });
1499
+ return viteServer;
1593
1500
  }
1594
1501
  }
1595
- async function printServerInfo(server, onlyUrl = false, https2 = false) {
1502
+ async function printServerInfo(server, onlyUrl = false) {
1503
+ if (onlyUrl)
1504
+ return server.printUrls();
1596
1505
  const info = server.config.logger.info;
1597
- const port = server.config.server.port || 5173;
1598
- const protocol = https2 ? "https" : "http";
1599
- const url = `${protocol}://localhost:${port}/${removeLeadingSlash(getBase())}`;
1600
- if (!onlyUrl) {
1601
- let ssrReadyMessage = " -- SSR";
1602
- if (globalThis.__ssr_start_time) {
1603
- ssrReadyMessage += ` ready in ${kolorist.reset(kolorist.bold(`${Math.round(
1604
- // @ts-expect-error global var
1605
- performance.now() - globalThis.__ssr_start_time
1606
- )}ms`))}`;
1607
- }
1608
- info(
1609
- `
1506
+ let ssrReadyMessage = " -- SSR";
1507
+ if (globalThis.__ssr_start_time) {
1508
+ ssrReadyMessage += ` ready in ${kolorist.reset(kolorist.bold(`${Math.round(
1509
+ // @ts-expect-error global var
1510
+ performance.now() - globalThis.__ssr_start_time
1511
+ )}ms`))}`;
1512
+ }
1513
+ info(
1514
+ `
1610
1515
  ${kolorist.bgLightCyan(` VITE-REACT-SSG v${version} `)}`,
1611
- { clear: !server.config.logger.hasWarned }
1612
- );
1613
- info(
1614
- `${kolorist.cyan(`
1516
+ { clear: !server.config.logger.hasWarned }
1517
+ );
1518
+ info(
1519
+ `${kolorist.cyan(`
1615
1520
  VITE v${vite.version}`) + kolorist.dim(ssrReadyMessage)}
1616
1521
  `
1617
- );
1618
- }
1522
+ );
1619
1523
  info(
1620
1524
  kolorist.green(" dev server running at:")
1621
1525
  );
1622
- printUrls(url, info);
1623
- }
1624
- function printUrls(url, info) {
1625
- const colorUrl = (url2) => kolorist.cyan(url2.replace(/:(\d+)\//, (_, port) => `:${kolorist.bold(port)}/`));
1626
- info(` ${kolorist.green("\u279C")} ${kolorist.bold("Local")}: ${colorUrl(url)}`);
1627
- }
1628
- let base = "";
1629
- function getBase() {
1630
- return base;
1631
- }
1632
- function setBase(newBase) {
1633
- base = newBase;
1526
+ server.printUrls();
1634
1527
  }
1635
1528
 
1636
1529
  exports.build = build;
package/dist/node.d.cts CHANGED
@@ -1,11 +1,11 @@
1
1
  import { InlineConfig } from 'vite';
2
- import { b as ViteReactSSGOptions } from './shared/vite-react-ssg.d734eb79.cjs';
2
+ import { b as ViteReactSSGOptions } from './shared/vite-react-ssg.870c683b.cjs';
3
3
  import 'critters';
4
4
  import 'react';
5
5
  import 'react-router-dom';
6
6
 
7
7
  declare function build(ssgOptions?: Partial<ViteReactSSGOptions>, viteConfig?: InlineConfig): Promise<void>;
8
8
 
9
- declare function dev(ssgOptions?: Partial<ViteReactSSGOptions>, viteConfig?: InlineConfig): Promise<void>;
9
+ declare function dev(ssgOptions?: Partial<ViteReactSSGOptions>, viteConfig?: InlineConfig, customOptions?: unknown): Promise<void>;
10
10
 
11
11
  export { build, dev };
package/dist/node.d.mts CHANGED
@@ -1,11 +1,11 @@
1
1
  import { InlineConfig } from 'vite';
2
- import { b as ViteReactSSGOptions } from './shared/vite-react-ssg.d734eb79.mjs';
2
+ import { b as ViteReactSSGOptions } from './shared/vite-react-ssg.870c683b.mjs';
3
3
  import 'critters';
4
4
  import 'react';
5
5
  import 'react-router-dom';
6
6
 
7
7
  declare function build(ssgOptions?: Partial<ViteReactSSGOptions>, viteConfig?: InlineConfig): Promise<void>;
8
8
 
9
- declare function dev(ssgOptions?: Partial<ViteReactSSGOptions>, viteConfig?: InlineConfig): Promise<void>;
9
+ declare function dev(ssgOptions?: Partial<ViteReactSSGOptions>, viteConfig?: InlineConfig, customOptions?: unknown): Promise<void>;
10
10
 
11
11
  export { build, dev };