@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.
@@ -1,9 +1,17 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_syncPO = require('./syncPO.cjs');
2
+ const require_poFormat = require('./poFormat.cjs');
3
3
  const require_loadPO = require('./loadPO.cjs');
4
+ const require_syncPO = require('./syncPO.cjs');
5
+ let _intlayer_engine_syncPluginKit = require("@intlayer/engine/syncPluginKit");
4
6
 
5
- exports.extractKeyAndLocaleFromPath = require_syncPO.extractKeyAndLocaleFromPath;
7
+ Object.defineProperty(exports, 'extractKeyAndLocaleFromPath', {
8
+ enumerable: true,
9
+ get: function () {
10
+ return _intlayer_engine_syncPluginKit.extractKeyAndLocaleFromPath;
11
+ }
12
+ });
6
13
  exports.loadPO = require_loadPO.loadPO;
7
- exports.parsePO = require_syncPO.parsePO;
8
- exports.serializePO = require_syncPO.serializePO;
14
+ exports.parsePO = require_poFormat.parsePO;
15
+ exports.poCodec = require_poFormat.poCodec;
16
+ exports.serializePO = require_poFormat.serializePO;
9
17
  exports.syncPO = require_syncPO.syncPO;
@@ -1,105 +1,26 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
3
- const require_syncPO = require('./syncPO.cjs');
4
- let node_fs_promises = require("node:fs/promises");
5
- let node_path = require("node:path");
6
- let _intlayer_config_logger = require("@intlayer/config/logger");
7
- let _intlayer_config_utils = require("@intlayer/config/utils");
8
- let fast_glob = require("fast-glob");
9
- fast_glob = require_runtime.__toESM(fast_glob);
2
+ const require_poFormat = require('./poFormat.cjs');
3
+ let _intlayer_engine_syncPluginKit = require("@intlayer/engine/syncPluginKit");
10
4
 
11
5
  //#region src/loadPO.ts
12
- const listMessages = async (source, configuration) => {
13
- const { system, internationalization } = configuration;
14
- const { baseDir } = system;
15
- const { locales } = internationalization;
16
- const result = {};
17
- for (const locale of locales) {
18
- const globPatternLocale = await (0, _intlayer_config_utils.parseFilePathPattern)(source, {
19
- key: "**",
20
- locale
21
- });
22
- const maskPatternLocale = await (0, _intlayer_config_utils.parseFilePathPattern)(source, {
23
- key: "{{__KEY__}}",
24
- locale
25
- });
26
- if (!globPatternLocale || !maskPatternLocale) continue;
27
- const files = await (0, fast_glob.default)(globPatternLocale.startsWith("./") ? globPatternLocale.slice(2) : globPatternLocale, { cwd: baseDir });
28
- for (const file of files) {
29
- const hasLocaleInMask = maskPatternLocale.includes("{{__LOCALE__}}");
30
- const hasKeyInMask = maskPatternLocale.includes("{{__KEY__}}");
31
- let key;
32
- let extractedLocale;
33
- if (hasLocaleInMask || hasKeyInMask) {
34
- const extraction = require_syncPO.extractKeyAndLocaleFromPath(file, maskPatternLocale, locales, locale);
35
- if (!extraction) continue;
36
- key = extraction.key;
37
- extractedLocale = extraction.locale;
38
- } else {
39
- key = "index";
40
- extractedLocale = locale;
41
- }
42
- const absolutePath = (0, node_path.isAbsolute)(file) ? file : (0, node_path.resolve)(baseDir, file);
43
- const usedLocale = extractedLocale;
44
- if (!result[usedLocale]) result[usedLocale] = {};
45
- result[usedLocale][key] = absolutePath;
46
- }
47
- }
48
- return result;
49
- };
50
- const loadMessagePathMap = async (source, configuration) => {
51
- const messages = await listMessages(source, configuration);
52
- return Object.entries(messages).flatMap(([locale, keysRecord]) => Object.entries(keysRecord).map(([key, path]) => {
53
- return {
54
- path: (0, node_path.isAbsolute)(path) ? path : (0, node_path.resolve)(configuration.system.baseDir, path),
55
- locale,
56
- key
57
- };
58
- }));
59
- };
60
- const loadPO = (options) => {
61
- const { location, priority, locale } = {
62
- location: "plugin",
63
- priority: 0,
64
- ...options
65
- };
66
- return {
67
- name: "load-po",
68
- loadDictionaries: async ({ configuration }) => {
69
- const appLogger = (0, _intlayer_config_logger.getAppLogger)(configuration);
70
- const dictionariesMap = await loadMessagePathMap(options.source, configuration);
71
- if (dictionariesMap.length === 0) appLogger(`No dictionaries found at locations matching source pattern: ${(0, _intlayer_config_logger.colorizePath)(await (0, _intlayer_config_utils.parseFilePathPattern)(options.source, {
72
- key: "{{key}}",
73
- locale: "{{locale}}"
74
- }))}`, { level: "warn" });
75
- const dictionaries = [];
76
- for (const { path, key, locale: entryLocale } of dictionariesMap) {
77
- let poContent;
78
- try {
79
- poContent = require_syncPO.parsePO(await (0, node_fs_promises.readFile)(path, "utf-8"));
80
- } catch {
81
- poContent = {};
82
- }
83
- const filePath = (0, node_path.relative)(configuration.system.baseDir, path);
84
- const entryUsedLocale = locale ?? entryLocale;
85
- const dictionary = {
86
- key,
87
- locale: entryUsedLocale,
88
- fill: filePath,
89
- format: "po",
90
- localId: `${key}::${location}::${filePath}`,
91
- location,
92
- filled: entryUsedLocale !== configuration.internationalization.defaultLocale ? true : void 0,
93
- content: poContent,
94
- filePath,
95
- priority
96
- };
97
- dictionaries.push(dictionary);
98
- }
99
- return dictionaries;
100
- }
101
- };
102
- };
6
+ /**
7
+ * Read-only PO ingestion plugin: loads gettext PO files as dictionaries
8
+ * without ever writing back to them.
9
+ */
10
+ const loadPO = (options) => (0, _intlayer_engine_syncPluginKit.createSyncPlugin)({
11
+ name: "load-po",
12
+ adapter: (0, _intlayer_engine_syncPluginKit.createFileAdapter)({
13
+ source: options.source,
14
+ codec: require_poFormat.poCodec,
15
+ discovery: "inclusive"
16
+ }),
17
+ direction: "pull",
18
+ location: options.location ?? "plugin",
19
+ priority: options.priority ?? 0,
20
+ format: "po",
21
+ splitKeys: false,
22
+ localeOverride: options.locale
23
+ });
103
24
 
104
25
  //#endregion
105
26
  exports.loadPO = loadPO;
@@ -1 +1 @@
1
- {"version":3,"file":"loadPO.cjs","names":["extractKeyAndLocaleFromPath","sourcePattern","parsePO"],"sources":["../../src/loadPO.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { 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 { Dictionary, LocalDictionaryId } 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';\nimport { extractKeyAndLocaleFromPath, parsePO } from './syncPO';\n\ntype FilePath = string;\n\ntype MessagesRecord = Record<Locale, Record<Dictionary['key'], FilePath>>;\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 // extractKeyAndLocaleFromPath requires at least one named capture group\n // ({{__LOCALE__}} or {{__KEY__}}) in the mask to return a non-null result.\n // When the mask is fully concrete (e.g. `messages/en.po` — the source has\n // {{locale}} but no {{key}}), no groups exist and it returns null.\n // In that case, fall back directly to the loop locale and key = 'index'.\n const hasLocaleInMask = maskPatternLocale.includes('{{__LOCALE__}}');\n const hasKeyInMask = maskPatternLocale.includes('{{__KEY__}}');\n\n let key: string;\n let extractedLocale: Locale;\n\n if (hasLocaleInMask || hasKeyInMask) {\n const extraction = extractKeyAndLocaleFromPath(\n file,\n maskPatternLocale,\n locales,\n locale\n );\n\n if (!extraction) {\n continue;\n }\n\n key = extraction.key;\n extractedLocale = extraction.locale;\n } else {\n // Mask has no placeholders — attribute directly to the current loop locale.\n key = 'index';\n extractedLocale = locale;\n }\n\n const absolutePath = isAbsolute(file) ? file : resolve(baseDir, file);\n\n const usedLocale = extractedLocale as Locale;\n if (!result[usedLocale]) {\n result[usedLocale] = {};\n }\n\n result[usedLocale][key as Dictionary['key']] = absolutePath;\n }\n }\n\n // For the load plugin we only use actual discovered files; do not fabricate\n // missing locales or keys, since we don't write outputs.\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 sourcePattern = source as FilePathPattern;\n const messages: MessagesRecord = await listMessages(\n sourcePattern,\n configuration\n );\n\n const entries = Object.entries(messages) as [\n Locale,\n Record<Dictionary['key'], FilePath>,\n ][];\n\n const dictionariesPathMap: DictionariesMap = entries.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\ntype 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\nexport const loadPO = (options: LoadPOPluginOptions): Plugin => {\n const { location, priority, locale } = {\n location: 'plugin',\n priority: 0,\n ...options,\n } as const;\n\n return {\n name: 'load-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 `No dictionaries found at locations matching source pattern: ${colorizePath(pattern)}`,\n { level: 'warn' }\n );\n }\n\n const dictionaries: Dictionary[] = [];\n\n for (const { path, key, locale: entryLocale } 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 // Use the per-entry locale discovered from the file path. If a fixed\n // locale override was provided, use it only as a fallback.\n const entryUsedLocale = (locale ?? entryLocale) as Locale;\n\n const dictionary: Dictionary = {\n key,\n locale: entryUsedLocale,\n fill: filePath,\n format: 'po',\n localId: `${key}::${location}::${filePath}` as LocalDictionaryId,\n location: location as Dictionary['location'],\n filled:\n entryUsedLocale !== 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};\n"],"mappings":";;;;;;;;;;;AAmBA,MAAM,eAAe,OACnB,QACA,kBAC4B;CAC5B,MAAM,EAAE,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AU,WAAW;EACrC,UAAU;EACV,UAAU;EACV,GAAG;EACJ;AAED,QAAO;EACL,MAAM;EAEN,kBAAkB,OAAO,EAAE,oBAAoB;GAC7C,MAAM,sDAAyB,cAAc;GAC7C,MAAM,kBAAmC,MAAM,mBAC7C,QAAQ,QACR,cACD;AAED,OAAI,gBAAgB,WAAW,EAM7B,WACE,yGAA4E,uDANnC,QAAQ,QAAQ;IACzD,KAAK;IACL,QAAQ;IACT,CAAkC,CAGmD,IACpF,EAAE,OAAO,QAAQ,CAClB;GAGH,MAAM,eAA6B,EAAE;AAErC,QAAK,MAAM,EAAE,MAAM,KAAK,QAAQ,iBAAiB,iBAAiB;IAChE,IAAI;AACJ,QAAI;AAEF,iBAAYC,uBAAQ,qCADe,MAAM,QAAQ,CACjB;YAC1B;AACN,iBAAY,EAAE;;IAGhB,MAAM,mCAAoB,cAAc,OAAO,SAAS,KAAK;IAI7D,MAAM,kBAAmB,UAAU;IAEnC,MAAM,aAAyB;KAC7B;KACA,QAAQ;KACR,MAAM;KACN,QAAQ;KACR,SAAS,GAAG,IAAI,IAAI,SAAS,IAAI;KACvB;KACV,QACE,oBAAoB,cAAc,qBAAqB,gBACnD,OACA;KACN,SAAS;KACT;KACA;KACD;AAED,iBAAa,KAAK,WAAW;;AAG/B,UAAO;;EAEV"}
1
+ {"version":3,"file":"loadPO.cjs","names":["poCodec"],"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,iEACJ;CACf,MAAM;CACN,+DAA2B;EACzB,QAAQ,QAAQ;EAChB,OAAOA;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,86 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+
3
+ //#region src/poFormat.ts
4
+ const unescapePO = (str) => str.replace(/\\n/g, "\n").replace(/\\t/g, " ").replace(/\\r/g, "\r").replace(/\\"/g, "\"").replace(/\\\\/g, "\\");
5
+ const escapePO = (str) => str.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\r/g, "\\r");
6
+ /**
7
+ * Parse a PO file string into a flat msgid → msgstr record.
8
+ * Skips the PO header (msgid ""), comment lines, and plural/context keywords.
9
+ */
10
+ const parsePO = (fileContent) => {
11
+ const result = {};
12
+ const lines = fileContent.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
13
+ let msgid = "";
14
+ let msgstr = "";
15
+ let currentField = null;
16
+ const finalize = () => {
17
+ if (msgid !== "") result[msgid] = msgstr;
18
+ msgid = "";
19
+ msgstr = "";
20
+ currentField = null;
21
+ };
22
+ for (const line of lines) {
23
+ if (line.startsWith("#")) continue;
24
+ if (line.trim() === "") {
25
+ finalize();
26
+ continue;
27
+ }
28
+ const msgidMatch = line.match(/^msgid\s+"((?:[^"\\]|\\.)*)"$/);
29
+ if (msgidMatch?.[1]) {
30
+ finalize();
31
+ msgid = unescapePO(msgidMatch[1]);
32
+ currentField = "msgid";
33
+ continue;
34
+ }
35
+ const msgstrMatch = line.match(/^msgstr\s+"((?:[^"\\]|\\.)*)"$/);
36
+ if (msgstrMatch?.[1]) {
37
+ msgstr = unescapePO(msgstrMatch[1]);
38
+ currentField = "msgstr";
39
+ continue;
40
+ }
41
+ const contMatch = line.match(/^"((?:[^"\\]|\\.)*)"$/);
42
+ if (contMatch?.[1]) {
43
+ if (currentField === "msgid") msgid += unescapePO(contMatch[1]);
44
+ else if (currentField === "msgstr") msgstr += unescapePO(contMatch[1]);
45
+ continue;
46
+ }
47
+ currentField = null;
48
+ }
49
+ finalize();
50
+ return result;
51
+ };
52
+ /**
53
+ * Serialize a flat key → value record to PO file format.
54
+ * Non-string values are silently skipped.
55
+ */
56
+ const serializePO = (content, locale) => {
57
+ const lines = [];
58
+ lines.push("msgid \"\"");
59
+ lines.push("msgstr \"\"");
60
+ lines.push("\"Content-Type: text/plain; charset=UTF-8\\n\"");
61
+ lines.push("\"Content-Transfer-Encoding: 8bit\\n\"");
62
+ if (locale) lines.push(`"Language: ${locale}\\n"`);
63
+ lines.push("\"MIME-Version: 1.0\\n\"");
64
+ lines.push("");
65
+ for (const [msgid, msgstr] of Object.entries(content)) {
66
+ if (typeof msgstr !== "string") continue;
67
+ lines.push(`msgid "${escapePO(msgid)}"`);
68
+ lines.push(`msgstr "${escapePO(msgstr)}"`);
69
+ lines.push("");
70
+ }
71
+ return `${lines.join("\n")}\n`;
72
+ };
73
+ /**
74
+ * PO payload codec bridging {@link parsePO} / {@link serializePO} to the
75
+ * sync-plugin kit.
76
+ */
77
+ const poCodec = {
78
+ parse: parsePO,
79
+ serialize: (content, { locale }) => serializePO(content, locale)
80
+ };
81
+
82
+ //#endregion
83
+ exports.parsePO = parsePO;
84
+ exports.poCodec = poCodec;
85
+ exports.serializePO = serializePO;
86
+ //# sourceMappingURL=poFormat.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"poFormat.cjs","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"}
@@ -1,254 +1,38 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
3
- let node_fs_promises = require("node:fs/promises");
4
- let node_path = require("node:path");
5
- let _intlayer_config_logger = require("@intlayer/config/logger");
2
+ const require_poFormat = require('./poFormat.cjs');
3
+ let _intlayer_engine_syncPluginKit = require("@intlayer/engine/syncPluginKit");
6
4
  let _intlayer_config_utils = require("@intlayer/config/utils");
7
- let fast_glob = require("fast-glob");
8
- fast_glob = require_runtime.__toESM(fast_glob);
9
5
 
10
6
  //#region src/syncPO.ts
11
- const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
12
- const extractKeyAndLocaleFromPath = (filePath, maskPattern, locales, defaultLocale) => {
13
- const keyPlaceholder = "{{__KEY__}}";
14
- const localePlaceholder = "{{__LOCALE__}}";
15
- const normalize = (path) => path.startsWith("./") ? path.slice(2) : path;
16
- const normalizedFilePath = normalize(filePath);
17
- const normalizedMask = normalize(maskPattern);
18
- const localesAlternation = locales.join("|");
19
- let regexStr = `^${escapeRegex(normalizedMask)}$`;
20
- regexStr = regexStr.replace(/\\\*\\\*/g, ".*");
21
- regexStr = regexStr.replace(/\\\*/g, "[^/]*");
22
- regexStr = regexStr.replace(escapeRegex(localePlaceholder), `(?<locale>${localesAlternation})`);
23
- if (normalizedMask.includes(keyPlaceholder)) regexStr = regexStr.replace(escapeRegex(keyPlaceholder), "(?<key>.+)");
24
- const match = new RegExp(regexStr).exec(normalizedFilePath);
25
- if (!match?.groups) return null;
26
- let locale = match.groups.locale;
27
- let key = match.groups.key ?? "index";
28
- if (typeof key === "undefined") key = "index";
29
- if (typeof locale === "undefined") locale = defaultLocale;
30
- return {
31
- key,
32
- locale
33
- };
34
- };
35
- const unescapePO = (str) => str.replace(/\\n/g, "\n").replace(/\\t/g, " ").replace(/\\r/g, "\r").replace(/\\"/g, "\"").replace(/\\\\/g, "\\");
36
- const escapePO = (str) => str.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\r/g, "\\r");
37
- /**
38
- * Parse a PO file string into a flat msgid → msgstr record.
39
- * Skips the PO header (msgid ""), comment lines, and plural/context keywords.
40
- */
41
- const parsePO = (fileContent) => {
42
- const result = {};
43
- const lines = fileContent.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
44
- let msgid = "";
45
- let msgstr = "";
46
- let currentField = null;
47
- const finalize = () => {
48
- if (msgid !== "") result[msgid] = msgstr;
49
- msgid = "";
50
- msgstr = "";
51
- currentField = null;
52
- };
53
- for (const line of lines) {
54
- if (line.startsWith("#")) continue;
55
- if (line.trim() === "") {
56
- finalize();
57
- continue;
58
- }
59
- const msgidMatch = line.match(/^msgid\s+"((?:[^"\\]|\\.)*)"$/);
60
- if (msgidMatch?.[1]) {
61
- finalize();
62
- msgid = unescapePO(msgidMatch[1]);
63
- currentField = "msgid";
64
- continue;
65
- }
66
- const msgstrMatch = line.match(/^msgstr\s+"((?:[^"\\]|\\.)*)"$/);
67
- if (msgstrMatch?.[1]) {
68
- msgstr = unescapePO(msgstrMatch[1]);
69
- currentField = "msgstr";
70
- continue;
71
- }
72
- const contMatch = line.match(/^"((?:[^"\\]|\\.)*)"$/);
73
- if (contMatch?.[1]) {
74
- if (currentField === "msgid") msgid += unescapePO(contMatch[1]);
75
- else if (currentField === "msgstr") msgstr += unescapePO(contMatch[1]);
76
- continue;
77
- }
78
- currentField = null;
79
- }
80
- finalize();
81
- return result;
82
- };
83
7
  /**
84
- * Serialize a flat key value record to PO file format.
85
- * Non-string values are silently skipped.
8
+ * Two-way PO synchronization plugin: ingests gettext PO files as dictionaries
9
+ * and writes the merged build output back to the same files.
86
10
  */
87
- const serializePO = (content, locale) => {
88
- const lines = [];
89
- lines.push("msgid \"\"");
90
- lines.push("msgstr \"\"");
91
- lines.push("\"Content-Type: text/plain; charset=UTF-8\\n\"");
92
- lines.push("\"Content-Transfer-Encoding: 8bit\\n\"");
93
- if (locale) lines.push(`"Language: ${locale}\\n"`);
94
- lines.push("\"MIME-Version: 1.0\\n\"");
95
- lines.push("");
96
- for (const [msgid, msgstr] of Object.entries(content)) {
97
- if (typeof msgstr !== "string") continue;
98
- lines.push(`msgid "${escapePO(msgid)}"`);
99
- lines.push(`msgstr "${escapePO(msgstr)}"`);
100
- lines.push("");
101
- }
102
- return `${lines.join("\n")}\n`;
103
- };
104
- const listMessages = async (source, configuration) => {
105
- const { system, internationalization } = configuration;
106
- const { baseDir } = system;
107
- const { locales } = internationalization;
108
- const result = {};
109
- for (const locale of locales) {
110
- const globPatternLocale = await (0, _intlayer_config_utils.parseFilePathPattern)(source, {
111
- key: "**",
112
- locale
113
- });
114
- const maskPatternLocale = await (0, _intlayer_config_utils.parseFilePathPattern)(source, {
115
- key: "{{__KEY__}}",
116
- locale
117
- });
118
- if (!globPatternLocale || !maskPatternLocale) continue;
119
- const files = await (0, fast_glob.default)(globPatternLocale.startsWith("./") ? globPatternLocale.slice(2) : globPatternLocale, { cwd: baseDir });
120
- for (const file of files) {
121
- const extraction = extractKeyAndLocaleFromPath(file, maskPatternLocale, locales, locale);
122
- if (!extraction) continue;
123
- const { key, locale: extractedLocale } = extraction;
124
- const expectedPath = await (0, _intlayer_config_utils.parseFilePathPattern)(source, {
125
- key,
126
- locale: extractedLocale
127
- });
128
- const absoluteFoundPath = (0, node_path.isAbsolute)(file) ? file : (0, node_path.resolve)(baseDir, file);
129
- if (absoluteFoundPath !== ((0, node_path.isAbsolute)(expectedPath) ? expectedPath : (0, node_path.resolve)(baseDir, expectedPath))) continue;
130
- const usedLocale = extractedLocale;
131
- if (!result[usedLocale]) result[usedLocale] = {};
132
- result[usedLocale][key] = absoluteFoundPath;
133
- }
134
- }
135
- const hasKeyInMask = (await (0, _intlayer_config_utils.parseFilePathPattern)(source, {
136
- key: "{{__KEY__}}",
137
- locale: locales[0]
138
- })).includes("{{__KEY__}}");
139
- const discoveredKeys = /* @__PURE__ */ new Set();
140
- for (const locale of Object.keys(result)) for (const key of Object.keys(result[locale] ?? {})) discoveredKeys.add(key);
141
- if (!hasKeyInMask) discoveredKeys.add("index");
142
- const keysToEnsure = discoveredKeys.size > 0 ? Array.from(discoveredKeys) : [];
143
- for (const locale of locales) {
144
- if (!result[locale]) result[locale] = {};
145
- for (const key of keysToEnsure) if (!result[locale][key]) {
146
- const builtPath = await (0, _intlayer_config_utils.parseFilePathPattern)(source, {
147
- key,
148
- locale
149
- });
150
- const absoluteBuiltPath = (0, node_path.isAbsolute)(builtPath) ? builtPath : (0, node_path.resolve)(baseDir, builtPath);
151
- result[locale][key] = absoluteBuiltPath;
152
- }
153
- }
154
- return result;
155
- };
156
- const loadMessagePathMap = async (source, configuration) => {
157
- const messages = await listMessages(source, configuration);
158
- return Object.entries(messages).flatMap(([locale, keysRecord]) => Object.entries(keysRecord).map(([key, path]) => {
159
- return {
160
- path: (0, node_path.isAbsolute)(path) ? path : (0, node_path.resolve)(configuration.system.baseDir, path),
161
- locale,
162
- key
163
- };
164
- }));
165
- };
166
11
  const syncPO = async (options) => {
167
- const { location, priority } = {
168
- location: `sync-po::${await (0, _intlayer_config_utils.parseFilePathPattern)(options.source, {
169
- key: "{{key}}",
170
- locale: "{{locale}}"
171
- })}`,
172
- priority: 0,
173
- ...options
174
- };
175
- return {
12
+ const defaultLocation = `sync-po::${await (0, _intlayer_config_utils.parseFilePathPattern)(options.source, (0, _intlayer_engine_syncPluginKit.buildFilePathPatternContext)("{{key}}", "{{locale}}"))}`;
13
+ return (0, _intlayer_engine_syncPluginKit.createSyncPlugin)({
176
14
  name: "sync-po",
177
- loadDictionaries: async ({ configuration }) => {
178
- const appLogger = (0, _intlayer_config_logger.getAppLogger)(configuration);
179
- const dictionariesMap = await loadMessagePathMap(options.source, configuration);
180
- if (dictionariesMap.length === 0) appLogger(`[sync-po] No dictionaries found at locations matching source pattern: ${(0, _intlayer_config_logger.colorizePath)(await (0, _intlayer_config_utils.parseFilePathPattern)(options.source, {
181
- key: "{{key}}",
182
- locale: "{{locale}}"
183
- }))}`, { level: "warn" });
184
- let fill = await (0, _intlayer_config_utils.parseFilePathPattern)(options.source, {
185
- key: "{{key}}",
186
- locale: "{{locale}}"
187
- });
188
- if (fill) fill = (0, node_path.relative)(configuration.system.baseDir, (0, node_path.resolve)(configuration.system.baseDir, fill));
189
- const dictionaries = [];
190
- for (const { locale, path, key } of dictionariesMap) {
191
- let poContent;
192
- try {
193
- poContent = parsePO(await (0, node_fs_promises.readFile)(path, "utf-8"));
194
- } catch {
195
- poContent = {};
196
- }
197
- const filePath = (0, node_path.relative)(configuration.system.baseDir, path);
198
- const dictionary = {
199
- key,
200
- locale,
201
- fill,
202
- format: "po",
203
- localId: `${key}::${location}::${filePath}`,
204
- location,
205
- filled: locale !== configuration.internationalization.defaultLocale ? true : void 0,
206
- content: poContent,
207
- filePath,
208
- priority
209
- };
210
- dictionaries.push(dictionary);
211
- }
212
- return dictionaries;
213
- },
214
- formatOutput: async ({ dictionary, configuration }) => {
215
- const { formatDictionaryOutput } = await import("@intlayer/engine/build");
216
- if (!dictionary.filePath || !dictionary.locale) return dictionary;
217
- const builderPath = await (0, _intlayer_config_utils.parseFilePathPattern)(options.source, {
218
- key: dictionary.key,
219
- locale: dictionary.locale
220
- });
221
- if ((0, node_path.resolve)(configuration.system.baseDir, builderPath) !== (0, node_path.resolve)(configuration.system.baseDir, dictionary.filePath)) return dictionary;
222
- return formatDictionaryOutput(dictionary, "po").content;
223
- },
224
- afterBuild: async ({ dictionaries, configuration }) => {
225
- const { getPerLocaleDictionary } = await import("@intlayer/core/plugins");
226
- const { parallelize } = await import("@intlayer/engine/utils");
227
- const { formatDictionaryOutput } = await import("@intlayer/engine/build");
228
- const { locales } = configuration.internationalization;
229
- await parallelize(Object.entries(dictionaries.mergedDictionaries).flatMap(([key, dictionary]) => locales.map((locale) => ({
230
- key,
231
- dictionary: dictionary.dictionary,
232
- locale
233
- }))), async ({ key, dictionary, locale }) => {
234
- if (dictionary.location !== location) return;
235
- const builderPath = await (0, _intlayer_config_utils.parseFilePathPattern)(options.source, {
236
- key,
237
- locale
238
- });
239
- const formattedOutput = formatDictionaryOutput(getPerLocaleDictionary(dictionary, locale), "po");
240
- const content = JSON.parse(JSON.stringify(formattedOutput.content));
241
- if (typeof content === "undefined" || typeof content === "object" && Object.keys(content).length === 0) return;
242
- await (0, node_fs_promises.mkdir)((0, node_path.dirname)(builderPath), { recursive: true });
243
- await (0, node_fs_promises.writeFile)(builderPath, serializePO(content, locale), "utf-8");
244
- });
245
- }
246
- };
15
+ adapter: (0, _intlayer_engine_syncPluginKit.createFileAdapter)({
16
+ source: options.source,
17
+ codec: require_poFormat.poCodec,
18
+ discovery: "strict"
19
+ }),
20
+ direction: "both",
21
+ location: options.location ?? defaultLocation,
22
+ priority: options.priority ?? 0,
23
+ format: "po",
24
+ splitKeys: false
25
+ });
247
26
  };
248
27
 
249
28
  //#endregion
250
- exports.extractKeyAndLocaleFromPath = extractKeyAndLocaleFromPath;
251
- exports.parsePO = parsePO;
252
- exports.serializePO = serializePO;
29
+ Object.defineProperty(exports, 'extractKeyAndLocaleFromPath', {
30
+ enumerable: true,
31
+ get: function () {
32
+ return _intlayer_engine_syncPluginKit.extractKeyAndLocaleFromPath;
33
+ }
34
+ });
35
+ exports.parsePO = require_poFormat.parsePO;
36
+ exports.serializePO = require_poFormat.serializePO;
253
37
  exports.syncPO = syncPO;
254
38
  //# sourceMappingURL=syncPO.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"syncPO.cjs","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/E,MAAa,+BACX,UACA,aACA,SACA,kBAC2C;CAC3C,MAAM,iBAAiB;CACvB,MAAM,oBAAoB;CAG1B,MAAM,aAAa,SACjB,KAAK,WAAW,KAAK,GAAG,KAAK,MAAM,EAAE,GAAG;CAE1C,MAAM,qBAAqB,UAAU,SAAS;CAC9C,MAAM,iBAAiB,UAAU,YAAY;CAE7C,MAAM,qBAAqB,QAAQ,KAAK,IAAI;CAI5C,IAAI,WAAW,IAAI,YAAY,eAAe,CAAC;AAC/C,YAAW,SAAS,QAAQ,aAAa,KAAK;AAC9C,YAAW,SAAS,QAAQ,SAAS,QAAQ;AAE7C,YAAW,SAAS,QAClB,YAAY,kBAAkB,EAC9B,aAAa,mBAAmB,GACjC;AAED,KAAI,eAAe,SAAS,eAAe,CACzC,YAAW,SAAS,QAAQ,YAAY,eAAe,EAAE,aAAa;CAIxE,MAAM,QAAQ,IADQ,OAAO,SACN,CAAC,KAAK,mBAAmB;AAEhD,KAAI,CAAC,OAAO,OACV,QAAO;CAGT,IAAI,SAAS,MAAM,OAAO;CAC1B,IAAI,MAAO,MAAM,OAAO,OAA8B;AAEtD,KAAI,OAAO,QAAQ,YACjB,OAAM;AAGR,KAAI,OAAO,WAAW,YACpB,UAAS;AAGX,QAAO;EAAE;EAAK;EAAQ;;AAKxB,MAAM,cAAc,QAClB,IACG,QAAQ,QAAQ,KAAK,CACrB,QAAQ,QAAQ,IAA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D,MAAM,EAAE,gBAAgB,MAAM,OAAO;GACrC,MAAM,EAAE,2BAA2B,MAAM,OAAO;GAEhD,MAAM,EAAE,YAAY,cAAc;AAkBlC,SAAM,YAV2B,OAAO,QACtC,aAAa,mBACd,CAAC,SAAS,CAAC,KAAK,gBACf,QAAQ,KAAK,YAAY;IACvB;IACA,YAAY,WAAW;IACvB;IACD,EAAE,CAGuB,EAAE,OAAO,EAAE,KAAK,YAAY,aAAa;AAEnE,QAAI,WAAW,aAAa,SAC1B;IAGF,MAAM,cAAc,uDAA2B,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,6DAAoB,YAAY,EAAE,EAAE,WAAW,MAAM,CAAC;AAItD,0CAAgB,aAFE,YAAY,SAAS,OAED,EAAE,QAAQ;KAChD;;EAEL"}
1
+ {"version":3,"file":"syncPO.cjs","names":["poCodec"],"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,uDAHlC,QAAQ,wEACoB,WAAW,aAAa,CACrD;AAGD,6DAAwB;EACtB,MAAM;EACN,+DAA2B;GACzB,QAAQ,QAAQ;GAChB,OAAOA;GACP,WAAW;GACZ,CAAC;EACF,WAAW;EACX,UAAU,QAAQ,YAAY;EAC9B,UAAU,QAAQ,YAAY;EAC9B,QAAQ;EAGR,WAAW;EACZ,CAAC"}
@@ -1,4 +1,5 @@
1
- import { extractKeyAndLocaleFromPath, parsePO, serializePO, syncPO } from "./syncPO.mjs";
1
+ import { parsePO, poCodec, serializePO } from "./poFormat.mjs";
2
2
  import { loadPO } from "./loadPO.mjs";
3
+ import { extractKeyAndLocaleFromPath, syncPO } from "./syncPO.mjs";
3
4
 
4
- export { extractKeyAndLocaleFromPath, loadPO, parsePO, serializePO, syncPO };
5
+ export { extractKeyAndLocaleFromPath, loadPO, parsePO, poCodec, serializePO, syncPO };