@parlajs/compiler 0.0.0-stage → 0.0.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.
Files changed (171) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +21 -2
  3. package/build/build.d.ts +18 -0
  4. package/build/build.d.ts.map +1 -0
  5. package/build/build.js +10 -0
  6. package/build/cli.d.ts +3 -0
  7. package/build/cli.d.ts.map +1 -0
  8. package/build/cli.js +8 -0
  9. package/build/command.d.ts +13 -0
  10. package/build/command.d.ts.map +1 -0
  11. package/build/command.js +156 -0
  12. package/build/compile/code.d.ts +13 -0
  13. package/build/compile/code.d.ts.map +1 -0
  14. package/build/compile/code.js +42 -0
  15. package/build/compile/compile.d.ts +11 -0
  16. package/build/compile/compile.d.ts.map +1 -0
  17. package/build/compile/compile.js +244 -0
  18. package/build/compile/error.d.ts +4 -0
  19. package/build/compile/error.d.ts.map +1 -0
  20. package/build/compile/error.js +3 -0
  21. package/build/compile/info.d.ts +49 -0
  22. package/build/compile/info.d.ts.map +1 -0
  23. package/build/compile/info.js +22 -0
  24. package/build/compile/scope.d.ts +7 -0
  25. package/build/compile/scope.d.ts.map +1 -0
  26. package/build/compile/scope.js +14 -0
  27. package/build/compile/single.d.ts +11 -0
  28. package/build/compile/single.d.ts.map +1 -0
  29. package/build/compile/single.js +36 -0
  30. package/build/compile/variants.d.ts +16 -0
  31. package/build/compile/variants.d.ts.map +1 -0
  32. package/build/compile/variants.js +48 -0
  33. package/build/compile.d.ts +61 -0
  34. package/build/compile.d.ts.map +1 -0
  35. package/build/compile.js +385 -0
  36. package/build/config/checks.d.ts +21 -0
  37. package/build/config/checks.d.ts.map +1 -0
  38. package/build/config/checks.js +97 -0
  39. package/build/config/config.d.ts +71 -0
  40. package/build/config/config.d.ts.map +1 -0
  41. package/build/config/config.js +7 -0
  42. package/build/config/fallbacks.d.ts +6 -0
  43. package/build/config/fallbacks.d.ts.map +1 -0
  44. package/build/config/fallbacks.js +13 -0
  45. package/build/config/import.d.ts +31 -0
  46. package/build/config/import.d.ts.map +1 -0
  47. package/build/config/import.js +115 -0
  48. package/build/config/load.d.ts +13 -0
  49. package/build/config/load.d.ts.map +1 -0
  50. package/build/config/load.js +59 -0
  51. package/build/config.d.ts +77 -0
  52. package/build/config.d.ts.map +1 -0
  53. package/build/config.js +223 -0
  54. package/build/diagnostics.d.ts +31 -0
  55. package/build/diagnostics.d.ts.map +1 -0
  56. package/build/diagnostics.js +41 -0
  57. package/build/generate/checks.d.ts +9 -0
  58. package/build/generate/checks.d.ts.map +1 -0
  59. package/build/generate/checks.js +93 -0
  60. package/build/generate/chunk.d.ts +11 -0
  61. package/build/generate/chunk.d.ts.map +1 -0
  62. package/build/generate/chunk.js +57 -0
  63. package/build/generate/digits.d.ts +8 -0
  64. package/build/generate/digits.d.ts.map +1 -0
  65. package/build/generate/digits.js +57 -0
  66. package/build/generate/files.d.ts +7 -0
  67. package/build/generate/files.d.ts.map +1 -0
  68. package/build/generate/files.js +59 -0
  69. package/build/generate/locale.d.ts +21 -0
  70. package/build/generate/locale.d.ts.map +1 -0
  71. package/build/generate/locale.js +108 -0
  72. package/build/generate/modules.d.ts +27 -0
  73. package/build/generate/modules.d.ts.map +1 -0
  74. package/build/generate/modules.js +61 -0
  75. package/build/generate/namespace.d.ts +19 -0
  76. package/build/generate/namespace.d.ts.map +1 -0
  77. package/build/generate/namespace.js +65 -0
  78. package/build/generate/namespaces.d.ts +5 -0
  79. package/build/generate/namespaces.d.ts.map +1 -0
  80. package/build/generate/namespaces.js +41 -0
  81. package/build/generate/read.d.ts +21 -0
  82. package/build/generate/read.d.ts.map +1 -0
  83. package/build/generate/read.js +115 -0
  84. package/build/index.d.ts +9 -0
  85. package/build/index.d.ts.map +1 -0
  86. package/build/index.js +7 -0
  87. package/build/init/detect.d.ts +43 -0
  88. package/build/init/detect.d.ts.map +1 -0
  89. package/build/init/detect.js +69 -0
  90. package/build/init/init.d.ts +12 -0
  91. package/build/init/init.d.ts.map +1 -0
  92. package/build/init/init.js +126 -0
  93. package/build/options/date.d.ts +3 -0
  94. package/build/options/date.d.ts.map +1 -0
  95. package/build/options/date.js +77 -0
  96. package/build/options/literal.d.ts +10 -0
  97. package/build/options/literal.d.ts.map +1 -0
  98. package/build/options/literal.js +11 -0
  99. package/build/options/names.d.ts +5 -0
  100. package/build/options/names.d.ts.map +1 -0
  101. package/build/options/names.js +56 -0
  102. package/build/options/number.d.ts +3 -0
  103. package/build/options/number.d.ts.map +1 -0
  104. package/build/options/number.js +17 -0
  105. package/build/options/options.d.ts +7 -0
  106. package/build/options/options.d.ts.map +1 -0
  107. package/build/options/options.js +66 -0
  108. package/build/options.d.ts +9 -0
  109. package/build/options.d.ts.map +1 -0
  110. package/build/options.js +214 -0
  111. package/build/plurals.d.ts +6 -0
  112. package/build/plurals.d.ts.map +1 -0
  113. package/build/plurals.js +50 -0
  114. package/build/types/names.d.ts +9 -0
  115. package/build/types/names.d.ts.map +1 -0
  116. package/build/types/names.js +109 -0
  117. package/build/types/namespace.d.ts +17 -0
  118. package/build/types/namespace.d.ts.map +1 -0
  119. package/build/types/namespace.js +113 -0
  120. package/build/types/signature.d.ts +8 -0
  121. package/build/types/signature.d.ts.map +1 -0
  122. package/build/types/signature.js +87 -0
  123. package/build/types.d.ts +25 -0
  124. package/build/types.d.ts.map +1 -0
  125. package/build/types.js +250 -0
  126. package/build/vite.d.ts +9 -0
  127. package/build/vite.d.ts.map +1 -0
  128. package/build/vite.js +125 -0
  129. package/build/watch.d.ts +12 -0
  130. package/build/watch.d.ts.map +1 -0
  131. package/build/watch.js +93 -0
  132. package/package.json +84 -3
  133. package/src/build.ts +31 -0
  134. package/src/cli.ts +9 -0
  135. package/src/command.ts +195 -0
  136. package/src/compile/code.ts +51 -0
  137. package/src/compile/compile.ts +289 -0
  138. package/src/compile/error.ts +3 -0
  139. package/src/compile/info.ts +63 -0
  140. package/src/compile/scope.ts +14 -0
  141. package/src/compile/single.ts +46 -0
  142. package/src/compile/variants.ts +68 -0
  143. package/src/config/checks.ts +140 -0
  144. package/src/config/config.ts +83 -0
  145. package/src/config/fallbacks.ts +18 -0
  146. package/src/config/import.ts +146 -0
  147. package/src/config/load.ts +75 -0
  148. package/src/diagnostics.ts +98 -0
  149. package/src/generate/checks.ts +103 -0
  150. package/src/generate/chunk.ts +73 -0
  151. package/src/generate/digits.ts +74 -0
  152. package/src/generate/files.ts +83 -0
  153. package/src/generate/locale.ts +145 -0
  154. package/src/generate/modules.ts +94 -0
  155. package/src/generate/namespace.ts +119 -0
  156. package/src/generate/namespaces.ts +59 -0
  157. package/src/generate/read.ts +159 -0
  158. package/src/index.ts +27 -0
  159. package/src/init/detect.ts +103 -0
  160. package/src/init/init.ts +158 -0
  161. package/src/options/date.ts +87 -0
  162. package/src/options/literal.ts +21 -0
  163. package/src/options/names.ts +64 -0
  164. package/src/options/number.ts +20 -0
  165. package/src/options/options.ts +75 -0
  166. package/src/plurals.ts +68 -0
  167. package/src/types/names.ts +115 -0
  168. package/src/types/namespace.ts +148 -0
  169. package/src/types/signature.ts +111 -0
  170. package/src/vite.ts +143 -0
  171. package/src/watch.ts +115 -0
@@ -0,0 +1,68 @@
1
+ import type { Model } from 'messageformat';
2
+
3
+ /** The keys the variants give selector `at`, and whether one is the catch-all `*`. */
4
+ export function keysAt(msg: Model.SelectMessage, at: number): { keys: Set<string>; open: boolean } {
5
+ const keys = new Set<string>();
6
+ let open = false;
7
+ for (const v of msg.variants) {
8
+ const key = v.keys[at];
9
+ if (key?.type === '*') {
10
+ open = true;
11
+ } else if (key) {
12
+ keys.add(key.value);
13
+ }
14
+ }
15
+ return { keys, open };
16
+ }
17
+
18
+ /**
19
+ * The params each key of the `:string` selector `at` needs, `null` for any other string; `undefined`
20
+ * when every key needs the same. `shared` are read outside any variant, `reads` by each variant.
21
+ */
22
+ export function branchNeeds(
23
+ msg: Model.SelectMessage,
24
+ {
25
+ at,
26
+ shared,
27
+ reads,
28
+ }: { at: number; shared: ReadonlySet<string>; reads: ReadonlyArray<Set<string>> },
29
+ ): Map<string | null, Set<string>> | undefined {
30
+ const keyOf = (v: Model.Variant): string | null => {
31
+ const key = v.keys[at];
32
+ return !key || key.type === '*' ? null : key.value;
33
+ };
34
+ const readBy = (match: (v: Model.Variant) => boolean): Set<string> => {
35
+ const out = new Set(shared);
36
+ for (const [n, v] of msg.variants.entries()) {
37
+ for (const param of match(v) ? (reads[n] ?? []) : []) {
38
+ out.add(param);
39
+ }
40
+ }
41
+ return out;
42
+ };
43
+ const needs = new Map<string | null, Set<string>>();
44
+ for (const key of new Set(msg.variants.map(keyOf))) {
45
+ if (key === null) {
46
+ needs.set(
47
+ null,
48
+ readBy((v) => keyOf(v) === null),
49
+ );
50
+ continue;
51
+ }
52
+ // First, the selector decides alone where a variant has `*` for every other selector.
53
+ const covered =
54
+ at === 0 &&
55
+ msg.variants.some(
56
+ (v) => keyOf(v) === key && v.keys.every((k, j) => j === 0 || k.type === '*'),
57
+ );
58
+ needs.set(
59
+ key,
60
+ readBy((v) => keyOf(v) === key || (!covered && keyOf(v) === null)),
61
+ );
62
+ }
63
+ const sets = [...needs.values()];
64
+ const differ = sets.some(
65
+ (set) => set.size !== sets[0]?.size || [...set].some((p) => !sets[0]?.has(p)),
66
+ );
67
+ return differ ? needs : undefined;
68
+ }
@@ -0,0 +1,140 @@
1
+ import path from 'node:path';
2
+
3
+ import { BUILTIN_FUNCTIONS } from '../compile/info.ts';
4
+ import type { FunctionKind } from '../compile/info.ts';
5
+
6
+ import { ConfigError } from './config.ts';
7
+ import type { NamespaceConfig, ResolvedNamespace } from './config.ts';
8
+
9
+ export function checkFunctions(
10
+ functions: Record<string, FunctionKind>,
11
+ ): Record<string, FunctionKind> {
12
+ const shadowing = Object.keys(functions).filter((name) => BUILTIN_FUNCTIONS.has(name));
13
+ if (shadowing.length > 0) {
14
+ throw new ConfigError(
15
+ `"functions" cannot redefine the built-in ${shadowing.map((n) => `:${n}`).join(', ')}`,
16
+ );
17
+ }
18
+ return functions;
19
+ }
20
+
21
+ /** Names that become path segments under `outDir`: no separators, no `..`. */
22
+ const NAMESPACE_NAME = /^[\w-]+(?:\.[\w-]+)*$/;
23
+
24
+ /** A tag `Intl` takes, such as `zh-Hant-TW`: any other would throw at the first plural or number. */
25
+ function checkLocale(locale: string): void {
26
+ let canonical: string | undefined;
27
+ try {
28
+ [canonical] = Intl.getCanonicalLocales(locale);
29
+ } catch {
30
+ const tag = locale.replaceAll('_', '-');
31
+ const hint = tag === locale ? ' such as "en" or "pt-BR"' : `: write "${tag}"`;
32
+ throw new ConfigError(`Locale "${locale}" is not a locale tag${hint}`);
33
+ }
34
+ // Fallbacks match tags by their spelling: `zh-hant-tw` would never inherit from `zh-Hant`.
35
+ if (canonical !== locale) {
36
+ throw new ConfigError(`Locale "${locale}" is not canonical: write "${canonical}"`);
37
+ }
38
+ }
39
+
40
+ function isInside(dir: string, file: string): boolean {
41
+ const rel = path.relative(dir, file);
42
+ return rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
43
+ }
44
+
45
+ /** Names of files: on macOS and Windows one would overwrite the other. */
46
+ function checkCase(what: string, names: ReadonlyArray<string>): void {
47
+ const seen = new Map<string, string>();
48
+ for (const name of names) {
49
+ const other = seen.get(name.toLowerCase()) ?? name;
50
+ if (other !== name) {
51
+ throw new ConfigError(`${what} "${other}" and "${name}" differ only in case: rename one`);
52
+ }
53
+ seen.set(name.toLowerCase(), name);
54
+ }
55
+ }
56
+
57
+ /** A fallback outside `locales` lends no text, only its `Intl` formats. */
58
+ export function checkFallbacks(
59
+ fallbacks: Record<string, Array<string>>,
60
+ {
61
+ locales,
62
+ hasCatalog,
63
+ }: {
64
+ readonly locales: ReadonlyArray<string>;
65
+ readonly hasCatalog: (locale: string) => boolean;
66
+ },
67
+ ): void {
68
+ for (const [locale, chain] of Object.entries(fallbacks)) {
69
+ if (!locales.includes(locale)) {
70
+ throw new ConfigError(`"fallbacks" lists "${locale}", which is not in locales`);
71
+ }
72
+ for (const fallback of chain.filter((l) => !locales.includes(l))) {
73
+ if (hasCatalog(fallback)) {
74
+ throw new ConfigError(
75
+ `"${locale}" falls back to "${fallback}", whose catalogs are not read: add it to locales`,
76
+ );
77
+ }
78
+ if (Intl.NumberFormat.supportedLocalesOf(fallback).length === 0) {
79
+ throw new ConfigError(
80
+ `"${locale}" falls back to "${fallback}", neither in locales nor known to Intl`,
81
+ );
82
+ }
83
+ }
84
+ }
85
+ }
86
+
87
+ /** Every tag `Intl` takes, each locale once, and the source locale among them. */
88
+ export function checkLocales({
89
+ locales,
90
+ sourceLocale,
91
+ fallbacks,
92
+ }: {
93
+ locales: ReadonlyArray<string>;
94
+ sourceLocale: string;
95
+ fallbacks: Record<string, Array<string>>;
96
+ }): void {
97
+ for (const locale of [
98
+ ...locales,
99
+ ...Object.keys(fallbacks),
100
+ ...Object.values(fallbacks).flat(),
101
+ ]) {
102
+ checkLocale(locale);
103
+ }
104
+ const repeated = locales.find((l, i) => locales.indexOf(l) !== i);
105
+ if (repeated !== undefined) {
106
+ throw new ConfigError(`Locale "${repeated}" is listed twice`);
107
+ }
108
+ if (!locales.includes(sourceLocale)) {
109
+ throw new ConfigError(`sourceLocale "${sourceLocale}" is not in locales`);
110
+ }
111
+ }
112
+
113
+ /** The config's namespaces, each with its catalogs' paths, none of them in `outDir`. */
114
+ export function resolveNamespaces(
115
+ namespaces: Record<string, NamespaceConfig>,
116
+ { root, outDir, locales }: { root: string; outDir: string; locales: ReadonlyArray<string> },
117
+ ): Array<ResolvedNamespace> {
118
+ checkCase('Namespaces', Object.keys(namespaces));
119
+ return Object.entries(namespaces).map(([name, ns]) => {
120
+ if (!NAMESPACE_NAME.test(name)) {
121
+ throw new ConfigError(
122
+ `Namespace "${name}" must be letters, digits, "_", "-" or inner dots: it names files`,
123
+ );
124
+ }
125
+ if (!ns.path.includes('{locale}')) {
126
+ throw new ConfigError(`Namespace "${name}" path must contain {locale}`);
127
+ }
128
+ const resolved: ResolvedNamespace = {
129
+ name,
130
+ format: ns.format,
131
+ file: (locale) => path.resolve(root, ns.path.replaceAll('{locale}', locale)),
132
+ };
133
+ if (locales.some((l) => isInside(outDir, resolved.file(l)))) {
134
+ throw new ConfigError(
135
+ `Namespace "${name}" has its catalogs in outDir, which holds generated files only: move one of them`,
136
+ );
137
+ }
138
+ return resolved;
139
+ });
140
+ }
@@ -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
+ }