@inglorious/ssx 2.1.4 → 2.1.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/ssx",
3
- "version": "2.1.4",
3
+ "version": "2.1.6",
4
4
  "description": "Server-Side-X. Xecution? Xperience? Who knows.",
5
5
  "author": "Matteo Antony Mistretta <antony.mistretta@gmail.com> (https://ingloriouscoderz.it)",
6
6
  "license": "MIT",
@@ -48,30 +48,30 @@
48
48
  },
49
49
  "sideEffects": false,
50
50
  "dependencies": {
51
- "@lit-labs/ssr": "^4.0.0",
52
- "commander": "^14.0.2",
51
+ "@inglorious/store": "11.0.1",
52
+ "@inglorious/utils": "3.8.0",
53
+ "@inglorious/web": "6.4.1",
54
+ "@lit-labs/ssr": "^4.1.0",
55
+ "commander": "^15.0.0",
53
56
  "connect": "^3.7.0",
54
- "fast-xml-parser": "^5.3.3",
55
- "glob": "^13.0.0",
57
+ "fast-xml-parser": "^5.11.1",
58
+ "glob": "^13.0.6",
56
59
  "gray-matter": "^4.0.3",
57
- "highlight.js": "^11.11.1",
58
- "katex": "^0.16.27",
59
- "markdown-it": "^14.1.0",
60
+ "highlight.js": "^11.12.0",
61
+ "katex": "^0.18.6",
62
+ "markdown-it": "^15.0.1",
60
63
  "markdown-it-texmath": "^1.0.0",
61
- "mermaid": "^11.12.2",
62
- "sharp": "^0.34.5",
63
- "svgo": "^4.0.0",
64
- "vite": "^7.1.3",
65
- "vite-plugin-image-optimizer": "^2.0.3",
66
- "@inglorious/store": "11.0.0",
67
- "@inglorious/web": "6.4.0",
68
- "@inglorious/utils": "3.8.0"
64
+ "mermaid": "^11.17.2",
65
+ "sharp": "^0.35.4",
66
+ "svgo": "^4.1.0",
67
+ "vite": "^8.2.2",
68
+ "vite-plugin-image-optimizer": "^2.0.3"
69
69
  },
70
70
  "devDependencies": {
71
- "prettier": "^3.6.2",
72
- "vitest": "^1.6.1",
73
71
  "@inglorious/eslint-config": "1.1.2",
74
- "@inglorious/logo": "3.0.9"
72
+ "@inglorious/logo": "3.0.10",
73
+ "prettier": "^3.9.6",
74
+ "vitest": "^5.0.0"
75
75
  },
76
76
  "engines": {
77
77
  "node": ">= 22"
@@ -11,8 +11,9 @@ import { loadConfig } from "../utils/config.js"
11
11
  import { build } from "."
12
12
  import {
13
13
  createManifest,
14
+ createPageHasher,
14
15
  determineRebuildPages,
15
- hashEntities,
16
+ hashSharedSources,
16
17
  loadManifest,
17
18
  saveManifest,
18
19
  } from "./manifest.js"
@@ -22,7 +23,25 @@ import { generateRSS } from "./rss.js"
22
23
  import { generateSitemap } from "./sitemap.js"
23
24
  import { createViteConfig } from "./vite-config.js"
24
25
 
25
- vi.mock("node:fs/promises")
26
+ const mockRm = vi.hoisted(() => vi.fn())
27
+ const mockMkdir = vi.hoisted(() => vi.fn())
28
+ const mockWriteFile = vi.hoisted(() => vi.fn())
29
+
30
+ vi.mock("node:fs/promises", async (importOriginal) => {
31
+ const actual = await importOriginal()
32
+ return {
33
+ ...actual,
34
+ rm: mockRm,
35
+ mkdir: mockMkdir,
36
+ writeFile: mockWriteFile,
37
+ default: {
38
+ ...actual.default,
39
+ rm: mockRm,
40
+ mkdir: mockMkdir,
41
+ writeFile: mockWriteFile,
42
+ },
43
+ }
44
+ })
26
45
  vi.mock("vite")
27
46
  vi.mock("../router/index.js")
28
47
  vi.mock("../scripts/app.js")
@@ -44,6 +63,7 @@ describe("build", () => {
44
63
  ssrLoadModule: vi.fn(),
45
64
  close: vi.fn(),
46
65
  })
66
+ createPageHasher.mockReturnValue(vi.fn().mockResolvedValue("page-hash"))
47
67
  })
48
68
 
49
69
  afterEach(() => {
@@ -55,7 +75,7 @@ describe("build", () => {
55
75
  loadConfig.mockResolvedValue({})
56
76
  loadManifest.mockResolvedValue(null) // First build
57
77
  getPages.mockResolvedValue([{ path: "/" }])
58
- hashEntities.mockResolvedValue("hash")
78
+ hashSharedSources.mockResolvedValue("hash")
59
79
  generateStore.mockResolvedValue({
60
80
  store: {},
61
81
  entities: {},
@@ -91,9 +111,9 @@ describe("build", () => {
91
111
  })
92
112
 
93
113
  it("should handle incremental builds", async () => {
94
- const manifest = { entities: "hash" }
114
+ const manifest = { shared: "hash" }
95
115
  loadManifest.mockResolvedValue(manifest)
96
- hashEntities.mockResolvedValue("hash")
116
+ hashSharedSources.mockResolvedValue("hash")
97
117
 
98
118
  const allPages = [{ path: "/changed" }, { path: "/skipped" }]
99
119
  getPages.mockResolvedValue(allPages)
@@ -9,9 +9,10 @@ import { generateStore } from "../store/index.js"
9
9
  import { loadConfig } from "../utils/config.js"
10
10
  import {
11
11
  createManifest,
12
+ createPageHasher,
12
13
  determineRebuildPages,
13
- hashEntities,
14
14
  hashRuntime,
15
+ hashSharedSources,
15
16
  loadManifest,
16
17
  saveManifest,
17
18
  } from "./manifest.js"
@@ -83,8 +84,9 @@ export async function build(options = {}) {
83
84
  await copyPublicDir(mergedOptions)
84
85
 
85
86
  // Determine which pages need rebuilding
86
- const entitiesHash = await hashEntities(rootDir)
87
+ const sharedHash = await hashSharedSources(rootDir)
87
88
  const runtimeHash = await hashRuntime()
89
+ const getPageHash = createPageHasher(vite)
88
90
  let pagesToChange = allPages
89
91
  let pagesToSkip = []
90
92
 
@@ -92,8 +94,9 @@ export async function build(options = {}) {
92
94
  const result = await determineRebuildPages(
93
95
  allPages,
94
96
  manifest,
95
- entitiesHash,
97
+ sharedHash,
96
98
  runtimeHash,
99
+ getPageHash,
97
100
  )
98
101
  pagesToChange = result.pagesToBuild
99
102
  pagesToSkip = result.pagesToSkip
@@ -181,8 +184,9 @@ export async function build(options = {}) {
181
184
  if (incremental) {
182
185
  const newManifest = await createManifest(
183
186
  allGeneratedPages,
184
- entitiesHash,
187
+ sharedHash,
185
188
  runtimeHash,
189
+ getPageHash,
186
190
  )
187
191
  await saveManifest(outDir, newManifest)
188
192
  }
@@ -3,6 +3,18 @@ import fs from "node:fs/promises"
3
3
  import path from "node:path"
4
4
 
5
5
  const MANIFEST_FILE = ".ssx-manifest.json"
6
+
7
+ /**
8
+ * Degraded page hasher used when no Vite server is available: hashes the page
9
+ * module on its own, ignoring everything it imports.
10
+ *
11
+ * @param {Object} page - Page to hash.
12
+ * @returns {Promise<string|null>} Hash of the page module.
13
+ */
14
+ async function hashPageAlone(page) {
15
+ return await hashFile(page.filePath)
16
+ }
17
+
6
18
  const RUNTIME_FILES = [
7
19
  "../scripts/app.js",
8
20
  "./pages.js",
@@ -26,7 +38,7 @@ export async function loadManifest(outDir) {
26
38
  return JSON.parse(content)
27
39
  } catch {
28
40
  // No manifest exists (first build or clean build)
29
- return { pages: {}, entities: null, runtime: null, buildTime: null }
41
+ return { pages: {}, shared: null, runtime: null, buildTime: null }
30
42
  }
31
43
  }
32
44
 
@@ -59,14 +71,46 @@ export async function hashFile(filePath) {
59
71
  }
60
72
 
61
73
  /**
62
- * Computes a hash for the entities file.
74
+ * Source files that affect every page but are not reachable from any page
75
+ * module, so the per-page dependency graph cannot see them.
76
+ *
77
+ * `entities` and `types` are loaded directly by `getStoreStuff`, and the site
78
+ * config supplies the layout that wraps every rendered page.
79
+ */
80
+ const SHARED_SOURCES = [
81
+ ["src", "store", "entities"],
82
+ ["src", "store", "types"],
83
+ ["src", "site.config"],
84
+ ]
85
+
86
+ const SOURCE_EXTENSIONS = ["js", "ts", "mjs", "cjs"]
87
+
88
+ /**
89
+ * Computes a hash over the source files that every page depends on but cannot
90
+ * reach through its own imports: store entities, store types, and the site
91
+ * config. When this changes, page HTML must be regenerated even if no page
92
+ * module changed.
63
93
  *
64
- * @param {string} rootDir - Source root directory.
65
- * @returns {Promise<string|null>} Hash of entities.js.
94
+ * @param {string} rootDir - Project root directory (the parent of `src`).
95
+ * @returns {Promise<string>} Hash of the shared sources.
66
96
  */
67
- export async function hashEntities(rootDir) {
68
- const entitiesPath = path.join(rootDir, "store", "entities.js")
69
- return await hashFile(entitiesPath)
97
+ export async function hashSharedSources(rootDir) {
98
+ const parts = []
99
+
100
+ for (const segments of SHARED_SOURCES) {
101
+ const base = path.join(rootDir, ...segments)
102
+
103
+ for (const extension of SOURCE_EXTENSIONS) {
104
+ const filePath = `${base}.${extension}`
105
+ const hash = await hashFile(filePath)
106
+
107
+ if (hash !== null) {
108
+ parts.push(`${filePath}:${hash}`)
109
+ }
110
+ }
111
+ }
112
+
113
+ return crypto.createHash("md5").update(parts.join("\n")).digest("hex")
70
114
  }
71
115
 
72
116
  /**
@@ -88,25 +132,114 @@ export async function hashRuntime() {
88
132
  return crypto.createHash("md5").update(contents.join("\n")).digest("hex")
89
133
  }
90
134
 
135
+ /**
136
+ * Determines whether a module id refers to a real source file that should take
137
+ * part in change detection.
138
+ *
139
+ * Virtual modules (Vite internals, `\0`-prefixed) and anything installed under
140
+ * `node_modules` are excluded: they are not the site's own source, and
141
+ * pre-bundled dependency ids are not stable between installs.
142
+ *
143
+ * @param {string|null|undefined} id - Module id from the Vite module graph.
144
+ * @returns {boolean} True if the module should be hashed.
145
+ */
146
+ function isTrackableModule(id) {
147
+ if (!id || typeof id !== "string") return false
148
+ if (id.startsWith("\0")) return false
149
+ if (!path.isAbsolute(id)) return false
150
+ if (id.split(path.sep).includes("node_modules")) return false
151
+
152
+ return true
153
+ }
154
+
155
+ /**
156
+ * Collects every source file a page depends on, following the Vite module graph
157
+ * so that changes to shared partials (components, nested types, styles, data)
158
+ * invalidate the pages that render them.
159
+ *
160
+ * Falls back to the page module alone when the graph has no entry for it, so
161
+ * change detection degrades to the previous behaviour instead of to nothing.
162
+ *
163
+ * @param {string} filePath - Path to the page module.
164
+ * @param {import("vite").ViteDevServer} [vite] - Vite server holding the module graph.
165
+ * @returns {Array<string>} Sorted, de-duplicated list of dependency file paths.
166
+ */
167
+ export function collectPageDependencies(filePath, vite) {
168
+ const root = vite?.moduleGraph?.getModuleById(filePath)
169
+ const dependencies = new Set([filePath])
170
+ const visited = new Set()
171
+ const stack = root ? [root] : []
172
+
173
+ while (stack.length) {
174
+ const node = stack.pop()
175
+
176
+ if (visited.has(node)) continue
177
+ visited.add(node)
178
+
179
+ if (isTrackableModule(node.id)) {
180
+ dependencies.add(node.id)
181
+ }
182
+
183
+ for (const imported of node.importedModules) {
184
+ stack.push(imported)
185
+ }
186
+ }
187
+
188
+ return [...dependencies].sort()
189
+ }
190
+
191
+ /**
192
+ * Creates a page hasher that folds a page's whole dependency graph into a
193
+ * single hash. File contents are read at most once per build, so pages sharing
194
+ * a partial do not re-read it.
195
+ *
196
+ * @param {import("vite").ViteDevServer} [vite] - Vite server holding the module graph.
197
+ * @returns {(page: Object) => Promise<string>} Function producing a page hash.
198
+ */
199
+ export function createPageHasher(vite) {
200
+ const contents = new Map()
201
+
202
+ const hashOnce = async (filePath) => {
203
+ if (!contents.has(filePath)) {
204
+ contents.set(filePath, await hashFile(filePath))
205
+ }
206
+
207
+ return contents.get(filePath)
208
+ }
209
+
210
+ return async (page) => {
211
+ const dependencies = collectPageDependencies(page.filePath, vite)
212
+ const parts = await Promise.all(
213
+ dependencies.map(
214
+ async (filePath) => `${filePath}:${await hashOnce(filePath)}`,
215
+ ),
216
+ )
217
+
218
+ return crypto.createHash("md5").update(parts.join("\n")).digest("hex")
219
+ }
220
+ }
221
+
91
222
  /**
92
223
  * Determines which pages need to be rebuilt.
93
- * Compares current file hashes against the manifest.
224
+ * Compares current dependency hashes against the manifest.
94
225
  *
95
226
  * @param {Array<Object>} pages - All pages to potentially build.
96
227
  * @param {Object} manifest - Previous build manifest.
97
- * @param {string} entitiesHash - Current entities hash.
228
+ * @param {string} sharedHash - Current hash of the shared sources.
98
229
  * @param {string} runtimeHash - Current SSX runtime hash.
230
+ * @param {(page: Object) => Promise<string>} [getPageHash=hashPageAlone] - Produces a page's hash.
99
231
  * @returns {Promise<{pagesToBuild: Array<Object>, pagesToSkip: Array<Object>}>} Object with pagesToBuild and pagesSkipped.
100
232
  */
101
233
  export async function determineRebuildPages(
102
234
  pages,
103
235
  manifest,
104
- entitiesHash,
236
+ sharedHash,
105
237
  runtimeHash,
238
+ getPageHash = hashPageAlone,
106
239
  ) {
107
- // If entities changed, rebuild all pages
108
- if (manifest.entities !== entitiesHash) {
109
- console.log("📦 Entities changed, rebuilding all pages\n")
240
+ // If shared sources changed, rebuild all pages
241
+ if (manifest.shared !== sharedHash) {
242
+ console.log("📦 Shared sources changed, rebuilding all pages\n")
110
243
  return { pagesToBuild: pages, pagesToSkip: [] }
111
244
  }
112
245
 
@@ -119,7 +252,7 @@ export async function determineRebuildPages(
119
252
  const pagesToSkip = []
120
253
 
121
254
  for (const page of pages) {
122
- const currentHash = await hashFile(page.filePath)
255
+ const currentHash = await getPageHash(page)
123
256
  const previousHash = manifest.pages[page.path]?.hash
124
257
 
125
258
  if (currentHash !== previousHash) {
@@ -136,24 +269,29 @@ export async function determineRebuildPages(
136
269
  * Creates a new manifest from build results.
137
270
  *
138
271
  * @param {Array<Object>} renderedPages - All rendered pages.
139
- * @param {string} entitiesHash - Hash of entities file.
272
+ * @param {string} sharedHash - Hash of the shared sources.
140
273
  * @param {string} runtimeHash - Hash of SSX runtime internals.
274
+ * @param {(page: Object) => Promise<string>} [getPageHash=hashPageAlone] - Produces a page's hash.
141
275
  * @returns {Promise<Object>} New manifest.
142
276
  */
143
- export async function createManifest(renderedPages, entitiesHash, runtimeHash) {
277
+ export async function createManifest(
278
+ renderedPages,
279
+ sharedHash,
280
+ runtimeHash,
281
+ getPageHash = hashPageAlone,
282
+ ) {
144
283
  const pages = {}
145
284
 
146
285
  for (const page of renderedPages) {
147
- const hash = await hashFile(page.filePath)
148
286
  pages[page.path] = {
149
- hash,
287
+ hash: await getPageHash(page),
150
288
  filePath: page.filePath,
151
289
  }
152
290
  }
153
291
 
154
292
  return {
155
293
  pages,
156
- entities: entitiesHash,
294
+ shared: sharedHash,
157
295
  runtime: runtimeHash,
158
296
  buildTime: new Date().toISOString(),
159
297
  }
@@ -3,16 +3,55 @@ import fs from "node:fs/promises"
3
3
  import { afterEach, describe, expect, it, vi } from "vitest"
4
4
 
5
5
  import {
6
+ collectPageDependencies,
6
7
  createManifest,
8
+ createPageHasher,
7
9
  determineRebuildPages,
8
- hashEntities,
9
10
  hashFile,
10
11
  hashRuntime,
12
+ hashSharedSources,
11
13
  loadManifest,
12
14
  saveManifest,
13
15
  } from "./manifest"
14
16
 
15
- vi.mock("node:fs/promises")
17
+ const mockReadFile = vi.hoisted(() => vi.fn())
18
+ const mockWriteFile = vi.hoisted(() => vi.fn())
19
+
20
+ vi.mock("node:fs/promises", async (importOriginal) => {
21
+ const actual = await importOriginal()
22
+ return {
23
+ ...actual,
24
+ readFile: mockReadFile,
25
+ writeFile: mockWriteFile,
26
+ default: {
27
+ ...actual.default,
28
+ readFile: mockReadFile,
29
+ writeFile: mockWriteFile,
30
+ },
31
+ }
32
+ })
33
+
34
+ /**
35
+ * Builds a stub Vite server whose module graph maps each id to the ids it
36
+ * imports, mirroring the shape of `vite.moduleGraph`.
37
+ */
38
+ function fakeVite(graph) {
39
+ const nodes = new Map()
40
+ const nodeFor = (id) => {
41
+ if (!nodes.has(id)) {
42
+ nodes.set(id, { id, importedModules: new Set() })
43
+ }
44
+ return nodes.get(id)
45
+ }
46
+
47
+ for (const [id, imported] of Object.entries(graph)) {
48
+ for (const childId of imported) {
49
+ nodeFor(id).importedModules.add(nodeFor(childId))
50
+ }
51
+ }
52
+
53
+ return { moduleGraph: { getModuleById: (id) => nodes.get(id) } }
54
+ }
16
55
 
17
56
  describe("manifest", () => {
18
57
  const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {})
@@ -40,7 +79,7 @@ describe("manifest", () => {
40
79
  const result = await loadManifest("dist")
41
80
  expect(result).toEqual({
42
81
  pages: {},
43
- entities: null,
82
+ shared: null,
44
83
  runtime: null,
45
84
  buildTime: null,
46
85
  })
@@ -75,14 +114,30 @@ describe("manifest", () => {
75
114
  })
76
115
  })
77
116
 
78
- describe("hashEntities", () => {
79
- it("should hash entities.js in root dir", async () => {
80
- fs.readFile.mockResolvedValue("entities")
81
- await hashEntities("src")
82
- expect(fs.readFile).toHaveBeenCalledWith(
83
- expect.stringContaining("entities.js"),
84
- "utf-8",
85
- )
117
+ describe("hashSharedSources", () => {
118
+ it("should hash store and config files under src", async () => {
119
+ fs.readFile.mockResolvedValue("content")
120
+
121
+ await hashSharedSources("root")
122
+
123
+ const readPaths = fs.readFile.mock.calls.map(([filePath]) => filePath)
124
+
125
+ expect(readPaths).toContain("root/src/store/entities.js")
126
+ expect(readPaths).toContain("root/src/store/types.js")
127
+ expect(readPaths).toContain("root/src/site.config.js")
128
+ })
129
+
130
+ it("should return a stable hash regardless of extension order", async () => {
131
+ fs.readFile.mockImplementation(async (filePath) => {
132
+ if (filePath === "root/src/store/entities.ts") return "entities"
133
+ return null
134
+ })
135
+
136
+ const first = await hashSharedSources("root")
137
+ const second = await hashSharedSources("root")
138
+
139
+ expect(typeof first).toBe("string")
140
+ expect(first).toBe(second)
86
141
  })
87
142
  })
88
143
 
@@ -96,15 +151,15 @@ describe("manifest", () => {
96
151
  })
97
152
 
98
153
  describe("determineRebuildPages", () => {
99
- it("should rebuild all if entities hash changed", async () => {
154
+ it("should rebuild all if shared sources hash changed", async () => {
100
155
  const pages = [{ path: "/" }]
101
- const manifest = { entities: "old" }
156
+ const manifest = { shared: "old" }
102
157
  const result = await determineRebuildPages(pages, manifest, "new", "rt")
103
158
 
104
159
  expect(result.pagesToBuild).toEqual(pages)
105
160
  expect(result.pagesToSkip).toEqual([])
106
161
  expect(consoleSpy).toHaveBeenCalledWith(
107
- expect.stringContaining("Entities changed"),
162
+ expect.stringContaining("Shared sources changed"),
108
163
  )
109
164
  })
110
165
 
@@ -114,7 +169,7 @@ describe("manifest", () => {
114
169
  { path: "/same", filePath: "same.js" },
115
170
  ]
116
171
  const manifest = {
117
- entities: "hash",
172
+ shared: "hash",
118
173
  pages: {
119
174
  "/changed": { hash: "old-hash" },
120
175
  "/same": { hash: "9a0364b9e99bb480dd25e1f0284c8555" }, // md5("content")
@@ -141,9 +196,49 @@ describe("manifest", () => {
141
196
  expect(result.pagesToSkip[0].path).toBe("/same")
142
197
  })
143
198
 
199
+ it("should rebuild a page when a shared partial it imports changes", async () => {
200
+ const page = { path: "/", filePath: "/site/src/pages/index.js" }
201
+ const pages = [page]
202
+ const vite = fakeVite({
203
+ "/site/src/pages/index.js": ["/site/src/components/nav.js"],
204
+ })
205
+ const read = (edited) =>
206
+ fs.readFile.mockImplementation(
207
+ async (filePath) =>
208
+ `content of ${
209
+ edited && filePath === "/site/src/components/nav.js"
210
+ ? "/site/src/components/nav.js EDITED"
211
+ : filePath
212
+ }`,
213
+ )
214
+
215
+ read(false)
216
+ const before = await createPageHasher(vite)(page)
217
+
218
+ read(true)
219
+ const after = await createPageHasher(vite)(page)
220
+
221
+ expect(after).not.toBe(before)
222
+
223
+ const result = await determineRebuildPages(
224
+ pages,
225
+ {
226
+ shared: "hash",
227
+ runtime: "rt",
228
+ pages: { "/": { hash: before } },
229
+ },
230
+ "hash",
231
+ "rt",
232
+ createPageHasher(vite),
233
+ )
234
+
235
+ expect(result.pagesToBuild).toHaveLength(1)
236
+ expect(result.pagesToSkip).toHaveLength(0)
237
+ })
238
+
144
239
  it("should rebuild all if runtime hash changed", async () => {
145
240
  const pages = [{ path: "/" }]
146
- const manifest = { entities: "hash", runtime: "old-rt" }
241
+ const manifest = { shared: "hash", runtime: "old-rt" }
147
242
  const result = await determineRebuildPages(
148
243
  pages,
149
244
  manifest,
@@ -159,13 +254,113 @@ describe("manifest", () => {
159
254
  })
160
255
  })
161
256
 
257
+ describe("collectPageDependencies", () => {
258
+ it("should follow the module graph transitively", () => {
259
+ const vite = fakeVite({
260
+ "/site/src/pages/index.js": [
261
+ "/site/src/components/nav.js",
262
+ "/site/src/store/theme.js",
263
+ ],
264
+ "/site/src/components/nav.js": ["/site/src/components/logo.js"],
265
+ })
266
+
267
+ expect(collectPageDependencies("/site/src/pages/index.js", vite)).toEqual(
268
+ [
269
+ "/site/src/components/logo.js",
270
+ "/site/src/components/nav.js",
271
+ "/site/src/pages/index.js",
272
+ "/site/src/store/theme.js",
273
+ ],
274
+ )
275
+ })
276
+
277
+ it("should exclude node_modules and virtual modules", () => {
278
+ const vite = fakeVite({
279
+ "/site/src/pages/index.js": [
280
+ "/site/node_modules/dep/index.js",
281
+ "\0virtual:module",
282
+ "/site/src/components/nav.js",
283
+ ],
284
+ })
285
+
286
+ expect(collectPageDependencies("/site/src/pages/index.js", vite)).toEqual(
287
+ ["/site/src/components/nav.js", "/site/src/pages/index.js"],
288
+ )
289
+ })
290
+
291
+ it("should track linked workspace packages but ignore installed ones", () => {
292
+ const vite = fakeVite({
293
+ "/site/src/pages/index.js": [
294
+ "/repo/packages/web/src/index.js",
295
+ "/site/node_modules/@inglorious/web/dist/index.js",
296
+ ],
297
+ })
298
+
299
+ expect(collectPageDependencies("/site/src/pages/index.js", vite)).toEqual(
300
+ ["/repo/packages/web/src/index.js", "/site/src/pages/index.js"],
301
+ )
302
+ })
303
+
304
+ it("should handle import cycles", () => {
305
+ const vite = fakeVite({
306
+ "/site/a.js": ["/site/b.js"],
307
+ "/site/b.js": ["/site/a.js"],
308
+ })
309
+
310
+ expect(collectPageDependencies("/site/a.js", vite)).toEqual([
311
+ "/site/a.js",
312
+ "/site/b.js",
313
+ ])
314
+ })
315
+
316
+ it("should fall back to the page module when the graph has no entry", () => {
317
+ expect(
318
+ collectPageDependencies("/site/src/pages/index.js", fakeVite({})),
319
+ ).toEqual(["/site/src/pages/index.js"])
320
+ expect(collectPageDependencies("/site/src/pages/index.js")).toEqual([
321
+ "/site/src/pages/index.js",
322
+ ])
323
+ })
324
+ })
325
+
326
+ describe("createPageHasher", () => {
327
+ it("should read each dependency at most once across pages", async () => {
328
+ const vite = fakeVite({
329
+ "/site/a.js": ["/site/shared.js"],
330
+ "/site/b.js": ["/site/shared.js"],
331
+ })
332
+ fs.readFile.mockResolvedValue("content")
333
+
334
+ const getPageHash = createPageHasher(vite)
335
+ await getPageHash({ filePath: "/site/a.js" })
336
+ await getPageHash({ filePath: "/site/b.js" })
337
+
338
+ const reads = fs.readFile.mock.calls
339
+ .map(([filePath]) => filePath)
340
+ .filter((filePath) => filePath === "/site/shared.js")
341
+
342
+ expect(reads).toHaveLength(1)
343
+ })
344
+
345
+ it("should be order-independent", async () => {
346
+ const forward = fakeVite({ "/site/a.js": ["/site/x.js", "/site/y.js"] })
347
+ const reverse = fakeVite({ "/site/a.js": ["/site/y.js", "/site/x.js"] })
348
+ fs.readFile.mockImplementation(async (filePath) => `body:${filePath}`)
349
+
350
+ const first = await createPageHasher(forward)({ filePath: "/site/a.js" })
351
+ const second = await createPageHasher(reverse)({ filePath: "/site/a.js" })
352
+
353
+ expect(first).toBe(second)
354
+ })
355
+ })
356
+
162
357
  describe("createManifest", () => {
163
358
  it("should create a new manifest with page hashes", async () => {
164
359
  const renderedPages = [
165
360
  { path: "/", filePath: "index.js" },
166
361
  { path: "/about", filePath: "about.js" },
167
362
  ]
168
- const entitiesHash = "entities-hash"
363
+ const sharedHash = "shared-hash"
169
364
  const runtimeHash = "runtime-hash"
170
365
 
171
366
  fs.readFile.mockImplementation(async (path) => {
@@ -176,21 +371,34 @@ describe("manifest", () => {
176
371
 
177
372
  const manifest = await createManifest(
178
373
  renderedPages,
179
- entitiesHash,
374
+ sharedHash,
180
375
  runtimeHash,
181
376
  )
182
377
 
183
- expect(manifest.entities).toBe(entitiesHash)
378
+ expect(manifest.shared).toBe(sharedHash)
184
379
  expect(manifest.runtime).toBe(runtimeHash)
185
380
  expect(manifest.buildTime).toBeDefined()
186
- expect(manifest.pages["/"]).toEqual({
187
- hash: "176b689259e8d68ef0aa869fd3b3be45",
188
- filePath: "index.js",
189
- })
190
- expect(manifest.pages["/about"]).toEqual({
191
- hash: "f43ab6cf4975e90e757c05cc3c619a85",
192
- filePath: "about.js",
193
- })
381
+ expect(manifest.pages["/"].filePath).toBe("index.js")
382
+ expect(manifest.pages["/about"].filePath).toBe("about.js")
383
+ })
384
+
385
+ it("should record the dependency-aware hash produced by the page hasher", async () => {
386
+ const vite = fakeVite({ "index.js": ["nav.js"] })
387
+ fs.readFile.mockImplementation(async (filePath) => `body:${filePath}`)
388
+
389
+ const getPageHash = createPageHasher(vite)
390
+ const manifest = await createManifest(
391
+ [{ path: "/", filePath: "index.js" }],
392
+ "shared",
393
+ "rt",
394
+ getPageHash,
395
+ )
396
+
397
+ expect(manifest.pages["/"].hash).toBe(
398
+ await getPageHash({
399
+ filePath: "index.js",
400
+ }),
401
+ )
194
402
  })
195
403
  })
196
404
  })
@@ -5,7 +5,28 @@ import { afterEach, describe, expect, it, vi } from "vitest"
5
5
 
6
6
  import { copyPublicDir } from "./public"
7
7
 
8
- vi.mock("node:fs/promises")
8
+ const mockAccess = vi.hoisted(() => vi.fn())
9
+ const mockReaddir = vi.hoisted(() => vi.fn())
10
+ const mockMkdir = vi.hoisted(() => vi.fn())
11
+ const mockCopyFile = vi.hoisted(() => vi.fn())
12
+
13
+ vi.mock("node:fs/promises", async (importOriginal) => {
14
+ const actual = await importOriginal()
15
+ return {
16
+ ...actual,
17
+ access: mockAccess,
18
+ readdir: mockReaddir,
19
+ mkdir: mockMkdir,
20
+ copyFile: mockCopyFile,
21
+ default: {
22
+ ...actual.default,
23
+ access: mockAccess,
24
+ readdir: mockReaddir,
25
+ mkdir: mockMkdir,
26
+ copyFile: mockCopyFile,
27
+ },
28
+ }
29
+ })
9
30
 
10
31
  describe("copyPublicDir", () => {
11
32
  const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {})
@@ -4,7 +4,19 @@ import { afterEach, describe, expect, it, vi } from "vitest"
4
4
 
5
5
  import { generateRSS } from "./rss"
6
6
 
7
- vi.mock("node:fs/promises")
7
+ const mockWriteFile = vi.hoisted(() => vi.fn())
8
+
9
+ vi.mock("node:fs/promises", async (importOriginal) => {
10
+ const actual = await importOriginal()
11
+ return {
12
+ ...actual,
13
+ writeFile: mockWriteFile,
14
+ default: {
15
+ ...actual.default,
16
+ writeFile: mockWriteFile,
17
+ },
18
+ }
19
+ })
8
20
 
9
21
  describe("generateRSS", () => {
10
22
  const consoleSpy = vi.spyOn(console, "warn").mockImplementation(() => {})
@@ -4,7 +4,19 @@ import { afterEach, describe, expect, it, vi } from "vitest"
4
4
 
5
5
  import { generateSitemap } from "./sitemap"
6
6
 
7
- vi.mock("node:fs/promises")
7
+ const mockWriteFile = vi.hoisted(() => vi.fn())
8
+
9
+ vi.mock("node:fs/promises", async (importOriginal) => {
10
+ const actual = await importOriginal()
11
+ return {
12
+ ...actual,
13
+ writeFile: mockWriteFile,
14
+ default: {
15
+ ...actual.default,
16
+ writeFile: mockWriteFile,
17
+ },
18
+ }
19
+ })
8
20
 
9
21
  describe("generateSitemap", () => {
10
22
  const consoleSpy = vi.spyOn(console, "warn").mockImplementation(() => {})
@@ -1,16 +1,32 @@
1
1
  import { existsSync } from "node:fs"
2
2
  import path from "node:path"
3
3
 
4
- import { describe, expect, it, vi } from "vitest"
4
+ import { beforeEach, describe, expect, it, vi } from "vitest"
5
5
 
6
6
  import { generateStore } from "."
7
7
 
8
+ const mockExistsSync = vi.hoisted(() => vi.fn(() => false))
9
+
10
+ vi.mock("node:fs", async (importOriginal) => {
11
+ const actual = await importOriginal()
12
+ return {
13
+ ...actual,
14
+ existsSync: mockExistsSync,
15
+ default: {
16
+ ...actual.default,
17
+ existsSync: mockExistsSync,
18
+ },
19
+ }
20
+ })
21
+
8
22
  const ROOT_DIR = path.join(import.meta.dirname, "..", "__fixtures__")
9
23
  const PAGES_DIR = path.join(ROOT_DIR, "src", "pages")
10
24
 
11
- vi.mock("node:fs")
12
-
13
25
  describe("generateStore", () => {
26
+ beforeEach(() => {
27
+ mockExistsSync.mockReturnValue(false)
28
+ })
29
+
14
30
  it("should generate the proper types and entities from a static page", async () => {
15
31
  const page = {
16
32
  filePath: path.join(PAGES_DIR, "index.js"),