@inglorious/ssx 2.0.6 → 2.1.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.
package/README.md CHANGED
@@ -3,9 +3,9 @@
3
3
  [![NPM version](https://img.shields.io/npm/v/@inglorious/ssx.svg)](https://www.npmjs.com/package/@inglorious/ssx)
4
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
5
 
6
- **Static Site Xecution** - Build blazing-fast static sites with [@inglorious/web](https://www.npmjs.com/package/@inglorious/web), complete with server-side rendering, client-side hydration, and zero-config routing.
6
+ **Static Site Xecution** - Build blazing-fast static sites with [@inglorious/web](https://www.npmjs.com/package/@inglorious/web), complete with static-site generation, optional server-side rendering, client-side hydration, and zero-config routing.
7
7
 
8
- SSX takes your entity-based web apps and generates optimized static HTML with full hydration support. Think Next.js SSG or Astro, but with the simplicity and predictability of Inglorious Web's entity architecture.
8
+ SSX takes your entity-based web apps and generates optimized static HTML with full hydration support. By default, pages are generated during the build and written to `dist/`, but you can opt specific pages into request-time rendering when you need fresh data or per-request behavior. Think Next.js SSG or Astro, but with the simplicity and predictability of Inglorious Web's entity architecture.
9
9
 
10
10
  ---
11
11
 
@@ -154,6 +154,32 @@ Deploy `dist/` to:
154
154
 
155
155
  ## Features
156
156
 
157
+ ### ⚙️ Rendering Modes: SSG by Default, SSR by Opt-In
158
+
159
+ SSX is primarily a static-site generator. During `ssx build`, most pages are rendered once and emitted as static HTML files in `dist/`.
160
+
161
+ If a page needs request-time rendering, export `ssr` from the page module:
162
+
163
+ ```javascript
164
+ // src/pages/checkout.js
165
+ import { html } from "@inglorious/web"
166
+
167
+ export const ssr = true
168
+
169
+ export async function load(entity) {
170
+ entity.checkout = await fetchCheckoutDetails()
171
+ }
172
+
173
+ export const Checkout = {
174
+ render(entity) {
175
+ return html`<h1>Checkout</h1>
176
+ <p>${entity.checkout?.status}</p>`
177
+ },
178
+ }
179
+ ```
180
+
181
+ SSR pages are skipped during the static build, then rendered on demand by the dev server or by a dedicated runtime server started with `ssx ssr`. That keeps the build output focused on pages that should be statically generated.
182
+
157
183
  ### 🗺️ Sitemap & RSS Generation
158
184
 
159
185
  SSX automatically generates `sitemap.xml` and `rss.xml` based on your pages. Configure them in `src/site.config.js`:
@@ -656,6 +682,19 @@ Options:
656
682
  -p, --port <port> Server port (default: 3000)
657
683
  ```
658
684
 
685
+ ### `ssx ssr`
686
+
687
+ Starts a runtime server that renders SSR-marked pages on demand:
688
+
689
+ ```bash
690
+ pnpm ssx ssr [options]
691
+
692
+ Options:
693
+ -c, --config <file> Config file (default: "site.config.js")
694
+ -r, --root <dir> Root directory (default: ".")
695
+ -p, --port <port> Server port (default: 3000)
696
+ ```
697
+
659
698
  ---
660
699
 
661
700
  ## Project Structure
package/bin/ssx.js CHANGED
@@ -9,6 +9,7 @@ import { Command } from "commander"
9
9
  import { build } from "../src/build/index.js"
10
10
  import { dev } from "../src/dev/index.js"
11
11
  import { serve } from "../src/serve/index.js"
12
+ import { ssr } from "../src/ssr/index.js"
12
13
 
13
14
  const __filename = fileURLToPath(import.meta.url)
14
15
  const __dirname = path.dirname(__filename)
@@ -119,6 +120,33 @@ program
119
120
  }
120
121
  })
121
122
 
123
+ program
124
+ .command("ssr")
125
+ .description("Start an SSR runtime server that renders pages on demand")
126
+ .option("-c, --config <file>", "config file name", "site.config.js")
127
+ .option("-r, --root <dir>", "root directory", ".")
128
+ .option("-p, --port <port>", "server port", 3000)
129
+ .action(async (options) => {
130
+ const cwd = process.cwd()
131
+ const rootDir = path.resolve(cwd, options.root)
132
+ const configPath = resolveConfigFile(rootDir, options.config)
133
+ const port = Number(options.port)
134
+
135
+ try {
136
+ await ssr({
137
+ ...options,
138
+ config: undefined,
139
+ root: undefined,
140
+ configPath,
141
+ rootDir,
142
+ port,
143
+ })
144
+ } catch (error) {
145
+ console.error("SSR server failed:", error)
146
+ process.exit(1)
147
+ }
148
+ })
149
+
122
150
  program.parse()
123
151
 
124
152
  function resolveConfigFile(rootDir, configFile) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/ssx",
3
- "version": "2.0.6",
3
+ "version": "2.1.0",
4
4
  "description": "Server-Side-X. Xecution? Xperience? Who knows.",
5
5
  "author": "IceOnFire <antony.mistretta@gmail.com> (https://ingloriouscoderz.it)",
6
6
  "license": "MIT",
@@ -64,15 +64,15 @@
64
64
  "svgo": "^4.0.0",
65
65
  "vite": "^7.1.3",
66
66
  "vite-plugin-image-optimizer": "^2.0.3",
67
+ "@inglorious/store": "11.0.0",
67
68
  "@inglorious/utils": "3.8.0",
68
- "@inglorious/web": "6.1.2",
69
- "@inglorious/store": "11.0.0"
69
+ "@inglorious/web": "6.1.2"
70
70
  },
71
71
  "devDependencies": {
72
72
  "prettier": "^3.6.2",
73
73
  "vitest": "^1.6.1",
74
- "@inglorious/eslint-config": "1.1.2",
75
- "@inglorious/logo": "3.0.6"
74
+ "@inglorious/logo": "3.0.6",
75
+ "@inglorious/eslint-config": "1.1.2"
76
76
  },
77
77
  "engines": {
78
78
  "node": ">= 22"
@@ -84,6 +84,7 @@
84
84
  "test": "vitest run",
85
85
  "dev": "node ./bin/ssx.js dev -r ./src/__fixtures__",
86
86
  "build": "node ./bin/ssx.js build -r ./src/__fixtures__",
87
- "preview": "node ./bin/ssx.js serve -r ./src/__fixtures__"
87
+ "preview": "node ./bin/ssx.js serve -r ./src/__fixtures__",
88
+ "ssr": "node ./bin/ssx.js ssr -r ./src/__fixtures__"
88
89
  }
89
90
  }
@@ -117,7 +117,7 @@ describe("build", () => {
117
117
  expect.any(String),
118
118
  expect.any(String),
119
119
  )
120
- expect(result).toEqual({ changed: 1, skipped: 1 })
120
+ expect(result).toEqual({ changed: 1, skipped: 0 })
121
121
  })
122
122
 
123
123
  it("should generate sitemap and rss if configured", async () => {
@@ -123,15 +123,20 @@ export async function build(options = {}) {
123
123
  loader,
124
124
  )
125
125
 
126
+ const staticChangedPages = changedPages.filter((page) => page.html)
127
+ const staticSkippedPages = skippedPages.filter(
128
+ (page) => page.html || page.metadata,
129
+ )
130
+
126
131
  // Combine rendered and skipped pages for sitemap/RSS
127
- const allGeneratedPages = [...changedPages, ...skippedPages]
132
+ const allGeneratedPages = [...staticChangedPages, ...staticSkippedPages]
128
133
 
129
- if (changedPages.length) {
134
+ if (staticChangedPages.length) {
130
135
  // 6. Generate client-side JavaScript
131
136
  console.log("\n💾 Writing files...\n")
132
137
 
133
138
  // 7. Write HTML pages
134
- for (const page of changedPages) {
139
+ for (const page of staticChangedPages) {
135
140
  const filePath = await writePageToDisk(page.path, page.html, outDir)
136
141
  console.log(` ✓ ${filePath}`)
137
142
  }
@@ -185,8 +190,8 @@ export async function build(options = {}) {
185
190
  console.log("\n✨ Build complete!\n")
186
191
 
187
192
  const result = {
188
- changed: changedPages.length,
189
- skipped: skippedPages.length,
193
+ changed: staticChangedPages.length,
194
+ skipped: staticSkippedPages.length,
190
195
  }
191
196
 
192
197
  if (previousNodeEnv == null) {
@@ -34,6 +34,10 @@ export async function generatePages(store, pages, options = {}, loader) {
34
34
  const module = await load(page.filePath)
35
35
  page.module = module
36
36
 
37
+ if (module?.ssr) {
38
+ continue
39
+ }
40
+
37
41
  const [entity] = store._api.getEntities(page.moduleName)
38
42
  if (page.locale) {
39
43
  entity.locale = page.locale
@@ -4,10 +4,14 @@ import path from "node:path"
4
4
  import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"
5
5
 
6
6
  import { renderPage } from "../render/index.js"
7
+ import { generateStore } from "../store/index.js"
7
8
  import { extractPageMetadata } from "./metadata.js"
8
9
  import { generatePages } from "./pages"
9
10
 
10
11
  vi.mock("../render/index.js")
12
+ vi.mock("../store/index.js", () => ({
13
+ generateStore: vi.fn(),
14
+ }))
11
15
  vi.mock("./metadata.js")
12
16
 
13
17
  describe("generatePages", () => {
@@ -146,4 +150,25 @@ describe("generatePages", () => {
146
150
 
147
151
  expect(entity.locale).toBe("pt")
148
152
  })
153
+
154
+ it("should skip pages marked as ssr during static build generation", async () => {
155
+ const sharedStore = {
156
+ _api: {
157
+ getEntities: vi.fn(() => [{}]),
158
+ getEntity: vi.fn(() => ({})),
159
+ },
160
+ }
161
+ const pages = [{ path: "/ssr", filePath: pageFile, moduleName: "ssr" }]
162
+ const loader = vi.fn(async () => ({ ssr: true, render: () => {} }))
163
+
164
+ vi.clearAllMocks()
165
+ renderPage.mockResolvedValue("<html></html>")
166
+ extractPageMetadata.mockReturnValue({})
167
+
168
+ await generatePages(sharedStore, pages, {}, loader)
169
+
170
+ expect(generateStore).not.toHaveBeenCalled()
171
+ expect(renderPage).not.toHaveBeenCalled()
172
+ expect(extractPageMetadata).not.toHaveBeenCalled()
173
+ })
149
174
  })
package/src/dev/index.js CHANGED
@@ -1,15 +1,10 @@
1
- import path from "node:path"
2
-
3
1
  import connect from "connect"
4
2
  import { createServer } from "vite"
5
3
 
6
- import { renderPage } from "../render/index.js"
7
- import { getPages, matchRoute } from "../router/index.js"
8
- import { generateApp } from "../scripts/app.js"
9
- import { generateStore } from "../store/index.js"
4
+ import { renderRequest } from "../ssr/index.js"
10
5
  import { loadConfig } from "../utils/config.js"
11
6
  import { createApiMiddleware } from "./api.js"
12
- import { createViteConfig, virtualFiles } from "./vite-config.js"
7
+ import { createViteConfig } from "./vite-config.js"
13
8
 
14
9
  /**
15
10
  * Starts the development server.
@@ -24,8 +19,6 @@ export async function dev(options = {}) {
24
19
  const mergedOptions = { ...config, ...options }
25
20
  const { rootDir = "." } = mergedOptions
26
21
 
27
- const pagesDir = path.join(rootDir, "src", "pages")
28
-
29
22
  console.log("🚀 Starting dev server...\n")
30
23
 
31
24
  // Create Vite dev server
@@ -57,50 +50,19 @@ export async function dev(options = {}) {
57
50
  return next() // Let Vite serve it
58
51
  }
59
52
 
60
- // Get all pages on each request (in dev mode, pages might be added/removed)
61
- const pages = await getPages(pagesDir, mergedOptions, loader)
62
-
63
- // Find matching page
64
- const page = pages.find((p) => matchRoute(p.path, url))
65
- if (!page) return next()
66
-
67
- const module = await loader(page.filePath)
68
- page.module = module
69
-
70
- // Generate store for THIS request (to pick up changes)
71
- const store = await generateStore(pages, mergedOptions, loader)
72
-
73
- const [entity] = store._api.getEntities(page.moduleName)
74
- if (page.locale) {
75
- entity.locale = page.locale
76
- }
77
-
78
- if (module.load) {
79
- await module.load(entity, page)
80
- }
81
-
82
- // Generate and update the virtual app file BEFORE rendering
83
- const app = await generateApp(
84
- pages,
85
- { ...mergedOptions, isDev: true },
53
+ const result = await renderRequest(url, {
54
+ rootDir,
55
+ options: { ...mergedOptions, isDev: true },
86
56
  loader,
87
- )
88
- virtualFiles.set("/main.js", app)
57
+ viteServer,
58
+ })
89
59
 
90
- // Invalidate the virtual module to ensure Vite picks up changes
91
- const virtualModule = viteServer.moduleGraph.getModuleById("/main.js")
92
- if (virtualModule) {
93
- viteServer.moduleGraph.invalidateModule(virtualModule)
60
+ if (!result) {
61
+ return next()
94
62
  }
95
63
 
96
- const html = await renderPage(store, page, entity, {
97
- ...mergedOptions,
98
- wrap: true,
99
- isDev: true,
100
- })
101
-
102
64
  res.setHeader("Content-Type", "text/html")
103
- res.end(html)
65
+ res.end(result.html)
104
66
  } catch (error) {
105
67
  viteServer.ssrFixStacktrace(error)
106
68
  next(error) // Let Vite handle the error overlay
@@ -0,0 +1,136 @@
1
+ import path from "node:path"
2
+
3
+ import connect from "connect"
4
+ import { createServer } from "vite"
5
+
6
+ import { createApiMiddleware } from "../dev/api.js"
7
+ import { createViteConfig, virtualFiles } from "../dev/vite-config.js"
8
+ import { renderPage } from "../render/index.js"
9
+ import { getPages, matchRoute } from "../router/index.js"
10
+ import { generateApp } from "../scripts/app.js"
11
+ import { generateStore } from "../store/index.js"
12
+ import { loadConfig } from "../utils/config.js"
13
+
14
+ export async function ssr(options = {}) {
15
+ const config = await loadConfig(options)
16
+ const mergedOptions = { ...config, ...options }
17
+ const { rootDir = "." } = mergedOptions
18
+
19
+ console.log("🚀 Starting SSR server...\n")
20
+
21
+ const viteConfig = createViteConfig(mergedOptions)
22
+ const viteServer = await createServer(viteConfig)
23
+ const loader = (p) => viteServer.ssrLoadModule(p)
24
+
25
+ const connectServer = connect()
26
+ connectServer.use(viteServer.middlewares)
27
+
28
+ const apiMiddleware = createApiMiddleware(rootDir, loader, (error) =>
29
+ viteServer.ssrFixStacktrace(error),
30
+ )
31
+ connectServer.use(apiMiddleware)
32
+
33
+ connectServer.use(async (req, res, next) => {
34
+ const [url] = req.url.split("?")
35
+
36
+ try {
37
+ if (
38
+ url.startsWith("/@") ||
39
+ url.startsWith("/api/") ||
40
+ url.includes(".") ||
41
+ url === "/favicon.ico"
42
+ ) {
43
+ return next()
44
+ }
45
+
46
+ const result = await renderRequest(url, {
47
+ rootDir,
48
+ options: { ...mergedOptions, isDev: false },
49
+ loader,
50
+ viteServer,
51
+ })
52
+
53
+ if (!result) {
54
+ return next()
55
+ }
56
+
57
+ res.setHeader("Content-Type", "text/html")
58
+ res.end(result.html)
59
+ } catch (error) {
60
+ viteServer.ssrFixStacktrace(error)
61
+ next(error)
62
+ }
63
+ })
64
+
65
+ const { port = 3000 } = viteConfig.server ?? {}
66
+ const server = connectServer.listen(port)
67
+
68
+ console.log(`\n✨ SSR server running at http://localhost:${port}\n`)
69
+ console.log("Press Ctrl+C to stop\n")
70
+
71
+ return {
72
+ close: () => {
73
+ server.close()
74
+ viteServer.close()
75
+ },
76
+ }
77
+ }
78
+
79
+ export async function renderRequest(
80
+ url,
81
+ { rootDir = ".", options = {}, loader, viteServer } = {},
82
+ ) {
83
+ const [pathname] = String(url || "").split("?")
84
+
85
+ if (
86
+ pathname.startsWith("/@") ||
87
+ pathname.startsWith("/api/") ||
88
+ pathname.includes(".") ||
89
+ pathname === "/favicon.ico"
90
+ ) {
91
+ return null
92
+ }
93
+
94
+ const pagesDir = path.join(rootDir, "src", "pages")
95
+ const pages = await getPages(pagesDir, options, loader)
96
+
97
+ const page = pages.find((candidate) => matchRoute(candidate.path, pathname))
98
+ if (!page) {
99
+ return null
100
+ }
101
+
102
+ const module = await loader(page.filePath)
103
+ page.module = module
104
+
105
+ const store = await generateStore(pages, options, loader)
106
+ const [entity] = store._api.getEntities(page.moduleName)
107
+ if (page.locale) {
108
+ entity.locale = page.locale
109
+ }
110
+
111
+ if (module.load) {
112
+ await module.load(entity, page)
113
+ }
114
+
115
+ const app = await generateApp(
116
+ pages,
117
+ { ...options, isDev: Boolean(options.isDev) },
118
+ loader,
119
+ )
120
+ virtualFiles.set("/main.js", app)
121
+
122
+ if (viteServer?.moduleGraph?.getModuleById) {
123
+ const virtualModule = viteServer.moduleGraph.getModuleById("/main.js")
124
+ if (virtualModule) {
125
+ viteServer.moduleGraph.invalidateModule(virtualModule)
126
+ }
127
+ }
128
+
129
+ const html = await renderPage(store, page, entity, {
130
+ ...options,
131
+ wrap: true,
132
+ isDev: Boolean(options.isDev),
133
+ })
134
+
135
+ return { html, page, entity, store }
136
+ }
@@ -0,0 +1,60 @@
1
+ import { describe, expect, it, vi } from "vitest"
2
+
3
+ const { generateStore, renderPage } = vi.hoisted(() => {
4
+ const generateStore = vi.fn()
5
+ const renderPage = vi.fn()
6
+
7
+ return { generateStore, renderPage }
8
+ })
9
+
10
+ vi.mock("../store/index.js", () => ({ generateStore }))
11
+ vi.mock("../render/index.js", () => ({ renderPage }))
12
+ vi.mock("../router/index.js", () => ({
13
+ getPages: vi.fn(async () => [
14
+ {
15
+ path: "/",
16
+ filePath: "page.js",
17
+ moduleName: "page",
18
+ },
19
+ ]),
20
+ matchRoute: vi.fn(() => true),
21
+ }))
22
+ vi.mock("../scripts/app.js", () => ({ generateApp: vi.fn(async () => "") }))
23
+ vi.mock("../dev/vite-config.js", () => ({ virtualFiles: new Map() }))
24
+
25
+ import { renderRequest as actualRenderRequest } from "./index.js"
26
+
27
+ describe("renderRequest", () => {
28
+ it("creates a fresh store for each SSR request", async () => {
29
+ const firstStore = {
30
+ _api: { getEntities: vi.fn(() => [{ locale: "en" }]) },
31
+ }
32
+ const secondStore = {
33
+ _api: { getEntities: vi.fn(() => [{ locale: "en" }]) },
34
+ }
35
+
36
+ generateStore.mockReset()
37
+ generateStore
38
+ .mockResolvedValueOnce(firstStore)
39
+ .mockResolvedValueOnce(secondStore)
40
+ renderPage.mockReset().mockResolvedValue("<html></html>")
41
+
42
+ const loader = vi.fn(async () => ({
43
+ load: vi.fn(),
44
+ render: () => {},
45
+ }))
46
+
47
+ await actualRenderRequest("/", {
48
+ rootDir: ".",
49
+ options: {},
50
+ loader,
51
+ })
52
+ await actualRenderRequest("/about", {
53
+ rootDir: ".",
54
+ options: {},
55
+ loader,
56
+ })
57
+
58
+ expect(generateStore).toHaveBeenCalledTimes(2)
59
+ })
60
+ })