@inglorious/ssx 2.1.20 → 2.3.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 +97 -27
- package/package.json +8 -7
- package/src/build/pages.js +3 -0
- package/src/build/pages.test.js +18 -3
- package/src/client.js +4 -0
- package/src/dev/api.js +7 -1
- package/src/dev/index.js +2 -1
- package/src/render/html.test.js +6 -3
- package/src/render/index.js +13 -3
- package/src/render/layout.js +3 -1
- package/src/render/layout.test.js +7 -2
- package/src/render/render.test.js +109 -0
- package/src/router/index.js +43 -1
- package/src/router/router.test.js +40 -1
- package/src/scripts/app.js +51 -13
- package/src/scripts/app.test.js +55 -11
- package/src/ssr/index.js +31 -8
- package/src/ssr/render-request.test.js +85 -0
- package/src/utils/i18n.js +84 -0
- package/src/utils/i18n.test.js +121 -0
- package/src/utils/page-head.js +127 -0
- package/src/utils/page-head.test.js +202 -0
- package/types/client.d.ts +22 -0
- package/types/i18n.d.ts +0 -6
package/src/router/index.js
CHANGED
|
@@ -31,7 +31,19 @@ export async function getPages(pagesDir = "pages", options, loader) {
|
|
|
31
31
|
const module = await load(route.filePath)
|
|
32
32
|
const moduleName = getModuleName(module)
|
|
33
33
|
|
|
34
|
-
if (isDynamic(route.pattern)) {
|
|
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
|
+
addPages(pages, options, {
|
|
38
|
+
pattern: route.pattern,
|
|
39
|
+
path: route.pattern,
|
|
40
|
+
params: {},
|
|
41
|
+
isDynamic: true,
|
|
42
|
+
moduleName,
|
|
43
|
+
modulePath: route.modulePath,
|
|
44
|
+
filePath: route.filePath,
|
|
45
|
+
})
|
|
46
|
+
} else if (isDynamic(route.pattern)) {
|
|
35
47
|
let { staticPaths = [] } = module
|
|
36
48
|
if (typeof staticPaths === "function") {
|
|
37
49
|
staticPaths = await staticPaths()
|
|
@@ -144,6 +156,36 @@ export function matchRoute(pattern, url) {
|
|
|
144
156
|
})
|
|
145
157
|
}
|
|
146
158
|
|
|
159
|
+
/**
|
|
160
|
+
* The params a URL gives a route pattern, such as `{ id: "42" }` for
|
|
161
|
+
* `/posts/:id` and `/posts/42`, or null when it does not match. A catch-all
|
|
162
|
+
* `*` takes the rest of the URL as `path`.
|
|
163
|
+
*
|
|
164
|
+
* @param {string} pattern - The route pattern (e.g. "/posts/:id").
|
|
165
|
+
* @param {string} url - The actual URL (e.g. "/posts/42").
|
|
166
|
+
* @returns {Object|null} The params, or null.
|
|
167
|
+
*/
|
|
168
|
+
export function matchParams(pattern, url) {
|
|
169
|
+
const patternParts = pattern.split("/").filter(Boolean)
|
|
170
|
+
const urlParts = url.split("/").filter(Boolean)
|
|
171
|
+
const params = {}
|
|
172
|
+
|
|
173
|
+
for (const [index, part] of patternParts.entries()) {
|
|
174
|
+
if (part === "*") {
|
|
175
|
+
params.path = urlParts.slice(index).map(decodeURIComponent).join("/")
|
|
176
|
+
return params
|
|
177
|
+
}
|
|
178
|
+
if (index >= urlParts.length) return null
|
|
179
|
+
if (part.startsWith(":")) {
|
|
180
|
+
params[part.slice(1)] = decodeURIComponent(urlParts[index])
|
|
181
|
+
} else if (part !== urlParts[index]) {
|
|
182
|
+
return null
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
return patternParts.length === urlParts.length ? params : null
|
|
187
|
+
}
|
|
188
|
+
|
|
147
189
|
/**
|
|
148
190
|
* Converts a file path to a route pattern.
|
|
149
191
|
* Examples:
|
|
@@ -2,7 +2,7 @@ import path from "node:path"
|
|
|
2
2
|
|
|
3
3
|
import { afterEach, describe, expect, it, vi } from "vitest"
|
|
4
4
|
|
|
5
|
-
import { getPages, getRoutes, matchRoute } from "./index.js"
|
|
5
|
+
import { getPages, getRoutes, matchParams, matchRoute } from "./index.js"
|
|
6
6
|
|
|
7
7
|
const ROOT_DIR = path.join(import.meta.dirname, "..", "fixtures")
|
|
8
8
|
const PAGES_DIR = path.join(ROOT_DIR, "src", "pages")
|
|
@@ -127,4 +127,43 @@ describe("router", () => {
|
|
|
127
127
|
expect(matchRoute("/about", "/about/")).toBe(true)
|
|
128
128
|
})
|
|
129
129
|
})
|
|
130
|
+
|
|
131
|
+
describe("matchParams", () => {
|
|
132
|
+
it("reads a dynamic segment's value from the URL", () => {
|
|
133
|
+
expect(matchParams("/posts/:id", "/posts/42")).toEqual({ id: "42" })
|
|
134
|
+
expect(matchParams("/posts/:id", "/posts/caf%C3%A9")).toEqual({
|
|
135
|
+
id: "café",
|
|
136
|
+
})
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
it("takes the rest of the URL for a catch-all", () => {
|
|
140
|
+
expect(matchParams("/docs/*", "/docs/guide/intro")).toEqual({
|
|
141
|
+
path: "guide/intro",
|
|
142
|
+
})
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
it("is null when the URL does not match", () => {
|
|
146
|
+
expect(matchParams("/posts/:id", "/posts")).toBeNull()
|
|
147
|
+
expect(matchParams("/posts/:id", "/blog/42")).toBeNull()
|
|
148
|
+
expect(matchParams("/posts/:id", "/posts/42/edit")).toBeNull()
|
|
149
|
+
})
|
|
150
|
+
})
|
|
151
|
+
|
|
152
|
+
describe("server-rendered dynamic pages", () => {
|
|
153
|
+
it("are registered by their pattern, with no staticPaths", async () => {
|
|
154
|
+
const warn = vi.spyOn(console, "warn").mockImplementation(() => {})
|
|
155
|
+
const loader = async (filePath) =>
|
|
156
|
+
filePath.endsWith("_slug.js")
|
|
157
|
+
? { ssr: true, Post: { render: () => "" } }
|
|
158
|
+
: import(filePath)
|
|
159
|
+
|
|
160
|
+
const pages = await getPages(PAGES_DIR, {}, loader)
|
|
161
|
+
const post = pages.find((page) => page.pattern === "/posts/:slug")
|
|
162
|
+
|
|
163
|
+
expect(post).toMatchObject({ path: "/posts/:slug", isDynamic: true })
|
|
164
|
+
expect(warn).not.toHaveBeenCalledWith(
|
|
165
|
+
expect.stringContaining("posts/_slug.js"),
|
|
166
|
+
)
|
|
167
|
+
})
|
|
168
|
+
})
|
|
130
169
|
})
|
package/src/scripts/app.js
CHANGED
|
@@ -8,6 +8,9 @@ import { getStoreStuff } from "../store/stuff.js"
|
|
|
8
8
|
* @param {Object} [options] - Runtime options.
|
|
9
9
|
* @param {boolean} [options.hasTypesFile] - Whether src/store/types.js exists.
|
|
10
10
|
* @param {boolean} [options.hasEntitiesFile] - Whether src/store/entities.js exists.
|
|
11
|
+
* @param {string} [options.title] - The site title, used when a page sets none.
|
|
12
|
+
* @param {string} [options.lang] - The site language, used when a page sets none.
|
|
13
|
+
* @param {Object} [options.meta] - Meta tags shared by every page.
|
|
11
14
|
* @returns {string} The generated JavaScript code for the client entry point.
|
|
12
15
|
*/
|
|
13
16
|
export async function generateApp(pages, options = {}, loader) {
|
|
@@ -26,7 +29,7 @@ export async function generateApp(pages, options = {}, loader) {
|
|
|
26
29
|
if (routesByPattern.has(routePattern)) continue
|
|
27
30
|
routesByPattern.set(
|
|
28
31
|
routePattern,
|
|
29
|
-
` "${routePattern}": () => import("@/pages/${page.modulePath}")`,
|
|
32
|
+
` "${routePattern}": loadPage(${JSON.stringify(page.moduleName)}, () => import("@/pages/${page.modulePath}"))`,
|
|
30
33
|
)
|
|
31
34
|
}
|
|
32
35
|
const routes = [...routesByPattern.values()]
|
|
@@ -52,7 +55,7 @@ import { createStore } from "@inglorious/store"
|
|
|
52
55
|
import { createDevtools } from "@inglorious/store/client/devtools"
|
|
53
56
|
import { mount } from "@inglorious/web"
|
|
54
57
|
import { Router, getRoute, setRoutes } from "@inglorious/web/router"
|
|
55
|
-
import { getLocaleFromPath } from "@inglorious/ssx/
|
|
58
|
+
import { getLocaleFromPath, syncPageHead, waitForLocale } from "@inglorious/ssx/client"
|
|
56
59
|
|
|
57
60
|
${typesImport}
|
|
58
61
|
${entitiesImport}
|
|
@@ -76,8 +79,24 @@ const pages = ${JSON.stringify(
|
|
|
76
79
|
null,
|
|
77
80
|
2,
|
|
78
81
|
)}
|
|
82
|
+
// A server-rendered dynamic page is listed by its pattern, such as /posts/:id.
|
|
83
|
+
const matchesPattern = (pattern, path) => {
|
|
84
|
+
const patternParts = pattern.split("/").filter(Boolean)
|
|
85
|
+
const pathParts = path.split("/").filter(Boolean)
|
|
86
|
+
if (patternParts.includes("*")) {
|
|
87
|
+
const fixed = patternParts.slice(0, patternParts.indexOf("*"))
|
|
88
|
+
return fixed.every((part, i) => part.startsWith(":") || part === pathParts[i])
|
|
89
|
+
}
|
|
90
|
+
return (
|
|
91
|
+
patternParts.length === pathParts.length &&
|
|
92
|
+
patternParts.every((part, i) => part.startsWith(":") || part === pathParts[i])
|
|
93
|
+
)
|
|
94
|
+
}
|
|
95
|
+
|
|
79
96
|
const path = normalizeRoutePath(window.location.pathname)
|
|
80
|
-
const page =
|
|
97
|
+
const page =
|
|
98
|
+
pages.find((page) => normalizeRoutePath(page.path) === path) ??
|
|
99
|
+
pages.find((page) => matchesPattern(page.path, path))
|
|
81
100
|
|
|
82
101
|
const types = { Router }
|
|
83
102
|
${typesAssignment}
|
|
@@ -92,7 +111,6 @@ const toCamelCase = (str) => {
|
|
|
92
111
|
|
|
93
112
|
const entities = {
|
|
94
113
|
router: { type: "Router", path, route: toCamelCase(page?.moduleName) },
|
|
95
|
-
i18n: { type: "I18n", ...i18n },
|
|
96
114
|
}
|
|
97
115
|
${entitiesAssignment}
|
|
98
116
|
Object.assign(entities, JSON.parse(document.getElementById("__SSX_PAGE__").textContent))
|
|
@@ -106,18 +124,31 @@ if (isDev) {
|
|
|
106
124
|
const systems = []
|
|
107
125
|
if (i18n.defaultLocale && i18n.locales?.length) {
|
|
108
126
|
systems.push({
|
|
109
|
-
routeChange(state, payload) {
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
const entity = state[
|
|
114
|
-
if (
|
|
115
|
-
|
|
116
|
-
|
|
127
|
+
routeChange(state, payload, api) {
|
|
128
|
+
if (!payload?.path) return
|
|
129
|
+
const locale = getLocaleFromPath(payload.path, i18n)
|
|
130
|
+
|
|
131
|
+
const entity = state[payload.route]
|
|
132
|
+
if (entity) entity.locale = locale
|
|
133
|
+
|
|
134
|
+
// The URL decides the locale, as it did for the page the server rendered, so
|
|
135
|
+
// an @inglorious/i18n entity follows it rather than the browser's language.
|
|
136
|
+
const translator = state.i18n
|
|
137
|
+
if (translator?.locale !== locale && api.getType(translator?.type)?.localeChange) {
|
|
138
|
+
api.notify("#i18n:localeChange", locale)
|
|
139
|
+
}
|
|
117
140
|
},
|
|
118
141
|
})
|
|
119
142
|
}
|
|
120
143
|
|
|
144
|
+
// Page modules by type name, kept so client navigation can read their metadata.
|
|
145
|
+
const modules = {}
|
|
146
|
+
const loadPage = (moduleName, load) => async () => {
|
|
147
|
+
const module = await load()
|
|
148
|
+
modules[moduleName] = module
|
|
149
|
+
return module
|
|
150
|
+
}
|
|
151
|
+
|
|
121
152
|
setRoutes({
|
|
122
153
|
${routes.join(",\n")}
|
|
123
154
|
})
|
|
@@ -130,10 +161,17 @@ const store = createStore({ types, entities, middlewares, systems, autoCreateEnt
|
|
|
130
161
|
|
|
131
162
|
const root = document.getElementById("root")
|
|
132
163
|
|
|
164
|
+
if (i18n.defaultLocale && i18n.locales?.length) {
|
|
165
|
+
// Hydrates in the language the server rendered, with its translations loaded.
|
|
166
|
+
await waitForLocale(store, getLocaleFromPath(path, i18n))
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const getPageName = syncPageHead(store, modules, ${JSON.stringify({ title: options.title, lang: options.lang, meta: options.meta })})
|
|
170
|
+
|
|
133
171
|
mount(store, (api) => {
|
|
134
172
|
const { route } = api.getEntity("router")
|
|
135
173
|
return api.render(route)
|
|
136
|
-
}, root)
|
|
174
|
+
}, root, { getPageName })
|
|
137
175
|
`
|
|
138
176
|
}
|
|
139
177
|
|
package/src/scripts/app.test.js
CHANGED
|
@@ -13,10 +13,11 @@ describe("generateApp", () => {
|
|
|
13
13
|
pattern: "/",
|
|
14
14
|
path: "/",
|
|
15
15
|
modulePath: "index.js",
|
|
16
|
+
moduleName: "Index",
|
|
16
17
|
filePath: PAGES_DIR,
|
|
17
18
|
}
|
|
18
19
|
|
|
19
|
-
const app = generateApp([page])
|
|
20
|
+
const app = await generateApp([page])
|
|
20
21
|
|
|
21
22
|
expect(app).toMatchSnapshot()
|
|
22
23
|
})
|
|
@@ -26,10 +27,11 @@ describe("generateApp", () => {
|
|
|
26
27
|
pattern: "/about",
|
|
27
28
|
path: "/about",
|
|
28
29
|
modulePath: "about.js",
|
|
30
|
+
moduleName: "About",
|
|
29
31
|
filePath: path.join(PAGES_DIR, "about.js"),
|
|
30
32
|
}
|
|
31
33
|
|
|
32
|
-
const app = generateApp([page])
|
|
34
|
+
const app = await generateApp([page])
|
|
33
35
|
|
|
34
36
|
expect(app).toMatchSnapshot()
|
|
35
37
|
})
|
|
@@ -39,10 +41,11 @@ describe("generateApp", () => {
|
|
|
39
41
|
pattern: "/blog",
|
|
40
42
|
path: "/blog",
|
|
41
43
|
modulePath: "blog.js",
|
|
44
|
+
moduleName: "Blog",
|
|
42
45
|
filePath: path.join(PAGES_DIR, "blog.js"),
|
|
43
46
|
}
|
|
44
47
|
|
|
45
|
-
const app = generateApp([page])
|
|
48
|
+
const app = await generateApp([page])
|
|
46
49
|
|
|
47
50
|
expect(app).toMatchSnapshot()
|
|
48
51
|
})
|
|
@@ -52,10 +55,11 @@ describe("generateApp", () => {
|
|
|
52
55
|
pattern: "/posts/:slug",
|
|
53
56
|
path: "/posts/my-first-post",
|
|
54
57
|
modulePath: "post.js",
|
|
58
|
+
moduleName: "Post",
|
|
55
59
|
filePath: path.join(PAGES_DIR, "posts", "_slug.js"),
|
|
56
60
|
}
|
|
57
61
|
|
|
58
|
-
const app = generateApp([page])
|
|
62
|
+
const app = await generateApp([page])
|
|
59
63
|
|
|
60
64
|
expect(app).toMatchSnapshot()
|
|
61
65
|
})
|
|
@@ -77,23 +81,63 @@ describe("generateApp", () => {
|
|
|
77
81
|
|
|
78
82
|
const app = await generateApp(localizedPages)
|
|
79
83
|
|
|
80
|
-
expect(app).toContain(
|
|
81
|
-
|
|
82
|
-
|
|
84
|
+
expect(app).toContain(
|
|
85
|
+
`"/hello": loadPage("hello", () => import("@/pages/hello.js"))`,
|
|
86
|
+
)
|
|
87
|
+
expect(app).toContain(
|
|
88
|
+
`"/it/hello": loadPage("hello", () => import("@/pages/hello.js"))`,
|
|
89
|
+
)
|
|
90
|
+
expect(app).toContain(
|
|
91
|
+
`"/pt/hello": loadPage("hello", () => import("@/pages/hello.js"))`,
|
|
92
|
+
)
|
|
83
93
|
expect(app).toContain(`const isDev = false`)
|
|
84
94
|
expect(app).toContain(
|
|
85
|
-
`import { getLocaleFromPath } from "@inglorious/ssx/
|
|
95
|
+
`import { getLocaleFromPath, syncPageHead, waitForLocale } from "@inglorious/ssx/client"`,
|
|
96
|
+
)
|
|
97
|
+
expect(app).toContain(
|
|
98
|
+
`await waitForLocale(store, getLocaleFromPath(path, i18n))`,
|
|
86
99
|
)
|
|
87
100
|
expect(app).toContain(`const systems = []`)
|
|
88
|
-
expect(app).toContain(`routeChange(state, payload)`)
|
|
101
|
+
expect(app).toContain(`routeChange(state, payload, api)`)
|
|
89
102
|
expect(app).toContain(
|
|
90
|
-
`
|
|
103
|
+
`const locale = getLocaleFromPath(payload.path, i18n)`,
|
|
91
104
|
)
|
|
105
|
+
expect(app).toContain(`if (entity) entity.locale = locale`)
|
|
106
|
+
expect(app).toContain(`api.notify("#i18n:localeChange", locale)`)
|
|
107
|
+
expect(app).not.toContain(`type: "I18n"`)
|
|
92
108
|
expect(app).toContain(
|
|
93
109
|
`const path = normalizeRoutePath(window.location.pathname)`,
|
|
94
110
|
)
|
|
111
|
+
// Its own path first, then a server-rendered page's pattern.
|
|
112
|
+
expect(app).toContain(
|
|
113
|
+
`pages.find((page) => normalizeRoutePath(page.path) === path) ??`,
|
|
114
|
+
)
|
|
115
|
+
expect(app).toContain(
|
|
116
|
+
`pages.find((page) => matchesPattern(page.path, path))`,
|
|
117
|
+
)
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
it("should sync the page head with the site defaults as fallback", async () => {
|
|
121
|
+
const page = {
|
|
122
|
+
pattern: "/about",
|
|
123
|
+
path: "/about",
|
|
124
|
+
modulePath: "about.js",
|
|
125
|
+
filePath: path.join(PAGES_DIR, "about.js"),
|
|
126
|
+
moduleName: "About",
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const app = await generateApp([page], {
|
|
130
|
+
title: "My Site",
|
|
131
|
+
lang: "en",
|
|
132
|
+
meta: { description: "A site" },
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
expect(app).toContain(
|
|
136
|
+
`"/about": loadPage("About", () => import("@/pages/about.js"))`,
|
|
137
|
+
)
|
|
95
138
|
expect(app).toContain(
|
|
96
|
-
`const
|
|
139
|
+
`const getPageName = syncPageHead(store, modules, {"title":"My Site","lang":"en","meta":{"description":"A site"}})`,
|
|
97
140
|
)
|
|
141
|
+
expect(app).toContain(`}, root, { getPageName })`)
|
|
98
142
|
})
|
|
99
143
|
})
|
package/src/ssr/index.js
CHANGED
|
@@ -3,13 +3,14 @@ import path from "node:path"
|
|
|
3
3
|
import connect from "connect"
|
|
4
4
|
import { createServer } from "vite"
|
|
5
5
|
|
|
6
|
-
import { createApiMiddleware } from "../dev/api.js"
|
|
6
|
+
import { createApiMiddleware, createRequest } from "../dev/api.js"
|
|
7
7
|
import { createViteConfig, virtualFiles } from "../dev/vite-config.js"
|
|
8
8
|
import { renderPage } from "../render/index.js"
|
|
9
|
-
import { getPages, matchRoute } from "../router/index.js"
|
|
9
|
+
import { getPages, matchParams, matchRoute } from "../router/index.js"
|
|
10
10
|
import { generateApp } from "../scripts/app.js"
|
|
11
11
|
import { generateStore } from "../store/index.js"
|
|
12
12
|
import { loadConfig } from "../utils/config.js"
|
|
13
|
+
import { waitForLocale } from "../utils/i18n.js"
|
|
13
14
|
|
|
14
15
|
export async function ssr(options = {}) {
|
|
15
16
|
const config = await loadConfig(options)
|
|
@@ -53,6 +54,7 @@ export async function ssr(options = {}) {
|
|
|
53
54
|
loader,
|
|
54
55
|
viteServer,
|
|
55
56
|
pages,
|
|
57
|
+
request: createRequest(req),
|
|
56
58
|
})
|
|
57
59
|
|
|
58
60
|
if (!result) {
|
|
@@ -81,9 +83,18 @@ export async function ssr(options = {}) {
|
|
|
81
83
|
}
|
|
82
84
|
}
|
|
83
85
|
|
|
86
|
+
/**
|
|
87
|
+
* Renders the page a URL asks for, with a store of its own: its `load` gets
|
|
88
|
+
* the entity and the page, with the URL's `params` and the `request`.
|
|
89
|
+
*
|
|
90
|
+
* @param {string} url - The URL requested.
|
|
91
|
+
* @param {Object} [context]
|
|
92
|
+
* @param {Request} [context.request] - The request, for `load` to read headers and cookies from.
|
|
93
|
+
* @returns {Promise<{html: string, page: Object, entity: Object, store: Object}|null>} Null when no page matches.
|
|
94
|
+
*/
|
|
84
95
|
export async function renderRequest(
|
|
85
96
|
url,
|
|
86
|
-
{ rootDir = ".", options = {}, loader, viteServer, pages } = {},
|
|
97
|
+
{ rootDir = ".", options = {}, loader, viteServer, pages, request } = {},
|
|
87
98
|
) {
|
|
88
99
|
const [pathname] = String(url || "").split("?")
|
|
89
100
|
|
|
@@ -103,22 +114,34 @@ export async function renderRequest(
|
|
|
103
114
|
await registerApp(resolvedPages, options, loader, viteServer)
|
|
104
115
|
}
|
|
105
116
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
117
|
+
// A page of its own path first, then one whose pattern matches the URL.
|
|
118
|
+
const origPage =
|
|
119
|
+
resolvedPages.find(
|
|
120
|
+
(candidate) =>
|
|
121
|
+
!candidate.isDynamic && matchRoute(candidate.path, pathname),
|
|
122
|
+
) ??
|
|
123
|
+
resolvedPages.find(
|
|
124
|
+
(candidate) =>
|
|
125
|
+
candidate.isDynamic && matchParams(candidate.path, pathname),
|
|
126
|
+
)
|
|
109
127
|
if (!origPage) {
|
|
110
128
|
return null
|
|
111
129
|
}
|
|
112
130
|
|
|
113
131
|
const module = await loader(origPage.filePath)
|
|
114
|
-
const page = { ...origPage }
|
|
115
|
-
|
|
132
|
+
const page = { ...origPage, module, request }
|
|
133
|
+
if (origPage.isDynamic) {
|
|
134
|
+
page.path = pathname
|
|
135
|
+
page.params = matchParams(origPage.path, pathname)
|
|
136
|
+
}
|
|
116
137
|
|
|
117
138
|
const store = await generateStore(resolvedPages, options, loader)
|
|
118
139
|
const [entity] = store._api.getEntities(page.moduleName)
|
|
119
140
|
if (page.locale) {
|
|
120
141
|
entity.locale = page.locale
|
|
121
142
|
}
|
|
143
|
+
// Translations in the page's locale, for `load` and the render.
|
|
144
|
+
await waitForLocale(store, page.locale)
|
|
122
145
|
|
|
123
146
|
if (module.load) {
|
|
124
147
|
await module.load(entity, page)
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// @vitest-environment node
|
|
2
|
+
// The server runs on Node, whose Request keeps cookies; a browser-like one
|
|
3
|
+
// drops them.
|
|
4
|
+
import { describe, expect, it, vi } from "vitest"
|
|
5
|
+
|
|
6
|
+
const { generateStore, renderPage } = vi.hoisted(() => ({
|
|
7
|
+
generateStore: vi.fn(),
|
|
8
|
+
renderPage: vi.fn(async () => "<html></html>"),
|
|
9
|
+
}))
|
|
10
|
+
|
|
11
|
+
vi.mock("../store/index.js", () => ({ generateStore }))
|
|
12
|
+
vi.mock("../render/index.js", () => ({ renderPage }))
|
|
13
|
+
vi.mock("../scripts/app.js", () => ({ generateApp: vi.fn(async () => "") }))
|
|
14
|
+
vi.mock("../dev/vite-config.js", () => ({ virtualFiles: new Map() }))
|
|
15
|
+
|
|
16
|
+
import { renderRequest } from "./index.js"
|
|
17
|
+
|
|
18
|
+
const pages = [
|
|
19
|
+
{
|
|
20
|
+
path: "/posts/new",
|
|
21
|
+
pattern: "/posts/new",
|
|
22
|
+
filePath: "new.js",
|
|
23
|
+
moduleName: "newPost",
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
path: "/posts/:id",
|
|
27
|
+
pattern: "/posts/:id",
|
|
28
|
+
isDynamic: true,
|
|
29
|
+
filePath: "post.js",
|
|
30
|
+
moduleName: "post",
|
|
31
|
+
},
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
async function render(url, request) {
|
|
35
|
+
const load = vi.fn()
|
|
36
|
+
const entity = {}
|
|
37
|
+
generateStore.mockResolvedValue({
|
|
38
|
+
_api: { getEntities: () => [entity] },
|
|
39
|
+
})
|
|
40
|
+
const result = await renderRequest(url, {
|
|
41
|
+
pages,
|
|
42
|
+
request,
|
|
43
|
+
loader: async () => ({ ssr: true, load }),
|
|
44
|
+
})
|
|
45
|
+
return { result, load, entity }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
describe("renderRequest for server-rendered pages", () => {
|
|
49
|
+
it("renders a dynamic page for any path its pattern matches, its params from the URL", async () => {
|
|
50
|
+
const { result, load } = await render("/posts/42?ref=home")
|
|
51
|
+
|
|
52
|
+
expect(result.page).toMatchObject({
|
|
53
|
+
moduleName: "post",
|
|
54
|
+
path: "/posts/42",
|
|
55
|
+
params: { id: "42" },
|
|
56
|
+
})
|
|
57
|
+
expect(load).toHaveBeenCalledWith(
|
|
58
|
+
expect.anything(),
|
|
59
|
+
expect.objectContaining({ params: { id: "42" } }),
|
|
60
|
+
)
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
it("prefers a page of its own path to a pattern", async () => {
|
|
64
|
+
const { result } = await render("/posts/new")
|
|
65
|
+
|
|
66
|
+
expect(result.page.moduleName).toBe("newPost")
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
it("gives load the request, for its headers and cookies", async () => {
|
|
70
|
+
const request = new Request("http://localhost/posts/7", {
|
|
71
|
+
headers: { cookie: "session=abc" },
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
const { load } = await render("/posts/7", request)
|
|
75
|
+
|
|
76
|
+
const [, page] = load.mock.calls[0]
|
|
77
|
+
expect(page.request.headers.get("cookie")).toBe("session=abc")
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
it("matches nothing for a path no page has", async () => {
|
|
81
|
+
const { result } = await render("/about")
|
|
82
|
+
|
|
83
|
+
expect(result).toBeNull()
|
|
84
|
+
})
|
|
85
|
+
})
|
package/src/utils/i18n.js
CHANGED
|
@@ -9,3 +9,87 @@ export function getLocaleFromPath(
|
|
|
9
9
|
if (first && locales.includes(first)) return first
|
|
10
10
|
return defaultLocale
|
|
11
11
|
}
|
|
12
|
+
|
|
13
|
+
// Scripts written right to left, by their ISO 15924 code.
|
|
14
|
+
const RTL_SCRIPTS = new Set([
|
|
15
|
+
"Adlm",
|
|
16
|
+
"Arab",
|
|
17
|
+
"Hebr",
|
|
18
|
+
"Mand",
|
|
19
|
+
"Nkoo",
|
|
20
|
+
"Rohg",
|
|
21
|
+
"Samr",
|
|
22
|
+
"Syrc",
|
|
23
|
+
"Thaa",
|
|
24
|
+
"Yezi",
|
|
25
|
+
])
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The direction a language is written in, for the `dir` of `<html>`. The script comes
|
|
29
|
+
* from the locale itself (`az-Arab`) or, when it names none, the likeliest one (`ar` is
|
|
30
|
+
* written in Arabic script).
|
|
31
|
+
*
|
|
32
|
+
* @param {string} [locale] - A BCP 47 language tag, such as `ar` or `en-US`.
|
|
33
|
+
* @returns {"ltr" | "rtl"} The text direction.
|
|
34
|
+
*/
|
|
35
|
+
export function getTextDirection(locale) {
|
|
36
|
+
if (!locale) return "ltr"
|
|
37
|
+
|
|
38
|
+
try {
|
|
39
|
+
const { script } = new Intl.Locale(locale).maximize()
|
|
40
|
+
return RTL_SCRIPTS.has(script) ? "rtl" : "ltr"
|
|
41
|
+
} catch {
|
|
42
|
+
// Not a valid language tag.
|
|
43
|
+
return "ltr"
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// The entity of an app that translates with @inglorious/i18n, by that package's convention.
|
|
48
|
+
const TRANSLATOR_ID = "i18n"
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Switches the app's @inglorious/i18n entity, if it has one, to `locale`. Immediate when
|
|
52
|
+
* the locale's catalogue is loaded, as `waitForLocale` makes sure of: call it right before
|
|
53
|
+
* rendering, so that every translation in the render is in that locale even when renders
|
|
54
|
+
* for other locales share the same i18next instance.
|
|
55
|
+
*
|
|
56
|
+
* @param {Object} store - The application store.
|
|
57
|
+
* @param {string} [locale] - The locale of the page.
|
|
58
|
+
*/
|
|
59
|
+
export function selectLocale(store, locale) {
|
|
60
|
+
if (!locale || !hasTranslator(store)) return
|
|
61
|
+
store.notify(`#${TRANSLATOR_ID}:localeChange`, locale)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Switches the app's @inglorious/i18n entity, if it has one, to `locale`, and resolves
|
|
66
|
+
* once its catalogue has loaded, or failed to. Without such an entity it resolves at once.
|
|
67
|
+
*
|
|
68
|
+
* @param {Object} store - The application store.
|
|
69
|
+
* @param {string} [locale] - The locale of the page.
|
|
70
|
+
* @returns {Promise<void>}
|
|
71
|
+
*/
|
|
72
|
+
export function waitForLocale(store, locale) {
|
|
73
|
+
if (!locale || !hasTranslator(store)) return Promise.resolve()
|
|
74
|
+
|
|
75
|
+
store.notify(`#${TRANSLATOR_ID}:localeChange`, locale)
|
|
76
|
+
|
|
77
|
+
return new Promise((resolve) => {
|
|
78
|
+
let unsubscribe = null
|
|
79
|
+
const isLoaded = () => !store._api.getEntity(TRANSLATOR_ID).loadingLocale
|
|
80
|
+
if (isLoaded()) return resolve()
|
|
81
|
+
|
|
82
|
+
unsubscribe = store.subscribe(() => {
|
|
83
|
+
if (!isLoaded()) return
|
|
84
|
+
unsubscribe()
|
|
85
|
+
resolve()
|
|
86
|
+
})
|
|
87
|
+
})
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function hasTranslator(store) {
|
|
91
|
+
const translator = store._api.getEntity(TRANSLATOR_ID)
|
|
92
|
+
return Boolean(
|
|
93
|
+
translator && store._api.getType(translator.type)?.localeChange,
|
|
94
|
+
)
|
|
95
|
+
}
|