@worldware/msg-cli 0.1.3 → 0.2.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 (38) hide show
  1. package/README.md +99 -13
  2. package/dist/{chunk-BRZS5LYD.mjs → chunk-6A6JGF7U.mjs} +2 -2
  3. package/dist/chunk-BM3O7ZJW.mjs +176 -0
  4. package/dist/{chunk-AT7DHQF7.mjs → chunk-F7XZRKP7.mjs} +2 -2
  5. package/dist/chunk-KKATA5YE.mjs +324 -0
  6. package/dist/{chunk-T4ENP5TS.mjs → chunk-LNCUPVEF.mjs} +2 -2
  7. package/dist/commands/create/project.cjs +23 -10
  8. package/dist/commands/create/project.mjs +26 -13
  9. package/dist/commands/create/resource.cjs +1 -1
  10. package/dist/commands/create/resource.mjs +2 -2
  11. package/dist/commands/export.cjs +356 -0
  12. package/dist/commands/export.d.mts +16 -0
  13. package/dist/commands/export.d.ts +16 -0
  14. package/dist/commands/export.mjs +91 -0
  15. package/dist/commands/import.cjs +526 -0
  16. package/dist/commands/import.d.mts +17 -0
  17. package/dist/commands/import.d.ts +17 -0
  18. package/dist/commands/import.mjs +116 -0
  19. package/dist/commands/init.cjs +2 -2
  20. package/dist/commands/init.mjs +1 -1
  21. package/dist/lib/create-project-helpers.mjs +3 -3
  22. package/dist/lib/create-resource-helpers.cjs +1 -1
  23. package/dist/lib/create-resource-helpers.mjs +2 -2
  24. package/dist/lib/export-helpers.cjs +229 -0
  25. package/dist/lib/export-helpers.d.mts +55 -0
  26. package/dist/lib/export-helpers.d.ts +55 -0
  27. package/dist/lib/export-helpers.mjs +18 -0
  28. package/dist/lib/import-helpers.cjs +380 -0
  29. package/dist/lib/import-helpers.d.mts +92 -0
  30. package/dist/lib/import-helpers.d.ts +92 -0
  31. package/dist/lib/import-helpers.mjs +24 -0
  32. package/dist/lib/init-helpers.cjs +2 -2
  33. package/dist/lib/init-helpers.mjs +1 -1
  34. package/package.json +2 -2
  35. package/dist/lib/utilities.cjs +0 -203
  36. package/dist/lib/utilities.d.mts +0 -59
  37. package/dist/lib/utilities.d.ts +0 -59
  38. package/dist/lib/utilities.mjs +0 -172
@@ -0,0 +1,356 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/commands/export.ts
21
+ var export_exports = {};
22
+ __export(export_exports, {
23
+ default: () => Export
24
+ });
25
+ module.exports = __toCommonJS(export_exports);
26
+ var import_core = require("@oclif/core");
27
+ var import_fs2 = require("fs");
28
+ var import_path3 = require("path");
29
+
30
+ // src/lib/init-helpers.ts
31
+ var import_fs = require("fs");
32
+ var import_path = require("path");
33
+ function findPackageJsonPath(cwd) {
34
+ let dir = cwd;
35
+ for (; ; ) {
36
+ const p = (0, import_path.join)(dir, "package.json");
37
+ if ((0, import_fs.existsSync)(p)) return p;
38
+ const parent = (0, import_path.dirname)(dir);
39
+ if (parent === dir) return null;
40
+ dir = parent;
41
+ }
42
+ }
43
+ function readPackageJson(pkgPath) {
44
+ const raw = (0, import_fs.readFileSync)(pkgPath, "utf-8");
45
+ try {
46
+ const parsed = JSON.parse(raw);
47
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
48
+ throw new Error("package.json must be a JSON object");
49
+ }
50
+ return parsed;
51
+ } catch (err) {
52
+ if (err instanceof SyntaxError) {
53
+ throw new Error("Invalid package.json: " + err.message);
54
+ }
55
+ throw err;
56
+ }
57
+ }
58
+ function loadPackageJsonForMsg(cwd, options) {
59
+ const pkgPath = findPackageJsonPath(cwd);
60
+ if (!pkgPath) {
61
+ throw new Error("package.json not found. Run this command from the project root.");
62
+ }
63
+ let pkg;
64
+ try {
65
+ pkg = readPackageJson(pkgPath);
66
+ } catch (err) {
67
+ const msg = err instanceof Error ? err.message : "package.json could not be parsed.";
68
+ throw new Error(msg);
69
+ }
70
+ const dirs = pkg.directories;
71
+ if (!dirs || typeof dirs !== "object" || !dirs.i18n) {
72
+ throw new Error("package.json must contain directories.i18n. Run 'msg init' first.");
73
+ }
74
+ if (options?.requireL10n && !dirs.l10n) {
75
+ throw new Error(
76
+ "package.json must contain directories.i18n and directories.l10n. Run 'msg init' first."
77
+ );
78
+ }
79
+ const rootDir = (0, import_path.dirname)(pkgPath);
80
+ const useTypeScript = (0, import_fs.existsSync)((0, import_path.join)(rootDir, "tsconfig.json"));
81
+ const isEsm = pkg.type === "module";
82
+ return {
83
+ pkgPath,
84
+ rootDir,
85
+ pkg,
86
+ i18nDir: dirs.i18n,
87
+ l10nDir: dirs.l10n,
88
+ isEsm,
89
+ useTypeScript
90
+ };
91
+ }
92
+
93
+ // src/lib/export-helpers.ts
94
+ var import_promises = require("fs/promises");
95
+ var import_path2 = require("path");
96
+ var import_url2 = require("url");
97
+
98
+ // src/lib/create-resource-helpers.ts
99
+ var import_module = require("module");
100
+ var import_url = require("url");
101
+ async function dynamicImportFromUrl(url) {
102
+ try {
103
+ return await import(
104
+ /* @vite-ignore */
105
+ url
106
+ );
107
+ } catch (err) {
108
+ const msg = err instanceof Error ? err.message : String(err);
109
+ const useRequire = msg.includes("dynamic import callback") || msg.includes("ERR_VM_DYNAMIC_IMPORT");
110
+ if (useRequire) {
111
+ try {
112
+ const path = url.startsWith("file:") ? (0, import_url.fileURLToPath)(url) : url;
113
+ const base = (0, import_url.pathToFileURL)(process.cwd()).href;
114
+ const req = (0, import_module.createRequire)(base);
115
+ const mod = req(path);
116
+ return Promise.resolve(mod ?? {});
117
+ } catch {
118
+ }
119
+ }
120
+ throw err;
121
+ }
122
+ }
123
+
124
+ // src/lib/export-helpers.ts
125
+ var MSG_PATTERN = /\.msg\.(ts|js)$/i;
126
+ function isMsgResourceLike(value) {
127
+ return Boolean(value) && typeof value.getProject === "function";
128
+ }
129
+ var XLIFF20_NS = "urn:oasis:names:tc:xliff:document:2.0";
130
+ async function findMsgResourceFilePaths(directory) {
131
+ const result = [];
132
+ const entries = await (0, import_promises.readdir)(directory, { withFileTypes: true });
133
+ for (const entry of entries) {
134
+ const fullPath = (0, import_path2.join)(directory, entry.name);
135
+ if (entry.isFile() && MSG_PATTERN.test(entry.name)) {
136
+ result.push(fullPath);
137
+ } else if (entry.isDirectory()) {
138
+ result.push(...await findMsgResourceFilePaths(fullPath));
139
+ }
140
+ }
141
+ return result;
142
+ }
143
+ async function importMsgResourcesFromPaths(filePaths) {
144
+ const result = [];
145
+ for (const filePath of filePaths) {
146
+ if (!MSG_PATTERN.test(filePath)) {
147
+ throw new Error(`File does not have .msg. in filename: ${filePath}`);
148
+ }
149
+ const url = (0, import_url2.pathToFileURL)(filePath).href;
150
+ const mod = await dynamicImportFromUrl(url);
151
+ const resource = mod.default ?? mod.resource ?? mod.MsgResource;
152
+ if (!isMsgResourceLike(resource)) {
153
+ throw new Error(
154
+ `Failed to import MsgResource from ${filePath}: no valid export found`
155
+ );
156
+ }
157
+ result.push(resource);
158
+ }
159
+ return result;
160
+ }
161
+ function groupResourcesByProject(resources) {
162
+ const byProject = /* @__PURE__ */ new Map();
163
+ for (const resource of resources) {
164
+ const projectName = resource.getProject().project.name;
165
+ let arr = byProject.get(projectName);
166
+ if (!arr) {
167
+ arr = [];
168
+ byProject.set(projectName, arr);
169
+ }
170
+ arr.push(resource);
171
+ }
172
+ return Array.from(byProject.entries(), ([project, resources2]) => ({
173
+ project,
174
+ resources: resources2
175
+ }));
176
+ }
177
+ function filterResourceGroupsByProject(groups, projectName) {
178
+ return groups.filter((g) => g.project === projectName);
179
+ }
180
+ function escapeXml(s) {
181
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
182
+ }
183
+ function sanitizeForXmlId(s) {
184
+ const sanitized = s.replace(/[^a-zA-Z0-9._:-]/g, "_").replace(/_+/g, "_");
185
+ if (/^[0-9]/.test(sanitized) || sanitized === "") {
186
+ return `k${sanitized}`;
187
+ }
188
+ return sanitized;
189
+ }
190
+ function noteTypeToCategory(type) {
191
+ const lower = type.toLowerCase();
192
+ if (lower.startsWith("x-")) return lower;
193
+ return ["description", "authorship", "parameters", "context", "comment"].includes(
194
+ lower
195
+ ) ? lower : `x-${lower}`;
196
+ }
197
+ function renderNotes(notes, idPrefix, indent = " ") {
198
+ const parts = [];
199
+ if (notes.length === 0) return parts;
200
+ const noteIndent = indent + " ";
201
+ parts.push(`${indent}<notes>`);
202
+ notes.forEach((n, i) => {
203
+ const cat = noteTypeToCategory(n.type);
204
+ const id = `${idPrefix}-n${i + 1}`;
205
+ parts.push(
206
+ `${noteIndent}<note id="${escapeXml(id)}" category="${escapeXml(cat)}">${escapeXml(n.content)}</note>`
207
+ );
208
+ });
209
+ parts.push(`${indent}</notes>`);
210
+ return parts;
211
+ }
212
+ function resourceGroupToXliff20(group) {
213
+ const srcLang = group.resources[0]?.attributes?.lang ?? "en";
214
+ const parts = [
215
+ '<?xml version="1.0" encoding="UTF-8"?>',
216
+ `<xliff xmlns="${XLIFF20_NS}" version="2.0" srcLang="${escapeXml(srcLang)}">`
217
+ ];
218
+ let fileIndex = 0;
219
+ for (const resource of group.resources) {
220
+ const orig = `${resource.title}.json`;
221
+ fileIndex += 1;
222
+ const fileId = `f${fileIndex}`;
223
+ const attrs = resource.attributes ?? {};
224
+ const fileAttrs = [
225
+ `id="${fileId}"`,
226
+ `original="${escapeXml(orig)}"`
227
+ ];
228
+ if (attrs.dir) {
229
+ fileAttrs.push(`srcDir="${escapeXml(attrs.dir)}"`);
230
+ }
231
+ if (attrs.dnt === true) {
232
+ fileAttrs.push('translate="no"');
233
+ }
234
+ parts.push(` <file ${fileAttrs.join(" ")}>`);
235
+ const data = resource.getData(false);
236
+ const resourceNotes = data.notes ?? [];
237
+ if (resourceNotes.length > 0) {
238
+ parts.push(...renderNotes(resourceNotes, fileId, " "));
239
+ }
240
+ const messages = data.messages ?? [];
241
+ messages.forEach((msg, idx) => {
242
+ const unitId = sanitizeForXmlId(msg.key) || `u${fileIndex}-${idx + 1}`;
243
+ const msgAttrs = [`id="${escapeXml(unitId)}"`];
244
+ if (msg.key) {
245
+ msgAttrs.push(`name="${escapeXml(msg.key)}"`);
246
+ }
247
+ const msgAttr = msg.attributes;
248
+ if (msgAttr?.dnt === true) {
249
+ msgAttrs.push('translate="no"');
250
+ }
251
+ if (msgAttr?.dir) {
252
+ msgAttrs.push(`srcDir="${escapeXml(msgAttr.dir)}"`);
253
+ }
254
+ parts.push(` <unit ${msgAttrs.join(" ")}>`);
255
+ const msgNotes = msg.notes ?? [];
256
+ if (msgNotes.length > 0) {
257
+ parts.push(
258
+ ...renderNotes(msgNotes, `${fileId}-${unitId}`, " ")
259
+ );
260
+ }
261
+ parts.push(" <segment>");
262
+ parts.push(` <source>${escapeXml(msg.value)}</source>`);
263
+ parts.push(" </segment>");
264
+ parts.push(" </unit>");
265
+ });
266
+ parts.push(" </file>");
267
+ }
268
+ parts.push("</xliff>");
269
+ return parts.join("\n");
270
+ }
271
+ function serializeResourceGroupsToXliff(groups) {
272
+ return groups.map((group) => ({
273
+ project: group.project,
274
+ xliff: resourceGroupToXliff20(group)
275
+ }));
276
+ }
277
+ async function writeXliffFiles(xliffDir, xliffGroups) {
278
+ await (0, import_promises.mkdir)(xliffDir, { recursive: true });
279
+ for (const { project, xliff } of xliffGroups) {
280
+ const filePath = (0, import_path2.join)(xliffDir, `${project}.xliff`);
281
+ await (0, import_promises.writeFile)(filePath, xliff, "utf-8");
282
+ }
283
+ }
284
+
285
+ // src/commands/export.ts
286
+ var Export = class _Export extends import_core.Command {
287
+ static description = "Serialize msg resources in i18n/resources to XLIFF 2.0 files in l10n/xliff (per project)";
288
+ static flags = {
289
+ help: import_core.Flags.help({ char: "h" }),
290
+ project: import_core.Flags.string({
291
+ char: "p",
292
+ description: "Filter the export to just the single named project"
293
+ })
294
+ };
295
+ async run() {
296
+ const { flags } = await this.parse(_Export);
297
+ const cwd = process.cwd();
298
+ let ctx;
299
+ try {
300
+ ctx = loadPackageJsonForMsg(cwd, { requireL10n: true });
301
+ } catch (err) {
302
+ const msg = err instanceof Error ? err.message : String(err);
303
+ this.error(msg, { exit: 1 });
304
+ }
305
+ const resourcesDir = (0, import_path3.join)(ctx.rootDir, ctx.i18nDir, "resources");
306
+ const xliffDir = (0, import_path3.join)(ctx.rootDir, ctx.l10nDir ?? "l10n", "xliff");
307
+ if (!(0, import_fs2.existsSync)(resourcesDir)) {
308
+ this.warn(
309
+ `i18n/resources directory does not exist at ${resourcesDir}. Run 'msg init' first.`
310
+ );
311
+ return;
312
+ }
313
+ this.log("Finding MsgResource files...");
314
+ let filePaths;
315
+ try {
316
+ filePaths = await findMsgResourceFilePaths(resourcesDir);
317
+ } catch (err) {
318
+ const msg = err instanceof Error ? err.message : String(err);
319
+ this.error(`Could not read resources directory: ${msg}`, { exit: 1 });
320
+ }
321
+ if (filePaths.length === 0) {
322
+ this.log("No MsgResource files found. Nothing to export.");
323
+ return;
324
+ }
325
+ this.log(`Found ${filePaths.length} MsgResource file(s). Importing...`);
326
+ let resources;
327
+ try {
328
+ resources = await importMsgResourcesFromPaths(filePaths);
329
+ } catch (err) {
330
+ const msg = err instanceof Error ? err.message : String(err);
331
+ this.error(msg, { exit: 1 });
332
+ }
333
+ let groups = groupResourcesByProject(resources);
334
+ this.log(`Grouped into ${groups.length} project(s).`);
335
+ if (flags.project) {
336
+ groups = filterResourceGroupsByProject(groups, flags.project);
337
+ if (groups.length === 0) {
338
+ this.log(`No resources found for project '${flags.project}'. Nothing to export.`);
339
+ return;
340
+ }
341
+ this.log(`Filtered to project '${flags.project}'.`);
342
+ }
343
+ this.log("Serializing to XLIFF 2.0...");
344
+ const xliffGroups = serializeResourceGroupsToXliff(groups);
345
+ this.log(`Writing ${xliffGroups.length} XLIFF file(s) to ${xliffDir}...`);
346
+ try {
347
+ await writeXliffFiles(xliffDir, xliffGroups);
348
+ } catch (err) {
349
+ const msg = err instanceof Error ? err.message : String(err);
350
+ this.error(`Could not write XLIFF files: ${msg}`, { exit: 1 });
351
+ }
352
+ for (const { project } of xliffGroups) {
353
+ this.log(` Wrote ${project}.xliff`);
354
+ }
355
+ }
356
+ };
@@ -0,0 +1,16 @@
1
+ import * as _oclif_core_lib_interfaces_parser_js from '@oclif/core/lib/interfaces/parser.js';
2
+ import { Command } from '@oclif/core';
3
+
4
+ /**
5
+ * Serializes MsgResource objects to XLIFF 2.0 files in l10n/xliff on a per-project basis.
6
+ */
7
+ declare class Export extends Command {
8
+ static description: string;
9
+ static flags: {
10
+ help: _oclif_core_lib_interfaces_parser_js.BooleanFlag<void>;
11
+ project: _oclif_core_lib_interfaces_parser_js.OptionFlag<string | undefined, _oclif_core_lib_interfaces_parser_js.CustomOptions>;
12
+ };
13
+ run(): Promise<void>;
14
+ }
15
+
16
+ export { Export as default };
@@ -0,0 +1,16 @@
1
+ import * as _oclif_core_lib_interfaces_parser_js from '@oclif/core/lib/interfaces/parser.js';
2
+ import { Command } from '@oclif/core';
3
+
4
+ /**
5
+ * Serializes MsgResource objects to XLIFF 2.0 files in l10n/xliff on a per-project basis.
6
+ */
7
+ declare class Export extends Command {
8
+ static description: string;
9
+ static flags: {
10
+ help: _oclif_core_lib_interfaces_parser_js.BooleanFlag<void>;
11
+ project: _oclif_core_lib_interfaces_parser_js.OptionFlag<string | undefined, _oclif_core_lib_interfaces_parser_js.CustomOptions>;
12
+ };
13
+ run(): Promise<void>;
14
+ }
15
+
16
+ export { Export as default };
@@ -0,0 +1,91 @@
1
+ import {
2
+ filterResourceGroupsByProject,
3
+ findMsgResourceFilePaths,
4
+ groupResourcesByProject,
5
+ importMsgResourcesFromPaths,
6
+ serializeResourceGroupsToXliff,
7
+ writeXliffFiles
8
+ } from "../chunk-BM3O7ZJW.mjs";
9
+ import "../chunk-LNCUPVEF.mjs";
10
+ import {
11
+ loadPackageJsonForMsg
12
+ } from "../chunk-F7XZRKP7.mjs";
13
+
14
+ // src/commands/export.ts
15
+ import { Command, Flags } from "@oclif/core";
16
+ import { existsSync } from "fs";
17
+ import { join } from "path";
18
+ var Export = class _Export extends Command {
19
+ static description = "Serialize msg resources in i18n/resources to XLIFF 2.0 files in l10n/xliff (per project)";
20
+ static flags = {
21
+ help: Flags.help({ char: "h" }),
22
+ project: Flags.string({
23
+ char: "p",
24
+ description: "Filter the export to just the single named project"
25
+ })
26
+ };
27
+ async run() {
28
+ const { flags } = await this.parse(_Export);
29
+ const cwd = process.cwd();
30
+ let ctx;
31
+ try {
32
+ ctx = loadPackageJsonForMsg(cwd, { requireL10n: true });
33
+ } catch (err) {
34
+ const msg = err instanceof Error ? err.message : String(err);
35
+ this.error(msg, { exit: 1 });
36
+ }
37
+ const resourcesDir = join(ctx.rootDir, ctx.i18nDir, "resources");
38
+ const xliffDir = join(ctx.rootDir, ctx.l10nDir ?? "l10n", "xliff");
39
+ if (!existsSync(resourcesDir)) {
40
+ this.warn(
41
+ `i18n/resources directory does not exist at ${resourcesDir}. Run 'msg init' first.`
42
+ );
43
+ return;
44
+ }
45
+ this.log("Finding MsgResource files...");
46
+ let filePaths;
47
+ try {
48
+ filePaths = await findMsgResourceFilePaths(resourcesDir);
49
+ } catch (err) {
50
+ const msg = err instanceof Error ? err.message : String(err);
51
+ this.error(`Could not read resources directory: ${msg}`, { exit: 1 });
52
+ }
53
+ if (filePaths.length === 0) {
54
+ this.log("No MsgResource files found. Nothing to export.");
55
+ return;
56
+ }
57
+ this.log(`Found ${filePaths.length} MsgResource file(s). Importing...`);
58
+ let resources;
59
+ try {
60
+ resources = await importMsgResourcesFromPaths(filePaths);
61
+ } catch (err) {
62
+ const msg = err instanceof Error ? err.message : String(err);
63
+ this.error(msg, { exit: 1 });
64
+ }
65
+ let groups = groupResourcesByProject(resources);
66
+ this.log(`Grouped into ${groups.length} project(s).`);
67
+ if (flags.project) {
68
+ groups = filterResourceGroupsByProject(groups, flags.project);
69
+ if (groups.length === 0) {
70
+ this.log(`No resources found for project '${flags.project}'. Nothing to export.`);
71
+ return;
72
+ }
73
+ this.log(`Filtered to project '${flags.project}'.`);
74
+ }
75
+ this.log("Serializing to XLIFF 2.0...");
76
+ const xliffGroups = serializeResourceGroupsToXliff(groups);
77
+ this.log(`Writing ${xliffGroups.length} XLIFF file(s) to ${xliffDir}...`);
78
+ try {
79
+ await writeXliffFiles(xliffDir, xliffGroups);
80
+ } catch (err) {
81
+ const msg = err instanceof Error ? err.message : String(err);
82
+ this.error(`Could not write XLIFF files: ${msg}`, { exit: 1 });
83
+ }
84
+ for (const { project } of xliffGroups) {
85
+ this.log(` Wrote ${project}.xliff`);
86
+ }
87
+ }
88
+ };
89
+ export {
90
+ Export as default
91
+ };