@jxsuite/compiler 11.1.2 → 11.2.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.
@@ -23,6 +23,7 @@ import type { ExtensionRegistry } from "@jxsuite/schema/extension-registry";
23
23
  import { isFunction, isNonNullObject } from "@jxsuite/schema/guards";
24
24
  import { errorMessage } from "@jxsuite/schema/parse";
25
25
  import type { ProjectConfig } from "@jxsuite/schema/types";
26
+ import { sectionOwnerActive } from "./project-sections.ts";
26
27
 
27
28
  /** What {@link copyMountedAssets} reports: files written, and URLs that resolved to nothing. */
28
29
  export interface MountedAssetCopy {
@@ -54,11 +55,7 @@ export async function loadAssetMounts(
54
55
  for (const entry of registry.assetProviders()) {
55
56
  const sectionKey = entry.project?.key;
56
57
  const sectionValue = sectionKey ? projectConfig[sectionKey] : undefined;
57
- if (
58
- sectionKey &&
59
- (sectionValue == null ||
60
- (isNonNullObject(sectionValue) && Object.keys(sectionValue).length === 0))
61
- ) {
58
+ if (!sectionOwnerActive(entry, projectConfig)) {
62
59
  continue;
63
60
  }
64
61
  try {
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Build-time-request.ts — the `$prototype: "Request"` entry a site build fetches once (spec.md
3
+ * §11.3)
4
+ *
5
+ * A `Request` at `timing: "compiler"` is the one built-in with a build-time value: the build sends
6
+ * the request the interpreter would send (the same method, headers and body), and its parsed JSON
7
+ * response becomes the entry's value, baked into the page. Anything the build cannot answer fails
8
+ * the build, naming the entry, because a page bound to nothing while the build reports success is
9
+ * the failure this exists to prevent.
10
+ *
11
+ * Identical requests share one fetch per build, so a layout read by a hundred pages is one call to
12
+ * the API it names, and a rate-limited endpoint is not hammered once per page.
13
+ *
14
+ * @module build-time-request
15
+ * @docs framework/concepts/timing
16
+ */
17
+
18
+ import { isString } from "@jxsuite/schema/guards";
19
+ import type { JsonValue, JxPrototypeDef } from "@jxsuite/schema/types";
20
+ import type { JxScope } from "@jxsuite/runtime/types";
21
+ import { evaluateStaticTemplate, isTemplateString } from "../shared.ts";
22
+
23
+ /** How long a build waits for a `Request`'s answer before it fails the build. */
24
+ export const BUILD_REQUEST_TIMEOUT_MS = 30_000;
25
+
26
+ /** The promises of the requests one build has started, keyed by {@link buildRequest}'s `key`. */
27
+ export type BuildRequestCache = Map<string, Promise<JsonValue>>;
28
+
29
+ /** A `Request` entry resolved to what the build sends for it. */
30
+ export interface BuildRequest {
31
+ /** The absolute URL the build fetches. */
32
+ url: string;
33
+ /** The `fetch` options, as the interpreter would pass them. */
34
+ init: RequestInit;
35
+ /** Identifies the request: two entries with the same key are the same fetch. */
36
+ key: string;
37
+ }
38
+
39
+ /**
40
+ * The request a build sends for a `Request` entry, evaluated against the build-time scope.
41
+ *
42
+ * @param def - A `$prototype: "Request"` entry
43
+ * @param scope - The build-time scope a `url` template reads (`$site`, `$page`, constants)
44
+ * @returns The URL, the fetch options and the cache key
45
+ * @throws {Error} When the entry is `manual`, its `url` does not resolve, or the result is not an
46
+ * absolute `http:` or `https:` URL
47
+ */
48
+ export function buildRequest(def: JxPrototypeDef, scope: JxScope | null): BuildRequest {
49
+ const { body: rawBody, headers, manual, method = "GET", url: template } = def;
50
+ if (manual) {
51
+ throw new Error("a manual Request has no build-time value");
52
+ }
53
+ const url = resolveUrl(template, scope);
54
+ let protocol: string;
55
+ try {
56
+ ({ protocol } = new URL(url));
57
+ } catch {
58
+ protocol = "";
59
+ }
60
+ if (protocol !== "http:" && protocol !== "https:") {
61
+ throw new Error(
62
+ `a build-time Request needs an absolute http(s) URL, got ${JSON.stringify(url)}`,
63
+ );
64
+ }
65
+ // The interpreter sends an object body as JSON and any other truthy body as it is.
66
+ const body = rawBody ? (isString(rawBody) ? rawBody : JSON.stringify(rawBody)) : undefined;
67
+ const init: RequestInit = {
68
+ method,
69
+ ...(headers && { headers }),
70
+ ...(body !== undefined && { body }),
71
+ };
72
+ return { init, key: JSON.stringify([method, url, headers ?? null, body ?? null]), url };
73
+ }
74
+
75
+ /**
76
+ * The URL a `Request` names, with a template evaluated against the build-time scope. A template
77
+ * that reads a runtime-only value, or that still reads `undefined`, does not resolve at build
78
+ * time.
79
+ */
80
+ function resolveUrl(raw: string | undefined, scope: JxScope | null): string {
81
+ const url = raw !== undefined && isTemplateString(raw) ? evaluateStaticTemplate(raw, scope) : raw;
82
+ if (!isString(url) || url === "" || url.includes("undefined")) {
83
+ throw new Error(`Request url ${JSON.stringify(raw ?? null)} does not resolve at build time`);
84
+ }
85
+ return url;
86
+ }
87
+
88
+ /**
89
+ * Fetches a `Request` entry once per build and returns its parsed JSON response.
90
+ *
91
+ * Every caller gets its own structured copy of the response: the resolver writes a `timing` marker
92
+ * onto an object value, and one page's state must not share an object with another's.
93
+ *
94
+ * @param def - A `$prototype: "Request"` entry
95
+ * @param scope - The build-time scope its `url` template is evaluated against
96
+ * @param options.cache - Shares the fetch between identical requests in one build (rejections too)
97
+ * @param options.timeoutMs - How long to wait for the answer (default
98
+ * {@link BUILD_REQUEST_TIMEOUT_MS})
99
+ * @returns The response body as JSON
100
+ * @throws {Error} When the request cannot be built, the answer is not 2xx, the body is not JSON, or
101
+ * no answer arrives within the timeout
102
+ */
103
+ export async function fetchAtBuildTime(
104
+ def: JxPrototypeDef,
105
+ scope: JxScope | null,
106
+ options: { cache?: BuildRequestCache | undefined; timeoutMs?: number | undefined } = {},
107
+ ): Promise<JsonValue> {
108
+ const { init, key, url } = buildRequest(def, scope);
109
+ const timeoutMs = options.timeoutMs ?? BUILD_REQUEST_TIMEOUT_MS;
110
+ const cached = options.cache?.get(key);
111
+ const pending = cached ?? request(url, init, timeoutMs);
112
+ if (cached === undefined) {
113
+ options.cache?.set(key, pending);
114
+ }
115
+ return structuredClone(await pending);
116
+ }
117
+
118
+ /** One fetch, failing on a non-2xx answer, a body that is not JSON, or the timeout. */
119
+ async function request(url: string, init: RequestInit, timeoutMs: number): Promise<JsonValue> {
120
+ const timeout = new Error(`no response within ${timeoutMs / 1000} s`);
121
+ let response: Response;
122
+ try {
123
+ response = await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
124
+ } catch (error) {
125
+ throw error instanceof DOMException && error.name === "TimeoutError" ? timeout : error;
126
+ }
127
+ if (!response.ok) {
128
+ throw new Error(`HTTP ${response.status} ${response.statusText}`.trimEnd());
129
+ }
130
+ // Reading the body and parsing it fail for different reasons, and each keeps its own message.
131
+ // A connection dropped mid-body fails as itself; only a body that does not parse is "not JSON".
132
+ let text: string;
133
+ try {
134
+ text = await response.text();
135
+ } catch (error) {
136
+ throw error instanceof DOMException && error.name === "TimeoutError" ? timeout : error;
137
+ }
138
+ try {
139
+ /* SAFETY: `JSON.parse` accepted the text, so the value is JSON, which is what JsonValue names. */
140
+ return JSON.parse(text) as JsonValue;
141
+ } catch {
142
+ throw new Error("response is not JSON");
143
+ }
144
+ }
@@ -15,7 +15,7 @@
15
15
  * @docs framework/build
16
16
  */
17
17
 
18
- import { existsSync, readdirSync } from "node:fs";
18
+ import { existsSync, readdirSync, statSync } from "node:fs";
19
19
  import { dirname, isAbsolute, relative, resolve } from "node:path";
20
20
  import { isJsonObject, isString } from "@jxsuite/schema/guards";
21
21
  import { errorMessage } from "@jxsuite/schema/parse";
@@ -25,6 +25,7 @@ import type { JxDocument, ProjectConfig } from "@jxsuite/schema/types";
25
25
  import { qualifiedDocument } from "./document-scripts.ts";
26
26
  import { layoutChain } from "./layout-resolver.ts";
27
27
  import { readPageDocument } from "./pages-discovery.ts";
28
+ import { caseTagName, forEachExternalCase } from "../switch-cases.ts";
28
29
 
29
30
  /** One component a build compiles: where it was read from, the tag it defines, and its document. */
30
31
  export interface SiteComponent {
@@ -74,14 +75,27 @@ function refEntries(doc: { $elements?: unknown }): string[] {
74
75
  * tag. Nothing here throws: a page or layout that cannot be read is skipped, because compiling its
75
76
  * route reports it with the route.
76
77
  */
77
- export async function collectSiteComponents(
78
- input: SiteComponentInput,
79
- ): Promise<{ components: SiteComponent[]; errors: string[] }> {
78
+ export async function collectSiteComponents(input: SiteComponentInput): Promise<{
79
+ components: SiteComponent[];
80
+ errors: string[];
81
+ /** Every external `$switch` case accepted, in first-seen order, each once. */
82
+ cases: SiteComponent[];
83
+ /**
84
+ * The tags a module renders or imports that no page scan can see: a component's or case's own
85
+ * external cases, and the components a case declares (each with its own `$elements`).
86
+ */
87
+ caseReach: Map<string, string[]>;
88
+ }> {
80
89
  const { formatRegistry, pageSources, projectConfig, projectRoot } = input;
81
90
  const components: SiteComponent[] = [];
82
91
  const errors: string[] = [];
83
92
  const visited = new Set<string>();
84
93
  const pathByTag = new Map<string, string>();
94
+ const cases: SiteComponent[] = [];
95
+ const caseTagByPath = new Map<string, string>();
96
+ const caseReach = new Map<string, string[]>();
97
+ const componentByPath = new Map<string, SiteComponent>();
98
+ const reported = new Set<string>();
85
99
  const rel = (path: string) => relative(projectRoot, path).replaceAll("\\", "/");
86
100
 
87
101
  const visit = async (path: string, from: Declaration | null): Promise<void> => {
@@ -126,8 +140,101 @@ export async function collectSiteComponents(
126
140
  return;
127
141
  }
128
142
  pathByTag.set(tagName, path);
129
- components.push({ doc, path, tagName });
143
+ const component = { doc, path, tagName };
144
+ components.push(component);
145
+ componentByPath.set(path, component);
130
146
  await visitDeclared(doc, path);
147
+ await visitCases(path, doc, tagName);
148
+ };
149
+
150
+ const reach = (owner: string, tag: string): void => {
151
+ const held = caseReach.get(owner) ?? [];
152
+ if (!held.includes(tag) && owner !== tag) {
153
+ held.push(tag);
154
+ }
155
+ caseReach.set(owner, held);
156
+ };
157
+
158
+ /** The tags of the components a document's `$elements` name, and theirs in turn. */
159
+ const declaredTags = (doc: { $elements?: unknown }, declarerPath: string, seen: Set<string>) => {
160
+ for (const ref of refEntries(doc)) {
161
+ const component = componentByPath.get(resolve(dirname(declarerPath), ref));
162
+ if (component && !seen.has(component.tagName)) {
163
+ seen.add(component.tagName);
164
+ declaredTags(component.doc, component.path, seen);
165
+ }
166
+ }
167
+ return seen;
168
+ };
169
+
170
+ const refuse = (declarerPath: string, key: string, ref: string, because: string): void => {
171
+ const message = `${rel(declarerPath)}: $switch case "${key}" names ${ref}, ${because}`;
172
+ if (!reported.has(message)) {
173
+ reported.add(message);
174
+ errors.push(message);
175
+ }
176
+ };
177
+
178
+ /**
179
+ * Visit the external `$switch` cases one declaring document names, each reference against that
180
+ * document's directory. An accepted case is read once, compiled under one generated tag, and
181
+ * followed through its own `$elements` and cases (spec.md §14.1).
182
+ */
183
+ const visitCases = async (
184
+ declarerPath: string,
185
+ doc: JxDocument,
186
+ owner: string | null,
187
+ ): Promise<void> => {
188
+ const found: [string, string][] = [];
189
+ forEachExternalCase(doc, (key, ref) => {
190
+ found.push([key, ref]);
191
+ });
192
+ for (const [key, ref] of found) {
193
+ if (/^[a-z][a-z0-9+.-]*:/iu.test(ref)) {
194
+ refuse(declarerPath, key, ref, "a URL, which a build cannot compile");
195
+ continue;
196
+ }
197
+ const path = resolve(dirname(declarerPath), ref);
198
+ const where = rel(path);
199
+ if (where.startsWith("..") || isAbsolute(where)) {
200
+ refuse(declarerPath, key, ref, `outside the project (${where})`);
201
+ continue;
202
+ }
203
+ if (!existsSync(path) || !statSync(path).isFile()) {
204
+ refuse(declarerPath, key, ref, `which is not a file (${where})`);
205
+ continue;
206
+ }
207
+ let tag = caseTagByPath.get(path);
208
+ if (tag === undefined) {
209
+ let caseDoc: JxDocument;
210
+ try {
211
+ // Each `#client` and `#server` names this document from here on (spec.md §23.2).
212
+ // oxlint-disable-next-line no-await-in-loop -- Compile order is declaration order.
213
+ caseDoc = qualifiedDocument(
214
+ await readPageDocument(path, formatRegistry),
215
+ path,
216
+ projectRoot,
217
+ );
218
+ } catch (error) {
219
+ refuse(declarerPath, key, ref, `which does not read (${where}): ${errorMessage(error)}`);
220
+ continue;
221
+ }
222
+ tag = caseTagName(projectRoot, path);
223
+ caseTagByPath.set(path, tag);
224
+ cases.push({ doc: caseDoc, path, tagName: tag });
225
+ // The case's own components, then its own cases.
226
+ // oxlint-disable-next-line no-await-in-loop
227
+ await visitDeclared(caseDoc, path);
228
+ for (const declared of declaredTags(caseDoc, path, new Set())) {
229
+ reach(tag, declared);
230
+ }
231
+ // oxlint-disable-next-line no-await-in-loop
232
+ await visitCases(path, caseDoc, tag);
233
+ }
234
+ if (owner !== null) {
235
+ reach(owner, tag);
236
+ }
237
+ }
131
238
  };
132
239
 
133
240
  /** Visit what one declaring document names, each `$ref` against that document's directory. */
@@ -166,14 +273,18 @@ export async function collectSiteComponents(
166
273
  const levels = layoutChain(pageDoc, projectConfig, projectRoot);
167
274
  // oxlint-disable-next-line no-await-in-loop
168
275
  await visitDeclared(pageDoc, pagePath);
276
+ // oxlint-disable-next-line no-await-in-loop
277
+ await visitCases(pagePath, pageDoc, null);
169
278
  for (const level of levels) {
170
279
  // oxlint-disable-next-line no-await-in-loop
171
280
  await visitDeclared(level.doc, level.path);
281
+ // oxlint-disable-next-line no-await-in-loop
282
+ await visitCases(level.path, level.doc, null);
172
283
  }
173
284
  } catch {
174
285
  // A page or layout that cannot be read is reported by its route's compile, with the route.
175
286
  }
176
287
  }
177
288
 
178
- return { components, errors };
289
+ return { caseReach, cases, components, errors };
179
290
  }
@@ -1,5 +1,6 @@
1
1
  /**
2
- * Db-push — `jx db push [root] [--dry-run] [--connection <name>]` (plan Part 4a).
2
+ * Db-push — `jx db push [root] [--dry-run] [--connection <name>]` (specs/site-architecture.md
3
+ * §12.2, specs/extensions.md §11.1).
3
4
  *
4
5
  * Registry-driven: every `connections` entry resolves to its connector class (by
5
6
  * `connector.provider`) and the additive schema sync runs through the class's `deploySchema`
@@ -13,7 +14,9 @@ import { existsSync, readFileSync, writeFileSync } from "node:fs";
13
14
  import { resolve } from "node:path";
14
15
  import { applyBindingFragments } from "@jxsuite/create/scaffold";
15
16
  import { buildProjectExtensionRegistry } from "./format-host.ts";
17
+ import { pushSectionOwners } from "./section-push.ts";
16
18
  import { loadProjectConfig } from "./site-loader.ts";
19
+ import type { SectionPushResult } from "./section-push.ts";
17
20
  import type { DataPushRequest, FormatEntry } from "@jxsuite/schema/format-registry";
18
21
  import { isJsonObject } from "@jxsuite/schema/guards";
19
22
  import type { JsonObject } from "@jxsuite/schema/types";
@@ -33,6 +36,8 @@ export interface ConnectionPushResult {
33
36
 
34
37
  export interface DbPushResult {
35
38
  results: ConnectionPushResult[];
39
+ /** Each section owner's steps, run after the connector plan on the connections as declared. */
40
+ sections: SectionPushResult[];
36
41
  /** True when wrangler.jsonc was rewritten with binding fragments. */
37
42
  bindingsPatched: boolean;
38
43
  wranglerPath: string | null;
@@ -132,6 +137,16 @@ export async function dbPush(
132
137
  }
133
138
  }
134
139
 
140
+ /* Section owners (the auth extension's account tables) push after the connector plan, handed each
141
+ provider's own class so their steps land on the database the plan just wrote. A throw rides on
142
+ the owner's result: the connector statements have run, so the bindings below still patch. */
143
+ const sections = await pushSectionOwners(registry, config, {
144
+ dryRun,
145
+ env,
146
+ connection: only,
147
+ standins: false,
148
+ });
149
+
135
150
  // Apply binding fragments to wrangler.jsonc (skipped on dry runs and non-wrangler projects).
136
151
  const wranglerPath = resolve(projectRoot, "wrangler.jsonc");
137
152
  let bindingsPatched = false;
@@ -144,7 +159,12 @@ export async function dbPush(
144
159
  }
145
160
  }
146
161
 
147
- return { bindingsPatched, results, wranglerPath: existsSync(wranglerPath) ? wranglerPath : null };
162
+ return {
163
+ bindingsPatched,
164
+ results,
165
+ sections,
166
+ wranglerPath: existsSync(wranglerPath) ? wranglerPath : null,
167
+ };
148
168
  }
149
169
 
150
170
  /** Find the connector class serving a provider id. */
@@ -19,6 +19,7 @@ import type {
19
19
  StudioHints,
20
20
  } from "@jxsuite/schema/format-registry";
21
21
  import { isJsonObject } from "@jxsuite/schema/guards";
22
+ import { parseJson } from "@jxsuite/schema/parse";
22
23
  import type { JsonObject, JsonValue, ProjectConfig } from "@jxsuite/schema/types";
23
24
  import { projectFilePath } from "@jxsuite/schema/project-file/node";
24
25
 
@@ -122,7 +123,7 @@ export function resolveFromProject(projectRoot: string, specifier: string): stri
122
123
  export function createNodeFormatIO(projectRoot: string): FormatHostIO {
123
124
  return {
124
125
  importModule: (path) => importImplementation(path),
125
- loadJson: async (path) => JSON.parse(readFileSync(path, "utf8")),
126
+ loadJson: async (path) => parseJson(readFileSync(path, "utf8"), path),
126
127
  resolvePath: (base, ref) => {
127
128
  if (ref.startsWith("./") || ref.startsWith("../")) {
128
129
  return resolve(dirname(base), ref);
package/src/site/i18n.ts CHANGED
@@ -13,8 +13,8 @@
13
13
  */
14
14
 
15
15
  import { siteAbsoluteUrl } from "@jxsuite/schema/asset-paths";
16
- import { canonicalizeLocale, localeDirection, localeOfRoute } from "@jxsuite/schema/locale";
17
- import type { ResolvedI18n, TextDirection } from "@jxsuite/schema/locale";
16
+ import { canonicalizeLocale, localeDirection, translationSets } from "@jxsuite/schema/locale";
17
+ import type { ResolvedI18n, TextDirection, TranslationRoute } from "@jxsuite/schema/locale";
18
18
  import type { TranslationMember } from "@jxsuite/site/context";
19
19
 
20
20
  import { servedRoute } from "./static-host.ts";
@@ -34,6 +34,14 @@ export type { LocaleRouting, ResolvedI18n } from "@jxsuite/schema/locale";
34
34
  does: the studio and the cloud preview both have to answer "what language is this URL" and
35
35
  neither can import this package. Re-exported so nothing in the build had to change its import. */
36
36
  export { localeOfRoute } from "@jxsuite/schema/locale";
37
+ /* The translation sets live beside `resolveI18n` in `@jxsuite/schema/locale`: the studio's page index
38
+ and the live preview derive them from the same routes the build does, and cannot import this package. */
39
+ export { translationKey, translationSets } from "@jxsuite/schema/locale";
40
+ export type {
41
+ TranslationConflict,
42
+ TranslationRoute,
43
+ TranslationSets,
44
+ } from "@jxsuite/schema/locale";
37
45
 
38
46
  /**
39
47
  * Routes sitting outside the locale tree under `prefix-always`.
@@ -110,61 +118,12 @@ export function undeclaredLocalePrefix(
110
118
  return meant === undefined ? null : { meant, segment: first };
111
119
  }
112
120
 
113
- /**
114
- * A route's identity across locales: its path with the locale prefix removed.
115
- *
116
- * `/fr-ca/about/` and `/about/` share the key `about/`, which is what makes them translations of
117
- * one another. The directory layout is the default mapping, and it is enough whenever the paths are
118
- * parallel.
119
- *
120
- * A **localized slug** is not parallel, and that is the case this cannot derive: `/fr-ca/a-propos/`
121
- * shares nothing with `/about/`. A document says so itself with `$translationKey`, which overrides
122
- * this exactly as `$lang` overrides the locale its route implies (§13.4) — one key, and the whole
123
- * annotation follows.
124
- *
125
- * @param {string} urlPattern
126
- * @param {ResolvedI18n | null} i18n
127
- * @returns {string}
128
- */
129
- export function translationKey(urlPattern: string, i18n: ResolvedI18n | null): string {
130
- const segments = urlPattern.split("/").filter(Boolean);
131
- const canonical = canonicalizeLocale(segments[0]);
132
- if (i18n !== null && canonical !== null && i18n.locales.includes(canonical)) {
133
- return segments.slice(1).join("/");
134
- }
135
- return segments.join("/");
136
- }
137
-
138
121
  /** One `<link rel="alternate">` / sitemap `xhtml:link`. */
139
122
  export interface LocaleAlternate {
140
123
  hreflang: string;
141
124
  href: string;
142
125
  }
143
126
 
144
- /** A route as translation grouping sees it: its URL, and the key its document declared. */
145
- export interface TranslationRoute {
146
- /** From the document's `$translationKey`; absent when the key is derived from the path. */
147
- translationKey?: string | undefined;
148
- urlPattern: string;
149
- }
150
-
151
- /** Two routes claiming to be the same page in the same language. */
152
- export interface TranslationConflict {
153
- /** True when at least one of them said so with `$translationKey`. */
154
- declared: boolean;
155
- key: string;
156
- locale: string;
157
- /** In route order; the first is the one that keeps the set. */
158
- urlPatterns: string[];
159
- }
160
-
161
- /** Routes grouped into translation sets, and the collisions found while grouping them. */
162
- export interface TranslationSets {
163
- conflicts: TranslationConflict[];
164
- /** Keyed by `urlPattern`; members of one set share one array. */
165
- sets: Map<string, TranslationMember[]>;
166
- }
167
-
168
127
  /** The `lang` a page ships with, and its `dir` when that is worth writing down. */
169
128
  export interface PageLanguage {
170
129
  lang: string;
@@ -180,92 +139,6 @@ export interface PageLocaleContext {
180
139
  translations: readonly TranslationMember[];
181
140
  }
182
141
 
183
- /**
184
- * Group routes into translation sets: for each route, every route that is the same page in another
185
- * language, itself included, ordered by tag.
186
- *
187
- * One derivation, two readers. {@link localeAlternates} turns a set into absolute `<link
188
- * rel="alternate">` hrefs for crawlers; `injectContext` turns it into `$page.alternates` for a
189
- * language switcher a reader can click. Deriving it twice is how the two would come to disagree
190
- * about which pages are translations of one another — and the disagreement would be invisible,
191
- * because one of them is only ever read by a machine.
192
- *
193
- * **A set of one is kept here and dropped there.** A lone `hreflang` pointing at itself is noise in
194
- * `<head>` (§13.5), but a template asking "which languages is this page in" wants the honest
195
- * answer, and dropping the page itself would leave a switcher unable to mark where the reader is.
196
- *
197
- * URLs stay **site-absolute** rather than becoming absolute hrefs, because a switcher is a link
198
- * within the site and works before `url` is configured — which is every project during
199
- * development.
200
- *
201
- * @param {readonly TranslationRoute[]} routes - Concrete routes only
202
- * @param {ResolvedI18n | null} i18n
203
- * @returns {TranslationSets} Sets are keyed by `urlPattern`; members of one set share one array
204
- */
205
- export function translationSets(
206
- routes: readonly TranslationRoute[],
207
- i18n: ResolvedI18n | null,
208
- ): TranslationSets {
209
- const out = new Map<string, TranslationMember[]>();
210
- const conflicts: TranslationConflict[] = [];
211
- if (i18n === null) {
212
- return { conflicts, sets: out };
213
- }
214
-
215
- const sets = new Map<string, TranslationMember[]>();
216
- const declared = new Set<string>();
217
- for (const route of routes) {
218
- /*
219
- * Slashes at the ends are trimmed so a declared key can be written the way the URL reads.
220
- * The derived form has none — `/about/` reduces to `about` — and a `"/about"` that silently
221
- * matched nothing would look exactly like a key that was ignored.
222
- */
223
- const key =
224
- route.translationKey === undefined
225
- ? translationKey(route.urlPattern, i18n)
226
- : route.translationKey.replaceAll(/^\/+|\/+$/g, "");
227
- if (route.translationKey !== undefined) {
228
- declared.add(route.urlPattern);
229
- }
230
- const locale = localeOfRoute(route.urlPattern, i18n);
231
- if (locale === null) {
232
- continue;
233
- }
234
- const members = sets.get(key) ?? [];
235
- /*
236
- * A duplicate locale in one set means two routes claim to be the same page in one language.
237
- * The first wins, which keeps the set single-valued rather than advertising a contradiction;
238
- * the loser is keyed nowhere, so it carries no alternates and no switcher.
239
- *
240
- * How loudly to say so is the caller's decision, and it turns on which kind of collision it
241
- * is: a declared one is a promise the author wrote down and broke, while a derived one may be
242
- * a deliberate alias the compiler cannot see the reason for.
243
- */
244
- const taken = members.find((m) => m.locale === locale);
245
- if (taken === undefined) {
246
- members.push({ locale, urlPattern: route.urlPattern });
247
- } else {
248
- conflicts.push({
249
- declared: declared.has(taken.urlPattern) || route.translationKey !== undefined,
250
- key,
251
- locale,
252
- urlPatterns: [taken.urlPattern, route.urlPattern],
253
- });
254
- }
255
- sets.set(key, members);
256
- }
257
-
258
- for (const members of sets.values()) {
259
- const ordered = members.toSorted((a, b) =>
260
- a.locale === b.locale ? 0 : a.locale < b.locale ? -1 : 1,
261
- );
262
- for (const member of members) {
263
- out.set(member.urlPattern, ordered);
264
- }
265
- }
266
- return { conflicts, sets: out };
267
- }
268
-
269
142
  /**
270
143
  * Group routes into translation sets and give each one its alternates.
271
144
  *
@@ -17,12 +17,22 @@ import { resolve } from "node:path";
17
17
  import { resolveLayout as resolveLayoutWith } from "@jxsuite/site/layout";
18
18
  import type { JxDocument, ProjectConfig } from "@jxsuite/schema/types";
19
19
 
20
+ /**
21
+ * A rewrite of each layout as it is read, given the layout's absolute path. A site build lowers the
22
+ * layout's external `$switch` cases here, against the directory that declares them, before the
23
+ * merge forgets which file did.
24
+ */
25
+ export type LayoutTransform = (doc: JxDocument, layoutPath: string) => JxDocument;
26
+
20
27
  /**
21
28
  * A layout loader (`LayoutLoader` in `@jxsuite/site/layout`) over the project's own directory. It
22
29
  * reads synchronously, which is what lets {@link layoutChain} walk a chain without awaiting each
23
30
  * level, and a synchronous loader is still one `resolveLayout` accepts.
24
31
  */
25
- export function nodeLayoutLoader(projectRoot: string): (layoutRef: string) => JxDocument {
32
+ export function nodeLayoutLoader(
33
+ projectRoot: string,
34
+ transform?: LayoutTransform,
35
+ ): (layoutRef: string) => JxDocument {
26
36
  return (layoutRef: string) => {
27
37
  const layoutPath = resolve(projectRoot, layoutRef);
28
38
  if (!existsSync(layoutPath)) {
@@ -32,7 +42,12 @@ export function nodeLayoutLoader(projectRoot: string): (layoutRef: string) => Jx
32
42
  // Qualified here, as the layout is read, so its `#client` and the page's stay two modules
33
43
  // Through the merge (spec.md §23.2).
34
44
  const layout = parseNativeDocument(readFileSync(layoutPath, "utf8"), layoutPath);
35
- return qualifiedDocument(erasedDocument(layout, layoutPath), layoutPath, projectRoot);
45
+ const qualified = qualifiedDocument(
46
+ erasedDocument(layout, layoutPath),
47
+ layoutPath,
48
+ projectRoot,
49
+ );
50
+ return transform ? transform(qualified, layoutPath) : qualified;
36
51
  } catch (error) {
37
52
  throw new Error(`Invalid layout at ${layoutPath}: ${errorMessage(error)}`, {
38
53
  cause: error,
@@ -47,14 +62,16 @@ export function nodeLayoutLoader(projectRoot: string): (layoutRef: string) => Jx
47
62
  * @param {JxDocument} pageDoc - The raw page document
48
63
  * @param {ProjectConfig} projectConfig - Site configuration (for defaults.layout)
49
64
  * @param {string} projectRoot - Project root directory
65
+ * @param {LayoutTransform} [transform] - Applied to each layout as it is read
50
66
  * @returns {Promise<JxDocument>} The merged document (layout wrapping page content)
51
67
  */
52
68
  export function resolveLayout(
53
69
  pageDoc: JxDocument,
54
70
  projectConfig: ProjectConfig,
55
71
  projectRoot: string,
72
+ transform?: LayoutTransform,
56
73
  ): Promise<JxDocument> {
57
- return resolveLayoutWith(pageDoc, projectConfig, nodeLayoutLoader(projectRoot));
74
+ return resolveLayoutWith(pageDoc, projectConfig, nodeLayoutLoader(projectRoot, transform));
58
75
  }
59
76
 
60
77
  /**