@inglorious/ssx 2.3.2 → 2.4.0

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.
@@ -0,0 +1,134 @@
1
+ /**
2
+ * @vitest-environment node
3
+ */
4
+ import { existsSync } from "node:fs"
5
+ import fs from "node:fs/promises"
6
+ import { tmpdir } from "node:os"
7
+ import path from "node:path"
8
+
9
+ import { afterEach, beforeEach, describe, expect, it } from "vitest"
10
+
11
+ import { linkPageStyles, pageFilePath, STYLES_MANIFEST } from "./styles.js"
12
+
13
+ const PAGE_HTML = "<html><head><title>Hi</title></head><body></body></html>"
14
+ const MANIFEST = {
15
+ "dist/main.js": { file: "main.js", isEntry: true, css: ["main.css"] },
16
+ "src/pages/index.js": {
17
+ file: "index.abc.js",
18
+ isDynamicEntry: true,
19
+ imports: ["_lib.js"],
20
+ css: ["index.css"],
21
+ },
22
+ "src/pages/about.js": { file: "about.abc.js", isDynamicEntry: true },
23
+ "_lib.js": { file: "lib.abc.js", css: ["lib.css"] },
24
+ }
25
+
26
+ describe("linkPageStyles", () => {
27
+ let outDir
28
+
29
+ beforeEach(async () => {
30
+ outDir = await fs.mkdtemp(path.join(tmpdir(), "ssx-styles-"))
31
+ await writePage("/", PAGE_HTML)
32
+ await writePage("/about", PAGE_HTML)
33
+ await writeManifest(STYLES_MANIFEST, MANIFEST)
34
+ })
35
+
36
+ afterEach(async () => {
37
+ await fs.rm(outDir, { recursive: true, force: true })
38
+ })
39
+
40
+ it("links the entry's CSS, then the page's imports' and its own", async () => {
41
+ await linkPageStyles(pages(), { outDir, viteConfig: viteConfig() })
42
+
43
+ const html = await readPage("/")
44
+ expect(stylesheets(html)).toEqual(["/main.css", "/lib.css", "/index.css"])
45
+ expect(html.indexOf("/main.css")).toBeLessThan(html.indexOf("</head>"))
46
+ })
47
+
48
+ it("links only the entry's CSS to a page without styles of its own", async () => {
49
+ await linkPageStyles(pages(), { outDir, viteConfig: viteConfig() })
50
+
51
+ expect(stylesheets(await readPage("/about"))).toEqual(["/main.css"])
52
+ })
53
+
54
+ it("replaces its own links when run again", async () => {
55
+ await linkPageStyles(pages(), { outDir, viteConfig: viteConfig() })
56
+ await writeManifest(STYLES_MANIFEST, MANIFEST)
57
+ await linkPageStyles(pages(), { outDir, viteConfig: viteConfig() })
58
+
59
+ expect(stylesheets(await readPage("/"))).toEqual([
60
+ "/main.css",
61
+ "/lib.css",
62
+ "/index.css",
63
+ ])
64
+ })
65
+
66
+ it("prefixes the links with Vite's base", async () => {
67
+ await linkPageStyles(pages(), {
68
+ outDir,
69
+ viteConfig: viteConfig({ base: "/docs/" }),
70
+ })
71
+
72
+ expect(stylesheets(await readPage("/about"))).toEqual(["/docs/main.css"])
73
+ })
74
+
75
+ it("removes the manifest it asked for", async () => {
76
+ await linkPageStyles(pages(), { outDir, viteConfig: viteConfig() })
77
+
78
+ expect(existsSync(path.join(outDir, STYLES_MANIFEST))).toBe(false)
79
+ expect(existsSync(path.join(outDir, path.dirname(STYLES_MANIFEST)))).toBe(
80
+ false,
81
+ )
82
+ })
83
+
84
+ it("keeps a manifest the site asked for itself", async () => {
85
+ await writeManifest(".vite/manifest.json", MANIFEST)
86
+
87
+ await linkPageStyles(pages(), {
88
+ outDir,
89
+ viteConfig: { build: { manifest: true } },
90
+ })
91
+
92
+ expect(stylesheets(await readPage("/about"))).toEqual(["/main.css"])
93
+ expect(existsSync(path.join(outDir, ".vite/manifest.json"))).toBe(true)
94
+ })
95
+
96
+ it("leaves pages alone without a manifest", async () => {
97
+ await linkPageStyles(pages(), { outDir, viteConfig: {} })
98
+
99
+ expect(await readPage("/")).toBe(PAGE_HTML)
100
+ })
101
+
102
+ async function writePage(pagePath, html) {
103
+ const file = pageFilePath(pagePath, outDir)
104
+ await fs.mkdir(path.dirname(file), { recursive: true })
105
+ await fs.writeFile(file, html)
106
+ }
107
+
108
+ function readPage(pagePath) {
109
+ return fs.readFile(pageFilePath(pagePath, outDir), "utf-8")
110
+ }
111
+
112
+ async function writeManifest(file, manifest) {
113
+ const manifestPath = path.join(outDir, file)
114
+ await fs.mkdir(path.dirname(manifestPath), { recursive: true })
115
+ await fs.writeFile(manifestPath, JSON.stringify(manifest))
116
+ }
117
+ })
118
+
119
+ function pages() {
120
+ return [
121
+ { path: "/", filePath: "src/pages/index.js" },
122
+ { path: "/about", filePath: "src/pages/about.js" },
123
+ ]
124
+ }
125
+
126
+ function viteConfig(overrides = {}) {
127
+ return { build: { manifest: STYLES_MANIFEST }, ...overrides }
128
+ }
129
+
130
+ function stylesheets(html) {
131
+ return [...html.matchAll(/<link rel="stylesheet" href="([^"]*)"/g)].map(
132
+ ([, href]) => href,
133
+ )
134
+ }
@@ -4,6 +4,7 @@ import { mergeConfig } from "vite"
4
4
  import { ViteImageOptimizer } from "vite-plugin-image-optimizer"
5
5
 
6
6
  import { markdownPlugin } from "../utils/markdown.js"
7
+ import { STYLES_MANIFEST } from "./styles.js"
7
8
 
8
9
  /**
9
10
  * Generate Vite config for building the client bundle
@@ -26,14 +27,14 @@ export function createViteConfig(options = {}) {
26
27
  // (`<circle/><text/>` becomes `<circle><text/></circle>`), and SVG
27
28
  // shapes don't render children — charts vanish. html-minifier-terser's
28
29
  // keepClosingSlash only covers void HTML elements, so it can't fix it.
29
- ViteImageOptimizer({
30
- // Options can be overridden by the user in site.config.js via the `vite` property
31
- }),
30
+ ViteImageOptimizer({}),
32
31
  markdownPlugin(markdown),
33
32
  ],
34
33
  build: {
35
34
  outDir,
36
35
  emptyOutDir: false, // Don't delete HTML files we already generated
36
+ // Tells which CSS each page needs, to link it in the page's HTML.
37
+ manifest: STYLES_MANIFEST,
37
38
  rollupOptions: {
38
39
  input: {
39
40
  main: path.resolve(outDir, "main.js"),
package/src/client.js CHANGED
@@ -1,4 +1,2 @@
1
- // The runtime of the client entry SSX generates, which imports it by package name
2
- // from inside the app. Not meant for apps themselves.
3
1
  export { getLocaleFromPath, waitForLocale } from "./utils/i18n.js"
4
2
  export { syncPageHead } from "./utils/page-head.js"
package/src/dev/index.js CHANGED
@@ -21,12 +21,10 @@ export async function dev(options = {}) {
21
21
 
22
22
  console.log("🚀 Starting dev server...\n")
23
23
 
24
- // Create Vite dev server
25
24
  const viteConfig = createViteConfig(mergedOptions)
26
25
  const viteServer = await createServer(viteConfig)
27
26
  const loader = (p) => viteServer.ssrLoadModule(p)
28
27
 
29
- // Use Vite's middleware first (handles HMR, static files, etc.)
30
28
  const connectServer = connect()
31
29
  connectServer.use(viteServer.middlewares)
32
30
 
@@ -35,19 +33,17 @@ export async function dev(options = {}) {
35
33
  )
36
34
  connectServer.use(apiMiddleware)
37
35
 
38
- // Add SSR middleware
39
36
  connectServer.use(async (req, res, next) => {
40
37
  const [url] = req.url.split("?")
41
38
 
42
39
  try {
43
- // Skip special routes, static files, AND public assets
44
40
  if (
45
41
  url.startsWith("/@") ||
46
42
  url.startsWith("/api/") ||
47
- url.includes(".") || // Vite handles static files
43
+ url.includes(".") ||
48
44
  url === "/favicon.ico"
49
45
  ) {
50
- return next() // Let Vite serve it
46
+ return next()
51
47
  }
52
48
 
53
49
  const result = await renderRequest(url, {
@@ -66,7 +62,7 @@ export async function dev(options = {}) {
66
62
  res.end(result.html)
67
63
  } catch (error) {
68
64
  viteServer.ssrFixStacktrace(error)
69
- next(error) // Let Vite handle the error overlay
65
+ next(error)
70
66
  }
71
67
  })
72
68
 
@@ -38,7 +38,6 @@ export function createViteConfig(options = {}) {
38
38
  vite,
39
39
  )
40
40
 
41
- // A port given on the command line wins over the config's.
42
41
  if (port) config.server.port = port
43
42
  return config
44
43
  }
@@ -25,10 +25,8 @@ export async function toHTML(store, renderFn, options = {}) {
25
25
  const api = { ...store._api }
26
26
  api.render = createRender(api)
27
27
 
28
- // Generate the template
29
28
  const template = renderFn(api)
30
29
 
31
- // SSR render → HTML with hydration markers
32
30
  const result = ssrRender(template)
33
31
  const resultString = await collectResult(result)
34
32
 
@@ -59,12 +57,9 @@ export async function toHTML(store, renderFn, options = {}) {
59
57
  * @returns {string} Cleaned HTML string.
60
58
  */
61
59
  function stripLitMarkers(html) {
62
- return html
63
- .replace(/<!--\?[^>]*-->/g, "") // All lit-html markers
64
- .replace(/<!--\s*-->/g, "") // Empty comments
60
+ return html.replace(/<!--\?[^>]*-->/g, "").replace(/<!--\s*-->/g, "")
65
61
  }
66
62
 
67
- // TODO: this was copied from @inglorious/web, maybe expose it?
68
63
  /**
69
64
  * Creates a render function for the mount API.
70
65
  * @param {Api} api - The mount API.
@@ -4,7 +4,6 @@ import { getTextDirection, selectLocale } from "../utils/i18n.js"
4
4
  import { createGetPageOption } from "../utils/page-options.js"
5
5
  import { toHTML } from "./html.js"
6
6
 
7
- // Empty, so the site options apply; the layout supplies the final defaults.
8
7
  const DEFAULT_OPTIONS = {
9
8
  lang: "",
10
9
  dir: "",
@@ -6,11 +6,11 @@
6
6
  * @param {string} [options.lang="en"] - Language attribute.
7
7
  * @param {"ltr" | "rtl"} [options.dir="ltr"] - Text direction attribute.
8
8
  * @param {string} [options.charset="UTF-8"] - Character set.
9
- * @param {string} [options.title=""] - Page title.
9
+ * @param {string} [options.title=""] - Page title, as plain text.
10
10
  * @param {string} [options.favicon=""] - Favicon URL; without one, no icon link is rendered.
11
- * @param {Object} [options.meta={}] - Meta tags.
11
+ * @param {Object} [options.meta={}] - Meta tags, with plain-text contents.
12
12
  * @param {string[]} [options.styles=[]] - Stylesheets.
13
- * @param {string} [options.head=""] - Additional head content.
13
+ * @param {string} [options.head=""] - Additional head content, as HTML.
14
14
  * @param {string[]} [options.scripts=[]] - Scripts.
15
15
  * @param {boolean} [options.isDev] - Whether in dev mode.
16
16
  * @returns {string} The full HTML document.
@@ -30,23 +30,28 @@ export function layout(body, options) {
30
30
  isDev,
31
31
  } = options
32
32
 
33
+ // Titles and meta contents are plain text, as the client sets them when it
34
+ // navigates: escape them here, or a "&" or a quote breaks the markup.
33
35
  return `<!DOCTYPE html>
34
- <html lang="${lang}" dir="${dir}">
36
+ <html lang="${escapeHTML(lang)}" dir="${escapeHTML(dir)}">
35
37
  <head>
36
38
  ${prescripts
37
- .map((src) => `<script type="text/javascript" src="${src}"></script>`)
39
+ .map(
40
+ (src) =>
41
+ `<script type="text/javascript" src="${escapeHTML(src)}"></script>`,
42
+ )
38
43
  .join("\n")}
39
- <meta charset="${charset}" />
40
- <title>${title}</title>
41
- ${favicon ? `<link rel="icon" href="${favicon}">` : ""}
44
+ <meta charset="${escapeHTML(charset)}" />
45
+ <title>${escapeHTML(title)}</title>
46
+ ${favicon ? `<link rel="icon" href="${escapeHTML(favicon)}">` : ""}
42
47
  ${Object.entries(meta)
43
48
  .map(
44
49
  ([key, content]) =>
45
- `<meta ${key.includes(":") ? "property" : "name"}="${key}" content="${content}">`,
50
+ `<meta ${key.includes(":") ? "property" : "name"}="${escapeHTML(key)}" content="${escapeHTML(content)}">`,
46
51
  )
47
52
  .join("\n")}
48
53
  ${styles
49
- .map((href) => `<link rel="stylesheet" href="${href}">`)
54
+ .map((href) => `<link rel="stylesheet" href="${escapeHTML(href)}">`)
50
55
  .join("\n")}
51
56
  ${head}
52
57
  </head>
@@ -55,8 +60,18 @@ export function layout(body, options) {
55
60
  ${isDev ? `<script type="module" src="/@vite/client"></script>` : ``}
56
61
  <script type="module" src="/main.js"></script>
57
62
  ${scripts
58
- .map((src) => `<script type="module" src="${src}"></script>`)
63
+ .map(
64
+ (src) => `<script type="module" src="${escapeHTML(src)}"></script>`,
65
+ )
59
66
  .join("\n")}
60
67
  </body>
61
68
  </html>`
62
69
  }
70
+
71
+ function escapeHTML(value) {
72
+ return String(value)
73
+ .replace(/&/g, "&amp;")
74
+ .replace(/</g, "&lt;")
75
+ .replace(/>/g, "&gt;")
76
+ .replace(/"/g, "&quot;")
77
+ }
@@ -28,6 +28,25 @@ describe("layout", () => {
28
28
  )
29
29
  })
30
30
 
31
+ it("should escape the title, which is plain text", () => {
32
+ const html = layout("", { title: "Tom & Jerry <3" })
33
+ expect(html).toContain("<title>Tom &amp; Jerry &lt;3</title>")
34
+ })
35
+
36
+ it("should escape meta contents, so quotes can't break the tag", () => {
37
+ const html = layout("", {
38
+ meta: { description: 'Say "hi" & <wave>' },
39
+ })
40
+ expect(html).toContain(
41
+ '<meta name="description" content="Say &quot;hi&quot; &amp; &lt;wave&gt;">',
42
+ )
43
+ })
44
+
45
+ it("should leave additional head content as HTML", () => {
46
+ const html = layout("", { head: '<link rel="canonical" href="/a?b&c">' })
47
+ expect(html).toContain('<link rel="canonical" href="/a?b&c">')
48
+ })
49
+
31
50
  it("should render styles", () => {
32
51
  const html = layout("", { styles: ["/style.css", "/theme.css"] })
33
52
  expect(html).toContain('<link rel="stylesheet" href="/style.css">')
@@ -64,7 +83,6 @@ describe("layout", () => {
64
83
 
65
84
  expect(charset).toBeGreaterThan(-1)
66
85
  expect(headStart).toBeGreaterThan(charset)
67
- // Browsers only prescan the first 1024 bytes to detect the encoding.
68
86
  expect(charset).toBeLessThan(1024)
69
87
  })
70
88
 
@@ -32,8 +32,6 @@ export async function getPages(pagesDir = "pages", options, loader) {
32
32
  const moduleName = getModuleName(module)
33
33
 
34
34
  if (isDynamic(route.pattern) && module.ssr) {
35
- // Rendered on request: any path the pattern matches is a page, its
36
- // params read from the URL then. No staticPaths needed.
37
35
  addPages(pages, options, {
38
36
  pattern: route.pattern,
39
37
  path: route.pattern,
@@ -101,7 +99,6 @@ export async function getPages(pagesDir = "pages", options, loader) {
101
99
  * @returns {Promise<Array<Object>>} A list of route objects.
102
100
  */
103
101
  export async function getRoutes(pagesDir = "pages") {
104
- // Find all .js and .ts files in pages directory
105
102
  const files = await glob("**/*.{js,ts,jsx,tsx,md}", {
106
103
  cwd: pagesDir,
107
104
  ignore: ["**/*.test.{js,ts}", "**/*.spec.{js,ts}"],
@@ -122,7 +119,6 @@ export async function getRoutes(pagesDir = "pages") {
122
119
  }
123
120
  })
124
121
 
125
- // Sort routes by specificity (most specific first)
126
122
  routes.sort((a, b) => {
127
123
  const aScore = routeSpecificity(a.pattern)
128
124
  const bScore = routeSpecificity(b.pattern)
@@ -200,13 +196,12 @@ export function matchParams(pattern, url) {
200
196
  function filePathToPattern(file) {
201
197
  let pattern = file
202
198
  .replace(/\\/g, "/")
203
- .replace(/\.(js|ts|jsx|tsx|md)$/, "") // Remove extension
204
- .replace(/\/index$/, "") // index becomes root of directory
205
- .replace(/^index$/, "") // Handle root index
206
- .replace(/__(\w+)/g, "*") // __path becomes *
207
- .replace(/_(\w+)/g, ":$1") // _id becomes :id
199
+ .replace(/\.(js|ts|jsx|tsx|md)$/, "")
200
+ .replace(/\/index$/, "")
201
+ .replace(/^index$/, "")
202
+ .replace(/__(\w+)/g, "*")
203
+ .replace(/_(\w+)/g, ":$1")
208
204
 
209
- // Normalize to start with /
210
205
  return "/" + pattern.replace(/^\//, "")
211
206
  }
212
207
 
@@ -219,19 +214,16 @@ function filePathToPattern(file) {
219
214
  function patternToRegex(pattern) {
220
215
  const params = []
221
216
 
222
- // Replace :param with capture groups
223
217
  let regexStr = pattern.replace(/:(\w+)/g, (_, param) => {
224
218
  params.push(param)
225
219
  return "([^/]+)"
226
220
  })
227
221
 
228
- // Replace * with greedy capture
229
222
  regexStr = regexStr.replace(/\*/g, () => {
230
223
  params.push("path")
231
224
  return "(.*)"
232
225
  })
233
226
 
234
- // Exact match
235
227
  regexStr = "^" + regexStr + "$"
236
228
 
237
229
  return {
@@ -250,7 +242,6 @@ function patternToRegex(pattern) {
250
242
  function routeSpecificity(pattern) {
251
243
  let score = 0
252
244
 
253
- // Static segments add 3 points each
254
245
  const segments = pattern.split("/").filter(Boolean)
255
246
  segments.forEach((segment) => {
256
247
  if (!segment.startsWith(":") && segment !== "*") {
@@ -258,16 +249,13 @@ function routeSpecificity(pattern) {
258
249
  }
259
250
  })
260
251
 
261
- // Dynamic segments add 1 point
262
252
  const dynamicCount = (pattern.match(/:/g) || []).length
263
253
  score += dynamicCount
264
254
 
265
- // Catch-all routes have lowest priority (subtract points)
266
255
  if (pattern.includes("*")) {
267
256
  score += CATCH_ALL_ROUTE_WEIGHT
268
257
  }
269
258
 
270
- // Longer paths are more specific
271
259
  score += segments.length * SCORE_MULTIPLIER
272
260
 
273
261
  return score
@@ -315,7 +303,6 @@ function addPages(pages, options = {}, pageData) {
315
303
  const prefix = isDefault ? "" : `/${locale}`
316
304
 
317
305
  let localizedPath = prefix + pageData.path
318
- // Handle root path: / -> / (default), /fr (fr)
319
306
  if (pageData.path === "/" && !isDefault) {
320
307
  localizedPath = prefix
321
308
  }
@@ -16,13 +16,6 @@ describe("router", () => {
16
16
  it("should discover and sort routes correctly", async () => {
17
17
  const routes = await getRoutes(PAGES_DIR)
18
18
 
19
- // Expected order based on specificity:
20
- // 1. /posts/:id (static 'posts' + dynamic 'id') -> score ~4.2
21
- // 2. /blog/:slug (static 'blog' + dynamic 'slug') -> score ~4.2
22
- // 3. /about (static 'about') -> score ~3.1
23
- // 4. / (root) -> score 0
24
- // 5. /api/* (catch-all) -> score negative
25
-
26
19
  const patterns = routes.map((r) => r.pattern)
27
20
 
28
21
  expect(patterns).toContain("/posts/:slug")
@@ -31,14 +24,9 @@ describe("router", () => {
31
24
  expect(patterns).toContain("/")
32
25
  expect(patterns).toContain("/api/*")
33
26
 
34
- // Check specific ordering constraints
35
- // Specific routes before catch-all
36
27
  expect(patterns.indexOf("/about")).toBeLessThan(
37
28
  patterns.indexOf("/api/*"),
38
29
  )
39
- // Root usually comes after specific paths but before catch-all if it was a catch-all root,
40
- // but here / is static.
41
- // Let's just check that we found them.
42
30
  expect(routes.length).toBeGreaterThanOrEqual(6)
43
31
  })
44
32
  })
@@ -48,10 +36,8 @@ describe("router", () => {
48
36
  const consoleSpy = vi.spyOn(console, "warn").mockImplementation(() => {})
49
37
  const pages = await getPages(PAGES_DIR)
50
38
 
51
- // Verify that we got some pages
52
39
  expect(pages.length).toBeGreaterThan(0)
53
40
 
54
- // Verify specific pages exist and have correct structure
55
41
  const rootPage = pages.find((p) => p.pattern === "/")
56
42
  expect(rootPage).toBeDefined()
57
43
  expect(rootPage.filePath).toMatch(/pages[/\\]index\.js$/)
@@ -60,7 +46,6 @@ describe("router", () => {
60
46
  expect(aboutPage).toBeDefined()
61
47
  expect(aboutPage.filePath).toMatch(/pages[/\\]about\.js$/)
62
48
 
63
- // Dynamic route without staticPaths should be skipped (and warn)
64
49
  const blogPage = pages.find((p) => p.path.includes("/api/"))
65
50
  expect(blogPage).toBeUndefined()
66
51
 
@@ -122,7 +107,6 @@ describe("router", () => {
122
107
  })
123
108
 
124
109
  it("should handle trailing slashes implicitly via split", () => {
125
- // split('/').filter(Boolean) removes empty strings, so trailing slashes are ignored
126
110
  expect(matchRoute("/about/", "/about")).toBe(true)
127
111
  expect(matchRoute("/about", "/about/")).toBe(true)
128
112
  })
@@ -22,7 +22,6 @@ export async function generateApp(pages, options = {}, loader) {
22
22
  const entities = await getStoreStuff("entities", options, loader)
23
23
  const hasEntitiesFile = Object.keys(entities).length
24
24
 
25
- // Build client route map, including localized patterns (e.g. /it/about).
26
25
  const routesByPattern = new Map()
27
26
  for (const page of pages) {
28
27
  const routePattern = getClientRoutePattern(page)
@@ -108,7 +108,6 @@ describe("generateApp", () => {
108
108
  expect(app).toContain(
109
109
  `const path = normalizeRoutePath(window.location.pathname)`,
110
110
  )
111
- // Its own path first, then a server-rendered page's pattern.
112
111
  expect(app).toContain(
113
112
  `pages.find((page) => normalizeRoutePath(page.path) === path) ??`,
114
113
  )
@@ -12,10 +12,13 @@ import { loadConfig } from "../utils/config.js"
12
12
 
13
13
  const require = createRequire(import.meta.url)
14
14
 
15
+ const DEFAULT_PORT = 3000
16
+
15
17
  /**
16
18
  * Starts a production server that serves static files and API routes.
17
19
  *
18
20
  * @param {Object} options - Configuration options.
21
+ * @param {number} [options.port] - The port from the command line, which overrides the config's `vite.server.port`.
19
22
  * @returns {Promise<{close: Function}>} A promise that resolves to a server control object.
20
23
  */
21
24
  export async function serve(options = {}) {
@@ -24,7 +27,7 @@ export async function serve(options = {}) {
24
27
  const mergedOptions = { ...config, ...options }
25
28
  const { rootDir = ".", outDir = "dist" } = mergedOptions
26
29
 
27
- const { port = 3000 } = mergedOptions.vite?.server ?? {}
30
+ const port = options.port ?? mergedOptions.vite?.server?.port ?? DEFAULT_PORT
28
31
 
29
32
  console.log("🚀 Starting production server...\n")
30
33
 
@@ -0,0 +1,77 @@
1
+ /**
2
+ * @vitest-environment node
3
+ */
4
+ import { mkdtemp, rm, writeFile } from "node:fs/promises"
5
+ import net from "node:net"
6
+ import { tmpdir } from "node:os"
7
+ import path from "node:path"
8
+
9
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
10
+
11
+ import { serve } from "./index.js"
12
+
13
+ describe("serve", () => {
14
+ let outDir
15
+ let server
16
+
17
+ beforeEach(async () => {
18
+ vi.spyOn(console, "log").mockImplementation(() => {})
19
+ outDir = await mkdtemp(path.join(tmpdir(), "ssx-serve-"))
20
+ await writeFile(path.join(outDir, "index.html"), "<h1>Home</h1>")
21
+ })
22
+
23
+ afterEach(async () => {
24
+ server?.close()
25
+ await rm(outDir, { recursive: true, force: true })
26
+ vi.restoreAllMocks()
27
+ })
28
+
29
+ it("listens on the port it is given", async () => {
30
+ const port = await freePort()
31
+
32
+ server = await serve({ rootDir: outDir, outDir, port })
33
+
34
+ const response = await fetch(`http://localhost:${port}/`)
35
+ expect(await response.text()).toBe("<h1>Home</h1>")
36
+ })
37
+
38
+ it("falls back to the config's vite.server.port", async () => {
39
+ const port = await freePort()
40
+
41
+ server = await serve({
42
+ rootDir: outDir,
43
+ outDir,
44
+ vite: { server: { port } },
45
+ })
46
+
47
+ const response = await fetch(`http://localhost:${port}/`)
48
+ expect(response.ok).toBe(true)
49
+ })
50
+
51
+ it("prefers the given port over the config's", async () => {
52
+ const port = await freePort()
53
+ const configPort = await freePort()
54
+
55
+ server = await serve({
56
+ rootDir: outDir,
57
+ outDir,
58
+ port,
59
+ vite: { server: { port: configPort } },
60
+ })
61
+
62
+ const response = await fetch(`http://localhost:${port}/`)
63
+ expect(response.ok).toBe(true)
64
+ })
65
+ })
66
+
67
+ function freePort() {
68
+ return new Promise((resolve, reject) => {
69
+ const probe = net.createServer()
70
+ probe.unref()
71
+ probe.on("error", reject)
72
+ probe.listen(0, () => {
73
+ const { port } = probe.address()
74
+ probe.close(() => resolve(port))
75
+ })
76
+ })
77
+ }
package/src/ssr/index.js CHANGED
@@ -114,7 +114,6 @@ export async function renderRequest(
114
114
  await registerApp(resolvedPages, options, loader, viteServer)
115
115
  }
116
116
 
117
- // A page of its own path first, then one whose pattern matches the URL.
118
117
  const origPage =
119
118
  resolvedPages.find(
120
119
  (candidate) =>
@@ -140,7 +139,6 @@ export async function renderRequest(
140
139
  if (page.locale) {
141
140
  entity.locale = page.locale
142
141
  }
143
- // Translations in the page's locale, for `load` and the render.
144
142
  await waitForLocale(store, page.locale)
145
143
 
146
144
  if (module.load) {
@@ -1,6 +1,4 @@
1
1
  // @vitest-environment node
2
- // The server runs on Node, whose Request keeps cookies; a browser-like one
3
- // drops them.
4
2
  import { describe, expect, it, vi } from "vitest"
5
3
 
6
4
  const { generateStore, renderPage } = vi.hoisted(() => ({
@@ -65,12 +65,10 @@ describe("generateStore", () => {
65
65
  filePath: path.join(PAGES_DIR, "index.js"),
66
66
  }
67
67
 
68
- // Point to a directory that doesn't contain entities.js
69
68
  const store = await generateStore([page], {
70
69
  rootDir: path.join(ROOT_DIR, "pages"),
71
70
  })
72
71
 
73
- // Should initialize with empty entities (or at least not the ones from fixtures)
74
72
  expect(store.getState()).not.toHaveProperty("about")
75
73
  })
76
74