@gitpagedocs/tools 1.1.67 → 1.1.69

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,11 +15,12 @@ The **shared business-logic core** of the [Git Page Docs](../README.md) monorepo
15
15
  | `errors/` | `AppError` + typed subclasses |
16
16
  | `filesystem/` | `FileService` (root-bounded list/read/write/search) |
17
17
  | `documentation/` | `DocumentationService`, `patchManagedRegion`, `DocUpdater` |
18
+ | `i18n/` | Language bundles (`site.languages` toggles in `config.json` + `langs/<lang>.json`): `loadConfigLanguageBundles`, `applyLanguageBundles` (fold into legacy `site.langmenu` / `translations`), `filterEnabledLanguages`, `splitLanguageBundles` (generator side); browser-safe |
18
19
  | `ports/` | Type-only contracts (logger, cache, crypto, security, config, ai) |
19
20
 
20
21
  ## Entry points (`exports`)
21
22
 
22
- `.` (full barrel) · `./ai` · `./errors` · `./ports` · `./crypto/web` · `./security/web` · `./cache/web` — the `web` subpaths are browser-safe (no `node:` imports) for the Next.js bundle.
23
+ `.` (full barrel) · `./ai` · `./errors` · `./i18n` · `./ports` · `./crypto/web` · `./security/web` · `./cache/web` — the `web` subpaths and `./i18n` are browser-safe (no `node:` imports) for the Next.js bundle.
23
24
 
24
25
  ## Usage
25
26
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gitpagedocs/tools",
3
- "version": "1.1.67",
3
+ "version": "1.1.69",
4
4
  "type": "module",
5
5
  "description": "Shared business-logic core for Git Page Docs (consumed by frontend, cli and mcp). Ships TypeScript source; consume via tsx or a TS-aware bundler.",
6
6
  "main": "./src/index.ts",
@@ -9,6 +9,7 @@
9
9
  ".": "./src/index.ts",
10
10
  "./ai": "./src/ai/index.ts",
11
11
  "./errors": "./src/errors/index.ts",
12
+ "./i18n": "./src/i18n/index.ts",
12
13
  "./ports": "./src/ports/index.ts",
13
14
  "./crypto/web": "./src/crypto/web.ts",
14
15
  "./security/web": "./src/security/web.ts",
@@ -9,8 +9,12 @@ export function resolveFetch(custom?: FetchLike): FetchLike {
9
9
  return f;
10
10
  }
11
11
 
12
- /** Yield the payload of each `data:` line from an SSE response body. */
13
- export async function* readSseData(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {
12
+ /**
13
+ * Yield every line of a streamed body, trimmed, as soon as it is complete;
14
+ * the (possibly empty) text after the last newline is yielded when the body ends.
15
+ * Chunk boundaries may fall anywhere, including inside a multi-byte character.
16
+ */
17
+ export async function* readLines(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {
14
18
  const reader = body.getReader();
15
19
  const decoder = new TextDecoder("utf-8");
16
20
  let buffer = "";
@@ -20,35 +24,23 @@ export async function* readSseData(body: ReadableStream<Uint8Array>): AsyncGener
20
24
  buffer += decoder.decode(value, { stream: true });
21
25
  const lines = buffer.split("\n");
22
26
  buffer = lines.pop() ?? "";
23
- for (const line of lines) {
24
- const trimmed = line.trim();
25
- if (trimmed.startsWith("data:")) {
26
- yield trimmed.slice(5).trim();
27
- }
28
- }
27
+ for (const line of lines) yield line.trim();
28
+ }
29
+ yield buffer.trim();
30
+ }
31
+
32
+ /** Yield the payload of each `data:` line from an SSE response body. */
33
+ export async function* readSseData(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {
34
+ for await (const line of readLines(body)) {
35
+ if (line.startsWith("data:")) yield line.slice(5).trim();
29
36
  }
30
- const tail = buffer.trim();
31
- if (tail.startsWith("data:")) yield tail.slice(5).trim();
32
37
  }
33
38
 
34
39
  /** Yield each complete JSON line from an NDJSON response body (e.g. Ollama). */
35
40
  export async function* readJsonLines(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {
36
- const reader = body.getReader();
37
- const decoder = new TextDecoder("utf-8");
38
- let buffer = "";
39
- for (;;) {
40
- const { value, done } = await reader.read();
41
- if (done) break;
42
- buffer += decoder.decode(value, { stream: true });
43
- const lines = buffer.split("\n");
44
- buffer = lines.pop() ?? "";
45
- for (const line of lines) {
46
- const trimmed = line.trim();
47
- if (trimmed) yield trimmed;
48
- }
41
+ for await (const line of readLines(body)) {
42
+ if (line) yield line;
49
43
  }
50
- const tail = buffer.trim();
51
- if (tail) yield tail;
52
44
  }
53
45
 
54
46
  export async function ensureOk(response: Response, providerLabel: string): Promise<Response> {
@@ -10,7 +10,7 @@ import type {
10
10
  } from "../../ports/ai";
11
11
  import type { ProviderSpec } from "../catalog";
12
12
  import { type FetchLike, ensureOk, readSseData, resolveFetch } from "../http/streaming";
13
- import { buildAuthHeaders, collect, resolveBaseUrl } from "./shared";
13
+ import { buildAuthHeaders, collect, resolveBaseUrl, toMultimodalParts } from "./shared";
14
14
 
15
15
  /** Anthropic Messages API adapter (content_block_delta streaming). */
16
16
  export class AnthropicProvider implements AIProvider {
@@ -26,17 +26,11 @@ export class AnthropicProvider implements AIProvider {
26
26
  }
27
27
 
28
28
  private mapMessage(msg: AiMessage): unknown {
29
- const images = (msg.attachments ?? []).filter((a) => a.kind === "image");
30
- if (images.length === 0) return { role: msg.role, content: msg.content };
31
- const content: unknown[] = [];
32
- if (msg.content) content.push({ type: "text", text: msg.content });
33
- for (const img of images) {
34
- content.push({
35
- type: "image",
36
- source: { type: "base64", media_type: img.mimeType, data: img.data },
37
- });
38
- }
39
- return { role: msg.role, content };
29
+ const parts = toMultimodalParts(msg, (img) => ({
30
+ type: "image",
31
+ source: { type: "base64", media_type: img.mimeType, data: img.data },
32
+ }));
33
+ return { role: msg.role, content: parts ?? msg.content };
40
34
  }
41
35
 
42
36
  async *stream(request: GenerateRequest, config: ProviderConfig): AsyncGenerator<string> {
@@ -1,4 +1,4 @@
1
- import type { AiMessage, GenerateRequest, ProviderConfig } from "../../ports/ai";
1
+ import type { AiAttachment, AiMessage, GenerateRequest, ProviderConfig } from "../../ports/ai";
2
2
  import type { ProviderSpec } from "../catalog";
3
3
  import { ProviderError } from "../../errors/app-error";
4
4
 
@@ -36,13 +36,20 @@ export function requireKey(spec: ProviderSpec, config: ProviderConfig): void {
36
36
  }
37
37
 
38
38
  export function resolveBaseUrl(spec: ProviderSpec, config: ProviderConfig): string {
39
- const base = (config.baseUrl ?? spec.baseUrl).replace(/\/+$/, "");
39
+ const base = trimTrailingSlashes(config.baseUrl ?? spec.baseUrl);
40
40
  if (spec.requiresBaseUrl && !config.baseUrl && !spec.baseUrl) {
41
41
  throw new ProviderError(`${spec.label} requires a baseUrl.`, { details: { provider: spec.id } });
42
42
  }
43
43
  return base;
44
44
  }
45
45
 
46
+ /** Drop trailing `/` so request paths can be appended with a single separator. */
47
+ function trimTrailingSlashes(value: string): string {
48
+ let end = value.length;
49
+ while (end > 0 && value[end - 1] === "/") end -= 1;
50
+ return value.slice(0, end);
51
+ }
52
+
46
53
  /** OpenAI chat-completions message shape (text + optional image parts). */
47
54
  export function toOpenAiMessages(request: GenerateRequest): unknown[] {
48
55
  const out: unknown[] = [];
@@ -54,14 +61,29 @@ export function toOpenAiMessages(request: GenerateRequest): unknown[] {
54
61
  }
55
62
 
56
63
  function mapOpenAiMessage(msg: AiMessage): unknown {
64
+ const parts = toMultimodalParts(msg, (img) => ({
65
+ type: "image_url",
66
+ image_url: { url: `data:${img.mimeType};base64,${img.data}` },
67
+ }));
68
+ return { role: msg.role, content: parts ?? msg.content };
69
+ }
70
+
71
+ /**
72
+ * Splits a message into multimodal parts: its text (when present) followed by
73
+ * one part per image attachment, built by `toImagePart`. A message without
74
+ * images yields null so callers keep the plain `content` string the APIs
75
+ * expect for text-only turns.
76
+ */
77
+ export function toMultimodalParts(
78
+ msg: AiMessage,
79
+ toImagePart: (image: AiAttachment) => unknown,
80
+ ): unknown[] | null {
57
81
  const images = (msg.attachments ?? []).filter((a) => a.kind === "image");
58
- if (images.length === 0) return { role: msg.role, content: msg.content };
59
- const content: unknown[] = [];
60
- if (msg.content) content.push({ type: "text", text: msg.content });
61
- for (const img of images) {
62
- content.push({ type: "image_url", image_url: { url: `data:${img.mimeType};base64,${img.data}` } });
63
- }
64
- return { role: msg.role, content };
82
+ if (images.length === 0) return null;
83
+ const parts: unknown[] = [];
84
+ if (msg.content) parts.push({ type: "text", text: msg.content });
85
+ for (const image of images) parts.push(toImagePart(image));
86
+ return parts;
65
87
  }
66
88
 
67
89
  /** Drain an async iterable of text deltas into a single string. */
@@ -68,7 +68,7 @@ export class WebStorageCache<TValue = unknown> implements Cache<TValue> {
68
68
  const toRemove: string[] = [];
69
69
  for (let i = 0; i < this.storage.length; i += 1) {
70
70
  const k = this.storage.key(i);
71
- if (k && k.startsWith(this.prefix)) toRemove.push(k);
71
+ if (k?.startsWith(this.prefix)) toRemove.push(k);
72
72
  }
73
73
  for (const k of toRemove) this.storage.removeItem(k);
74
74
  }
@@ -57,6 +57,8 @@ export async function verifyDocAccess(
57
57
  function hexEqual(a: string, b: string): boolean {
58
58
  if (a.length !== b.length) return false;
59
59
  let diff = 0;
60
- for (let i = 0; i < a.length; i += 1) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
60
+ // Hex digits are single code units, so codePointAt(i) never straddles a pair
61
+ // and is never undefined for i < length; the fallback only satisfies the type.
62
+ for (let i = 0; i < a.length; i += 1) diff |= (a.codePointAt(i) ?? 0) ^ (b.codePointAt(i) ?? 0);
61
63
  return diff === 0;
62
64
  }
@@ -7,14 +7,16 @@ const DEFAULT_ITERATIONS = 210_000;
7
7
 
8
8
  function toBase64(bytes: Uint8Array): string {
9
9
  let binary = "";
10
- for (let i = 0; i < bytes.length; i += 1) binary += String.fromCharCode(bytes[i]);
10
+ for (const byte of bytes) binary += String.fromCodePoint(byte);
11
11
  return btoa(binary);
12
12
  }
13
13
 
14
14
  function fromBase64(b64: string): Uint8Array<ArrayBuffer> {
15
15
  const binary = atob(b64);
16
16
  const out = new Uint8Array(binary.length);
17
- for (let i = 0; i < binary.length; i += 1) out[i] = binary.charCodeAt(i);
17
+ // atob yields one Latin-1 code unit per byte, so codePointAt(i) is that byte
18
+ // (never undefined for i < length; the fallback only satisfies the type).
19
+ for (let i = 0; i < binary.length; i += 1) out[i] = binary.codePointAt(i) ?? 0;
18
20
  return out;
19
21
  }
20
22
 
@@ -28,6 +28,6 @@ export function patchManagedRegion(existing: string, generated: string): PatchRe
28
28
  return { content: `${before}${block}${after}`, replaced: true };
29
29
  }
30
30
 
31
- const separator = existing.trim() ? `${existing.replace(/\s+$/, "")}\n\n` : "";
31
+ const separator = existing.trim() ? `${existing.trimEnd()}\n\n` : "";
32
32
  return { content: `${separator}${block}\n`, replaced: false };
33
33
  }
@@ -24,7 +24,41 @@ export interface SearchMatch {
24
24
  readonly text: string;
25
25
  }
26
26
 
27
- const TEXT_EXT = /\.(md|markdown|mdx|txt|json|ya?ml|ts|tsx|js|jsx|mjs|cjs|css|scss|html?|svg|toml|env)$/i;
27
+ /** Extensions (lower-case, dot included) that `search()` scans by default. */
28
+ const TEXT_EXTENSIONS = new Set([
29
+ ".md", ".markdown", ".mdx", ".txt", ".json", ".yml", ".yaml",
30
+ ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",
31
+ ".css", ".scss", ".htm", ".html", ".svg", ".toml", ".env",
32
+ ]);
33
+
34
+ /**
35
+ * Whether a repo-relative file path carries a text extension. The suffix after
36
+ * the last dot is compared, so a dotfile such as `.env` counts and a dot in a
37
+ * folder name (`dir.x/file`) does not.
38
+ */
39
+ function isTextFile(file: string): boolean {
40
+ const dot = file.lastIndexOf(".");
41
+ return dot !== -1 && TEXT_EXTENSIONS.has(file.slice(dot).toLowerCase());
42
+ }
43
+
44
+ /** Line matches of `needle` (already lower-cased) in one file, at most `limit`. */
45
+ function collectLineMatches(file: string, content: string, needle: string, limit: number): SearchMatch[] {
46
+ const found: SearchMatch[] = [];
47
+ const lines = content.split("\n");
48
+ for (let i = 0; i < lines.length && found.length < limit; i += 1) {
49
+ if (lines[i].toLowerCase().includes(needle)) {
50
+ found.push({ file, line: i + 1, text: lines[i].trim().slice(0, 240) });
51
+ }
52
+ }
53
+ return found;
54
+ }
55
+
56
+ /** Plain UTF-16 code-unit order (the default `sort()` order), independent of locale. */
57
+ function compareCodeUnits(a: string, b: string): number {
58
+ if (a < b) return -1;
59
+ if (a > b) return 1;
60
+ return 0;
61
+ }
28
62
 
29
63
  /**
30
64
  * Root-bounded filesystem service. All paths are resolved relative to `root`
@@ -69,7 +103,7 @@ export class FileService {
69
103
  };
70
104
 
71
105
  await walk(start);
72
- return out.sort();
106
+ return out.sort(compareCodeUnits);
73
107
  }
74
108
 
75
109
  async read(relativePath: string, maxBytes = 512_000): Promise<string> {
@@ -90,6 +124,21 @@ export class FileService {
90
124
  return this.toRel(abs);
91
125
  }
92
126
 
127
+ /** Directories are skipped; an explicit extension filter replaces the text-extension default. */
128
+ private static isSearchable(entry: string, extension?: string): boolean {
129
+ if (entry.endsWith("/")) return false;
130
+ return extension ? entry.endsWith(extension) : isTextFile(entry);
131
+ }
132
+
133
+ /** File content for searching, or undefined when it is missing, too large or unreadable. */
134
+ private async readForSearch(file: string, maxFileBytes: number): Promise<string | undefined> {
135
+ try {
136
+ return await this.read(file, maxFileBytes);
137
+ } catch {
138
+ return undefined;
139
+ }
140
+ }
141
+
93
142
  async search(query: string, options: SearchOptions = {}): Promise<SearchMatch[]> {
94
143
  if (!query.trim()) throw new ValidationError("Search query must not be empty.");
95
144
  const { extension, maxResults = 200, maxFileBytes = 512_000 } = options;
@@ -98,23 +147,11 @@ export class FileService {
98
147
  const needle = query.toLowerCase();
99
148
 
100
149
  for (const file of files) {
101
- if (file.endsWith("/")) continue;
102
- if (extension && !file.endsWith(extension)) continue;
103
- if (!extension && !TEXT_EXT.test(file)) continue;
104
150
  if (matches.length >= maxResults) break;
105
- let content: string;
106
- try {
107
- content = await this.read(file, maxFileBytes);
108
- } catch {
109
- continue;
110
- }
111
- const lines = content.split("\n");
112
- for (let i = 0; i < lines.length; i += 1) {
113
- if (lines[i].toLowerCase().includes(needle)) {
114
- matches.push({ file, line: i + 1, text: lines[i].trim().slice(0, 240) });
115
- if (matches.length >= maxResults) break;
116
- }
117
- }
151
+ if (!FileService.isSearchable(file, extension)) continue;
152
+ const content = await this.readForSearch(file, maxFileBytes);
153
+ if (content === undefined) continue;
154
+ matches.push(...collectLineMatches(file, content, needle, maxResults - matches.length));
118
155
  }
119
156
  return matches;
120
157
  }
@@ -0,0 +1,36 @@
1
+ export {
2
+ DEFAULT_LANGS_DIR,
3
+ DEFAULT_LANGS_MANIFEST_PATH,
4
+ LANGS_DIRNAME,
5
+ LANGS_MANIFEST_FILENAME,
6
+ applyLanguageBundles,
7
+ buildLanguageToggles,
8
+ filterEnabledLanguages,
9
+ getEnabledLanguages,
10
+ getLanguageBundlePath,
11
+ getSiteLanguageToggles,
12
+ isLanguageCode,
13
+ isLanguageEnabled,
14
+ loadConfigLanguageBundles,
15
+ loadLanguageBundles,
16
+ parseLanguageBundle,
17
+ parseLanguageManifest,
18
+ parseLanguageToggles,
19
+ resolveBundleLanguages,
20
+ splitLanguageBundles,
21
+ } from "./language-bundles";
22
+ export type {
23
+ InlineLangMenu,
24
+ InlineTranslationSection,
25
+ InlineTranslations,
26
+ JsonReader,
27
+ LanguageBundle,
28
+ LanguageBundleMap,
29
+ LanguageManifest,
30
+ LanguageStrings,
31
+ LanguageToggles,
32
+ LoadLanguageBundlesOptions,
33
+ LocalizableConfig,
34
+ LocalizableSite,
35
+ TranslationSections,
36
+ } from "./language-bundles";
@@ -0,0 +1,289 @@
1
+ /**
2
+ * Language bundles — the UI strings of a gitpagedocs site, one JSON file per
3
+ * language, switched on and off from `config.json`:
4
+ *
5
+ * gitpagedocs/config.json { "site": { "languages": { "en": true, "pt": true, "es": false } } }
6
+ * gitpagedocs/langs/<lang>.json { "langmenu": {...}, "translations": {...} }
7
+ *
8
+ * `site.languages` is the only place a language is enabled (`true`) or disabled
9
+ * (`false`): a disabled language has its bundle skipped and is hidden from the
10
+ * language selector, even when its docs exist. A language the map does not
11
+ * mention stays enabled, so old configs keep every content language they ship.
12
+ *
13
+ * Historically the strings lived inline in `config.json` (`site.langmenu` keyed
14
+ * by language and `translations.<section>.<key>` keyed by language), and
15
+ * release 1.1.68 listed the languages in a separate `gitpagedocs/langs.json`
16
+ * manifest. Both still load: `applyLanguageBundles` folds the bundles back into
17
+ * the inline shape, so every consumer keeps reading `site.langmenu` /
18
+ * `translations` unchanged, and the manifest is read only when `config.json`
19
+ * carries no `site.languages`. Bundles win over inline strings.
20
+ */
21
+
22
+ export const LANGS_DIRNAME = "langs";
23
+ export const DEFAULT_LANGS_DIR = `gitpagedocs/${LANGS_DIRNAME}`;
24
+ /** Legacy (1.1.68) manifest; superseded by `site.languages` in config.json. */
25
+ export const LANGS_MANIFEST_FILENAME = "langs.json";
26
+ export const DEFAULT_LANGS_MANIFEST_PATH = `gitpagedocs/${LANGS_MANIFEST_FILENAME}`;
27
+
28
+ /** Language codes become file names, so they are kept to a safe alphabet. */
29
+ const LANGUAGE_CODE_PATTERN = /^[A-Za-z0-9]{2,8}(?:[-_][A-Za-z0-9]{1,8})?$/;
30
+
31
+ export type LanguageStrings = Record<string, string>;
32
+ export type TranslationSections = Record<string, LanguageStrings>;
33
+
34
+ /** `site.languages`: language code → enabled flag, in menu order. */
35
+ export type LanguageToggles = Record<string, boolean>;
36
+
37
+ /** Legacy `gitpagedocs/langs.json` shape. */
38
+ export interface LanguageManifest {
39
+ languages: string[];
40
+ }
41
+
42
+ export interface LanguageBundle {
43
+ langmenu?: LanguageStrings;
44
+ translations?: TranslationSections;
45
+ }
46
+
47
+ export type LanguageBundleMap = Record<string, LanguageBundle>;
48
+
49
+ /**
50
+ * Legacy inline shapes: `langmenu[lang][key]` and `translations[section][key][lang]`.
51
+ * Sections and keys may be absent, matching the optional fields of typed configs.
52
+ */
53
+ export type InlineLangMenu = Record<string, LanguageStrings>;
54
+ export type InlineTranslationSection = { [key: string]: LanguageStrings | undefined };
55
+ export type InlineTranslations = { [section: string]: InlineTranslationSection | undefined };
56
+
57
+ export interface LocalizableSite {
58
+ defaultLanguage?: string;
59
+ languages?: LanguageToggles;
60
+ langmenu?: InlineLangMenu;
61
+ supportedLanguages?: string[];
62
+ }
63
+
64
+ export interface LocalizableConfig {
65
+ site?: LocalizableSite;
66
+ translations?: InlineTranslations;
67
+ }
68
+
69
+ /** Reads a repo-relative JSON file; resolves null when it is missing or invalid. */
70
+ export type JsonReader = (relativePath: string) => Promise<unknown>;
71
+
72
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
73
+ return typeof value === "object" && value !== null && !Array.isArray(value);
74
+ }
75
+
76
+ function isStringRecord(value: unknown): value is LanguageStrings {
77
+ return isPlainObject(value) && Object.values(value).every((entry) => typeof entry === "string");
78
+ }
79
+
80
+ export function isLanguageCode(value: unknown): value is string {
81
+ return typeof value === "string" && LANGUAGE_CODE_PATTERN.test(value);
82
+ }
83
+
84
+ export function getLanguageBundlePath(language: string, langsDir: string = DEFAULT_LANGS_DIR): string {
85
+ return `${langsDir}/${language}.json`;
86
+ }
87
+
88
+ /** `{ en: true, pt: true }` for a language list; the generator's view of `site.languages`. */
89
+ export function buildLanguageToggles(languages: readonly string[], enabled = true): LanguageToggles {
90
+ const toggles: LanguageToggles = {};
91
+ for (const language of languages) toggles[language] = enabled;
92
+ return toggles;
93
+ }
94
+
95
+ /**
96
+ * Parses `site.languages`. Only valid codes with a boolean flag are kept, in
97
+ * key order; resolves null when nothing usable is there (legacy configs).
98
+ */
99
+ export function parseLanguageToggles(raw: unknown): LanguageToggles | null {
100
+ if (!isPlainObject(raw)) return null;
101
+ const toggles: LanguageToggles = {};
102
+ for (const [language, enabled] of Object.entries(raw)) {
103
+ if (isLanguageCode(language) && typeof enabled === "boolean") toggles[language] = enabled;
104
+ }
105
+ return Object.keys(toggles).length > 0 ? toggles : null;
106
+ }
107
+
108
+ export function getEnabledLanguages(toggles: LanguageToggles | null | undefined): string[] {
109
+ return Object.entries(toggles ?? {})
110
+ .filter(([, enabled]) => enabled)
111
+ .map(([language]) => language);
112
+ }
113
+
114
+ /** Only an explicit `false` disables a language; unknown codes stay enabled. */
115
+ export function isLanguageEnabled(toggles: LanguageToggles | null | undefined, language: string): boolean {
116
+ return toggles?.[language] !== false;
117
+ }
118
+
119
+ /**
120
+ * Drops the disabled languages from a content-derived list, keeping its order.
121
+ * A site can never end up without a language: when every entry is disabled the
122
+ * preferred (default) language survives, else the first one.
123
+ */
124
+ export function filterEnabledLanguages<T extends string>(
125
+ languages: readonly T[],
126
+ toggles: LanguageToggles | null | undefined,
127
+ preferred?: T,
128
+ ): T[] {
129
+ const enabled = languages.filter((language) => isLanguageEnabled(toggles, language));
130
+ if (enabled.length > 0 || languages.length === 0) return enabled;
131
+ const fallback = preferred !== undefined && languages.includes(preferred) ? preferred : languages[0];
132
+ return [fallback];
133
+ }
134
+
135
+ export function getSiteLanguageToggles(config: LocalizableConfig): LanguageToggles | null {
136
+ return parseLanguageToggles(config.site?.languages);
137
+ }
138
+
139
+ /** The bundles a config asks for: its enabled toggles, or null when it has none (legacy). */
140
+ export function resolveBundleLanguages(config: LocalizableConfig): string[] | null {
141
+ const toggles = getSiteLanguageToggles(config);
142
+ return toggles ? getEnabledLanguages(toggles) : null;
143
+ }
144
+
145
+ export function parseLanguageManifest(raw: unknown): LanguageManifest | null {
146
+ if (!isPlainObject(raw) || !Array.isArray(raw.languages)) return null;
147
+ const languages = Array.from(new Set(raw.languages.filter(isLanguageCode)));
148
+ return languages.length > 0 ? { languages } : null;
149
+ }
150
+
151
+ function parseTranslationSections(raw: unknown): TranslationSections | undefined {
152
+ if (!isPlainObject(raw)) return undefined;
153
+ const sections: TranslationSections = {};
154
+ for (const [section, strings] of Object.entries(raw)) {
155
+ if (isStringRecord(strings)) sections[section] = strings;
156
+ }
157
+ return sections;
158
+ }
159
+
160
+ export function parseLanguageBundle(raw: unknown): LanguageBundle | null {
161
+ if (!isPlainObject(raw)) return null;
162
+ const bundle: LanguageBundle = {};
163
+ if (isStringRecord(raw.langmenu)) bundle.langmenu = raw.langmenu;
164
+ const translations = parseTranslationSections(raw.translations);
165
+ if (translations) bundle.translations = translations;
166
+ return bundle;
167
+ }
168
+
169
+ export interface LoadLanguageBundlesOptions {
170
+ /** Languages to load (the enabled `site.languages`). Without it the legacy manifest is consulted. */
171
+ languages?: readonly string[];
172
+ manifestPath?: string;
173
+ langsDir?: string;
174
+ }
175
+
176
+ async function readLegacyManifestLanguages(readJson: JsonReader, manifestPath: string): Promise<string[] | null> {
177
+ const manifest = parseLanguageManifest(await readJson(manifestPath));
178
+ return manifest ? manifest.languages : null;
179
+ }
180
+
181
+ /**
182
+ * Loads one bundle per requested language. Resolves null when nothing is
183
+ * requested (legacy inline config without a manifest); bundles that are
184
+ * missing or malformed are skipped so one broken file never takes the other
185
+ * languages down.
186
+ */
187
+ export async function loadLanguageBundles(
188
+ readJson: JsonReader,
189
+ options: LoadLanguageBundlesOptions = {},
190
+ ): Promise<LanguageBundleMap | null> {
191
+ const languages =
192
+ options.languages ?? (await readLegacyManifestLanguages(readJson, options.manifestPath ?? DEFAULT_LANGS_MANIFEST_PATH));
193
+ if (!languages || languages.length === 0) return null;
194
+
195
+ const entries = await Promise.all(
196
+ languages.filter(isLanguageCode).map(async (language) => {
197
+ const bundle = parseLanguageBundle(await readJson(getLanguageBundlePath(language, options.langsDir)));
198
+ return [language, bundle] as const;
199
+ }),
200
+ );
201
+
202
+ const bundles: LanguageBundleMap = {};
203
+ for (const [language, bundle] of entries) {
204
+ if (bundle) bundles[language] = bundle;
205
+ }
206
+ return Object.keys(bundles).length > 0 ? bundles : null;
207
+ }
208
+
209
+ /** Loads the bundles `config.json` enables through `site.languages` (legacy manifest as fallback). */
210
+ export function loadConfigLanguageBundles(
211
+ config: LocalizableConfig,
212
+ readJson: JsonReader,
213
+ options: Omit<LoadLanguageBundlesOptions, "languages"> = {},
214
+ ): Promise<LanguageBundleMap | null> {
215
+ return loadLanguageBundles(readJson, { ...options, languages: resolveBundleLanguages(config) ?? undefined });
216
+ }
217
+
218
+ function mergeLangMenu(inline: InlineLangMenu | undefined, bundles: LanguageBundleMap): InlineLangMenu {
219
+ const merged: InlineLangMenu = { ...inline };
220
+ for (const [language, bundle] of Object.entries(bundles)) {
221
+ merged[language] = { ...inline?.[language], ...bundle.langmenu };
222
+ }
223
+ return merged;
224
+ }
225
+
226
+ function cloneTranslations(inline: InlineTranslations | undefined): Record<string, InlineTranslationSection> {
227
+ const cloned: Record<string, InlineTranslationSection> = {};
228
+ for (const [section, keys] of Object.entries(inline ?? {})) {
229
+ if (!keys) continue;
230
+ cloned[section] = {};
231
+ for (const [key, byLanguage] of Object.entries(keys)) {
232
+ if (byLanguage) cloned[section][key] = { ...byLanguage };
233
+ }
234
+ }
235
+ return cloned;
236
+ }
237
+
238
+ function mergeTranslations(inline: InlineTranslations | undefined, bundles: LanguageBundleMap): InlineTranslations {
239
+ const merged = cloneTranslations(inline);
240
+ for (const [language, bundle] of Object.entries(bundles)) {
241
+ for (const [section, strings] of Object.entries(bundle.translations ?? {})) {
242
+ const target = (merged[section] ??= {});
243
+ for (const [key, text] of Object.entries(strings)) {
244
+ target[key] = { ...target[key], [language]: text };
245
+ }
246
+ }
247
+ }
248
+ return merged;
249
+ }
250
+
251
+ /**
252
+ * Folds bundles into the legacy inline shape. The loaded bundles define
253
+ * `site.supportedLanguages`; `site.languages` and inline strings survive (the
254
+ * latter only for keys a bundle does not provide).
255
+ */
256
+ export function applyLanguageBundles<T extends LocalizableConfig>(config: T, bundles: LanguageBundleMap | null): T {
257
+ if (!bundles || Object.keys(bundles).length === 0) return config;
258
+ return {
259
+ ...config,
260
+ site: {
261
+ ...config.site,
262
+ langmenu: mergeLangMenu(config.site?.langmenu, bundles),
263
+ supportedLanguages: Object.keys(bundles),
264
+ },
265
+ translations: mergeTranslations(config.translations, bundles),
266
+ };
267
+ }
268
+
269
+ /** The generator-side inverse of `applyLanguageBundles`: one bundle per language. */
270
+ export function splitLanguageBundles(
271
+ languages: readonly string[],
272
+ langmenu: InlineLangMenu,
273
+ translations: InlineTranslations,
274
+ ): LanguageBundleMap {
275
+ const bundles: LanguageBundleMap = {};
276
+ for (const language of languages) {
277
+ const sections: TranslationSections = {};
278
+ for (const [section, keys] of Object.entries(translations)) {
279
+ const strings: LanguageStrings = {};
280
+ for (const [key, byLanguage] of Object.entries(keys ?? {})) {
281
+ const text = byLanguage?.[language];
282
+ if (typeof text === "string") strings[key] = text;
283
+ }
284
+ if (Object.keys(strings).length > 0) sections[section] = strings;
285
+ }
286
+ bundles[language] = { langmenu: { ...langmenu[language] }, translations: sections };
287
+ }
288
+ return bundles;
289
+ }
package/src/index.ts CHANGED
@@ -16,6 +16,7 @@ export * from "./security";
16
16
  export * from "./config";
17
17
  export * from "./constants";
18
18
  export * from "./platform";
19
+ export * from "./i18n";
19
20
 
20
21
  // Phase 5 — shared AI system.
21
22
  export * from "./ai";
@@ -10,7 +10,7 @@ export class WebStorageVaultStorage implements VaultStorage {
10
10
 
11
11
  async load(): Promise<string | null> {
12
12
  const raw = this.storage.getItem(this.key);
13
- return raw && raw.trim() ? raw : null;
13
+ return raw?.trim() ? raw : null;
14
14
  }
15
15
 
16
16
  async save(serialized: string): Promise<void> {