@intlayer/sync-po-plugin 9.0.0-canary.13 → 9.0.0-canary.14
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/dist/cjs/index.cjs +12 -4
- package/dist/cjs/loadPO.cjs +20 -99
- package/dist/cjs/loadPO.cjs.map +1 -1
- package/dist/cjs/poFormat.cjs +86 -0
- package/dist/cjs/poFormat.cjs.map +1 -0
- package/dist/cjs/syncPO.cjs +25 -241
- package/dist/cjs/syncPO.cjs.map +1 -1
- package/dist/esm/index.mjs +3 -2
- package/dist/esm/loadPO.mjs +20 -97
- package/dist/esm/loadPO.mjs.map +1 -1
- package/dist/esm/poFormat.mjs +82 -0
- package/dist/esm/poFormat.mjs.map +1 -0
- package/dist/esm/syncPO.mjs +17 -236
- package/dist/esm/syncPO.mjs.map +1 -1
- package/dist/types/index.d.ts +4 -3
- package/dist/types/loadPO.d.ts +5 -1
- package/dist/types/loadPO.d.ts.map +1 -1
- package/dist/types/poFormat.d.ts +21 -0
- package/dist/types/poFormat.d.ts.map +1 -0
- package/dist/types/syncPO.d.ts +7 -16
- package/dist/types/syncPO.d.ts.map +1 -1
- package/package.json +5 -5
package/dist/esm/loadPO.mjs
CHANGED
|
@@ -1,102 +1,25 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { isAbsolute, relative, resolve } from "node:path";
|
|
4
|
-
import { colorizePath, getAppLogger } from "@intlayer/config/logger";
|
|
5
|
-
import { parseFilePathPattern } from "@intlayer/config/utils";
|
|
6
|
-
import fg from "fast-glob";
|
|
1
|
+
import { poCodec } from "./poFormat.mjs";
|
|
2
|
+
import { createFileAdapter, createSyncPlugin } from "@intlayer/engine/syncPluginKit";
|
|
7
3
|
|
|
8
4
|
//#region src/loadPO.ts
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
const hasKeyInMask = maskPatternLocale.includes("{{__KEY__}}");
|
|
28
|
-
let key;
|
|
29
|
-
let extractedLocale;
|
|
30
|
-
if (hasLocaleInMask || hasKeyInMask) {
|
|
31
|
-
const extraction = extractKeyAndLocaleFromPath(file, maskPatternLocale, locales, locale);
|
|
32
|
-
if (!extraction) continue;
|
|
33
|
-
key = extraction.key;
|
|
34
|
-
extractedLocale = extraction.locale;
|
|
35
|
-
} else {
|
|
36
|
-
key = "index";
|
|
37
|
-
extractedLocale = locale;
|
|
38
|
-
}
|
|
39
|
-
const absolutePath = isAbsolute(file) ? file : resolve(baseDir, file);
|
|
40
|
-
const usedLocale = extractedLocale;
|
|
41
|
-
if (!result[usedLocale]) result[usedLocale] = {};
|
|
42
|
-
result[usedLocale][key] = absolutePath;
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
return result;
|
|
46
|
-
};
|
|
47
|
-
const loadMessagePathMap = async (source, configuration) => {
|
|
48
|
-
const messages = await listMessages(source, configuration);
|
|
49
|
-
return Object.entries(messages).flatMap(([locale, keysRecord]) => Object.entries(keysRecord).map(([key, path]) => {
|
|
50
|
-
return {
|
|
51
|
-
path: isAbsolute(path) ? path : resolve(configuration.system.baseDir, path),
|
|
52
|
-
locale,
|
|
53
|
-
key
|
|
54
|
-
};
|
|
55
|
-
}));
|
|
56
|
-
};
|
|
57
|
-
const loadPO = (options) => {
|
|
58
|
-
const { location, priority, locale } = {
|
|
59
|
-
location: "plugin",
|
|
60
|
-
priority: 0,
|
|
61
|
-
...options
|
|
62
|
-
};
|
|
63
|
-
return {
|
|
64
|
-
name: "load-po",
|
|
65
|
-
loadDictionaries: async ({ configuration }) => {
|
|
66
|
-
const appLogger = getAppLogger(configuration);
|
|
67
|
-
const dictionariesMap = await loadMessagePathMap(options.source, configuration);
|
|
68
|
-
if (dictionariesMap.length === 0) appLogger(`No dictionaries found at locations matching source pattern: ${colorizePath(await parseFilePathPattern(options.source, {
|
|
69
|
-
key: "{{key}}",
|
|
70
|
-
locale: "{{locale}}"
|
|
71
|
-
}))}`, { level: "warn" });
|
|
72
|
-
const dictionaries = [];
|
|
73
|
-
for (const { path, key, locale: entryLocale } of dictionariesMap) {
|
|
74
|
-
let poContent;
|
|
75
|
-
try {
|
|
76
|
-
poContent = parsePO(await readFile(path, "utf-8"));
|
|
77
|
-
} catch {
|
|
78
|
-
poContent = {};
|
|
79
|
-
}
|
|
80
|
-
const filePath = relative(configuration.system.baseDir, path);
|
|
81
|
-
const entryUsedLocale = locale ?? entryLocale;
|
|
82
|
-
const dictionary = {
|
|
83
|
-
key,
|
|
84
|
-
locale: entryUsedLocale,
|
|
85
|
-
fill: filePath,
|
|
86
|
-
format: "po",
|
|
87
|
-
localId: `${key}::${location}::${filePath}`,
|
|
88
|
-
location,
|
|
89
|
-
filled: entryUsedLocale !== configuration.internationalization.defaultLocale ? true : void 0,
|
|
90
|
-
content: poContent,
|
|
91
|
-
filePath,
|
|
92
|
-
priority
|
|
93
|
-
};
|
|
94
|
-
dictionaries.push(dictionary);
|
|
95
|
-
}
|
|
96
|
-
return dictionaries;
|
|
97
|
-
}
|
|
98
|
-
};
|
|
99
|
-
};
|
|
5
|
+
/**
|
|
6
|
+
* Read-only PO ingestion plugin: loads gettext PO files as dictionaries
|
|
7
|
+
* without ever writing back to them.
|
|
8
|
+
*/
|
|
9
|
+
const loadPO = (options) => createSyncPlugin({
|
|
10
|
+
name: "load-po",
|
|
11
|
+
adapter: createFileAdapter({
|
|
12
|
+
source: options.source,
|
|
13
|
+
codec: poCodec,
|
|
14
|
+
discovery: "inclusive"
|
|
15
|
+
}),
|
|
16
|
+
direction: "pull",
|
|
17
|
+
location: options.location ?? "plugin",
|
|
18
|
+
priority: options.priority ?? 0,
|
|
19
|
+
format: "po",
|
|
20
|
+
splitKeys: false,
|
|
21
|
+
localeOverride: options.locale
|
|
22
|
+
});
|
|
100
23
|
|
|
101
24
|
//#endregion
|
|
102
25
|
export { loadPO };
|
package/dist/esm/loadPO.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loadPO.mjs","names":[
|
|
1
|
+
{"version":3,"file":"loadPO.mjs","names":[],"sources":["../../src/loadPO.ts"],"sourcesContent":["import {\n createFileAdapter,\n createSyncPlugin,\n} from '@intlayer/engine/syncPluginKit';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { FilePathPattern } from '@intlayer/types/filePathPattern';\nimport type { Plugin } from '@intlayer/types/plugin';\nimport { poCodec } from './poFormat';\n\nexport type LoadPOPluginOptions = {\n /**\n * The source of the plugin.\n * Is a function to build the source from the key and locale.\n *\n * @example\n * ```ts\n * loadPO({\n * source: ({ key }) => `blog/${'**'}/${key}.i18n.po`,\n * })\n * ```\n */\n source: FilePathPattern;\n\n /**\n * Locale\n *\n * If not provided, the plugin will consider the default locale.\n *\n * @example\n * ```ts\n * loadPO({\n * source: ({ key }) => `blog/${'**'}/${key}.i18n.po`,\n * locale: Locales.ENGLISH,\n * })\n * ```\n */\n locale?: Locale;\n\n /**\n * Because Intlayer transforms PO files into Dictionary, we need to identify the plugin in the dictionary.\n * Used to identify the plugin in the dictionary.\n *\n * In the case you have multiple plugins, you can use this to identify the plugin in the dictionary.\n *\n * @example\n * ```ts\n * const config = {\n * plugins: [\n * loadPO({\n * source: ({ key }) => `./resources/${key}.po`,\n * location: 'plugin-i18next-po',\n * }),\n * ]\n * }\n * ```\n */\n location?: string;\n\n /**\n * The priority of the dictionaries created by the plugin.\n *\n * In the case of conflicts with remote dictionaries, or .content files, the dictionary with the highest priority will override the other dictionaries.\n *\n * Default is 0.\n */\n priority?: number;\n};\n\n/**\n * Read-only PO ingestion plugin: loads gettext PO files as dictionaries\n * without ever writing back to them.\n */\nexport const loadPO = (options: LoadPOPluginOptions): Plugin =>\n createSyncPlugin({\n name: 'load-po',\n adapter: createFileAdapter({\n source: options.source,\n codec: poCodec,\n discovery: 'inclusive',\n }),\n direction: 'pull',\n location: options.location ?? 'plugin',\n priority: options.priority ?? 0,\n format: 'po',\n // PO files are flat msgid → msgstr records; never split on first level.\n splitKeys: false,\n localeOverride: options.locale,\n });\n"],"mappings":";;;;;;;;AAwEA,MAAa,UAAU,YACrB,iBAAiB;CACf,MAAM;CACN,SAAS,kBAAkB;EACzB,QAAQ,QAAQ;EAChB,OAAO;EACP,WAAW;EACZ,CAAC;CACF,WAAW;CACX,UAAU,QAAQ,YAAY;CAC9B,UAAU,QAAQ,YAAY;CAC9B,QAAQ;CAER,WAAW;CACX,gBAAgB,QAAQ;CACzB,CAAC"}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
//#region src/poFormat.ts
|
|
2
|
+
const unescapePO = (str) => str.replace(/\\n/g, "\n").replace(/\\t/g, " ").replace(/\\r/g, "\r").replace(/\\"/g, "\"").replace(/\\\\/g, "\\");
|
|
3
|
+
const escapePO = (str) => str.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\r/g, "\\r");
|
|
4
|
+
/**
|
|
5
|
+
* Parse a PO file string into a flat msgid → msgstr record.
|
|
6
|
+
* Skips the PO header (msgid ""), comment lines, and plural/context keywords.
|
|
7
|
+
*/
|
|
8
|
+
const parsePO = (fileContent) => {
|
|
9
|
+
const result = {};
|
|
10
|
+
const lines = fileContent.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
|
|
11
|
+
let msgid = "";
|
|
12
|
+
let msgstr = "";
|
|
13
|
+
let currentField = null;
|
|
14
|
+
const finalize = () => {
|
|
15
|
+
if (msgid !== "") result[msgid] = msgstr;
|
|
16
|
+
msgid = "";
|
|
17
|
+
msgstr = "";
|
|
18
|
+
currentField = null;
|
|
19
|
+
};
|
|
20
|
+
for (const line of lines) {
|
|
21
|
+
if (line.startsWith("#")) continue;
|
|
22
|
+
if (line.trim() === "") {
|
|
23
|
+
finalize();
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
const msgidMatch = line.match(/^msgid\s+"((?:[^"\\]|\\.)*)"$/);
|
|
27
|
+
if (msgidMatch?.[1]) {
|
|
28
|
+
finalize();
|
|
29
|
+
msgid = unescapePO(msgidMatch[1]);
|
|
30
|
+
currentField = "msgid";
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
const msgstrMatch = line.match(/^msgstr\s+"((?:[^"\\]|\\.)*)"$/);
|
|
34
|
+
if (msgstrMatch?.[1]) {
|
|
35
|
+
msgstr = unescapePO(msgstrMatch[1]);
|
|
36
|
+
currentField = "msgstr";
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
const contMatch = line.match(/^"((?:[^"\\]|\\.)*)"$/);
|
|
40
|
+
if (contMatch?.[1]) {
|
|
41
|
+
if (currentField === "msgid") msgid += unescapePO(contMatch[1]);
|
|
42
|
+
else if (currentField === "msgstr") msgstr += unescapePO(contMatch[1]);
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
currentField = null;
|
|
46
|
+
}
|
|
47
|
+
finalize();
|
|
48
|
+
return result;
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Serialize a flat key → value record to PO file format.
|
|
52
|
+
* Non-string values are silently skipped.
|
|
53
|
+
*/
|
|
54
|
+
const serializePO = (content, locale) => {
|
|
55
|
+
const lines = [];
|
|
56
|
+
lines.push("msgid \"\"");
|
|
57
|
+
lines.push("msgstr \"\"");
|
|
58
|
+
lines.push("\"Content-Type: text/plain; charset=UTF-8\\n\"");
|
|
59
|
+
lines.push("\"Content-Transfer-Encoding: 8bit\\n\"");
|
|
60
|
+
if (locale) lines.push(`"Language: ${locale}\\n"`);
|
|
61
|
+
lines.push("\"MIME-Version: 1.0\\n\"");
|
|
62
|
+
lines.push("");
|
|
63
|
+
for (const [msgid, msgstr] of Object.entries(content)) {
|
|
64
|
+
if (typeof msgstr !== "string") continue;
|
|
65
|
+
lines.push(`msgid "${escapePO(msgid)}"`);
|
|
66
|
+
lines.push(`msgstr "${escapePO(msgstr)}"`);
|
|
67
|
+
lines.push("");
|
|
68
|
+
}
|
|
69
|
+
return `${lines.join("\n")}\n`;
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* PO payload codec bridging {@link parsePO} / {@link serializePO} to the
|
|
73
|
+
* sync-plugin kit.
|
|
74
|
+
*/
|
|
75
|
+
const poCodec = {
|
|
76
|
+
parse: parsePO,
|
|
77
|
+
serialize: (content, { locale }) => serializePO(content, locale)
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
//#endregion
|
|
81
|
+
export { parsePO, poCodec, serializePO };
|
|
82
|
+
//# sourceMappingURL=poFormat.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"poFormat.mjs","names":[],"sources":["../../src/poFormat.ts"],"sourcesContent":["import type { FormatCodec } from '@intlayer/engine/syncPluginKit';\n\nconst unescapePO = (str: string): string =>\n str\n .replace(/\\\\n/g, '\\n')\n .replace(/\\\\t/g, '\\t')\n .replace(/\\\\r/g, '\\r')\n .replace(/\\\\\"/g, '\"')\n .replace(/\\\\\\\\/g, '\\\\');\n\nconst escapePO = (str: string): string =>\n str\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\t/g, '\\\\t')\n .replace(/\\r/g, '\\\\r');\n\n/**\n * Parse a PO file string into a flat msgid → msgstr record.\n * Skips the PO header (msgid \"\"), comment lines, and plural/context keywords.\n */\nexport const parsePO = (fileContent: string): Record<string, string> => {\n const result: Record<string, string> = {};\n const lines = fileContent\n .replace(/\\r\\n/g, '\\n')\n .replace(/\\r/g, '\\n')\n .split('\\n');\n\n let msgid = '';\n let msgstr = '';\n let currentField: 'msgid' | 'msgstr' | null = null;\n\n const finalize = () => {\n if (msgid !== '') {\n result[msgid] = msgstr;\n }\n msgid = '';\n msgstr = '';\n currentField = null;\n };\n\n for (const line of lines) {\n // Skip all comment types (#, #., #:, #,, #|)\n if (line.startsWith('#')) continue;\n\n if (line.trim() === '') {\n finalize();\n continue;\n }\n\n const msgidMatch = line.match(/^msgid\\s+\"((?:[^\"\\\\]|\\\\.)*)\"$/);\n if (msgidMatch?.[1]) {\n // Starting a new entry — finalize the previous one first\n finalize();\n msgid = unescapePO(msgidMatch[1]);\n currentField = 'msgid';\n continue;\n }\n\n const msgstrMatch = line.match(/^msgstr\\s+\"((?:[^\"\\\\]|\\\\.)*)\"$/);\n if (msgstrMatch?.[1]) {\n msgstr = unescapePO(msgstrMatch[1]);\n currentField = 'msgstr';\n continue;\n }\n\n // Continuation line: `\"...\"` appends to the current keyword's value\n const contMatch = line.match(/^\"((?:[^\"\\\\]|\\\\.)*)\"$/);\n if (contMatch?.[1]) {\n if (currentField === 'msgid') {\n msgid += unescapePO(contMatch[1]);\n } else if (currentField === 'msgstr') {\n msgstr += unescapePO(contMatch[1]);\n }\n continue;\n }\n\n // Other keywords (msgid_plural, msgstr[n], msgctxt) — not supported; reset field\n currentField = null;\n }\n\n // Finalize the last entry in the file (no trailing blank line needed)\n finalize();\n\n return result;\n};\n\n/**\n * Serialize a flat key → value record to PO file format.\n * Non-string values are silently skipped.\n */\nexport const serializePO = (\n content: Record<string, unknown>,\n locale?: string\n): string => {\n const lines: string[] = [];\n\n // PO header entry\n lines.push('msgid \"\"');\n lines.push('msgstr \"\"');\n lines.push('\"Content-Type: text/plain; charset=UTF-8\\\\n\"');\n lines.push('\"Content-Transfer-Encoding: 8bit\\\\n\"');\n if (locale) {\n lines.push(`\"Language: ${locale}\\\\n\"`);\n }\n lines.push('\"MIME-Version: 1.0\\\\n\"');\n lines.push('');\n\n for (const [msgid, msgstr] of Object.entries(content)) {\n if (typeof msgstr !== 'string') continue;\n\n lines.push(`msgid \"${escapePO(msgid)}\"`);\n lines.push(`msgstr \"${escapePO(msgstr)}\"`);\n lines.push('');\n }\n\n return `${lines.join('\\n')}\\n`;\n};\n\n/**\n * PO payload codec bridging {@link parsePO} / {@link serializePO} to the\n * sync-plugin kit.\n */\nexport const poCodec: FormatCodec = {\n parse: parsePO,\n serialize: (content, { locale }) => serializePO(content, locale),\n};\n"],"mappings":";AAEA,MAAM,cAAc,QAClB,IACG,QAAQ,QAAQ,KAAK,CACrB,QAAQ,QAAQ,IAAK,CACrB,QAAQ,QAAQ,KAAK,CACrB,QAAQ,QAAQ,KAAI,CACpB,QAAQ,SAAS,KAAK;AAE3B,MAAM,YAAY,QAChB,IACG,QAAQ,OAAO,OAAO,CACtB,QAAQ,MAAM,OAAM,CACpB,QAAQ,OAAO,MAAM,CACrB,QAAQ,OAAO,MAAM,CACrB,QAAQ,OAAO,MAAM;;;;;AAM1B,MAAa,WAAW,gBAAgD;CACtE,MAAM,SAAiC,EAAE;CACzC,MAAM,QAAQ,YACX,QAAQ,SAAS,KAAK,CACtB,QAAQ,OAAO,KAAK,CACpB,MAAM,KAAK;CAEd,IAAI,QAAQ;CACZ,IAAI,SAAS;CACb,IAAI,eAA0C;CAE9C,MAAM,iBAAiB;AACrB,MAAI,UAAU,GACZ,QAAO,SAAS;AAElB,UAAQ;AACR,WAAS;AACT,iBAAe;;AAGjB,MAAK,MAAM,QAAQ,OAAO;AAExB,MAAI,KAAK,WAAW,IAAI,CAAE;AAE1B,MAAI,KAAK,MAAM,KAAK,IAAI;AACtB,aAAU;AACV;;EAGF,MAAM,aAAa,KAAK,MAAM,gCAAgC;AAC9D,MAAI,aAAa,IAAI;AAEnB,aAAU;AACV,WAAQ,WAAW,WAAW,GAAG;AACjC,kBAAe;AACf;;EAGF,MAAM,cAAc,KAAK,MAAM,iCAAiC;AAChE,MAAI,cAAc,IAAI;AACpB,YAAS,WAAW,YAAY,GAAG;AACnC,kBAAe;AACf;;EAIF,MAAM,YAAY,KAAK,MAAM,wBAAwB;AACrD,MAAI,YAAY,IAAI;AAClB,OAAI,iBAAiB,QACnB,UAAS,WAAW,UAAU,GAAG;YACxB,iBAAiB,SAC1B,WAAU,WAAW,UAAU,GAAG;AAEpC;;AAIF,iBAAe;;AAIjB,WAAU;AAEV,QAAO;;;;;;AAOT,MAAa,eACX,SACA,WACW;CACX,MAAM,QAAkB,EAAE;AAG1B,OAAM,KAAK,aAAW;AACtB,OAAM,KAAK,cAAY;AACvB,OAAM,KAAK,iDAA+C;AAC1D,OAAM,KAAK,yCAAuC;AAClD,KAAI,OACF,OAAM,KAAK,cAAc,OAAO,MAAM;AAExC,OAAM,KAAK,2BAAyB;AACpC,OAAM,KAAK,GAAG;AAEd,MAAK,MAAM,CAAC,OAAO,WAAW,OAAO,QAAQ,QAAQ,EAAE;AACrD,MAAI,OAAO,WAAW,SAAU;AAEhC,QAAM,KAAK,UAAU,SAAS,MAAM,CAAC,GAAG;AACxC,QAAM,KAAK,WAAW,SAAS,OAAO,CAAC,GAAG;AAC1C,QAAM,KAAK,GAAG;;AAGhB,QAAO,GAAG,MAAM,KAAK,KAAK,CAAC;;;;;;AAO7B,MAAa,UAAuB;CAClC,OAAO;CACP,YAAY,SAAS,EAAE,aAAa,YAAY,SAAS,OAAO;CACjE"}
|
package/dist/esm/syncPO.mjs
CHANGED
|
@@ -1,246 +1,27 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { colorizePath, getAppLogger } from "@intlayer/config/logger";
|
|
1
|
+
import { parsePO, poCodec, serializePO } from "./poFormat.mjs";
|
|
2
|
+
import { buildFilePathPatternContext, createFileAdapter, createSyncPlugin, extractKeyAndLocaleFromPath } from "@intlayer/engine/syncPluginKit";
|
|
4
3
|
import { parseFilePathPattern } from "@intlayer/config/utils";
|
|
5
|
-
import fg from "fast-glob";
|
|
6
4
|
|
|
7
5
|
//#region src/syncPO.ts
|
|
8
|
-
const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
9
|
-
const extractKeyAndLocaleFromPath = (filePath, maskPattern, locales, defaultLocale) => {
|
|
10
|
-
const keyPlaceholder = "{{__KEY__}}";
|
|
11
|
-
const localePlaceholder = "{{__LOCALE__}}";
|
|
12
|
-
const normalize = (path) => path.startsWith("./") ? path.slice(2) : path;
|
|
13
|
-
const normalizedFilePath = normalize(filePath);
|
|
14
|
-
const normalizedMask = normalize(maskPattern);
|
|
15
|
-
const localesAlternation = locales.join("|");
|
|
16
|
-
let regexStr = `^${escapeRegex(normalizedMask)}$`;
|
|
17
|
-
regexStr = regexStr.replace(/\\\*\\\*/g, ".*");
|
|
18
|
-
regexStr = regexStr.replace(/\\\*/g, "[^/]*");
|
|
19
|
-
regexStr = regexStr.replace(escapeRegex(localePlaceholder), `(?<locale>${localesAlternation})`);
|
|
20
|
-
if (normalizedMask.includes(keyPlaceholder)) regexStr = regexStr.replace(escapeRegex(keyPlaceholder), "(?<key>.+)");
|
|
21
|
-
const match = new RegExp(regexStr).exec(normalizedFilePath);
|
|
22
|
-
if (!match?.groups) return null;
|
|
23
|
-
let locale = match.groups.locale;
|
|
24
|
-
let key = match.groups.key ?? "index";
|
|
25
|
-
if (typeof key === "undefined") key = "index";
|
|
26
|
-
if (typeof locale === "undefined") locale = defaultLocale;
|
|
27
|
-
return {
|
|
28
|
-
key,
|
|
29
|
-
locale
|
|
30
|
-
};
|
|
31
|
-
};
|
|
32
|
-
const unescapePO = (str) => str.replace(/\\n/g, "\n").replace(/\\t/g, " ").replace(/\\r/g, "\r").replace(/\\"/g, "\"").replace(/\\\\/g, "\\");
|
|
33
|
-
const escapePO = (str) => str.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\r/g, "\\r");
|
|
34
|
-
/**
|
|
35
|
-
* Parse a PO file string into a flat msgid → msgstr record.
|
|
36
|
-
* Skips the PO header (msgid ""), comment lines, and plural/context keywords.
|
|
37
|
-
*/
|
|
38
|
-
const parsePO = (fileContent) => {
|
|
39
|
-
const result = {};
|
|
40
|
-
const lines = fileContent.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
|
|
41
|
-
let msgid = "";
|
|
42
|
-
let msgstr = "";
|
|
43
|
-
let currentField = null;
|
|
44
|
-
const finalize = () => {
|
|
45
|
-
if (msgid !== "") result[msgid] = msgstr;
|
|
46
|
-
msgid = "";
|
|
47
|
-
msgstr = "";
|
|
48
|
-
currentField = null;
|
|
49
|
-
};
|
|
50
|
-
for (const line of lines) {
|
|
51
|
-
if (line.startsWith("#")) continue;
|
|
52
|
-
if (line.trim() === "") {
|
|
53
|
-
finalize();
|
|
54
|
-
continue;
|
|
55
|
-
}
|
|
56
|
-
const msgidMatch = line.match(/^msgid\s+"((?:[^"\\]|\\.)*)"$/);
|
|
57
|
-
if (msgidMatch?.[1]) {
|
|
58
|
-
finalize();
|
|
59
|
-
msgid = unescapePO(msgidMatch[1]);
|
|
60
|
-
currentField = "msgid";
|
|
61
|
-
continue;
|
|
62
|
-
}
|
|
63
|
-
const msgstrMatch = line.match(/^msgstr\s+"((?:[^"\\]|\\.)*)"$/);
|
|
64
|
-
if (msgstrMatch?.[1]) {
|
|
65
|
-
msgstr = unescapePO(msgstrMatch[1]);
|
|
66
|
-
currentField = "msgstr";
|
|
67
|
-
continue;
|
|
68
|
-
}
|
|
69
|
-
const contMatch = line.match(/^"((?:[^"\\]|\\.)*)"$/);
|
|
70
|
-
if (contMatch?.[1]) {
|
|
71
|
-
if (currentField === "msgid") msgid += unescapePO(contMatch[1]);
|
|
72
|
-
else if (currentField === "msgstr") msgstr += unescapePO(contMatch[1]);
|
|
73
|
-
continue;
|
|
74
|
-
}
|
|
75
|
-
currentField = null;
|
|
76
|
-
}
|
|
77
|
-
finalize();
|
|
78
|
-
return result;
|
|
79
|
-
};
|
|
80
6
|
/**
|
|
81
|
-
*
|
|
82
|
-
*
|
|
7
|
+
* Two-way PO synchronization plugin: ingests gettext PO files as dictionaries
|
|
8
|
+
* and writes the merged build output back to the same files.
|
|
83
9
|
*/
|
|
84
|
-
const serializePO = (content, locale) => {
|
|
85
|
-
const lines = [];
|
|
86
|
-
lines.push("msgid \"\"");
|
|
87
|
-
lines.push("msgstr \"\"");
|
|
88
|
-
lines.push("\"Content-Type: text/plain; charset=UTF-8\\n\"");
|
|
89
|
-
lines.push("\"Content-Transfer-Encoding: 8bit\\n\"");
|
|
90
|
-
if (locale) lines.push(`"Language: ${locale}\\n"`);
|
|
91
|
-
lines.push("\"MIME-Version: 1.0\\n\"");
|
|
92
|
-
lines.push("");
|
|
93
|
-
for (const [msgid, msgstr] of Object.entries(content)) {
|
|
94
|
-
if (typeof msgstr !== "string") continue;
|
|
95
|
-
lines.push(`msgid "${escapePO(msgid)}"`);
|
|
96
|
-
lines.push(`msgstr "${escapePO(msgstr)}"`);
|
|
97
|
-
lines.push("");
|
|
98
|
-
}
|
|
99
|
-
return `${lines.join("\n")}\n`;
|
|
100
|
-
};
|
|
101
|
-
const listMessages = async (source, configuration) => {
|
|
102
|
-
const { system, internationalization } = configuration;
|
|
103
|
-
const { baseDir } = system;
|
|
104
|
-
const { locales } = internationalization;
|
|
105
|
-
const result = {};
|
|
106
|
-
for (const locale of locales) {
|
|
107
|
-
const globPatternLocale = await parseFilePathPattern(source, {
|
|
108
|
-
key: "**",
|
|
109
|
-
locale
|
|
110
|
-
});
|
|
111
|
-
const maskPatternLocale = await parseFilePathPattern(source, {
|
|
112
|
-
key: "{{__KEY__}}",
|
|
113
|
-
locale
|
|
114
|
-
});
|
|
115
|
-
if (!globPatternLocale || !maskPatternLocale) continue;
|
|
116
|
-
const files = await fg(globPatternLocale.startsWith("./") ? globPatternLocale.slice(2) : globPatternLocale, { cwd: baseDir });
|
|
117
|
-
for (const file of files) {
|
|
118
|
-
const extraction = extractKeyAndLocaleFromPath(file, maskPatternLocale, locales, locale);
|
|
119
|
-
if (!extraction) continue;
|
|
120
|
-
const { key, locale: extractedLocale } = extraction;
|
|
121
|
-
const expectedPath = await parseFilePathPattern(source, {
|
|
122
|
-
key,
|
|
123
|
-
locale: extractedLocale
|
|
124
|
-
});
|
|
125
|
-
const absoluteFoundPath = isAbsolute(file) ? file : resolve(baseDir, file);
|
|
126
|
-
if (absoluteFoundPath !== (isAbsolute(expectedPath) ? expectedPath : resolve(baseDir, expectedPath))) continue;
|
|
127
|
-
const usedLocale = extractedLocale;
|
|
128
|
-
if (!result[usedLocale]) result[usedLocale] = {};
|
|
129
|
-
result[usedLocale][key] = absoluteFoundPath;
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
const hasKeyInMask = (await parseFilePathPattern(source, {
|
|
133
|
-
key: "{{__KEY__}}",
|
|
134
|
-
locale: locales[0]
|
|
135
|
-
})).includes("{{__KEY__}}");
|
|
136
|
-
const discoveredKeys = /* @__PURE__ */ new Set();
|
|
137
|
-
for (const locale of Object.keys(result)) for (const key of Object.keys(result[locale] ?? {})) discoveredKeys.add(key);
|
|
138
|
-
if (!hasKeyInMask) discoveredKeys.add("index");
|
|
139
|
-
const keysToEnsure = discoveredKeys.size > 0 ? Array.from(discoveredKeys) : [];
|
|
140
|
-
for (const locale of locales) {
|
|
141
|
-
if (!result[locale]) result[locale] = {};
|
|
142
|
-
for (const key of keysToEnsure) if (!result[locale][key]) {
|
|
143
|
-
const builtPath = await parseFilePathPattern(source, {
|
|
144
|
-
key,
|
|
145
|
-
locale
|
|
146
|
-
});
|
|
147
|
-
const absoluteBuiltPath = isAbsolute(builtPath) ? builtPath : resolve(baseDir, builtPath);
|
|
148
|
-
result[locale][key] = absoluteBuiltPath;
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
return result;
|
|
152
|
-
};
|
|
153
|
-
const loadMessagePathMap = async (source, configuration) => {
|
|
154
|
-
const messages = await listMessages(source, configuration);
|
|
155
|
-
return Object.entries(messages).flatMap(([locale, keysRecord]) => Object.entries(keysRecord).map(([key, path]) => {
|
|
156
|
-
return {
|
|
157
|
-
path: isAbsolute(path) ? path : resolve(configuration.system.baseDir, path),
|
|
158
|
-
locale,
|
|
159
|
-
key
|
|
160
|
-
};
|
|
161
|
-
}));
|
|
162
|
-
};
|
|
163
10
|
const syncPO = async (options) => {
|
|
164
|
-
const {
|
|
165
|
-
|
|
166
|
-
key: "{{key}}",
|
|
167
|
-
locale: "{{locale}}"
|
|
168
|
-
})}`,
|
|
169
|
-
priority: 0,
|
|
170
|
-
...options
|
|
171
|
-
};
|
|
172
|
-
return {
|
|
11
|
+
const defaultLocation = `sync-po::${await parseFilePathPattern(options.source, buildFilePathPatternContext("{{key}}", "{{locale}}"))}`;
|
|
12
|
+
return createSyncPlugin({
|
|
173
13
|
name: "sync-po",
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
if (fill) fill = relative(configuration.system.baseDir, resolve(configuration.system.baseDir, fill));
|
|
186
|
-
const dictionaries = [];
|
|
187
|
-
for (const { locale, path, key } of dictionariesMap) {
|
|
188
|
-
let poContent;
|
|
189
|
-
try {
|
|
190
|
-
poContent = parsePO(await readFile(path, "utf-8"));
|
|
191
|
-
} catch {
|
|
192
|
-
poContent = {};
|
|
193
|
-
}
|
|
194
|
-
const filePath = relative(configuration.system.baseDir, path);
|
|
195
|
-
const dictionary = {
|
|
196
|
-
key,
|
|
197
|
-
locale,
|
|
198
|
-
fill,
|
|
199
|
-
format: "po",
|
|
200
|
-
localId: `${key}::${location}::${filePath}`,
|
|
201
|
-
location,
|
|
202
|
-
filled: locale !== configuration.internationalization.defaultLocale ? true : void 0,
|
|
203
|
-
content: poContent,
|
|
204
|
-
filePath,
|
|
205
|
-
priority
|
|
206
|
-
};
|
|
207
|
-
dictionaries.push(dictionary);
|
|
208
|
-
}
|
|
209
|
-
return dictionaries;
|
|
210
|
-
},
|
|
211
|
-
formatOutput: async ({ dictionary, configuration }) => {
|
|
212
|
-
const { formatDictionaryOutput } = await import("@intlayer/engine/build");
|
|
213
|
-
if (!dictionary.filePath || !dictionary.locale) return dictionary;
|
|
214
|
-
const builderPath = await parseFilePathPattern(options.source, {
|
|
215
|
-
key: dictionary.key,
|
|
216
|
-
locale: dictionary.locale
|
|
217
|
-
});
|
|
218
|
-
if (resolve(configuration.system.baseDir, builderPath) !== resolve(configuration.system.baseDir, dictionary.filePath)) return dictionary;
|
|
219
|
-
return formatDictionaryOutput(dictionary, "po").content;
|
|
220
|
-
},
|
|
221
|
-
afterBuild: async ({ dictionaries, configuration }) => {
|
|
222
|
-
const { getPerLocaleDictionary } = await import("@intlayer/core/plugins");
|
|
223
|
-
const { parallelize } = await import("@intlayer/engine/utils");
|
|
224
|
-
const { formatDictionaryOutput } = await import("@intlayer/engine/build");
|
|
225
|
-
const { locales } = configuration.internationalization;
|
|
226
|
-
await parallelize(Object.entries(dictionaries.mergedDictionaries).flatMap(([key, dictionary]) => locales.map((locale) => ({
|
|
227
|
-
key,
|
|
228
|
-
dictionary: dictionary.dictionary,
|
|
229
|
-
locale
|
|
230
|
-
}))), async ({ key, dictionary, locale }) => {
|
|
231
|
-
if (dictionary.location !== location) return;
|
|
232
|
-
const builderPath = await parseFilePathPattern(options.source, {
|
|
233
|
-
key,
|
|
234
|
-
locale
|
|
235
|
-
});
|
|
236
|
-
const formattedOutput = formatDictionaryOutput(getPerLocaleDictionary(dictionary, locale), "po");
|
|
237
|
-
const content = JSON.parse(JSON.stringify(formattedOutput.content));
|
|
238
|
-
if (typeof content === "undefined" || typeof content === "object" && Object.keys(content).length === 0) return;
|
|
239
|
-
await mkdir(dirname(builderPath), { recursive: true });
|
|
240
|
-
await writeFile(builderPath, serializePO(content, locale), "utf-8");
|
|
241
|
-
});
|
|
242
|
-
}
|
|
243
|
-
};
|
|
14
|
+
adapter: createFileAdapter({
|
|
15
|
+
source: options.source,
|
|
16
|
+
codec: poCodec,
|
|
17
|
+
discovery: "strict"
|
|
18
|
+
}),
|
|
19
|
+
direction: "both",
|
|
20
|
+
location: options.location ?? defaultLocation,
|
|
21
|
+
priority: options.priority ?? 0,
|
|
22
|
+
format: "po",
|
|
23
|
+
splitKeys: false
|
|
24
|
+
});
|
|
244
25
|
};
|
|
245
26
|
|
|
246
27
|
//#endregion
|
package/dist/esm/syncPO.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncPO.mjs","names":[],"sources":["../../src/syncPO.ts"],"sourcesContent":["import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, relative, resolve } from 'node:path';\nimport { colorizePath, getAppLogger } from '@intlayer/config/logger';\nimport { parseFilePathPattern } from '@intlayer/config/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type {\n Dictionary,\n DictionaryLocation,\n LocalDictionaryId,\n} from '@intlayer/types/dictionary';\nimport type {\n FilePathPattern,\n FilePathPatternContext,\n} from '@intlayer/types/filePathPattern';\nimport type { Plugin } from '@intlayer/types/plugin';\nimport fg from 'fast-glob';\n\ntype FilePath = string;\n\ntype MessagesRecord = Record<Locale, Record<Dictionary['key'], FilePath>>;\n\nconst escapeRegex = (str: string) => str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\nexport const extractKeyAndLocaleFromPath = (\n filePath: string,\n maskPattern: string,\n locales: Locale[],\n defaultLocale: Locale\n): { key: string; locale: Locale } | null => {\n const keyPlaceholder = '{{__KEY__}}';\n const localePlaceholder = '{{__LOCALE__}}';\n\n // fast-glob strips leading \"./\" from returned paths; normalize both sides\n const normalize = (path: string) =>\n path.startsWith('./') ? path.slice(2) : path;\n\n const normalizedFilePath = normalize(filePath);\n const normalizedMask = normalize(maskPattern);\n\n const localesAlternation = locales.join('|');\n\n // Escape special regex chars, then convert glob wildcards to regex equivalents.\n // Must replace ** before * to avoid double-replacing.\n let regexStr = `^${escapeRegex(normalizedMask)}$`;\n regexStr = regexStr.replace(/\\\\\\*\\\\\\*/g, '.*'); // ** → match any path segments\n regexStr = regexStr.replace(/\\\\\\*/g, '[^/]*'); // * → match within a single segment\n\n regexStr = regexStr.replace(\n escapeRegex(localePlaceholder),\n `(?<locale>${localesAlternation})`\n );\n\n if (normalizedMask.includes(keyPlaceholder)) {\n regexStr = regexStr.replace(escapeRegex(keyPlaceholder), '(?<key>.+)');\n }\n\n const maskRegex = new RegExp(regexStr);\n const match = maskRegex.exec(normalizedFilePath);\n\n if (!match?.groups) {\n return null;\n }\n\n let locale = match.groups.locale as Locale | undefined;\n let key = (match.groups.key as string | undefined) ?? 'index';\n\n if (typeof key === 'undefined') {\n key = 'index';\n }\n\n if (typeof locale === 'undefined') {\n locale = defaultLocale;\n }\n\n return { key, locale };\n};\n\n// ─── PO format utilities ────────────────────────────────────────────────────\n\nconst unescapePO = (str: string): string =>\n str\n .replace(/\\\\n/g, '\\n')\n .replace(/\\\\t/g, '\\t')\n .replace(/\\\\r/g, '\\r')\n .replace(/\\\\\"/g, '\"')\n .replace(/\\\\\\\\/g, '\\\\');\n\nconst escapePO = (str: string): string =>\n str\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\t/g, '\\\\t')\n .replace(/\\r/g, '\\\\r');\n\n/**\n * Parse a PO file string into a flat msgid → msgstr record.\n * Skips the PO header (msgid \"\"), comment lines, and plural/context keywords.\n */\nexport const parsePO = (fileContent: string): Record<string, string> => {\n const result: Record<string, string> = {};\n const lines = fileContent\n .replace(/\\r\\n/g, '\\n')\n .replace(/\\r/g, '\\n')\n .split('\\n');\n\n let msgid = '';\n let msgstr = '';\n let currentField: 'msgid' | 'msgstr' | null = null;\n\n const finalize = () => {\n if (msgid !== '') {\n result[msgid] = msgstr;\n }\n msgid = '';\n msgstr = '';\n currentField = null;\n };\n\n for (const line of lines) {\n // Skip all comment types (#, #., #:, #,, #|)\n if (line.startsWith('#')) continue;\n\n if (line.trim() === '') {\n finalize();\n continue;\n }\n\n const msgidMatch = line.match(/^msgid\\s+\"((?:[^\"\\\\]|\\\\.)*)\"$/);\n if (msgidMatch?.[1]) {\n // Starting a new entry — finalize the previous one first\n finalize();\n msgid = unescapePO(msgidMatch[1]);\n currentField = 'msgid';\n continue;\n }\n\n const msgstrMatch = line.match(/^msgstr\\s+\"((?:[^\"\\\\]|\\\\.)*)\"$/);\n if (msgstrMatch?.[1]) {\n msgstr = unescapePO(msgstrMatch[1]);\n currentField = 'msgstr';\n continue;\n }\n\n // Continuation line: `\"...\"` appends to the current keyword's value\n const contMatch = line.match(/^\"((?:[^\"\\\\]|\\\\.)*)\"$/);\n if (contMatch?.[1]) {\n if (currentField === 'msgid') {\n msgid += unescapePO(contMatch[1]);\n } else if (currentField === 'msgstr') {\n msgstr += unescapePO(contMatch[1]);\n }\n continue;\n }\n\n // Other keywords (msgid_plural, msgstr[n], msgctxt) — not supported; reset field\n currentField = null;\n }\n\n // Finalize the last entry in the file (no trailing blank line needed)\n finalize();\n\n return result;\n};\n\n/**\n * Serialize a flat key → value record to PO file format.\n * Non-string values are silently skipped.\n */\nexport const serializePO = (\n content: Record<string, unknown>,\n locale?: string\n): string => {\n const lines: string[] = [];\n\n // PO header entry\n lines.push('msgid \"\"');\n lines.push('msgstr \"\"');\n lines.push('\"Content-Type: text/plain; charset=UTF-8\\\\n\"');\n lines.push('\"Content-Transfer-Encoding: 8bit\\\\n\"');\n if (locale) {\n lines.push(`\"Language: ${locale}\\\\n\"`);\n }\n lines.push('\"MIME-Version: 1.0\\\\n\"');\n lines.push('');\n\n for (const [msgid, msgstr] of Object.entries(content)) {\n if (typeof msgstr !== 'string') continue;\n\n lines.push(`msgid \"${escapePO(msgid)}\"`);\n lines.push(`msgstr \"${escapePO(msgstr)}\"`);\n lines.push('');\n }\n\n return `${lines.join('\\n')}\\n`;\n};\n\n// ─── File-discovery helpers (format-agnostic) ────────────────────────────────\n\nconst listMessages = async (\n source: FilePathPattern,\n configuration: IntlayerConfig\n): Promise<MessagesRecord> => {\n const { system, internationalization } = configuration;\n\n const { baseDir } = system;\n const { locales } = internationalization;\n\n const result: MessagesRecord = {} as MessagesRecord;\n\n for (const locale of locales) {\n const globPatternLocale = await parseFilePathPattern(source, {\n key: '**',\n locale,\n } as any as FilePathPatternContext);\n\n const maskPatternLocale = await parseFilePathPattern(source, {\n key: '{{__KEY__}}',\n locale,\n } as any as FilePathPatternContext);\n\n if (!globPatternLocale || !maskPatternLocale) {\n continue;\n }\n\n const normalizedGlobPattern = globPatternLocale.startsWith('./')\n ? globPatternLocale.slice(2)\n : globPatternLocale;\n\n const files = await fg(normalizedGlobPattern, {\n cwd: baseDir,\n });\n\n for (const file of files) {\n const extraction = extractKeyAndLocaleFromPath(\n file,\n maskPatternLocale,\n locales,\n locale\n );\n\n if (!extraction) {\n continue;\n }\n\n const { key, locale: extractedLocale } = extraction;\n\n // Generate what the path SHOULD be for this key/locale using the current builder\n const expectedPath = await parseFilePathPattern(source, {\n key,\n locale: extractedLocale,\n } as any as FilePathPatternContext);\n\n // Resolve both to absolute paths to ensure safe comparison\n const absoluteFoundPath = isAbsolute(file)\n ? file\n : resolve(baseDir, file);\n const absoluteExpectedPath = isAbsolute(expectedPath)\n ? expectedPath\n : resolve(baseDir, expectedPath);\n\n // If the file found doesn't exactly match the file expected, it belongs to another plugin/structure\n if (absoluteFoundPath !== absoluteExpectedPath) {\n continue;\n }\n\n const usedLocale = extractedLocale as Locale;\n if (!result[usedLocale]) {\n result[usedLocale] = {};\n }\n\n result[usedLocale][key as Dictionary['key']] = absoluteFoundPath;\n }\n }\n\n // Ensure all declared locales are present even if the file doesn't exist yet\n const maskWithKey = await parseFilePathPattern(source, {\n key: '{{__KEY__}}',\n locale: locales[0],\n } as any as FilePathPatternContext);\n\n const hasKeyInMask = maskWithKey.includes('{{__KEY__}}');\n const discoveredKeys = new Set<string>();\n\n for (const locale of Object.keys(result)) {\n for (const key of Object.keys(result[locale as Locale] ?? {})) {\n discoveredKeys.add(key);\n }\n }\n\n if (!hasKeyInMask) {\n discoveredKeys.add('index');\n }\n\n const keysToEnsure =\n discoveredKeys.size > 0 ? Array.from(discoveredKeys) : [];\n\n for (const locale of locales) {\n if (!result[locale]) {\n result[locale] = {} as Record<Dictionary['key'], FilePath>;\n }\n\n for (const key of keysToEnsure) {\n if (!result[locale][key as Dictionary['key']]) {\n const builtPath = await parseFilePathPattern(source, {\n key,\n locale,\n } as any as FilePathPatternContext);\n const absoluteBuiltPath = isAbsolute(builtPath)\n ? builtPath\n : resolve(baseDir, builtPath);\n\n result[locale][key as Dictionary['key']] = absoluteBuiltPath;\n }\n }\n }\n\n return result;\n};\n\ntype DictionariesMap = { path: string; locale: Locale; key: string }[];\n\nconst loadMessagePathMap = async (\n source: MessagesRecord | FilePathPattern,\n configuration: IntlayerConfig\n) => {\n const messages: MessagesRecord = await listMessages(\n source as FilePathPattern,\n configuration\n );\n\n const dictionariesPathMap: DictionariesMap = Object.entries(messages).flatMap(\n ([locale, keysRecord]) =>\n Object.entries(keysRecord).map(([key, path]) => {\n const absolutePath = isAbsolute(path)\n ? path\n : resolve(configuration.system.baseDir, path);\n\n return {\n path: absolutePath,\n locale,\n key,\n } as DictionariesMap[number];\n })\n );\n\n return dictionariesPathMap;\n};\n\n// ─── Plugin ──────────────────────────────────────────────────────────────────\n\ntype SyncPOPluginOptions = {\n /**\n * The source of the plugin.\n * Is a function to build the source from the key and locale.\n *\n * ```ts\n * syncPO({\n * source: ({ key, locale }) => `./messages/${locale}/${key}.po`\n * })\n * ```\n */\n source: FilePathPattern;\n\n /**\n * Because Intlayer transforms PO files into Dictionary, we need to identify the plugin in the dictionary.\n * Used to identify the plugin in the dictionary.\n *\n * In the case you have multiple plugins, you can use this to identify the plugin in the dictionary.\n *\n * ```ts\n * // Example usage:\n * const config = {\n * plugins: [\n * syncPO({\n * source: ({ key, locale }) => `./resources/${locale}/${key}.po`,\n * location: 'plugin-i18next-po',\n * }),\n * ]\n * }\n * ```\n */\n location?: DictionaryLocation | (string & {});\n\n /**\n * The priority of the dictionaries created by the plugin.\n *\n * In the case of conflicts with remote dictionaries, or .content files, the dictionary with the highest priority will override the other dictionaries.\n *\n * Default is 0.\n */\n priority?: number;\n};\n\nexport const syncPO = async (options: SyncPOPluginOptions): Promise<Plugin> => {\n // Generate a unique default location based on the source pattern.\n const patternMarker = await parseFilePathPattern(options.source, {\n key: '{{key}}',\n locale: '{{locale}}',\n } as any as FilePathPatternContext);\n const defaultLocation = `sync-po::${patternMarker}`;\n\n const { location, priority } = {\n location: defaultLocation,\n priority: 0,\n ...options,\n };\n\n return {\n name: 'sync-po',\n\n loadDictionaries: async ({ configuration }) => {\n const appLogger = getAppLogger(configuration);\n const dictionariesMap: DictionariesMap = await loadMessagePathMap(\n options.source,\n configuration\n );\n\n if (dictionariesMap.length === 0) {\n const pattern = await parseFilePathPattern(options.source, {\n key: '{{key}}',\n locale: '{{locale}}',\n } as any as FilePathPatternContext);\n\n appLogger(\n `[sync-po] No dictionaries found at locations matching source pattern: ${colorizePath(pattern)}`,\n { level: 'warn' }\n );\n }\n\n let fill: string = await parseFilePathPattern(options.source, {\n key: '{{key}}',\n locale: '{{locale}}',\n } as any as FilePathPatternContext);\n\n if (fill) {\n fill = relative(\n configuration.system.baseDir,\n resolve(configuration.system.baseDir, fill)\n );\n }\n\n const dictionaries: Dictionary[] = [];\n\n for (const { locale, path, key } of dictionariesMap) {\n let poContent: Record<string, string>;\n try {\n const fileContent = await readFile(path, 'utf-8');\n poContent = parsePO(fileContent);\n } catch {\n poContent = {};\n }\n\n const filePath = relative(configuration.system.baseDir, path);\n\n const dictionary: Dictionary = {\n key,\n locale,\n fill,\n format: 'po',\n localId: `${key}::${location}::${filePath}` as LocalDictionaryId,\n location: location as Dictionary['location'],\n filled:\n locale !== configuration.internationalization.defaultLocale\n ? true\n : undefined,\n content: poContent,\n filePath,\n priority,\n };\n\n dictionaries.push(dictionary);\n }\n\n return dictionaries;\n },\n\n formatOutput: async ({ dictionary, configuration }) => {\n // Lazy import intlayer modules to avoid circular dependencies\n const { formatDictionaryOutput } = await import('@intlayer/engine/build');\n\n if (!dictionary.filePath || !dictionary.locale) return dictionary;\n\n const builderPath = await parseFilePathPattern(options.source, {\n key: dictionary.key,\n locale: dictionary.locale,\n } as FilePathPatternContext);\n\n // Verification to ensure we are formatting the correct file\n if (\n resolve(configuration.system.baseDir, builderPath) !==\n resolve(configuration.system.baseDir, dictionary.filePath)\n ) {\n return dictionary;\n }\n\n const formattedOutput = formatDictionaryOutput(dictionary, 'po');\n\n return formattedOutput.content;\n },\n\n afterBuild: async ({ dictionaries, configuration }) => {\n // Lazy import intlayer modules to avoid circular dependencies\n const { getPerLocaleDictionary } = await import('@intlayer/core/plugins');\n const { parallelize } = await import('@intlayer/engine/utils');\n const { formatDictionaryOutput } = await import('@intlayer/engine/build');\n\n const { locales } = configuration.internationalization;\n\n type RecordList = {\n key: string;\n dictionary: Dictionary;\n locale: Locale;\n };\n\n const recordList: RecordList[] = Object.entries(\n dictionaries.mergedDictionaries\n ).flatMap(([key, dictionary]) =>\n locales.map((locale) => ({\n key,\n dictionary: dictionary.dictionary as Dictionary,\n locale,\n }))\n );\n\n await parallelize(recordList, async ({ key, dictionary, locale }) => {\n // Only process dictionaries that belong to THIS plugin instance.\n if (dictionary.location !== location) {\n return;\n }\n\n const builderPath = await parseFilePathPattern(options.source, {\n key,\n locale,\n } as any as FilePathPatternContext);\n\n const localizedDictionary = getPerLocaleDictionary(dictionary, locale);\n\n const formattedOutput = formatDictionaryOutput(\n localizedDictionary,\n 'po'\n );\n\n const content = JSON.parse(\n JSON.stringify(formattedOutput.content)\n ) as Record<string, unknown>;\n\n if (\n typeof content === 'undefined' ||\n (typeof content === 'object' &&\n Object.keys(content as Record<string, unknown>).length === 0)\n ) {\n return;\n }\n\n await mkdir(dirname(builderPath), { recursive: true });\n\n const poContent = serializePO(content, locale);\n\n await writeFile(builderPath, poContent, 'utf-8');\n });\n },\n };\n};\n"],"mappings":";;;;;;;AAsBA,MAAM,eAAe,QAAgB,IAAI,QAAQ,uBAAuB,OAAO;AAE/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W;IACvB;IACD,EAAE,CAGuB,EAAE,OAAO,EAAE,KAAK,YAAY,aAAa;AAEnE,QAAI,WAAW,aAAa,SAC1B;IAGF,MAAM,cAAc,MAAM,qBAAqB,QAAQ,QAAQ;KAC7D;KACA;KACD,CAAkC;IAInC,MAAM,kBAAkB,uBAFI,uBAAuB,YAAY,OAG1C,EACnB,KACD;IAED,MAAM,UAAU,KAAK,MACnB,KAAK,UAAU,gBAAgB,QAAQ,CACxC;AAED,QACE,OAAO,YAAY,eAClB,OAAO,YAAY,YAClB,OAAO,KAAK,QAAmC,CAAC,WAAW,EAE7D;AAGF,UAAM,MAAM,QAAQ,YAAY,EAAE,EAAE,WAAW,MAAM,CAAC;AAItD,UAAM,UAAU,aAFE,YAAY,SAAS,OAED,EAAE,QAAQ;KAChD;;EAEL"}
|
|
1
|
+
{"version":3,"file":"syncPO.mjs","names":[],"sources":["../../src/syncPO.ts"],"sourcesContent":["import { parseFilePathPattern } from '@intlayer/config/utils';\nimport {\n buildFilePathPatternContext,\n createFileAdapter,\n createSyncPlugin,\n} from '@intlayer/engine/syncPluginKit';\nimport type { DictionaryLocation } from '@intlayer/types/dictionary';\nimport type { FilePathPattern } from '@intlayer/types/filePathPattern';\nimport type { Plugin } from '@intlayer/types/plugin';\nimport { poCodec } from './poFormat';\n\n// Re-exported for backward compatibility: these helpers used to live here.\nexport { extractKeyAndLocaleFromPath } from '@intlayer/engine/syncPluginKit';\nexport { parsePO, serializePO } from './poFormat';\n\nexport type SyncPOPluginOptions = {\n /**\n * The source of the plugin.\n * Is a function to build the source from the key and locale.\n *\n * ```ts\n * syncPO({\n * source: ({ key, locale }) => `./messages/${locale}/${key}.po`\n * })\n * ```\n */\n source: FilePathPattern;\n\n /**\n * Because Intlayer transforms PO files into Dictionary, we need to identify the plugin in the dictionary.\n * Used to identify the plugin in the dictionary.\n *\n * In the case you have multiple plugins, you can use this to identify the plugin in the dictionary.\n *\n * ```ts\n * // Example usage:\n * const config = {\n * plugins: [\n * syncPO({\n * source: ({ key, locale }) => `./resources/${locale}/${key}.po`,\n * location: 'plugin-i18next-po',\n * }),\n * ]\n * }\n * ```\n */\n location?: DictionaryLocation | (string & {});\n\n /**\n * The priority of the dictionaries created by the plugin.\n *\n * In the case of conflicts with remote dictionaries, or .content files, the dictionary with the highest priority will override the other dictionaries.\n *\n * Default is 0.\n */\n priority?: number;\n};\n\n/**\n * Two-way PO synchronization plugin: ingests gettext PO files as dictionaries\n * and writes the merged build output back to the same files.\n */\nexport const syncPO = async (options: SyncPOPluginOptions): Promise<Plugin> => {\n // Generate a unique default location based on the source pattern.\n const patternMarker = await parseFilePathPattern(\n options.source,\n buildFilePathPatternContext('{{key}}', '{{locale}}')\n );\n const defaultLocation = `sync-po::${patternMarker}`;\n\n return createSyncPlugin({\n name: 'sync-po',\n adapter: createFileAdapter({\n source: options.source,\n codec: poCodec,\n discovery: 'strict',\n }),\n direction: 'both',\n location: options.location ?? defaultLocation,\n priority: options.priority ?? 0,\n format: 'po',\n // PO files are flat msgid → msgstr records; there is no namespace level\n // to split on, regardless of the source pattern shape.\n splitKeys: false,\n });\n};\n"],"mappings":";;;;;;;;;AA8DA,MAAa,SAAS,OAAO,YAAkD;CAM7E,MAAM,kBAAkB,YAAY,MAJR,qBAC1B,QAAQ,QACR,4BAA4B,WAAW,aAAa,CACrD;AAGD,QAAO,iBAAiB;EACtB,MAAM;EACN,SAAS,kBAAkB;GACzB,QAAQ,QAAQ;GAChB,OAAO;GACP,WAAW;GACZ,CAAC;EACF,WAAW;EACX,UAAU,QAAQ,YAAY;EAC9B,UAAU,QAAQ,YAAY;EAC9B,QAAQ;EAGR,WAAW;EACZ,CAAC"}
|
package/dist/types/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
import { loadPO } from "./loadPO.js";
|
|
2
|
-
import {
|
|
3
|
-
|
|
1
|
+
import { LoadPOPluginOptions, loadPO } from "./loadPO.js";
|
|
2
|
+
import { parsePO, poCodec, serializePO } from "./poFormat.js";
|
|
3
|
+
import { SyncPOPluginOptions, extractKeyAndLocaleFromPath, syncPO } from "./syncPO.js";
|
|
4
|
+
export { LoadPOPluginOptions, SyncPOPluginOptions, extractKeyAndLocaleFromPath, loadPO, parsePO, poCodec, serializePO, syncPO };
|
package/dist/types/loadPO.d.ts
CHANGED
|
@@ -58,7 +58,11 @@ type LoadPOPluginOptions = {
|
|
|
58
58
|
*/
|
|
59
59
|
priority?: number;
|
|
60
60
|
};
|
|
61
|
+
/**
|
|
62
|
+
* Read-only PO ingestion plugin: loads gettext PO files as dictionaries
|
|
63
|
+
* without ever writing back to them.
|
|
64
|
+
*/
|
|
61
65
|
declare const loadPO: (options: LoadPOPluginOptions) => Plugin;
|
|
62
66
|
//#endregion
|
|
63
|
-
export { loadPO };
|
|
67
|
+
export { LoadPOPluginOptions, loadPO };
|
|
64
68
|
//# sourceMappingURL=loadPO.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loadPO.d.ts","names":[],"sources":["../../src/loadPO.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"loadPO.d.ts","names":[],"sources":["../../src/loadPO.ts"],"mappings":";;;;;KASY,mBAAA;;AAAZ;;;;;;;;;;EAYE,MAAA,EAAQ,eAAA;EA4CA;AAOV;;;;;;;;;;;;EApCE,MAAA,GAAS,MAAA;;;;;;;;;;;;;;;;;;;EAoBT,QAAA;;;;;;;;EASA,QAAA;AAAA;;;;;cAOW,MAAA,GAAU,OAAA,EAAS,mBAAA,KAAsB,MAAA"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { FormatCodec } from "@intlayer/engine/syncPluginKit";
|
|
2
|
+
|
|
3
|
+
//#region src/poFormat.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Parse a PO file string into a flat msgid → msgstr record.
|
|
6
|
+
* Skips the PO header (msgid ""), comment lines, and plural/context keywords.
|
|
7
|
+
*/
|
|
8
|
+
declare const parsePO: (fileContent: string) => Record<string, string>;
|
|
9
|
+
/**
|
|
10
|
+
* Serialize a flat key → value record to PO file format.
|
|
11
|
+
* Non-string values are silently skipped.
|
|
12
|
+
*/
|
|
13
|
+
declare const serializePO: (content: Record<string, unknown>, locale?: string) => string;
|
|
14
|
+
/**
|
|
15
|
+
* PO payload codec bridging {@link parsePO} / {@link serializePO} to the
|
|
16
|
+
* sync-plugin kit.
|
|
17
|
+
*/
|
|
18
|
+
declare const poCodec: FormatCodec;
|
|
19
|
+
//#endregion
|
|
20
|
+
export { parsePO, poCodec, serializePO };
|
|
21
|
+
//# sourceMappingURL=poFormat.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"poFormat.d.ts","names":[],"sources":["../../src/poFormat.ts"],"mappings":";;;;;AAsBA;;cAAa,OAAA,GAAW,WAAA,aAAsB,MAAA;;;AAsE9C;;cAAa,WAAA,GACX,OAAA,EAAS,MAAA,mBACT,MAAA;;;;;cA8BW,OAAA,EAAS,WAAA"}
|