@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
package/build/types.js ADDED
@@ -0,0 +1,250 @@
1
+ const IDENT = /^[A-Za-z_$][\w$]*$/;
2
+ const prop = (name) => (IDENT.test(name) ? name : JSON.stringify(name));
3
+ function interfaceName(namespace) {
4
+ const pascal = namespace
5
+ .split(/[^A-Za-z0-9]+/)
6
+ .filter(Boolean)
7
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
8
+ .join('');
9
+ // `_` keeps a name like `-` from becoming `Messages`, whose plain part would shadow `Text`
10
+ return `${/^(?:\d|$)/.test(pascal) ? '_' : ''}${pascal}Messages`;
11
+ }
12
+ // Not valid as a `const` name in a module, or a built-in TypeScript rejects as one.
13
+ const RESERVED = new Set('arguments await break case catch class const continue debugger default delete do else enum eval export extends false finally for function globalThis if implements import in instanceof interface let new null package private protected public return static super switch this throw true try typeof undefined var void while with yield'.split(' '));
14
+ const isOwnName = (ns) => IDENT.test(ns) && !RESERVED.has(ns);
15
+ /**
16
+ * Each namespace's export: the name itself where it is an identifier, to match `t`'s key; else one
17
+ * derived from its interface (`foo-bar` → `fooBar`), numbered around the names already taken.
18
+ */
19
+ export function exportNames(ifaces) {
20
+ const names = new Map();
21
+ for (const ns of [...ifaces.keys()].filter((n) => isOwnName(n))) {
22
+ names.set(ns, ns);
23
+ }
24
+ const used = new Set(names.values());
25
+ for (const [ns, iface] of [...ifaces].filter(([n]) => !isOwnName(n))) {
26
+ const base = iface.replace(/Messages$/, '');
27
+ const camel = base.charAt(0).toLowerCase() + base.slice(1);
28
+ const derived = RESERVED.has(camel) ? `_${camel}` : camel;
29
+ let name = derived;
30
+ for (let n = 2; used.has(name); n += 1) {
31
+ name = `${derived}${n}`;
32
+ }
33
+ used.add(name);
34
+ names.set(ns, name);
35
+ }
36
+ return names;
37
+ }
38
+ /** {@link interfaceName} per namespace, numbered where two collide (`foo-bar`, `foo_bar`). */
39
+ export function interfaceNames(namespaces) {
40
+ const names = new Map();
41
+ // its kind would shadow the imported `NamespaceKind`
42
+ const used = new Set(['NamespaceMessages']);
43
+ for (const namespace of namespaces) {
44
+ const base = interfaceName(namespace);
45
+ let name = base;
46
+ for (let n = 2; used.has(name); n += 1) {
47
+ name = base.replace(/Messages$/, `${n}Messages`);
48
+ }
49
+ used.add(name);
50
+ names.set(namespace, name);
51
+ }
52
+ return names;
53
+ }
54
+ /** Collapses every use of one parameter into a single TS type. */
55
+ export function paramType(kinds) {
56
+ if (kinds.some((k) => k.kind === 'number')) {
57
+ return 'number';
58
+ }
59
+ if (kinds.some((k) => k.kind === 'date')) {
60
+ return 'Date | number';
61
+ }
62
+ const selects = kinds.filter((k) => k.kind === 'select');
63
+ if (selects.length > 0) {
64
+ // sorted: a translation may list the variants in another order
65
+ const keys = [...new Set(selects.flatMap((s) => s.keys))]
66
+ .toSorted()
67
+ .map((k) => JSON.stringify(k));
68
+ if (selects.some((s) => s.open)) {
69
+ keys.push('(string & {})');
70
+ }
71
+ return keys.join(' | ') || 'string';
72
+ }
73
+ if (kinds.some((k) => k.kind === 'string')) {
74
+ return 'string';
75
+ }
76
+ return 'string | number';
77
+ }
78
+ /** A select param's listed keys as a type, `undefined` unless it also takes any other string. */
79
+ function listedKeys(kinds) {
80
+ const selects = kinds.filter((k) => k.kind === 'select');
81
+ if (selects.every((s) => !s.open) ||
82
+ kinds.some((k) => k.kind === 'number' || k.kind === 'date')) {
83
+ return undefined;
84
+ }
85
+ const keys = new Set(selects.flatMap((s) => s.keys));
86
+ return keys.size > 0
87
+ ? [...keys.add('other')]
88
+ .toSorted()
89
+ .map((k) => JSON.stringify(k))
90
+ .join(' | ')
91
+ : undefined;
92
+ }
93
+ /** One params object: `names` typed by their uses, `selected` overriding a selector's type. */
94
+ function fields(info, names, defaults, selected) {
95
+ const out = [...names]
96
+ .toSorted((a, b) => a.localeCompare(b))
97
+ .map((name) => {
98
+ const kinds = info.params.get(name) ?? [];
99
+ const keys = listedKeys(kinds);
100
+ const open = keys === undefined ? paramType(kinds) : `${keys} | Other<G>`;
101
+ const type = name === selected?.[0] ? selected[1] : open;
102
+ return `${prop(name)}: ${type}`;
103
+ });
104
+ let required = out.length;
105
+ for (const tag of [...info.markup].toSorted()) {
106
+ if (!info.params.has(tag)) {
107
+ const optional = defaults.has(tag);
108
+ out.push(`${prop(tag)}${optional ? '?' : ''}: Markup<Node>`);
109
+ required += optional ? 0 : 1;
110
+ }
111
+ }
112
+ return { fields: out, required };
113
+ }
114
+ /** Any `string` but a literal, which only a generic tells apart: a literal makes `Record` a required key. */
115
+ const OTHER = 'type Other<G extends string> = G extends string ? {} extends Record<G, 1> ? G : never : never;';
116
+ /** `defaults`: markup the runtime renders when a call leaves it out (the config's `markup`). */
117
+ export function signature(info, defaults = new Set()) {
118
+ const ret = info.rich ? 'Node' : 'string';
119
+ const { branches } = info;
120
+ if (branches) {
121
+ // One member per key, so a key's own params are required only with it; `string` last.
122
+ const every = new Set([...branches.needs.values()].flatMap((names) => [...names]));
123
+ const members = [...branches.needs]
124
+ .toSorted(([a], [b]) => Number(a === null) - Number(b === null) || String(a).localeCompare(String(b)))
125
+ .map(([key, names]) => {
126
+ // a plain `string` may hold any key, so it needs every branch's params
127
+ const [type, needed] = key === null ? ['string', every] : [JSON.stringify(key), names];
128
+ return `{ ${fields(info, needed, defaults, [branches.param, type]).fields.join('; ')} }`;
129
+ });
130
+ return `(params: ${members.join(' | ')}): ${ret}`;
131
+ }
132
+ const own = fields(info, info.params.keys(), defaults);
133
+ if (own.fields.length === 0) {
134
+ return info.rich ? '(): Node' : ': Text';
135
+ }
136
+ // One `G` for every select, as a union of methods with different type params is not callable.
137
+ const generic = own.fields.some((f) => f.includes('Other<G>')) ? '<G extends string>' : '';
138
+ return `${generic}(params${own.required === 0 ? '?' : ''}: { ${own.fields.join('; ')} }): ${ret}`;
139
+ }
140
+ const isLeaf = (n) => !(n instanceof Map);
141
+ /** Whether `node` holds a message with markup (`rich`) or one without. */
142
+ const holds = (node, rich) => isLeaf(node) ? Boolean(node.rich) === rich : [...node.values()].some((n) => holds(n, rich));
143
+ function render(tree, indent) {
144
+ const lines = [];
145
+ for (const [key, node] of tree) {
146
+ if (isLeaf(node)) {
147
+ if (node.doc !== undefined) {
148
+ // Not `/\s*\n\s*/g`, quadratic in a run of spaces.
149
+ const doc = node.doc.split('\n').map((line) => line.trim());
150
+ const text = doc
151
+ .filter(Boolean)
152
+ .join(' ')
153
+ .replaceAll('*/', String.raw `*\/`);
154
+ lines.push(`${indent}/** ${text} */`);
155
+ }
156
+ lines.push(`${indent}${prop(key)}${node.leaf};`);
157
+ }
158
+ else {
159
+ lines.push(`${indent}${prop(key)}: {`, render(node, `${indent} `), `${indent}};`);
160
+ }
161
+ }
162
+ return lines.join('\n');
163
+ }
164
+ function treeOf(entries) {
165
+ const tree = new Map();
166
+ for (const [path, leaf] of entries) {
167
+ const last = path.at(-1) ?? '';
168
+ let node = tree;
169
+ for (const segment of path.slice(0, -1)) {
170
+ let child = node.get(segment);
171
+ if (!child || isLeaf(child)) {
172
+ child = new Map();
173
+ node.set(segment, child);
174
+ }
175
+ node = child;
176
+ }
177
+ node.set(last, leaf);
178
+ }
179
+ return tree;
180
+ }
181
+ const pascal = (key) => key
182
+ .split(/[^A-Za-z0-9]+/)
183
+ .filter(Boolean)
184
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
185
+ .join('');
186
+ /**
187
+ * Plain messages in a non-generic `XText`, and those with markup in `XMessages<Node> extends XText`,
188
+ * so instantiating `Node` skips every plain message. A group holding both splits the same way.
189
+ */
190
+ function declare(tree, name, unique, out) {
191
+ const plain = new Map();
192
+ const rich = new Map();
193
+ for (const [key, node] of tree) {
194
+ if (!holds(node, true)) {
195
+ plain.set(key, node);
196
+ }
197
+ else if (isLeaf(node) || !holds(node, false)) {
198
+ rich.set(key, node);
199
+ }
200
+ else {
201
+ const group = unique(name.replace(/Messages$/, `${pascal(key)}Messages`));
202
+ declare(node, group, unique, out);
203
+ rich.set(key, { leaf: `: ${group}<Node>` });
204
+ }
205
+ }
206
+ const text = name.replace(/Messages$/, 'Text');
207
+ const body = (members) => render(members, ' ');
208
+ if (rich.size === 0) {
209
+ out.push(`export interface ${name} {\n${body(plain)}\n}`);
210
+ }
211
+ else if (plain.size === 0) {
212
+ out.push(`export interface ${name}<Node> {\n${body(rich)}\n}`);
213
+ }
214
+ else {
215
+ out.push(`export interface ${text} {\n${body(plain)}\n}`, `export interface ${name}<Node> extends ${text} {\n${body(rich)}\n}`);
216
+ }
217
+ }
218
+ function withAliases(code) {
219
+ const aliases = [
220
+ ...(code.includes('Markup<Node>') ? ['type Markup<Node> = (children: Node) => Node;'] : []),
221
+ ...(code.includes('Other<G>') ? [OTHER] : []),
222
+ ];
223
+ return aliases.length > 0 ? `${aliases.join('\n')}\n\n${code}\n\nexport {};` : code;
224
+ }
225
+ export function namespaceTypes(messages, name, defaults) {
226
+ const leaves = [...messages].map(([key, { info, source }]) => [
227
+ key.split('.'),
228
+ { leaf: signature(info, defaults), doc: source, rich: info.rich },
229
+ ]);
230
+ const tree = treeOf(leaves);
231
+ const used = new Set([name]);
232
+ const unique = (base) => {
233
+ let group = base;
234
+ for (let n = 2; used.has(group); n += 1) {
235
+ group = base.replace(/Messages$/, `${n}Messages`);
236
+ }
237
+ used.add(group);
238
+ return group;
239
+ };
240
+ const out = [];
241
+ declare(tree, name, unique, out);
242
+ const code = out.join('\n\n');
243
+ return {
244
+ // One alias: TypeScript instantiates it once per node type, not once per tag. `export {}` keeps
245
+ // it private, as a .d.ts otherwise exports every top-level name.
246
+ code: withAliases(code),
247
+ generic: holds(tree, true),
248
+ usesText: leaves.some(([, leaf]) => leaf.leaf === ': Text'),
249
+ };
250
+ }
@@ -0,0 +1,9 @@
1
+ import type { Plugin } from 'vite';
2
+ import type { BuildOptions } from './build.ts';
3
+ export interface ParlaViteOptions extends Pick<BuildOptions, 'config'> {
4
+ /** Folder holding the config. Defaults to Vite's root. */
5
+ root?: string;
6
+ }
7
+ /** Runs `parla build` on start and on every catalog change. */
8
+ export declare function parla(options?: ParlaViteOptions): Plugin;
9
+ //# sourceMappingURL=vite.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vite.d.ts","sourceRoot":"","sources":["../src/vite.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAwB,MAAM,EAAiB,MAAM,MAAM,CAAC;AAGxE,OAAO,KAAK,EAAE,YAAY,EAAe,MAAM,YAAY,CAAC;AAG5D,MAAM,WAAW,gBAAiB,SAAQ,IAAI,CAAC,YAAY,EAAE,QAAQ,CAAC;IACpE,0DAA0D;IAC1D,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAeD,+DAA+D;AAC/D,wBAAgB,KAAK,CAAC,OAAO,GAAE,gBAAqB,GAAG,MAAM,CAmH5D"}
package/build/vite.js ADDED
@@ -0,0 +1,125 @@
1
+ import path from 'node:path';
2
+ import { build } from './build.js';
3
+ import { formatDiagnostics, unreported } from './diagnostics.js';
4
+ const overlay = (message) => ({
5
+ type: 'error',
6
+ err: { message, stack: '', plugin: 'parla' },
7
+ });
8
+ /** The catalog errors, as Vite's overlay shows them; undefined without any. */
9
+ function catalogErrors({ diagnostics, config }) {
10
+ const lines = formatDiagnostics(diagnostics, config.root)
11
+ .filter(({ level }) => level === 'error')
12
+ .map(({ line }) => line);
13
+ return lines.length > 0 ? overlay(lines.join('\n')) : undefined;
14
+ }
15
+ /** Runs `parla build` on start and on every catalog change. */
16
+ export function parla(options = {}) {
17
+ let root = process.cwd();
18
+ let config;
19
+ let isBuild = false;
20
+ let logger;
21
+ // One plugin serves every environment and rebuild: each would repeat the same warnings.
22
+ const fresh = unreported();
23
+ // From a change until the build it starts has ended, in dev.
24
+ let pending;
25
+ // What the overlay shows in dev: the build leaves a broken message out, so the page would fail.
26
+ let shown;
27
+ const run = async () => {
28
+ const result = await build({ cwd: root, config: options.config });
29
+ ({ config } = result);
30
+ for (const { level, line } of formatDiagnostics(fresh(result.diagnostics), result.config.root)) {
31
+ logger?.[level === 'error' ? 'error' : 'warn'](`[parla] ${line}`);
32
+ }
33
+ shown = catalogErrors(result);
34
+ return result;
35
+ };
36
+ const settle = () => {
37
+ pending?.resolve();
38
+ pending = undefined;
39
+ };
40
+ const watched = () => config ? [...config.watchFiles, ...config.watchFolders] : [];
41
+ return {
42
+ name: 'parla',
43
+ enforce: 'pre',
44
+ configResolved(vite) {
45
+ root = options.root ? path.resolve(vite.root, options.root) : vite.root;
46
+ isBuild = vite.command === 'build';
47
+ ({ logger } = vite);
48
+ },
49
+ async buildStart() {
50
+ const result = await run();
51
+ for (const f of watched()) {
52
+ this.addWatchFile(f);
53
+ }
54
+ if (isBuild && result.diagnostics.some((d) => d.level === 'error')) {
55
+ this.error('parla: catalog errors, see above');
56
+ }
57
+ },
58
+ resolveId: {
59
+ filter: { id: /\b(?:namespaces\/|catalog\b)/ },
60
+ // On a branch switch, a page may import a namespace the build is about to generate.
61
+ async handler() {
62
+ await pending?.promise;
63
+ },
64
+ },
65
+ configureServer(server) {
66
+ // a save that leaves the config as broken as before repeats nothing
67
+ let failure;
68
+ const rebuild = async () => {
69
+ const wasShown = shown !== undefined;
70
+ try {
71
+ const result = await run();
72
+ failure = undefined;
73
+ server.watcher.add(watched());
74
+ if (shown) {
75
+ server.ws.send(shown);
76
+ }
77
+ else if (wasShown || result.written.length > 0) {
78
+ server.ws.send({ type: 'full-reload' });
79
+ }
80
+ }
81
+ catch (error) {
82
+ const line = `parla: ${error.message}`;
83
+ if (line !== failure) {
84
+ server.config.logger.error(line);
85
+ }
86
+ failure = line;
87
+ shown = overlay(line);
88
+ server.ws.send(shown);
89
+ }
90
+ };
91
+ // One build for files that change together, as on a branch switch.
92
+ let timer;
93
+ let changes = 0;
94
+ const rebuildAt = async (change) => {
95
+ await rebuild();
96
+ if (change === changes) {
97
+ settle();
98
+ }
99
+ };
100
+ const onChange = (file) => {
101
+ if (config?.watches(path.resolve(file))) {
102
+ pending ??= Promise.withResolvers();
103
+ changes += 1;
104
+ clearTimeout(timer);
105
+ timer = setTimeout(() => {
106
+ void rebuildAt(changes);
107
+ }, 50);
108
+ }
109
+ };
110
+ server.httpServer?.on('close', () => {
111
+ clearTimeout(timer);
112
+ settle();
113
+ });
114
+ // A page that loads, or reloads as Vite sees the new chunk, has missed it.
115
+ server.ws.on('connection', () => {
116
+ if (shown) {
117
+ server.ws.send(shown);
118
+ }
119
+ });
120
+ for (const event of ['change', 'add', 'unlink']) {
121
+ server.watcher.on(event, onChange);
122
+ }
123
+ },
124
+ };
125
+ }
@@ -0,0 +1,12 @@
1
+ import type { ResolvedConfig } from './config/config.ts';
2
+ /** Rebuilds after each change to what the last build's config watches, until `close`. */
3
+ export declare function rebuildOnChange(first: ResolvedConfig, { run, error, }: {
4
+ run: () => Promise<{
5
+ readonly config: ResolvedConfig;
6
+ }>;
7
+ error: (line: string) => void;
8
+ }): {
9
+ readonly folders: number;
10
+ readonly close: () => void;
11
+ };
12
+ //# sourceMappingURL=watch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"watch.d.ts","sourceRoot":"","sources":["../src/watch.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAkEzD,yFAAyF;AACzF,wBAAgB,eAAe,CAC7B,KAAK,EAAE,cAAc,EACrB,EACE,GAAG,EACH,KAAK,GACN,EAAE;IACD,GAAG,EAAE,MAAM,OAAO,CAAC;QAAE,QAAQ,CAAC,MAAM,EAAE,cAAc,CAAA;KAAE,CAAC,CAAC;IACxD,KAAK,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CAC/B,GACA;IAAE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,IAAI,CAAA;CAAE,CAkC1D"}
package/build/watch.js ADDED
@@ -0,0 +1,93 @@
1
+ import { existsSync, watch } from 'node:fs';
2
+ import path from 'node:path';
3
+ /** What to watch in each folder: the files, or for a folder not there yet, its name in its parent. */
4
+ function watchedNames(files) {
5
+ const out = new Map();
6
+ for (const file of files) {
7
+ let name = file;
8
+ let dir = path.dirname(file);
9
+ while (!existsSync(dir)) {
10
+ name = dir;
11
+ dir = path.dirname(dir);
12
+ }
13
+ out.set(dir, (out.get(dir) ?? new Set()).add(path.basename(name)));
14
+ }
15
+ return out;
16
+ }
17
+ function watchFolders(changes) {
18
+ const watchers = new Map();
19
+ let names = new Map();
20
+ let watched;
21
+ let closed = false;
22
+ const start = (dir) => watch(dir, (_, name) => {
23
+ // a folder holds more than catalogs; `name` is null where the platform does not tell
24
+ if (name === null || names.get(dir)?.has(name) || watched?.watches(path.join(dir, name))) {
25
+ changes.dispatchEvent(new Event('change'));
26
+ }
27
+ });
28
+ return {
29
+ follow(config) {
30
+ // a build may end after `close`
31
+ if (closed) {
32
+ return;
33
+ }
34
+ names = watchedNames(config.watchFiles);
35
+ watched = config;
36
+ for (const [dir, watcher] of watchers) {
37
+ if (!names.has(dir)) {
38
+ watcher.close();
39
+ watchers.delete(dir);
40
+ }
41
+ }
42
+ for (const dir of names.keys()) {
43
+ if (!watchers.has(dir)) {
44
+ watchers.set(dir, start(dir));
45
+ }
46
+ }
47
+ },
48
+ close() {
49
+ closed = true;
50
+ for (const watcher of watchers.values()) {
51
+ watcher.close();
52
+ }
53
+ },
54
+ size: () => watchers.size,
55
+ };
56
+ }
57
+ /** Rebuilds after each change to what the last build's config watches, until `close`. */
58
+ export function rebuildOnChange(first, { run, error, }) {
59
+ const changes = new EventTarget();
60
+ const folders = watchFolders(changes);
61
+ let timer;
62
+ // a save that leaves the config as broken as before repeats nothing
63
+ let failure;
64
+ const rebuild = async () => {
65
+ try {
66
+ const { config } = await run();
67
+ folders.follow(config);
68
+ failure = undefined;
69
+ }
70
+ catch (error_) {
71
+ const line = `parla: ${error_.message}`;
72
+ if (line !== failure) {
73
+ error(line);
74
+ }
75
+ failure = line;
76
+ }
77
+ };
78
+ const schedule = () => {
79
+ clearTimeout(timer);
80
+ timer = setTimeout(() => {
81
+ void rebuild();
82
+ }, 50);
83
+ };
84
+ changes.addEventListener('change', schedule);
85
+ folders.follow(first);
86
+ return {
87
+ folders: folders.size(),
88
+ close: () => {
89
+ clearTimeout(timer);
90
+ folders.close();
91
+ },
92
+ };
93
+ }
package/package.json CHANGED
@@ -1,6 +1,87 @@
1
1
  {
2
2
  "name": "@parlajs/compiler",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.0",
4
+ "description": "Compiles Parla catalogs into per-locale chunks and typed accessors.",
5
+ "keywords": [
6
+ "codegen",
7
+ "compiler",
8
+ "i18n",
9
+ "icu",
10
+ "internationalization",
11
+ "l10n",
12
+ "localization",
13
+ "messageformat",
14
+ "messageformat2",
15
+ "mf2",
16
+ "parla",
17
+ "type-safe",
18
+ "typescript",
19
+ "vite",
20
+ "vite-plugin"
21
+ ],
22
+ "homepage": "https://github.com/parlajs/parla",
23
+ "bugs": {
24
+ "url": "https://github.com/parlajs/parla/issues"
25
+ },
26
+ "license": "MIT",
27
+ "author": {
28
+ "name": "Marco Pasqualetti",
29
+ "url": "https://github.com/marcalexiei"
30
+ },
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/parlajs/parla.git",
34
+ "directory": "packages/compiler"
35
+ },
36
+ "bin": {
37
+ "parla": "./build/cli.js"
38
+ },
39
+ "files": [
40
+ "build",
41
+ "src",
42
+ "README.md"
43
+ ],
44
+ "type": "module",
45
+ "exports": {
46
+ ".": {
47
+ "@parlajs/source": "./src/index.ts",
48
+ "default": "./build/index.js"
49
+ },
50
+ "./vite": {
51
+ "@parlajs/source": "./src/vite.ts",
52
+ "default": "./build/vite.js"
53
+ }
54
+ },
55
+ "publishConfig": {
56
+ "access": "public"
57
+ },
58
+ "dependencies": {
59
+ "messageformat": "^4.1.0"
60
+ },
61
+ "devDependencies": {
62
+ "@parlajs/core": "^0.0.0",
63
+ "@parlajs/format-icu": "^0.0.0",
64
+ "@parlajs/format-mf2": "^0.0.0",
65
+ "@types/node": "26.6.6",
66
+ "intl-messageformat": "12.2.0",
67
+ "vite": "8.3.8",
68
+ "vitest": "5.1.1"
69
+ },
70
+ "peerDependencies": {
71
+ "vite": ">=6"
72
+ },
73
+ "peerDependenciesMeta": {
74
+ "vite": {
75
+ "optional": true
76
+ }
77
+ },
78
+ "engines": {
79
+ "node": "^22.18 || ^24 || >=26"
80
+ },
81
+ "scripts": {
82
+ "build": "tsc -p tsconfig.build.json",
83
+ "lint:publish": "attw --pack . --profile esm-only && publint --strict",
84
+ "test": "vitest",
85
+ "typecheck": "tsc -p tsconfig.typecheck.json"
86
+ }
6
87
  }
package/src/build.ts ADDED
@@ -0,0 +1,31 @@
1
+ import type { ResolvedConfig } from './config/config.ts';
2
+ import { loadConfig } from './config/load.ts';
3
+ import type { Diagnostic } from './diagnostics.ts';
4
+ import { writeOutput } from './generate/files.ts';
5
+ import type { Output } from './generate/namespace.ts';
6
+ import { buildNamespaces } from './generate/namespaces.ts';
7
+
8
+ export interface BuildOptions {
9
+ cwd?: string;
10
+ /** Path to the config file, relative to `cwd`. */
11
+ config?: string | undefined;
12
+ /** `false` writes nothing: a check. */
13
+ write?: boolean | undefined;
14
+ }
15
+
16
+ export interface BuildResult {
17
+ config: ResolvedConfig;
18
+ diagnostics: Array<Diagnostic>;
19
+ written: Array<string>;
20
+ /** Files an earlier build generated that this one no longer does. */
21
+ removed: Array<string>;
22
+ }
23
+
24
+ export async function build(options: BuildOptions = {}): Promise<BuildResult> {
25
+ const config = await loadConfig(options.cwd ?? process.cwd(), options.config);
26
+ const out: Output = { diagnostics: [], files: new Map() };
27
+ buildNamespaces(config, out);
28
+ const { written, removed } =
29
+ (options.write ?? true) ? writeOutput(config, out.files) : { written: [], removed: [] };
30
+ return { config, diagnostics: out.diagnostics, written, removed };
31
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { runCommand } from './command.ts';
3
+
4
+ const { code } = await runCommand(process.argv.slice(2), {
5
+ cwd: process.cwd(),
6
+ log: console.log,
7
+ error: console.error,
8
+ });
9
+ process.exitCode = code;