@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.
Files changed (159) 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/config/checks.d.ts +21 -0
  34. package/build/config/checks.d.ts.map +1 -0
  35. package/build/config/checks.js +97 -0
  36. package/build/config/config.d.ts +71 -0
  37. package/build/config/config.d.ts.map +1 -0
  38. package/build/config/config.js +7 -0
  39. package/build/config/fallbacks.d.ts +6 -0
  40. package/build/config/fallbacks.d.ts.map +1 -0
  41. package/build/config/fallbacks.js +13 -0
  42. package/build/config/import.d.ts +31 -0
  43. package/build/config/import.d.ts.map +1 -0
  44. package/build/config/import.js +115 -0
  45. package/build/config/load.d.ts +13 -0
  46. package/build/config/load.d.ts.map +1 -0
  47. package/build/config/load.js +59 -0
  48. package/build/diagnostics.d.ts +31 -0
  49. package/build/diagnostics.d.ts.map +1 -0
  50. package/build/diagnostics.js +41 -0
  51. package/build/generate/checks.d.ts +9 -0
  52. package/build/generate/checks.d.ts.map +1 -0
  53. package/build/generate/checks.js +93 -0
  54. package/build/generate/chunk.d.ts +11 -0
  55. package/build/generate/chunk.d.ts.map +1 -0
  56. package/build/generate/chunk.js +57 -0
  57. package/build/generate/digits.d.ts +8 -0
  58. package/build/generate/digits.d.ts.map +1 -0
  59. package/build/generate/digits.js +57 -0
  60. package/build/generate/files.d.ts +7 -0
  61. package/build/generate/files.d.ts.map +1 -0
  62. package/build/generate/files.js +59 -0
  63. package/build/generate/locale.d.ts +21 -0
  64. package/build/generate/locale.d.ts.map +1 -0
  65. package/build/generate/locale.js +108 -0
  66. package/build/generate/modules.d.ts +27 -0
  67. package/build/generate/modules.d.ts.map +1 -0
  68. package/build/generate/modules.js +61 -0
  69. package/build/generate/namespace.d.ts +19 -0
  70. package/build/generate/namespace.d.ts.map +1 -0
  71. package/build/generate/namespace.js +65 -0
  72. package/build/generate/namespaces.d.ts +5 -0
  73. package/build/generate/namespaces.d.ts.map +1 -0
  74. package/build/generate/namespaces.js +41 -0
  75. package/build/generate/read.d.ts +21 -0
  76. package/build/generate/read.d.ts.map +1 -0
  77. package/build/generate/read.js +115 -0
  78. package/build/index.d.ts +9 -0
  79. package/build/index.d.ts.map +1 -0
  80. package/build/index.js +7 -0
  81. package/build/init/detect.d.ts +43 -0
  82. package/build/init/detect.d.ts.map +1 -0
  83. package/build/init/detect.js +69 -0
  84. package/build/init/init.d.ts +12 -0
  85. package/build/init/init.d.ts.map +1 -0
  86. package/build/init/init.js +126 -0
  87. package/build/options/date.d.ts +3 -0
  88. package/build/options/date.d.ts.map +1 -0
  89. package/build/options/date.js +77 -0
  90. package/build/options/literal.d.ts +10 -0
  91. package/build/options/literal.d.ts.map +1 -0
  92. package/build/options/literal.js +11 -0
  93. package/build/options/names.d.ts +5 -0
  94. package/build/options/names.d.ts.map +1 -0
  95. package/build/options/names.js +56 -0
  96. package/build/options/number.d.ts +3 -0
  97. package/build/options/number.d.ts.map +1 -0
  98. package/build/options/number.js +17 -0
  99. package/build/options/options.d.ts +7 -0
  100. package/build/options/options.d.ts.map +1 -0
  101. package/build/options/options.js +66 -0
  102. package/build/plurals.d.ts +6 -0
  103. package/build/plurals.d.ts.map +1 -0
  104. package/build/plurals.js +50 -0
  105. package/build/types/names.d.ts +9 -0
  106. package/build/types/names.d.ts.map +1 -0
  107. package/build/types/names.js +109 -0
  108. package/build/types/namespace.d.ts +17 -0
  109. package/build/types/namespace.d.ts.map +1 -0
  110. package/build/types/namespace.js +113 -0
  111. package/build/types/signature.d.ts +8 -0
  112. package/build/types/signature.d.ts.map +1 -0
  113. package/build/types/signature.js +87 -0
  114. package/build/vite.d.ts +9 -0
  115. package/build/vite.d.ts.map +1 -0
  116. package/build/vite.js +125 -0
  117. package/build/watch.d.ts +12 -0
  118. package/build/watch.d.ts.map +1 -0
  119. package/build/watch.js +93 -0
  120. package/package.json +84 -3
  121. package/src/build.ts +31 -0
  122. package/src/cli.ts +9 -0
  123. package/src/command.ts +195 -0
  124. package/src/compile/code.ts +51 -0
  125. package/src/compile/compile.ts +289 -0
  126. package/src/compile/error.ts +3 -0
  127. package/src/compile/info.ts +63 -0
  128. package/src/compile/scope.ts +14 -0
  129. package/src/compile/single.ts +46 -0
  130. package/src/compile/variants.ts +68 -0
  131. package/src/config/checks.ts +140 -0
  132. package/src/config/config.ts +83 -0
  133. package/src/config/fallbacks.ts +18 -0
  134. package/src/config/import.ts +146 -0
  135. package/src/config/load.ts +75 -0
  136. package/src/diagnostics.ts +98 -0
  137. package/src/generate/checks.ts +103 -0
  138. package/src/generate/chunk.ts +73 -0
  139. package/src/generate/digits.ts +74 -0
  140. package/src/generate/files.ts +83 -0
  141. package/src/generate/locale.ts +145 -0
  142. package/src/generate/modules.ts +94 -0
  143. package/src/generate/namespace.ts +119 -0
  144. package/src/generate/namespaces.ts +59 -0
  145. package/src/generate/read.ts +159 -0
  146. package/src/index.ts +27 -0
  147. package/src/init/detect.ts +103 -0
  148. package/src/init/init.ts +158 -0
  149. package/src/options/date.ts +87 -0
  150. package/src/options/literal.ts +21 -0
  151. package/src/options/names.ts +64 -0
  152. package/src/options/number.ts +20 -0
  153. package/src/options/options.ts +75 -0
  154. package/src/plurals.ts +68 -0
  155. package/src/types/names.ts +115 -0
  156. package/src/types/namespace.ts +148 -0
  157. package/src/types/signature.ts +111 -0
  158. package/src/vite.ts +143 -0
  159. package/src/watch.ts +115 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Marco Pasqualetti
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,22 @@
1
- # Temporary Holding Version
1
+ # @parlajs/compiler
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [Parla](https://github.com/parlajs/parla)'s CLI and Vite plugin: builds catalogs into typed
4
+ namespaces, one chunk per locale × namespace.
5
+
6
+ ```sh
7
+ parla init # parla.config.ts, catalogs, .gitignore; prints what is left
8
+ parla build # or the Vite plugin, which rebuilds on every catalog change
9
+ ```
10
+
11
+ ```ts
12
+ import { parla } from '@parlajs/compiler/vite';
13
+
14
+ export default defineConfig({ plugins: [parla(), react()] });
15
+ ```
16
+
17
+ Docs: [CLI and Vite plugin](https://parlajs.github.io/parla/core/cli/),
18
+ [`parla.config.ts`](https://parlajs.github.io/parla/core/config/).
19
+
20
+ ## License
21
+
22
+ [MIT](./LICENSE)
@@ -0,0 +1,18 @@
1
+ import type { ResolvedConfig } from './config/config.ts';
2
+ import type { Diagnostic } from './diagnostics.ts';
3
+ export interface BuildOptions {
4
+ cwd?: string;
5
+ /** Path to the config file, relative to `cwd`. */
6
+ config?: string | undefined;
7
+ /** `false` writes nothing: a check. */
8
+ write?: boolean | undefined;
9
+ }
10
+ export interface BuildResult {
11
+ config: ResolvedConfig;
12
+ diagnostics: Array<Diagnostic>;
13
+ written: Array<string>;
14
+ /** Files an earlier build generated that this one no longer does. */
15
+ removed: Array<string>;
16
+ }
17
+ export declare function build(options?: BuildOptions): Promise<BuildResult>;
18
+ //# sourceMappingURL=build.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../src/build.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEzD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAKnD,MAAM,WAAW,YAAY;IAC3B,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,kDAAkD;IAClD,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,uCAAuC;IACvC,KAAK,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;CAC7B;AAED,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,cAAc,CAAC;IACvB,WAAW,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC;IAC/B,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IACvB,qEAAqE;IACrE,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;CACxB;AAED,wBAAsB,KAAK,CAAC,OAAO,GAAE,YAAiB,GAAG,OAAO,CAAC,WAAW,CAAC,CAO5E"}
package/build/build.js ADDED
@@ -0,0 +1,10 @@
1
+ import { loadConfig } from './config/load.js';
2
+ import { writeOutput } from './generate/files.js';
3
+ import { buildNamespaces } from './generate/namespaces.js';
4
+ export async function build(options = {}) {
5
+ const config = await loadConfig(options.cwd ?? process.cwd(), options.config);
6
+ const out = { diagnostics: [], files: new Map() };
7
+ buildNamespaces(config, out);
8
+ const { written, removed } = (options.write ?? true) ? writeOutput(config, out.files) : { written: [], removed: [] };
9
+ return { config, diagnostics: out.diagnostics, written, removed };
10
+ }
package/build/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
package/build/cli.js ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ import { runCommand } from './command.js';
3
+ const { code } = await runCommand(process.argv.slice(2), {
4
+ cwd: process.cwd(),
5
+ log: console.log,
6
+ error: console.error,
7
+ });
8
+ process.exitCode = code;
@@ -0,0 +1,13 @@
1
+ export interface CommandIO {
2
+ readonly cwd: string;
3
+ readonly log: (line: string) => void;
4
+ readonly error: (line: string) => void;
5
+ }
6
+ export interface CommandRun {
7
+ readonly code: number;
8
+ /** Stops watching; a no-op unless `--watch`. */
9
+ readonly close: () => void;
10
+ }
11
+ /** Runs `parla <args>`: the exit code, and in watch mode the watchers that keep it running. */
12
+ export declare function runCommand(args: ReadonlyArray<string>, { cwd, log, error }: CommandIO): Promise<CommandRun>;
13
+ //# sourceMappingURL=command.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"command.d.ts","sourceRoot":"","sources":["../src/command.ts"],"names":[],"mappings":"AA6BA,MAAM,WAAW,SAAS;IACxB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IACrC,QAAQ,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CACxC;AAED,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,gDAAgD;IAChD,QAAQ,CAAC,KAAK,EAAE,MAAM,IAAI,CAAC;CAC5B;AAuFD,+FAA+F;AAC/F,wBAAsB,UAAU,CAC9B,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,EAC3B,EAAE,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,EAAE,SAAS,GAC7B,OAAO,CAAC,UAAU,CAAC,CAgErB"}
@@ -0,0 +1,156 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { build } from './build.js';
3
+ import { ConfigError } from './config/config.js';
4
+ import { formatDiagnostics, unreported } from './diagnostics.js';
5
+ import { init } from './init/init.js';
6
+ import { rebuildOnChange } from './watch.js';
7
+ const HELP = `Usage: parla <command> [options]
8
+
9
+ Commands
10
+ build Compile catalogs into per-locale chunks and typed namespace objects
11
+ check Validate catalogs without writing anything
12
+ init Write parla.config.ts, a catalog per locale and the .gitignore line
13
+
14
+ Options
15
+ -c, --config <file> Config file (default: parla.config.ts, then .mts)
16
+ -w, --watch Rebuild on change (build)
17
+ --strict Treat warnings as errors
18
+ --json Print diagnostics as JSON (check)
19
+ --format <name> mf2 or icu (init; default mf2)
20
+ --locales <list> Comma-separated, source first (init; default en)
21
+ --catalogs <dir> Catalog folder (init; default locales)
22
+ -h, --help`;
23
+ const done = (code) => ({
24
+ code,
25
+ close: () => {
26
+ // nothing to stop
27
+ },
28
+ });
29
+ const ARGS = {
30
+ allowPositionals: true,
31
+ options: {
32
+ config: { type: 'string', short: 'c' },
33
+ watch: { type: 'boolean', short: 'w' },
34
+ strict: { type: 'boolean' },
35
+ json: { type: 'boolean' },
36
+ format: { type: 'string' },
37
+ locales: { type: 'string' },
38
+ catalogs: { type: 'string' },
39
+ help: { type: 'boolean', short: 'h' },
40
+ },
41
+ };
42
+ /** The options of `parla`, or why they are wrong. */
43
+ function parse(args) {
44
+ try {
45
+ return parseArgs({ ...ARGS, args: [...args] });
46
+ }
47
+ catch (error) {
48
+ return error.message;
49
+ }
50
+ }
51
+ const INIT_ONLY = ['format', 'locales', 'catalogs'];
52
+ const NOT_INIT = ['config', 'strict', 'json'];
53
+ /** Why a known command cannot run as given, or nothing. */
54
+ function misuse(command, { extra, values }) {
55
+ if (extra !== undefined) {
56
+ return `unexpected argument "${extra}"`;
57
+ }
58
+ if (values.watch && command !== 'build') {
59
+ return '--watch works only with build';
60
+ }
61
+ if (command === 'init') {
62
+ const option = NOT_INIT.find((name) => values[name] !== undefined);
63
+ return option ? `--${option} does not work with init` : '';
64
+ }
65
+ const option = INIT_ONLY.find((name) => values[name] !== undefined);
66
+ return option ? `--${option} works only with init` : '';
67
+ }
68
+ function runInit({ cwd, log, error }, values) {
69
+ try {
70
+ for (const line of init(cwd, values)) {
71
+ log(line);
72
+ }
73
+ return done(0);
74
+ }
75
+ catch (error_) {
76
+ error(`parla: ${error_.message}`);
77
+ return done(1);
78
+ }
79
+ }
80
+ function reportFailure(thrown, { json, io }) {
81
+ const { message } = thrown;
82
+ if (json && thrown instanceof ConfigError) {
83
+ // A consumer parsing stdout gets a document either way.
84
+ const diagnostic = { level: 'error', code: 'invalid-config', message };
85
+ io.log(JSON.stringify([diagnostic], null, 2));
86
+ }
87
+ else {
88
+ io.error(`parla: ${message}`);
89
+ }
90
+ }
91
+ function filesOf({ written, removed }) {
92
+ const gone = removed.length > 0 ? ` · ${removed.length} removed` : '';
93
+ return ` · ${written.length} files written${gone}`;
94
+ }
95
+ /** Runs `parla <args>`: the exit code, and in watch mode the watchers that keep it running. */
96
+ export async function runCommand(args, { cwd, log, error }) {
97
+ const parsed = parse(args);
98
+ if (typeof parsed === 'string') {
99
+ error(`parla: ${parsed}`);
100
+ return done(1);
101
+ }
102
+ const { values, positionals } = parsed;
103
+ const [command, extra] = positionals;
104
+ if (values.help || !command || !['build', 'check', 'init'].includes(command)) {
105
+ log(HELP);
106
+ return done(values.help ? 0 : 1);
107
+ }
108
+ const problem = misuse(command, { extra, values });
109
+ if (problem) {
110
+ error(`parla: ${problem}`);
111
+ return done(1);
112
+ }
113
+ if (command === 'init') {
114
+ return runInit({ cwd, log, error }, values);
115
+ }
116
+ const write = command === 'build';
117
+ const fresh = unreported();
118
+ const run = async () => {
119
+ const started = performance.now();
120
+ const result = await build({ cwd, config: values.config, write });
121
+ const { diagnostics, config } = result;
122
+ const reports = formatDiagnostics(diagnostics);
123
+ const errors = reports.filter((r) => r.level === 'error').length;
124
+ const warnings = reports.length - errors;
125
+ if (values.json) {
126
+ log(JSON.stringify(diagnostics, null, 2));
127
+ }
128
+ else {
129
+ for (const { line } of formatDiagnostics(fresh(diagnostics), config.root)) {
130
+ log(line);
131
+ }
132
+ const ms = Math.round(performance.now() - started);
133
+ const files = write ? filesOf(result) : '';
134
+ log(`parla ${command}: ${config.namespaces.length} namespaces × ${config.locales.length} locales · ${errors} errors · ${warnings} warnings · ${ms}ms${files}`);
135
+ }
136
+ return {
137
+ failed: errors > 0 || (Boolean(values.strict) && warnings > 0),
138
+ config,
139
+ };
140
+ };
141
+ let first;
142
+ try {
143
+ first = await run();
144
+ }
145
+ catch (error_) {
146
+ reportFailure(error_, { json: values.json, io: { cwd, log, error } });
147
+ return done(1);
148
+ }
149
+ const code = first.failed ? 1 : 0;
150
+ if (!values.watch) {
151
+ return done(code);
152
+ }
153
+ const watcher = rebuildOnChange(first.config, { run, error });
154
+ log(`parla: watching ${watcher.folders} folders`);
155
+ return { code, close: watcher.close };
156
+ }
@@ -0,0 +1,13 @@
1
+ import type { Model } from 'messageformat';
2
+ export declare function literalValue(value: string): string;
3
+ /** Where markup finds its callback, without what objects inherit: a check at run time costs 30%. */
4
+ export declare const params: (markup: string) => string;
5
+ /** A call's `{ __proto__: value }` sets the object's prototype, so the message would never get it. */
6
+ export declare function checkName(name: string): void;
7
+ /** A parser that assigns a `__proto__` option sets the prototype instead, dropping the option. */
8
+ export declare function checkOptions(options: object | undefined): void;
9
+ /** `:offset`'s `add` or `subtract`, as an operation. */
10
+ export declare function offsetBy({ options }: Model.FunctionRef): string;
11
+ /** The number a selector picks by: the one its function writes. */
12
+ export declare function selected(name: string, raw: string): string;
13
+ //# sourceMappingURL=code.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"code.d.ts","sourceRoot":"","sources":["../../src/compile/code.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAI3C,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CASlD;AAED,oGAAoG;AACpG,eAAO,MAAM,MAAM,WAAY,MAAM,KAAG,MACwB,CAAC;AAEjE,sGAAsG;AACtG,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAI5C;AAED,kGAAkG;AAClG,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAI9D;AAED,wDAAwD;AACxD,wBAAgB,QAAQ,CAAC,EAAE,OAAY,EAAE,EAAE,KAAK,CAAC,WAAW,GAAG,MAAM,CAOpE;AAED,mEAAmE;AACnE,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAM1D"}
@@ -0,0 +1,42 @@
1
+ import { CompileError } from './error.js';
2
+ export function literalValue(value) {
3
+ if (/^-?\d+(?:\.\d+)?$/.test(value)) {
4
+ // `02` would be a legacy octal literal: a syntax error in the chunk, which is a module
5
+ return String(Number(value));
6
+ }
7
+ if (value === 'true' || value === 'false') {
8
+ return value;
9
+ }
10
+ return JSON.stringify(value);
11
+ }
12
+ /** Where markup finds its callback, without what objects inherit: a check at run time costs 30%. */
13
+ export const params = (markup) => markup in Object.prototype ? '{ __proto__: null, ...p }' : 'p';
14
+ /** A call's `{ __proto__: value }` sets the object's prototype, so the message would never get it. */
15
+ export function checkName(name) {
16
+ if (name === '__proto__') {
17
+ throw new CompileError('a param or markup cannot be named "__proto__": rename it');
18
+ }
19
+ }
20
+ /** A parser that assigns a `__proto__` option sets the prototype instead, dropping the option. */
21
+ export function checkOptions(options) {
22
+ if (options && Object.getPrototypeOf(options) !== Object.prototype) {
23
+ throw new CompileError('an option cannot be named "__proto__": rename it');
24
+ }
25
+ }
26
+ /** `:offset`'s `add` or `subtract`, as an operation. */
27
+ export function offsetBy({ options = {} }) {
28
+ const [[name, value] = [], ...rest] = Object.entries(options);
29
+ const isDigits = value?.type === 'literal' && /^\d+$/.test(value.value);
30
+ if (!isDigits || rest.length > 0 || (name !== 'add' && name !== 'subtract')) {
31
+ throw new CompileError(':offset needs one literal integer, add or subtract');
32
+ }
33
+ return `${name === 'add' ? '+' : '-'} ${Number(value.value)}`;
34
+ }
35
+ /** The number a selector picks by: the one its function writes. */
36
+ export function selected(name, raw) {
37
+ if (name === 'integer') {
38
+ return `Math.round(Number(${raw}))`;
39
+ }
40
+ // Rounded, as 0.29 * 100 is 28.999999999999996.
41
+ return name === 'percent' ? `Math.round(Number(${raw}) * 1e4) / 100` : raw;
42
+ }
@@ -0,0 +1,11 @@
1
+ import type { Model } from 'messageformat';
2
+ import type { CompiledMessage, CustomFunctions } from './info.ts';
3
+ import { ModuleScope } from './scope.ts';
4
+ export interface CompileOptions {
5
+ readonly scope?: ModuleScope;
6
+ readonly custom?: CustomFunctions;
7
+ /** The locale whose plural rules apply, when not the chunk's. */
8
+ readonly pluralsOf?: string | undefined;
9
+ }
10
+ export declare function compileMessage(msg: Model.Message, options?: CompileOptions): CompiledMessage;
11
+ //# sourceMappingURL=compile.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compile.d.ts","sourceRoot":"","sources":["../../src/compile/compile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAO3C,OAAO,KAAK,EACV,eAAe,EACf,eAAe,EAIhB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAUzC,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,KAAK,CAAC,EAAE,WAAW,CAAC;IAC7B,QAAQ,CAAC,MAAM,CAAC,EAAE,eAAe,CAAC;IAClC,iEAAiE;IACjE,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACzC;AA4PD,wBAAgB,cAAc,CAAC,GAAG,EAAE,KAAK,CAAC,OAAO,EAAE,OAAO,GAAE,cAAmB,GAAG,eAAe,CAOhG"}
@@ -0,0 +1,244 @@
1
+ import { inheritedOptions, intlOptions } from '../options/options.js';
2
+ import { checkName, checkOptions, literalValue, offsetBy, params, selected } from './code.js';
3
+ import { CompileError } from './error.js';
4
+ import { BUILTIN_FUNCTIONS, kindOf, SELECTS } from './info.js';
5
+ import { ModuleScope } from './scope.js';
6
+ import { single } from './single.js';
7
+ import { branchNeeds, keysAt } from './variants.js';
8
+ class MessageCompiler {
9
+ vars = new Map();
10
+ scope;
11
+ custom;
12
+ info = { params: new Map(), markup: new Set(), rich: false, plurals: [] };
13
+ /** The params read outside any variant, and those the variant being compiled reads. */
14
+ shared = new Set();
15
+ reads;
16
+ pluralsOf;
17
+ constructor({ scope = new ModuleScope(), custom = {}, pluralsOf }) {
18
+ this.scope = scope;
19
+ this.custom = new Map(Object.entries(custom));
20
+ this.pluralsOf = pluralsOf;
21
+ }
22
+ record(param, kind) {
23
+ checkName(param);
24
+ const list = this.info.params.get(param) ?? [];
25
+ list.push(kind);
26
+ this.info.params.set(param, list);
27
+ (this.reads ?? this.shared).add(param);
28
+ }
29
+ resolve(name) {
30
+ return this.vars.get(name) ?? { raw: `p[${JSON.stringify(name)}]`, param: name };
31
+ }
32
+ options(fn, extra = {}) {
33
+ const entries = Object.entries({ ...this.resolved(fn), ...extra });
34
+ if (entries.length === 0) {
35
+ return '';
36
+ }
37
+ // A custom function's options are text: `zip=01234` is no number.
38
+ const literal = this.custom.has(fn.name) ? JSON.stringify : literalValue;
39
+ const parts = entries.map(([k, v]) => `${JSON.stringify(k)}: ${v.type === 'literal' ? literal(v.value) : this.variable(v)}`);
40
+ const code = `{ ${parts.join(', ')} }`;
41
+ const constant = entries.every(([, v]) => v.type === 'literal');
42
+ return `, ${constant ? this.scope.hoist(code) : code}`;
43
+ }
44
+ /** An option's variable, which the call then needs as it does any placeholder. */
45
+ variable({ name }) {
46
+ const { raw, param } = this.resolve(name);
47
+ if (param) {
48
+ this.record(param, { kind: 'any' });
49
+ }
50
+ return raw;
51
+ }
52
+ resolved(fn) {
53
+ if (this.custom.has(fn.name)) {
54
+ return fn.options ?? {};
55
+ }
56
+ try {
57
+ return intlOptions(fn);
58
+ }
59
+ catch (error) {
60
+ throw new CompileError(error.message, { cause: error });
61
+ }
62
+ }
63
+ effective(expr) {
64
+ let binding;
65
+ if (expr.arg?.type === 'literal') {
66
+ binding = { raw: JSON.stringify(expr.arg.value) };
67
+ }
68
+ else if (expr.arg?.type === 'variable') {
69
+ binding = { ...this.resolve(expr.arg.name) };
70
+ }
71
+ else {
72
+ binding = { raw: 'undefined' };
73
+ }
74
+ const own = expr.functionRef;
75
+ if (own) {
76
+ if (!BUILTIN_FUNCTIONS.has(own.name) && !this.custom.has(own.name)) {
77
+ throw new CompileError(`unknown function :${own.name}`);
78
+ }
79
+ checkOptions(own.options);
80
+ const { name } = own;
81
+ const isOffset = name === 'offset' && !this.custom.has(name);
82
+ const inherited = binding.fn ? inheritedOptions(binding.fn, isOffset ? 'number' : name) : {};
83
+ if (isOffset) {
84
+ binding.raw = `(Number(${binding.raw}) ${offsetBy(own)})`;
85
+ binding.fn = { type: 'function', name: 'number', options: inherited };
86
+ }
87
+ else {
88
+ binding.fn = { ...own, options: { ...inherited, ...own.options } };
89
+ }
90
+ }
91
+ return binding;
92
+ }
93
+ declare(decl) {
94
+ const binding = this.effective(decl.value);
95
+ if (decl.type === 'input') {
96
+ binding.param = decl.name;
97
+ }
98
+ this.vars.set(decl.name, binding);
99
+ if (binding.param && binding.fn) {
100
+ this.record(binding.param, kindOf(binding.fn, this.custom));
101
+ }
102
+ }
103
+ expression(expr) {
104
+ const b = this.effective(expr);
105
+ if (b.param) {
106
+ this.record(b.param, kindOf(b.fn, this.custom));
107
+ }
108
+ if (!b.fn) {
109
+ return `$.str(${b.raw})`;
110
+ }
111
+ const options = this.options(b.fn);
112
+ if (b.fn.name === 'number' && !options) {
113
+ return `$.n(${b.raw})`;
114
+ }
115
+ return `$.f(${JSON.stringify(b.fn.name)}, ${b.raw}${options})`;
116
+ }
117
+ pattern(pattern) {
118
+ const root = [];
119
+ const stack = [];
120
+ let rich = false;
121
+ const top = () => stack.at(-1)?.items ?? root;
122
+ for (const part of pattern) {
123
+ if (typeof part === 'string') {
124
+ if (part) {
125
+ top().push(JSON.stringify(part));
126
+ }
127
+ }
128
+ else if (part.type === 'expression') {
129
+ top().push(this.expression(part));
130
+ }
131
+ else {
132
+ rich = true;
133
+ checkName(part.name);
134
+ this.info.markup.add(part.name);
135
+ if (part.kind === 'open') {
136
+ stack.push({ name: part.name, items: [] });
137
+ }
138
+ else if (part.kind === 'standalone') {
139
+ top().push(`$.tag(${params(part.name)}, ${JSON.stringify(part.name)}, [])`);
140
+ }
141
+ else {
142
+ const open = stack.pop();
143
+ if (open?.name !== part.name) {
144
+ throw new CompileError(`closing markup {/${part.name}} has no matching open`);
145
+ }
146
+ top().push(`$.tag(${params(part.name)}, ${JSON.stringify(part.name)}, [${open.items.join(', ')}])`);
147
+ }
148
+ }
149
+ }
150
+ const unclosed = stack.at(-1);
151
+ if (unclosed) {
152
+ throw new CompileError(`markup {#${unclosed.name}} is never closed`);
153
+ }
154
+ if (rich) {
155
+ this.info.rich = true;
156
+ return { code: `$.rich([${root.join(', ')}])`, rich };
157
+ }
158
+ return { code: root.length > 0 ? root.join(' + ') : '""', rich };
159
+ }
160
+ select(msg) {
161
+ const selectors = msg.selectors.map((sel, i) => {
162
+ const b = this.resolve(sel.name);
163
+ if (!b.fn) {
164
+ throw new CompileError(`selector $${sel.name} needs an annotation such as :number or :string`);
165
+ }
166
+ if (SELECTS.has(b.fn.name)) {
167
+ if (b.param) {
168
+ this.record(b.param, { kind: 'number' });
169
+ }
170
+ const raw = selected(b.fn.name, b.raw);
171
+ return { numeric: true, raw, options: this.plural(b.fn, { msg, at: i }) };
172
+ }
173
+ if (b.fn.name === 'string') {
174
+ if (b.param) {
175
+ const { keys, open } = keysAt(msg, i);
176
+ this.record(b.param, { kind: 'select', keys: [...keys], open });
177
+ }
178
+ return { numeric: false, raw: b.raw, options: '' };
179
+ }
180
+ throw new CompileError(`:${b.fn.name} cannot be used as a selector`);
181
+ });
182
+ const reads = [];
183
+ const codes = msg.variants.map((v) => {
184
+ this.reads = new Set();
185
+ reads.push(this.reads);
186
+ return this.pattern(v.value).code;
187
+ });
188
+ this.reads = undefined;
189
+ this.branch(msg, reads);
190
+ const keys = msg.variants.map((v) => v.keys.map((k) => (k.type === '*' ? null : k.value)));
191
+ const [only] = selectors;
192
+ if (only && selectors.length === 1) {
193
+ return single(only, keys.map(([key = null], i) => ({ key, code: codes[i] ?? '""' })));
194
+ }
195
+ const values = selectors.map((s) => `$.${s.numeric ? 'sn' : 'ss'}(${s.raw}${s.options})`);
196
+ const pick = `$.pick([${values.join(', ')}], ${this.scope.hoist(JSON.stringify(keys))})`;
197
+ // `one`/`other` is the commonest select, and a ternary a fraction of a switch's size.
198
+ if (codes.length === 2) {
199
+ const [first, second] = codes;
200
+ return `${pick} ? ${second} : ${first}`;
201
+ }
202
+ const cases = codes.map((code, i) => `case ${i}: return ${code};`);
203
+ return `{ switch (${pick}) { ${cases.join(' ')} } }`;
204
+ }
205
+ /** A numeric selector's options, noting the categories it picks by. */
206
+ plural(fn, { msg, at }) {
207
+ const { keys } = keysAt(msg, at);
208
+ const select = fn.options?.['select'];
209
+ const kind = select?.type === 'literal' ? select.value : 'cardinal';
210
+ if (kind === 'exact') {
211
+ return this.options(fn);
212
+ }
213
+ const type = kind === 'ordinal' ? 'ordinal' : 'cardinal';
214
+ this.info.plurals.push({ type, keys });
215
+ const { pluralsOf } = this;
216
+ return this.options(fn, pluralsOf ? { locale: { type: 'literal', value: pluralsOf } } : {});
217
+ }
218
+ /** Fills `info.branches` when exactly one selector is a `:string` param's. */
219
+ branch(msg, reads) {
220
+ const strings = msg.selectors.flatMap((sel, i) => {
221
+ const b = this.resolve(sel.name);
222
+ return b.fn?.name === 'string' && b.param ? [{ i, param: b.param }] : [];
223
+ });
224
+ const [only] = strings;
225
+ const kinds = only && this.info.params.get(only.param);
226
+ if (strings.length !== 1 ||
227
+ !only ||
228
+ kinds?.some((k) => k.kind !== 'select' && k.kind !== 'string' && k.kind !== 'any')) {
229
+ return;
230
+ }
231
+ const needs = branchNeeds(msg, { at: only.i, shared: this.shared, reads });
232
+ if (needs) {
233
+ this.info.branches = { param: only.param, needs };
234
+ }
235
+ }
236
+ }
237
+ export function compileMessage(msg, options = {}) {
238
+ const c = new MessageCompiler(options);
239
+ for (const decl of msg.declarations) {
240
+ c.declare(decl);
241
+ }
242
+ const body = msg.type === 'message' ? c.pattern(msg.pattern).code : c.select(msg);
243
+ return { body, info: c.info };
244
+ }
@@ -0,0 +1,4 @@
1
+ export declare class CompileError extends Error {
2
+ name: string;
3
+ }
4
+ //# sourceMappingURL=error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../../src/compile/error.ts"],"names":[],"mappings":"AAAA,qBAAa,YAAa,SAAQ,KAAK;IAC5B,IAAI,SAAkB;CAChC"}
@@ -0,0 +1,3 @@
1
+ export class CompileError extends Error {
2
+ name = 'CompileError';
3
+ }
@@ -0,0 +1,49 @@
1
+ import type { Model } from 'messageformat';
2
+ /** What a custom function's value is: it types the param. */
3
+ export type FunctionKind = 'string' | 'number' | 'date';
4
+ /** Message functions beyond the built-in ones, by what their value is. */
5
+ export type CustomFunctions = Readonly<Record<string, FunctionKind>>;
6
+ /** MF2 gives the other number functions no selection. */
7
+ export declare const SELECTS: Set<string>;
8
+ /** The built-in message functions; the config's `functions` add to them. */
9
+ export declare const BUILTIN_FUNCTIONS: ReadonlySet<string>;
10
+ /** What a message needs from one parameter. `any` is an unannotated placeholder. */
11
+ export type ParamKind = {
12
+ kind: 'number';
13
+ } | {
14
+ kind: 'date';
15
+ } | {
16
+ kind: 'string';
17
+ } | {
18
+ kind: 'any';
19
+ } | {
20
+ kind: 'select';
21
+ keys: Array<string>;
22
+ open: boolean;
23
+ };
24
+ export interface MessageInfo {
25
+ params: Map<string, Array<ParamKind>>;
26
+ markup: Set<string>;
27
+ rich: boolean;
28
+ /**
29
+ * Set when a `:string` selector's value decides which params a call needs: the params each key
30
+ * needs, `null` for any other string. Unset when every key needs the same.
31
+ */
32
+ branches?: {
33
+ param: string;
34
+ needs: Map<string | null, Set<string>>;
35
+ };
36
+ /** Each selector that picks by plural category, with the keys its variants name. */
37
+ plurals: Array<{
38
+ type: Intl.PluralRuleType;
39
+ keys: Set<string>;
40
+ }>;
41
+ }
42
+ export interface CompiledMessage {
43
+ /** A function body reading params from `p` and the runtime from `$`. */
44
+ body: string;
45
+ info: MessageInfo;
46
+ }
47
+ export type CustomKinds = ReadonlyMap<string, FunctionKind>;
48
+ export declare function kindOf(fn: Model.FunctionRef | undefined, custom: CustomKinds): ParamKind;
49
+ //# sourceMappingURL=info.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"info.d.ts","sourceRoot":"","sources":["../../src/compile/info.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAE3C,6DAA6D;AAC7D,MAAM,MAAM,YAAY,GAAG,QAAQ,GAAG,QAAQ,GAAG,MAAM,CAAC;AAExD,0EAA0E;AAC1E,MAAM,MAAM,eAAe,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC,CAAC;AAIrE,yDAAyD;AACzD,eAAO,MAAM,OAAO,aAA4C,CAAC;AAIjE,4EAA4E;AAC5E,eAAO,MAAM,iBAAiB,EAAE,WAAW,CAAC,MAAM,CAA6C,CAAC;AAEhG,oFAAoF;AACpF,MAAM,MAAM,SAAS,GACjB;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,GAClB;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,GAChB;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,GAClB;IAAE,IAAI,EAAE,KAAK,CAAA;CAAE,GACf;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAAC,IAAI,EAAE,OAAO,CAAA;CAAE,CAAC;AAE3D,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC;IACtC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACpB,IAAI,EAAE,OAAO,CAAC;IACd;;;OAGG;IACH,QAAQ,CAAC,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,GAAG,CAAC,MAAM,GAAG,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAA;KAAE,CAAC;IACrE,oFAAoF;IACpF,OAAO,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,IAAI,CAAC,cAAc,CAAC;QAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;KAAE,CAAC,CAAC;CAClE;AAED,MAAM,WAAW,eAAe;IAC9B,wEAAwE;IACxE,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,WAAW,CAAC;CACnB;AAED,MAAM,MAAM,WAAW,GAAG,WAAW,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;AAE5D,wBAAgB,MAAM,CAAC,EAAE,EAAE,KAAK,CAAC,WAAW,GAAG,SAAS,EAAE,MAAM,EAAE,WAAW,GAAG,SAAS,CAexF"}