@worldware/msg-cli 0.2.1 → 0.2.3

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.
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  msg-cli is a command-line tool for the [msg](https://github.com/worldware-studios/msg) library. It helps you scaffold internationalization (i18n) and localization (l10n) layout and wire up your project for use with msg.
6
6
 
7
- **Current status:** CLI for the msg library (npm: `@worldware/msg-cli`, v0.2.0). Commands: `init` (scaffold i18n/l10n and config), `create project` (new MsgProject in i18n/projects), `create resource` (new MsgResource in i18n/resources), `export` (serialize MsgResources to XLIFF 2.0 in l10n/xliff), `import` (import translations from XLIFF 2.0 to JSON in l10n/translations).
7
+ **Current status:** CLI for the msg library (npm: `@worldware/msg-cli`, v0.2.2). Commands: `init` (scaffold i18n/l10n and config), `create project` (new MsgProject in i18n/projects), `create resource` (new MsgResource in i18n/resources), `export` (serialize MsgResources to XLIFF 2.2 in l10n/xliff), `import` (import translations from XLIFF 2.0/2.2 to JSON in l10n/translations).
8
8
 
9
9
  ## Installation
10
10
 
@@ -20,7 +20,7 @@ Or use via `npx`:
20
20
  npx msg <command>
21
21
  ```
22
22
 
23
- For project-local setup, run `msg init` in your project root to add msg and msg-cli as dependencies and scaffold directories and config.
23
+ For project-local setup, run `msg init` in your project root to add `@worldware/msg` and scaffold directories and config. Install msg-cli globally (as above) or as a dev dependency to run the commands.
24
24
 
25
25
  ## Core Concepts
26
26
 
@@ -113,9 +113,10 @@ msg create project -h
113
113
 
114
114
  **Behavior:**
115
115
 
116
- - Writes the file to `i18n/projects/<projectName>.js` or `.ts` (TypeScript if `tsconfig.json` exists).
117
- - Uses ES module or CommonJS export based on `package.json` `"type"`.
116
+ - Writes the file to `i18n/projects/<projectName>.js` (always `.js`).
117
+ - Uses ES module or CommonJS export syntax based on `package.json` `"type"` or presence of `tsconfig.json`.
118
118
  - Generates a translation loader that imports from `l10n/translations` using the relative path from `i18n/projects` (from `directories` in package.json).
119
+ - Includes `pseudoLocale: 'en-XA'` by default (or inherits from the base project when extending), for use with msg's `getTranslation(pseudoLocale)` pseudolocalization support.
119
120
  - With `--extend <name>`, merges target locales and pseudoLocale from the existing project. If `source` and `targets` are omitted, they are inherited from the base project.
120
121
  - Errors if the project name already exists, package.json is missing or invalid, or required directories are not configured.
121
122
 
@@ -153,15 +154,15 @@ msg create resource myProject messages --edit
153
154
 
154
155
  **Behavior:**
155
156
 
156
- - Writes the file to `i18n/resources/<title>.msg.js` or `.msg.ts` (TypeScript if `tsconfig.json` exists).
157
- - Uses ES module or CommonJS export based on `package.json` `"type"`.
157
+ - Writes the file to `i18n/resources/<title>.msg.js` (always `.js`).
158
+ - Uses ES module or CommonJS export syntax based on `package.json` `"type"` or presence of `tsconfig.json`.
158
159
  - Sets `lang` from the project's `sourceLocale` and `dir` to `rtl` for Arabic/Hebrew, `ltr` otherwise.
159
160
  - Includes a minimal example message. Validates that the generated file is importable.
160
161
  - Errors if i18n/projects or i18n/resources does not exist, the project is not found, or the resource file already exists (unless `--force`).
161
162
 
162
163
  ### export
163
164
 
164
- Serialize all MsgResource files in `i18n/resources` to XLIFF 2.0 files in `l10n/xliff`, one file per project. Does not send files for translation; use your own translation workflow with the generated XLIFF. Requires `package.json` with `directories.i18n` and `directories.l10n` (run `msg init` first).
165
+ Serialize all MsgResource files in `i18n/resources` to XLIFF 2.2 files in `l10n/xliff`, one file per project. Does not send files for translation; use your own translation workflow with the generated XLIFF. Requires `package.json` with `directories.i18n` and `directories.l10n` (run `msg init` first).
165
166
 
166
167
  ```bash
167
168
  msg export [-p <projectName>]
@@ -187,22 +188,24 @@ msg export -p myApp
187
188
 
188
189
  - Recursively finds all `.msg.js` and `.msg.ts` files under `i18n/resources`.
189
190
  - Imports each file as a MsgResource; errors if any file is invalid.
190
- - Groups resources by project name and writes one XLIFF 2.0 file per project to `l10n/xliff` (e.g. `myApp.xliff`).
191
+ - Groups resources by project name and writes one XLIFF 2.2 file per project to `l10n/xliff` (e.g. `myApp.xliff`).
191
192
  - With `--project`, only that project is exported; existing other files in `l10n/xliff` are not removed.
192
193
  - If no MsgResource files are found, exits with an informational message (no error).
193
194
  - Logs each major step (finding files, importing, grouping, writing).
194
195
 
195
- **What is preserved in XLIFF 2.0:**
196
+ **What is preserved in XLIFF 2.2:**
196
197
 
197
198
  - **Message keys** — Stored as unit `id` (sanitized for XML) and `name` (original key).
198
199
  - **Resource notes** — Emitted as file-level `<notes>` with category (e.g. `description`, `comment`).
199
200
  - **Resource attributes** — `dir` → file `srcDir`; `dnt` → file `translate="no"`.
200
201
  - **Message notes** — Emitted as unit-level `<notes>` with category (e.g. `description`, `context`, `parameters`).
201
- - **Message attributes** — `dnt` → unit `translate="no"`; message `dir` is serialized as the unit’s `srcDir` attribute (XLIFF 2.0 text direction for the segment).
202
+ - **Message attributes** — `dnt` → unit `translate="no"`; message `dir` is serialized as the unit’s `srcDir` attribute (XLIFF text direction for the segment).
203
+
204
+ **Plural, gender, select (PGS) and MessageFormat 2:** Messages written in Unicode MessageFormat 2 using `.match` are exported to the [XLIFF 2.2 Plural, Gender, and Select module](https://docs.oasis-open.org/xliff/xliff-core/v2.2/xliff-extended-v2.2-part2.html) when the selectors classify as `plural`, `ordinal`, `gender`, or `select` (see implementation in `pgs-mf2`). Such units use `xmlns:pgs="urn:oasis:names:tc:xliff:pgs:1.0"`, `pgs:switch` on the `<unit>`, and one `<segment>` per variant with `pgs:case`. Other messages stay a single segment with the full MF2 string in `<source>`. Unsupported `.match` shapes fall back to that single-segment form.
202
205
 
203
206
  ### import
204
207
 
205
- Import translations from bilingual XLIFF 2.0 files in `l10n/xliff` to JSON files in `l10n/translations`. Expects XLIFF files with `trgLang` (target language) and translated content in `<target>` elements. Writes JSON files without notes for minimal size. Requires `package.json` with `directories.i18n` and `directories.l10n` (run `msg init` first).
208
+ Import translations from bilingual XLIFF 2.0 or 2.2 files in `l10n/xliff` to JSON files in `l10n/translations`. Expects XLIFF files with `trgLang` (target language) and translated content in `<target>` elements. Writes JSON files without notes for minimal size. Requires `package.json` with `directories.i18n` and `directories.l10n` (run `msg init` first). Units with `pgs:switch` are reassembled into a single MessageFormat 2 string per message key from the segment bodies (targets when present).
206
209
 
207
210
  ```bash
208
211
  msg import [-p <projectName>] [-l <locale>]
@@ -236,10 +239,95 @@ msg import -l zh
236
239
  - Dynamically imports `MsgProject` from `i18n/projects` to validate target locales.
237
240
  - Skips monolingual XLIFF files (no `trgLang`).
238
241
  - Skips files whose target locale is not in the project's `targetLocales`.
242
+ - Skips files when the matching project file does not exist or cannot be loaded.
239
243
  - Writes JSON to `l10n/translations/<project>/<locale>/<title>.json`.
240
244
  - Preserves existing translation files for other projects or locales when filtering.
241
245
  - Errors on malformed XLIFF and logs each step.
242
246
 
247
+ ### Example: plural messages (XLIFF 2.2 PGS)
248
+
249
+ Plural (and other classifiable `.match`) messages use the [XLIFF 2.2 PGS module](https://docs.oasis-open.org/xliff/xliff-core/v2.2/xliff-extended-v2.2-part2.html): export splits them into one `<segment>` per variant (`pgs:case`), and import merges `<target>` text back into a single MessageFormat 2 string per message key.
250
+
251
+ **1. Message in the MsgResource** (Unicode MessageFormat 2 with `.input` / `.match` on a plural):
252
+
253
+ ```js
254
+ // i18n/resources/messages.msg.js — excerpt
255
+ itemsCount: `.input {$n :number}
256
+ .match $n
257
+ one {{One item}}
258
+ * {{{$n} items}}`,
259
+ ```
260
+
261
+ **2. Export** — writes monolingual XLIFF 2.2 to `l10n/xliff/<project>.xliff` (here `l10n/xliff/myApp.xliff`):
262
+
263
+ ```bash
264
+ msg export
265
+ # or: msg export --project myApp
266
+ ```
267
+
268
+ The plural becomes a `pgs:switch` unit with one segment per case (abbreviated):
269
+
270
+ ```xml
271
+ <?xml version="1.0" encoding="UTF-8"?>
272
+ <xliff xmlns="urn:oasis:names:tc:xliff:document:2.2" xmlns:pgs="urn:oasis:names:tc:xliff:pgs:1.0" version="2.2" srcLang="en">
273
+ <file id="f1" original="messages.json" srcDir="ltr">
274
+ <unit id="itemsCount" name="itemsCount" pgs:switch="plural:n">
275
+ <segment id="itemsCount_s1" pgs:case="one">
276
+ <source>One item</source>
277
+ </segment>
278
+ <segment id="itemsCount_s2" pgs:case="other">
279
+ <source>{$n} items</source>
280
+ </segment>
281
+ </unit>
282
+ </file>
283
+ </xliff>
284
+ ```
285
+
286
+ **3. Bilingual file for translation** — `msg import` needs `trgLang` and `<target>` elements. Typical workflow: copy the export to a locale-specific name such as `myApp.fr.xliff`, set `trgLang="fr"` on the root `<xliff>`, and add a `<target>` under **each** `<segment>` (preserving `pgs:switch` / `pgs:case`). The project’s `MsgProject` must list `fr` in `targetLocales`.
287
+
288
+ ```xml
289
+ <xliff xmlns="urn:oasis:names:tc:xliff:document:2.2" xmlns:pgs="urn:oasis:names:tc:xliff:pgs:1.0" version="2.2" srcLang="en" trgLang="fr">
290
+ <file id="f1" original="messages.json" srcDir="ltr">
291
+ <unit id="itemsCount" name="itemsCount" pgs:switch="plural:n">
292
+ <segment id="itemsCount_s1" pgs:case="one">
293
+ <source>One item</source>
294
+ <target>Un élément</target>
295
+ </segment>
296
+ <segment id="itemsCount_s2" pgs:case="other">
297
+ <source>{$n} items</source>
298
+ <target>{$n} éléments</target>
299
+ </segment>
300
+ </unit>
301
+ </file>
302
+ </xliff>
303
+ ```
304
+
305
+ **4. Import** — writes minimal JSON under `l10n/translations/<project>/<locale>/<resource>.json`, with one MF2 message per key rebuilt from the PGS segments:
306
+
307
+ ```bash
308
+ msg import
309
+ # or: msg import --project myApp --language fr
310
+ ```
311
+
312
+ **5. Resulting French translation file** — `l10n/translations/myApp/fr/messages.json` (notes omitted; `attributes.dir` is empty unless the XLIFF `<file>` carries `trgDir`):
313
+
314
+ ```json
315
+ {
316
+ "title": "messages",
317
+ "attributes": {
318
+ "lang": "fr",
319
+ "dir": "",
320
+ "dnt": false
321
+ },
322
+ "messages": [
323
+ {
324
+ "key": "itemsCount",
325
+ "value": ".input {$n :number}\n.match $n\none {{Un élément}}\n* {{{$n} éléments}}"
326
+ }
327
+ ]
328
+ }
329
+ ```
330
+
243
331
  ## API Reference
244
332
 
245
333
  The CLI does not expose a programmatic API. For library usage, see [@worldware/msg](https://github.com/worldware-studios/msg).
@@ -1,3 +1,6 @@
1
+ import {
2
+ pgsImportToSelectMessage
3
+ } from "./chunk-DPUF7YUH.mjs";
1
4
  import {
2
5
  dynamicImportFromUrl
3
6
  } from "./chunk-LNCUPVEF.mjs";
@@ -110,7 +113,7 @@ function parseXliff20(xml) {
110
113
  return parsed;
111
114
  } catch (err) {
112
115
  const message = err instanceof Error ? err.message : "Failed to parse XLIFF";
113
- throw new Error(`Malformed XLIFF 2.0: ${message}`);
116
+ throw new Error(`Malformed XLIFF: ${message}`);
114
117
  }
115
118
  }
116
119
  function categoryToNoteType(category) {
@@ -197,11 +200,32 @@ function processUnit(unit, fileAttrs) {
197
200
  }
198
201
  }
199
202
  const segments = unit.segment ? Array.isArray(unit.segment) ? unit.segment : [unit.segment] : [];
200
- const targetParts = [];
201
- for (const seg of segments) {
202
- targetParts.push(extractSegmentText(seg));
203
+ const pgsSwitch = unit["@_pgs:switch"];
204
+ let value;
205
+ if (pgsSwitch && segments.length > 0 && segments.every(
206
+ (seg) => typeof seg["@_pgs:case"] === "string"
207
+ )) {
208
+ const importSegments = segments.map((seg) => ({
209
+ caseAttr: seg["@_pgs:case"],
210
+ body: extractSegmentText(seg)
211
+ }));
212
+ const rebuilt = pgsImportToSelectMessage(pgsSwitch, importSegments);
213
+ if (rebuilt) {
214
+ value = rebuilt;
215
+ } else {
216
+ const targetParts = [];
217
+ for (const seg of segments) {
218
+ targetParts.push(extractSegmentText(seg));
219
+ }
220
+ value = targetParts.join("");
221
+ }
222
+ } else {
223
+ const targetParts = [];
224
+ for (const seg of segments) {
225
+ targetParts.push(extractSegmentText(seg));
226
+ }
227
+ value = targetParts.join("");
203
228
  }
204
- const value = targetParts.join("");
205
229
  const attributes = {};
206
230
  if (trgLang !== fileAttrs.trgLang) attributes.lang = trgLang || void 0;
207
231
  if (trgDir !== fileAttrs.trgDir) attributes.dir = trgDir || void 0;
@@ -0,0 +1,269 @@
1
+ // src/lib/pgs-mf2.ts
2
+ import {
3
+ parseMessage,
4
+ stringifyMessage,
5
+ validate,
6
+ isSelectMessage,
7
+ isCatchallKey,
8
+ isLiteral
9
+ } from "messageformat";
10
+ var PGS_SWITCH_ITEM = /^(plural|ordinal|gender|select):([a-zA-Z_][a-zA-Z0-9_]*)$/;
11
+ var GENDER_LABELS = /* @__PURE__ */ new Set([
12
+ "feminine",
13
+ "masculine",
14
+ "neuter",
15
+ "other"
16
+ ]);
17
+ function parsePgsSwitch(value) {
18
+ const trimmed = value.trim();
19
+ if (!trimmed) return null;
20
+ const parts = trimmed.split(/\s+/);
21
+ const out = [];
22
+ for (const p of parts) {
23
+ const m = p.match(PGS_SWITCH_ITEM);
24
+ if (!m) return null;
25
+ out.push({ kind: m[1], name: m[2] });
26
+ }
27
+ return out.length > 0 ? out : null;
28
+ }
29
+ function findInputDeclaration(msg, varName) {
30
+ for (const d of msg.declarations) {
31
+ const decl = d;
32
+ if (decl.type === "input" && decl.name === varName) {
33
+ return decl;
34
+ }
35
+ }
36
+ return null;
37
+ }
38
+ function getFunctionName(expr) {
39
+ return expr.functionRef?.name;
40
+ }
41
+ function getSelectOptionOrdinal(expr) {
42
+ const opts = expr.functionRef?.options;
43
+ if (!opts || !(opts instanceof Map)) return false;
44
+ const sel = opts.get("select");
45
+ if (!sel || typeof sel !== "object" || sel === null) return false;
46
+ if (sel.type !== "literal") return false;
47
+ return sel.value === "ordinal";
48
+ }
49
+ function variantKeyAt(msg, variantIndex, keyIndex) {
50
+ const v = msg.variants[variantIndex];
51
+ return v?.keys[keyIndex];
52
+ }
53
+ function allKeysAtIndexAreGenderLike(msg, keyIndex) {
54
+ for (let vi = 0; vi < msg.variants.length; vi++) {
55
+ const k = variantKeyAt(msg, vi, keyIndex);
56
+ if (!k) return false;
57
+ if (isCatchallKey(k)) continue;
58
+ if (isLiteral(k)) {
59
+ if (!GENDER_LABELS.has(k.value)) return false;
60
+ continue;
61
+ }
62
+ return false;
63
+ }
64
+ return true;
65
+ }
66
+ function classifySelectMessageForPgs(msg) {
67
+ const out = [];
68
+ for (let si = 0; si < msg.selectors.length; si++) {
69
+ const sel = msg.selectors[si];
70
+ if (!sel || sel.type !== "variable" || !sel.name) return null;
71
+ const varName = sel.name;
72
+ const decl = findInputDeclaration(msg, varName);
73
+ if (!decl) return null;
74
+ const expr = decl.value;
75
+ if (expr.type !== "expression") return null;
76
+ const fname = getFunctionName(expr);
77
+ if (fname === "number") {
78
+ out.push({
79
+ kind: getSelectOptionOrdinal(expr) ? "ordinal" : "plural",
80
+ name: varName
81
+ });
82
+ continue;
83
+ }
84
+ if (fname === "string") {
85
+ const kind = allKeysAtIndexAreGenderLike(msg, si) ? "gender" : "select";
86
+ out.push({ kind, name: varName });
87
+ continue;
88
+ }
89
+ return null;
90
+ }
91
+ return out.length === msg.selectors.length ? out : null;
92
+ }
93
+ function mf2KeyToPgsToken(key, kind) {
94
+ if (isCatchallKey(key)) {
95
+ return "other";
96
+ }
97
+ if (isLiteral(key)) {
98
+ return key.value;
99
+ }
100
+ return "other";
101
+ }
102
+ function pgsTokenToMf2Key(token, kind) {
103
+ if (kind === "plural" || kind === "ordinal") {
104
+ if (token === "other") {
105
+ return { type: "*" };
106
+ }
107
+ return { type: "literal", value: token };
108
+ }
109
+ return { type: "literal", value: token };
110
+ }
111
+ function stringifyPattern(pattern) {
112
+ const wrap = {
113
+ type: "message",
114
+ declarations: [],
115
+ pattern
116
+ };
117
+ return stringifyMessage(
118
+ wrap
119
+ );
120
+ }
121
+ function selectMessageToPgsExport(source) {
122
+ let msg;
123
+ try {
124
+ msg = parseMessage(source);
125
+ } catch {
126
+ return null;
127
+ }
128
+ if (!isSelectMessage(msg)) return null;
129
+ const classification = classifySelectMessageForPgs(
130
+ msg
131
+ );
132
+ if (!classification) return null;
133
+ const switchAttr = classification.map((c) => `${c.kind}:${c.name}`).join(" ");
134
+ const segments = [];
135
+ const sel = msg;
136
+ for (let vi = 0; vi < sel.variants.length; vi++) {
137
+ const variant = sel.variants[vi];
138
+ const caseParts = [];
139
+ for (let ki = 0; ki < classification.length; ki++) {
140
+ const key = variant.keys[ki];
141
+ if (!key) return null;
142
+ caseParts.push(
143
+ mf2KeyToPgsToken(key, classification[ki].kind)
144
+ );
145
+ }
146
+ segments.push({
147
+ caseAttr: caseParts.join(" "),
148
+ sourcePattern: stringifyPattern(variant.value)
149
+ });
150
+ }
151
+ return { switchAttr, segments };
152
+ }
153
+ function parsePatternFromSegmentBody(body) {
154
+ const trimmed = body.trim();
155
+ if (!trimmed) return [];
156
+ try {
157
+ const m = parseMessage(trimmed);
158
+ if (m.type !== "message") return [];
159
+ return m.pattern;
160
+ } catch {
161
+ return [];
162
+ }
163
+ }
164
+ function ensureFallbackVariant(keysCount, variants) {
165
+ const hasAllStars = variants.some(
166
+ (v) => v.keys.length === keysCount && v.keys.every((k) => isCatchallKey(k))
167
+ );
168
+ if (hasAllStars) return;
169
+ const fallbackPattern = variants.length > 0 ? variants[variants.length - 1].value : [];
170
+ const starKeys = Array.from({ length: keysCount }, () => ({
171
+ type: "*"
172
+ }));
173
+ variants.push({ keys: starKeys, value: fallbackPattern });
174
+ }
175
+ function pgsImportToSelectMessage(switchAttr, segments) {
176
+ const parsedSwitch = parsePgsSwitch(switchAttr);
177
+ if (!parsedSwitch || parsedSwitch.length === 0) return null;
178
+ const n = parsedSwitch.length;
179
+ const declarations = [];
180
+ for (const { kind, name } of parsedSwitch) {
181
+ const varRef = { type: "variable", name };
182
+ if (kind === "plural") {
183
+ declarations.push({
184
+ type: "input",
185
+ name,
186
+ value: {
187
+ type: "expression",
188
+ arg: varRef,
189
+ functionRef: { type: "function", name: "number" }
190
+ }
191
+ });
192
+ } else if (kind === "ordinal") {
193
+ const opts = /* @__PURE__ */ new Map([
194
+ ["select", { type: "literal", value: "ordinal" }]
195
+ ]);
196
+ declarations.push({
197
+ type: "input",
198
+ name,
199
+ value: {
200
+ type: "expression",
201
+ arg: varRef,
202
+ functionRef: { type: "function", name: "number", options: opts }
203
+ }
204
+ });
205
+ } else {
206
+ declarations.push({
207
+ type: "input",
208
+ name,
209
+ value: {
210
+ type: "expression",
211
+ arg: varRef,
212
+ functionRef: { type: "function", name: "string" }
213
+ }
214
+ });
215
+ }
216
+ }
217
+ const selectors = parsedSwitch.map(
218
+ ({ name }) => ({ type: "variable", name })
219
+ );
220
+ const variants = [];
221
+ for (const seg of segments) {
222
+ const tokens = seg.caseAttr.trim().split(/\s+/).filter(Boolean);
223
+ if (tokens.length !== n) return null;
224
+ const keys = tokens.map(
225
+ (t, i) => pgsTokenToMf2Key(t, parsedSwitch[i].kind)
226
+ );
227
+ variants.push({
228
+ keys,
229
+ value: parsePatternFromSegmentBody(seg.body)
230
+ });
231
+ }
232
+ if (variants.length === 0) return null;
233
+ const msg = {
234
+ type: "select",
235
+ declarations,
236
+ selectors,
237
+ variants
238
+ };
239
+ ensureFallbackVariant(n, msg.variants);
240
+ try {
241
+ validate(
242
+ msg
243
+ );
244
+ } catch {
245
+ return null;
246
+ }
247
+ return stringifyMessage(
248
+ msg
249
+ );
250
+ }
251
+ function messagesStructurallyEqual(a, b) {
252
+ try {
253
+ const ma = parseMessage(a);
254
+ const mb = parseMessage(b);
255
+ return stringifyMessage(ma) === stringifyMessage(mb);
256
+ } catch {
257
+ return false;
258
+ }
259
+ }
260
+
261
+ export {
262
+ parsePgsSwitch,
263
+ classifySelectMessageForPgs,
264
+ mf2KeyToPgsToken,
265
+ pgsTokenToMf2Key,
266
+ selectMessageToPgsExport,
267
+ pgsImportToSelectMessage,
268
+ messagesStructurallyEqual
269
+ };
@@ -1,3 +1,6 @@
1
+ import {
2
+ selectMessageToPgsExport
3
+ } from "./chunk-DPUF7YUH.mjs";
1
4
  import {
2
5
  dynamicImportFromUrl
3
6
  } from "./chunk-LNCUPVEF.mjs";
@@ -10,7 +13,8 @@ var MSG_PATTERN = /\.msg\.(ts|js)$/i;
10
13
  function isMsgResourceLike(value) {
11
14
  return Boolean(value) && typeof value.getProject === "function";
12
15
  }
13
- var XLIFF20_NS = "urn:oasis:names:tc:xliff:document:2.0";
16
+ var XLIFF22_NS = "urn:oasis:names:tc:xliff:document:2.2";
17
+ var PGS_NS = "urn:oasis:names:tc:xliff:pgs:1.0";
14
18
  async function findMsgResourceFilePaths(directory) {
15
19
  const result = [];
16
20
  const entries = await readdir(directory, { withFileTypes: true });
@@ -93,11 +97,11 @@ function renderNotes(notes, idPrefix, indent = " ") {
93
97
  parts.push(`${indent}</notes>`);
94
98
  return parts;
95
99
  }
96
- function resourceGroupToXliff20(group) {
100
+ function resourceGroupToXliff22(group) {
97
101
  const srcLang = group.resources[0]?.attributes?.lang ?? "en";
98
102
  const parts = [
99
103
  '<?xml version="1.0" encoding="UTF-8"?>',
100
- `<xliff xmlns="${XLIFF20_NS}" version="2.0" srcLang="${escapeXml(srcLang)}">`
104
+ `<xliff xmlns="${XLIFF22_NS}" xmlns:pgs="${PGS_NS}" version="2.2" srcLang="${escapeXml(srcLang)}">`
101
105
  ];
102
106
  let fileIndex = 0;
103
107
  for (const resource of group.resources) {
@@ -135,6 +139,10 @@ function resourceGroupToXliff20(group) {
135
139
  if (msgAttr?.dir) {
136
140
  msgAttrs.push(`srcDir="${escapeXml(msgAttr.dir)}"`);
137
141
  }
142
+ const pgsExport = selectMessageToPgsExport(msg.value);
143
+ if (pgsExport) {
144
+ msgAttrs.push(`pgs:switch="${escapeXml(pgsExport.switchAttr)}"`);
145
+ }
138
146
  parts.push(` <unit ${msgAttrs.join(" ")}>`);
139
147
  const msgNotes = msg.notes ?? [];
140
148
  if (msgNotes.length > 0) {
@@ -142,9 +150,20 @@ function resourceGroupToXliff20(group) {
142
150
  ...renderNotes(msgNotes, `${fileId}-${unitId}`, " ")
143
151
  );
144
152
  }
145
- parts.push(" <segment>");
146
- parts.push(` <source>${escapeXml(msg.value)}</source>`);
147
- parts.push(" </segment>");
153
+ if (pgsExport) {
154
+ pgsExport.segments.forEach((seg, segIdx) => {
155
+ const segId = `${unitId}_s${segIdx + 1}`;
156
+ parts.push(
157
+ ` <segment id="${escapeXml(segId)}" pgs:case="${escapeXml(seg.caseAttr)}">`
158
+ );
159
+ parts.push(` <source>${escapeXml(seg.sourcePattern)}</source>`);
160
+ parts.push(" </segment>");
161
+ });
162
+ } else {
163
+ parts.push(" <segment>");
164
+ parts.push(` <source>${escapeXml(msg.value)}</source>`);
165
+ parts.push(" </segment>");
166
+ }
148
167
  parts.push(" </unit>");
149
168
  });
150
169
  parts.push(" </file>");
@@ -155,7 +174,7 @@ function resourceGroupToXliff20(group) {
155
174
  function serializeResourceGroupsToXliff(groups) {
156
175
  return groups.map((group) => ({
157
176
  project: group.project,
158
- xliff: resourceGroupToXliff20(group)
177
+ xliff: resourceGroupToXliff22(group)
159
178
  }));
160
179
  }
161
180
  async function writeXliffFiles(xliffDir, xliffGroups) {
@@ -215,7 +215,7 @@ var CreateProject = class _CreateProject extends import_core.Command {
215
215
  const projectsDir = (0, import_path3.join)(rootDir, i18nDir, "projects");
216
216
  const translationsDir = (0, import_path3.join)(rootDir, l10nDir, "translations");
217
217
  const relPath = calculateRelativePath(projectsDir, translationsDir);
218
- const isEsm = pkg.type === "module";
218
+ const isEsm = pkg.type === "module" || (0, import_fs3.existsSync)((0, import_path3.join)(rootDir, "tsconfig.json"));
219
219
  const ext = ".js";
220
220
  const outPath = (0, import_path3.join)(projectsDir, `${projectName}${ext}`);
221
221
  if ((0, import_fs3.existsSync)(outPath)) {
@@ -70,7 +70,7 @@ var CreateProject = class _CreateProject extends Command {
70
70
  const projectsDir = join(rootDir, i18nDir, "projects");
71
71
  const translationsDir = join(rootDir, l10nDir, "translations");
72
72
  const relPath = calculateRelativePath(projectsDir, translationsDir);
73
- const isEsm = pkg.type === "module";
73
+ const isEsm = pkg.type === "module" || existsSync(join(rootDir, "tsconfig.json"));
74
74
  const ext = ".js";
75
75
  const outPath = join(projectsDir, `${projectName}${ext}`);
76
76
  if (existsSync(outPath)) {
@@ -320,7 +320,7 @@ var CreateResource = class _CreateResource extends import_core.Command {
320
320
  projectName: projectName.trim(),
321
321
  sourceLocale: projectData.sourceLocale,
322
322
  dir: projectData.dir,
323
- isEsm: pkgInfo.isEsm
323
+ isEsm: pkgInfo.isEsm || pkgInfo.useTypeScript
324
324
  });
325
325
  try {
326
326
  writeMsgResourceFile(outPath, content);
@@ -105,7 +105,7 @@ var CreateResource = class _CreateResource extends Command {
105
105
  projectName: projectName.trim(),
106
106
  sourceLocale: projectData.sourceLocale,
107
107
  dir: projectData.dir,
108
- isEsm: pkgInfo.isEsm
108
+ isEsm: pkgInfo.isEsm || pkgInfo.useTypeScript
109
109
  });
110
110
  try {
111
111
  writeMsgResourceFile(outPath, content);