@parlajs/x18n-plugin 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 (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +23 -2
  3. package/build/ast.d.ts +29 -0
  4. package/build/ast.d.ts.map +1 -0
  5. package/build/ast.js +64 -0
  6. package/build/bindings.d.ts +31 -0
  7. package/build/bindings.d.ts.map +1 -0
  8. package/build/bindings.js +177 -0
  9. package/build/configs.d.ts +7 -0
  10. package/build/configs.d.ts.map +1 -0
  11. package/build/configs.js +46 -0
  12. package/build/declare.d.ts +8 -0
  13. package/build/declare.d.ts.map +1 -0
  14. package/build/declare.js +69 -0
  15. package/build/index.d.ts +10 -0
  16. package/build/index.d.ts.map +1 -0
  17. package/build/index.js +23 -0
  18. package/build/namespaces.d.ts +11 -0
  19. package/build/namespaces.d.ts.map +1 -0
  20. package/build/namespaces.js +72 -0
  21. package/build/paths.d.ts +3 -0
  22. package/build/paths.d.ts.map +1 -0
  23. package/build/paths.js +7 -0
  24. package/build/placeholders.d.ts +3 -0
  25. package/build/placeholders.d.ts.map +1 -0
  26. package/build/placeholders.js +58 -0
  27. package/build/scanner.d.ts +4 -0
  28. package/build/scanner.d.ts.map +1 -0
  29. package/build/scanner.js +154 -0
  30. package/build/templates.d.ts +8 -0
  31. package/build/templates.d.ts.map +1 -0
  32. package/build/templates.js +107 -0
  33. package/build/types.d.ts +21 -0
  34. package/build/types.d.ts.map +1 -0
  35. package/build/types.js +1 -0
  36. package/build/values.d.ts +4 -0
  37. package/build/values.d.ts.map +1 -0
  38. package/build/values.js +29 -0
  39. package/package.json +64 -3
  40. package/src/ast.ts +90 -0
  41. package/src/bindings.ts +226 -0
  42. package/src/configs.ts +58 -0
  43. package/src/declare.ts +94 -0
  44. package/src/index.ts +34 -0
  45. package/src/namespaces.ts +93 -0
  46. package/src/paths.ts +9 -0
  47. package/src/placeholders.ts +63 -0
  48. package/src/scanner.ts +175 -0
  49. package/src/templates.ts +115 -0
  50. package/src/types.ts +27 -0
  51. package/src/values.ts +33 -0
@@ -0,0 +1,226 @@
1
+ import { isNode, segmentOf, stringValue } from './ast.ts';
2
+ import type { Node } from './ast.ts';
3
+ import { loadedBy, namespacesOf, translationsOf, WRAPPERS } from './namespaces.ts';
4
+
5
+ /** What a name holds: a `t`, one namespace's messages, a hook's result with a `t`, or a promise of `t`. */
6
+ type Holds =
7
+ | { readonly namespaces: ReadonlyArray<string> }
8
+ | { readonly namespace: string }
9
+ | { readonly hook: ReadonlyArray<string> }
10
+ | { readonly promise: ReadonlyArray<string> };
11
+
12
+ /** A name that holds messages, visible inside `scope`. */
13
+ export type Binding = Holds & { readonly name: string; readonly scope: Node };
14
+
15
+ /** The innermost binding of `name` whose scope holds `position`. */
16
+ export function resolve(
17
+ bindings: ReadonlyArray<Binding>,
18
+ { name, position }: { name: string; position: number },
19
+ ): Binding | undefined {
20
+ let best: Binding | undefined;
21
+ for (const binding of bindings) {
22
+ const { scope } = binding;
23
+ const inside = binding.name === name && scope.start <= position && position < scope.end;
24
+ if (inside && (!best || scope.end - scope.start < best.scope.end - best.scope.start)) {
25
+ best = binding;
26
+ }
27
+ }
28
+ return best;
29
+ }
30
+
31
+ const FUNCTIONS = new Set(['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression']);
32
+
33
+ /** The local name `t` is bound to in `{ t }` or `{ t: alias }`. */
34
+ function tName(pattern: Node): string | undefined {
35
+ for (const property of pattern['properties'] as Array<Node>) {
36
+ const { key } = property;
37
+ const { value } = property;
38
+ if (
39
+ property.type === 'Property' &&
40
+ isNode(key) &&
41
+ key['name'] === 't' &&
42
+ isNode(value) &&
43
+ value.type === 'Identifier'
44
+ ) {
45
+ return value['name'] as string;
46
+ }
47
+ }
48
+ return undefined;
49
+ }
50
+
51
+ /** `const t = …`, or `const { checkout: messages } = …`, of a `t` with these namespaces. */
52
+ function boundNames(
53
+ id: unknown,
54
+ namespaces: ReadonlyArray<string>,
55
+ ): Array<Holds & { readonly name: string }> {
56
+ if (!isNode(id)) {
57
+ return [];
58
+ }
59
+ if (id.type === 'Identifier') {
60
+ return [{ name: id['name'] as string, namespaces }];
61
+ }
62
+ const properties = id.type === 'ObjectPattern' ? (id['properties'] as Array<Node>) : [];
63
+ return properties.flatMap(({ key, value }) => {
64
+ const namespace = isNode(key) ? (stringValue(key) ?? (key['name'] as string)) : '';
65
+ return namespaces.includes(namespace) && isNode(value) && value.type === 'Identifier'
66
+ ? [{ name: value['name'] as string, namespace }]
67
+ : [];
68
+ });
69
+ }
70
+
71
+ /** `t: Translations<typeof ns>`, or `{ t }: { t: Translations<typeof ns> }`, in a function's params. */
72
+ function paramBinding(
73
+ param: Node,
74
+ imports: ReadonlyMap<string, string>,
75
+ ): [string, Array<string>] | undefined {
76
+ const type = (param['typeAnnotation'] as Node | null)?.['typeAnnotation'];
77
+ if (param.type === 'Identifier') {
78
+ const namespaces = translationsOf(type, imports);
79
+ return namespaces && [param['name'] as string, namespaces];
80
+ }
81
+ const name = param.type === 'ObjectPattern' ? tName(param) : undefined;
82
+ if (!isNode(type) || type.type !== 'TSTypeLiteral' || name === undefined) {
83
+ return undefined;
84
+ }
85
+ for (const member of type['members'] as Array<Node>) {
86
+ const { key } = member;
87
+ if (member.type === 'TSPropertySignature' && isNode(key) && key['name'] === 't') {
88
+ const annotation = (member['typeAnnotation'] as Node | null)?.['typeAnnotation'];
89
+ const namespaces = translationsOf(annotation, imports);
90
+ return namespaces && [name, namespaces];
91
+ }
92
+ }
93
+ return undefined;
94
+ }
95
+
96
+ interface Collect {
97
+ /** The innermost function around the node, or the program. */
98
+ readonly scope: Node;
99
+ readonly callees: ReadonlySet<string>;
100
+ readonly imports: ReadonlyMap<string, string>;
101
+ readonly out: Array<Binding>;
102
+ }
103
+
104
+ type Context = Omit<Collect, 'scope'> & { readonly position: number };
105
+
106
+ /** What `await x`, `x!`, `(x)` or Svelte's `$derived(x)` wraps. */
107
+ function wrapped(node: Node): unknown {
108
+ if (node.type === 'AwaitExpression' || WRAPPERS.has(node.type)) {
109
+ return node['argument'] ?? node['expression'];
110
+ }
111
+ const { callee } = node;
112
+ const args = node['arguments'] as Array<unknown> | undefined;
113
+ const isDerived = isNode(callee) && callee['name'] === '$derived' && args?.length === 1;
114
+ return node.type === 'CallExpression' && isDerived ? args[0] : undefined;
115
+ }
116
+
117
+ function unwrap(node: unknown): { node: unknown; awaited: boolean } {
118
+ let current = node;
119
+ let awaited = false;
120
+ let next = isNode(current) ? wrapped(current) : undefined;
121
+ while (next !== undefined) {
122
+ awaited ||= (current as Node).type === 'AwaitExpression';
123
+ current = next;
124
+ next = isNode(current) ? wrapped(current) : undefined;
125
+ }
126
+ return { node: current, awaited };
127
+ }
128
+
129
+ /** A hook's result, or `x.load([…])` not awaited. */
130
+ function called(
131
+ node: Node,
132
+ { awaited, callees, imports }: Context & { awaited: boolean },
133
+ ): Holds | undefined {
134
+ const { callee } = node;
135
+ const namespaces = namespacesOf((node['arguments'] as Array<Node>)[0], imports);
136
+ if (!namespaces || !isNode(callee)) {
137
+ return undefined;
138
+ }
139
+ if (callee.type === 'Identifier' && callees.has(callee['name'] as string)) {
140
+ return { hook: namespaces };
141
+ }
142
+ const isLoad = callee.type === 'MemberExpression' && segmentOf(callee)?.name === 'load';
143
+ return isLoad && !awaited ? { promise: namespaces } : undefined;
144
+ }
145
+
146
+ /** What a declaration's `init` holds, if anything Parla's. */
147
+ function holdsOf(init: unknown, context: Context): Holds | undefined {
148
+ const loaded = loadedBy(init, context.imports);
149
+ if (loaded) {
150
+ return { namespaces: loaded };
151
+ }
152
+ const { node, awaited } = unwrap(init);
153
+ if (!isNode(node)) {
154
+ return undefined;
155
+ }
156
+ if (node.type === 'CallExpression') {
157
+ return called(node, { ...context, awaited });
158
+ }
159
+ // `messages.t` of a hook's result, or a promise of `t`.
160
+ const held = node.type === 'MemberExpression' ? node['object'] : node;
161
+ const binding =
162
+ isNode(held) && held.type === 'Identifier'
163
+ ? resolve(context.out, { name: held['name'] as string, position: context.position })
164
+ : undefined;
165
+ if (binding && 'hook' in binding && held !== node && segmentOf(node)?.name === 't') {
166
+ return { namespaces: binding.hook };
167
+ }
168
+ if (binding && 'promise' in binding && held === node) {
169
+ return awaited ? { namespaces: binding.promise } : { promise: binding.promise };
170
+ }
171
+ return undefined;
172
+ }
173
+
174
+ /** The names `id` binds to what `holds` holds. */
175
+ function bind(id: unknown, holds: Holds): Array<Holds & { readonly name: string }> {
176
+ if ('namespaces' in holds) {
177
+ return boundNames(id, holds.namespaces);
178
+ }
179
+ if (isNode(id) && id.type === 'Identifier') {
180
+ return [{ ...holds, name: id['name'] as string }];
181
+ }
182
+ const name = 'hook' in holds && isNode(id) && id.type === 'ObjectPattern' ? tName(id) : undefined;
183
+ return 'hook' in holds && name !== undefined ? [{ name, namespaces: holds.hook }] : [];
184
+ }
185
+
186
+ /** `promise.then((t) => …)` on a promise of `t`. */
187
+ function thenBindings(node: Node, context: Context): Array<Binding> {
188
+ const { callee } = node;
189
+ if (node.type !== 'CallExpression' || !isNode(callee) || segmentOf(callee)?.name !== 'then') {
190
+ return [];
191
+ }
192
+ const [callback] = node['arguments'] as Array<Node>;
193
+ const [param] =
194
+ isNode(callback) && FUNCTIONS.has(callback.type) ? (callback['params'] as Array<Node>) : [];
195
+ const holds = holdsOf(callee['object'], context);
196
+ return param && holds && 'promise' in holds
197
+ ? boundNames(param, holds.promise).map((bound) => ({ ...bound, scope: callback as Node }))
198
+ : [];
199
+ }
200
+
201
+ export function collectBindings(node: Node, collect: Collect): void {
202
+ const { scope, out } = collect;
203
+ const inner = FUNCTIONS.has(node.type) ? node : scope;
204
+ for (const param of FUNCTIONS.has(node.type) ? (node['params'] as Array<Node>) : []) {
205
+ const binding = paramBinding(param, collect.imports);
206
+ if (binding) {
207
+ out.push({ name: binding[0], namespaces: binding[1], scope: node });
208
+ }
209
+ }
210
+ const context = { ...collect, position: node.start };
211
+ if (node.type === 'VariableDeclarator') {
212
+ const holds = holdsOf(node['init'], context);
213
+ for (const bound of holds ? bind(node['id'], holds) : []) {
214
+ out.push({ ...bound, scope: inner });
215
+ }
216
+ }
217
+ out.push(...thenBindings(node, context));
218
+ const within = inner === scope ? collect : { ...collect, scope: inner };
219
+ for (const value of Object.values(node)) {
220
+ for (const child of Array.isArray(value) ? value : [value]) {
221
+ if (isNode(child)) {
222
+ collectBindings(child, within);
223
+ }
224
+ }
225
+ }
226
+ }
package/src/configs.ts ADDED
@@ -0,0 +1,58 @@
1
+ import { loadConfig } from '@parlajs/compiler';
2
+ import type { ResolvedConfig } from '@parlajs/compiler';
3
+
4
+ import { declare } from './declare.ts';
5
+ import { relative } from './paths.ts';
6
+ import type { Declared, Host, LocaleFinder } from './types.ts';
7
+
8
+ /**
9
+ * Each catalog file under the namespace its parla config gives it, so `scopeAudit` may live in
10
+ * `scope_audit.json`; `pre`, so these names win over a `resources` pattern matching the same file.
11
+ */
12
+ export function configFinder(
13
+ configs: ReadonlyArray<string> | undefined,
14
+ declared: Declared,
15
+ ): LocaleFinder {
16
+ let loaded: Promise<Array<ResolvedConfig>> | undefined;
17
+ const load = async (host: Host): Promise<Array<ResolvedConfig>> => {
18
+ loaded ??= (async (): Promise<Array<ResolvedConfig>> => {
19
+ const files =
20
+ configs ??
21
+ (await host.glob(['**/parla.config.{ts,mts}'], {
22
+ ignore: ['**/node_modules/**'],
23
+ gitignore: true,
24
+ }));
25
+ const all = await Promise.all(files.map(async (file) => loadConfig(host.root, file)));
26
+ await declare(declared, {
27
+ configs: all,
28
+ readFile: async (path) => host.readFile(relative(host.root, path)),
29
+ });
30
+ return all;
31
+ })();
32
+ return loaded;
33
+ };
34
+ let resolved: Array<ResolvedConfig> = [];
35
+ return {
36
+ id: 'parla:configs',
37
+ async find({ host }) {
38
+ resolved = await load(host);
39
+ return resolved.flatMap((config) =>
40
+ config.namespaces.flatMap((ns) =>
41
+ config.locales.map((locale) => ({
42
+ path: relative(host.root, ns.file(locale)),
43
+ locale,
44
+ namespace: ns.name,
45
+ })),
46
+ ),
47
+ );
48
+ },
49
+ resolveNew({ locale, namespace }, { host }): string | undefined {
50
+ const file = resolved
51
+ .filter((config) => config.locales.includes(locale))
52
+ .flatMap((config) => config.namespaces)
53
+ .find((ns) => ns.name === namespace)
54
+ ?.file(locale);
55
+ return file === undefined ? file : relative(host.root, file);
56
+ },
57
+ };
58
+ }
package/src/declare.ts ADDED
@@ -0,0 +1,94 @@
1
+ import { compileMessage } from '@parlajs/compiler';
2
+ import type { CustomFunctions, FormatAdapter, ResolvedConfig } from '@parlajs/compiler';
3
+
4
+ import type { Declared, ReadFile } from './types.ts';
5
+
6
+ type Catalog = Readonly<Record<string, unknown>>;
7
+
8
+ /** `[path, message]` for every leaf of a catalog; the compiler reports what is no message. */
9
+ function* leaves(catalog: unknown, prefix = ''): Generator<[string, string]> {
10
+ if (!catalog || typeof catalog !== 'object' || Array.isArray(catalog)) {
11
+ return;
12
+ }
13
+ for (const [key, value] of Object.entries(catalog)) {
14
+ if (typeof value === 'string') {
15
+ yield [`${prefix}${key}`, value];
16
+ } else {
17
+ yield* leaves(value, `${prefix}${key}.`);
18
+ }
19
+ }
20
+ }
21
+
22
+ /** A catalog's messages, read as its format reads them; an unreadable one counts as empty. */
23
+ async function readCatalog(
24
+ readFile: ReadFile,
25
+ { path, adapter }: { path: string; adapter: FormatAdapter | undefined },
26
+ ): Promise<Catalog> {
27
+ try {
28
+ const text = await readFile(path);
29
+ if (text === undefined) {
30
+ return {};
31
+ }
32
+ return (adapter?.parseFile ? adapter.parseFile(text) : JSON.parse(text)) as Catalog;
33
+ } catch {
34
+ return {};
35
+ }
36
+ }
37
+
38
+ /** Whether a message selects on keys that need different params. */
39
+ function hasBranches(
40
+ value: string,
41
+ { adapter, functions }: { adapter: FormatAdapter | undefined; functions: CustomFunctions },
42
+ ): boolean {
43
+ try {
44
+ return Boolean(
45
+ adapter && compileMessage(adapter.parse(value), { custom: functions }).info.branches,
46
+ );
47
+ } catch {
48
+ // Reported by `validate`.
49
+ return false;
50
+ }
51
+ }
52
+
53
+ /** Fills `declared` from the configs and their source catalogs. */
54
+ export async function declare(
55
+ declared: Declared,
56
+ { configs, readFile }: { configs: ReadonlyArray<ResolvedConfig>; readFile: ReadFile },
57
+ ): Promise<void> {
58
+ for (const config of configs) {
59
+ Object.assign(declared.functions, config.functions);
60
+ for (const [name, adapter] of Object.entries(config.formats)) {
61
+ if (!declared.formats.has(name)) {
62
+ declared.formats.set(name, adapter);
63
+ }
64
+ }
65
+ declared.markup.push(...config.markup.filter((tag) => !declared.markup.includes(tag)));
66
+ }
67
+ // `placeholders` tells ICU from MF2 by name, so they read only the source locale.
68
+ const sources = configs.flatMap((config) =>
69
+ config.namespaces.flatMap((ns) => {
70
+ const adapter = config.formats[ns.format];
71
+ const own = ns.format !== 'icu' && ns.format !== 'mf2';
72
+ const locales = own ? config.locales : [config.sourceLocale];
73
+ return locales.map((locale) => ({ config, ns, adapter, own, locale }));
74
+ }),
75
+ );
76
+ const catalogs = await Promise.all(
77
+ sources.map(async ({ ns, adapter, locale }) =>
78
+ readCatalog(readFile, { path: ns.file(locale), adapter }),
79
+ ),
80
+ );
81
+ for (const [index, { config, ns, adapter, own, locale }] of sources.entries()) {
82
+ for (const [key, value] of leaves(catalogs[index] ?? {})) {
83
+ if (own && adapter) {
84
+ declared.syntaxes.set(value, adapter);
85
+ }
86
+ if (
87
+ locale === config.sourceLocale &&
88
+ hasBranches(value, { adapter, functions: config.functions })
89
+ ) {
90
+ declared.branchy.add(`${ns.name}:${key}`);
91
+ }
92
+ }
93
+ }
94
+ }
package/src/index.ts ADDED
@@ -0,0 +1,34 @@
1
+ import type { Plugin } from '@x18n/core';
2
+
3
+ import { configFinder } from './configs.ts';
4
+ import { placeholders } from './placeholders.ts';
5
+ import { accessorScanner } from './scanner.ts';
6
+ import type { Declared } from './types.ts';
7
+
8
+ export interface ParlaOptions {
9
+ /** Hooks that take a list of namespaces and return `{ t }`. Default: both of Parla's. */
10
+ readonly callees?: ReadonlyArray<string>;
11
+ /** Parla configs whose namespaces x18n reads, relative to the root. Default: every `parla.config.ts` or `.mts`. */
12
+ readonly configs?: ReadonlyArray<string>;
13
+ }
14
+
15
+ /** The x18n plugin: Parla's catalogs, `t.ns.key()` usages, and ICU and MF2 params. */
16
+ export default function parla(options: ParlaOptions = {}): Plugin {
17
+ const declared: Declared = {
18
+ functions: {},
19
+ formats: new Map(),
20
+ syntaxes: new Map(),
21
+ markup: [],
22
+ branchy: new Set(),
23
+ };
24
+ return {
25
+ name: 'parla',
26
+ enforce: 'pre',
27
+ runtime: 'node',
28
+ localeFinders: [configFinder(options.configs, declared)],
29
+ scanners: [
30
+ accessorScanner(new Set(options.callees ?? ['useParla', 'useParlaLoaded']), declared),
31
+ ],
32
+ placeholders: [placeholders(declared)],
33
+ };
34
+ }
@@ -0,0 +1,93 @@
1
+ import { isNode, segmentOf, stringValue } from './ast.ts';
2
+ import type { Node } from './ast.ts';
3
+
4
+ // Parla writes each namespace to `namespaces/<name>.js`, so the path names it whatever the binding.
5
+ // A bundler needs no extension.
6
+ const NAMESPACE_MODULE = /\/namespaces\/(?<name>[^/]+?)(?:\.js)?$/;
7
+
8
+ /** Local names of the namespace objects a file imports, to their namespace. */
9
+ export function namespaceImports(program: Node): Map<string, string> {
10
+ const out = new Map<string, string>();
11
+ for (const statement of program['body'] as Array<Node>) {
12
+ const name =
13
+ statement.type === 'ImportDeclaration'
14
+ ? stringValue(statement['source'])?.match(NAMESPACE_MODULE)?.groups?.['name']
15
+ : undefined;
16
+ for (const specifier of name ? (statement['specifiers'] as Array<Node>) : []) {
17
+ const { local } = specifier;
18
+ if (specifier.type === 'ImportSpecifier' && isNode(local)) {
19
+ out.set(local['name'] as string, name as string);
20
+ }
21
+ }
22
+ }
23
+ return out;
24
+ }
25
+
26
+ /** `[a, b]`; undefined unless every element is an imported namespace object. */
27
+ export function namespacesOf(
28
+ arg: unknown,
29
+ imports: ReadonlyMap<string, string>,
30
+ ): Array<string> | undefined {
31
+ if (!isNode(arg) || arg.type !== 'ArrayExpression') {
32
+ return undefined;
33
+ }
34
+ const namespaces = (arg['elements'] as Array<unknown>).map((element) =>
35
+ isNode(element) && element.type === 'Identifier'
36
+ ? imports.get(element['name'] as string)
37
+ : undefined,
38
+ );
39
+ return namespaces.every((ns) => ns !== undefined) ? namespaces : undefined;
40
+ }
41
+
42
+ /** `Translations<typeof a | typeof b>` → the namespaces of `a` and `b`; undefined for anything else. */
43
+ export function translationsOf(
44
+ type: unknown,
45
+ imports: ReadonlyMap<string, string>,
46
+ ): Array<string> | undefined {
47
+ if (!isNode(type) || type.type !== 'TSTypeReference') {
48
+ return undefined;
49
+ }
50
+ const name = type['typeName'];
51
+ const arg = ((type['typeArguments'] as Node | null)?.['params'] as Array<Node> | undefined)?.at(
52
+ 0,
53
+ );
54
+ if (!isNode(name) || name['name'] !== 'Translations' || !arg) {
55
+ return undefined;
56
+ }
57
+ const queries = arg.type === 'TSUnionType' ? (arg['types'] as Array<Node>) : [arg];
58
+ const namespaces = queries.map((query) => {
59
+ const expr = query['exprName'];
60
+ return query.type === 'TSTypeQuery' && isNode(expr)
61
+ ? imports.get(expr['name'] as string)
62
+ : undefined;
63
+ });
64
+ return namespaces.every((ns) => ns !== undefined) ? namespaces : undefined;
65
+ }
66
+
67
+ export const WRAPPERS = new Set([
68
+ 'TSNonNullExpression',
69
+ 'ParenthesizedExpression',
70
+ 'ChainExpression',
71
+ ]);
72
+
73
+ /** The namespaces of `await x.load([a, b])` or `x.loaded([a, b])`, whatever `x` is. */
74
+ export function loadedBy(
75
+ init: unknown,
76
+ imports: ReadonlyMap<string, string>,
77
+ ): Array<string> | undefined {
78
+ let node = init;
79
+ let awaited = false;
80
+ while (isNode(node) && (node.type === 'AwaitExpression' || WRAPPERS.has(node.type))) {
81
+ awaited ||= node.type === 'AwaitExpression';
82
+ node = node['argument'] ?? node['expression'];
83
+ }
84
+ if (!isNode(node) || node.type !== 'CallExpression') {
85
+ return undefined;
86
+ }
87
+ const { callee } = node;
88
+ const method = isNode(callee) && callee.type === 'MemberExpression' && segmentOf(callee)?.name;
89
+ const [arg] = node['arguments'] as Array<Node>;
90
+ return method === 'loaded' || (method === 'load' && awaited)
91
+ ? namespacesOf(arg, imports)
92
+ : undefined;
93
+ }
package/src/paths.ts ADDED
@@ -0,0 +1,9 @@
1
+ import path from 'node:path';
2
+
3
+ const posix = (file: string): string => file.replaceAll(path.sep, '/');
4
+
5
+ /** `file` relative to `root`, as x18n names resources: with `/` on Windows too. */
6
+ export function relative(root: string, file: string): string {
7
+ const [dir, target] = [posix(root), posix(file)];
8
+ return target.startsWith(`${dir}/`) ? target.slice(dir.length + 1) : target;
9
+ }
@@ -0,0 +1,63 @@
1
+ import { compileMessage } from '@parlajs/compiler';
2
+
3
+ import type { Declared, Placeholder, PlaceholderSyntax } from './types.ts';
4
+
5
+ // A namespace's format is in parla's config, which a placeholder syntax never sees: only MF2
6
+ // writes `{$name}` or starts with a declaration, and ICU is tried first. Other formats are known for
7
+ // the messages `declare` read.
8
+ const MF2_ONLY = /\{\s*\$|^\s*\.(?:input|local|match)\b/;
9
+
10
+ /** Params and markup a message reads, through parla's own parsers. Throws on invalid syntax. */
11
+ function messageNames(value: string, declared: Declared): Array<string> {
12
+ const own = declared.syntaxes.get(value);
13
+ const builtIn = (MF2_ONLY.test(value) ? ['mf2'] : ['icu', 'mf2']).flatMap(
14
+ (id) => declared.formats.get(id) ?? [],
15
+ );
16
+ let firstError: Error | undefined;
17
+ for (const format of own ? [own] : builtIn) {
18
+ try {
19
+ const { info } = compileMessage(format.parse(value), { custom: declared.functions });
20
+ return [...new Set([...info.params.keys(), ...info.markup])];
21
+ } catch (error) {
22
+ firstError ??= error as Error;
23
+ }
24
+ }
25
+ // No config reads ICU or MF2, so this message has no syntax to check.
26
+ if (firstError === undefined) {
27
+ return [];
28
+ }
29
+ throw firstError;
30
+ }
31
+
32
+ /** Where `name` opens a placeholder or tag (`{name`, `{$name`, `{#name`, `<name`), not inside text. */
33
+ function nameAt(value: string, name: string): number {
34
+ const escaped = name.replaceAll(/[$()*+.?[\\\]^{|}-]/g, String.raw`\$&`);
35
+ const match = new RegExp(String.raw`[{<]\s*[$#/]?\s*(?:${escaped})(?![\w.-])`).exec(value);
36
+ return match ? match.index + match[0].length - name.length : value.indexOf(name);
37
+ }
38
+
39
+ export const placeholders = (declared: Declared): PlaceholderSyntax => ({
40
+ id: 'parla',
41
+ example: '{name}',
42
+ implicit: declared.markup,
43
+ find(value): Array<Placeholder> {
44
+ let names: Array<string>;
45
+ try {
46
+ names = messageNames(value, declared);
47
+ } catch {
48
+ return [];
49
+ }
50
+ return names.map((name): Placeholder => {
51
+ const start = Math.max(nameAt(value, name), 0);
52
+ return { syntax: 'parla', text: name, name, range: { start, end: start + name.length } };
53
+ });
54
+ },
55
+ validate(value): Array<string> {
56
+ try {
57
+ messageNames(value, declared);
58
+ return [];
59
+ } catch (error) {
60
+ return [(error as Error).message];
61
+ }
62
+ },
63
+ });