@uniweb/core 0.35.0 → 0.35.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uniweb/core",
3
- "version": "0.35.0",
3
+ "version": "0.35.2",
4
4
  "description": "Core classes for the Uniweb platform - Uniweb, Website, Page, Block",
5
5
  "type": "module",
6
6
  "exports": {
@@ -18,6 +18,7 @@
18
18
  "./insets": "./src/insets.js",
19
19
  "./locale-config": "./src/locale-config.js",
20
20
  "./route-match": "./src/route-match.js",
21
+ "./resolve-route": "./src/resolve-route.js",
21
22
  "./section-id": "./src/section-id.js",
22
23
  "./services": "./src/services.js",
23
24
  "./sort": "./src/sort.js",
@@ -48,8 +49,8 @@
48
49
  "vitest": "^4.1.7"
49
50
  },
50
51
  "dependencies": {
51
- "@uniweb/theming": "^0.2.0",
52
- "@uniweb/semantic-parser": "^1.4.1"
52
+ "@uniweb/semantic-parser": "^1.5.1",
53
+ "@uniweb/theming": "^0.2.0"
53
54
  },
54
55
  "scripts": {
55
56
  "test": "vitest run"
package/src/index.js CHANGED
@@ -83,6 +83,16 @@ export {
83
83
  recordRouteBase,
84
84
  findPageForRoute,
85
85
  } from './route-match.js'
86
+ // What a URL names — a page, a redirect, a rewrite, or nothing — for every lane. Also the
87
+ // zero-React leaf `@uniweb/core/resolve-route`, which is how a host reaches it.
88
+ export {
89
+ resolveRoute,
90
+ routeIndex,
91
+ localeOfPath,
92
+ localeUrl,
93
+ landingRoute,
94
+ RESOLUTION_STATUS,
95
+ } from './resolve-route.js'
86
96
  export { isRichSchema } from './schemas.js'
87
97
  // ⛔ `Tracker` is NOT on the package entry. It is a FEATURE, not part of the
88
98
  // object graph this package exists to define, and putting it here made every
package/src/page.js CHANGED
@@ -8,6 +8,7 @@
8
8
  import Block from './block.js'
9
9
  import ObservableState from './observable-state.js'
10
10
  import { normalizeSeo } from './seo.js'
11
+ import { landingRoute } from './resolve-route.js'
11
12
 
12
13
  // Normalize a page's nav-visibility into a deduped hideIn array (the layout-area
13
14
  // names the page is suppressed from). Reads the canonical hideIn (array, or a single
@@ -588,18 +589,14 @@ export default class Page {
588
589
  * page.getNavigableRoute() // Returns '/docs/getting-started'
589
590
  */
590
591
  getNavigableRoute() {
591
- if (this.hasContent()) return this.route
592
- const children = this.children || []
593
- // Prefer the index child (designated landing page for this folder).
594
- // Return this folder's own route so the URL stays clean (/Articles, not /Articles/index).
595
- const indexChild = children.find((c) => c.isIndex)
596
- if (indexChild) return this.route
597
- // Fall back to first child with content
598
- for (const child of children) {
599
- const route = child.getNavigableRoute()
600
- if (route) return route
601
- }
602
- return this.route // Fallback to own route
592
+ // ⭐ ONE RULE with the resolver's (`landingRoute`, `./resolve-route.js`): itself when it has
593
+ // content or an `isIndex` child, else its first descendant with content, depth-first in page
594
+ // order. ⛔ Until 2026-09-30 an empty first child ended the walk, so a container sent visitors
595
+ // to a page with nothing on it while a later sibling had content. A page the site's index
596
+ // does not hold — a record's page, a layout area — lands on itself.
597
+ const index = this.website?._routeIndex
598
+ const data = index?.byRoute.get(this.route)
599
+ return (data && landingRoute(index, data)) || this.route
603
600
  }
604
601
 
605
602
  /**
@@ -0,0 +1,429 @@
1
+ /**
2
+ * ⭐ **WHAT A URL NAMES — one function for every lane that asks.**
3
+ *
4
+ * A page, a redirect, a page proxied from elsewhere, or nothing: the SPA asks it on every
5
+ * navigation, the static build asks it for every page it writes, a host rendering server-side
6
+ * asks it before it fetches anything, and a server that runs no JS reproduces it from test
7
+ * vectors generated from this code.
8
+ *
9
+ * ⛔ **Why it is a module rather than a method.** The rule used to live in `Website#getPage`
10
+ * (the page), `PageRenderer.jsx` and `prerender.js` (the redirect, twice), and every host kept
11
+ * a copy of its own around the renderer — a redirect target, a fallback matcher, a locale
12
+ * redirect — each reading the same payload by a slightly different rule. Two copies that
13
+ * disagree give two answers to one URL, and nothing fails: a container redirected to an empty
14
+ * page on one lane and to its content on another. It reads only a locale's site content, so
15
+ * every lane can call it and none needs a copy.
16
+ *
17
+ * What it does NOT decide: whether the record behind a parametric page exists. That is a data
18
+ * question, answered by the render's data step (`Website#_createDynamicPage`); the question a
19
+ * records service is asked for it is the other vector file (`record-miss`).
20
+ *
21
+ * @module @uniweb/core/resolve-route
22
+ */
23
+
24
+ import { decodeRouteValue, matchDynamicRoute, parentRouteOf } from './route-match.js'
25
+ import { resolveDefaultLocale } from './locale-config.js'
26
+
27
+ /** The not-found page's route. It is never a routable page of its own. */
28
+ export const NOT_FOUND_ROUTE = '/404'
29
+
30
+ /** The status a host that sends one sends for each answer. */
31
+ export const RESOLUTION_STATUS = Object.freeze({
32
+ page: 200,
33
+ notFound: 404,
34
+ // A page's redirect — authored, or a page with no content going to its content. Temporary:
35
+ // what a container lands on changes when its pages do.
36
+ pageRedirect: 302,
37
+ // The locale a host serves unprefixed, asked for with its prefix: the same page, for good.
38
+ localeRedirect: 301,
39
+ })
40
+
41
+ const hasContent = (page) => (page.hasContent ?? (Array.isArray(page.sections) && page.sections.length > 0)) === true
42
+ const isIndex = (page) => page.isIndex === true
43
+
44
+ /** An index page's own URL: `/articles/index` → `/articles`. */
45
+ function navRoute(page) {
46
+ if (isIndex(page) && page.route.endsWith('/index')) return page.route.slice(0, -'/index'.length) || '/'
47
+ return page.route
48
+ }
49
+
50
+ /**
51
+ * What `resolveRoute` reads of one locale's site content — build it once per payload and pass
52
+ * it instead of the content when resolving many paths.
53
+ *
54
+ * @param {Object} content - one locale's site content: `{ pages, config, notFound? }`
55
+ * @returns {Object} the index
56
+ */
57
+ export function routeIndex(content = {}) {
58
+ const all = Array.isArray(content?.pages) ? content.pages : []
59
+ const config = content?.config || {}
60
+ const pages = all.filter((p) => p && typeof p.route === 'string' && p.route !== NOT_FOUND_ROUTE)
61
+
62
+ // The one parent rule (`parentRouteOf`), over the same relation `Website#buildPageHierarchy`
63
+ // links: a page's children, in page order.
64
+ // A route's page: the FIRST page holding it, as a lookup in page order finds it.
65
+ const byRoute = new Map()
66
+ for (const page of pages) if (!byRoute.has(page.route)) byRoute.set(page.route, page)
67
+ const has = (route) => byRoute.has(route)
68
+ const childrenOf = new Map()
69
+ for (const page of pages) {
70
+ const parent = parentRouteOf(page.route, { declared: page.parent || null, has })
71
+ if (!parent || parent === page.route) continue
72
+ if (!childrenOf.has(parent)) childrenOf.set(parent, [])
73
+ childrenOf.get(parent).push(page)
74
+ }
75
+
76
+ const translations = {}
77
+ for (const [locale, routesOf] of Object.entries(config.i18n?.routeTranslations || {})) {
78
+ const forward = new Map()
79
+ const reverse = new Map()
80
+ for (const [canonical, translated] of Object.entries(routesOf || {})) {
81
+ forward.set(canonical, translated)
82
+ reverse.set(translated, canonical)
83
+ }
84
+ translations[locale] = { forward, reverse }
85
+ }
86
+
87
+ const siteDefaultLocale = resolveDefaultLocale(config)
88
+ const defaultLocale = config.domainLocale || siteDefaultLocale
89
+ return {
90
+ pages,
91
+ byRoute,
92
+ childrenOf,
93
+ notFound: content?.notFound || all.find((p) => p?.route === NOT_FOUND_ROUTE) || null,
94
+ translations,
95
+ siteDefaultLocale,
96
+ // The locale this host serves unprefixed: the host's own, else the site's default.
97
+ defaultLocale,
98
+ activeLocale: config.activeLocale || defaultLocale,
99
+ locales: servedLocales(config, siteDefaultLocale),
100
+ domainLocales: config.domainLocales || null,
101
+ }
102
+ }
103
+
104
+ function servedLocales(config, siteDefaultLocale) {
105
+ const codes = [siteDefaultLocale]
106
+ for (const entry of Array.isArray(config.languages) ? config.languages : []) {
107
+ const code = typeof entry === 'string' ? entry : entry?.code
108
+ if (typeof code === 'string' && code && !codes.includes(code)) codes.push(code)
109
+ }
110
+ return codes
111
+ }
112
+
113
+ const indexOf = (site) => (site && site.byRoute instanceof Map ? site : routeIndex(site))
114
+
115
+ /** A canonical route → the route this locale shows it at (`/blog` → `/noticias`, by prefix too). */
116
+ export function translateRoute(site, canonicalRoute, locale) {
117
+ const index = indexOf(site)
118
+ if (!locale || locale === index.siteDefaultLocale) return canonicalRoute
119
+ const entry = index.translations[locale]
120
+ if (!entry) return canonicalRoute
121
+ const exact = entry.forward.get(canonicalRoute)
122
+ if (exact) return exact
123
+ for (const [canonical, translated] of entry.forward) {
124
+ if (canonicalRoute.startsWith(canonical + '/')) return translated + canonicalRoute.slice(canonical.length)
125
+ }
126
+ return canonicalRoute
127
+ }
128
+
129
+ /**
130
+ * A route a locale shows → its canonical route. Decoded first: a browser percent-encodes a
131
+ * translated slug, and the translations are authored as plain text.
132
+ */
133
+ export function reverseTranslateRoute(site, displayRoute, locale) {
134
+ const index = indexOf(site)
135
+ if (!locale || locale === index.siteDefaultLocale) return displayRoute
136
+ const entry = index.translations[locale]
137
+ if (!entry) return displayRoute
138
+ const route = decodeRouteValue(displayRoute)
139
+ const exact = entry.reverse.get(route)
140
+ if (exact) return exact
141
+ for (const [translated, canonical] of entry.reverse) {
142
+ if (route.startsWith(translated + '/')) return canonical + route.slice(translated.length)
143
+ }
144
+ return route
145
+ }
146
+
147
+ /**
148
+ * ⭐ **A PAGE'S URL IN A LOCALE** — the one rule the language switcher, a redirect's destination
149
+ * and the canonical form share. The locale served unprefixed shows the canonical route; a locale
150
+ * with a domain of its own is that domain; any other is `/{code}` plus its translated route.
151
+ *
152
+ * @param {Object} site - a locale's site content, or its `routeIndex`
153
+ * @param {string} localeCode - the locale the URL is for
154
+ * @param {string} route - the page's route, canonical or as the active locale shows it
155
+ * @param {{ activeLocale?: string, defaultLocale?: string }} [context]
156
+ * @returns {string} a path, or an absolute URL on a locale's own domain
157
+ */
158
+ export function localeUrl(site, localeCode, route, context = {}) {
159
+ const index = indexOf(site)
160
+ const activeLocale = context.activeLocale ?? index.activeLocale
161
+ const defaultLocale = context.defaultLocale ?? index.defaultLocale
162
+ let target = route
163
+
164
+ // The active locale's prefix, then its display route → canonical.
165
+ if (activeLocale && activeLocale !== defaultLocale) {
166
+ const prefix = `/${activeLocale}`
167
+ if (target === prefix || target === `${prefix}/`) target = '/'
168
+ else if (target.startsWith(`${prefix}/`)) target = target.slice(prefix.length)
169
+ }
170
+ target = reverseTranslateRoute(index, target, activeLocale)
171
+
172
+ const designated = index.domainLocales && Object.entries(index.domainLocales).find(([, lang]) => lang === localeCode)
173
+ if (designated) {
174
+ const translated = translateRoute(index, target, localeCode)
175
+ return `https://${designated[0]}${translated === '/' ? '/' : translated}`
176
+ }
177
+ // The locale served unprefixed: no prefix — and its own slugs, unless it is the site's default,
178
+ // whose routes are the canonical ones. ⛔ Until 2026-09-30 this returned the canonical route for a
179
+ // host's own locale too: on a French host a French reader was sent to `/docs/intro`, not
180
+ // `/documents/introduction`.
181
+ if (localeCode === defaultLocale) return translateRoute(index, target, localeCode)
182
+ const translated = translateRoute(index, target, localeCode)
183
+ return translated === '/' ? `/${localeCode}/` : `/${localeCode}${translated}`
184
+ }
185
+
186
+ /**
187
+ * The locale a path names by its prefix, and the path without it — for a host choosing which
188
+ * locale's content to resolve a request against. A path with no served locale's prefix is the
189
+ * locale served unprefixed: the host's own (`domainLocale`), else the site's default.
190
+ *
191
+ * @param {string} path - the request path, base removed
192
+ * @param {Object} config - the site's config (`languages`, `defaultLanguage`, `domainLocale`)
193
+ * @returns {{ locale: string, prefixed: boolean, path: string }}
194
+ */
195
+ export function localeOfPath(path, config = {}) {
196
+ const siteDefault = resolveDefaultLocale(config)
197
+ const unprefixed = config.domainLocale || siteDefault
198
+ const raw = typeof path === 'string' && path ? path : '/'
199
+ const first = raw.split('/')[1] || ''
200
+ if (first && servedLocales(config, siteDefault).includes(first)) {
201
+ const rest = raw.slice(first.length + 1)
202
+ return { locale: first, prefixed: true, path: rest || '/' }
203
+ }
204
+ return { locale: unprefixed, prefixed: false, path: raw }
205
+ }
206
+
207
+ /**
208
+ * The page a path names — as `Website#getPage` has always found it — or null.
209
+ *
210
+ * In order: the active locale's prefix comes off; the page whose route is the path as given (a
211
+ * published payload may carry a locale's own routes); else the path reverse-translated and the
212
+ * page of that canonical route (a folder resolving to its `isIndex` child either way); else an
213
+ * index page whose own URL is the path; else the parametric pages in page order, against the
214
+ * canonical route and then the path as given. A static page always wins.
215
+ *
216
+ * @returns {{ page: Object, route: string, params: Object, template: string|null } | null}
217
+ */
218
+ function findPage(index, path, { activeLocale, defaultLocale }) {
219
+ let stripped = decodeRouteValue(path)
220
+ if (activeLocale && activeLocale !== defaultLocale) {
221
+ const prefix = `/${activeLocale}`
222
+ if (stripped === prefix || stripped === `${prefix}/`) stripped = '/'
223
+ else if (stripped.startsWith(`${prefix}/`)) stripped = stripped.slice(prefix.length)
224
+ }
225
+ const asGiven = stripped === '/' ? '/' : stripped.replace(/\/$/, '')
226
+
227
+ const promoted = (page) => (index.childrenOf.get(page.route) || []).find(isIndex) || page
228
+ const exactly = (route) => index.byRoute.get(route)
229
+
230
+ const direct = exactly(asGiven)
231
+ if (direct) {
232
+ const page = promoted(direct)
233
+ return { page, route: page.route, params: {}, template: null }
234
+ }
235
+
236
+ const reversed = reverseTranslateRoute(index, asGiven, activeLocale)
237
+ const canonical = reversed === '/' ? '/' : reversed.replace(/\/$/, '')
238
+ const exact = exactly(canonical)
239
+ if (exact) {
240
+ const page = promoted(exact)
241
+ return { page, route: page.route, params: {}, template: null }
242
+ }
243
+
244
+ const indexPage = index.pages.find((p) => isIndex(p) && navRoute(p) === canonical)
245
+ if (indexPage) return { page: indexPage, route: indexPage.route, params: {}, template: null }
246
+
247
+ for (const candidate of new Set([canonical, asGiven])) {
248
+ for (const page of index.pages) {
249
+ if (!page.route.includes(':')) continue
250
+ const hit = matchDynamicRoute(page.route, candidate)
251
+ if (hit) return { page, route: candidate, params: hit.params, template: page.route }
252
+ }
253
+ }
254
+ return null
255
+ }
256
+
257
+ /**
258
+ * Where a page with no content of its own lands: itself when it has an `isIndex` child, else its
259
+ * first descendant with content, depth-first in page order — or null when nothing in it has
260
+ * content.
261
+ *
262
+ * @param {Object} site - a locale's site content, or its `routeIndex`
263
+ * @param {Object} page - a page of it
264
+ * @returns {string|null}
265
+ */
266
+ export function landingRoute(site, page, seen = new Set()) {
267
+ const index = indexOf(site)
268
+ if (!page || seen.has(page.route)) return null
269
+ seen.add(page.route)
270
+ if (hasContent(page)) return page.route
271
+ const children = index.childrenOf.get(page.route) || []
272
+ if (children.some(isIndex)) return page.route
273
+ for (const child of children) {
274
+ const route = landingRoute(index, child, seen)
275
+ if (route) return route
276
+ }
277
+ return null
278
+ }
279
+
280
+ /**
281
+ * ⭐ **RESOLVE A PATH** against one locale's site content.
282
+ *
283
+ * ```
284
+ * { kind: 'page', status: 200, page, route, params, template }
285
+ * { kind: 'redirect', status: 302 | 301, location, reason: 'authored' | 'container' | 'locale', page?, … }
286
+ * { kind: 'rewrite', target, page, … } — the page is served from `target`, by a host that proxies
287
+ * { kind: 'notFound', status: 404, page } — `page`: the site's not-found page, or null
288
+ * ```
289
+ *
290
+ * In order:
291
+ * 1. **The locale served unprefixed, asked for with its prefix** — `/en/docs` where `en` is the
292
+ * default (or the host's own locale) — is a `301` to the path without it. Ruled 2026-09-30
293
+ * [Diego]; until then no page matched it.
294
+ * 2. **The page** (`findPage`). None ⇒ `notFound`, with the site's not-found page: its
295
+ * `notFound` content, else the page at `/404`.
296
+ * 3. **An authored `redirect:`** ⇒ a `302` to it: a page of the site in this locale, anything
297
+ * else as written (`authoredRedirectLocation`).
298
+ * 4. **An authored `rewrite:`** ⇒ the page is served from there; only a host that proxies can.
299
+ * 5. **A page with no content** ⇒ a `302` to where it lands (`landingRoute`), in this locale
300
+ * (`localeUrl`) — when that is not the page itself.
301
+ * 6. Otherwise the page. A parametric page's record may still not exist; that is the render's
302
+ * data step to say.
303
+ *
304
+ * `status` is what a host that sends one sends. A static host has its own ways to say each kind.
305
+ *
306
+ * @param {Object} site - one locale's site content (`{ pages, config, notFound? }`), or its `routeIndex`
307
+ * @param {string} path - the request path, with any deployment base removed
308
+ * @param {{ activeLocale?: string, defaultLocale?: string }} [context] - defaults to the content's
309
+ * own (`config.activeLocale`, `config.domainLocale`)
310
+ * @returns {Object} the resolution
311
+ */
312
+ export function resolveRoute(site, path, context = {}) {
313
+ const index = indexOf(site)
314
+ const activeLocale = context.activeLocale ?? index.activeLocale
315
+ const defaultLocale = context.defaultLocale ?? index.defaultLocale
316
+ const raw = typeof path === 'string' && path ? path : '/'
317
+
318
+ // 1 · the unprefixed locale, asked for with its prefix. The rest of the path goes as written.
319
+ if (defaultLocale) {
320
+ const prefix = `/${defaultLocale}`
321
+ if (raw === prefix || raw === `${prefix}/`) return redirect('/', RESOLUTION_STATUS.localeRedirect, 'locale')
322
+ if (raw.startsWith(`${prefix}/`)) return redirect(raw.slice(prefix.length), RESOLUTION_STATUS.localeRedirect, 'locale')
323
+ }
324
+
325
+ // 2 · the page
326
+ const found = findPage(index, raw, { activeLocale, defaultLocale })
327
+ if (!found) return { kind: 'notFound', status: RESOLUTION_STATUS.notFound, page: index.notFound }
328
+ const { page } = found
329
+
330
+ // 3 · 4 · what an author wrote on the page
331
+ if (typeof page.redirect === 'string' && page.redirect) {
332
+ const location = authoredRedirectLocation(index, found.route, page.redirect, { activeLocale, defaultLocale })
333
+ return { ...redirect(location, RESOLUTION_STATUS.pageRedirect, 'authored'), ...found }
334
+ }
335
+ if (typeof page.rewrite === 'string' && page.rewrite) {
336
+ return { kind: 'rewrite', target: page.rewrite, ...found }
337
+ }
338
+
339
+ // 5 · a page with no content goes to its content. The DECISION is canonical (`page.route`);
340
+ // the DESTINATION is this locale's URL for it.
341
+ if (!hasContent(page)) {
342
+ const landing = landingRoute(index, page)
343
+ if (landing && landing !== page.route) {
344
+ const location = localeUrl(index, activeLocale, landing, { activeLocale, defaultLocale })
345
+ return { ...redirect(location, RESOLUTION_STATUS.pageRedirect, 'container'), ...found }
346
+ }
347
+ }
348
+
349
+ return { kind: 'page', status: RESOLUTION_STATUS.page, ...found }
350
+ }
351
+
352
+ function redirect(location, status, reason) {
353
+ return { kind: 'redirect', status, location, reason }
354
+ }
355
+
356
+ const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i
357
+
358
+ /**
359
+ * An authored `redirect:` resolved against the page that carries it, as a browser resolves a
360
+ * relative URL with the page as a FOLDER: a URL with a scheme, or a protocol-relative one, as
361
+ * written; `academic` on `/solutions` is `/solutions/academic`; `./x` and `../x` step as they do
362
+ * in a URL, on a relative target and on a path from the root alike. A trailing slash and an empty
363
+ * segment are kept, as a URL keeps them — the page a path names is matched with a trailing slash
364
+ * or without. Any query or fragment rides along untouched.
365
+ *
366
+ * The build resolves a site's redirects by this rule, and `resolveRoute` resolves a payload's that
367
+ * were not (a pushed page carries its target as written). ⛔ Until 2026-09-30 a relative target was
368
+ * joined to the page's route and no `.` or `..` was resolved, so `../pricing` stayed in the path.
369
+ *
370
+ * @param {string} route - the page's own route
371
+ * @param {string} target - its `redirect:`
372
+ * @returns {string}
373
+ */
374
+ export function authoredRedirectTarget(route, target) {
375
+ if (typeof target !== 'string' || !target) return target
376
+ if (target.startsWith('//') || HAS_SCHEME.test(target)) return target
377
+ const cut = target.search(/[?#]/)
378
+ const path = cut < 0 ? target : target.slice(0, cut)
379
+ const suffix = cut < 0 ? '' : target.slice(cut)
380
+ const base = route === '/' ? '/' : `${route}/`
381
+ return removeDotSegments(path.startsWith('/') ? path : base + path) + suffix
382
+ }
383
+
384
+ /** RFC 3986 § 5.2.4 for a path from the root: `.` and `..` segments resolved, nothing else changed. */
385
+ function removeDotSegments(path) {
386
+ const segments = path.split('/').slice(1)
387
+ const out = []
388
+ segments.forEach((segment, i) => {
389
+ const last = i === segments.length - 1
390
+ if (segment === '.' || segment === '..') {
391
+ if (segment === '..') out.pop()
392
+ if (last) out.push('')
393
+ return
394
+ }
395
+ out.push(segment)
396
+ })
397
+ return '/' + out.join('/')
398
+ }
399
+
400
+ /**
401
+ * ⭐ WHERE AN AUTHORED REDIRECT SENDS A VISITOR OF THIS LOCALE — a page of the site in their
402
+ * language, as a page with no content sends them (ruled for containers 2026-09-30 [Diego]; for an
403
+ * authored redirect the same day, asked by the host that serves it).
404
+ *
405
+ * - A URL with a scheme, a protocol-relative one, or a path that already carries a served locale's
406
+ * prefix: as written — the author named where.
407
+ * - A path naming a page of the site: that page's URL in this locale (`localeUrl`) — its prefix and
408
+ * its translated slugs — with any query or fragment kept.
409
+ * - Any other path — a file, a route the site does not hold: as written.
410
+ *
411
+ * ⛔ Until 2026-09-30 every authored redirect went as written, so a French visitor was sent to the
412
+ * English page, and a relative target was left for the browser to resolve against the URL it had
413
+ * asked for rather than the page.
414
+ *
415
+ * @returns {string}
416
+ */
417
+ function authoredRedirectLocation(index, route, target, { activeLocale, defaultLocale }) {
418
+ const resolved = authoredRedirectTarget(route, target)
419
+ if (!resolved.startsWith('/') || resolved.startsWith('//')) return resolved
420
+ const cut = resolved.search(/[?#]/)
421
+ const path = cut < 0 ? resolved : resolved.slice(0, cut)
422
+ const suffix = cut < 0 ? '' : resolved.slice(cut)
423
+ const first = path.split('/')[1] || ''
424
+ if (first && index.locales.includes(first)) return resolved
425
+ const canonical = path === '/' ? '/' : path.replace(/\/$/, '')
426
+ const named = findPage(index, canonical, { activeLocale: index.siteDefaultLocale, defaultLocale: index.siteDefaultLocale })
427
+ if (!named) return resolved
428
+ return localeUrl(index, activeLocale, canonical, { activeLocale, defaultLocale }) + suffix
429
+ }
@@ -666,6 +666,13 @@ export function stripLocalePrefix(route, activeLocale, defaultLocale) {
666
666
  * ⚖️ Matching is not resolving: a hit means the ROUTE exists. Whether the record
667
667
  * behind a parametric page exists is a data question answered later.
668
668
  *
669
+ * ⚠️ **It is a SUBSET of `Website#getPage`, not the whole rule.** It strips no locale
670
+ * prefix, reverse-translates no route (`config.i18n.routeTranslations`), matches no
671
+ * index page by its nav route, and promotes no folder to its `isIndex` child —
672
+ * `getPage` does all four. So for a localized URL, or a folder with an index child,
673
+ * the two can name different pages. *(This comment called it "one rule, for every
674
+ * lane" without that caveat until 2026-09-30.)*
675
+ *
669
676
  * @param {Array<Object>|{pages?: Array<Object>}} source - the pages, or a payload holding them
670
677
  * @param {string} route - the concrete path
671
678
  * @returns {{ page: Object|null, params: Record<string,string> }} `page` is null when nothing matches
package/src/website.js CHANGED
@@ -11,12 +11,19 @@ import FetcherDispatcher from './fetcher-dispatcher.js'
11
11
  import ObservableState from './observable-state.js'
12
12
  import { normalizeSeo } from './seo.js'
13
13
  import { resolveDefaultLocale, localeLabel } from './locale-config.js'
14
- import { matchDynamicRoute, decodeRouteValue, recordTitle, routeBinding, routeParamName, parentRouteOf } from './route-match.js'
14
+ import { matchDynamicRoute, recordTitle, routeBinding, routeParamName, parentRouteOf } from './route-match.js'
15
15
  import { resolveFetchConfigs, pageRouteQuery, recordPages } from './fetch-config.js'
16
16
  import { declaredKeys } from './data-keys.js'
17
17
  import { pageRecordConfig, planFor, runPlanSync } from './page-data.js'
18
18
  import { findLayoutEntry } from './layout-name.js'
19
19
  import { resolveService } from './services.js'
20
+ import {
21
+ routeIndex,
22
+ resolveRoute as resolveRouteIn,
23
+ localeUrl,
24
+ translateRoute as translateRouteIn,
25
+ reverseTranslateRoute as reverseTranslateRouteIn,
26
+ } from './resolve-route.js'
20
27
 
21
28
  /**
22
29
  * Services whose provider is not simply an address, keyed by name.
@@ -103,7 +110,10 @@ export default class Website {
103
110
  this.locales = []
104
111
  this.activeLang = 'en'
105
112
  this.langs = []
106
- this._routeTranslations = {}
113
+ // What a URL names — the one rule, over this content (`./resolve-route.js`).
114
+ this._routeIndex = null
115
+ // A payload page → its Page, for the pages `resolveRoute` names.
116
+ this._pageOfData = new Map()
107
117
  this.basePath = ''
108
118
  this.versionedScopes = {}
109
119
  this.assets = {}
@@ -166,7 +176,13 @@ export default class Website {
166
176
  this._dynamicPageCache = new Map()
167
177
  this._recordPages = null
168
178
 
169
- this.pages = regularPages.map((page, index) => new Page(page, index, this))
179
+ this._pageOfData = new Map()
180
+ this.pages = regularPages.map((page, index) => {
181
+ const instance = new Page(page, index, this)
182
+ this._pageOfData.set(page, instance)
183
+ return instance
184
+ })
185
+ this._routeIndex = routeIndex(content)
170
186
  this.buildPageHierarchy()
171
187
 
172
188
  this.activePage =
@@ -192,7 +208,6 @@ export default class Website {
192
208
  this.activeLang = this.activeLocale
193
209
  this.langs = this.locales.map((l) => ({ label: l.label || l.code, value: l.code }))
194
210
 
195
- this._routeTranslations = this._buildRouteTranslations(config)
196
211
  this.versionedScopes = versionedScopes
197
212
  this.assets = assets
198
213
  }
@@ -319,87 +334,35 @@ export default class Website {
319
334
  }))
320
335
  }
321
336
 
322
- /**
323
- * Build forward and reverse route translation maps per locale
324
- * @private
325
- */
326
- _buildRouteTranslations(config) {
327
- const translations = config.i18n?.routeTranslations || {}
328
- const result = {}
329
- for (const [locale, routes] of Object.entries(translations)) {
330
- const forward = new Map() // canonical → translated
331
- const reverse = new Map() // translated → canonical
332
- for (const [canonical, translated] of Object.entries(routes)) {
333
- forward.set(canonical, translated)
334
- reverse.set(translated, canonical)
335
- }
336
- result[locale] = { forward, reverse }
337
- }
338
- return result
339
- }
340
-
341
337
  /**
342
338
  * Translate a canonical route to a locale-specific display route
343
339
  * Supports exact match and prefix match (e.g., /blog → /noticias also applies to /blog/my-post)
344
340
  *
341
+ * One rule with the resolver's (`./resolve-route.js`), over the same content.
342
+ *
345
343
  * @param {string} canonicalRoute - Internal route (e.g., '/about')
346
344
  * @param {string} [locale] - Target locale (defaults to active locale)
347
345
  * @returns {string} Translated route or original if no translation exists
348
346
  */
349
347
  translateRoute(canonicalRoute, locale = this.activeLocale) {
350
- if (!locale || locale === this.siteDefaultLocale) return canonicalRoute
351
- const entry = this._routeTranslations[locale]
352
- if (!entry) return canonicalRoute
353
- // Exact match
354
- const translated = entry.forward.get(canonicalRoute)
355
- if (translated) return translated
356
- // Prefix match (e.g., /blog matches /blog/my-post → /noticias/my-post)
357
- for (const [canonical, trans] of entry.forward) {
358
- if (canonicalRoute.startsWith(canonical + '/')) {
359
- return trans + canonicalRoute.slice(canonical.length)
360
- }
361
- }
362
- return canonicalRoute
348
+ return translateRouteIn(this._routeIndex, canonicalRoute, locale)
363
349
  }
364
350
 
365
351
  /**
366
352
  * Reverse-translate a display route back to the canonical route
367
353
  * Used when resolving incoming URLs to find the matching page
368
354
  *
355
+ * ⭐ It DECODES first (`./resolve-route.js`): a browser percent-encodes a translated slug —
356
+ * `/Sites-Web/Th%C3%A8me-du-site-Web` — and the translations are authored as plain text.
357
+ * Without it every translated route carrying a non-ASCII character or an apostrophe resolved
358
+ * to nothing, while the same route with an all-ASCII slug worked.
359
+ *
369
360
  * @param {string} displayRoute - Display route (e.g., '/acerca-de')
370
361
  * @param {string} [locale] - Source locale (defaults to active locale)
371
362
  * @returns {string} Canonical route or original if no translation exists
372
363
  */
373
364
  reverseTranslateRoute(displayRoute, locale = this.activeLocale) {
374
- if (!locale || locale === this.siteDefaultLocale) return displayRoute
375
- const entry = this._routeTranslations[locale]
376
- if (!entry) return displayRoute
377
-
378
- // The caller hands us a route that came from a URL, and a browser
379
- // percent-encodes everything outside the unreserved set — so a French slug
380
- // arrives as `/Sites-Web/Th%C3%A8me-du-site-Web`. The translation map is
381
- // built from site.yml, where it is authored as plain text. Decoding here
382
- // rather than at each call site is deliberate: getPage(), normalizeRoute()
383
- // and getLocaleUrl() all feed this, and a future caller would have to
384
- // remember otherwise.
385
- //
386
- // Without it translateRoute() emits a URL this method cannot read back —
387
- // every translated route carrying a non-ASCII character or an apostrophe
388
- // resolved to nothing and rendered the 404 page, while the SAME route with
389
- // an all-ASCII slug worked. The helper is shared with the captured-param
390
- // decode in `route-match.js`, which needs the identical guard.
391
- const route = decodeRouteValue(displayRoute)
392
-
393
- // Exact match
394
- const canonical = entry.reverse.get(route)
395
- if (canonical) return canonical
396
- // Prefix match
397
- for (const [trans, canon] of entry.reverse) {
398
- if (route.startsWith(trans + '/')) {
399
- return canon + route.slice(trans.length)
400
- }
401
- }
402
- return route
365
+ return reverseTranslateRouteIn(this._routeIndex, displayRoute, locale)
403
366
  }
404
367
 
405
368
  /**
@@ -458,124 +421,64 @@ export default class Website {
458
421
  }
459
422
 
460
423
  /**
461
- * Get page by route
462
- * Matches in priority order:
463
- * 1. Exact match on actual route
464
- * 2. Index page nav route match
465
- * 3. Dynamic route pattern match (e.g., /blog/:slug matches /blog/my-post)
424
+ * Get page by route — the page a URL names, or undefined.
425
+ *
426
+ * ⭐ **The rule is `resolveRoute`** (`./resolve-route.js`), the one every lane calls: the
427
+ * active locale's prefix, the page as given or by its translated route (a folder resolving to
428
+ * its `isIndex` child), an index page by its own URL, then the parametric pages in page order.
429
+ * This maps what it names to this Website's Page — a parametric page's concrete Page made here,
430
+ * with its record looked up (`_createDynamicPage`).
431
+ *
432
+ * A page that redirects is still returned: it is the page the URL names, and what to do about
433
+ * its redirect is `resolveRoute`'s to say. A URL naming no page — the locale served unprefixed,
434
+ * asked for with its prefix, included — returns undefined.
466
435
  *
467
436
  * @param {string} route - The route to find
468
437
  * @returns {Page|undefined}
469
438
  */
470
439
  getPage(route) {
471
- // Strip locale prefix if present (e.g., '/fr/about' → '/about')
472
- // Pages are stored with non-prefixed routes; the locale is a URL concern,
473
- // not a page identity concern.
474
- // Decode before ANY comparison: a published payload can hold translated
475
- // display routes verbatim, so the direct match below needs the same plain
476
- // text form the reverse-translate path does.
477
- let stripped = decodeRouteValue(route)
478
- if (this.activeLocale && this.activeLocale !== this.defaultLocale) {
479
- const prefix = `/${this.activeLocale}`
480
- if (stripped === prefix || stripped === `${prefix}/`) {
481
- stripped = '/'
482
- } else if (stripped.startsWith(`${prefix}/`)) {
483
- stripped = stripped.slice(prefix.length)
484
- }
485
- }
486
-
487
- // Normalize trailing slashes for consistent matching
488
- const normalizedStripped = stripped === '/' ? '/' : stripped.replace(/\/$/, '')
489
-
490
- // Priority 1: Direct match on the (possibly display) route.
491
- // Handles published-payload sites where the page map may already contain
492
- // locale-translated display routes (e.g. fr pages have fr routes).
493
- // For file-system sites whose page map uses canonical routes this will
494
- // simply fall through to the reverse-translate path below.
495
- const directMatch = this.pages.find((page) => page.route === normalizedStripped)
496
- if (directMatch) {
497
- // Folder with index child: always resolve to the index page.
498
- // The index child is the designated landing page for this folder URL.
499
- const indexChild = directMatch.children.find((c) => c.isIndex)
500
- if (indexChild) return indexChild
501
- return directMatch
502
- }
503
-
504
- // Reverse-translate display route to canonical (e.g., '/acerca-de' → '/about')
505
- //
506
- // Feed it the TRAILING-SLASH-NORMALIZED form. The translation map is keyed
507
- // without a trailing slash, so `/acerca-de/` missed the exact lookup and
508
- // fell through to the prefix branch, which rewrites only the FIRST segment
509
- // — `/blogue/mi-articulo/` became `/blog/mi-articulo/`, leaving the child
510
- // segment untranslated and pointing at no page. It looked like it worked
511
- // for as long as every child slug happened to be identical in both locales.
512
- stripped = this.reverseTranslateRoute(normalizedStripped)
513
-
514
- // A translation VALUE may itself carry a trailing slash, so normalize again
515
- // rather than assuming the input normalization covered it.
516
- const normalizedRoute = stripped === '/' ? '/' : stripped.replace(/\/$/, '')
517
-
518
- // Priority 1b: Exact match on canonical route
519
- const exactMatch = this.pages.find((page) => page.route === normalizedRoute)
520
- if (exactMatch) {
521
- const indexChild = exactMatch.children.find((c) => c.isIndex)
522
- if (indexChild) return indexChild
523
- return exactMatch
524
- }
440
+ const result = resolveRouteIn(this._routeIndex, route, this._routeContext())
441
+ return result.kind !== 'notFound' && result.page ? this._pageFor(result) : undefined
442
+ }
525
443
 
526
- // Priority 2: Index page nav route match
527
- const indexMatch = this.pages.find((page) => page.isIndex && page.getNavRoute() === normalizedRoute)
528
- if (indexMatch) return indexMatch
529
-
530
- // Priority 3: Dynamic route pattern matching — on the canonical route, then on the display route,
531
- // as Priorities 1 and 1b match a static page in either payload shape. A published payload's
532
- // parametric page carries its locale's own pattern (`/noticias/:slug`), which only the display
533
- // route matches. ⛔ Until 2026-09-26 only the canonical route was tried, so a backend-served
534
- // site's `/es/noticias/x` showed the not-found page without asking for its record. The canonical
535
- // route goes first so a file-lane site — whose patterns are all canonical — matches as before.
536
- for (const candidate of new Set([normalizedRoute, normalizedStripped])) {
537
- const found = this._matchDynamicPage(candidate)
538
- if (found) return found
539
- }
444
+ /**
445
+ * ⭐ **WHAT A URL NAMES, on this Website** — `resolveRoute` (`./resolve-route.js`), with its
446
+ * page as this Website's Page: a page, a redirect (`location`, `status`, `reason`), a page
447
+ * served from elsewhere (`rewrite`), or not found (`page`: the site's not-found page, or null).
448
+ *
449
+ * @param {string} route - a path, with any deployment base removed
450
+ * @returns {Object} the resolution
451
+ */
452
+ resolveRoute(route) {
453
+ const result = resolveRouteIn(this._routeIndex, route, this._routeContext())
454
+ if (result.kind === 'notFound') return { ...result, page: this.notFoundPage }
455
+ if (!result.page) return result
456
+ return { ...result, page: this._pageFor(result) ?? null }
457
+ }
540
458
 
541
- return undefined
459
+ /** The locale context a route is resolved in: this Website's, which a host may have set. */
460
+ _routeContext() {
461
+ return { activeLocale: this.activeLocale, defaultLocale: this.defaultLocale }
542
462
  }
543
463
 
544
464
  /**
545
- * The dynamic page a concrete route names, from the cache or a fresh match of the dynamic
546
- * patterns — or undefined.
465
+ * The Page of a resolution: the payload page's own, or — for a parametric page — the concrete
466
+ * page at the resolved route, from the cache or made now.
547
467
  *
548
468
  * @private
549
- * @param {string} route - a concrete route, in the form the page patterns are matched against
550
- * @returns {Page|undefined}
551
469
  */
552
- _matchDynamicPage(route) {
553
- if (this._dynamicPageCache.has(route)) {
554
- return this._dynamicPageCache.get(route)
555
- }
556
-
557
- // Try to match against dynamic route patterns
558
- for (const page of this.pages) {
559
- // Check if this is a dynamic page (has :param in route)
560
- if (!page.route.includes(':')) continue
561
-
562
- const match = this._matchDynamicRoute(page.route, route)
563
- if (match) {
564
- // Create a dynamic page instance with the concrete route and params
565
- const result = this._createDynamicPage(page, route, match.params)
566
- if (result) {
567
- const { page: dynamicPage, recordsLoaded } = result
568
- // Only cache when the records were available at creation time.
569
- // If DataStore was empty, skip caching so the next render recreates
570
- // the page with fresh data (correct title, not-found state, etc.).
571
- if (recordsLoaded) {
572
- this._dynamicPageCache.set(route, dynamicPage)
573
- }
574
- return dynamicPage
575
- }
576
- }
577
- }
578
- return undefined
470
+ _pageFor({ page, route, params, template }) {
471
+ if (!template) return this._pageOfData.get(page)
472
+ if (this._dynamicPageCache.has(route)) return this._dynamicPageCache.get(route)
473
+ const templatePage = this._pageOfData.get(page)
474
+ const result = templatePage ? this._createDynamicPage(templatePage, route, params) : null
475
+ if (!result) return undefined
476
+ const { page: dynamicPage, recordsLoaded } = result
477
+ // Only cache when the records were available at creation time. If DataStore was empty,
478
+ // skip caching so the next render recreates the page with fresh data (correct title,
479
+ // not-found state, etc.).
480
+ if (recordsLoaded) this._dynamicPageCache.set(route, dynamicPage)
481
+ return dynamicPage
579
482
  }
580
483
 
581
484
  /**
@@ -1105,47 +1008,11 @@ export default class Website {
1105
1008
  getLocaleUrl(localeCode, route = null) {
1106
1009
  // Use getNavRoute() so index pages return the clean folder URL
1107
1010
  // (e.g., /Articles instead of /Articles/index)
1108
- let targetRoute = route || this.activePage.getNavRoute()
1109
-
1110
- // Strip current locale prefix if present in route
1111
- if (this.activeLocale && this.activeLocale !== this.defaultLocale) {
1112
- const prefix = `/${this.activeLocale}`
1113
- if (targetRoute === prefix || targetRoute === `${prefix}/`) {
1114
- targetRoute = '/'
1115
- } else if (targetRoute.startsWith(`${prefix}/`)) {
1116
- targetRoute = targetRoute.slice(prefix.length)
1117
- }
1118
- }
1119
-
1120
- // Reverse-translate from current locale to canonical route
1121
- targetRoute = this.reverseTranslateRoute(targetRoute)
1122
-
1123
- // Per-domain locale: if a domain is designated for this locale,
1124
- // return a full cross-domain URL instead of a path-based prefix.
1125
- const domainLocales = this.config?.domainLocales
1126
- if (domainLocales) {
1127
- const designated = Object.entries(domainLocales).find(([, lang]) => lang === localeCode)
1128
- if (designated) {
1129
- const domain = designated[0]
1130
- const translatedRoute = this.translateRoute(targetRoute, localeCode)
1131
- return `https://${domain}${translatedRoute === '/' ? '/' : translatedRoute}`
1132
- }
1133
- }
1134
-
1135
- // Default locale uses root path (no prefix), no translation needed
1136
- if (localeCode === this.defaultLocale) {
1137
- return targetRoute
1138
- }
1139
-
1140
- // Translate canonical route to target locale's display route
1141
- const translatedRoute = this.translateRoute(targetRoute, localeCode)
1142
-
1143
- // Other locales use /locale/ prefix
1144
- if (translatedRoute === '/') {
1145
- return `/${localeCode}/`
1146
- }
1147
-
1148
- return `/${localeCode}${translatedRoute}`
1011
+ const targetRoute = route || this.activePage.getNavRoute()
1012
+ // ⭐ One rule with a redirect's destination (`localeUrl`, `./resolve-route.js`): the locale
1013
+ // served unprefixed shows the canonical route, a locale with its own domain is that domain,
1014
+ // any other is `/{code}` plus its translated route.
1015
+ return localeUrl(this._routeIndex, localeCode, targetRoute, this._routeContext())
1149
1016
  }
1150
1017
 
1151
1018
  /**