@parlajs/compiler 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +21 -2
- package/build/build.d.ts +18 -0
- package/build/build.d.ts.map +1 -0
- package/build/build.js +10 -0
- package/build/cli.d.ts +3 -0
- package/build/cli.d.ts.map +1 -0
- package/build/cli.js +8 -0
- package/build/command.d.ts +13 -0
- package/build/command.d.ts.map +1 -0
- package/build/command.js +156 -0
- package/build/compile/code.d.ts +13 -0
- package/build/compile/code.d.ts.map +1 -0
- package/build/compile/code.js +42 -0
- package/build/compile/compile.d.ts +11 -0
- package/build/compile/compile.d.ts.map +1 -0
- package/build/compile/compile.js +244 -0
- package/build/compile/error.d.ts +4 -0
- package/build/compile/error.d.ts.map +1 -0
- package/build/compile/error.js +3 -0
- package/build/compile/info.d.ts +49 -0
- package/build/compile/info.d.ts.map +1 -0
- package/build/compile/info.js +22 -0
- package/build/compile/scope.d.ts +7 -0
- package/build/compile/scope.d.ts.map +1 -0
- package/build/compile/scope.js +14 -0
- package/build/compile/single.d.ts +11 -0
- package/build/compile/single.d.ts.map +1 -0
- package/build/compile/single.js +36 -0
- package/build/compile/variants.d.ts +16 -0
- package/build/compile/variants.d.ts.map +1 -0
- package/build/compile/variants.js +48 -0
- package/build/config/checks.d.ts +21 -0
- package/build/config/checks.d.ts.map +1 -0
- package/build/config/checks.js +97 -0
- package/build/config/config.d.ts +71 -0
- package/build/config/config.d.ts.map +1 -0
- package/build/config/config.js +7 -0
- package/build/config/fallbacks.d.ts +6 -0
- package/build/config/fallbacks.d.ts.map +1 -0
- package/build/config/fallbacks.js +13 -0
- package/build/config/import.d.ts +31 -0
- package/build/config/import.d.ts.map +1 -0
- package/build/config/import.js +115 -0
- package/build/config/load.d.ts +13 -0
- package/build/config/load.d.ts.map +1 -0
- package/build/config/load.js +59 -0
- package/build/diagnostics.d.ts +31 -0
- package/build/diagnostics.d.ts.map +1 -0
- package/build/diagnostics.js +41 -0
- package/build/generate/checks.d.ts +9 -0
- package/build/generate/checks.d.ts.map +1 -0
- package/build/generate/checks.js +93 -0
- package/build/generate/chunk.d.ts +11 -0
- package/build/generate/chunk.d.ts.map +1 -0
- package/build/generate/chunk.js +57 -0
- package/build/generate/digits.d.ts +8 -0
- package/build/generate/digits.d.ts.map +1 -0
- package/build/generate/digits.js +57 -0
- package/build/generate/files.d.ts +7 -0
- package/build/generate/files.d.ts.map +1 -0
- package/build/generate/files.js +59 -0
- package/build/generate/locale.d.ts +21 -0
- package/build/generate/locale.d.ts.map +1 -0
- package/build/generate/locale.js +108 -0
- package/build/generate/modules.d.ts +27 -0
- package/build/generate/modules.d.ts.map +1 -0
- package/build/generate/modules.js +61 -0
- package/build/generate/namespace.d.ts +19 -0
- package/build/generate/namespace.d.ts.map +1 -0
- package/build/generate/namespace.js +65 -0
- package/build/generate/namespaces.d.ts +5 -0
- package/build/generate/namespaces.d.ts.map +1 -0
- package/build/generate/namespaces.js +41 -0
- package/build/generate/read.d.ts +21 -0
- package/build/generate/read.d.ts.map +1 -0
- package/build/generate/read.js +115 -0
- package/build/index.d.ts +9 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +7 -0
- package/build/init/detect.d.ts +43 -0
- package/build/init/detect.d.ts.map +1 -0
- package/build/init/detect.js +69 -0
- package/build/init/init.d.ts +12 -0
- package/build/init/init.d.ts.map +1 -0
- package/build/init/init.js +126 -0
- package/build/options/date.d.ts +3 -0
- package/build/options/date.d.ts.map +1 -0
- package/build/options/date.js +77 -0
- package/build/options/literal.d.ts +10 -0
- package/build/options/literal.d.ts.map +1 -0
- package/build/options/literal.js +11 -0
- package/build/options/names.d.ts +5 -0
- package/build/options/names.d.ts.map +1 -0
- package/build/options/names.js +56 -0
- package/build/options/number.d.ts +3 -0
- package/build/options/number.d.ts.map +1 -0
- package/build/options/number.js +17 -0
- package/build/options/options.d.ts +7 -0
- package/build/options/options.d.ts.map +1 -0
- package/build/options/options.js +66 -0
- package/build/plurals.d.ts +6 -0
- package/build/plurals.d.ts.map +1 -0
- package/build/plurals.js +50 -0
- package/build/types/names.d.ts +9 -0
- package/build/types/names.d.ts.map +1 -0
- package/build/types/names.js +109 -0
- package/build/types/namespace.d.ts +17 -0
- package/build/types/namespace.d.ts.map +1 -0
- package/build/types/namespace.js +113 -0
- package/build/types/signature.d.ts +8 -0
- package/build/types/signature.d.ts.map +1 -0
- package/build/types/signature.js +87 -0
- package/build/vite.d.ts +9 -0
- package/build/vite.d.ts.map +1 -0
- package/build/vite.js +125 -0
- package/build/watch.d.ts +12 -0
- package/build/watch.d.ts.map +1 -0
- package/build/watch.js +93 -0
- package/package.json +84 -3
- package/src/build.ts +31 -0
- package/src/cli.ts +9 -0
- package/src/command.ts +195 -0
- package/src/compile/code.ts +51 -0
- package/src/compile/compile.ts +289 -0
- package/src/compile/error.ts +3 -0
- package/src/compile/info.ts +63 -0
- package/src/compile/scope.ts +14 -0
- package/src/compile/single.ts +46 -0
- package/src/compile/variants.ts +68 -0
- package/src/config/checks.ts +140 -0
- package/src/config/config.ts +83 -0
- package/src/config/fallbacks.ts +18 -0
- package/src/config/import.ts +146 -0
- package/src/config/load.ts +75 -0
- package/src/diagnostics.ts +98 -0
- package/src/generate/checks.ts +103 -0
- package/src/generate/chunk.ts +73 -0
- package/src/generate/digits.ts +74 -0
- package/src/generate/files.ts +83 -0
- package/src/generate/locale.ts +145 -0
- package/src/generate/modules.ts +94 -0
- package/src/generate/namespace.ts +119 -0
- package/src/generate/namespaces.ts +59 -0
- package/src/generate/read.ts +159 -0
- package/src/index.ts +27 -0
- package/src/init/detect.ts +103 -0
- package/src/init/init.ts +158 -0
- package/src/options/date.ts +87 -0
- package/src/options/literal.ts +21 -0
- package/src/options/names.ts +64 -0
- package/src/options/number.ts +20 -0
- package/src/options/options.ts +75 -0
- package/src/plurals.ts +68 -0
- package/src/types/names.ts +115 -0
- package/src/types/namespace.ts +148 -0
- package/src/types/signature.ts +111 -0
- package/src/vite.ts +143 -0
- package/src/watch.ts +115 -0
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { Model } from 'messageformat';
|
|
2
|
+
|
|
3
|
+
import type { FunctionKind } from '../compile/info.ts';
|
|
4
|
+
|
|
5
|
+
/** Parses one message into the MF2 data model, which the compiler reads. */
|
|
6
|
+
export interface FormatAdapter {
|
|
7
|
+
readonly name: string;
|
|
8
|
+
readonly parse: (source: string) => Model.Message;
|
|
9
|
+
/** Reads a catalog file into `{ key: message | group }`, for files that are not JSON. */
|
|
10
|
+
readonly parseFile?: ((text: string) => unknown) | undefined;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface NamespaceConfig<Format extends string = string> {
|
|
14
|
+
/** Message syntax: a key of `formats`. */
|
|
15
|
+
format: Format;
|
|
16
|
+
/** Catalog path relative to the config, with a `{locale}` token. */
|
|
17
|
+
path: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** `Formats` are the keys of `formats`, which a namespace's `format` may name. */
|
|
21
|
+
export interface ParlaConfig<Formats extends string = string> {
|
|
22
|
+
locales?: Array<string>;
|
|
23
|
+
sourceLocale?: string;
|
|
24
|
+
/** Extra fallback chain per locale; the source locale is always last. */
|
|
25
|
+
fallbacks?: Record<string, Array<string>>;
|
|
26
|
+
/** Where generated files go, relative to the config. Default `src/parla`. */
|
|
27
|
+
outDir?: string;
|
|
28
|
+
/** Namespaces this package owns: other packages import their built objects. */
|
|
29
|
+
// NoInfer: a typo in `format` must not become a format of its own.
|
|
30
|
+
namespaces?: Record<string, NamespaceConfig<NoInfer<Formats>>>;
|
|
31
|
+
/**
|
|
32
|
+
* Message functions beyond the built-in ones, by what their value is. Each needs an
|
|
33
|
+
* implementation in `createParla({ functions })`.
|
|
34
|
+
*/
|
|
35
|
+
functions?: Record<string, FunctionKind>;
|
|
36
|
+
/** Markup that calls may leave out: `createParla({ markup })` renders it. */
|
|
37
|
+
markup?: Array<string>;
|
|
38
|
+
/** Message syntaxes by the name a namespace's `format` gives: `{ icu }` from `@parlajs/format-icu`. */
|
|
39
|
+
formats?: Record<Formats, FormatAdapter>;
|
|
40
|
+
/**
|
|
41
|
+
* Module the generated types import and augment: the adapter this package depends on.
|
|
42
|
+
* Default: the first of `@parlajs/react`, `solid`, `svelte`, `vue` and `core` in `package.json`.
|
|
43
|
+
*/
|
|
44
|
+
runtime?: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface ResolvedNamespace {
|
|
48
|
+
name: string;
|
|
49
|
+
format: string;
|
|
50
|
+
readonly file: (locale: string) => string;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface ResolvedConfig {
|
|
54
|
+
root: string;
|
|
55
|
+
configFile: string;
|
|
56
|
+
locales: Array<string>;
|
|
57
|
+
sourceLocale: string;
|
|
58
|
+
fallbacks: Record<string, Array<string>>;
|
|
59
|
+
outDir: string;
|
|
60
|
+
namespaces: Array<ResolvedNamespace>;
|
|
61
|
+
/** Module the generated types import and augment. */
|
|
62
|
+
runtime: string;
|
|
63
|
+
functions: Record<string, FunctionKind>;
|
|
64
|
+
markup: Array<string>;
|
|
65
|
+
formats: Record<string, FormatAdapter>;
|
|
66
|
+
/** Every file whose change should trigger a rebuild. */
|
|
67
|
+
watchFiles: Array<string>;
|
|
68
|
+
/** Folders that hold catalogs, which a config may list from disk. */
|
|
69
|
+
watchFolders: Array<string>;
|
|
70
|
+
/** Whether a change to `file` should trigger a rebuild. */
|
|
71
|
+
readonly watches: (file: string) => boolean;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export class ConfigError extends Error {
|
|
75
|
+
override name = 'ConfigError';
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Types a `parla.config.ts`: `export default defineConfig({ … })`. */
|
|
79
|
+
export function defineConfig<Formats extends string = never>(
|
|
80
|
+
config: ParlaConfig<Formats>,
|
|
81
|
+
): ParlaConfig<Formats> {
|
|
82
|
+
return config;
|
|
83
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { ResolvedConfig } from './config.ts';
|
|
2
|
+
|
|
3
|
+
/** The locales listed for `locale`, then its parents: `zh-Hant-TW` → `zh-Hant`, `zh`. */
|
|
4
|
+
export function parents(config: ResolvedConfig, locale: string): Array<string> {
|
|
5
|
+
const subtags = locale.split('-');
|
|
6
|
+
const bases = subtags.map((_, i) => subtags.slice(0, -1 - i).join('-'));
|
|
7
|
+
return [
|
|
8
|
+
...(config.fallbacks[locale] ?? []),
|
|
9
|
+
...bases.filter((base) => config.locales.includes(base)),
|
|
10
|
+
];
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Locales to try, in order, when `locale` lacks a key. */
|
|
14
|
+
export function fallbackChain(config: ResolvedConfig, locale: string): Array<string> {
|
|
15
|
+
return [...new Set([...parents(config, locale), config.sourceLocale])].filter(
|
|
16
|
+
(l) => l !== locale,
|
|
17
|
+
);
|
|
18
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { existsSync, readdirSync, statSync } from 'node:fs';
|
|
2
|
+
import { registerHooks } from 'node:module';
|
|
3
|
+
import type { ResolveHookSync } from 'node:module';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
6
|
+
|
|
7
|
+
import { ConfigError } from './config.ts';
|
|
8
|
+
import type { ParlaConfig, ResolvedConfig } from './config.ts';
|
|
9
|
+
|
|
10
|
+
export interface Load {
|
|
11
|
+
/** How many times the catalog folders had other files than before. */
|
|
12
|
+
readonly version: number;
|
|
13
|
+
/** The catalogs in each folder. */
|
|
14
|
+
readonly names: ReadonlyMap<string, string>;
|
|
15
|
+
readonly list: (dir: string) => string;
|
|
16
|
+
/** The modules the config imported from its own folder. */
|
|
17
|
+
readonly imports: ReadonlyArray<string>;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The last load of each config file, for watchers. */
|
|
21
|
+
const loads = new Map<string, Load>();
|
|
22
|
+
|
|
23
|
+
/** The load to come, before the import: a file added meanwhile counts at the next one. */
|
|
24
|
+
export function nextLoad(file: string): Load | undefined {
|
|
25
|
+
const last = loads.get(file);
|
|
26
|
+
if (!last) {
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
const names = new Map([...last.names.keys()].map((dir) => [dir, last.list(dir)]));
|
|
30
|
+
const same = [...names].every(([dir, list]) => list === last.names.get(dir));
|
|
31
|
+
const next = { ...last, names, version: last.version + (same ? 0 : 1) };
|
|
32
|
+
loads.set(file, next);
|
|
33
|
+
return next;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface Importing {
|
|
37
|
+
readonly root: string;
|
|
38
|
+
readonly imports: Set<string>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Each config import under way or done, by its URL's query. */
|
|
42
|
+
const importing = new Map<string, Importing>();
|
|
43
|
+
/** A number per config file, so two configs never share a query. */
|
|
44
|
+
const ids = new Map<string, number>();
|
|
45
|
+
let hooked = false;
|
|
46
|
+
|
|
47
|
+
const isInside = (dir: string, file: string): boolean =>
|
|
48
|
+
file.startsWith(dir + path.sep) && !file.includes(`${path.sep}node_modules${path.sep}`);
|
|
49
|
+
|
|
50
|
+
/** A resolve hook that carries a config's query to what it imports from its own folder. */
|
|
51
|
+
export function carrying(configs: ReadonlyMap<string, Importing>): ResolveHookSync {
|
|
52
|
+
return (specifier, context, nextResolve) => {
|
|
53
|
+
const result = nextResolve(specifier, context);
|
|
54
|
+
const from = context.parentURL ?? '';
|
|
55
|
+
const query = from.slice(from.indexOf('?'));
|
|
56
|
+
const config = from.includes('?') ? configs.get(query) : undefined;
|
|
57
|
+
if (!config || !result.url.startsWith('file:') || result.url.includes('?')) {
|
|
58
|
+
return result;
|
|
59
|
+
}
|
|
60
|
+
const file = fileURLToPath(result.url);
|
|
61
|
+
if (!isInside(config.root, file)) {
|
|
62
|
+
return result;
|
|
63
|
+
}
|
|
64
|
+
config.imports.add(file);
|
|
65
|
+
return { ...result, url: result.url + query };
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Node would keep what a config imports cached, however its own URL changes. */
|
|
70
|
+
function reloadImports(): void {
|
|
71
|
+
if (!hooked) {
|
|
72
|
+
hooked = true;
|
|
73
|
+
registerHooks({ resolve: carrying(importing) });
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const mtimeOf = (file: string): bigint =>
|
|
78
|
+
statSync(file, { bigint: true, throwIfNoEntry: false })?.mtimeNs ?? 0n;
|
|
79
|
+
|
|
80
|
+
export async function importConfig(
|
|
81
|
+
file: string,
|
|
82
|
+
load: Load | undefined,
|
|
83
|
+
): Promise<{ config: ParlaConfig; imports: Array<string> }> {
|
|
84
|
+
reloadImports();
|
|
85
|
+
// All bust Node's module cache, so a watcher sees an edited config, an edited module it imports,
|
|
86
|
+
// or a config that lists new catalogs.
|
|
87
|
+
let stamp = statSync(file, { bigint: true }).mtimeNs;
|
|
88
|
+
for (const dependency of load?.imports ?? []) {
|
|
89
|
+
const edited = mtimeOf(dependency);
|
|
90
|
+
stamp = edited > stamp ? edited : stamp;
|
|
91
|
+
}
|
|
92
|
+
const id = ids.get(file) ?? ids.size;
|
|
93
|
+
ids.set(file, id);
|
|
94
|
+
const query = `?t=${stamp}&v=${load?.version ?? 0}&c=${id}`;
|
|
95
|
+
const url = pathToFileURL(file).href + query;
|
|
96
|
+
// The same query is the same module, cached: it resolves nothing again.
|
|
97
|
+
const entry = importing.get(query) ?? { root: path.dirname(file), imports: new Set<string>() };
|
|
98
|
+
importing.set(query, entry);
|
|
99
|
+
let mod: unknown;
|
|
100
|
+
try {
|
|
101
|
+
mod = await import(url);
|
|
102
|
+
} catch (error) {
|
|
103
|
+
const { message, stack = '' } = error as Error;
|
|
104
|
+
// Only the stack tells where, a syntax error's included.
|
|
105
|
+
const [position = ''] = /^(?::\d+)+/.exec(stack.split(url)[1] ?? '') ?? [];
|
|
106
|
+
throw new ConfigError(`Cannot load ${file}${position}: ${message}`);
|
|
107
|
+
}
|
|
108
|
+
const config = (mod as { default?: unknown }).default;
|
|
109
|
+
if (typeof config !== 'object' || config === null) {
|
|
110
|
+
throw new ConfigError(`${file} must \`export default defineConfig({ … })\``);
|
|
111
|
+
}
|
|
112
|
+
return { config, imports: [...entry.imports] };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** What a watcher of this load follows, kept to tell the next load whether its folders changed. */
|
|
116
|
+
export function watching(
|
|
117
|
+
file: string,
|
|
118
|
+
{
|
|
119
|
+
load,
|
|
120
|
+
catalogs,
|
|
121
|
+
imports,
|
|
122
|
+
}: { load: Load | undefined; catalogs: ReadonlyArray<string>; imports: ReadonlyArray<string> },
|
|
123
|
+
): Pick<ResolvedConfig, 'watchFiles' | 'watchFolders' | 'watches'> {
|
|
124
|
+
const watchFiles = [file, ...imports, ...catalogs];
|
|
125
|
+
const extensions = new Set(catalogs.map((f) => path.extname(f)));
|
|
126
|
+
const folders = new Set(catalogs.map((f) => path.dirname(f)));
|
|
127
|
+
const isCatalog = (f: string): boolean => extensions.has(path.extname(f));
|
|
128
|
+
const list = (dir: string): string =>
|
|
129
|
+
existsSync(dir)
|
|
130
|
+
? readdirSync(dir)
|
|
131
|
+
.filter((f) => isCatalog(f))
|
|
132
|
+
.toSorted()
|
|
133
|
+
.join('/')
|
|
134
|
+
: '';
|
|
135
|
+
loads.set(file, {
|
|
136
|
+
version: load?.version ?? 0,
|
|
137
|
+
names: new Map([...folders].map((dir) => [dir, load?.names.get(dir) ?? list(dir)])),
|
|
138
|
+
list,
|
|
139
|
+
imports,
|
|
140
|
+
});
|
|
141
|
+
return {
|
|
142
|
+
watchFiles,
|
|
143
|
+
watchFolders: [...folders],
|
|
144
|
+
watches: (f) => watchFiles.includes(f) || (folders.has(path.dirname(f)) && isCatalog(f)),
|
|
145
|
+
};
|
|
146
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
import { checkFallbacks, checkFunctions, checkLocales, resolveNamespaces } from './checks.ts';
|
|
5
|
+
import { ConfigError } from './config.ts';
|
|
6
|
+
import type { ResolvedConfig } from './config.ts';
|
|
7
|
+
import { importConfig, nextLoad, watching } from './import.ts';
|
|
8
|
+
|
|
9
|
+
interface PackageJson {
|
|
10
|
+
type?: string;
|
|
11
|
+
dependencies?: Record<string, string>;
|
|
12
|
+
devDependencies?: Record<string, string>;
|
|
13
|
+
peerDependencies?: Record<string, string>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** `.mts` for a package that is not `"type": "module"`, where Node reads a `.ts` as CommonJS. */
|
|
17
|
+
export const CONFIG_FILES = ['parla.config.ts', 'parla.config.mts'] as const;
|
|
18
|
+
|
|
19
|
+
export function readPackageJson(dir: string): PackageJson | undefined {
|
|
20
|
+
const file = path.join(dir, 'package.json');
|
|
21
|
+
return existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as PackageJson) : undefined;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// The adapters first: an app on one may list core too.
|
|
25
|
+
const RUNTIMES = [
|
|
26
|
+
'@parlajs/react',
|
|
27
|
+
'@parlajs/solid',
|
|
28
|
+
'@parlajs/svelte',
|
|
29
|
+
'@parlajs/vue',
|
|
30
|
+
'@parlajs/core',
|
|
31
|
+
];
|
|
32
|
+
|
|
33
|
+
function detectRuntime(dir: string): string {
|
|
34
|
+
const pkg = readPackageJson(dir);
|
|
35
|
+
const deps = { ...pkg?.peerDependencies, ...pkg?.devDependencies, ...pkg?.dependencies };
|
|
36
|
+
return RUNTIMES.find((name) => name in deps) ?? '@parlajs/core';
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function loadConfig(cwd: string, configFile?: string): Promise<ResolvedConfig> {
|
|
40
|
+
const found = CONFIG_FILES.find((name) => existsSync(path.join(cwd, name)));
|
|
41
|
+
if (!configFile && !found) {
|
|
42
|
+
throw new ConfigError(`No ${CONFIG_FILES[0]} in ${cwd}`);
|
|
43
|
+
}
|
|
44
|
+
const file = path.resolve(cwd, configFile ?? found ?? CONFIG_FILES[0]);
|
|
45
|
+
const load = nextLoad(file);
|
|
46
|
+
const { config, imports } = await importConfig(file, load);
|
|
47
|
+
const root = path.dirname(file);
|
|
48
|
+
const sourceLocale = config.sourceLocale ?? 'en';
|
|
49
|
+
const locales = config.locales ?? [sourceLocale];
|
|
50
|
+
const fallbacks = config.fallbacks ?? {};
|
|
51
|
+
checkLocales({ locales, sourceLocale, fallbacks });
|
|
52
|
+
|
|
53
|
+
const outDir = path.resolve(root, config.outDir ?? 'src/parla');
|
|
54
|
+
const namespaces = resolveNamespaces(config.namespaces ?? {}, { root, outDir, locales });
|
|
55
|
+
checkFallbacks(fallbacks, {
|
|
56
|
+
locales,
|
|
57
|
+
hasCatalog: (locale) => namespaces.some((ns) => existsSync(ns.file(locale))),
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
const catalogs = namespaces.flatMap((ns) => locales.map((l) => ns.file(l)));
|
|
61
|
+
return {
|
|
62
|
+
root,
|
|
63
|
+
configFile: file,
|
|
64
|
+
locales,
|
|
65
|
+
sourceLocale,
|
|
66
|
+
fallbacks,
|
|
67
|
+
outDir,
|
|
68
|
+
runtime: config.runtime ?? detectRuntime(root),
|
|
69
|
+
functions: checkFunctions(config.functions ?? {}),
|
|
70
|
+
markup: config.markup ?? [],
|
|
71
|
+
formats: config.formats ?? {},
|
|
72
|
+
namespaces,
|
|
73
|
+
...watching(file, { load, catalogs, imports }),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
|
|
3
|
+
interface Located {
|
|
4
|
+
message: string;
|
|
5
|
+
namespace?: string;
|
|
6
|
+
locale?: string;
|
|
7
|
+
key?: string;
|
|
8
|
+
file?: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Fails the build. A missing file is one only in the source locale. */
|
|
12
|
+
export interface ErrorDiagnostic extends Located {
|
|
13
|
+
level: 'error';
|
|
14
|
+
code:
|
|
15
|
+
| 'invalid-config'
|
|
16
|
+
| 'invalid-syntax'
|
|
17
|
+
| 'invalid-resource'
|
|
18
|
+
| 'missing-file'
|
|
19
|
+
| 'param-mismatch'
|
|
20
|
+
| 'key-conflict'
|
|
21
|
+
| 'unknown-format';
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Fails only `--strict`. */
|
|
25
|
+
export interface WarningDiagnostic extends Located {
|
|
26
|
+
level: 'warning';
|
|
27
|
+
code:
|
|
28
|
+
| 'missing-file'
|
|
29
|
+
| 'missing-translation'
|
|
30
|
+
| 'missing-param'
|
|
31
|
+
| 'missing-plural'
|
|
32
|
+
| 'unknown-key'
|
|
33
|
+
| 'namespace-name';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export type Diagnostic = ErrorDiagnostic | WarningDiagnostic;
|
|
37
|
+
|
|
38
|
+
/** A diagnostic before its namespace and locale are known. */
|
|
39
|
+
export type Unplaced =
|
|
40
|
+
| Omit<ErrorDiagnostic, 'namespace' | 'locale'>
|
|
41
|
+
| Omit<WarningDiagnostic, 'namespace' | 'locale'>;
|
|
42
|
+
|
|
43
|
+
/** Catalogs are others' text: no new lines, which a CI may read as commands, nor terminal codes. */
|
|
44
|
+
const printable = (text: string): string =>
|
|
45
|
+
text.replaceAll(/\p{Cc}/gu, (char) => {
|
|
46
|
+
const code = char.codePointAt(0) ?? 0;
|
|
47
|
+
return `\\u${code.toString(16).padStart(4, '0')}`;
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
export function formatDiagnostic(d: Diagnostic, root?: string): string {
|
|
51
|
+
const where = [d.namespace, d.locale, d.key].filter(Boolean).join(' › ');
|
|
52
|
+
// `/` on Windows too, where its terminals open both.
|
|
53
|
+
const file = d.file && root ? ` (${path.relative(root, d.file).replaceAll(path.sep, '/')})` : '';
|
|
54
|
+
return printable(
|
|
55
|
+
`${d.level === 'error' ? 'error ' : 'warning'} [${d.code}] ${where}: ${d.message}${file}`,
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface Report {
|
|
60
|
+
level: Diagnostic['level'];
|
|
61
|
+
line: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const SHOWN_KEYS = 5;
|
|
65
|
+
|
|
66
|
+
/** One line per problem: diagnostics that differ only in their key share it. */
|
|
67
|
+
export function formatDiagnostics(
|
|
68
|
+
diagnostics: ReadonlyArray<Diagnostic>,
|
|
69
|
+
root?: string,
|
|
70
|
+
): Array<Report> {
|
|
71
|
+
const groups = new Map<string, { d: Diagnostic; keys: Array<string> }>();
|
|
72
|
+
for (const d of diagnostics) {
|
|
73
|
+
const id = JSON.stringify([d.level, d.code, d.namespace, d.locale, d.file, d.message]);
|
|
74
|
+
const group = groups.get(id) ?? { d, keys: [] };
|
|
75
|
+
groups.set(id, group);
|
|
76
|
+
if (d.key) {
|
|
77
|
+
group.keys.push(d.key);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return [...groups.values()].map(({ d, keys }) => {
|
|
81
|
+
const more = keys.length - SHOWN_KEYS;
|
|
82
|
+
// "and 1 more" is no shorter than the key itself
|
|
83
|
+
const key =
|
|
84
|
+
more > 1 ? `${keys.slice(0, SHOWN_KEYS).join(', ')} and ${more} more` : keys.join(', ');
|
|
85
|
+
return { level: d.level, line: formatDiagnostic({ ...d, key }, root) };
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Filters out what the previous call returned, so a rebuild repeats no warning. */
|
|
90
|
+
export function unreported(): (diagnostics: ReadonlyArray<Diagnostic>) => Array<Diagnostic> {
|
|
91
|
+
let last = new Set<string>();
|
|
92
|
+
return (diagnostics) => {
|
|
93
|
+
const ids = diagnostics.map((d) => JSON.stringify(d));
|
|
94
|
+
const fresh = diagnostics.filter((_, i) => !last.has(ids[i] ?? ''));
|
|
95
|
+
last = new Set(ids);
|
|
96
|
+
return fresh;
|
|
97
|
+
};
|
|
98
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import type { MessageInfo, ParamKind } from '../compile/info.ts';
|
|
2
|
+
import type { ResolvedConfig } from '../config/config.ts';
|
|
3
|
+
import { parents } from '../config/fallbacks.ts';
|
|
4
|
+
import { paramType } from '../types/signature.ts';
|
|
5
|
+
|
|
6
|
+
/** A locale with a parent (a fallback or its base) leaves gaps by design; the parent reports its own. */
|
|
7
|
+
export function inherits(config: ResolvedConfig, locale: string): boolean {
|
|
8
|
+
return parents(config, locale).some((l) => l !== locale && config.locales.includes(l));
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const selectKeys = (kinds: ReadonlyArray<ParamKind>): Array<string> =>
|
|
12
|
+
kinds.flatMap((k) => (k.kind === 'select' ? k.keys : []));
|
|
13
|
+
|
|
14
|
+
/** Whether a param typed by the source's kinds suits the translation's. */
|
|
15
|
+
function accepts(own: ReadonlyArray<ParamKind>, source: ReadonlyArray<ParamKind>): boolean {
|
|
16
|
+
const [ownType, sourceType] = [paramType(own), paramType(source)];
|
|
17
|
+
if (ownType === sourceType || ownType === 'string | number') {
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
const isText = [...own, ...source].every((k) => k.kind === 'select' || k.kind === 'string');
|
|
21
|
+
// A language may need fewer branches, down to none.
|
|
22
|
+
return (
|
|
23
|
+
isText &&
|
|
24
|
+
source.some((k) => k.kind === 'select') &&
|
|
25
|
+
selectKeys(own).every((key) => selectKeys(source).includes(key))
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** `$p when $k is "a"`, per param the source needs in a branch and the translation leaves out. */
|
|
30
|
+
function branchOmissions(own: MessageInfo, source: MessageInfo): Array<string> {
|
|
31
|
+
const { branches } = source;
|
|
32
|
+
const out = new Map<string, string>();
|
|
33
|
+
if (branches && own.branches?.param === branches.param) {
|
|
34
|
+
for (const [key, needs] of branches.needs) {
|
|
35
|
+
const ownNeeds = own.branches.needs.get(key) ?? own.branches.needs.get(null);
|
|
36
|
+
for (const name of needs) {
|
|
37
|
+
if (own.params.has(name) && ownNeeds?.has(name) === false && !out.has(name)) {
|
|
38
|
+
const when = key === null ? 'another value' : JSON.stringify(key);
|
|
39
|
+
out.set(name, `$${name} when $${branches.param} is ${when}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return [...out.values()];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** What the source message has and a translation leaves out. */
|
|
48
|
+
export function omissions(own: MessageInfo, source: MessageInfo): Array<string> {
|
|
49
|
+
const left: Array<string> = [];
|
|
50
|
+
for (const [name, kinds] of source.params) {
|
|
51
|
+
// A language may not need a select, as of gender.
|
|
52
|
+
if (!own.params.has(name) && !kinds.some((k) => k.kind === 'select')) {
|
|
53
|
+
left.push(`$${name}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
left.push(...branchOmissions(own, source));
|
|
57
|
+
for (const tag of source.markup) {
|
|
58
|
+
if (!own.markup.has(tag)) {
|
|
59
|
+
left.push(`markup "${tag}"`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return left.map((what) => `leaves out ${what}, which the source message has`);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** A translation's params and markup against the source message's. */
|
|
66
|
+
export function mismatches(own: MessageInfo, source: MessageInfo): Array<string> {
|
|
67
|
+
const out: Array<string> = [];
|
|
68
|
+
for (const [param, kinds] of own.params) {
|
|
69
|
+
const expected = source.params.get(param);
|
|
70
|
+
if (!expected) {
|
|
71
|
+
out.push(`uses $${param}, which the source message does not have`);
|
|
72
|
+
} else if (!accepts(kinds, expected)) {
|
|
73
|
+
out.push(`$${param} is ${paramType(kinds)} here but ${paramType(expected)} in the source`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
for (const tag of own.markup) {
|
|
77
|
+
if (!source.markup.has(tag)) {
|
|
78
|
+
out.push(`uses markup "${tag}", which the source message does not have`);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const { branches } = source;
|
|
82
|
+
if (branches) {
|
|
83
|
+
// The source's type lets a call leave out what its value's branch does not read.
|
|
84
|
+
const ownBranches = own.branches?.param === branches.param ? own.branches : undefined;
|
|
85
|
+
const needs = (info: MessageInfo, key: string | null): Set<string> => {
|
|
86
|
+
const map = info === source ? branches : ownBranches;
|
|
87
|
+
return map?.needs.get(key) ?? map?.needs.get(null) ?? new Set(info.params.keys());
|
|
88
|
+
};
|
|
89
|
+
const keys = new Set([...branches.needs.keys(), ...(ownBranches?.needs.keys() ?? [])]);
|
|
90
|
+
const reported = new Set<string>();
|
|
91
|
+
for (const key of keys) {
|
|
92
|
+
const allowed = needs(source, key);
|
|
93
|
+
for (const param of needs(own, key)) {
|
|
94
|
+
if (source.params.has(param) && !allowed.has(param) && !reported.has(param)) {
|
|
95
|
+
reported.add(param);
|
|
96
|
+
const when = key === null ? 'another value' : JSON.stringify(key);
|
|
97
|
+
out.push(`needs $${param} when $${branches.param} is ${when}, but the source does not`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return out;
|
|
103
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// oxlint-disable-next-line typescript/no-empty-object-type -- a type alias cannot refer to itself here
|
|
2
|
+
interface ChunkTree extends Map<string, ChunkTree | string> {}
|
|
3
|
+
|
|
4
|
+
/** Dotted keys as nested groups; `key-conflict` already rules out a key that is also a group. */
|
|
5
|
+
export function treeOf(messages: ReadonlyArray<[key: string, fn: string]>): ChunkTree {
|
|
6
|
+
const root: ChunkTree = new Map();
|
|
7
|
+
for (const [key, fn] of messages) {
|
|
8
|
+
const path = key.split('.');
|
|
9
|
+
const leaf = path.pop() ?? key;
|
|
10
|
+
let node = root;
|
|
11
|
+
for (const segment of path) {
|
|
12
|
+
let child = node.get(segment);
|
|
13
|
+
if (typeof child !== 'object') {
|
|
14
|
+
child = new Map();
|
|
15
|
+
node.set(segment, child);
|
|
16
|
+
}
|
|
17
|
+
node = child;
|
|
18
|
+
}
|
|
19
|
+
node.set(leaf, fn);
|
|
20
|
+
}
|
|
21
|
+
return root;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// A literal `"__proto__": …` would set the prototype; a computed key defines a property.
|
|
25
|
+
const literalKey = (key: string): string =>
|
|
26
|
+
key === '__proto__' ? '["__proto__"]' : JSON.stringify(key);
|
|
27
|
+
|
|
28
|
+
// V8 builds a literal of up to 127 properties from a template; at 128 it takes a path ~100× slower.
|
|
29
|
+
const MAX_LITERAL = 127;
|
|
30
|
+
|
|
31
|
+
/** A group as an expression: a literal or, when larger, a const that `statements` builds. */
|
|
32
|
+
function emitGroup(
|
|
33
|
+
node: ChunkTree,
|
|
34
|
+
{ indent, statements }: { indent: string; statements: Array<string> },
|
|
35
|
+
): string {
|
|
36
|
+
const inner = `${indent} `;
|
|
37
|
+
const value = (v: ChunkTree | string): string =>
|
|
38
|
+
typeof v === 'string' ? v : emitGroup(v, { indent: inner, statements });
|
|
39
|
+
// `__proto__` must stay in the literal: an assignment would set the prototype.
|
|
40
|
+
const entries = [...node].toSorted(
|
|
41
|
+
([a], [b]) => Number(b === '__proto__') - Number(a === '__proto__'),
|
|
42
|
+
);
|
|
43
|
+
const literal = entries
|
|
44
|
+
.slice(0, MAX_LITERAL)
|
|
45
|
+
.map(([key, v]) => `${inner}${literalKey(key)}: ${value(v)},`)
|
|
46
|
+
.join('\n');
|
|
47
|
+
if (entries.length <= MAX_LITERAL) {
|
|
48
|
+
return `{\n${literal}\n${indent}}`;
|
|
49
|
+
}
|
|
50
|
+
const rest = entries
|
|
51
|
+
.slice(MAX_LITERAL)
|
|
52
|
+
.map(([key, v]) => [JSON.stringify(key), value(v)] as const);
|
|
53
|
+
const name = `g${statements.length}`;
|
|
54
|
+
statements.push(
|
|
55
|
+
[
|
|
56
|
+
`const ${name} = {\n${literal}\n};`,
|
|
57
|
+
...rest.map(([key, v]) => `${name}[${key}] = ${v};`),
|
|
58
|
+
].join('\n'),
|
|
59
|
+
);
|
|
60
|
+
return name;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* A chunk's factory. In parentheses, so V8 compiles it at once instead of parsing it twice; bigger
|
|
65
|
+
* groups are built in its own body, as V8 runs a function nested there ~5× slower.
|
|
66
|
+
*/
|
|
67
|
+
export function emitFactory(tree: ChunkTree): string {
|
|
68
|
+
const statements: Array<string> = [];
|
|
69
|
+
const root = emitGroup(tree, { indent: '', statements });
|
|
70
|
+
return statements.length === 0
|
|
71
|
+
? `(($) => (${root}))`
|
|
72
|
+
: `(($) => {\n${statements.join('\n')}\nreturn ${root};\n})`;
|
|
73
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// A locale of another script, such as `ar`, has latin digits in some engines and its own in others.
|
|
2
|
+
const DIGITLESS_SCRIPTS = new Set([
|
|
3
|
+
'Armn',
|
|
4
|
+
'Cyrl',
|
|
5
|
+
'Geor',
|
|
6
|
+
'Grek',
|
|
7
|
+
'Hans',
|
|
8
|
+
'Hant',
|
|
9
|
+
'Hebr',
|
|
10
|
+
'Jpan',
|
|
11
|
+
'Kore',
|
|
12
|
+
'Latn',
|
|
13
|
+
]);
|
|
14
|
+
|
|
15
|
+
/** Whether `Intl` writes 0 to 999 as JavaScript does: asking it in a browser costs what this saves. */
|
|
16
|
+
export function hasPlainDigits(locale: string): boolean {
|
|
17
|
+
const { script = '' } = new Intl.Locale(locale).maximize();
|
|
18
|
+
const numbers = new Intl.NumberFormat(locale);
|
|
19
|
+
return (
|
|
20
|
+
DIGITLESS_SCRIPTS.has(script) &&
|
|
21
|
+
Array.from({ length: 1000 }, (_, n) => n).every((n) => numbers.format(n) === String(n))
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Languages every engine has data for: another may be written as one of its fallbacks.
|
|
26
|
+
const COMMON_LANGUAGES = new Set(
|
|
27
|
+
'af am ar bg bn ca cs da de el en es et fa fi fil fr gu he hi hr hu id it ja kn ko lt lv ml mr ms nb nl pl pt ro ru sk sl sr sv sw ta te th tr uk ur vi zh'.split(
|
|
28
|
+
' ',
|
|
29
|
+
),
|
|
30
|
+
);
|
|
31
|
+
|
|
32
|
+
/** The integers checked against `Intl`: at each power of ten up to the runtime's limit, and between. */
|
|
33
|
+
const PROBES = Array.from({ length: 13 }, (_, i) => 10 ** (i + 3)).flatMap((power) => [
|
|
34
|
+
power,
|
|
35
|
+
power + 1,
|
|
36
|
+
power + Math.floor(power / 7),
|
|
37
|
+
power * 9 - 1,
|
|
38
|
+
]);
|
|
39
|
+
|
|
40
|
+
/** What `Intl` puts between the groups of three of every integer from 1000 up, if that is all it does. */
|
|
41
|
+
function separatorOf(locale: string): string | undefined {
|
|
42
|
+
if (Intl.NumberFormat.supportedLocalesOf(locale).length === 0) {
|
|
43
|
+
// It would answer for the machine's own locale.
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
const numbers = new Intl.NumberFormat(locale);
|
|
47
|
+
// Not from 10 000, as Italian does since 2022: engines differ on which locales do.
|
|
48
|
+
const [separator] = /\D+/.exec(numbers.format(1000)) ?? [];
|
|
49
|
+
return separator !== undefined &&
|
|
50
|
+
PROBES.every((n) => numbers.format(n) === String(n).replaceAll(/\B(?=(?:\d{3})+$)/g, separator))
|
|
51
|
+
? separator
|
|
52
|
+
: undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The locale, then what an engine without its region or script reads instead. */
|
|
56
|
+
function lineage(locale: string): Array<string> {
|
|
57
|
+
const subtags = new Intl.Locale(locale).baseName.split('-');
|
|
58
|
+
return [locale, ...subtags.slice(1).map((_, i) => subtags.slice(0, -1 - i).join('-'))];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* What every engine puts between the groups of three of `locale`'s integers, or nothing where they
|
|
63
|
+
* may differ: its parents, and for a language some engines lack its `fallbacks` too, must agree.
|
|
64
|
+
*/
|
|
65
|
+
export function groupSeparator(
|
|
66
|
+
locale: string,
|
|
67
|
+
fallbacks: ReadonlyArray<string>,
|
|
68
|
+
): string | undefined {
|
|
69
|
+
const common = COMMON_LANGUAGES.has(new Intl.Locale(locale).language);
|
|
70
|
+
const [own, ...rest] = [...lineage(locale), ...(common ? [] : fallbacks)].map((tag) =>
|
|
71
|
+
separatorOf(tag),
|
|
72
|
+
);
|
|
73
|
+
return rest.every((other) => other === own) ? own : undefined;
|
|
74
|
+
}
|