@gitpagedocs/tools 1.1.68 → 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 +1 -1
- package/package.json +1 -1
- package/src/ai/http/streaming.ts +17 -25
- package/src/ai/providers/anthropic-provider.ts +6 -12
- package/src/ai/providers/shared.ts +31 -9
- package/src/cache/web-storage-cache.ts +1 -1
- package/src/crypto/doc-access.ts +3 -1
- package/src/crypto/web-crypto-service.ts +4 -2
- package/src/documentation/marker-patcher.ts +1 -1
- package/src/filesystem/file-service.ts +55 -18
- package/src/i18n/index.ts +9 -1
- package/src/i18n/language-bundles.ts +108 -23
- package/src/security/web-storage-vault-storage.ts +1 -1
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@ 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 (`
|
|
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 |
|
|
19
19
|
| `ports/` | Type-only contracts (logger, cache, crypto, security, config, ai) |
|
|
20
20
|
|
|
21
21
|
## Entry points (`exports`)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gitpagedocs/tools",
|
|
3
|
-
"version": "1.1.
|
|
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",
|
package/src/ai/http/streaming.ts
CHANGED
|
@@ -9,8 +9,12 @@ export function resolveFetch(custom?: FetchLike): FetchLike {
|
|
|
9
9
|
return f;
|
|
10
10
|
}
|
|
11
11
|
|
|
12
|
-
/**
|
|
13
|
-
|
|
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
|
-
|
|
25
|
-
|
|
26
|
-
|
|
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
|
|
37
|
-
|
|
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
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
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)
|
|
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
|
|
59
|
-
const
|
|
60
|
-
if (msg.content)
|
|
61
|
-
for (const
|
|
62
|
-
|
|
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
|
|
71
|
+
if (k?.startsWith(this.prefix)) toRemove.push(k);
|
|
72
72
|
}
|
|
73
73
|
for (const k of toRemove) this.storage.removeItem(k);
|
|
74
74
|
}
|
package/src/crypto/doc-access.ts
CHANGED
|
@@ -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
|
-
|
|
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 (
|
|
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
|
-
|
|
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.
|
|
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
|
-
|
|
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
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
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
|
}
|
package/src/i18n/index.ts
CHANGED
|
@@ -4,12 +4,19 @@ export {
|
|
|
4
4
|
LANGS_DIRNAME,
|
|
5
5
|
LANGS_MANIFEST_FILENAME,
|
|
6
6
|
applyLanguageBundles,
|
|
7
|
-
|
|
7
|
+
buildLanguageToggles,
|
|
8
|
+
filterEnabledLanguages,
|
|
9
|
+
getEnabledLanguages,
|
|
8
10
|
getLanguageBundlePath,
|
|
11
|
+
getSiteLanguageToggles,
|
|
9
12
|
isLanguageCode,
|
|
13
|
+
isLanguageEnabled,
|
|
14
|
+
loadConfigLanguageBundles,
|
|
10
15
|
loadLanguageBundles,
|
|
11
16
|
parseLanguageBundle,
|
|
12
17
|
parseLanguageManifest,
|
|
18
|
+
parseLanguageToggles,
|
|
19
|
+
resolveBundleLanguages,
|
|
13
20
|
splitLanguageBundles,
|
|
14
21
|
} from "./language-bundles";
|
|
15
22
|
export type {
|
|
@@ -21,6 +28,7 @@ export type {
|
|
|
21
28
|
LanguageBundleMap,
|
|
22
29
|
LanguageManifest,
|
|
23
30
|
LanguageStrings,
|
|
31
|
+
LanguageToggles,
|
|
24
32
|
LoadLanguageBundlesOptions,
|
|
25
33
|
LocalizableConfig,
|
|
26
34
|
LocalizableSite,
|
|
@@ -1,21 +1,29 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Language bundles — the UI strings of a gitpagedocs site, one JSON file per
|
|
3
|
-
* language,
|
|
3
|
+
* language, switched on and off from `config.json`:
|
|
4
4
|
*
|
|
5
|
-
* gitpagedocs/
|
|
5
|
+
* gitpagedocs/config.json { "site": { "languages": { "en": true, "pt": true, "es": false } } }
|
|
6
6
|
* gitpagedocs/langs/<lang>.json { "langmenu": {...}, "translations": {...} }
|
|
7
7
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
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.
|
|
13
20
|
*/
|
|
14
21
|
|
|
15
|
-
export const LANGS_MANIFEST_FILENAME = "langs.json";
|
|
16
22
|
export const LANGS_DIRNAME = "langs";
|
|
17
|
-
export const DEFAULT_LANGS_MANIFEST_PATH = `gitpagedocs/${LANGS_MANIFEST_FILENAME}`;
|
|
18
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}`;
|
|
19
27
|
|
|
20
28
|
/** Language codes become file names, so they are kept to a safe alphabet. */
|
|
21
29
|
const LANGUAGE_CODE_PATTERN = /^[A-Za-z0-9]{2,8}(?:[-_][A-Za-z0-9]{1,8})?$/;
|
|
@@ -23,6 +31,10 @@ const LANGUAGE_CODE_PATTERN = /^[A-Za-z0-9]{2,8}(?:[-_][A-Za-z0-9]{1,8})?$/;
|
|
|
23
31
|
export type LanguageStrings = Record<string, string>;
|
|
24
32
|
export type TranslationSections = Record<string, LanguageStrings>;
|
|
25
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. */
|
|
26
38
|
export interface LanguageManifest {
|
|
27
39
|
languages: string[];
|
|
28
40
|
}
|
|
@@ -43,6 +55,8 @@ export type InlineTranslationSection = { [key: string]: LanguageStrings | undefi
|
|
|
43
55
|
export type InlineTranslations = { [section: string]: InlineTranslationSection | undefined };
|
|
44
56
|
|
|
45
57
|
export interface LocalizableSite {
|
|
58
|
+
defaultLanguage?: string;
|
|
59
|
+
languages?: LanguageToggles;
|
|
46
60
|
langmenu?: InlineLangMenu;
|
|
47
61
|
supportedLanguages?: string[];
|
|
48
62
|
}
|
|
@@ -71,6 +85,63 @@ export function getLanguageBundlePath(language: string, langsDir: string = DEFAU
|
|
|
71
85
|
return `${langsDir}/${language}.json`;
|
|
72
86
|
}
|
|
73
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
|
+
|
|
74
145
|
export function parseLanguageManifest(raw: unknown): LanguageManifest | null {
|
|
75
146
|
if (!isPlainObject(raw) || !Array.isArray(raw.languages)) return null;
|
|
76
147
|
const languages = Array.from(new Set(raw.languages.filter(isLanguageCode)));
|
|
@@ -96,24 +167,33 @@ export function parseLanguageBundle(raw: unknown): LanguageBundle | null {
|
|
|
96
167
|
}
|
|
97
168
|
|
|
98
169
|
export interface LoadLanguageBundlesOptions {
|
|
170
|
+
/** Languages to load (the enabled `site.languages`). Without it the legacy manifest is consulted. */
|
|
171
|
+
languages?: readonly string[];
|
|
99
172
|
manifestPath?: string;
|
|
100
173
|
langsDir?: string;
|
|
101
174
|
}
|
|
102
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
|
+
|
|
103
181
|
/**
|
|
104
|
-
* Loads
|
|
105
|
-
*
|
|
106
|
-
* are skipped so one broken file never takes the other
|
|
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.
|
|
107
186
|
*/
|
|
108
187
|
export async function loadLanguageBundles(
|
|
109
188
|
readJson: JsonReader,
|
|
110
189
|
options: LoadLanguageBundlesOptions = {},
|
|
111
190
|
): Promise<LanguageBundleMap | null> {
|
|
112
|
-
const
|
|
113
|
-
|
|
191
|
+
const languages =
|
|
192
|
+
options.languages ?? (await readLegacyManifestLanguages(readJson, options.manifestPath ?? DEFAULT_LANGS_MANIFEST_PATH));
|
|
193
|
+
if (!languages || languages.length === 0) return null;
|
|
114
194
|
|
|
115
195
|
const entries = await Promise.all(
|
|
116
|
-
|
|
196
|
+
languages.filter(isLanguageCode).map(async (language) => {
|
|
117
197
|
const bundle = parseLanguageBundle(await readJson(getLanguageBundlePath(language, options.langsDir)));
|
|
118
198
|
return [language, bundle] as const;
|
|
119
199
|
}),
|
|
@@ -126,6 +206,15 @@ export async function loadLanguageBundles(
|
|
|
126
206
|
return Object.keys(bundles).length > 0 ? bundles : null;
|
|
127
207
|
}
|
|
128
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
|
+
|
|
129
218
|
function mergeLangMenu(inline: InlineLangMenu | undefined, bundles: LanguageBundleMap): InlineLangMenu {
|
|
130
219
|
const merged: InlineLangMenu = { ...inline };
|
|
131
220
|
for (const [language, bundle] of Object.entries(bundles)) {
|
|
@@ -160,9 +249,9 @@ function mergeTranslations(inline: InlineTranslations | undefined, bundles: Lang
|
|
|
160
249
|
}
|
|
161
250
|
|
|
162
251
|
/**
|
|
163
|
-
* Folds bundles into the legacy inline shape. The
|
|
164
|
-
* `site.supportedLanguages`; inline strings survive
|
|
165
|
-
* does not provide.
|
|
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).
|
|
166
255
|
*/
|
|
167
256
|
export function applyLanguageBundles<T extends LocalizableConfig>(config: T, bundles: LanguageBundleMap | null): T {
|
|
168
257
|
if (!bundles || Object.keys(bundles).length === 0) return config;
|
|
@@ -179,7 +268,7 @@ export function applyLanguageBundles<T extends LocalizableConfig>(config: T, bun
|
|
|
179
268
|
|
|
180
269
|
/** The generator-side inverse of `applyLanguageBundles`: one bundle per language. */
|
|
181
270
|
export function splitLanguageBundles(
|
|
182
|
-
languages: string[],
|
|
271
|
+
languages: readonly string[],
|
|
183
272
|
langmenu: InlineLangMenu,
|
|
184
273
|
translations: InlineTranslations,
|
|
185
274
|
): LanguageBundleMap {
|
|
@@ -198,7 +287,3 @@ export function splitLanguageBundles(
|
|
|
198
287
|
}
|
|
199
288
|
return bundles;
|
|
200
289
|
}
|
|
201
|
-
|
|
202
|
-
export function buildLanguageManifest(languages: string[]): LanguageManifest {
|
|
203
|
-
return { languages: [...languages] };
|
|
204
|
-
}
|
|
@@ -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
|
|
13
|
+
return raw?.trim() ? raw : null;
|
|
14
14
|
}
|
|
15
15
|
|
|
16
16
|
async save(serialized: string): Promise<void> {
|