@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
@@ -0,0 +1,19 @@
1
+ import type { ResolvedConfig, ResolvedNamespace } from '../config/config.ts';
2
+ import type { Diagnostic } from '../diagnostics.ts';
3
+ import type { CatalogText } from './read.ts';
4
+ /** What a build collects: its diagnostics, and the files to write by path under `outDir`. */
5
+ export interface Output {
6
+ readonly diagnostics: Array<Diagnostic>;
7
+ readonly files: Map<string, string>;
8
+ }
9
+ /** A namespace's chunk per locale, its object and its types, from its catalogs' `texts` per locale. */
10
+ export declare function buildNamespace(ns: ResolvedNamespace, { config, names: { iface, exported }, texts, out, }: {
11
+ config: ResolvedConfig;
12
+ names: {
13
+ readonly iface: string;
14
+ readonly exported: string;
15
+ };
16
+ texts: ReadonlyArray<CatalogText>;
17
+ out: Output;
18
+ }): void;
19
+ //# sourceMappingURL=namespace.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"namespace.d.ts","sourceRoot":"","sources":["../../src/generate/namespace.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAiB,cAAc,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAC5F,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAMpD,OAAO,KAAK,EAAE,WAAW,EAAS,MAAM,WAAW,CAAC;AAEpD,6FAA6F;AAC7F,MAAM,WAAW,MAAM;IACrB,QAAQ,CAAC,WAAW,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC;IACxC,QAAQ,CAAC,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACrC;AAiDD,uGAAuG;AACvG,wBAAgB,cAAc,CAC5B,EAAE,EAAE,iBAAiB,EACrB,EACE,MAAM,EACN,KAAK,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,EAC1B,KAAK,EACL,GAAG,GACJ,EAAE;IACD,MAAM,EAAE,cAAc,CAAC;IACvB,KAAK,EAAE;QAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC;IAC7D,KAAK,EAAE,aAAa,CAAC,WAAW,CAAC,CAAC;IAClC,GAAG,EAAE,MAAM,CAAC;CACb,GACA,IAAI,CAuCN"}
@@ -0,0 +1,65 @@
1
+ import path from 'node:path';
2
+ import { inherits } from './checks.js';
3
+ import { compileLocale } from './locale.js';
4
+ import { namespaceDeclaration, namespaceModule } from './modules.js';
5
+ import { readCatalog } from './read.js';
6
+ function readCatalogs(ns, { config, adapter, texts, diagnostics, }) {
7
+ const catalogs = new Map();
8
+ const reported = new Set();
9
+ for (const [index, locale] of config.locales.entries()) {
10
+ const read = readCatalog(ns, {
11
+ locale,
12
+ adapter,
13
+ text: texts[index],
14
+ report: (d) => {
15
+ reported.add(d.key ? `${locale}\0${d.key}` : locale);
16
+ diagnostics.push({ ...d, namespace: ns.name, locale });
17
+ },
18
+ });
19
+ if (!read.exists && (locale === config.sourceLocale || !inherits(config, locale))) {
20
+ reported.add(locale);
21
+ diagnostics.push({
22
+ level: locale === config.sourceLocale ? 'error' : 'warning',
23
+ code: 'missing-file',
24
+ namespace: ns.name,
25
+ locale,
26
+ file: read.file,
27
+ message: 'no such file: create it',
28
+ });
29
+ }
30
+ catalogs.set(locale, read.entries);
31
+ }
32
+ return { catalogs, reported };
33
+ }
34
+ /** A namespace's chunk per locale, its object and its types, from its catalogs' `texts` per locale. */
35
+ export function buildNamespace(ns, { config, names: { iface, exported }, texts, out, }) {
36
+ const { diagnostics, files } = out;
37
+ if (exported !== ns.name) {
38
+ // two names for one namespace is what tools like codemods and x18n trip over
39
+ diagnostics.push({
40
+ level: 'warning',
41
+ code: 'namespace-name',
42
+ namespace: ns.name,
43
+ message: `exports as ${exported} while t keeps "${ns.name}": name it as an identifier and map the file in path`,
44
+ });
45
+ }
46
+ const adapter = config.formats[ns.format];
47
+ if (!adapter) {
48
+ diagnostics.push({
49
+ level: 'error',
50
+ code: 'unknown-format',
51
+ namespace: ns.name,
52
+ message: `format "${ns.format}" is not in formats (${Object.keys(config.formats).join(', ') || 'empty'})`,
53
+ });
54
+ return;
55
+ }
56
+ const read = readCatalogs(ns, { config, adapter, texts, diagnostics });
57
+ const sourceInfo = new Map();
58
+ // The source locale first, so every translation has its source message to compare against.
59
+ const locales = [config.sourceLocale, ...config.locales.filter((l) => l !== config.sourceLocale)];
60
+ for (const locale of locales) {
61
+ files.set(path.join('messages', locale, `${ns.name}.js`), compileLocale(locale, { ...read, config, ns, sourceInfo, diagnostics }));
62
+ }
63
+ files.set(path.join('namespaces', `${ns.name}.js`), namespaceModule(ns.name, { exported, locales: config.locales }));
64
+ files.set(path.join('namespaces', `${ns.name}.d.ts`), namespaceDeclaration(config, { namespace: ns.name, iface, exported, messages: sourceInfo }));
65
+ }
@@ -0,0 +1,5 @@
1
+ import type { ResolvedConfig } from '../config/config.ts';
2
+ import type { Output } from './namespace.ts';
3
+ /** Every namespace's output, the last build's where nothing the namespace reads has changed. */
4
+ export declare function buildNamespaces(config: ResolvedConfig, out: Output): void;
5
+ //# sourceMappingURL=namespaces.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"namespaces.d.ts","sourceRoot":"","sources":["../../src/generate/namespaces.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAiB,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAKzE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAgB7C,gGAAgG;AAChG,wBAAgB,eAAe,CAAC,MAAM,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAoCzE"}
@@ -0,0 +1,41 @@
1
+ import { exportNames, interfaceNames } from '../types/names.js';
2
+ import { buildNamespace } from './namespace.js';
3
+ import { readText } from './read.js';
4
+ // Per config file, its last build: a watcher's rebuild compiles only the namespaces that changed.
5
+ const builds = new Map();
6
+ /** Every namespace's output, the last build's where nothing the namespace reads has changed. */
7
+ export function buildNamespaces(config, out) {
8
+ const ifaces = interfaceNames(config.namespaces.map((ns) => ns.name));
9
+ const exports = exportNames(ifaces);
10
+ // Whatever else the config holds, so an option added later is not forgotten here.
11
+ const shared = JSON.stringify({
12
+ ...config,
13
+ formats: Object.keys(config.formats),
14
+ namespaces: 0,
15
+ watchFiles: 0,
16
+ watchFolders: 0,
17
+ });
18
+ const last = builds.get(config.configFile);
19
+ const kept = new Map();
20
+ for (const ns of config.namespaces) {
21
+ const names = { iface: ifaces.get(ns.name) ?? '', exported: exports.get(ns.name) ?? '' };
22
+ const files = config.locales.map((locale) => ns.file(locale));
23
+ const settings = JSON.stringify([shared, ns.format, names, files]);
24
+ const adapter = config.formats[ns.format];
25
+ const texts = files.map((file) => readText(file));
26
+ let built = last?.get(ns.name);
27
+ if (built?.settings !== settings ||
28
+ built.adapter !== adapter ||
29
+ texts.some((text, i) => text !== built?.texts[i])) {
30
+ const fresh = { diagnostics: [], files: new Map() };
31
+ buildNamespace(ns, { config, names, texts, out: fresh });
32
+ built = { settings, adapter, texts, ...fresh };
33
+ }
34
+ kept.set(ns.name, built);
35
+ out.diagnostics.push(...built.diagnostics);
36
+ for (const [file, content] of built.files) {
37
+ out.files.set(file, content);
38
+ }
39
+ }
40
+ builds.set(config.configFile, kept);
41
+ }
@@ -0,0 +1,21 @@
1
+ import type { Model } from 'messageformat';
2
+ import type { FormatAdapter, ResolvedNamespace } from '../config/config.ts';
3
+ import type { Unplaced } from '../diagnostics.ts';
4
+ export interface Entry {
5
+ source: string;
6
+ model: Model.Message;
7
+ }
8
+ /** A catalog's text: none where there is no file, an error where it cannot be read. */
9
+ export type CatalogText = string | Error | undefined;
10
+ export declare function readText(file: string): CatalogText;
11
+ export declare function readCatalog(ns: ResolvedNamespace, { locale, adapter, text, report: diag, }: {
12
+ locale: string;
13
+ adapter: FormatAdapter;
14
+ text: CatalogText;
15
+ report: (d: Unplaced) => void;
16
+ }): {
17
+ file: string;
18
+ entries: Map<string, Entry>;
19
+ exists: boolean;
20
+ };
21
+ //# sourceMappingURL=read.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../src/generate/read.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAE3C,OAAO,KAAK,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,KAAK,EAAmB,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAmEnE,MAAM,WAAW,KAAK;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC;CACtB;AAED,uFAAuF;AACvF,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,KAAK,GAAG,SAAS,CAAC;AAErD,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,CASlD;AAED,wBAAgB,WAAW,CACzB,EAAE,EAAE,iBAAiB,EACrB,EACE,MAAM,EACN,OAAO,EACP,IAAI,EACJ,MAAM,EAAE,IAAI,GACb,EAAE;IACD,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,aAAa,CAAC;IACvB,IAAI,EAAE,WAAW,CAAC;IAClB,MAAM,EAAE,CAAC,CAAC,EAAE,QAAQ,KAAK,IAAI,CAAC;CAC/B,GACA;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAAC,MAAM,EAAE,OAAO,CAAA;CAAE,CAsDhE"}
@@ -0,0 +1,115 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ /** Groups in groups past this would overflow the stack, here or in what reads the output. */
3
+ const MAX_DEPTH = 100;
4
+ /** `value`'s messages into `out` by dotted key. */
5
+ function flatten(value, { prefix, out, report, }) {
6
+ const invalid = (message) => {
7
+ report({ key: prefix, message, code: 'invalid-resource' });
8
+ };
9
+ if (prefix.split('.').length > MAX_DEPTH) {
10
+ invalid(`more than ${MAX_DEPTH} levels of keys`);
11
+ return;
12
+ }
13
+ if (typeof value === 'string') {
14
+ if (out.has(prefix)) {
15
+ report({
16
+ key: prefix,
17
+ message: `"${prefix}" is written twice, with dots and in a group`,
18
+ code: 'key-conflict',
19
+ });
20
+ }
21
+ out.set(prefix, value);
22
+ return;
23
+ }
24
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
25
+ for (const [k, v] of Object.entries(value)) {
26
+ flatten(v, { prefix: `${prefix}.${k}`, out, report });
27
+ }
28
+ return;
29
+ }
30
+ const kind = Array.isArray(value) ? 'array' : typeof value;
31
+ invalid(`expected a string or an object, got ${value === null ? 'null' : kind}`);
32
+ }
33
+ /** A catalog's messages by dotted key; nothing, reported, unless it is an object. */
34
+ function flattenRoot(tree, report) {
35
+ if (!tree || typeof tree !== 'object' || Array.isArray(tree)) {
36
+ const kind = Array.isArray(tree) ? 'array' : typeof tree;
37
+ const message = `expected an object of messages, got ${tree === null ? 'null' : kind}`;
38
+ report({ key: '', message, code: 'invalid-resource' });
39
+ return undefined;
40
+ }
41
+ const out = new Map();
42
+ // From the root, as a group named "" would otherwise pass for it.
43
+ for (const [key, value] of Object.entries(tree)) {
44
+ flatten(value, { prefix: key, out, report });
45
+ }
46
+ return out;
47
+ }
48
+ export function readText(file) {
49
+ if (!existsSync(file)) {
50
+ return undefined;
51
+ }
52
+ try {
53
+ return readFileSync(file, 'utf8');
54
+ }
55
+ catch (error) {
56
+ return error;
57
+ }
58
+ }
59
+ export function readCatalog(ns, { locale, adapter, text, report: diag, }) {
60
+ const file = ns.file(locale);
61
+ const entries = new Map();
62
+ if (text === undefined) {
63
+ return { file, entries, exists: false };
64
+ }
65
+ let tree;
66
+ try {
67
+ if (text instanceof Error) {
68
+ throw text;
69
+ }
70
+ tree = adapter.parseFile ? adapter.parseFile(text) : JSON.parse(text);
71
+ }
72
+ catch (error) {
73
+ diag({ level: 'error', code: 'invalid-resource', message: error.message, file });
74
+ return { file, entries, exists: true };
75
+ }
76
+ const flat = flattenRoot(tree, (problem) => {
77
+ diag({ level: 'error', ...problem, file });
78
+ });
79
+ if (!flat) {
80
+ return { file, entries, exists: true };
81
+ }
82
+ // Every prefix, not a sorted neighbour: `-` and others sort between `a` and `a.b`.
83
+ const groups = new Set();
84
+ for (const key of flat.keys()) {
85
+ for (let dot = key.indexOf('.'); dot !== -1; dot = key.indexOf('.', dot + 1)) {
86
+ groups.add(key.slice(0, dot));
87
+ }
88
+ }
89
+ for (const key of flat.keys()) {
90
+ if (groups.has(key)) {
91
+ diag({
92
+ level: 'error',
93
+ code: 'key-conflict',
94
+ key,
95
+ message: `"${key}" is both a message and a group`,
96
+ file,
97
+ });
98
+ }
99
+ }
100
+ for (const [key, source] of flat) {
101
+ try {
102
+ entries.set(key, { source, model: adapter.parse(source) });
103
+ }
104
+ catch (error) {
105
+ diag({
106
+ level: 'error',
107
+ code: 'invalid-syntax',
108
+ key,
109
+ message: error.message,
110
+ file,
111
+ });
112
+ }
113
+ }
114
+ return { file, entries, exists: true };
115
+ }
@@ -0,0 +1,9 @@
1
+ export { build, type BuildOptions, type BuildResult } from './build.ts';
2
+ export { compileMessage } from './compile/compile.ts';
3
+ export { CompileError } from './compile/error.ts';
4
+ export type { CompiledMessage, CustomFunctions, FunctionKind, MessageInfo, ParamKind, } from './compile/info.ts';
5
+ export { ModuleScope } from './compile/scope.ts';
6
+ export { ConfigError, defineConfig, type FormatAdapter, type NamespaceConfig, type ParlaConfig, type ResolvedConfig, type ResolvedNamespace, } from './config/config.ts';
7
+ export { loadConfig } from './config/load.ts';
8
+ export { formatDiagnostic, type Diagnostic, type ErrorDiagnostic, type WarningDiagnostic, } from './diagnostics.ts';
9
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,KAAK,YAAY,EAAE,KAAK,WAAW,EAAE,MAAM,YAAY,CAAC;AACxE,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,YAAY,EACV,eAAe,EACf,eAAe,EACf,YAAY,EACZ,WAAW,EACX,SAAS,GACV,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EACL,WAAW,EACX,YAAY,EACZ,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,KAAK,WAAW,EAChB,KAAK,cAAc,EACnB,KAAK,iBAAiB,GACvB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EACL,gBAAgB,EAChB,KAAK,UAAU,EACf,KAAK,eAAe,EACpB,KAAK,iBAAiB,GACvB,MAAM,kBAAkB,CAAC"}
package/build/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export { build } from './build.js';
2
+ export { compileMessage } from './compile/compile.js';
3
+ export { CompileError } from './compile/error.js';
4
+ export { ModuleScope } from './compile/scope.js';
5
+ export { ConfigError, defineConfig, } from './config/config.js';
6
+ export { loadConfig } from './config/load.js';
7
+ export { formatDiagnostic, } from './diagnostics.js';
@@ -0,0 +1,43 @@
1
+ interface Framework {
2
+ readonly name: string;
3
+ readonly adapter: string;
4
+ /** The framework's Vite plugin, as `vite.config.ts` calls it. */
5
+ readonly plugin: string;
6
+ /** How a component loads a namespace. */
7
+ readonly load: string;
8
+ readonly docs: string;
9
+ }
10
+ declare const ADD: {
11
+ readonly pnpm: {
12
+ readonly add: 'pnpm add';
13
+ readonly dev: 'pnpm add -D';
14
+ };
15
+ readonly npm: {
16
+ readonly add: 'npm install';
17
+ readonly dev: 'npm install -D';
18
+ };
19
+ readonly yarn: {
20
+ readonly add: 'yarn add';
21
+ readonly dev: 'yarn add -D';
22
+ };
23
+ readonly bun: {
24
+ readonly add: 'bun add';
25
+ readonly dev: 'bun add -d';
26
+ };
27
+ };
28
+ type Manager = keyof typeof ADD;
29
+ export interface Project {
30
+ readonly dependencies: ReadonlySet<string>;
31
+ readonly framework: Framework;
32
+ readonly vite: boolean;
33
+ /** Whether Node reads the package's `.ts` files as ES modules. */
34
+ readonly esm: boolean;
35
+ readonly manager: Manager;
36
+ readonly add: (typeof ADD)[Manager];
37
+ }
38
+ /** The nearest lockfile's manager, as a workspace keeps one at its root; else the one running us. */
39
+ export declare function detectManager(cwd: string): Manager;
40
+ /** What `parla init` reads from the folder instead of asking. */
41
+ export declare function detectProject(cwd: string): Project | undefined;
42
+ export {};
43
+ //# sourceMappingURL=detect.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"detect.d.ts","sourceRoot":"","sources":["../../src/init/detect.ts"],"names":[],"mappings":"AAKA,UAAU,SAAS;IACjB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,iEAAiE;IACjE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,yCAAyC;IACzC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB;AA2BD,QAAA,MAAM,GAAG;aACP,IAAI;iBAAI,GAAG,EAAE,UAAU;iBAAE,GAAG,EAAE,aAAa;;aAC3C,GAAG;iBAAI,GAAG,EAAE,aAAa;iBAAE,GAAG,EAAE,gBAAgB;;aAChD,IAAI;iBAAI,GAAG,EAAE,UAAU;iBAAE,GAAG,EAAE,aAAa;;aAC3C,GAAG;iBAAI,GAAG,EAAE,SAAS;iBAAE,GAAG,EAAE,YAAY;;CAChC,CAAC;AAEX,KAAK,OAAO,GAAG,MAAM,OAAO,GAAG,CAAC;AAUhC,MAAM,WAAW,OAAO;IACtB,QAAQ,CAAC,YAAY,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IAC3C,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;IAC9B,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;IACvB,kEAAkE;IAClE,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,GAAG,EAAE,CAAC,OAAO,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC;CACrC;AAID,qGAAqG;AACrG,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAYlD;AAED,iEAAiE;AACjE,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,GAAG,SAAS,CAiB9D"}
@@ -0,0 +1,69 @@
1
+ import { existsSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { readPackageJson } from '../config/load.js';
4
+ const DOCS = 'https://parlajs.github.io/parla';
5
+ const adapter = (name, plugin) => ({
6
+ name,
7
+ adapter: `@parlajs/${name.toLowerCase()}`,
8
+ plugin,
9
+ load: 'useParla([common])',
10
+ docs: `${DOCS}/adapters/${name.toLowerCase()}/`,
11
+ });
12
+ const FRAMEWORKS = [
13
+ ['react', adapter('React', 'react()')],
14
+ ['vue', adapter('Vue', 'vue()')],
15
+ ['svelte', adapter('Svelte', 'svelte()')],
16
+ ['solid-js', adapter('Solid', 'solid()')],
17
+ ];
18
+ const CORE = {
19
+ name: 'no framework',
20
+ adapter: '@parlajs/core',
21
+ plugin: '',
22
+ load: 'await parla.load([common])',
23
+ docs: `${DOCS}/core/loading/`,
24
+ };
25
+ const ADD = {
26
+ pnpm: { add: 'pnpm add', dev: 'pnpm add -D' },
27
+ npm: { add: 'npm install', dev: 'npm install -D' },
28
+ yarn: { add: 'yarn add', dev: 'yarn add -D' },
29
+ bun: { add: 'bun add', dev: 'bun add -d' },
30
+ };
31
+ const LOCKFILES = [
32
+ ['pnpm-lock.yaml', 'pnpm'],
33
+ ['yarn.lock', 'yarn'],
34
+ ['bun.lock', 'bun'],
35
+ ['bun.lockb', 'bun'],
36
+ ['package-lock.json', 'npm'],
37
+ ];
38
+ const isManager = (name) => name !== undefined && name in ADD;
39
+ /** The nearest lockfile's manager, as a workspace keeps one at its root; else the one running us. */
40
+ export function detectManager(cwd) {
41
+ for (let dir = cwd;; dir = path.dirname(dir)) {
42
+ const found = LOCKFILES.find(([file]) => existsSync(path.join(dir, file)));
43
+ if (found) {
44
+ return found[1];
45
+ }
46
+ if (path.dirname(dir) === dir) {
47
+ break;
48
+ }
49
+ }
50
+ const agent = process.env['npm_config_user_agent']?.split('/')[0];
51
+ return isManager(agent) ? agent : 'npm';
52
+ }
53
+ /** What `parla init` reads from the folder instead of asking. */
54
+ export function detectProject(cwd) {
55
+ const pkg = readPackageJson(cwd);
56
+ if (!pkg) {
57
+ return undefined;
58
+ }
59
+ const dependencies = new Set(Object.keys({ ...pkg.peerDependencies, ...pkg.devDependencies, ...pkg.dependencies }));
60
+ const manager = detectManager(cwd);
61
+ return {
62
+ dependencies,
63
+ framework: FRAMEWORKS.find(([name]) => dependencies.has(name))?.[1] ?? CORE,
64
+ vite: dependencies.has('vite'),
65
+ esm: pkg.type === 'module',
66
+ manager,
67
+ add: ADD[manager],
68
+ };
69
+ }
@@ -0,0 +1,12 @@
1
+ interface InitOptions {
2
+ /** `mf2` or `icu`. */
3
+ readonly format?: string | undefined;
4
+ /** Comma-separated, the source locale first. */
5
+ readonly locales?: string | undefined;
6
+ /** The folder of the catalogs, relative to the config. */
7
+ readonly catalogs?: string | undefined;
8
+ }
9
+ /** Runs `parla init` in `cwd`: what it wrote and what is left to do. */
10
+ export declare function init(cwd: string, options: InitOptions): Array<string>;
11
+ export {};
12
+ //# sourceMappingURL=init.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../src/init/init.ts"],"names":[],"mappings":"AAUA,UAAU,WAAW;IACnB,sBAAsB;IACtB,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACrC,gDAAgD;IAChD,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC,0DAA0D;IAC1D,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACxC;AAyHD,wEAAwE;AACxE,wBAAgB,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,GAAG,KAAK,CAAC,MAAM,CAAC,CAkBrE"}
@@ -0,0 +1,126 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { checkLocales } from '../config/checks.js';
4
+ import { ConfigError } from '../config/config.js';
5
+ import { CONFIG_FILES } from '../config/load.js';
6
+ import { detectProject } from './detect.js';
7
+ const FORMATS = {
8
+ mf2: { package: '@parlajs/format-mf2', hello: 'Hello, {$name}!' },
9
+ icu: { package: '@parlajs/format-icu', hello: 'Hello, {name}!' },
10
+ };
11
+ const OUT_DIR = 'src/parla';
12
+ const IGNORED = /^(?:\*\*\/|\/)?src\/parla\/?$/;
13
+ /** The options, checked before anything is written. */
14
+ function choose({ format = 'mf2', locales = 'en', catalogs = 'locales' }, config) {
15
+ if (!Object.hasOwn(FORMATS, format)) {
16
+ throw new ConfigError(`--format is mf2 or icu, not "${format}"`);
17
+ }
18
+ const list = locales.split(',').map((l) => l.trim());
19
+ checkLocales({ locales: list, sourceLocale: list[0] ?? '', fallbacks: {} });
20
+ const dir = catalogs.replace(/\/+$/, '');
21
+ // The path lands in a string literal of the config.
22
+ if (!/^[\w.-][\w./-]*$/.test(dir) || dir.split('/').includes('..')) {
23
+ throw new ConfigError(`--catalogs takes a relative folder of letters, digits, ".", "_" or "-"`);
24
+ }
25
+ const inside = path.posix.relative(OUT_DIR, path.posix.normalize(dir));
26
+ if (inside !== '..' && !inside.startsWith('../')) {
27
+ throw new ConfigError(`--catalogs cannot be in ${OUT_DIR}, which holds generated files only`);
28
+ }
29
+ return { config, format, locales: list, catalogs: dir };
30
+ }
31
+ const configModule = ({ format, locales, catalogs }) => `import { defineConfig } from '@parlajs/compiler';
32
+ import { ${format} } from '${FORMATS[format]?.package}';
33
+
34
+ export default defineConfig({
35
+ locales: [${locales.map((l) => `'${l}'`).join(', ')}],
36
+ sourceLocale: '${locales[0]}',
37
+ outDir: '${OUT_DIR}',
38
+ formats: { ${format} },
39
+ namespaces: { common: { format: '${format}', path: '${catalogs}/{locale}/common.json' } },
40
+ });
41
+ `;
42
+ /** Adds `src/parla/` to `.gitignore`, unless it is there. */
43
+ function ignore(cwd) {
44
+ const file = path.join(cwd, '.gitignore');
45
+ const text = existsSync(file) ? readFileSync(file, 'utf8') : undefined;
46
+ if (text?.split(/\r?\n/).some((line) => IGNORED.test(line.trim()))) {
47
+ return '';
48
+ }
49
+ const before = text === undefined || text === '' || text.endsWith('\n') ? '' : '\n';
50
+ writeFileSync(file, `${text ?? ''}${before}${OUT_DIR}/\n`);
51
+ return ` ${text === undefined ? 'created' : 'updated'} .gitignore: ${OUT_DIR}/`;
52
+ }
53
+ /** Writes the config, a catalog per locale and the ignore line; never one that exists. */
54
+ function write(cwd, choices) {
55
+ writeFileSync(path.join(cwd, choices.config), configModule(choices));
56
+ const lines = [` created ${choices.config}`];
57
+ const hello = `${JSON.stringify({ hello: FORMATS[choices.format]?.hello }, null, 2)}\n`;
58
+ for (const locale of choices.locales) {
59
+ const file = `${choices.catalogs}/${locale}/common.json`;
60
+ const target = path.join(cwd, file);
61
+ if (existsSync(target)) {
62
+ lines.push(` kept ${file}`);
63
+ }
64
+ else {
65
+ mkdirSync(path.dirname(target), { recursive: true });
66
+ writeFileSync(target, hello);
67
+ lines.push(` created ${file}`);
68
+ }
69
+ }
70
+ return [...lines, ignore(cwd)].filter(Boolean);
71
+ }
72
+ /** What is left to the user: installing, the Vite plugin, the first call. */
73
+ function next(project, { format }) {
74
+ const { framework, add, dependencies } = project;
75
+ const missing = (list) => list.filter((name) => !dependencies.has(name)).join(' ');
76
+ const runtime = missing([...new Set([framework.adapter, '@parlajs/core'])]);
77
+ const dev = missing(['@parlajs/compiler', FORMATS[format]?.package ?? '']);
78
+ const plugins = framework.plugin ? `parla(), ${framework.plugin}` : 'parla()';
79
+ return [
80
+ '',
81
+ 'Next',
82
+ ...(runtime ? [` ${add.add} ${runtime}`] : []),
83
+ ...(dev ? [` ${add.dev} ${dev}`] : []),
84
+ '',
85
+ ...(project.vite
86
+ ? [
87
+ ' vite.config.ts',
88
+ " import { parla } from '@parlajs/compiler/vite';",
89
+ ` plugins: [${plugins}]`,
90
+ ]
91
+ : [
92
+ ' parla build before the bundler',
93
+ ' parla build --watch beside its dev server',
94
+ ]),
95
+ ...(framework.name === 'Svelte'
96
+ ? [
97
+ ' svelte.config.js, for useParla',
98
+ ' compilerOptions: { experimental: { async: true } }',
99
+ ]
100
+ : []),
101
+ '',
102
+ " import { common } from './parla/namespaces/common.js';",
103
+ ` ${framework.load} → t.common.hello({ name: 'Ada' })`,
104
+ ` ${framework.docs}`,
105
+ ];
106
+ }
107
+ /** Runs `parla init` in `cwd`: what it wrote and what is left to do. */
108
+ export function init(cwd, options) {
109
+ const project = detectProject(cwd);
110
+ if (!project) {
111
+ throw new ConfigError(`No package.json in ${cwd}: run parla init in the app's folder`);
112
+ }
113
+ // Node reads a `.ts` as CommonJS unless the package says `"type": "module"`.
114
+ const choices = choose(options, CONFIG_FILES[project.esm ? 0 : 1]);
115
+ const existing = CONFIG_FILES.find((name) => existsSync(path.join(cwd, name)));
116
+ if (existing) {
117
+ throw new ConfigError(`${existing} exists: edit it instead`);
118
+ }
119
+ const { framework, vite, manager } = project;
120
+ const header = [framework.name, vite ? 'Vite' : 'no Vite', manager, choices.format];
121
+ return [
122
+ `parla init: ${[...header, choices.locales.join(', ')].join(' · ')}`,
123
+ ...write(cwd, choices),
124
+ ...next(project, choices),
125
+ ];
126
+ }
@@ -0,0 +1,3 @@
1
+ import type { Options } from './literal.ts';
2
+ export declare function dateOptions(name: string, options: Options): Options;
3
+ //# sourceMappingURL=date.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"date.d.ts","sourceRoot":"","sources":["../../src/options/date.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAwD5C,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CA6BnE"}
@@ -0,0 +1,77 @@
1
+ import { chosen, literal } from './literal.js';
2
+ import { FIELDS, SETTINGS } from './names.js';
3
+ const DATE_FIELDS = new Set([
4
+ 'weekday',
5
+ 'day-weekday',
6
+ 'month-day',
7
+ 'month-day-weekday',
8
+ 'year-month-day',
9
+ 'year-month-day-weekday',
10
+ ]);
11
+ const LENGTHS = new Set(['long', 'medium', 'short']);
12
+ const PRECISIONS = ['hour', 'minute', 'second'];
13
+ /** MF2's fields, length and precision, as `Intl`'s fields. */
14
+ function semanticFields(name, options) {
15
+ const { fields, dateFields, length, dateLength, precision, timePrecision, timeZoneStyle } = options;
16
+ const out = {};
17
+ if (name !== 'time') {
18
+ const size = length ?? dateLength;
19
+ const isLong = size ? chosen('length', { value: size, allowed: LENGTHS }) : 'medium';
20
+ const asked = fields ?? dateFields;
21
+ const set = asked ? chosen('fields', { value: asked, allowed: DATE_FIELDS }) : 'year-month-day';
22
+ const months = { long: 'long', medium: 'short', short: 'numeric' };
23
+ for (const field of set.split('-')) {
24
+ let value = 'numeric';
25
+ if (field === 'month') {
26
+ value = months[isLong] ?? value;
27
+ }
28
+ else if (field === 'weekday') {
29
+ value = isLong === 'long' ? 'long' : 'short';
30
+ }
31
+ out[field] = literal(value);
32
+ }
33
+ }
34
+ if (name !== 'date') {
35
+ const asked = precision ?? timePrecision;
36
+ const until = asked
37
+ ? chosen('precision', { value: asked, allowed: new Set(PRECISIONS) })
38
+ : 'minute';
39
+ for (const field of PRECISIONS.slice(0, PRECISIONS.indexOf(until) + 1)) {
40
+ out[field] = literal('numeric');
41
+ }
42
+ if (timeZoneStyle) {
43
+ out['timeZoneName'] = timeZoneStyle;
44
+ }
45
+ }
46
+ return out;
47
+ }
48
+ const STYLES = ['style', 'dateStyle', 'timeStyle'];
49
+ const SEMANTIC = ['fields', 'dateFields', 'precision', 'timePrecision', 'timeZoneStyle'];
50
+ export function dateOptions(name, options) {
51
+ const out = Object.fromEntries(Object.entries(options).filter(([k]) => SETTINGS.includes(k) || FIELDS.includes(k)));
52
+ if (SEMANTIC.some((k) => options[k])) {
53
+ const style = STYLES.find((k) => options[k]);
54
+ if (style) {
55
+ throw new Error(`${style} cannot be combined with fields or a precision: use length`);
56
+ }
57
+ return { ...out, ...semanticFields(name, options) };
58
+ }
59
+ const { style, length, dateLength, dateStyle, timeStyle } = options;
60
+ if (style || length || dateLength || dateStyle || timeStyle) {
61
+ const size = style ?? length;
62
+ if (name === 'time') {
63
+ return { ...out, timeStyle: size ?? literal('short') };
64
+ }
65
+ out['dateStyle'] = dateStyle ?? dateLength ?? size ?? literal('medium');
66
+ return name === 'date' ? out : { ...out, timeStyle: timeStyle ?? literal('short') };
67
+ }
68
+ if (FIELDS.some((k) => options[k])) {
69
+ return out;
70
+ }
71
+ // Settings alone: the runtime adds the default style only to a call without options.
72
+ return {
73
+ ...out,
74
+ ...(name === 'time' ? {} : { dateStyle: literal('medium') }),
75
+ ...(name === 'date' ? {} : { timeStyle: literal('short') }),
76
+ };
77
+ }