@intlayer/cli 8.4.0 → 8.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/dist/cjs/IntlayerEventListener.cjs +1 -1
  2. package/dist/cjs/IntlayerEventListener.cjs.map +1 -1
  3. package/dist/cjs/_utils_asset-ghp_Cjwk.cjs +2 -0
  4. package/dist/cjs/auth/login.cjs +1 -1
  5. package/dist/cjs/auth/login.cjs.map +1 -1
  6. package/dist/cjs/build.cjs +1 -1
  7. package/dist/cjs/build.cjs.map +1 -1
  8. package/dist/cjs/{_virtual/_rolldown/runtime.cjs → chunk-Bmb41Sf3.cjs} +1 -1
  9. package/dist/cjs/ci.cjs +1 -1
  10. package/dist/cjs/ci.cjs.map +1 -1
  11. package/dist/cjs/cli.cjs +1 -1
  12. package/dist/cjs/cli.cjs.map +1 -1
  13. package/dist/cjs/config.cjs +1 -1
  14. package/dist/cjs/config.cjs.map +1 -1
  15. package/dist/cjs/editor.cjs +1 -1
  16. package/dist/cjs/editor.cjs.map +1 -1
  17. package/dist/cjs/extract.cjs +1 -1
  18. package/dist/cjs/extract.cjs.map +1 -1
  19. package/dist/cjs/fill/fill.cjs +1 -1
  20. package/dist/cjs/fill/fill.cjs.map +1 -1
  21. package/dist/cjs/fill/formatAutoFilledFilePath.cjs +1 -1
  22. package/dist/cjs/fill/formatAutoFilledFilePath.cjs.map +1 -1
  23. package/dist/cjs/fill/formatFillData.cjs +1 -1
  24. package/dist/cjs/fill/formatFillData.cjs.map +1 -1
  25. package/dist/cjs/fill/listTranslationsTasks.cjs +1 -1
  26. package/dist/cjs/fill/listTranslationsTasks.cjs.map +1 -1
  27. package/dist/cjs/fill/translateDictionary.cjs +1 -1
  28. package/dist/cjs/fill/translateDictionary.cjs.map +1 -1
  29. package/dist/cjs/fill/writeFill.cjs +1 -1
  30. package/dist/cjs/fill/writeFill.cjs.map +1 -1
  31. package/dist/cjs/getTargetDictionary.cjs +1 -1
  32. package/dist/cjs/getTargetDictionary.cjs.map +1 -1
  33. package/dist/cjs/init.cjs +1 -1
  34. package/dist/cjs/init.cjs.map +1 -1
  35. package/dist/cjs/initMCP.cjs +1 -1
  36. package/dist/cjs/initMCP.cjs.map +1 -1
  37. package/dist/cjs/initSkills.cjs +1 -1
  38. package/dist/cjs/initSkills.cjs.map +1 -1
  39. package/dist/cjs/listContentDeclaration.cjs +1 -1
  40. package/dist/cjs/listContentDeclaration.cjs.map +1 -1
  41. package/dist/cjs/listProjects.cjs +1 -1
  42. package/dist/cjs/listProjects.cjs.map +1 -1
  43. package/dist/cjs/liveSync.cjs +1 -1
  44. package/dist/cjs/liveSync.cjs.map +1 -1
  45. package/dist/cjs/pull.cjs +1 -1
  46. package/dist/cjs/pull.cjs.map +1 -1
  47. package/dist/cjs/push/pullLog.cjs +1 -1
  48. package/dist/cjs/push/pullLog.cjs.map +1 -1
  49. package/dist/cjs/push/push.cjs +1 -1
  50. package/dist/cjs/push/push.cjs.map +1 -1
  51. package/dist/cjs/pushConfig.cjs +1 -1
  52. package/dist/cjs/pushConfig.cjs.map +1 -1
  53. package/dist/cjs/pushLog.cjs +1 -1
  54. package/dist/cjs/pushLog.cjs.map +1 -1
  55. package/dist/cjs/reviewDoc/reviewDoc.cjs +1 -1
  56. package/dist/cjs/reviewDoc/reviewDoc.cjs.map +1 -1
  57. package/dist/cjs/reviewDoc/reviewDocBlockAware.cjs +1 -1
  58. package/dist/cjs/reviewDoc/reviewDocBlockAware.cjs.map +1 -1
  59. package/dist/cjs/searchDoc.cjs +1 -1
  60. package/dist/cjs/searchDoc.cjs.map +1 -1
  61. package/dist/cjs/test/listMissingTranslations.cjs +1 -1
  62. package/dist/cjs/test/listMissingTranslations.cjs.map +1 -1
  63. package/dist/cjs/test/test.cjs +1 -1
  64. package/dist/cjs/test/test.cjs.map +1 -1
  65. package/dist/cjs/translateDoc/index.cjs +1 -1
  66. package/dist/cjs/translateDoc/translateDoc.cjs +1 -1
  67. package/dist/cjs/translateDoc/translateDoc.cjs.map +1 -1
  68. package/dist/cjs/translateDoc/translateFile.cjs +1 -1
  69. package/dist/cjs/translateDoc/translateFile.cjs.map +1 -1
  70. package/dist/cjs/translation-alignment/fingerprintBlock.cjs +1 -1
  71. package/dist/cjs/translation-alignment/fingerprintBlock.cjs.map +1 -1
  72. package/dist/cjs/utils/calculateChunks.cjs +1 -1
  73. package/dist/cjs/utils/calculateChunks.cjs.map +1 -1
  74. package/dist/cjs/utils/checkAccess.cjs +1 -1
  75. package/dist/cjs/utils/checkAccess.cjs.map +1 -1
  76. package/dist/cjs/utils/checkLastUpdateTime.cjs +1 -1
  77. package/dist/cjs/utils/checkLastUpdateTime.cjs.map +1 -1
  78. package/dist/cjs/utils/chunkInference.cjs +1 -1
  79. package/dist/cjs/utils/chunkInference.cjs.map +1 -1
  80. package/dist/cjs/utils/getIsFileUpdatedRecently.cjs +1 -1
  81. package/dist/cjs/utils/getIsFileUpdatedRecently.cjs.map +1 -1
  82. package/dist/cjs/utils/getParentPackageJSON.cjs +1 -1
  83. package/dist/cjs/utils/getParentPackageJSON.cjs.map +1 -1
  84. package/dist/cjs/utils/mapChunksBetweenFiles.cjs +1 -1
  85. package/dist/cjs/utils/mapChunksBetweenFiles.cjs.map +1 -1
  86. package/dist/cjs/utils/openBrowser.cjs +1 -1
  87. package/dist/cjs/utils/openBrowser.cjs.map +1 -1
  88. package/dist/cjs/utils/setupAI.cjs +1 -1
  89. package/dist/cjs/utils/setupAI.cjs.map +1 -1
  90. package/dist/cjs/watch.cjs +1 -1
  91. package/dist/cjs/watch.cjs.map +1 -1
  92. package/dist/esm/{_virtual/_utils_asset.mjs → _utils_asset-B187VPMw.mjs} +1 -1
  93. package/dist/esm/cli.mjs +1 -1
  94. package/dist/esm/cli.mjs.map +1 -1
  95. package/dist/esm/editor-D8BGlLzF.mjs +2 -0
  96. package/dist/esm/editor-D8BGlLzF.mjs.map +1 -0
  97. package/dist/esm/editor.mjs +1 -2
  98. package/dist/esm/index.mjs +1 -1
  99. package/dist/esm/reviewDoc/reviewDoc.mjs +1 -1
  100. package/dist/esm/reviewDoc/reviewDoc.mjs.map +1 -1
  101. package/dist/esm/reviewDoc/reviewDocBlockAware.mjs +1 -1
  102. package/dist/esm/reviewDoc/reviewDocBlockAware.mjs.map +1 -1
  103. package/dist/esm/translateDoc/index.mjs +1 -1
  104. package/dist/esm/translateDoc/translateDoc.mjs +1 -1
  105. package/dist/esm/translateDoc/translateDoc.mjs.map +1 -1
  106. package/dist/esm/translateDoc/translateFile.mjs +1 -1
  107. package/dist/esm/translateDoc/translateFile.mjs.map +1 -1
  108. package/dist/types/fill/fill.d.ts +1 -1
  109. package/dist/types/fill/translateDictionary.d.ts +1 -1
  110. package/dist/types/getTargetDictionary-RBSRtaQj.d.ts +19 -0
  111. package/dist/types/getTargetDictionary-RBSRtaQj.d.ts.map +1 -0
  112. package/dist/types/getTargetDictionary.d.ts +2 -19
  113. package/dist/types/index.d.ts +2 -2
  114. package/dist/types/listMissingTranslations-DxKw7nqI.d.ts +28 -0
  115. package/dist/types/listMissingTranslations-DxKw7nqI.d.ts.map +1 -0
  116. package/dist/types/reviewDoc/reviewDocBlockAware.d.ts +1 -1
  117. package/dist/types/setupAI-Bosjx7ah.d.ts +21 -0
  118. package/dist/types/setupAI-Bosjx7ah.d.ts.map +1 -0
  119. package/dist/types/test/index.d.ts +2 -2
  120. package/dist/types/test/listMissingTranslations.d.ts +2 -28
  121. package/dist/types/test/test.d.ts +2 -11
  122. package/dist/types/test-DUTiJR5_.d.ts +11 -0
  123. package/dist/types/test-DUTiJR5_.d.ts.map +1 -0
  124. package/dist/types/translateDoc/index.d.ts +1 -1
  125. package/dist/types/translateDoc/translateDoc.d.ts +1 -1
  126. package/dist/types/translateDoc/translateFile.d.ts +1 -1
  127. package/dist/types/translateDoc/types.d.ts +2 -48
  128. package/dist/types/types-BKvc3FmV.d.ts +48 -0
  129. package/dist/types/types-BKvc3FmV.d.ts.map +1 -0
  130. package/dist/types/utils/chunkInference.d.ts +1 -1
  131. package/dist/types/utils/setupAI.d.ts +2 -21
  132. package/package.json +12 -12
  133. package/dist/cjs/_virtual/_utils_asset.cjs +0 -2
  134. package/dist/esm/_virtual/_rolldown/runtime.mjs +0 -1
  135. package/dist/esm/editor.mjs.map +0 -1
  136. package/dist/types/getTargetDictionary.d.ts.map +0 -1
  137. package/dist/types/test/listMissingTranslations.d.ts.map +0 -1
  138. package/dist/types/test/test.d.ts.map +0 -1
  139. package/dist/types/translateDoc/types.d.ts.map +0 -1
  140. package/dist/types/utils/setupAI.d.ts.map +0 -1
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./_virtual/_rolldown/runtime.cjs`);let e=require(`node:path`),t=require(`@intlayer/chokidar/utils`),n=require(`@intlayer/config/logger`),r=require(`@intlayer/config/node`),i=require(`@intlayer/unmerged-dictionaries-entry`);const a=t=>{let n=(0,r.getConfiguration)(t?.configOptions),a=(0,i.getUnmergedDictionaries)(n);return Object.values(a).flat().map(r=>({key:r.key??``,path:t?.absolute?r.filePath??`Remote`:(0,e.relative)(n.system.baseDir,r.filePath??`Remote`)}))},o=e=>{let i=a(e);if(e?.json){console.log(JSON.stringify(i));return}let o=(0,n.getAppLogger)((0,r.getConfiguration)(e?.configOptions)),s=i.map(e=>[(0,n.colon)(` - ${(0,n.colorizeKey)(e.key)}`,{colSize:i.map(e=>e.key.length),maxSize:60}),` - `,(0,t.formatPath)(e.path)].join(``));o(`Content declaration files:`),s.forEach(e=>{o(e,{level:`info`})}),o(`Total content declaration files: ${(0,n.colorizeNumber)(i.length)}`)};exports.listContentDeclaration=o,exports.listContentDeclarationRows=a;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./chunk-Bmb41Sf3.cjs`);let e=require(`node:path`),t=require(`@intlayer/chokidar/utils`),n=require(`@intlayer/config/logger`),r=require(`@intlayer/config/node`),i=require(`@intlayer/unmerged-dictionaries-entry`);const a=t=>{let n=(0,r.getConfiguration)(t?.configOptions),a=(0,i.getUnmergedDictionaries)(n);return Object.values(a).flat().map(r=>({key:r.key??``,path:t?.absolute?r.filePath??`Remote`:(0,e.relative)(n.system.baseDir,r.filePath??`Remote`)}))},o=e=>{let i=a(e);if(e?.json){console.log(JSON.stringify(i));return}let o=(0,n.getAppLogger)((0,r.getConfiguration)(e?.configOptions)),s=i.map(e=>[(0,n.colon)(` - ${(0,n.colorizeKey)(e.key)}`,{colSize:i.map(e=>e.key.length),maxSize:60}),` - `,(0,t.formatPath)(e.path)].join(``));o(`Content declaration files:`),s.forEach(e=>{o(e,{level:`info`})}),o(`Total content declaration files: ${(0,n.colorizeNumber)(i.length)}`)};exports.listContentDeclaration=o,exports.listContentDeclarationRows=a;
2
2
  //# sourceMappingURL=listContentDeclaration.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"listContentDeclaration.cjs","names":[],"sources":["../../src/listContentDeclaration.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport { formatPath } from '@intlayer/chokidar/utils';\nimport {\n colon,\n colorizeKey,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\n\ntype ListContentDeclarationOptions = {\n configOptions?: GetConfigurationOptions;\n json?: boolean;\n absolute?: boolean;\n};\n\nexport const listContentDeclarationRows = (\n options?: ListContentDeclarationOptions\n) => {\n const config = getConfiguration(options?.configOptions);\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(config);\n\n const rows = Object.values(unmergedDictionariesRecord)\n .flat()\n .map((dictionary) => ({\n key: dictionary.key ?? '',\n path: options?.absolute\n ? (dictionary.filePath ?? 'Remote')\n : relative(config.system.baseDir, dictionary.filePath ?? 'Remote'),\n }));\n return rows;\n};\n\nexport const listContentDeclaration = (\n options?: ListContentDeclarationOptions\n) => {\n const rows = listContentDeclarationRows(options);\n\n if (options?.json) {\n console.log(JSON.stringify(rows));\n return;\n }\n\n const config = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(config);\n\n const lines = rows.map((row) =>\n [\n colon(` - ${colorizeKey(row.key)}`, {\n colSize: rows.map((row) => row.key.length),\n maxSize: 60,\n }),\n ' - ',\n formatPath(row.path),\n ].join('')\n );\n\n appLogger(`Content declaration files:`);\n\n lines.forEach((line) => {\n appLogger(line, {\n level: 'info',\n });\n });\n\n appLogger(`Total content declaration files: ${colorizeNumber(rows.length)}`);\n};\n"],"mappings":"2SAoBA,MAAa,EACX,GACG,CACH,IAAM,GAAA,EAAA,EAAA,kBAA0B,GAAS,cAAc,CAEjD,GAAA,EAAA,EAAA,yBAAqD,EAAO,CAUlE,OARa,OAAO,OAAO,EAA2B,CACnD,MAAM,CACN,IAAK,IAAgB,CACpB,IAAK,EAAW,KAAO,GACvB,KAAM,GAAS,SACV,EAAW,UAAY,UAAA,EAAA,EAAA,UACf,EAAO,OAAO,QAAS,EAAW,UAAY,SAAS,CACrE,EAAE,EAIM,EACX,GACG,CACH,IAAM,EAAO,EAA2B,EAAQ,CAEhD,GAAI,GAAS,KAAM,CACjB,QAAQ,IAAI,KAAK,UAAU,EAAK,CAAC,CACjC,OAIF,IAAM,GAAA,EAAA,EAAA,eAAA,EAAA,EAAA,kBAD0B,GAAS,cAAc,CACjB,CAEhC,EAAQ,EAAK,IAAK,GACtB,aACQ,OAAA,EAAA,EAAA,aAAkB,EAAI,IAAI,GAAI,CAClC,QAAS,EAAK,IAAK,GAAQ,EAAI,IAAI,OAAO,CAC1C,QAAS,GACV,CAAC,CACF,uBACW,EAAI,KAAK,CACrB,CAAC,KAAK,GAAG,CACX,CAED,EAAU,6BAA6B,CAEvC,EAAM,QAAS,GAAS,CACtB,EAAU,EAAM,CACd,MAAO,OACR,CAAC,EACF,CAEF,EAAU,qCAAA,EAAA,EAAA,gBAAmD,EAAK,OAAO,GAAG"}
1
+ {"version":3,"file":"listContentDeclaration.cjs","names":[],"sources":["../../src/listContentDeclaration.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport { formatPath } from '@intlayer/chokidar/utils';\nimport {\n colon,\n colorizeKey,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\n\ntype ListContentDeclarationOptions = {\n configOptions?: GetConfigurationOptions;\n json?: boolean;\n absolute?: boolean;\n};\n\nexport const listContentDeclarationRows = (\n options?: ListContentDeclarationOptions\n) => {\n const config = getConfiguration(options?.configOptions);\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(config);\n\n const rows = Object.values(unmergedDictionariesRecord)\n .flat()\n .map((dictionary) => ({\n key: dictionary.key ?? '',\n path: options?.absolute\n ? (dictionary.filePath ?? 'Remote')\n : relative(config.system.baseDir, dictionary.filePath ?? 'Remote'),\n }));\n return rows;\n};\n\nexport const listContentDeclaration = (\n options?: ListContentDeclarationOptions\n) => {\n const rows = listContentDeclarationRows(options);\n\n if (options?.json) {\n console.log(JSON.stringify(rows));\n return;\n }\n\n const config = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(config);\n\n const lines = rows.map((row) =>\n [\n colon(` - ${colorizeKey(row.key)}`, {\n colSize: rows.map((row) => row.key.length),\n maxSize: 60,\n }),\n ' - ',\n formatPath(row.path),\n ].join('')\n );\n\n appLogger(`Content declaration files:`);\n\n lines.forEach((line) => {\n appLogger(line, {\n level: 'info',\n });\n });\n\n appLogger(`Total content declaration files: ${colorizeNumber(rows.length)}`);\n};\n"],"mappings":"+RAoBA,MAAa,EACX,GACG,CACH,IAAM,GAAA,EAAA,EAAA,kBAA0B,GAAS,cAAc,CAEjD,GAAA,EAAA,EAAA,yBAAqD,EAAO,CAUlE,OARa,OAAO,OAAO,EAA2B,CACnD,MAAM,CACN,IAAK,IAAgB,CACpB,IAAK,EAAW,KAAO,GACvB,KAAM,GAAS,SACV,EAAW,UAAY,UAAA,EAAA,EAAA,UACf,EAAO,OAAO,QAAS,EAAW,UAAY,SAAS,CACrE,EAAE,EAIM,EACX,GACG,CACH,IAAM,EAAO,EAA2B,EAAQ,CAEhD,GAAI,GAAS,KAAM,CACjB,QAAQ,IAAI,KAAK,UAAU,EAAK,CAAC,CACjC,OAIF,IAAM,GAAA,EAAA,EAAA,eAAA,EAAA,EAAA,kBAD0B,GAAS,cAAc,CACjB,CAEhC,EAAQ,EAAK,IAAK,GACtB,aACQ,OAAA,EAAA,EAAA,aAAkB,EAAI,IAAI,GAAI,CAClC,QAAS,EAAK,IAAK,GAAQ,EAAI,IAAI,OAAO,CAC1C,QAAS,GACV,CAAC,CACF,uBACW,EAAI,KAAK,CACrB,CAAC,KAAK,GAAG,CACX,CAED,EAAU,6BAA6B,CAEvC,EAAM,QAAS,GAAS,CACtB,EAAU,EAAM,CACd,MAAO,OACR,CAAC,EACF,CAEF,EAAU,qCAAA,EAAA,EAAA,gBAAmD,EAAK,OAAO,GAAG"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./_virtual/_rolldown/runtime.cjs`);let e=require(`node:path`),t=require(`@intlayer/chokidar/cli`);const n=async n=>{let{searchDir:r,projectsPath:i}=await(0,t.listProjects)(n),a=i.map(t=>n?.absolute?t:(0,e.relative)(r,t)).map(e=>e===``?`.`:e);if(n?.json){console.dir(a,{depth:null,arrayLimit:null});return}if(i.length===0){console.log(`No Intlayer projects found.`);return}console.log(`Found ${i.length} Intlayer project(s):\n`),i.forEach(e=>{console.log(` - ${e}`)})};exports.listProjectsCommand=n;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./chunk-Bmb41Sf3.cjs`);let e=require(`node:path`),t=require(`@intlayer/chokidar/cli`);const n=async n=>{let{searchDir:r,projectsPath:i}=await(0,t.listProjects)(n),a=i.map(t=>n?.absolute?t:(0,e.relative)(r,t)).map(e=>e===``?`.`:e);if(n?.json){console.dir(a,{depth:null,arrayLimit:null});return}if(i.length===0){console.log(`No Intlayer projects found.`);return}console.log(`Found ${i.length} Intlayer project(s):\n`),i.forEach(e=>{console.log(` - ${e}`)})};exports.listProjectsCommand=n;
2
2
  //# sourceMappingURL=listProjects.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"listProjects.cjs","names":[],"sources":["../../src/listProjects.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport { type ListProjectsOptions, listProjects } from '@intlayer/chokidar/cli';\n\nexport type ListProjectsCommandOptions = ListProjectsOptions & {\n json?: boolean;\n absolute?: boolean;\n};\n\nexport const listProjectsCommand = async (\n options?: ListProjectsCommandOptions\n) => {\n const { searchDir, projectsPath } = await listProjects(options);\n\n const projectsRelativePath = projectsPath\n .map((projectPath) =>\n options?.absolute ? projectPath : relative(searchDir, projectPath)\n )\n .map((projectPath) => (projectPath === '' ? '.' : projectPath));\n\n if (options?.json) {\n console.dir(projectsRelativePath, { depth: null, arrayLimit: null });\n return;\n }\n\n if (projectsPath.length === 0) {\n console.log('No Intlayer projects found.');\n return;\n }\n\n console.log(`Found ${projectsPath.length} Intlayer project(s):\\n`);\n projectsPath.forEach((project) => {\n console.log(` - ${project}`);\n });\n};\n"],"mappings":"8KAQA,MAAa,EAAsB,KACjC,IACG,CACH,GAAM,CAAE,YAAW,gBAAiB,MAAA,EAAA,EAAA,cAAmB,EAAQ,CAEzD,EAAuB,EAC1B,IAAK,GACJ,GAAS,SAAW,GAAA,EAAA,EAAA,UAAuB,EAAW,EAAY,CACnE,CACA,IAAK,GAAiB,IAAgB,GAAK,IAAM,EAAa,CAEjE,GAAI,GAAS,KAAM,CACjB,QAAQ,IAAI,EAAsB,CAAE,MAAO,KAAM,WAAY,KAAM,CAAC,CACpE,OAGF,GAAI,EAAa,SAAW,EAAG,CAC7B,QAAQ,IAAI,8BAA8B,CAC1C,OAGF,QAAQ,IAAI,SAAS,EAAa,OAAO,yBAAyB,CAClE,EAAa,QAAS,GAAY,CAChC,QAAQ,IAAI,OAAO,IAAU,EAC7B"}
1
+ {"version":3,"file":"listProjects.cjs","names":[],"sources":["../../src/listProjects.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport { type ListProjectsOptions, listProjects } from '@intlayer/chokidar/cli';\n\nexport type ListProjectsCommandOptions = ListProjectsOptions & {\n json?: boolean;\n absolute?: boolean;\n};\n\nexport const listProjectsCommand = async (\n options?: ListProjectsCommandOptions\n) => {\n const { searchDir, projectsPath } = await listProjects(options);\n\n const projectsRelativePath = projectsPath\n .map((projectPath) =>\n options?.absolute ? projectPath : relative(searchDir, projectPath)\n )\n .map((projectPath) => (projectPath === '' ? '.' : projectPath));\n\n if (options?.json) {\n console.dir(projectsRelativePath, { depth: null, arrayLimit: null });\n return;\n }\n\n if (projectsPath.length === 0) {\n console.log('No Intlayer projects found.');\n return;\n }\n\n console.log(`Found ${projectsPath.length} Intlayer project(s):\\n`);\n projectsPath.forEach((project) => {\n console.log(` - ${project}`);\n });\n};\n"],"mappings":"kKAQA,MAAa,EAAsB,KACjC,IACG,CACH,GAAM,CAAE,YAAW,gBAAiB,MAAA,EAAA,EAAA,cAAmB,EAAQ,CAEzD,EAAuB,EAC1B,IAAK,GACJ,GAAS,SAAW,GAAA,EAAA,EAAA,UAAuB,EAAW,EAAY,CACnE,CACA,IAAK,GAAiB,IAAgB,GAAK,IAAM,EAAa,CAEjE,GAAI,GAAS,KAAM,CACjB,QAAQ,IAAI,EAAsB,CAAE,MAAO,KAAM,WAAY,KAAM,CAAC,CACpE,OAGF,GAAI,EAAa,SAAW,EAAG,CAC7B,QAAQ,IAAI,8BAA8B,CAC1C,OAGF,QAAQ,IAAI,SAAS,EAAa,OAAO,yBAAyB,CAClE,EAAa,QAAS,GAAY,CAChC,QAAQ,IAAI,OAAO,IAAU,EAC7B"}
@@ -1,4 +1,4 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./_virtual/_rolldown/runtime.cjs`),t=require(`./IntlayerEventListener.cjs`);let n=require(`@intlayer/chokidar/build`),r=require(`@intlayer/chokidar/utils`),i=require(`@intlayer/config/logger`),a=require(`@intlayer/config/node`),o=require(`@intlayer/unmerged-dictionaries-entry`),s=require(`node:http`),c=require(`@intlayer/config/package.json`);c=e.__toESM(c);let l=require(`@intlayer/core/plugins`),u=require(`@intlayer/dictionaries-entry`);const d=async(e,t)=>{(0,i.getAppLogger)(t)(`Writing dictionary ${e.key}`),await(0,n.buildDictionary)([e],t)},f=async e=>{let n=(0,a.getConfiguration)(e?.configOptions),f=(0,i.getAppLogger)(n),{liveSyncPort:p,liveSyncURL:m}=n.editor,h=null,g=null;if(e?.with&&(h=(0,r.runParallel)(e.with),h.result.catch(()=>{})),n.editor.liveSync&&n.editor.backendURL&&n.editor.clientId&&n.editor.clientSecret){g=new t.IntlayerEventListener(n),g.onConnectionOpen=()=>{f(`Live sync connection established`)},g.onConnectionError=e=>{let t=e;f(`Live sync connection error: ${t.message??`Unknown error`}`,{level:`warn`}),(t.message?.includes(`terminated`)||t.message?.includes(`closed`))&&f(`Server connection was terminated, automatic reconnection will be attempted...`,{level:`info`})},g.onDictionaryAdded=e=>d(e,n),g.onDictionaryChange=e=>d(e,n),g.onDictionaryDeleted=e=>d(e,n);try{await g.initialize()}catch(e){f(`Failed to initialize IntlayerEventListener:`,{level:`error`}),f(`Error: ${e instanceof Error?e.message:String(e)}`,{level:`error`})}}else n.editor.liveSync?(!n.editor.clientId||!n.editor.clientSecret)&&f(`Missing client credentials for hot reload. Please configure clientId and clientSecret`):f(`Hot reload is disabled. Please enable it in the configuration (editor.liveSync).`);let _=(0,s.createServer)(async(e,t)=>{if(e.method===`OPTIONS`){t.writeHead(200,{"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`GET, POST, PUT, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization`}),t.end();return}if(e.url?.startsWith(`/dictionaries`)){t.writeHead(200,{"Content-Type":`application/json; charset=utf-8`,"Cache-Control":`no-store`,"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`GET, POST, PUT, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization`});let r=(0,u.getDictionaries)(n);if(e.url.startsWith(`/dictionaries/`)){let[n,i]=decodeURIComponent(e.url).slice(14).split(`/`),a=r[n]??null;if(i){let e=(0,l.getLocalizedContent)(a.content,i,{dictionaryKey:n,keyPath:[]});t.end(JSON.stringify(e));return}t.end(JSON.stringify(a));return}t.end(JSON.stringify(r));return}if(e.url?.startsWith(`/unmerged_dictionaries`)){t.writeHead(200,{"Content-Type":`application/json; charset=utf-8`,"Cache-Control":`no-store`,"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`GET, POST, PUT, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization`});let r=(0,o.getUnmergedDictionaries)(n);if(e.url.startsWith(`/unmerged_dictionaries/`)){let n=r[decodeURIComponent(e.url.slice(23))]??null;t.end(JSON.stringify(n));return}t.end(JSON.stringify(r));return}if(e.url===`/configuration`){t.writeHead(200,{"Content-Type":`application/json; charset=utf-8`,"Cache-Control":`no-store`,"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`GET, POST, PUT, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization`}),t.end(JSON.stringify(n));return}if(e.url===`/health`){t.writeHead(200,{"Content-Type":`application/json; charset=utf-8`}),t.end(JSON.stringify({status:`ok`}));return}t.end(`Not found`)}),v=()=>n.editor.liveSync?`\x1B[32m✓ Enabled\x1B[0m`:`\x1B[31m✗ Disabled\x1B[0m`;_.listen(p,()=>{console.log(`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./chunk-Bmb41Sf3.cjs`),t=require(`./IntlayerEventListener.cjs`);let n=require(`@intlayer/chokidar/build`),r=require(`@intlayer/chokidar/utils`),i=require(`@intlayer/config/logger`),a=require(`@intlayer/config/node`),o=require(`@intlayer/unmerged-dictionaries-entry`),s=require(`node:http`),c=require(`@intlayer/config/package.json`);c=e.t(c);let l=require(`@intlayer/core/plugins`),u=require(`@intlayer/dictionaries-entry`);const d=async(e,t)=>{(0,i.getAppLogger)(t)(`Writing dictionary ${e.key}`),await(0,n.buildDictionary)([e],t)},f=async e=>{let n=(0,a.getConfiguration)(e?.configOptions),f=(0,i.getAppLogger)(n),{liveSyncPort:p,liveSyncURL:m}=n.editor,h=null,g=null;if(e?.with&&(h=(0,r.runParallel)(e.with),h.result.catch(()=>{})),n.editor.liveSync&&n.editor.backendURL&&n.editor.clientId&&n.editor.clientSecret){g=new t.IntlayerEventListener(n),g.onConnectionOpen=()=>{f(`Live sync connection established`)},g.onConnectionError=e=>{let t=e;f(`Live sync connection error: ${t.message??`Unknown error`}`,{level:`warn`}),(t.message?.includes(`terminated`)||t.message?.includes(`closed`))&&f(`Server connection was terminated, automatic reconnection will be attempted...`,{level:`info`})},g.onDictionaryAdded=e=>d(e,n),g.onDictionaryChange=e=>d(e,n),g.onDictionaryDeleted=e=>d(e,n);try{await g.initialize()}catch(e){f(`Failed to initialize IntlayerEventListener:`,{level:`error`}),f(`Error: ${e instanceof Error?e.message:String(e)}`,{level:`error`})}}else n.editor.liveSync?(!n.editor.clientId||!n.editor.clientSecret)&&f(`Missing client credentials for hot reload. Please configure clientId and clientSecret`):f(`Hot reload is disabled. Please enable it in the configuration (editor.liveSync).`);let _=(0,s.createServer)(async(e,t)=>{if(e.method===`OPTIONS`){t.writeHead(200,{"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`GET, POST, PUT, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization`}),t.end();return}if(e.url?.startsWith(`/dictionaries`)){t.writeHead(200,{"Content-Type":`application/json; charset=utf-8`,"Cache-Control":`no-store`,"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`GET, POST, PUT, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization`});let r=(0,u.getDictionaries)(n);if(e.url.startsWith(`/dictionaries/`)){let[n,i]=decodeURIComponent(e.url).slice(14).split(`/`),a=r[n]??null;if(i){let e=(0,l.getLocalizedContent)(a.content,i,{dictionaryKey:n,keyPath:[]});t.end(JSON.stringify(e));return}t.end(JSON.stringify(a));return}t.end(JSON.stringify(r));return}if(e.url?.startsWith(`/unmerged_dictionaries`)){t.writeHead(200,{"Content-Type":`application/json; charset=utf-8`,"Cache-Control":`no-store`,"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`GET, POST, PUT, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization`});let r=(0,o.getUnmergedDictionaries)(n);if(e.url.startsWith(`/unmerged_dictionaries/`)){let n=r[decodeURIComponent(e.url.slice(23))]??null;t.end(JSON.stringify(n));return}t.end(JSON.stringify(r));return}if(e.url===`/configuration`){t.writeHead(200,{"Content-Type":`application/json; charset=utf-8`,"Cache-Control":`no-store`,"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`GET, POST, PUT, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization`}),t.end(JSON.stringify(n));return}if(e.url===`/health`){t.writeHead(200,{"Content-Type":`application/json; charset=utf-8`}),t.end(JSON.stringify({status:`ok`}));return}t.end(`Not found`)}),v=()=>n.editor.liveSync?`\x1B[32m✓ Enabled\x1B[0m`:`\x1B[31m✗ Disabled\x1B[0m`;_.listen(p,()=>{console.log(`
2
2
  \x1b[1;90mINTLAYER v${c.default.version}\x1b[0m
3
3
 
4
4
  Live server running at: \x1b[90m${m}\x1b[0m
@@ -1 +1 @@
1
- {"version":3,"file":"liveSync.cjs","names":["IntlayerEventListener","packageJson"],"sources":["../../src/liveSync.ts"],"sourcesContent":["import { createServer } from 'node:http';\n// @ts-ignore: @intlayer/backend is not built yet\nimport type { DictionaryAPI } from '@intlayer/backend';\nimport { buildDictionary } from '@intlayer/chokidar/build';\nimport { type ParallelHandle, runParallel } from '@intlayer/chokidar/utils';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport packageJson from '@intlayer/config/package.json' with { type: 'json' };\nimport { getLocalizedContent } from '@intlayer/core/plugins';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { IntlayerEventListener } from './IntlayerEventListener';\n\ntype LiveSyncOptions = {\n with?: string | string[];\n configOptions?: GetConfigurationOptions;\n};\n\nconst writeDictionary = async (\n dictionary: DictionaryAPI,\n configuration: IntlayerConfig\n) => {\n const appLogger = getAppLogger(configuration);\n appLogger(`Writing dictionary ${dictionary.key}`);\n await buildDictionary([dictionary], configuration);\n};\n\nexport const liveSync = async (options?: LiveSyncOptions) => {\n const configuration = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n\n const { liveSyncPort, liveSyncURL } = configuration.editor;\n\n let parallelProcess: ParallelHandle | null = null;\n let eventListener: IntlayerEventListener | null = null;\n let _isHotReloadConnected = false;\n let _connectionStatus = 'disconnected'; // 'connected', 'connecting', 'reconnecting', 'disconnected', 'error'\n\n // Start the parallel process if provided\n if (options?.with) {\n parallelProcess = runParallel(options.with);\n // Handle the promise to avoid unhandled rejection\n parallelProcess.result.catch(() => {\n // Parallel process failed or was terminated\n });\n }\n\n // Initialize the event listener for hot reload if configured\n if (\n configuration.editor.liveSync &&\n configuration.editor.backendURL &&\n configuration.editor.clientId &&\n configuration.editor.clientSecret\n ) {\n eventListener = new IntlayerEventListener(configuration);\n _connectionStatus = 'connecting';\n\n // Set up connection callbacks\n eventListener.onConnectionOpen = () => {\n _connectionStatus = 'connected';\n _isHotReloadConnected = true;\n appLogger('Live sync connection established');\n };\n\n eventListener.onConnectionError = (error) => {\n _connectionStatus = 'error';\n _isHotReloadConnected = false;\n const errorEvent = error as any;\n appLogger(\n `Live sync connection error: ${errorEvent.message ?? 'Unknown error'}`,\n {\n level: 'warn',\n }\n );\n\n // If this is a \"terminated: other side closed\" error, it's likely a server restart\n if (\n errorEvent.message?.includes('terminated') ||\n errorEvent.message?.includes('closed')\n ) {\n appLogger(\n 'Server connection was terminated, automatic reconnection will be attempted...',\n {\n level: 'info',\n }\n );\n _connectionStatus = 'reconnecting';\n }\n };\n\n // Set up dictionary change callbacks\n eventListener.onDictionaryAdded = (dictionary) =>\n writeDictionary(dictionary, configuration);\n eventListener.onDictionaryChange = (dictionary) =>\n writeDictionary(dictionary, configuration);\n eventListener.onDictionaryDeleted = (dictionary) =>\n writeDictionary(dictionary, configuration);\n\n try {\n await eventListener.initialize();\n } catch (error) {\n _connectionStatus = 'error';\n _isHotReloadConnected = false;\n appLogger('Failed to initialize IntlayerEventListener:', {\n level: 'error',\n });\n appLogger(\n `Error: ${error instanceof Error ? error.message : String(error)}`,\n {\n level: 'error',\n }\n );\n }\n } else if (!configuration.editor.liveSync) {\n appLogger(\n 'Hot reload is disabled. Please enable it in the configuration (editor.liveSync).'\n );\n } else if (\n !configuration.editor.clientId ||\n !configuration.editor.clientSecret\n ) {\n appLogger(\n 'Missing client credentials for hot reload. Please configure clientId and clientSecret'\n );\n }\n\n const server = createServer(async (req, res) => {\n // Handle CORS preflight requests\n if (req.method === 'OPTIONS') {\n res.writeHead(200, {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Authorization',\n });\n\n res.end();\n return;\n }\n\n if (req.url?.startsWith('/dictionaries')) {\n res.writeHead(200, {\n 'Content-Type': 'application/json; charset=utf-8',\n 'Cache-Control': 'no-store',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Authorization',\n });\n const dictionaries = getDictionaries(configuration);\n\n const prefix = '/dictionaries/';\n if (req.url.startsWith(prefix)) {\n const [key, locale] = decodeURIComponent(req.url)\n .slice(prefix.length)\n .split('/');\n\n const dictionary = dictionaries[key] ?? null;\n\n if (locale) {\n // @ts-ignore Type instantiation is excessively deep and possibly infinite\n const sourceLocaleContent = getLocalizedContent(\n dictionary.content,\n locale,\n {\n dictionaryKey: key,\n keyPath: [],\n }\n );\n\n res.end(JSON.stringify(sourceLocaleContent));\n return;\n }\n\n res.end(JSON.stringify(dictionary));\n return;\n }\n\n res.end(JSON.stringify(dictionaries));\n return;\n }\n\n if (req.url?.startsWith('/unmerged_dictionaries')) {\n res.writeHead(200, {\n 'Content-Type': 'application/json; charset=utf-8',\n 'Cache-Control': 'no-store',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Authorization',\n });\n const unmergedDictionaries = getUnmergedDictionaries(configuration);\n\n const prefix = '/unmerged_dictionaries/';\n if (req.url.startsWith(prefix)) {\n const key = decodeURIComponent(req.url.slice(prefix.length));\n const one = unmergedDictionaries[key] ?? null;\n\n res.end(JSON.stringify(one));\n return;\n }\n\n res.end(JSON.stringify(unmergedDictionaries));\n return;\n }\n\n if (req.url === '/configuration') {\n res.writeHead(200, {\n 'Content-Type': 'application/json; charset=utf-8',\n 'Cache-Control': 'no-store',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Authorization',\n });\n res.end(JSON.stringify(configuration));\n return;\n }\n\n if (req.url === '/health') {\n res.writeHead(200, {\n 'Content-Type': 'application/json; charset=utf-8',\n });\n res.end(JSON.stringify({ status: 'ok' }));\n return;\n }\n\n res.end('Not found');\n return;\n });\n\n const getLiveSyncParam = () => {\n if (!configuration.editor.liveSync) return '\\x1b[31m✗ Disabled\\x1b[0m';\n\n return '\\x1b[32m✓ Enabled\\x1b[0m';\n };\n server.listen(liveSyncPort, () => {\n console.log(`\n \\x1b[1;90mINTLAYER v${packageJson.version}\\x1b[0m\n \n Live server running at: \\x1b[90m${liveSyncURL}\\x1b[0m\n - Backend URL: \\x1b[90m${configuration.editor.backendURL ?? '-'}\\x1b[0m\n - Live sync: ${getLiveSyncParam()}\n - Parallel process: ${options?.with ? `\\x1b[90m${Array.isArray(options.with) ? options.with.join(' ') : options.with}\\x1b[0m` : '-'}\n - Access key: ${configuration.editor.clientId ?? '-'}\n `);\n });\n\n // Cleanup function to terminate child process and event listener when the main process exits\n const cleanup = () => {\n // Clean up event listener\n if (eventListener) {\n appLogger('Closing SSE connection...');\n eventListener.cleanup();\n }\n\n if (parallelProcess) {\n parallelProcess.kill();\n }\n\n server.close(() => {\n appLogger('Live sync server stopped');\n process.exit(0);\n });\n };\n\n // Handle process termination signals\n process.on('SIGINT', cleanup);\n process.on('SIGTERM', cleanup);\n process.on('exit', cleanup);\n};\n"],"mappings":"8gBAsBA,MAAM,EAAkB,MACtB,EACA,IACG,EAEH,EAAA,EAAA,cAD+B,EAAc,CACnC,sBAAsB,EAAW,MAAM,CACjD,MAAA,EAAA,EAAA,iBAAsB,CAAC,EAAW,CAAE,EAAc,EAGvC,EAAW,KAAO,IAA8B,CAC3D,IAAM,GAAA,EAAA,EAAA,kBAAiC,GAAS,cAAc,CACxD,GAAA,EAAA,EAAA,cAAyB,EAAc,CAEvC,CAAE,eAAc,eAAgB,EAAc,OAEhD,EAAyC,KACzC,EAA8C,KAclD,GATI,GAAS,OACX,GAAA,EAAA,EAAA,aAA8B,EAAQ,KAAK,CAE3C,EAAgB,OAAO,UAAY,GAEjC,EAKF,EAAc,OAAO,UACrB,EAAc,OAAO,YACrB,EAAc,OAAO,UACrB,EAAc,OAAO,aACrB,CACA,EAAgB,IAAIA,EAAAA,sBAAsB,EAAc,CAIxD,EAAc,qBAAyB,CAGrC,EAAU,mCAAmC,EAG/C,EAAc,kBAAqB,GAAU,CAG3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IAAI;yCAC9G,EAAc,OAAO,UAAY,IAAI;QACtE,EACJ,CAGF,IAAM,MAAgB,CAEhB,IACF,EAAU,4BAA4B,CACtC,EAAc,SAAS,EAGrB,GACF,EAAgB,MAAM,CAGxB,EAAO,UAAY,CACjB,EAAU,2BAA2B,CACrC,QAAQ,KAAK,EAAE,EACf,EAIJ,QAAQ,GAAG,SAAU,EAAQ,CAC7B,QAAQ,GAAG,UAAW,EAAQ,CAC9B,QAAQ,GAAG,OAAQ,EAAQ"}
1
+ {"version":3,"file":"liveSync.cjs","names":["IntlayerEventListener","packageJson"],"sources":["../../src/liveSync.ts"],"sourcesContent":["import { createServer } from 'node:http';\n// @ts-ignore: @intlayer/backend is not built yet\nimport type { DictionaryAPI } from '@intlayer/backend';\nimport { buildDictionary } from '@intlayer/chokidar/build';\nimport { type ParallelHandle, runParallel } from '@intlayer/chokidar/utils';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport packageJson from '@intlayer/config/package.json' with { type: 'json' };\nimport { getLocalizedContent } from '@intlayer/core/plugins';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { IntlayerEventListener } from './IntlayerEventListener';\n\ntype LiveSyncOptions = {\n with?: string | string[];\n configOptions?: GetConfigurationOptions;\n};\n\nconst writeDictionary = async (\n dictionary: DictionaryAPI,\n configuration: IntlayerConfig\n) => {\n const appLogger = getAppLogger(configuration);\n appLogger(`Writing dictionary ${dictionary.key}`);\n await buildDictionary([dictionary], configuration);\n};\n\nexport const liveSync = async (options?: LiveSyncOptions) => {\n const configuration = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n\n const { liveSyncPort, liveSyncURL } = configuration.editor;\n\n let parallelProcess: ParallelHandle | null = null;\n let eventListener: IntlayerEventListener | null = null;\n let _isHotReloadConnected = false;\n let _connectionStatus = 'disconnected'; // 'connected', 'connecting', 'reconnecting', 'disconnected', 'error'\n\n // Start the parallel process if provided\n if (options?.with) {\n parallelProcess = runParallel(options.with);\n // Handle the promise to avoid unhandled rejection\n parallelProcess.result.catch(() => {\n // Parallel process failed or was terminated\n });\n }\n\n // Initialize the event listener for hot reload if configured\n if (\n configuration.editor.liveSync &&\n configuration.editor.backendURL &&\n configuration.editor.clientId &&\n configuration.editor.clientSecret\n ) {\n eventListener = new IntlayerEventListener(configuration);\n _connectionStatus = 'connecting';\n\n // Set up connection callbacks\n eventListener.onConnectionOpen = () => {\n _connectionStatus = 'connected';\n _isHotReloadConnected = true;\n appLogger('Live sync connection established');\n };\n\n eventListener.onConnectionError = (error) => {\n _connectionStatus = 'error';\n _isHotReloadConnected = false;\n const errorEvent = error as any;\n appLogger(\n `Live sync connection error: ${errorEvent.message ?? 'Unknown error'}`,\n {\n level: 'warn',\n }\n );\n\n // If this is a \"terminated: other side closed\" error, it's likely a server restart\n if (\n errorEvent.message?.includes('terminated') ||\n errorEvent.message?.includes('closed')\n ) {\n appLogger(\n 'Server connection was terminated, automatic reconnection will be attempted...',\n {\n level: 'info',\n }\n );\n _connectionStatus = 'reconnecting';\n }\n };\n\n // Set up dictionary change callbacks\n eventListener.onDictionaryAdded = (dictionary) =>\n writeDictionary(dictionary, configuration);\n eventListener.onDictionaryChange = (dictionary) =>\n writeDictionary(dictionary, configuration);\n eventListener.onDictionaryDeleted = (dictionary) =>\n writeDictionary(dictionary, configuration);\n\n try {\n await eventListener.initialize();\n } catch (error) {\n _connectionStatus = 'error';\n _isHotReloadConnected = false;\n appLogger('Failed to initialize IntlayerEventListener:', {\n level: 'error',\n });\n appLogger(\n `Error: ${error instanceof Error ? error.message : String(error)}`,\n {\n level: 'error',\n }\n );\n }\n } else if (!configuration.editor.liveSync) {\n appLogger(\n 'Hot reload is disabled. Please enable it in the configuration (editor.liveSync).'\n );\n } else if (\n !configuration.editor.clientId ||\n !configuration.editor.clientSecret\n ) {\n appLogger(\n 'Missing client credentials for hot reload. Please configure clientId and clientSecret'\n );\n }\n\n const server = createServer(async (req, res) => {\n // Handle CORS preflight requests\n if (req.method === 'OPTIONS') {\n res.writeHead(200, {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Authorization',\n });\n\n res.end();\n return;\n }\n\n if (req.url?.startsWith('/dictionaries')) {\n res.writeHead(200, {\n 'Content-Type': 'application/json; charset=utf-8',\n 'Cache-Control': 'no-store',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Authorization',\n });\n const dictionaries = getDictionaries(configuration);\n\n const prefix = '/dictionaries/';\n if (req.url.startsWith(prefix)) {\n const [key, locale] = decodeURIComponent(req.url)\n .slice(prefix.length)\n .split('/');\n\n const dictionary = dictionaries[key] ?? null;\n\n if (locale) {\n // @ts-ignore Type instantiation is excessively deep and possibly infinite\n const sourceLocaleContent = getLocalizedContent(\n dictionary.content,\n locale,\n {\n dictionaryKey: key,\n keyPath: [],\n }\n );\n\n res.end(JSON.stringify(sourceLocaleContent));\n return;\n }\n\n res.end(JSON.stringify(dictionary));\n return;\n }\n\n res.end(JSON.stringify(dictionaries));\n return;\n }\n\n if (req.url?.startsWith('/unmerged_dictionaries')) {\n res.writeHead(200, {\n 'Content-Type': 'application/json; charset=utf-8',\n 'Cache-Control': 'no-store',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Authorization',\n });\n const unmergedDictionaries = getUnmergedDictionaries(configuration);\n\n const prefix = '/unmerged_dictionaries/';\n if (req.url.startsWith(prefix)) {\n const key = decodeURIComponent(req.url.slice(prefix.length));\n const one = unmergedDictionaries[key] ?? null;\n\n res.end(JSON.stringify(one));\n return;\n }\n\n res.end(JSON.stringify(unmergedDictionaries));\n return;\n }\n\n if (req.url === '/configuration') {\n res.writeHead(200, {\n 'Content-Type': 'application/json; charset=utf-8',\n 'Cache-Control': 'no-store',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Authorization',\n });\n res.end(JSON.stringify(configuration));\n return;\n }\n\n if (req.url === '/health') {\n res.writeHead(200, {\n 'Content-Type': 'application/json; charset=utf-8',\n });\n res.end(JSON.stringify({ status: 'ok' }));\n return;\n }\n\n res.end('Not found');\n return;\n });\n\n const getLiveSyncParam = () => {\n if (!configuration.editor.liveSync) return '\\x1b[31m✗ Disabled\\x1b[0m';\n\n return '\\x1b[32m✓ Enabled\\x1b[0m';\n };\n server.listen(liveSyncPort, () => {\n console.log(`\n \\x1b[1;90mINTLAYER v${packageJson.version}\\x1b[0m\n \n Live server running at: \\x1b[90m${liveSyncURL}\\x1b[0m\n - Backend URL: \\x1b[90m${configuration.editor.backendURL ?? '-'}\\x1b[0m\n - Live sync: ${getLiveSyncParam()}\n - Parallel process: ${options?.with ? `\\x1b[90m${Array.isArray(options.with) ? options.with.join(' ') : options.with}\\x1b[0m` : '-'}\n - Access key: ${configuration.editor.clientId ?? '-'}\n `);\n });\n\n // Cleanup function to terminate child process and event listener when the main process exits\n const cleanup = () => {\n // Clean up event listener\n if (eventListener) {\n appLogger('Closing SSE connection...');\n eventListener.cleanup();\n }\n\n if (parallelProcess) {\n parallelProcess.kill();\n }\n\n server.close(() => {\n appLogger('Live sync server stopped');\n process.exit(0);\n });\n };\n\n // Handle process termination signals\n process.on('SIGINT', cleanup);\n process.on('SIGTERM', cleanup);\n process.on('exit', cleanup);\n};\n"],"mappings":"4fAsBA,MAAM,EAAkB,MACtB,EACA,IACG,EAEH,EAAA,EAAA,cAD+B,EAAc,CACnC,sBAAsB,EAAW,MAA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C,CAAC,CACF,EAAI,IAAI,KAAK,UAAU,EAAc,CAAC,CACtC,OAGF,GAAI,EAAI,MAAQ,UAAW,CACzB,EAAI,UAAU,IAAK,CACjB,eAAgB,kCACjB,CAAC,CACF,EAAI,IAAI,KAAK,UAAU,CAAE,OAAQ,KAAM,CAAC,CAAC,CACzC,OAGF,EAAI,IAAI,YAAY,EAEpB,CAEI,MACC,EAAc,OAAO,SAEnB,2BAFoC,4BAI7C,EAAO,OAAO,MAAoB,CAChC,QAAQ,IAAI;4BACYC,EAAAA,QAAY,QAAQ;;iDAEC,EAAY;iDACZ,EAAc,OAAO,YAAc,IAAI;yCAC/C,GAAkB,CAAC;yCACnB,GAAS,KAAO,WAAW,MAAM,QAAQ,EAAQ,KAAK,CAAG,EAAQ,KAAK,KAAK,IAAI,CAAG,EAAQ,KAAK,SAAW,IAAI;yCAC9G,EAAc,OAAO,UAAY,IAAI;QACtE,EACJ,CAGF,IAAM,MAAgB,CAEhB,IACF,EAAU,4BAA4B,CACtC,EAAc,SAAS,EAGrB,GACF,EAAgB,MAAM,CAGxB,EAAO,UAAY,CACjB,EAAU,2BAA2B,CACrC,QAAQ,KAAK,EAAE,EACf,EAIJ,QAAQ,GAAG,SAAU,EAAQ,CAC7B,QAAQ,GAAG,UAAW,EAAQ,CAC9B,QAAQ,GAAG,OAAQ,EAAQ"}
package/dist/cjs/pull.cjs CHANGED
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./_virtual/_rolldown/runtime.cjs`);const e=require(`./utils/checkAccess.cjs`),t=require(`./push/pullLog.cjs`);let n=require(`node:fs`),r=require(`node:path`),i=require(`@intlayer/chokidar/build`),a=require(`@intlayer/chokidar/cli`),o=require(`@intlayer/chokidar/utils`),s=require(`@intlayer/config/logger`),c=require(`@intlayer/config/node`),l=require(`@intlayer/unmerged-dictionaries-entry`),u=require(`@intlayer/api`),d=require(`@intlayer/config/utils`);const f=async f=>{let p=(0,s.getAppLogger)(f?.configOptions?.override);try{let m=(0,c.getConfiguration)(f?.configOptions);if((0,a.logConfigDetails)(f?.configOptions),!await e.checkCMSAuth(m))return;let h=(0,u.getIntlayerAPIProxy)(void 0,m),g=(0,l.getUnmergedDictionaries)(m),_=await h.dictionary.getDictionariesUpdateTimestamp();if(!_.data)throw Error(`No distant dictionaries found`);let v=_.data;f?.dictionaries&&(v=Object.fromEntries(Object.entries(v).filter(([e])=>f.dictionaries?.includes(e)))),v=Object.fromEntries(Object.entries(v).filter(([e])=>{let t=g[e]?.[0]?.location??m.dictionary?.location??`remote`;return t===`remote`||t===`hybrid`}));let y=(0,r.join)(m.system.mainDir,`remote_dictionaries.cjs`),b=m.build?.require??(0,d.getProjectRequire)(),x=(0,n.existsSync)(y)?b(y):{},S=Object.entries(v),C=S.filter(([e,t])=>{if(!t)return!0;let n=typeof t==`object`?t.updatedAt:t,r=x[e];if(!r)return!0;let i=r?.updatedAt,a=typeof i==`number`?i:i?new Date(i).getTime():void 0;return typeof a==`number`?n>a:!0}).map(([e])=>e),w=S.filter(([e,t])=>{let n=typeof t==`object`?t.updatedAt:t,r=x[e]?.updatedAt,i=typeof r==`number`?r:r?new Date(r).getTime():void 0;return typeof i==`number`&&typeof n==`number`&&i>=n}).map(([e])=>e);if(S.length===0){p(`No dictionaries to fetch`,{level:`error`});return}p(`Fetching dictionaries:`);let T=[...w.map(e=>({dictionaryKey:e,status:`imported`})),...C.map(e=>({dictionaryKey:e,status:`pending`}))],E=new t.PullLogger;E.update(T.map(e=>({dictionaryKey:e.dictionaryKey,status:e.status})));let D=[];await(0,o.parallelize)(T,async e=>{let t=e.status===`imported`||e.status===`up-to-date`;t||(e.status=`fetching`,E.update([{dictionaryKey:e.dictionaryKey,status:`fetching`}]));try{let n;if(t&&(n=x[e.dictionaryKey]),n||=(await h.dictionary.getDictionary(e.dictionaryKey)).data,!n)throw Error(`Dictionary ${e.dictionaryKey} not found on remote`);let r=g[e.dictionaryKey]?.find(e=>e.location===`hybrid`);r&&(n={...n,location:`hybrid`,filePath:r.filePath,localId:r.localId});let{status:a}=await(0,i.writeContentDeclaration)(n,m,f);e.status=a,E.update([{dictionaryKey:e.dictionaryKey,status:a}]),D.push(n)}catch(t){e.status=`error`,e.error=t,e.errorMessage=`Error fetching dictionary ${e.dictionaryKey}: ${t}`,E.update([{dictionaryKey:e.dictionaryKey,status:`error`}])}},5),E.finish();let O=e=>{switch(e){case`fetched`:case`imported`:case`updated`:case`up-to-date`:case`reimported in JSON`:case`new content file`:return`✔`;case`error`:return`✖`;default:return`⏲`}},k=e=>{switch(e){case`fetched`:case`imported`:case`updated`:case`up-to-date`:return s.ANSIColors.GREEN;case`reimported in JSON`:case`new content file`:return s.ANSIColors.YELLOW;case`error`:return s.ANSIColors.RED;default:return s.ANSIColors.BLUE}};for(let e of T){let t=O(e.status),n=k(e.status);p(` - ${e.dictionaryKey} ${s.ANSIColors.GREY}[${n}${t} ${e.status}${s.ANSIColors.GREY}]${s.ANSIColors.RESET}`)}for(let e of T)e.errorMessage&&p(e.errorMessage,{level:`error`})}catch(e){p(e,{level:`error`})}};exports.pull=f;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./chunk-Bmb41Sf3.cjs`);const e=require(`./utils/checkAccess.cjs`),t=require(`./push/pullLog.cjs`);let n=require(`node:fs`),r=require(`node:path`),i=require(`@intlayer/chokidar/build`),a=require(`@intlayer/chokidar/cli`),o=require(`@intlayer/chokidar/utils`),s=require(`@intlayer/config/logger`),c=require(`@intlayer/config/node`),l=require(`@intlayer/unmerged-dictionaries-entry`),u=require(`@intlayer/api`),d=require(`@intlayer/config/utils`);const f=async f=>{let p=(0,s.getAppLogger)(f?.configOptions?.override);try{let m=(0,c.getConfiguration)(f?.configOptions);if((0,a.logConfigDetails)(f?.configOptions),!await e.checkCMSAuth(m))return;let h=(0,u.getIntlayerAPIProxy)(void 0,m),g=(0,l.getUnmergedDictionaries)(m),_=await h.dictionary.getDictionariesUpdateTimestamp();if(!_.data)throw Error(`No distant dictionaries found`);let v=_.data;f?.dictionaries&&(v=Object.fromEntries(Object.entries(v).filter(([e])=>f.dictionaries?.includes(e)))),v=Object.fromEntries(Object.entries(v).filter(([e])=>{let t=g[e]?.[0]?.location??m.dictionary?.location??`remote`;return t===`remote`||t===`hybrid`}));let y=(0,r.join)(m.system.mainDir,`remote_dictionaries.cjs`),b=m.build?.require??(0,d.getProjectRequire)(),x=(0,n.existsSync)(y)?b(y):{},S=Object.entries(v),C=S.filter(([e,t])=>{if(!t)return!0;let n=typeof t==`object`?t.updatedAt:t,r=x[e];if(!r)return!0;let i=r?.updatedAt,a=typeof i==`number`?i:i?new Date(i).getTime():void 0;return typeof a==`number`?n>a:!0}).map(([e])=>e),w=S.filter(([e,t])=>{let n=typeof t==`object`?t.updatedAt:t,r=x[e]?.updatedAt,i=typeof r==`number`?r:r?new Date(r).getTime():void 0;return typeof i==`number`&&typeof n==`number`&&i>=n}).map(([e])=>e);if(S.length===0){p(`No dictionaries to fetch`,{level:`error`});return}p(`Fetching dictionaries:`);let T=[...w.map(e=>({dictionaryKey:e,status:`imported`})),...C.map(e=>({dictionaryKey:e,status:`pending`}))],E=new t.PullLogger;E.update(T.map(e=>({dictionaryKey:e.dictionaryKey,status:e.status})));let D=[];await(0,o.parallelize)(T,async e=>{let t=e.status===`imported`||e.status===`up-to-date`;t||(e.status=`fetching`,E.update([{dictionaryKey:e.dictionaryKey,status:`fetching`}]));try{let n;if(t&&(n=x[e.dictionaryKey]),n||=(await h.dictionary.getDictionary(e.dictionaryKey)).data,!n)throw Error(`Dictionary ${e.dictionaryKey} not found on remote`);let r=g[e.dictionaryKey]?.find(e=>e.location===`hybrid`);r&&(n={...n,location:`hybrid`,filePath:r.filePath,localId:r.localId});let{status:a}=await(0,i.writeContentDeclaration)(n,m,f);e.status=a,E.update([{dictionaryKey:e.dictionaryKey,status:a}]),D.push(n)}catch(t){e.status=`error`,e.error=t,e.errorMessage=`Error fetching dictionary ${e.dictionaryKey}: ${t}`,E.update([{dictionaryKey:e.dictionaryKey,status:`error`}])}},5),E.finish();let O=e=>{switch(e){case`fetched`:case`imported`:case`updated`:case`up-to-date`:case`reimported in JSON`:case`new content file`:return`✔`;case`error`:return`✖`;default:return`⏲`}},k=e=>{switch(e){case`fetched`:case`imported`:case`updated`:case`up-to-date`:return s.ANSIColors.GREEN;case`reimported in JSON`:case`new content file`:return s.ANSIColors.YELLOW;case`error`:return s.ANSIColors.RED;default:return s.ANSIColors.BLUE}};for(let e of T){let t=O(e.status),n=k(e.status);p(` - ${e.dictionaryKey} ${s.ANSIColors.GREY}[${n}${t} ${e.status}${s.ANSIColors.GREY}]${s.ANSIColors.RESET}`)}for(let e of T)e.errorMessage&&p(e.errorMessage,{level:`error`})}catch(e){p(e,{level:`error`})}};exports.pull=f;
2
2
  //# sourceMappingURL=pull.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"pull.cjs","names":["checkCMSAuth","PullLogger","ANSIColors"],"sources":["../../src/pull.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { getIntlayerAPIProxy } from '@intlayer/api';\nimport {\n type DictionaryStatus,\n writeContentDeclaration,\n} from '@intlayer/chokidar/build';\nimport { logConfigDetails } from '@intlayer/chokidar/cli';\nimport { parallelize } from '@intlayer/chokidar/utils';\nimport { ANSIColors, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { getProjectRequire } from '@intlayer/config/utils';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { PullLogger, type PullStatus } from './push/pullLog';\nimport { checkCMSAuth } from './utils/checkAccess';\n\ntype PullOptions = {\n dictionaries?: string[];\n newDictionariesPath?: string;\n configOptions?: GetConfigurationOptions;\n};\n\ntype DictionariesStatus = {\n dictionaryKey: string;\n status: DictionaryStatus | 'pending' | 'fetching' | 'error';\n error?: Error;\n errorMessage?: string;\n};\n\n/**\n * Fetch distant dictionaries and write them locally,\n * with progress indicators and concurrency control.\n */\nexport const pull = async (options?: PullOptions): Promise<void> => {\n const appLogger = getAppLogger(options?.configOptions?.override);\n\n try {\n const config = getConfiguration(options?.configOptions);\n logConfigDetails(options?.configOptions);\n\n const hasCMSAuth = await checkCMSAuth(config);\n\n if (!hasCMSAuth) return;\n\n const intlayerAPI = getIntlayerAPIProxy(undefined, config);\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(config);\n\n // Get remote update timestamps map\n const getDictionariesUpdateTimestampResult =\n await intlayerAPI.dictionary.getDictionariesUpdateTimestamp();\n\n if (!getDictionariesUpdateTimestampResult.data) {\n throw new Error('No distant dictionaries found');\n }\n\n let distantDictionariesUpdateTimeStamp: Record<string, any> =\n getDictionariesUpdateTimestampResult.data;\n\n // Optional filtering by requested dictionaries\n if (options?.dictionaries) {\n distantDictionariesUpdateTimeStamp = Object.fromEntries(\n Object.entries(distantDictionariesUpdateTimeStamp).filter(([key]) =>\n options.dictionaries?.includes(key)\n )\n );\n }\n\n // Filter by location\n distantDictionariesUpdateTimeStamp = Object.fromEntries(\n Object.entries(distantDictionariesUpdateTimeStamp).filter(([key]) => {\n const localDictionaries = unmergedDictionariesRecord[key];\n const location =\n localDictionaries?.[0]?.location ??\n config.dictionary?.location ??\n 'remote';\n\n return location === 'remote' || location === 'hybrid';\n })\n );\n\n // Load local cached remote dictionaries (if any)\n const remoteDictionariesPath = join(\n config.system.mainDir,\n 'remote_dictionaries.cjs'\n );\n const requireFunction = config.build?.require ?? getProjectRequire();\n const remoteDictionariesRecord: Record<string, any> = existsSync(\n remoteDictionariesPath\n )\n ? (requireFunction(remoteDictionariesPath) as any)\n : {};\n\n // Determine which keys need fetching by comparing updatedAt with local cache\n const entries = Object.entries(distantDictionariesUpdateTimeStamp);\n const keysToFetch = entries\n .filter(([key, remoteUpdatedAtValue]) => {\n if (!remoteUpdatedAtValue) return true;\n\n const remoteUpdatedAt =\n typeof remoteUpdatedAtValue === 'object'\n ? (remoteUpdatedAtValue as any).updatedAt\n : remoteUpdatedAtValue;\n\n const local = (remoteDictionariesRecord as any)[key];\n if (!local) return true;\n const localUpdatedAtRaw = (local as any)?.updatedAt as\n | number\n | string\n | undefined;\n const localUpdatedAt =\n typeof localUpdatedAtRaw === 'number'\n ? localUpdatedAtRaw\n : localUpdatedAtRaw\n ? new Date(localUpdatedAtRaw).getTime()\n : undefined;\n if (typeof localUpdatedAt !== 'number') return true;\n return remoteUpdatedAt > localUpdatedAt;\n })\n .map(([key]) => key);\n\n const cachedKeys = entries\n .filter(([key, remoteUpdatedAtValue]) => {\n const remoteUpdatedAt =\n typeof remoteUpdatedAtValue === 'object'\n ? (remoteUpdatedAtValue as any).updatedAt\n : remoteUpdatedAtValue;\n\n const local = (remoteDictionariesRecord as any)[key];\n const localUpdatedAtRaw = (local as any)?.updatedAt as\n | number\n | string\n | undefined;\n const localUpdatedAt =\n typeof localUpdatedAtRaw === 'number'\n ? localUpdatedAtRaw\n : localUpdatedAtRaw\n ? new Date(localUpdatedAtRaw).getTime()\n : undefined;\n return (\n typeof localUpdatedAt === 'number' &&\n typeof remoteUpdatedAt === 'number' &&\n localUpdatedAt >= remoteUpdatedAt\n );\n })\n .map(([key]) => key);\n\n // Check if dictionaries list is empty\n if (entries.length === 0) {\n appLogger('No dictionaries to fetch', {\n level: 'error',\n });\n return;\n }\n\n appLogger('Fetching dictionaries:');\n\n // Prepare dictionaries statuses\n const dictionariesStatuses: DictionariesStatus[] = [\n ...cachedKeys.map((dictionaryKey) => ({\n dictionaryKey,\n status: 'imported' as DictionaryStatus,\n })),\n ...keysToFetch.map((dictionaryKey) => ({\n dictionaryKey,\n status: 'pending' as const,\n })),\n ];\n\n // Initialize aggregated logger\n const logger = new PullLogger();\n logger.update(\n dictionariesStatuses.map<PullStatus>((s) => ({\n dictionaryKey: s.dictionaryKey,\n status: s.status,\n }))\n );\n\n const successfullyFetchedDictionaries: Dictionary[] = [];\n\n const processDictionary = async (\n statusObj: DictionariesStatus\n ): Promise<void> => {\n const isCached =\n statusObj.status === 'imported' || statusObj.status === 'up-to-date';\n\n if (!isCached) {\n statusObj.status = 'fetching';\n logger.update([\n { dictionaryKey: statusObj.dictionaryKey, status: 'fetching' },\n ]);\n }\n\n try {\n let sourceDictionary: Dictionary | undefined;\n\n if (isCached) {\n sourceDictionary = remoteDictionariesRecord[\n statusObj.dictionaryKey\n ] as Dictionary | undefined;\n }\n\n if (!sourceDictionary) {\n // Fetch the dictionary\n const getDictionaryResult =\n await intlayerAPI.dictionary.getDictionary(statusObj.dictionaryKey);\n\n sourceDictionary = getDictionaryResult.data as Dictionary | undefined;\n }\n\n if (!sourceDictionary) {\n throw new Error(\n `Dictionary ${statusObj.dictionaryKey} not found on remote`\n );\n }\n\n // Check if there is a local version of this dictionary that is hybrid\n const localDictionaries =\n unmergedDictionariesRecord[statusObj.dictionaryKey];\n const localAndRemoteDictionary = localDictionaries?.find(\n (d) => d.location === 'hybrid'\n );\n\n if (localAndRemoteDictionary) {\n // We want to preserve the local properties but use the remote content\n sourceDictionary = {\n ...sourceDictionary,\n location: 'hybrid',\n filePath: localAndRemoteDictionary.filePath,\n localId: localAndRemoteDictionary.localId,\n };\n }\n\n // Now, write the dictionary to local file\n const { status } = await writeContentDeclaration(\n sourceDictionary,\n config,\n options\n );\n\n statusObj.status = status;\n logger.update([{ dictionaryKey: statusObj.dictionaryKey, status }]);\n\n successfullyFetchedDictionaries.push(sourceDictionary);\n } catch (error) {\n statusObj.status = 'error';\n statusObj.error = error as Error;\n statusObj.errorMessage = `Error fetching dictionary ${statusObj.dictionaryKey}: ${error}`;\n logger.update([\n { dictionaryKey: statusObj.dictionaryKey, status: 'error' },\n ]);\n }\n };\n\n // Process dictionaries in parallel with concurrency limit\n await parallelize(dictionariesStatuses, processDictionary, 5);\n\n // Stop the logger and render final state\n logger.finish();\n\n // Per-dictionary summary\n const iconFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'fetched':\n case 'imported':\n case 'updated':\n case 'up-to-date':\n case 'reimported in JSON':\n case 'new content file':\n return '✔';\n case 'error':\n return '✖';\n default:\n return '⏲';\n }\n };\n\n const colorFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'fetched':\n case 'imported':\n case 'updated':\n case 'up-to-date':\n return ANSIColors.GREEN;\n case 'reimported in JSON':\n case 'new content file':\n return ANSIColors.YELLOW;\n case 'error':\n return ANSIColors.RED;\n default:\n return ANSIColors.BLUE;\n }\n };\n\n for (const s of dictionariesStatuses) {\n const icon = iconFor(s.status);\n const color = colorFor(s.status);\n appLogger(\n ` - ${s.dictionaryKey} ${ANSIColors.GREY}[${color}${icon} ${s.status}${ANSIColors.GREY}]${ANSIColors.RESET}`\n );\n }\n\n // Output any error messages\n for (const statusObj of dictionariesStatuses) {\n if (statusObj.errorMessage) {\n appLogger(statusObj.errorMessage, {\n level: 'error',\n });\n }\n }\n } catch (error) {\n appLogger(error, {\n level: 'error',\n });\n }\n};\n"],"mappings":"ohBAqCA,MAAa,EAAO,KAAO,IAAyC,CAClE,IAAM,GAAA,EAAA,EAAA,cAAyB,GAAS,eAAe,SAAS,CAEhE,GAAI,CACF,IAAM,GAAA,EAAA,EAAA,kBAA0B,GAAS,cAAc,CAKvD,IAJA,EAAA,EAAA,kBAAiB,GAAS,cAAc,CAIpC,CAFe,MAAMA,EAAAA,aAAa,EAAO,CAE5B,OAEjB,IAAM,GAAA,EAAA,EAAA,qBAAkC,IAAA,GAAW,EAAO,CAEpD,GAAA,EAAA,EAAA,yBAAqD,EAAO,CAG5D,EACJ,MAAM,EAAY,WAAW,gCAAgC,CAE/D,GAAI,CAAC,EAAqC,KACxC,MAAU,MAAM,gCAAgC,CAGlD,IAAI,EACF,EAAqC,KAGnC,GAAS,eACX,EAAqC,OAAO,YAC1C,OAAO,QAAQ,EAAmC,CAAC,QAAQ,CAAC,KAC1D,EAAQ,cAAc,SAAS,EAAI,CACpC,CACF,EAIH,EAAqC,OAA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ACT,IAAK,QACH,MAAO,IACT,QACE,MAAO,MAIP,EAAY,GAAyC,CACzD,OAAQ,EAAR,CACE,IAAK,UACL,IAAK,WACL,IAAK,UACL,IAAK,aACH,OAAOC,EAAAA,WAAW,MACpB,IAAK,qBACL,IAAK,mBACH,OAAOA,EAAAA,WAAW,OACpB,IAAK,QACH,OAAOA,EAAAA,WAAW,IACpB,QACE,OAAOA,EAAAA,WAAW,OAIxB,IAAK,IAAM,KAAK,EAAsB,CACpC,IAAM,EAAO,EAAQ,EAAE,OAAO,CACxB,EAAQ,EAAS,EAAE,OAAO,CAChC,EACE,MAAM,EAAE,cAAc,GAAGA,EAAAA,WAAW,KAAK,GAAG,IAAQ,EAAK,GAAG,EAAE,SAASA,EAAAA,WAAW,KAAK,GAAGA,EAAAA,WAAW,QACtG,CAIH,IAAK,IAAM,KAAa,EAClB,EAAU,cACZ,EAAU,EAAU,aAAc,CAChC,MAAO,QACR,CAAC,OAGC,EAAO,CACd,EAAU,EAAO,CACf,MAAO,QACR,CAAC"}
1
+ {"version":3,"file":"pull.cjs","names":["checkCMSAuth","PullLogger","ANSIColors"],"sources":["../../src/pull.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { getIntlayerAPIProxy } from '@intlayer/api';\nimport {\n type DictionaryStatus,\n writeContentDeclaration,\n} from '@intlayer/chokidar/build';\nimport { logConfigDetails } from '@intlayer/chokidar/cli';\nimport { parallelize } from '@intlayer/chokidar/utils';\nimport { ANSIColors, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { getProjectRequire } from '@intlayer/config/utils';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { PullLogger, type PullStatus } from './push/pullLog';\nimport { checkCMSAuth } from './utils/checkAccess';\n\ntype PullOptions = {\n dictionaries?: string[];\n newDictionariesPath?: string;\n configOptions?: GetConfigurationOptions;\n};\n\ntype DictionariesStatus = {\n dictionaryKey: string;\n status: DictionaryStatus | 'pending' | 'fetching' | 'error';\n error?: Error;\n errorMessage?: string;\n};\n\n/**\n * Fetch distant dictionaries and write them locally,\n * with progress indicators and concurrency control.\n */\nexport const pull = async (options?: PullOptions): Promise<void> => {\n const appLogger = getAppLogger(options?.configOptions?.override);\n\n try {\n const config = getConfiguration(options?.configOptions);\n logConfigDetails(options?.configOptions);\n\n const hasCMSAuth = await checkCMSAuth(config);\n\n if (!hasCMSAuth) return;\n\n const intlayerAPI = getIntlayerAPIProxy(undefined, config);\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(config);\n\n // Get remote update timestamps map\n const getDictionariesUpdateTimestampResult =\n await intlayerAPI.dictionary.getDictionariesUpdateTimestamp();\n\n if (!getDictionariesUpdateTimestampResult.data) {\n throw new Error('No distant dictionaries found');\n }\n\n let distantDictionariesUpdateTimeStamp: Record<string, any> =\n getDictionariesUpdateTimestampResult.data;\n\n // Optional filtering by requested dictionaries\n if (options?.dictionaries) {\n distantDictionariesUpdateTimeStamp = Object.fromEntries(\n Object.entries(distantDictionariesUpdateTimeStamp).filter(([key]) =>\n options.dictionaries?.includes(key)\n )\n );\n }\n\n // Filter by location\n distantDictionariesUpdateTimeStamp = Object.fromEntries(\n Object.entries(distantDictionariesUpdateTimeStamp).filter(([key]) => {\n const localDictionaries = unmergedDictionariesRecord[key];\n const location =\n localDictionaries?.[0]?.location ??\n config.dictionary?.location ??\n 'remote';\n\n return location === 'remote' || location === 'hybrid';\n })\n );\n\n // Load local cached remote dictionaries (if any)\n const remoteDictionariesPath = join(\n config.system.mainDir,\n 'remote_dictionaries.cjs'\n );\n const requireFunction = config.build?.require ?? getProjectRequire();\n const remoteDictionariesRecord: Record<string, any> = existsSync(\n remoteDictionariesPath\n )\n ? (requireFunction(remoteDictionariesPath) as any)\n : {};\n\n // Determine which keys need fetching by comparing updatedAt with local cache\n const entries = Object.entries(distantDictionariesUpdateTimeStamp);\n const keysToFetch = entries\n .filter(([key, remoteUpdatedAtValue]) => {\n if (!remoteUpdatedAtValue) return true;\n\n const remoteUpdatedAt =\n typeof remoteUpdatedAtValue === 'object'\n ? (remoteUpdatedAtValue as any).updatedAt\n : remoteUpdatedAtValue;\n\n const local = (remoteDictionariesRecord as any)[key];\n if (!local) return true;\n const localUpdatedAtRaw = (local as any)?.updatedAt as\n | number\n | string\n | undefined;\n const localUpdatedAt =\n typeof localUpdatedAtRaw === 'number'\n ? localUpdatedAtRaw\n : localUpdatedAtRaw\n ? new Date(localUpdatedAtRaw).getTime()\n : undefined;\n if (typeof localUpdatedAt !== 'number') return true;\n return remoteUpdatedAt > localUpdatedAt;\n })\n .map(([key]) => key);\n\n const cachedKeys = entries\n .filter(([key, remoteUpdatedAtValue]) => {\n const remoteUpdatedAt =\n typeof remoteUpdatedAtValue === 'object'\n ? (remoteUpdatedAtValue as any).updatedAt\n : remoteUpdatedAtValue;\n\n const local = (remoteDictionariesRecord as any)[key];\n const localUpdatedAtRaw = (local as any)?.updatedAt as\n | number\n | string\n | undefined;\n const localUpdatedAt =\n typeof localUpdatedAtRaw === 'number'\n ? localUpdatedAtRaw\n : localUpdatedAtRaw\n ? new Date(localUpdatedAtRaw).getTime()\n : undefined;\n return (\n typeof localUpdatedAt === 'number' &&\n typeof remoteUpdatedAt === 'number' &&\n localUpdatedAt >= remoteUpdatedAt\n );\n })\n .map(([key]) => key);\n\n // Check if dictionaries list is empty\n if (entries.length === 0) {\n appLogger('No dictionaries to fetch', {\n level: 'error',\n });\n return;\n }\n\n appLogger('Fetching dictionaries:');\n\n // Prepare dictionaries statuses\n const dictionariesStatuses: DictionariesStatus[] = [\n ...cachedKeys.map((dictionaryKey) => ({\n dictionaryKey,\n status: 'imported' as DictionaryStatus,\n })),\n ...keysToFetch.map((dictionaryKey) => ({\n dictionaryKey,\n status: 'pending' as const,\n })),\n ];\n\n // Initialize aggregated logger\n const logger = new PullLogger();\n logger.update(\n dictionariesStatuses.map<PullStatus>((s) => ({\n dictionaryKey: s.dictionaryKey,\n status: s.status,\n }))\n );\n\n const successfullyFetchedDictionaries: Dictionary[] = [];\n\n const processDictionary = async (\n statusObj: DictionariesStatus\n ): Promise<void> => {\n const isCached =\n statusObj.status === 'imported' || statusObj.status === 'up-to-date';\n\n if (!isCached) {\n statusObj.status = 'fetching';\n logger.update([\n { dictionaryKey: statusObj.dictionaryKey, status: 'fetching' },\n ]);\n }\n\n try {\n let sourceDictionary: Dictionary | undefined;\n\n if (isCached) {\n sourceDictionary = remoteDictionariesRecord[\n statusObj.dictionaryKey\n ] as Dictionary | undefined;\n }\n\n if (!sourceDictionary) {\n // Fetch the dictionary\n const getDictionaryResult =\n await intlayerAPI.dictionary.getDictionary(statusObj.dictionaryKey);\n\n sourceDictionary = getDictionaryResult.data as Dictionary | undefined;\n }\n\n if (!sourceDictionary) {\n throw new Error(\n `Dictionary ${statusObj.dictionaryKey} not found on remote`\n );\n }\n\n // Check if there is a local version of this dictionary that is hybrid\n const localDictionaries =\n unmergedDictionariesRecord[statusObj.dictionaryKey];\n const localAndRemoteDictionary = localDictionaries?.find(\n (d) => d.location === 'hybrid'\n );\n\n if (localAndRemoteDictionary) {\n // We want to preserve the local properties but use the remote content\n sourceDictionary = {\n ...sourceDictionary,\n location: 'hybrid',\n filePath: localAndRemoteDictionary.filePath,\n localId: localAndRemoteDictionary.localId,\n };\n }\n\n // Now, write the dictionary to local file\n const { status } = await writeContentDeclaration(\n sourceDictionary,\n config,\n options\n );\n\n statusObj.status = status;\n logger.update([{ dictionaryKey: statusObj.dictionaryKey, status }]);\n\n successfullyFetchedDictionaries.push(sourceDictionary);\n } catch (error) {\n statusObj.status = 'error';\n statusObj.error = error as Error;\n statusObj.errorMessage = `Error fetching dictionary ${statusObj.dictionaryKey}: ${error}`;\n logger.update([\n { dictionaryKey: statusObj.dictionaryKey, status: 'error' },\n ]);\n }\n };\n\n // Process dictionaries in parallel with concurrency limit\n await parallelize(dictionariesStatuses, processDictionary, 5);\n\n // Stop the logger and render final state\n logger.finish();\n\n // Per-dictionary summary\n const iconFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'fetched':\n case 'imported':\n case 'updated':\n case 'up-to-date':\n case 'reimported in JSON':\n case 'new content file':\n return '✔';\n case 'error':\n return '✖';\n default:\n return '⏲';\n }\n };\n\n const colorFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'fetched':\n case 'imported':\n case 'updated':\n case 'up-to-date':\n return ANSIColors.GREEN;\n case 'reimported in JSON':\n case 'new content file':\n return ANSIColors.YELLOW;\n case 'error':\n return ANSIColors.RED;\n default:\n return ANSIColors.BLUE;\n }\n };\n\n for (const s of dictionariesStatuses) {\n const icon = iconFor(s.status);\n const color = colorFor(s.status);\n appLogger(\n ` - ${s.dictionaryKey} ${ANSIColors.GREY}[${color}${icon} ${s.status}${ANSIColors.GREY}]${ANSIColors.RESET}`\n );\n }\n\n // Output any error messages\n for (const statusObj of dictionariesStatuses) {\n if (statusObj.errorMessage) {\n appLogger(statusObj.errorMessage, {\n level: 'error',\n });\n }\n }\n } catch (error) {\n appLogger(error, {\n level: 'error',\n });\n }\n};\n"],"mappings":"wgBAqCA,MAAa,EAAO,KAAO,IAAyC,CAClE,IAAM,GAAA,EAAA,EAAA,cAAyB,GAAS,eAAe,SAAS,CAEhE,GAAI,CACF,IAAM,GAAA,EAAA,EAAA,kBAA0B,GAAS,cAAc,CAKvD,IAJA,EAAA,EAAA,kBAAiB,GAAS,cAAc,CAIpC,CAFe,MAAMA,EAAAA,aAAa,EAAO,CAE5B,OAEjB,IAAM,GAAA,EAAA,EAAA,qBAAkC,IAAA,GAAW,EAAO,CAEpD,GAAA,EAAA,EAAA,yBAAqD,EAAO,CAG5D,EACJ,MAAM,EAAY,WAAW,gCAAgC,CAE/D,GAAI,CAAC,EAAqC,KACxC,MAAU,MAAM,gCAAgC,CAGlD,IAAI,EACF,EAAqC,KAGnC,GAAS,eACX,EAAqC,OAAO,YAC1C,OA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ACxD,OAAQ,EAAR,CACE,IAAK,UACL,IAAK,WACL,IAAK,UACL,IAAK,aACL,IAAK,qBACL,IAAK,mBACH,MAAO,IACT,IAAK,QACH,MAAO,IACT,QACE,MAAO,MAIP,EAAY,GAAyC,CACzD,OAAQ,EAAR,CACE,IAAK,UACL,IAAK,WACL,IAAK,UACL,IAAK,aACH,OAAOC,EAAAA,WAAW,MACpB,IAAK,qBACL,IAAK,mBACH,OAAOA,EAAAA,WAAW,OACpB,IAAK,QACH,OAAOA,EAAAA,WAAW,IACpB,QACE,OAAOA,EAAAA,WAAW,OAIxB,IAAK,IAAM,KAAK,EAAsB,CACpC,IAAM,EAAO,EAAQ,EAAE,OAAO,CACxB,EAAQ,EAAS,EAAE,OAAO,CAChC,EACE,MAAM,EAAE,cAAc,GAAGA,EAAAA,WAAW,KAAK,GAAG,IAAQ,EAAK,GAAG,EAAE,SAASA,EAAAA,WAAW,KAAK,GAAGA,EAAAA,WAAW,QACtG,CAIH,IAAK,IAAM,KAAa,EAClB,EAAU,cACZ,EAAU,EAAU,aAAc,CAChC,MAAO,QACR,CAAC,OAGC,EAAO,CACd,EAAU,EAAO,CACf,MAAO,QACR,CAAC"}
@@ -1,4 +1,4 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);let e=require(`@intlayer/config/logger`),t=require(`@intlayer/config/node`);var n=class{statuses=[];spinnerTimer=null;spinnerIndex=0;renderedLines=0;spinnerFrames=e.spinnerFrames;isFinished=!1;prefix;lastRenderedState=``;constructor(){this.prefix=(0,t.getConfiguration)().log.prefix}update(e){if(!this.isFinished){for(let t of e){let e=this.statuses.findIndex(e=>e.dictionaryKey===t.dictionaryKey);e>=0?this.statuses[e]=t:this.statuses.push(t)}this.startSpinner(),this.render()}}finish(){this.isFinished=!0,this.stopSpinner(),this.render()}startSpinner(){this.spinnerTimer||this.isFinished||(this.spinnerTimer=setInterval(()=>{this.spinnerIndex=(this.spinnerIndex+1)%this.spinnerFrames.length,this.render()},100))}stopSpinner(){this.spinnerTimer&&=(clearInterval(this.spinnerTimer),null)}render(){let{total:t,done:n,success:r,errors:i}=this.computeProgress(),a=this.spinnerFrames[this.spinnerIndex],o=[],s=n===t,c=`dictionaries: ${n}/${t}`,l=[];r>0&&l.push(`ok: ${r}`),i>0&&l.push((0,e.colorize)(`errors: ${i}`,e.ANSIColors.RED));let u=l.length>0?` (${l.join(`, `)})`:``;s?o.push(`${this.prefix} ${(0,e.colorize)(`✔`,e.ANSIColors.GREEN)} fetched ${c}${u}`):o.push(`${this.prefix} ${(0,e.colorize)(a,e.ANSIColors.BLUE)} fetching ${c}${u}`);let d=o.join(`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../chunk-Bmb41Sf3.cjs`);let e=require(`@intlayer/config/logger`),t=require(`@intlayer/config/node`);var n=class{statuses=[];spinnerTimer=null;spinnerIndex=0;renderedLines=0;spinnerFrames=e.spinnerFrames;isFinished=!1;prefix;lastRenderedState=``;constructor(){this.prefix=(0,t.getConfiguration)().log.prefix}update(e){if(!this.isFinished){for(let t of e){let e=this.statuses.findIndex(e=>e.dictionaryKey===t.dictionaryKey);e>=0?this.statuses[e]=t:this.statuses.push(t)}this.startSpinner(),this.render()}}finish(){this.isFinished=!0,this.stopSpinner(),this.render()}startSpinner(){this.spinnerTimer||this.isFinished||(this.spinnerTimer=setInterval(()=>{this.spinnerIndex=(this.spinnerIndex+1)%this.spinnerFrames.length,this.render()},100))}stopSpinner(){this.spinnerTimer&&=(clearInterval(this.spinnerTimer),null)}render(){let{total:t,done:n,success:r,errors:i}=this.computeProgress(),a=this.spinnerFrames[this.spinnerIndex],o=[],s=n===t,c=`dictionaries: ${n}/${t}`,l=[];r>0&&l.push(`ok: ${r}`),i>0&&l.push((0,e.colorize)(`errors: ${i}`,e.ANSIColors.RED));let u=l.length>0?` (${l.join(`, `)})`:``;s?o.push(`${this.prefix} ${(0,e.colorize)(`✔`,e.ANSIColors.GREEN)} fetched ${c}${u}`):o.push(`${this.prefix} ${(0,e.colorize)(a,e.ANSIColors.BLUE)} fetching ${c}${u}`);let d=o.join(`
2
2
  `);if(d===this.lastRenderedState)return;this.lastRenderedState=d,this.renderedLines>0&&process.stdout.write(`\x1b[${this.renderedLines}F`);let f=Math.max(this.renderedLines,o.length);for(let e=0;e<f;e++){process.stdout.write(`\x1B[2K`);let t=o[e];t!==void 0&&process.stdout.write(t),process.stdout.write(`
3
3
  `)}this.renderedLines=o.length}computeProgress(){let e=new Set(this.statuses.map(e=>e.dictionaryKey)),t=new Set([`fetched`,`imported`,`updated`,`up-to-date`,`reimported in JSON`,`new content file`,`error`]),n=new Set([`fetched`,`imported`,`updated`,`up-to-date`,`reimported in JSON`,`new content file`]),r=this.statuses.filter(e=>t.has(e.status)).length,i=this.statuses.filter(e=>n.has(e.status)).length,a=this.statuses.filter(e=>e.status===`error`).length;return{total:e.size,done:r,success:i,errors:a}}};exports.PullLogger=n;
4
4
  //# sourceMappingURL=pullLog.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"pullLog.cjs","names":["spinnerFrames","ANSIColors"],"sources":["../../../src/push/pullLog.ts"],"sourcesContent":["import type { DictionaryStatus } from '@intlayer/chokidar/build';\nimport { ANSIColors, colorize, spinnerFrames } from '@intlayer/config/logger';\nimport { getConfiguration } from '@intlayer/config/node';\n\nexport type PullStatus = {\n dictionaryKey: string;\n status: DictionaryStatus | 'pending' | 'fetching';\n errorMessage?: string;\n};\n\nexport class PullLogger {\n private statuses: PullStatus[] = [];\n private spinnerTimer: NodeJS.Timeout | null = null;\n private spinnerIndex = 0;\n private renderedLines = 0;\n private readonly spinnerFrames = spinnerFrames;\n private isFinished = false;\n private readonly prefix: string;\n private lastRenderedState: string = '';\n\n constructor() {\n const configuration = getConfiguration();\n this.prefix = configuration.log.prefix;\n }\n\n update(newStatuses: PullStatus[]) {\n if (this.isFinished) return;\n for (const status of newStatuses) {\n const index = this.statuses.findIndex(\n (s) => s.dictionaryKey === status.dictionaryKey\n );\n if (index >= 0) {\n this.statuses[index] = status;\n } else {\n this.statuses.push(status);\n }\n }\n\n this.startSpinner();\n this.render();\n }\n\n finish() {\n this.isFinished = true;\n this.stopSpinner();\n this.render();\n }\n\n private startSpinner() {\n if (this.spinnerTimer || this.isFinished) return;\n this.spinnerTimer = setInterval(() => {\n this.spinnerIndex = (this.spinnerIndex + 1) % this.spinnerFrames.length;\n this.render();\n }, 100);\n }\n\n private stopSpinner() {\n if (!this.spinnerTimer) return;\n clearInterval(this.spinnerTimer);\n this.spinnerTimer = null;\n }\n\n private render() {\n const { total, done, success, errors } = this.computeProgress();\n\n const frame = this.spinnerFrames[this.spinnerIndex];\n const lines: string[] = [];\n\n const isDone = done === total;\n const progressLabel = `dictionaries: ${done}/${total}`;\n const details: string[] = [];\n if (success > 0) details.push(`ok: ${success}`);\n if (errors > 0) details.push(colorize(`errors: ${errors}`, ANSIColors.RED));\n\n const suffix = details.length > 0 ? ` (${details.join(', ')})` : '';\n\n if (isDone) {\n lines.push(\n `${this.prefix} ${colorize('✔', ANSIColors.GREEN)} fetched ${progressLabel}${suffix}`\n );\n } else {\n lines.push(\n `${this.prefix} ${colorize(frame, ANSIColors.BLUE)} fetching ${progressLabel}${suffix}`\n );\n }\n\n const currentState = lines.join('\\n');\n if (currentState === this.lastRenderedState) {\n return;\n }\n this.lastRenderedState = currentState;\n\n if (this.renderedLines > 0) {\n process.stdout.write(`\\x1b[${this.renderedLines}F`);\n }\n\n const totalLinesToClear = Math.max(this.renderedLines, lines.length);\n for (let i = 0; i < totalLinesToClear; i++) {\n process.stdout.write('\\x1b[2K');\n const line = lines[i];\n if (line !== undefined) {\n process.stdout.write(line);\n }\n process.stdout.write('\\n');\n }\n\n this.renderedLines = lines.length;\n }\n\n private computeProgress() {\n const keys = new Set(this.statuses.map((s) => s.dictionaryKey));\n\n const doneSet = new Set<DictionaryStatus | 'error'>([\n 'fetched',\n 'imported',\n 'updated',\n 'up-to-date',\n 'reimported in JSON',\n 'new content file',\n 'error',\n ] as const);\n\n const successesSet = new Set<DictionaryStatus>([\n 'fetched',\n 'imported',\n 'updated',\n 'up-to-date',\n 'reimported in JSON',\n 'new content file',\n ] as const);\n\n const done = this.statuses.filter((s) =>\n doneSet.has(s.status as any)\n ).length;\n const success = this.statuses.filter((s) =>\n successesSet.has(s.status as any)\n ).length;\n const errors = this.statuses.filter((s) => s.status === 'error').length;\n\n return {\n total: keys.size,\n done,\n success,\n errors,\n } as const;\n }\n}\n"],"mappings":"4LAUA,IAAa,EAAb,KAAwB,CACtB,SAAiC,EAAE,CACnC,aAA8C,KAC9C,aAAuB,EACvB,cAAwB,EACxB,cAAiCA,EAAAA,cACjC,WAAqB,GACrB,OACA,kBAAoC,GAEpC,aAAc,CAEZ,KAAK,QAAA,EAAA,EAAA,mBADmC,CACZ,IAAI,OAGlC,OAAO,EAA2B,CAC5B,SAAK,WACT,KAAK,IAAM,KAAU,EAAa,CAChC,IAAM,EAAQ,KAAK,SAAS,UACzB,GAAM,EAAE,gBAAkB,EAAO,cACnC,CACG,GAAS,EACX,KAAK,SAAS,GAAS,EAEvB,KAAK,SAAS,KAAK,EAAO,CAI9B,KAAK,cAAc,CACnB,KAAK,QAAQ,EAGf,QAAS,CACP,KAAK,WAAa,GAClB,KAAK,aAAa,CAClB,KAAK,QAAQ,CAGf,cAAuB,CACjB,KAAK,cAAgB,KAAK,aAC9B,KAAK,aAAe,gBAAkB,CACpC,KAAK,cAAgB,KAAK,aAAe,GAAK,KAAK,cAAc,OACjE,KAAK,QAAQ,EACZ,IAAI,EAGT,aAAsB,CACf,AAEL,KAAK,gBADL,cAAc,KAAK,aAAa,CACZ,MAGtB,QAAiB,CACf,GAAM,CAAE,QAAO,OAAM,UAAS,UAAW,KAAK,iBAAiB,CAEzD,EAAQ,KAAK,cAAc,KAAK,cAChC,EAAkB,EAAE,CAEpB,EAAS,IAAS,EAClB,EAAgB,iBAAiB,EAAK,GAAG,IACzC,EAAoB,EAAE,CACxB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ClC,CAAC,OACI,EAAS,KAAK,SAAS,OAAQ,GAAM,EAAE,SAAW,QAAQ,CAAC,OAEjE,MAAO,CACL,MAAO,EAAK,KACZ,OACA,UACA,SACD"}
1
+ {"version":3,"file":"pullLog.cjs","names":["spinnerFrames","ANSIColors"],"sources":["../../../src/push/pullLog.ts"],"sourcesContent":["import type { DictionaryStatus } from '@intlayer/chokidar/build';\nimport { ANSIColors, colorize, spinnerFrames } from '@intlayer/config/logger';\nimport { getConfiguration } from '@intlayer/config/node';\n\nexport type PullStatus = {\n dictionaryKey: string;\n status: DictionaryStatus | 'pending' | 'fetching';\n errorMessage?: string;\n};\n\nexport class PullLogger {\n private statuses: PullStatus[] = [];\n private spinnerTimer: NodeJS.Timeout | null = null;\n private spinnerIndex = 0;\n private renderedLines = 0;\n private readonly spinnerFrames = spinnerFrames;\n private isFinished = false;\n private readonly prefix: string;\n private lastRenderedState: string = '';\n\n constructor() {\n const configuration = getConfiguration();\n this.prefix = configuration.log.prefix;\n }\n\n update(newStatuses: PullStatus[]) {\n if (this.isFinished) return;\n for (const status of newStatuses) {\n const index = this.statuses.findIndex(\n (s) => s.dictionaryKey === status.dictionaryKey\n );\n if (index >= 0) {\n this.statuses[index] = status;\n } else {\n this.statuses.push(status);\n }\n }\n\n this.startSpinner();\n this.render();\n }\n\n finish() {\n this.isFinished = true;\n this.stopSpinner();\n this.render();\n }\n\n private startSpinner() {\n if (this.spinnerTimer || this.isFinished) return;\n this.spinnerTimer = setInterval(() => {\n this.spinnerIndex = (this.spinnerIndex + 1) % this.spinnerFrames.length;\n this.render();\n }, 100);\n }\n\n private stopSpinner() {\n if (!this.spinnerTimer) return;\n clearInterval(this.spinnerTimer);\n this.spinnerTimer = null;\n }\n\n private render() {\n const { total, done, success, errors } = this.computeProgress();\n\n const frame = this.spinnerFrames[this.spinnerIndex];\n const lines: string[] = [];\n\n const isDone = done === total;\n const progressLabel = `dictionaries: ${done}/${total}`;\n const details: string[] = [];\n if (success > 0) details.push(`ok: ${success}`);\n if (errors > 0) details.push(colorize(`errors: ${errors}`, ANSIColors.RED));\n\n const suffix = details.length > 0 ? ` (${details.join(', ')})` : '';\n\n if (isDone) {\n lines.push(\n `${this.prefix} ${colorize('✔', ANSIColors.GREEN)} fetched ${progressLabel}${suffix}`\n );\n } else {\n lines.push(\n `${this.prefix} ${colorize(frame, ANSIColors.BLUE)} fetching ${progressLabel}${suffix}`\n );\n }\n\n const currentState = lines.join('\\n');\n if (currentState === this.lastRenderedState) {\n return;\n }\n this.lastRenderedState = currentState;\n\n if (this.renderedLines > 0) {\n process.stdout.write(`\\x1b[${this.renderedLines}F`);\n }\n\n const totalLinesToClear = Math.max(this.renderedLines, lines.length);\n for (let i = 0; i < totalLinesToClear; i++) {\n process.stdout.write('\\x1b[2K');\n const line = lines[i];\n if (line !== undefined) {\n process.stdout.write(line);\n }\n process.stdout.write('\\n');\n }\n\n this.renderedLines = lines.length;\n }\n\n private computeProgress() {\n const keys = new Set(this.statuses.map((s) => s.dictionaryKey));\n\n const doneSet = new Set<DictionaryStatus | 'error'>([\n 'fetched',\n 'imported',\n 'updated',\n 'up-to-date',\n 'reimported in JSON',\n 'new content file',\n 'error',\n ] as const);\n\n const successesSet = new Set<DictionaryStatus>([\n 'fetched',\n 'imported',\n 'updated',\n 'up-to-date',\n 'reimported in JSON',\n 'new content file',\n ] as const);\n\n const done = this.statuses.filter((s) =>\n doneSet.has(s.status as any)\n ).length;\n const success = this.statuses.filter((s) =>\n successesSet.has(s.status as any)\n ).length;\n const errors = this.statuses.filter((s) => s.status === 'error').length;\n\n return {\n total: keys.size,\n done,\n success,\n errors,\n } as const;\n }\n}\n"],"mappings":"gLAUA,IAAa,EAAb,KAAwB,CACtB,SAAiC,EAAE,CACnC,aAA8C,KAC9C,aAAuB,EACvB,cAAwB,EACxB,cAAiCA,EAAAA,cACjC,WAAqB,GACrB,OACA,kBAAoC,GAEpC,aAAc,CAEZ,KAAK,QAAA,EAAA,EAAA,mBADmC,CACZ,IAAI,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ErB,KAAK,cAAgB,GACvB,QAAQ,OAAO,MAAM,QAAQ,KAAK,cAAc,GAAG,CAGrD,IAAM,EAAoB,KAAK,IAAI,KAAK,cAAe,EAAM,OAAO,CACpE,IAAK,IAAI,EAAI,EAAG,EAAI,EAAmB,IAAK,CAC1C,QAAQ,OAAO,MAAM,UAAU,CAC/B,IAAM,EAAO,EAAM,GACf,IAAS,IAAA,IACX,QAAQ,OAAO,MAAM,EAAK,CAE5B,QAAQ,OAAO,MAAM;EAAK,CAG5B,KAAK,cAAgB,EAAM,OAG7B,iBAA0B,CACxB,IAAM,EAAO,IAAI,IAAI,KAAK,SAAS,IAAK,GAAM,EAAE,cAAc,CAAC,CAEzD,EAAU,IAAI,IAAgC,CAClD,UACA,WACA,UACA,aACA,qBACA,mBACA,QACD,CAAU,CAEL,EAAe,IAAI,IAAsB,CAC7C,UACA,WACA,UACA,aACA,qBACA,mBACD,CAAU,CAEL,EAAO,KAAK,SAAS,OAAQ,GACjC,EAAQ,IAAI,EAAE,OAAc,CAC7B,CAAC,OACI,EAAU,KAAK,SAAS,OAAQ,GACpC,EAAa,IAAI,EAAE,OAAc,CAClC,CAAC,OACI,EAAS,KAAK,SAAS,OAAQ,GAAM,EAAE,SAAW,QAAQ,CAAC,OAEjE,MAAO,CACL,MAAO,EAAK,KACZ,OACA,UACA,SACD"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`),t=require(`../utils/checkAccess.cjs`),n=require(`../pushLog.cjs`);let r=require(`node:path`),i=require(`@intlayer/chokidar/build`),a=require(`@intlayer/chokidar/cli`),o=require(`@intlayer/chokidar/utils`),s=require(`@intlayer/config/logger`),c=require(`@intlayer/config/node`),l=require(`@intlayer/unmerged-dictionaries-entry`),u=require(`@intlayer/api`),d=require(`node:fs/promises`);d=e.__toESM(d);const f={pushed:{icon:`✔`,color:s.ANSIColors.GREEN},modified:{icon:`✔`,color:s.ANSIColors.GREEN},error:{icon:`✖`,color:s.ANSIColors.RED},default:{icon:`⏲`,color:s.ANSIColors.BLUE}},p=e=>f[e]??f.default,m=async e=>{let d=(0,c.getConfiguration)(e?.configOptions);(0,a.logConfigDetails)(e?.configOptions);let f=(0,s.getAppLogger)(d);e?.build===!0?await(0,i.prepareIntlayer)(d,{forceRun:!0}):e?.build===void 0&&await(0,i.prepareIntlayer)(d);try{if(!await t.checkCMSAuth(d))return;let c=(0,u.getIntlayerAPIProxy)(void 0,d),m=(0,l.getUnmergedDictionaries)(d),g=Object.values(m).flat(),_=Array.from(new Set(g.map(e=>e.location).filter(e=>e&&![`remote`,`local`,`hybrid`].includes(e)))),v=[];if(_.length>0){let{multiselect:e,confirm:t,isCancel:n}=await import(`@clack/prompts`);if(_.length===1){let e=await t({message:`Do you want to push dictionaries with custom location ${(0,s.colorize)(_[0],s.ANSIColors.BLUE,s.ANSIColors.RESET)}?`,initialValue:!1});if(n(e))return;e&&(v=[_[0]])}else{let t=await e({message:`Select custom locations to push:`,options:_.map(e=>({value:e,label:e})),required:!1});if(n(t))return;v=t}}let y=g.filter(e=>{let t=e.location??d.dictionary?.location??`local`;return t===`remote`||t===`hybrid`||v.includes(t)});if(y.length===0){f(`No dictionaries found to push. Only dictionaries with location ${(0,s.colorize)(`remote`,s.ANSIColors.BLUE,s.ANSIColors.RESET)}, ${(0,s.colorize)(`hybrid`,s.ANSIColors.BLUE,s.ANSIColors.RESET)} or selected custom locations are pushed.`,{level:`warn`}),f(`You can set the location in your dictionary file (e.g. ${(0,s.colorize)(`{ key: 'my-key', location: 'hybrid', ... }`,s.ANSIColors.BLUE,s.ANSIColors.RESET)} or globally in your intlayer.config.ts file (e.g. ${(0,s.colorize)(`{ dictionary: { location: 'hybrid' } }`,s.ANSIColors.BLUE,s.ANSIColors.RESET)}).`,{level:`info`});return}let b=Object.keys(m);if(e?.dictionaries){let t=e.dictionaries.filter(e=>!b.includes(e));t.length>0&&f(`The following dictionaries do not exist: ${t.join(`, `)} and have been ignored.`,{level:`error`}),y=y.filter(t=>e.dictionaries?.includes(t.key))}if(e?.gitOptions){let t=await(0,a.listGitFiles)(e.gitOptions);y=y.filter(e=>t.includes((0,r.join)(d.system.baseDir,e.filePath??``)))}if(y.length===0){f(`No local dictionaries found`,{level:`error`});return}f(`Pushing dictionaries:`);let x=y.map(e=>({dictionary:e,status:`pending`})),S=new n.PushLogger;S.update(x.map(e=>({dictionaryKey:e.dictionary.key,status:`pending`})));let C=[];await(0,o.parallelize)(x,async e=>{e.status=`pushing`,S.update([{dictionaryKey:e.dictionary.key,status:`pushing`}]);try{let t=await c.dictionary.pushDictionaries([e.dictionary]),n=t.data?.updatedDictionaries??[],r=t.data?.newDictionaries??[],a=[...n,...r];for(let e of a){let t=m[e.key]?.find(t=>t.localId===e.localId);t&&await(0,i.writeContentDeclaration)({...t,id:e.id},d)}n.some(t=>t.key===e.dictionary.key)?(e.status=`modified`,C.push(e.dictionary),S.update([{dictionaryKey:e.dictionary.key,status:`modified`}])):r.some(t=>t.key===e.dictionary.key)?(e.status=`pushed`,C.push(e.dictionary),S.update([{dictionaryKey:e.dictionary.key,status:`pushed`}])):e.status=`unknown`}catch(t){e.status=`error`,e.error=t,e.errorMessage=`Error pushing dictionary ${e.dictionary.key}: ${t}`,S.update([{dictionaryKey:e.dictionary.key,status:`error`}])}},5),S.finish();for(let e of x){let{icon:t,color:n}=p(e.status);f(` - ${(0,s.colorizeKey)(e.dictionary.key)} ${s.ANSIColors.GREY}[${n}${t} ${e.status}${s.ANSIColors.GREY}]${s.ANSIColors.RESET}`)}for(let e of x)e.errorMessage&&f(e.errorMessage,{level:`error`});let w=e?.deleteLocaleDictionary,T=e?.keepLocaleDictionary;if(w&&T)throw Error(`Cannot specify both --deleteLocaleDictionary and --keepLocaleDictionary options.`);if(w)await h(C,e);else if(!T){let t=C.filter(e=>e.location===`remote`),n=t.map(e=>e.key);if(t.length>0){let{confirm:r,isCancel:i}=await import(`@clack/prompts`),a=await r({message:`Do you want to delete the local dictionaries that were successfully pushed? ${(0,s.colorize)(`(Dictionaries:`,s.ANSIColors.GREY,s.ANSIColors.RESET)} ${(0,s.colorizeKey)(n)}${(0,s.colorize)(`)`,s.ANSIColors.GREY,s.ANSIColors.RESET)}`,initialValue:!1});if(i(a))return;a&&await h(t,e)}}}catch(e){f(e,{level:`error`})}},h=async(e,t)=>{let n=(0,s.getAppLogger)((0,c.getConfiguration)(t?.configOptions)),r=new Set;for(let t of e){let{filePath:e}=t;if(!e){n(`Dictionary ${(0,s.colorizeKey)(t.key)} does not have a file path`,{level:`error`});continue}r.add(e)}for(let e of r)try{let t=await d.lstat(e);t.isFile()?(await d.unlink(e),n(`Deleted file ${(0,o.formatPath)(e)}`,{})):t.isDirectory()?n(`Path is a directory ${(0,o.formatPath)(e)}, skipping.`,{}):n(`Unknown file type for ${(0,o.formatPath)(e)}, skipping.`,{})}catch(t){n(`Error deleting ${(0,o.formatPath)(e)}: ${t}`,{level:`error`})}};exports.push=m;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../chunk-Bmb41Sf3.cjs`),t=require(`../utils/checkAccess.cjs`),n=require(`../pushLog.cjs`);let r=require(`node:path`),i=require(`@intlayer/chokidar/build`),a=require(`@intlayer/chokidar/cli`),o=require(`@intlayer/chokidar/utils`),s=require(`@intlayer/config/logger`),c=require(`@intlayer/config/node`),l=require(`@intlayer/unmerged-dictionaries-entry`),u=require(`@intlayer/api`),d=require(`node:fs/promises`);d=e.t(d);const f={pushed:{icon:`✔`,color:s.ANSIColors.GREEN},modified:{icon:`✔`,color:s.ANSIColors.GREEN},error:{icon:`✖`,color:s.ANSIColors.RED},default:{icon:`⏲`,color:s.ANSIColors.BLUE}},p=e=>f[e]??f.default,m=async e=>{let d=(0,c.getConfiguration)(e?.configOptions);(0,a.logConfigDetails)(e?.configOptions);let f=(0,s.getAppLogger)(d);e?.build===!0?await(0,i.prepareIntlayer)(d,{forceRun:!0}):e?.build===void 0&&await(0,i.prepareIntlayer)(d);try{if(!await t.checkCMSAuth(d))return;let c=(0,u.getIntlayerAPIProxy)(void 0,d),m=(0,l.getUnmergedDictionaries)(d),g=Object.values(m).flat(),_=Array.from(new Set(g.map(e=>e.location).filter(e=>e&&![`remote`,`local`,`hybrid`].includes(e)))),v=[];if(_.length>0){let{multiselect:e,confirm:t,isCancel:n}=await import(`@clack/prompts`);if(_.length===1){let e=await t({message:`Do you want to push dictionaries with custom location ${(0,s.colorize)(_[0],s.ANSIColors.BLUE,s.ANSIColors.RESET)}?`,initialValue:!1});if(n(e))return;e&&(v=[_[0]])}else{let t=await e({message:`Select custom locations to push:`,options:_.map(e=>({value:e,label:e})),required:!1});if(n(t))return;v=t}}let y=g.filter(e=>{let t=e.location??d.dictionary?.location??`local`;return t===`remote`||t===`hybrid`||v.includes(t)});if(y.length===0){f(`No dictionaries found to push. Only dictionaries with location ${(0,s.colorize)(`remote`,s.ANSIColors.BLUE,s.ANSIColors.RESET)}, ${(0,s.colorize)(`hybrid`,s.ANSIColors.BLUE,s.ANSIColors.RESET)} or selected custom locations are pushed.`,{level:`warn`}),f(`You can set the location in your dictionary file (e.g. ${(0,s.colorize)(`{ key: 'my-key', location: 'hybrid', ... }`,s.ANSIColors.BLUE,s.ANSIColors.RESET)} or globally in your intlayer.config.ts file (e.g. ${(0,s.colorize)(`{ dictionary: { location: 'hybrid' } }`,s.ANSIColors.BLUE,s.ANSIColors.RESET)}).`,{level:`info`});return}let b=Object.keys(m);if(e?.dictionaries){let t=e.dictionaries.filter(e=>!b.includes(e));t.length>0&&f(`The following dictionaries do not exist: ${t.join(`, `)} and have been ignored.`,{level:`error`}),y=y.filter(t=>e.dictionaries?.includes(t.key))}if(e?.gitOptions){let t=await(0,a.listGitFiles)(e.gitOptions);y=y.filter(e=>t.includes((0,r.join)(d.system.baseDir,e.filePath??``)))}if(y.length===0){f(`No local dictionaries found`,{level:`error`});return}f(`Pushing dictionaries:`);let x=y.map(e=>({dictionary:e,status:`pending`})),S=new n.PushLogger;S.update(x.map(e=>({dictionaryKey:e.dictionary.key,status:`pending`})));let C=[];await(0,o.parallelize)(x,async e=>{e.status=`pushing`,S.update([{dictionaryKey:e.dictionary.key,status:`pushing`}]);try{let t=await c.dictionary.pushDictionaries([e.dictionary]),n=t.data?.updatedDictionaries??[],r=t.data?.newDictionaries??[],a=[...n,...r];for(let e of a){let t=m[e.key]?.find(t=>t.localId===e.localId);t&&await(0,i.writeContentDeclaration)({...t,id:e.id},d)}n.some(t=>t.key===e.dictionary.key)?(e.status=`modified`,C.push(e.dictionary),S.update([{dictionaryKey:e.dictionary.key,status:`modified`}])):r.some(t=>t.key===e.dictionary.key)?(e.status=`pushed`,C.push(e.dictionary),S.update([{dictionaryKey:e.dictionary.key,status:`pushed`}])):e.status=`unknown`}catch(t){e.status=`error`,e.error=t,e.errorMessage=`Error pushing dictionary ${e.dictionary.key}: ${t}`,S.update([{dictionaryKey:e.dictionary.key,status:`error`}])}},5),S.finish();for(let e of x){let{icon:t,color:n}=p(e.status);f(` - ${(0,s.colorizeKey)(e.dictionary.key)} ${s.ANSIColors.GREY}[${n}${t} ${e.status}${s.ANSIColors.GREY}]${s.ANSIColors.RESET}`)}for(let e of x)e.errorMessage&&f(e.errorMessage,{level:`error`});let w=e?.deleteLocaleDictionary,T=e?.keepLocaleDictionary;if(w&&T)throw Error(`Cannot specify both --deleteLocaleDictionary and --keepLocaleDictionary options.`);if(w)await h(C,e);else if(!T){let t=C.filter(e=>e.location===`remote`),n=t.map(e=>e.key);if(t.length>0){let{confirm:r,isCancel:i}=await import(`@clack/prompts`),a=await r({message:`Do you want to delete the local dictionaries that were successfully pushed? ${(0,s.colorize)(`(Dictionaries:`,s.ANSIColors.GREY,s.ANSIColors.RESET)} ${(0,s.colorizeKey)(n)}${(0,s.colorize)(`)`,s.ANSIColors.GREY,s.ANSIColors.RESET)}`,initialValue:!1});if(i(a))return;a&&await h(t,e)}}}catch(e){f(e,{level:`error`})}},h=async(e,t)=>{let n=(0,s.getAppLogger)((0,c.getConfiguration)(t?.configOptions)),r=new Set;for(let t of e){let{filePath:e}=t;if(!e){n(`Dictionary ${(0,s.colorizeKey)(t.key)} does not have a file path`,{level:`error`});continue}r.add(e)}for(let e of r)try{let t=await d.lstat(e);t.isFile()?(await d.unlink(e),n(`Deleted file ${(0,o.formatPath)(e)}`,{})):t.isDirectory()?n(`Path is a directory ${(0,o.formatPath)(e)}, skipping.`,{}):n(`Unknown file type for ${(0,o.formatPath)(e)}, skipping.`,{})}catch(t){n(`Error deleting ${(0,o.formatPath)(e)}: ${t}`,{level:`error`})}};exports.push=m;
2
2
  //# sourceMappingURL=push.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"push.cjs","names":["ANSIColors","checkCMSAuth","PushLogger","fsPromises"],"sources":["../../../src/push/push.ts"],"sourcesContent":["import * as fsPromises from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { getIntlayerAPIProxy } from '@intlayer/api';\nimport {\n prepareIntlayer,\n writeContentDeclaration,\n} from '@intlayer/chokidar/build';\nimport {\n type ListGitFilesOptions,\n listGitFiles,\n logConfigDetails,\n} from '@intlayer/chokidar/cli';\nimport { formatPath, parallelize } from '@intlayer/chokidar/utils';\nimport {\n ANSIColors,\n colorize,\n colorizeKey,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { PushLogger, type PushStatus } from '../pushLog';\nimport { checkCMSAuth } from '../utils/checkAccess';\n\ntype PushOptions = {\n deleteLocaleDictionary?: boolean;\n keepLocaleDictionary?: boolean;\n dictionaries?: string[];\n gitOptions?: ListGitFilesOptions;\n configOptions?: GetConfigurationOptions;\n build?: boolean;\n};\n\ntype DictionariesStatus = {\n dictionary: Dictionary;\n status: 'pending' | 'pushing' | 'modified' | 'pushed' | 'unknown' | 'error';\n error?: Error;\n errorMessage?: string;\n};\n\n// Print per-dictionary summary similar to loadDictionaries\nconst statusIconsAndColors = {\n pushed: { icon: '✔', color: ANSIColors.GREEN },\n modified: { icon: '✔', color: ANSIColors.GREEN },\n error: { icon: '✖', color: ANSIColors.RED },\n default: { icon: '⏲', color: ANSIColors.BLUE },\n};\n\nconst getIconAndColor = (status: DictionariesStatus['status']) => {\n return (\n statusIconsAndColors[status as keyof typeof statusIconsAndColors] ??\n statusIconsAndColors.default\n );\n};\n\n/**\n * Get all local dictionaries and push them simultaneously.\n */\nexport const push = async (options?: PushOptions): Promise<void> => {\n const config = getConfiguration(options?.configOptions);\n logConfigDetails(options?.configOptions);\n\n const appLogger = getAppLogger(config);\n\n if (options?.build === true) {\n await prepareIntlayer(config, { forceRun: true });\n } else if (typeof options?.build === 'undefined') {\n await prepareIntlayer(config);\n }\n\n try {\n const hasCMSAuth = await checkCMSAuth(config);\n\n if (!hasCMSAuth) return;\n\n const intlayerAPI = getIntlayerAPIProxy(undefined, config);\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(config);\n const allDictionaries = Object.values(unmergedDictionariesRecord).flat();\n\n const customLocations = Array.from(\n new Set(\n allDictionaries\n .map((dictionary) => dictionary.location)\n .filter(\n (location) =>\n location && !['remote', 'local', 'hybrid'].includes(location)\n )\n )\n ) as string[];\n\n let selectedCustomLocations: string[] = [];\n\n if (customLocations.length > 0) {\n const { multiselect, confirm, isCancel } = await import('@clack/prompts');\n\n if (customLocations.length === 1) {\n const shouldPush = await confirm({\n message: `Do you want to push dictionaries with custom location ${colorize(customLocations[0], ANSIColors.BLUE, ANSIColors.RESET)}?`,\n initialValue: false,\n });\n\n if (isCancel(shouldPush)) {\n return;\n }\n\n if (shouldPush) {\n selectedCustomLocations = [customLocations[0]];\n }\n } else {\n const selected = await multiselect({\n message: 'Select custom locations to push:',\n options: customLocations.map((location) => ({\n value: location,\n label: location,\n })),\n required: false,\n });\n\n if (isCancel(selected)) {\n return;\n }\n\n selectedCustomLocations = selected as string[];\n }\n }\n\n let dictionaries: Dictionary[] = allDictionaries.filter((dictionary) => {\n const location =\n dictionary.location ?? config.dictionary?.location ?? 'local';\n\n return (\n location === 'remote' ||\n location === 'hybrid' ||\n selectedCustomLocations.includes(location)\n );\n });\n\n // Check if the dictionaries list is empty after filtering by location\n if (dictionaries.length === 0) {\n appLogger(\n `No dictionaries found to push. Only dictionaries with location ${colorize('remote', ANSIColors.BLUE, ANSIColors.RESET)}, ${colorize('hybrid', ANSIColors.BLUE, ANSIColors.RESET)} or selected custom locations are pushed.`,\n { level: 'warn' }\n );\n appLogger(\n `You can set the location in your dictionary file (e.g. ${colorize(\"{ key: 'my-key', location: 'hybrid', ... }\", ANSIColors.BLUE, ANSIColors.RESET)} or globally in your intlayer.config.ts file (e.g. ${colorize(\"{ dictionary: { location: 'hybrid' } }\", ANSIColors.BLUE, ANSIColors.RESET)}).`,\n { level: 'info' }\n );\n return;\n }\n\n const existingDictionariesKeys: string[] = Object.keys(\n unmergedDictionariesRecord\n );\n\n if (options?.dictionaries) {\n // Check if the provided dictionaries exist\n const noneExistingDictionariesOption = options.dictionaries.filter(\n (dictionaryId) => !existingDictionariesKeys.includes(dictionaryId)\n );\n\n if (noneExistingDictionariesOption.length > 0) {\n appLogger(\n `The following dictionaries do not exist: ${noneExistingDictionariesOption.join(\n ', '\n )} and have been ignored.`,\n {\n level: 'error',\n }\n );\n }\n\n // Filter the dictionaries from the provided list of IDs\n dictionaries = dictionaries.filter((dictionary) =>\n options.dictionaries?.includes(dictionary.key)\n );\n }\n\n if (options?.gitOptions) {\n const gitFiles = await listGitFiles(options.gitOptions);\n\n dictionaries = dictionaries.filter((dictionary) =>\n gitFiles.includes(\n join(config.system.baseDir, dictionary.filePath ?? '')\n )\n );\n }\n\n // Check if the dictionaries list is empty\n if (dictionaries.length === 0) {\n appLogger('No local dictionaries found', {\n level: 'error',\n });\n return;\n }\n\n appLogger('Pushing dictionaries:');\n\n // Prepare dictionaries statuses\n const dictionariesStatuses: DictionariesStatus[] = dictionaries.map(\n (dictionary) => ({\n dictionary,\n status: 'pending',\n })\n );\n\n // Initialize aggregated logger similar to loadDictionaries\n const logger = new PushLogger();\n logger.update(\n dictionariesStatuses.map<PushStatus>((s) => ({\n dictionaryKey: s.dictionary.key,\n status: 'pending',\n }))\n );\n\n const successfullyPushedDictionaries: Dictionary[] = [];\n\n const processDictionary = async (\n statusObj: DictionariesStatus\n ): Promise<void> => {\n statusObj.status = 'pushing';\n logger.update([\n { dictionaryKey: statusObj.dictionary.key, status: 'pushing' },\n ]);\n\n try {\n const pushResult = await intlayerAPI.dictionary.pushDictionaries([\n statusObj.dictionary,\n ]);\n\n const updatedDictionaries = pushResult.data?.updatedDictionaries ?? [];\n const newDictionaries = pushResult.data?.newDictionaries ?? [];\n\n const allDictionaries = [...updatedDictionaries, ...newDictionaries];\n\n for (const remoteDictionaryData of allDictionaries) {\n const localDictionary = unmergedDictionariesRecord[\n remoteDictionaryData.key\n ]?.find(\n (dictionary) => dictionary.localId === remoteDictionaryData.localId\n );\n\n if (!localDictionary) continue;\n\n await writeContentDeclaration(\n { ...localDictionary, id: remoteDictionaryData.id },\n config\n );\n }\n\n if (\n updatedDictionaries.some(\n (dictionary) => dictionary.key === statusObj.dictionary.key\n )\n ) {\n statusObj.status = 'modified';\n successfullyPushedDictionaries.push(statusObj.dictionary);\n logger.update([\n { dictionaryKey: statusObj.dictionary.key, status: 'modified' },\n ]);\n } else if (\n newDictionaries.some(\n (dictionary) => dictionary.key === statusObj.dictionary.key\n )\n ) {\n statusObj.status = 'pushed';\n successfullyPushedDictionaries.push(statusObj.dictionary);\n logger.update([\n { dictionaryKey: statusObj.dictionary.key, status: 'pushed' },\n ]);\n } else {\n statusObj.status = 'unknown';\n }\n } catch (error) {\n statusObj.status = 'error';\n statusObj.error = error as Error;\n statusObj.errorMessage = `Error pushing dictionary ${statusObj.dictionary.key}: ${error}`;\n logger.update([\n { dictionaryKey: statusObj.dictionary.key, status: 'error' },\n ]);\n }\n };\n\n // Process dictionaries in parallel with a concurrency limit (reuse parallelize)\n await parallelize(dictionariesStatuses, processDictionary, 5);\n\n // Stop the logger and render final state\n logger.finish();\n\n for (const dictionaryStatus of dictionariesStatuses) {\n const { icon, color } = getIconAndColor(dictionaryStatus.status);\n appLogger(\n ` - ${colorizeKey(dictionaryStatus.dictionary.key)} ${ANSIColors.GREY}[${color}${icon} ${dictionaryStatus.status}${ANSIColors.GREY}]${ANSIColors.RESET}`\n );\n }\n\n // Output any error messages\n for (const statusObj of dictionariesStatuses) {\n if (statusObj.errorMessage) {\n appLogger(statusObj.errorMessage, {\n level: 'error',\n });\n }\n }\n\n // Handle delete or keep options\n const deleteOption = options?.deleteLocaleDictionary;\n const keepOption = options?.keepLocaleDictionary;\n\n if (deleteOption && keepOption) {\n throw new Error(\n 'Cannot specify both --deleteLocaleDictionary and --keepLocaleDictionary options.'\n );\n }\n\n if (deleteOption) {\n // Delete only the successfully pushed dictionaries\n await deleteLocalDictionaries(successfullyPushedDictionaries, options);\n } else if (keepOption) {\n // Do nothing, keep the local dictionaries\n } else {\n // Ask the user\n const remoteDictionaries = successfullyPushedDictionaries.filter(\n (dictionary) => dictionary.location === 'remote'\n );\n const remoteDictionariesKeys = remoteDictionaries.map(\n (dictionary) => dictionary.key\n );\n\n if (remoteDictionaries.length > 0) {\n const { confirm, isCancel } = await import('@clack/prompts');\n\n const shouldDelete = await confirm({\n message: `Do you want to delete the local dictionaries that were successfully pushed? ${colorize('(Dictionaries:', ANSIColors.GREY, ANSIColors.RESET)} ${colorizeKey(remoteDictionariesKeys)}${colorize(')', ANSIColors.GREY, ANSIColors.RESET)}`,\n initialValue: false,\n });\n\n if (isCancel(shouldDelete)) {\n return;\n }\n\n if (shouldDelete) {\n await deleteLocalDictionaries(remoteDictionaries, options);\n }\n }\n }\n } catch (error) {\n appLogger(error, {\n level: 'error',\n });\n }\n};\n\nconst deleteLocalDictionaries = async (\n dictionariesToDelete: Dictionary[],\n options?: PushOptions\n): Promise<void> => {\n const config = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(config);\n\n // Use a Set to collect all unique file paths\n const filePathsSet: Set<string> = new Set();\n\n for (const dictionary of dictionariesToDelete) {\n const { filePath } = dictionary;\n\n if (!filePath) {\n appLogger(\n `Dictionary ${colorizeKey(dictionary.key)} does not have a file path`,\n {\n level: 'error',\n }\n );\n continue;\n }\n\n filePathsSet.add(filePath);\n }\n\n for (const filePath of filePathsSet) {\n try {\n const stats = await fsPromises.lstat(filePath);\n\n if (stats.isFile()) {\n await fsPromises.unlink(filePath);\n appLogger(`Deleted file ${formatPath(filePath)}`, {});\n } else if (stats.isDirectory()) {\n appLogger(`Path is a directory ${formatPath(filePath)}, skipping.`, {});\n } else {\n appLogger(\n `Unknown file type for ${formatPath(filePath)}, skipping.`,\n {}\n );\n }\n } catch (err) {\n appLogger(`Error deleting ${formatPath(filePath)}: ${err}`, {\n level: 'error',\n });\n }\n }\n};\n"],"mappings":"wgBA6CA,MAAM,EAAuB,CAC3B,OAAQ,CAAE,KAAM,IAAK,MAAOA,EAAAA,WAAW,MAAO,CAC9C,SAAU,CAAE,KAAM,IAAK,MAAOA,EAAAA,WAAW,MAAO,CAChD,MAAO,CAAE,KAAM,IAAK,MAAOA,EAAAA,WAAW,IAAK,CAC3C,QAAS,CAAE,KAAM,IAAK,MAAOA,EAAAA,WAAW,KAAM,CAC/C,CAEK,EAAmB,GAErB,EAAqB,IACrB,EAAqB,QAOZ,EAAO,KAAO,IAAyC,CAClE,IAAM,GAAA,EAAA,EAAA,kBAA0B,GAAS,cAAc,EACvD,EAAA,EAAA,kBAAiB,GAAS,cAAc,CAExC,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAO,CAElC,GAAS,QAAU,GACrB,MAAA,EAAA,EAAA,iBAAsB,EAAQ,CAAE,SAAU,GAAM,CAAC,CACjC,GAAS,QAAU,QACnC,MAAA,EAAA,EAAA,iBAAsB,EAAO,CAG/B,GAAI,CAGF,GAAI,CAFe,MAAMC,E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,CAAC,EAC5C,EAAM,aAAa,CAC5B,EAAU,wBAAA,EAAA,EAAA,YAAkC,EAAS,CAAC,aAAc,EAAE,CAAC,CAEvE,EACE,0BAAA,EAAA,EAAA,YAAoC,EAAS,CAAC,aAC9C,EAAE,CACH,OAEI,EAAK,CACZ,EAAU,mBAAA,EAAA,EAAA,YAA6B,EAAS,CAAC,IAAI,IAAO,CAC1D,MAAO,QACR,CAAC"}
1
+ {"version":3,"file":"push.cjs","names":["ANSIColors","checkCMSAuth","PushLogger","fsPromises"],"sources":["../../../src/push/push.ts"],"sourcesContent":["import * as fsPromises from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { getIntlayerAPIProxy } from '@intlayer/api';\nimport {\n prepareIntlayer,\n writeContentDeclaration,\n} from '@intlayer/chokidar/build';\nimport {\n type ListGitFilesOptions,\n listGitFiles,\n logConfigDetails,\n} from '@intlayer/chokidar/cli';\nimport { formatPath, parallelize } from '@intlayer/chokidar/utils';\nimport {\n ANSIColors,\n colorize,\n colorizeKey,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { PushLogger, type PushStatus } from '../pushLog';\nimport { checkCMSAuth } from '../utils/checkAccess';\n\ntype PushOptions = {\n deleteLocaleDictionary?: boolean;\n keepLocaleDictionary?: boolean;\n dictionaries?: string[];\n gitOptions?: ListGitFilesOptions;\n configOptions?: GetConfigurationOptions;\n build?: boolean;\n};\n\ntype DictionariesStatus = {\n dictionary: Dictionary;\n status: 'pending' | 'pushing' | 'modified' | 'pushed' | 'unknown' | 'error';\n error?: Error;\n errorMessage?: string;\n};\n\n// Print per-dictionary summary similar to loadDictionaries\nconst statusIconsAndColors = {\n pushed: { icon: '✔', color: ANSIColors.GREEN },\n modified: { icon: '✔', color: ANSIColors.GREEN },\n error: { icon: '✖', color: ANSIColors.RED },\n default: { icon: '⏲', color: ANSIColors.BLUE },\n};\n\nconst getIconAndColor = (status: DictionariesStatus['status']) => {\n return (\n statusIconsAndColors[status as keyof typeof statusIconsAndColors] ??\n statusIconsAndColors.default\n );\n};\n\n/**\n * Get all local dictionaries and push them simultaneously.\n */\nexport const push = async (options?: PushOptions): Promise<void> => {\n const config = getConfiguration(options?.configOptions);\n logConfigDetails(options?.configOptions);\n\n const appLogger = getAppLogger(config);\n\n if (options?.build === true) {\n await prepareIntlayer(config, { forceRun: true });\n } else if (typeof options?.build === 'undefined') {\n await prepareIntlayer(config);\n }\n\n try {\n const hasCMSAuth = await checkCMSAuth(config);\n\n if (!hasCMSAuth) return;\n\n const intlayerAPI = getIntlayerAPIProxy(undefined, config);\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(config);\n const allDictionaries = Object.values(unmergedDictionariesRecord).flat();\n\n const customLocations = Array.from(\n new Set(\n allDictionaries\n .map((dictionary) => dictionary.location)\n .filter(\n (location) =>\n location && !['remote', 'local', 'hybrid'].includes(location)\n )\n )\n ) as string[];\n\n let selectedCustomLocations: string[] = [];\n\n if (customLocations.length > 0) {\n const { multiselect, confirm, isCancel } = await import('@clack/prompts');\n\n if (customLocations.length === 1) {\n const shouldPush = await confirm({\n message: `Do you want to push dictionaries with custom location ${colorize(customLocations[0], ANSIColors.BLUE, ANSIColors.RESET)}?`,\n initialValue: false,\n });\n\n if (isCancel(shouldPush)) {\n return;\n }\n\n if (shouldPush) {\n selectedCustomLocations = [customLocations[0]];\n }\n } else {\n const selected = await multiselect({\n message: 'Select custom locations to push:',\n options: customLocations.map((location) => ({\n value: location,\n label: location,\n })),\n required: false,\n });\n\n if (isCancel(selected)) {\n return;\n }\n\n selectedCustomLocations = selected as string[];\n }\n }\n\n let dictionaries: Dictionary[] = allDictionaries.filter((dictionary) => {\n const location =\n dictionary.location ?? config.dictionary?.location ?? 'local';\n\n return (\n location === 'remote' ||\n location === 'hybrid' ||\n selectedCustomLocations.includes(location)\n );\n });\n\n // Check if the dictionaries list is empty after filtering by location\n if (dictionaries.length === 0) {\n appLogger(\n `No dictionaries found to push. Only dictionaries with location ${colorize('remote', ANSIColors.BLUE, ANSIColors.RESET)}, ${colorize('hybrid', ANSIColors.BLUE, ANSIColors.RESET)} or selected custom locations are pushed.`,\n { level: 'warn' }\n );\n appLogger(\n `You can set the location in your dictionary file (e.g. ${colorize(\"{ key: 'my-key', location: 'hybrid', ... }\", ANSIColors.BLUE, ANSIColors.RESET)} or globally in your intlayer.config.ts file (e.g. ${colorize(\"{ dictionary: { location: 'hybrid' } }\", ANSIColors.BLUE, ANSIColors.RESET)}).`,\n { level: 'info' }\n );\n return;\n }\n\n const existingDictionariesKeys: string[] = Object.keys(\n unmergedDictionariesRecord\n );\n\n if (options?.dictionaries) {\n // Check if the provided dictionaries exist\n const noneExistingDictionariesOption = options.dictionaries.filter(\n (dictionaryId) => !existingDictionariesKeys.includes(dictionaryId)\n );\n\n if (noneExistingDictionariesOption.length > 0) {\n appLogger(\n `The following dictionaries do not exist: ${noneExistingDictionariesOption.join(\n ', '\n )} and have been ignored.`,\n {\n level: 'error',\n }\n );\n }\n\n // Filter the dictionaries from the provided list of IDs\n dictionaries = dictionaries.filter((dictionary) =>\n options.dictionaries?.includes(dictionary.key)\n );\n }\n\n if (options?.gitOptions) {\n const gitFiles = await listGitFiles(options.gitOptions);\n\n dictionaries = dictionaries.filter((dictionary) =>\n gitFiles.includes(\n join(config.system.baseDir, dictionary.filePath ?? '')\n )\n );\n }\n\n // Check if the dictionaries list is empty\n if (dictionaries.length === 0) {\n appLogger('No local dictionaries found', {\n level: 'error',\n });\n return;\n }\n\n appLogger('Pushing dictionaries:');\n\n // Prepare dictionaries statuses\n const dictionariesStatuses: DictionariesStatus[] = dictionaries.map(\n (dictionary) => ({\n dictionary,\n status: 'pending',\n })\n );\n\n // Initialize aggregated logger similar to loadDictionaries\n const logger = new PushLogger();\n logger.update(\n dictionariesStatuses.map<PushStatus>((s) => ({\n dictionaryKey: s.dictionary.key,\n status: 'pending',\n }))\n );\n\n const successfullyPushedDictionaries: Dictionary[] = [];\n\n const processDictionary = async (\n statusObj: DictionariesStatus\n ): Promise<void> => {\n statusObj.status = 'pushing';\n logger.update([\n { dictionaryKey: statusObj.dictionary.key, status: 'pushing' },\n ]);\n\n try {\n const pushResult = await intlayerAPI.dictionary.pushDictionaries([\n statusObj.dictionary,\n ]);\n\n const updatedDictionaries = pushResult.data?.updatedDictionaries ?? [];\n const newDictionaries = pushResult.data?.newDictionaries ?? [];\n\n const allDictionaries = [...updatedDictionaries, ...newDictionaries];\n\n for (const remoteDictionaryData of allDictionaries) {\n const localDictionary = unmergedDictionariesRecord[\n remoteDictionaryData.key\n ]?.find(\n (dictionary) => dictionary.localId === remoteDictionaryData.localId\n );\n\n if (!localDictionary) continue;\n\n await writeContentDeclaration(\n { ...localDictionary, id: remoteDictionaryData.id },\n config\n );\n }\n\n if (\n updatedDictionaries.some(\n (dictionary) => dictionary.key === statusObj.dictionary.key\n )\n ) {\n statusObj.status = 'modified';\n successfullyPushedDictionaries.push(statusObj.dictionary);\n logger.update([\n { dictionaryKey: statusObj.dictionary.key, status: 'modified' },\n ]);\n } else if (\n newDictionaries.some(\n (dictionary) => dictionary.key === statusObj.dictionary.key\n )\n ) {\n statusObj.status = 'pushed';\n successfullyPushedDictionaries.push(statusObj.dictionary);\n logger.update([\n { dictionaryKey: statusObj.dictionary.key, status: 'pushed' },\n ]);\n } else {\n statusObj.status = 'unknown';\n }\n } catch (error) {\n statusObj.status = 'error';\n statusObj.error = error as Error;\n statusObj.errorMessage = `Error pushing dictionary ${statusObj.dictionary.key}: ${error}`;\n logger.update([\n { dictionaryKey: statusObj.dictionary.key, status: 'error' },\n ]);\n }\n };\n\n // Process dictionaries in parallel with a concurrency limit (reuse parallelize)\n await parallelize(dictionariesStatuses, processDictionary, 5);\n\n // Stop the logger and render final state\n logger.finish();\n\n for (const dictionaryStatus of dictionariesStatuses) {\n const { icon, color } = getIconAndColor(dictionaryStatus.status);\n appLogger(\n ` - ${colorizeKey(dictionaryStatus.dictionary.key)} ${ANSIColors.GREY}[${color}${icon} ${dictionaryStatus.status}${ANSIColors.GREY}]${ANSIColors.RESET}`\n );\n }\n\n // Output any error messages\n for (const statusObj of dictionariesStatuses) {\n if (statusObj.errorMessage) {\n appLogger(statusObj.errorMessage, {\n level: 'error',\n });\n }\n }\n\n // Handle delete or keep options\n const deleteOption = options?.deleteLocaleDictionary;\n const keepOption = options?.keepLocaleDictionary;\n\n if (deleteOption && keepOption) {\n throw new Error(\n 'Cannot specify both --deleteLocaleDictionary and --keepLocaleDictionary options.'\n );\n }\n\n if (deleteOption) {\n // Delete only the successfully pushed dictionaries\n await deleteLocalDictionaries(successfullyPushedDictionaries, options);\n } else if (keepOption) {\n // Do nothing, keep the local dictionaries\n } else {\n // Ask the user\n const remoteDictionaries = successfullyPushedDictionaries.filter(\n (dictionary) => dictionary.location === 'remote'\n );\n const remoteDictionariesKeys = remoteDictionaries.map(\n (dictionary) => dictionary.key\n );\n\n if (remoteDictionaries.length > 0) {\n const { confirm, isCancel } = await import('@clack/prompts');\n\n const shouldDelete = await confirm({\n message: `Do you want to delete the local dictionaries that were successfully pushed? ${colorize('(Dictionaries:', ANSIColors.GREY, ANSIColors.RESET)} ${colorizeKey(remoteDictionariesKeys)}${colorize(')', ANSIColors.GREY, ANSIColors.RESET)}`,\n initialValue: false,\n });\n\n if (isCancel(shouldDelete)) {\n return;\n }\n\n if (shouldDelete) {\n await deleteLocalDictionaries(remoteDictionaries, options);\n }\n }\n }\n } catch (error) {\n appLogger(error, {\n level: 'error',\n });\n }\n};\n\nconst deleteLocalDictionaries = async (\n dictionariesToDelete: Dictionary[],\n options?: PushOptions\n): Promise<void> => {\n const config = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(config);\n\n // Use a Set to collect all unique file paths\n const filePathsSet: Set<string> = new Set();\n\n for (const dictionary of dictionariesToDelete) {\n const { filePath } = dictionary;\n\n if (!filePath) {\n appLogger(\n `Dictionary ${colorizeKey(dictionary.key)} does not have a file path`,\n {\n level: 'error',\n }\n );\n continue;\n }\n\n filePathsSet.add(filePath);\n }\n\n for (const filePath of filePathsSet) {\n try {\n const stats = await fsPromises.lstat(filePath);\n\n if (stats.isFile()) {\n await fsPromises.unlink(filePath);\n appLogger(`Deleted file ${formatPath(filePath)}`, {});\n } else if (stats.isDirectory()) {\n appLogger(`Path is a directory ${formatPath(filePath)}, skipping.`, {});\n } else {\n appLogger(\n `Unknown file type for ${formatPath(filePath)}, skipping.`,\n {}\n );\n }\n } catch (err) {\n appLogger(`Error deleting ${formatPath(filePath)}: ${err}`, {\n level: 'error',\n });\n }\n }\n};\n"],"mappings":"sfA6CA,MAAM,EAAuB,CAC3B,OAAQ,CAAE,KAAM,IAAK,MAAOA,EAAAA,WAAW,MAAO,CAC9C,SAAU,CAAE,KAAM,IAAK,MAAOA,EAAAA,WAAW,MAAO,CAChD,MAAO,CAAE,KAAM,IAAK,MAAOA,EAAAA,WAAW,IAAK,CAC3C,QAAS,CAAE,KAAM,IAAK,MAAOA,EAAAA,WAAW,KAAM,CAC/C,CAEK,EAAmB,GAErB,EAAqB,IACrB,EAAqB,QAOZ,EAAO,KAAO,IAAyC,CAClE,IAAM,GAAA,EAAA,EAAA,kBAA0B,GAAS,cAAc,EACvD,EAAA,EAAA,kBAAiB,GAAS,cAAc,CAExC,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAO,CAElC,GAAS,QAAU,GACrB,MAAA,EAAA,EAAA,iBAAsB,EAAQ,CAAE,SAAU,GAAM,CAAC,CACjC,GAAS,QAAU,QACnC,MAAA,EAAA,EAAA,iBAAsB,EAAO,CAG/B,GAAI,CAGF,GAAI,CAFe,MAAMC,EAAAA,aAAa,EAAO,CAE5B,OAEjB,IAAM,GAAA,EAAA,EAAA,qBAAkC,IAAA,GAAW,EAAO,CAEpD,GAAA,EAAA,EAAA,yBAAqD,EAAO,CAC5D,EAAkB,OAAO,OAAO,E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9C,EAAE,CACH,OAEI,EAAK,CACZ,EAAU,mBAAA,EAAA,EAAA,YAA6B,EAAS,CAAC,IAAI,IAAO,CAC1D,MAAO,QACR,CAAC"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./_virtual/_rolldown/runtime.cjs`);const e=require(`./utils/checkAccess.cjs`);let t=require(`@intlayer/chokidar/cli`),n=require(`@intlayer/config/logger`),r=require(`@intlayer/config/node`),i=require(`@intlayer/api`);const a=async a=>{let o=(0,r.getConfiguration)(a?.configOptions);(0,t.logConfigDetails)(a?.configOptions);let s=(0,n.getAppLogger)(o);if(!await e.checkCMSAuth(o,!1))return;let c=await(0,i.getIntlayerAPIProxy)(void 0,o).project.pushProjectConfiguration(o);if(!c.data)throw Error(`Error pushing project configuration`);s(`Project configuration pushed successfully`),s(JSON.stringify(c.data,null,2))};exports.pushConfig=a;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./chunk-Bmb41Sf3.cjs`);const e=require(`./utils/checkAccess.cjs`);let t=require(`@intlayer/chokidar/cli`),n=require(`@intlayer/config/logger`),r=require(`@intlayer/config/node`),i=require(`@intlayer/api`);const a=async a=>{let o=(0,r.getConfiguration)(a?.configOptions);(0,t.logConfigDetails)(a?.configOptions);let s=(0,n.getAppLogger)(o);if(!await e.checkCMSAuth(o,!1))return;let c=await(0,i.getIntlayerAPIProxy)(void 0,o).project.pushProjectConfiguration(o);if(!c.data)throw Error(`Error pushing project configuration`);s(`Project configuration pushed successfully`),s(JSON.stringify(c.data,null,2))};exports.pushConfig=a;
2
2
  //# sourceMappingURL=pushConfig.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"pushConfig.cjs","names":["checkCMSAuth"],"sources":["../../src/pushConfig.ts"],"sourcesContent":["import { getIntlayerAPIProxy } from '@intlayer/api';\nimport { logConfigDetails } from '@intlayer/chokidar/cli';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { checkCMSAuth } from './utils/checkAccess';\n\ntype PushOptions = {\n configOptions?: GetConfigurationOptions;\n};\n\nexport const pushConfig = async (options?: PushOptions) => {\n const config = getConfiguration(options?.configOptions);\n logConfigDetails(options?.configOptions);\n\n const appLogger = getAppLogger(config);\n\n const hasCMSAuth = await checkCMSAuth(config, false);\n\n if (!hasCMSAuth) return;\n\n const intlayerAPI = getIntlayerAPIProxy(undefined, config);\n\n // Push the project configuration\n const getDictionariesKeysResult =\n await intlayerAPI.project.pushProjectConfiguration(config);\n\n if (!getDictionariesKeysResult.data) {\n throw new Error('Error pushing project configuration');\n }\n\n appLogger('Project configuration pushed successfully');\n\n appLogger(JSON.stringify(getDictionariesKeysResult.data, null, 2));\n};\n"],"mappings":"qSAaA,MAAa,EAAa,KAAO,IAA0B,CACzD,IAAM,GAAA,EAAA,EAAA,kBAA0B,GAAS,cAAc,EACvD,EAAA,EAAA,kBAAiB,GAAS,cAAc,CAExC,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAO,CAItC,GAAI,CAFe,MAAMA,EAAAA,aAAa,EAAQ,GAAM,CAEnC,OAKjB,IAAM,EACJ,MAAA,EAAA,EAAA,qBAJsC,IAAA,GAAW,EAAO,CAItC,QAAQ,yBAAyB,EAAO,CAE5D,GAAI,CAAC,EAA0B,KAC7B,MAAU,MAAM,sCAAsC,CAGxD,EAAU,4CAA4C,CAEtD,EAAU,KAAK,UAAU,EAA0B,KAAM,KAAM,EAAE,CAAC"}
1
+ {"version":3,"file":"pushConfig.cjs","names":["checkCMSAuth"],"sources":["../../src/pushConfig.ts"],"sourcesContent":["import { getIntlayerAPIProxy } from '@intlayer/api';\nimport { logConfigDetails } from '@intlayer/chokidar/cli';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { checkCMSAuth } from './utils/checkAccess';\n\ntype PushOptions = {\n configOptions?: GetConfigurationOptions;\n};\n\nexport const pushConfig = async (options?: PushOptions) => {\n const config = getConfiguration(options?.configOptions);\n logConfigDetails(options?.configOptions);\n\n const appLogger = getAppLogger(config);\n\n const hasCMSAuth = await checkCMSAuth(config, false);\n\n if (!hasCMSAuth) return;\n\n const intlayerAPI = getIntlayerAPIProxy(undefined, config);\n\n // Push the project configuration\n const getDictionariesKeysResult =\n await intlayerAPI.project.pushProjectConfiguration(config);\n\n if (!getDictionariesKeysResult.data) {\n throw new Error('Error pushing project configuration');\n }\n\n appLogger('Project configuration pushed successfully');\n\n appLogger(JSON.stringify(getDictionariesKeysResult.data, null, 2));\n};\n"],"mappings":"yRAaA,MAAa,EAAa,KAAO,IAA0B,CACzD,IAAM,GAAA,EAAA,EAAA,kBAA0B,GAAS,cAAc,EACvD,EAAA,EAAA,kBAAiB,GAAS,cAAc,CAExC,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAO,CAItC,GAAI,CAFe,MAAMA,EAAAA,aAAa,EAAQ,GAAM,CAEnC,OAKjB,IAAM,EACJ,MAAA,EAAA,EAAA,qBAJsC,IAAA,GAAW,EAAO,CAItC,QAAQ,yBAAyB,EAAO,CAE5D,GAAI,CAAC,EAA0B,KAC7B,MAAU,MAAM,sCAAsC,CAGxD,EAAU,4CAA4C,CAEtD,EAAU,KAAK,UAAU,EAA0B,KAAM,KAAM,EAAE,CAAC"}
@@ -1,4 +1,4 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./_virtual/_rolldown/runtime.cjs`);let e=require(`@intlayer/config/logger`);var t=class{statuses=[];spinnerTimer=null;spinnerIndex=0;renderedLines=0;spinnerFrames=e.spinnerFrames;isFinished=!1;lastRenderedState=``;update(e){if(!this.isFinished){for(let t of e){let e=this.statuses.findIndex(e=>e.dictionaryKey===t.dictionaryKey);e>=0?this.statuses[e]=t:this.statuses.push(t)}this.startSpinner(),this.render()}}finish(){this.isFinished=!0,this.stopSpinner(),this.render()}startSpinner(){this.spinnerTimer||this.isFinished||(this.spinnerTimer=setInterval(()=>{this.spinnerIndex=(this.spinnerIndex+1)%this.spinnerFrames.length,this.render()},100))}stopSpinner(){this.spinnerTimer&&=(clearInterval(this.spinnerTimer),null)}render(){let{total:t,done:n,pushed:r,modified:i,errors:a}=this.computeProgress(),o=this.spinnerFrames[this.spinnerIndex],s=[],c=n===t,l=`dictionaries: ${(0,e.colorizeNumber)(n)}/${(0,e.colorizeNumber)(t)}`,u=[];r>0&&u.push(`new: ${(0,e.colorizeNumber)(r)}`),i>0&&u.push(`modified: ${(0,e.colorizeNumber)(i)}`),a>0&&u.push((0,e.colorize)(`errors: ${(0,e.colorizeNumber)(a)}`,e.ANSIColors.RED));let d=u.length>0?` (${u.join(`, `)})`:``;c?s.push(`${(0,e.colorize)(`✔`,e.ANSIColors.GREEN)} pushed ${l}${d}`):s.push(`${(0,e.colorize)(o,e.ANSIColors.BLUE)} pushing ${l}${d}`);let f=s.join(`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`./chunk-Bmb41Sf3.cjs`);let e=require(`@intlayer/config/logger`);var t=class{statuses=[];spinnerTimer=null;spinnerIndex=0;renderedLines=0;spinnerFrames=e.spinnerFrames;isFinished=!1;lastRenderedState=``;update(e){if(!this.isFinished){for(let t of e){let e=this.statuses.findIndex(e=>e.dictionaryKey===t.dictionaryKey);e>=0?this.statuses[e]=t:this.statuses.push(t)}this.startSpinner(),this.render()}}finish(){this.isFinished=!0,this.stopSpinner(),this.render()}startSpinner(){this.spinnerTimer||this.isFinished||(this.spinnerTimer=setInterval(()=>{this.spinnerIndex=(this.spinnerIndex+1)%this.spinnerFrames.length,this.render()},100))}stopSpinner(){this.spinnerTimer&&=(clearInterval(this.spinnerTimer),null)}render(){let{total:t,done:n,pushed:r,modified:i,errors:a}=this.computeProgress(),o=this.spinnerFrames[this.spinnerIndex],s=[],c=n===t,l=`dictionaries: ${(0,e.colorizeNumber)(n)}/${(0,e.colorizeNumber)(t)}`,u=[];r>0&&u.push(`new: ${(0,e.colorizeNumber)(r)}`),i>0&&u.push(`modified: ${(0,e.colorizeNumber)(i)}`),a>0&&u.push((0,e.colorize)(`errors: ${(0,e.colorizeNumber)(a)}`,e.ANSIColors.RED));let d=u.length>0?` (${u.join(`, `)})`:``;c?s.push(`${(0,e.colorize)(`✔`,e.ANSIColors.GREEN)} pushed ${l}${d}`):s.push(`${(0,e.colorize)(o,e.ANSIColors.BLUE)} pushing ${l}${d}`);let f=s.join(`
2
2
  `);if(f===this.lastRenderedState)return;this.lastRenderedState=f,this.renderedLines>0&&process.stdout.write(`\x1b[${this.renderedLines}F`);let p=Math.max(this.renderedLines,s.length);for(let e=0;e<p;e++){process.stdout.write(`\x1B[2K`);let t=s[e];t!==void 0&&process.stdout.write(t),process.stdout.write(`
3
3
  `)}this.renderedLines=s.length}computeProgress(){let e=new Set(this.statuses.map(e=>e.dictionaryKey)),t=this.statuses.filter(e=>e.status===`pushed`).length,n=this.statuses.filter(e=>e.status===`modified`).length,r=this.statuses.filter(e=>e.status===`error`).length,i=t+n+r;return{total:e.size,done:i,pushed:t,modified:n,errors:r}}};exports.PushLogger=t;
4
4
  //# sourceMappingURL=pushLog.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"pushLog.cjs","names":["spinnerFrames","ANSIColors"],"sources":["../../src/pushLog.ts"],"sourcesContent":["import {\n ANSIColors,\n colorize,\n colorizeNumber,\n spinnerFrames,\n} from '@intlayer/config/logger';\n\nexport type PushStatus = {\n dictionaryKey: string;\n status: 'pending' | 'pushing' | 'pushed' | 'modified' | 'error';\n errorMessage?: string;\n};\n\nexport class PushLogger {\n private statuses: PushStatus[] = [];\n private spinnerTimer: NodeJS.Timeout | null = null;\n private spinnerIndex = 0;\n private renderedLines = 0;\n private readonly spinnerFrames = spinnerFrames;\n private isFinished = false;\n private lastRenderedState: string = '';\n\n update(newStatuses: PushStatus[]) {\n if (this.isFinished) return;\n for (const status of newStatuses) {\n const index = this.statuses.findIndex(\n (s) => s.dictionaryKey === status.dictionaryKey\n );\n if (index >= 0) {\n this.statuses[index] = status;\n } else {\n this.statuses.push(status);\n }\n }\n\n this.startSpinner();\n this.render();\n }\n\n finish() {\n this.isFinished = true;\n this.stopSpinner();\n this.render();\n }\n\n private startSpinner() {\n if (this.spinnerTimer || this.isFinished) return;\n this.spinnerTimer = setInterval(() => {\n this.spinnerIndex = (this.spinnerIndex + 1) % this.spinnerFrames.length;\n this.render();\n }, 100);\n }\n\n private stopSpinner() {\n if (!this.spinnerTimer) return;\n clearInterval(this.spinnerTimer);\n this.spinnerTimer = null;\n }\n\n private render() {\n const { total, done, pushed, modified, errors } = this.computeProgress();\n\n const frame = this.spinnerFrames[this.spinnerIndex];\n const lines: string[] = [];\n\n const isDone = done === total;\n\n const progressLabel = `dictionaries: ${colorizeNumber(done)}/${colorizeNumber(total)}`;\n const details: string[] = [];\n if (pushed > 0) details.push(`new: ${colorizeNumber(pushed)}`);\n if (modified > 0) details.push(`modified: ${colorizeNumber(modified)}`);\n if (errors > 0)\n details.push(\n colorize(`errors: ${colorizeNumber(errors)}`, ANSIColors.RED)\n );\n\n const suffix = details.length > 0 ? ` (${details.join(', ')})` : '';\n\n if (isDone) {\n lines.push(\n `${colorize('✔', ANSIColors.GREEN)} pushed ${progressLabel}${suffix}`\n );\n } else {\n lines.push(\n `${colorize(frame, ANSIColors.BLUE)} pushing ${progressLabel}${suffix}`\n );\n }\n\n const currentState = lines.join('\\n');\n if (currentState === this.lastRenderedState) {\n return;\n }\n this.lastRenderedState = currentState;\n\n if (this.renderedLines > 0) {\n process.stdout.write(`\\x1b[${this.renderedLines}F`);\n }\n\n const totalLinesToClear = Math.max(this.renderedLines, lines.length);\n for (let i = 0; i < totalLinesToClear; i++) {\n process.stdout.write('\\x1b[2K');\n const line = lines[i];\n if (line !== undefined) {\n process.stdout.write(line);\n }\n process.stdout.write('\\n');\n }\n\n this.renderedLines = lines.length;\n }\n\n private computeProgress() {\n const keys = new Set(this.statuses.map((s) => s.dictionaryKey));\n\n const pushed = this.statuses.filter((s) => s.status === 'pushed').length;\n const modified = this.statuses.filter(\n (s) => s.status === 'modified'\n ).length;\n const errors = this.statuses.filter((s) => s.status === 'error').length;\n const done = pushed + modified + errors;\n\n return {\n total: keys.size,\n done,\n pushed,\n modified,\n errors,\n } as const;\n }\n}\n"],"mappings":"wJAaA,IAAa,EAAb,KAAwB,CACtB,SAAiC,EAAE,CACnC,aAA8C,KAC9C,aAAuB,EACvB,cAAwB,EACxB,cAAiCA,EAAAA,cACjC,WAAqB,GACrB,kBAAoC,GAEpC,OAAO,EAA2B,CAC5B,SAAK,WACT,KAAK,IAAM,KAAU,EAAa,CAChC,IAAM,EAAQ,KAAK,SAAS,UACzB,GAAM,EAAE,gBAAkB,EAAO,cACnC,CACG,GAAS,EACX,KAAK,SAAS,GAAS,EAEvB,KAAK,SAAS,KAAK,EAAO,CAI9B,KAAK,cAAc,CACnB,KAAK,QAAQ,EAGf,QAAS,CACP,KAAK,WAAa,GAClB,KAAK,aAAa,CAClB,KAAK,QAAQ,CAGf,cAAuB,CACjB,KAAK,cAAgB,KAAK,aAC9B,KAAK,aAAe,gBAAkB,CACpC,KAAK,cAAgB,KAAK,aAAe,GAAK,KAAK,cAAc,OACjE,KAAK,QAAQ,EACZ,IAAI,EAGT,aAAsB,CACf,AAEL,KAAK,gBADL,cAAc,KAAK,aAAa,CACZ,MAGtB,QAAiB,CACf,GAAM,CAAE,QAAO,OAAM,SAAQ,WAAU,UAAW,KAAK,iBAAiB,CAElE,EAAQ,KAAK,cAAc,KAAK,cAChC,EAAkB,EAAE,CAEpB,EAAS,IAAS,EAElB,EAAgB,kBAAA,EAAA,EAAA,gBAAgC,EAAK,CAAC,IAAA,EAAA,EAAA,gBAAkB,EAAM,GAC9E,EAAoB,EAAE,CACxB,EAAS,GAAG,EAAQ,KAAK,SAAA,EAAA,EAAA,gBAAuB,EAAO,GAAG,CAC1D,EAAW,GAAG,EAAQ,KAAK,cAAA,EAAA,EAAA,gBAA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],"sources":["../../src/pushLog.ts"],"sourcesContent":["import {\n ANSIColors,\n colorize,\n colorizeNumber,\n spinnerFrames,\n} from '@intlayer/config/logger';\n\nexport type PushStatus = {\n dictionaryKey: string;\n status: 'pending' | 'pushing' | 'pushed' | 'modified' | 'error';\n errorMessage?: string;\n};\n\nexport class PushLogger {\n private statuses: PushStatus[] = [];\n private spinnerTimer: NodeJS.Timeout | null = null;\n private spinnerIndex = 0;\n private renderedLines = 0;\n private readonly spinnerFrames = spinnerFrames;\n private isFinished = false;\n private lastRenderedState: string = '';\n\n update(newStatuses: PushStatus[]) {\n if (this.isFinished) return;\n for (const status of newStatuses) {\n const index = this.statuses.findIndex(\n (s) => s.dictionaryKey === status.dictionaryKey\n );\n if (index >= 0) {\n this.statuses[index] = status;\n } else {\n this.statuses.push(status);\n }\n }\n\n this.startSpinner();\n this.render();\n }\n\n finish() {\n this.isFinished = true;\n this.stopSpinner();\n this.render();\n }\n\n private startSpinner() {\n if (this.spinnerTimer || this.isFinished) return;\n this.spinnerTimer = setInterval(() => {\n this.spinnerIndex = (this.spinnerIndex + 1) % this.spinnerFrames.length;\n this.render();\n }, 100);\n }\n\n private stopSpinner() {\n if (!this.spinnerTimer) return;\n clearInterval(this.spinnerTimer);\n this.spinnerTimer = null;\n }\n\n private render() {\n const { total, done, pushed, modified, errors } = this.computeProgress();\n\n const frame = this.spinnerFrames[this.spinnerIndex];\n const lines: string[] = [];\n\n const isDone = done === total;\n\n const progressLabel = `dictionaries: ${colorizeNumber(done)}/${colorizeNumber(total)}`;\n const details: string[] = [];\n if (pushed > 0) details.push(`new: ${colorizeNumber(pushed)}`);\n if (modified > 0) details.push(`modified: ${colorizeNumber(modified)}`);\n if (errors > 0)\n details.push(\n colorize(`errors: ${colorizeNumber(errors)}`, ANSIColors.RED)\n );\n\n const suffix = details.length > 0 ? ` (${details.join(', ')})` : '';\n\n if (isDone) {\n lines.push(\n `${colorize('✔', ANSIColors.GREEN)} pushed ${progressLabel}${suffix}`\n );\n } else {\n lines.push(\n `${colorize(frame, ANSIColors.BLUE)} pushing ${progressLabel}${suffix}`\n );\n }\n\n const currentState = lines.join('\\n');\n if (currentState === this.lastRenderedState) {\n return;\n }\n this.lastRenderedState = currentState;\n\n if (this.renderedLines > 0) {\n process.stdout.write(`\\x1b[${this.renderedLines}F`);\n }\n\n const totalLinesToClear = Math.max(this.renderedLines, lines.length);\n for (let i = 0; i < totalLinesToClear; i++) {\n process.stdout.write('\\x1b[2K');\n const line = lines[i];\n if (line !== undefined) {\n process.stdout.write(line);\n }\n process.stdout.write('\\n');\n }\n\n this.renderedLines = lines.length;\n }\n\n private computeProgress() {\n const keys = new Set(this.statuses.map((s) => s.dictionaryKey));\n\n const pushed = this.statuses.filter((s) => s.status === 'pushed').length;\n const modified = this.statuses.filter(\n (s) => s.status === 'modified'\n ).length;\n const errors = this.statuses.filter((s) => s.status === 'error').length;\n const done = pushed + modified + errors;\n\n return {\n total: keys.size,\n done,\n pushed,\n modified,\n errors,\n } as const;\n }\n}\n"],"mappings":"4IAaA,IAAa,EAAb,KAAwB,CACtB,SAAiC,EAAE,CACnC,aAA8C,KAC9C,aAAuB,EACvB,cAAwB,EACxB,cAAiCA,EAAAA,cACjC,WAAqB,GACrB,kBAAoC,GAEpC,OAAO,EAA2B,CAC5B,SAAK,WACT,KAAK,IAAM,KAAU,EAAa,CAChC,IAAM,EAAQ,KAAK,SAAS,UACzB,GAAM,EAAE,gBAAkB,EAAO,cACnC,CACG,GAAS,EACX,KAAK,SAAS,GAAS,EAEvB,KAAK,SAAS,KAAK,EAAO,CAI9B,KAAK,cAAc,CACnB,KAAK,QAAQ,EAGf,QAAS,CACP,KAAK,WAAa,GAClB,KAAK,aAAa,CAClB,KAAK,QAAQ,CAGf,cAAuB,CACjB,KAAK,cAAgB,KAAK,aAC9B,KAAK,aAAe,gBAAkB,CACpC,KAAK,cAAgB,KAAK,aAAe,GAAK,KAAK,cAAc,OACjE,KAAK,QAAQ,EACZ,IAAI,EAGT,aAA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B,KAAK,cAAgB,EAAM,OAG7B,iBAA0B,CACxB,IAAM,EAAO,IAAI,IAAI,KAAK,SAAS,IAAK,GAAM,EAAE,cAAc,CAAC,CAEzD,EAAS,KAAK,SAAS,OAAQ,GAAM,EAAE,SAAW,SAAS,CAAC,OAC5D,EAAW,KAAK,SAAS,OAC5B,GAAM,EAAE,SAAW,WACrB,CAAC,OACI,EAAS,KAAK,SAAS,OAAQ,GAAM,EAAE,SAAW,QAAQ,CAAC,OAC3D,EAAO,EAAS,EAAW,EAEjC,MAAO,CACL,MAAO,EAAK,KACZ,OACA,SACA,WACA,SACD"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`),t=require(`../utils/setupAI.cjs`),n=require(`../utils/checkFileModifiedRange.cjs`),r=require(`../utils/getOutputFilePath.cjs`),i=require(`./reviewDocBlockAware.cjs`);let a=require(`node:fs`),o=require(`node:path`),s=require(`@intlayer/chokidar/cli`),c=require(`@intlayer/chokidar/utils`),l=require(`@intlayer/config/logger`),u=require(`@intlayer/config/node`),d=require(`fast-glob`);d=e.__toESM(d);const f=async({docPattern:e,locales:f,excludedGlobPattern:p,baseLocale:m,aiOptions:h,nbSimultaneousFileProcessed:g,configOptions:_,customInstructions:v,skipIfModifiedBefore:y,skipIfModifiedAfter:b,skipIfExists:x,gitOptions:S})=>{let C=(0,u.getConfiguration)(_);(0,s.logConfigDetails)(_);let w=(0,l.getAppLogger)(C),T=await t.setupAI(C,h);if(!T?.hasAIAccess)return;let{aiClient:E,aiConfig:D}=T;g&&g>10&&(w(`Warning: nbSimultaneousFileProcessed is set to ${g}, which is greater than 10. Setting it to 10.`),g=10);let O=await(0,d.default)(e,{ignore:p});if(S){let e=await(0,s.listGitFiles)(S);e&&(O=O.filter(t=>e.some(e=>(0,o.join)(process.cwd(),t)===e)))}w(`Base locale is ${(0,c.formatLocale)(m)}`),w(`Reviewing ${(0,l.colorizeNumber)(f.length)} locales: [ ${(0,c.formatLocale)(f)} ]`),w(`Reviewing ${(0,l.colorizeNumber)(O.length)} files:`),w(O.map(e=>` - ${(0,c.formatPath)(e)}\n`)),await(0,c.parallelize)(O.flatMap(e=>f.map(t=>async()=>{w(`Reviewing file: ${(0,c.formatPath)(e)} to ${(0,c.formatLocale)(t)}`);let u=(0,o.join)(C.system.baseDir,e),d=r.getOutputFilePath(u,t,m);if(x&&(0,a.existsSync)(d)){let e=(0,o.relative)(C.system.baseDir,d);w(`${(0,l.colorize)(`⊘`,l.ANSIColors.YELLOW)} File ${(0,c.formatPath)(e)} already exists, skipping.`);return}if((0,a.existsSync)(d)){let e=n.checkFileModifiedRange(d,{skipIfModifiedBefore:y,skipIfModifiedAfter:b});if(e.isSkipped){w(e.message);return}}else (y||b)&&w(`${(0,l.colorize)(`!`,l.ANSIColors.YELLOW)} File ${(0,c.formatPath)(d)} does not exist, skipping modification date check.`);let f;if(S){let e=await(0,s.listGitLines)(u,S);w(`Git changed lines: ${e.join(`, `)}`),f=e}await i.reviewFileBlockAware(u,d,t,m,h,_,v,f,E,D)})),e=>e(),g??3)};exports.reviewDoc=f;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../chunk-Bmb41Sf3.cjs`),t=require(`../utils/setupAI.cjs`),n=require(`../utils/checkFileModifiedRange.cjs`),r=require(`../utils/getOutputFilePath.cjs`),i=require(`./reviewDocBlockAware.cjs`);let a=require(`node:fs`),o=require(`node:path`),s=require(`@intlayer/chokidar/cli`),c=require(`@intlayer/chokidar/utils`),l=require(`@intlayer/config/logger`),u=require(`@intlayer/config/node`),d=require(`fast-glob`);d=e.t(d);const f=async({docPattern:e,locales:f,excludedGlobPattern:p,baseLocale:m,aiOptions:h,nbSimultaneousFileProcessed:g,configOptions:_,customInstructions:v,skipIfModifiedBefore:y,skipIfModifiedAfter:b,skipIfExists:x,gitOptions:S})=>{let C=(0,u.getConfiguration)(_);(0,s.logConfigDetails)(_);let w=(0,l.getAppLogger)(C),T=await t.setupAI(C,h);if(!T?.hasAIAccess)return;let{aiClient:E,aiConfig:D}=T;g&&g>10&&(w(`Warning: nbSimultaneousFileProcessed is set to ${g}, which is greater than 10. Setting it to 10.`),g=10);let O=await(0,d.default)(e,{ignore:p});if(S){let e=await(0,s.listGitFiles)(S);e&&(O=O.filter(t=>e.some(e=>(0,o.join)(process.cwd(),t)===e)))}w(`Base locale is ${(0,c.formatLocale)(m)}`),w(`Reviewing ${(0,l.colorizeNumber)(f.length)} locales: [ ${(0,c.formatLocale)(f)} ]`),w(`Reviewing ${(0,l.colorizeNumber)(O.length)} files:`),w(O.map(e=>` - ${(0,c.formatPath)(e)}\n`)),await(0,c.parallelize)(O.flatMap(e=>f.map(t=>async()=>{w(`Reviewing file: ${(0,c.formatPath)(e)} to ${(0,c.formatLocale)(t)}`);let u=(0,o.join)(C.system.baseDir,e),d=r.getOutputFilePath(u,t,m);if(x&&(0,a.existsSync)(d)){let e=(0,o.relative)(C.system.baseDir,d);w(`${(0,l.colorize)(`⊘`,l.ANSIColors.YELLOW)} File ${(0,c.formatPath)(e)} already exists, skipping.`);return}if((0,a.existsSync)(d)){let e=n.checkFileModifiedRange(d,{skipIfModifiedBefore:y,skipIfModifiedAfter:b});if(e.isSkipped){w(e.message);return}}else (y||b)&&w(`${(0,l.colorize)(`!`,l.ANSIColors.YELLOW)} File ${(0,c.formatPath)(d)} does not exist, skipping modification date check.`);let f;if(S){let e=await(0,s.listGitLines)(u,S);w(`Git changed lines: ${e.join(`, `)}`),f=e}await i.reviewFileBlockAware(u,d,t,m,h,_,v,f,E,D)})),e=>e(),g??3)};exports.reviewDoc=f;
2
2
  //# sourceMappingURL=reviewDoc.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"reviewDoc.cjs","names":["setupAI","getOutputFilePath","ANSIColors","checkFileModifiedRange","reviewFileBlockAware"],"sources":["../../../src/reviewDoc/reviewDoc.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport type { AIOptions } from '@intlayer/api';\nimport {\n type ListGitFilesOptions,\n listGitFiles,\n listGitLines,\n logConfigDetails,\n} from '@intlayer/chokidar/cli';\nimport {\n formatLocale,\n formatPath,\n parallelize,\n} from '@intlayer/chokidar/utils';\nimport {\n ANSIColors,\n colorize,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport fg from 'fast-glob';\nimport { checkFileModifiedRange } from '../utils/checkFileModifiedRange';\nimport { getOutputFilePath } from '../utils/getOutputFilePath';\nimport { setupAI } from '../utils/setupAI';\nimport { reviewFileBlockAware } from './reviewDocBlockAware';\n\ntype ReviewDocOptions = {\n docPattern: string[];\n locales: Locale[];\n excludedGlobPattern: string[];\n baseLocale: Locale;\n aiOptions?: AIOptions;\n nbSimultaneousFileProcessed?: number;\n configOptions?: GetConfigurationOptions;\n customInstructions?: string;\n skipIfModifiedBefore?: number | string | Date;\n skipIfModifiedAfter?: number | string | Date;\n skipIfExists?: boolean;\n gitOptions?: ListGitFilesOptions;\n};\n\n/**\n * Main audit function: scans all .md files in \"en/\" (unless you specified DOC_LIST),\n * then audits them to each locale in LOCALE_LIST.\n */\nexport const reviewDoc = async ({\n docPattern,\n locales,\n excludedGlobPattern,\n baseLocale,\n aiOptions,\n nbSimultaneousFileProcessed,\n configOptions,\n customInstructions,\n skipIfModifiedBefore,\n skipIfModifiedAfter,\n skipIfExists,\n gitOptions,\n}: ReviewDocOptions) => {\n const configuration = getConfiguration(configOptions);\n logConfigDetails(configOptions);\n\n const appLogger = getAppLogger(configuration);\n\n const aiResult = await setupAI(configuration, aiOptions);\n\n if (!aiResult?.hasAIAccess) return;\n\n const { aiClient, aiConfig } = aiResult;\n\n if (nbSimultaneousFileProcessed && nbSimultaneousFileProcessed > 10) {\n appLogger(\n `Warning: nbSimultaneousFileProcessed is set to ${nbSimultaneousFileProcessed}, which is greater than 10. Setting it to 10.`\n );\n nbSimultaneousFileProcessed = 10; // Limit the number of simultaneous file processed to 10\n }\n\n let docList: string[] = await fg(docPattern, {\n ignore: excludedGlobPattern,\n });\n\n if (gitOptions) {\n const gitChangedFiles = await listGitFiles(gitOptions);\n\n if (gitChangedFiles) {\n // Convert dictionary file paths to be relative to git root for comparison\n\n // Filter dictionaries based on git changed files\n docList = docList.filter((path) =>\n gitChangedFiles.some((gitFile) => join(process.cwd(), path) === gitFile)\n );\n }\n }\n\n // OAuth handled by API proxy internally\n\n appLogger(`Base locale is ${formatLocale(baseLocale)}`);\n appLogger(\n `Reviewing ${colorizeNumber(locales.length)} locales: [ ${formatLocale(locales)} ]`\n );\n\n appLogger(`Reviewing ${colorizeNumber(docList.length)} files:`);\n appLogger(docList.map((path) => ` - ${formatPath(path)}\\n`));\n\n // Create all tasks to be processed\n const allTasks = docList.flatMap((docPath) =>\n locales.map((locale) => async () => {\n appLogger(\n `Reviewing file: ${formatPath(docPath)} to ${formatLocale(locale)}`\n );\n\n const absoluteBaseFilePath = join(configuration.system.baseDir, docPath);\n const outputFilePath = getOutputFilePath(\n absoluteBaseFilePath,\n locale,\n baseLocale\n );\n\n // Skip if file exists and skipIfExists option is enabled\n if (skipIfExists && existsSync(outputFilePath)) {\n const relativePath = relative(\n configuration.system.baseDir,\n outputFilePath\n );\n appLogger(\n `${colorize('⊘', ANSIColors.YELLOW)} File ${formatPath(relativePath)} already exists, skipping.`\n );\n return;\n }\n\n // Check modification range only if the file exists\n if (existsSync(outputFilePath)) {\n const fileModificationData = checkFileModifiedRange(outputFilePath, {\n skipIfModifiedBefore,\n skipIfModifiedAfter,\n });\n\n if (fileModificationData.isSkipped) {\n appLogger(fileModificationData.message);\n return;\n }\n } else if (skipIfModifiedBefore || skipIfModifiedAfter) {\n // Log if we intended to check modification time but couldn't because the file doesn't exist\n appLogger(\n `${colorize('!', ANSIColors.YELLOW)} File ${formatPath(outputFilePath)} does not exist, skipping modification date check.`\n );\n }\n\n let changedLines: number[] | undefined;\n // FIXED: Enable git optimization that was previously commented out\n if (gitOptions) {\n const gitChangedLines = await listGitLines(\n absoluteBaseFilePath,\n gitOptions\n );\n\n appLogger(`Git changed lines: ${gitChangedLines.join(', ')}`);\n changedLines = gitChangedLines;\n }\n\n await reviewFileBlockAware(\n absoluteBaseFilePath,\n outputFilePath,\n locale as Locale,\n baseLocale,\n aiOptions,\n configOptions,\n customInstructions,\n changedLines,\n aiClient,\n aiConfig\n );\n })\n );\n\n await parallelize(\n allTasks,\n (task) => task(),\n nbSimultaneousFileProcessed ?? 3\n );\n};\n"],"mappings":"sgBAkDA,MAAa,EAAY,MAAO,CAC9B,aACA,UACA,sBACA,aACA,YACA,8BACA,gBACA,qBACA,uBACA,sBACA,eACA,gBACsB,CACtB,IAAM,GAAA,EAAA,EAAA,kBAAiC,EAAc,EACrD,EAAA,EAAA,kBAAiB,EAAc,CAE/B,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAc,CAEvC,EAAW,MAAMA,EAAAA,QAAQ,EAAe,EAAU,CAExD,GAAI,CAAC,GAAU,YAAa,OAE5B,GAAM,CAAE,WAAU,YAAa,EAE3B,GAA+B,EAA8B,KAC/D,EACE,kDAAkD,EAA4B,+CAC/E,CACD,EAA8B,IAGhC,IAAI,EAAoB,MAAA,EAAA,EAAA,SAAS,EAAY,CAC3C,OAAQ,EACT,CAAC,CAEF,GAAI,EAAY,CACd,IAAM,EAAkB,MAAA,EAAA,EAAA,cAAmB,EAAW,CAElD,IAIF,EAAU,EAAQ,OAAQ,GACxB,EAAgB,KAAM,IAAA,EAAA,EAAA,MAAiB,QAAQ,KAAK,CAAE,EAAK,GAAK,EAAQ,CACzE,EAML,EAAU,mBAAA,EAAA,EAAA,cAA+B,EAAW,GAAG,CACvD,EACE,cAAA,EAAA,EAAA,gBAA4B,EAAQ,OAAO,CAAC,eAAA,EAAA,EAAA,cAA2B,EAAQ,CAAC,IACjF,CAED,EAAU,cAAA,EAA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ANSIColors","checkFileModifiedRange","reviewFileBlockAware"],"sources":["../../../src/reviewDoc/reviewDoc.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport type { AIOptions } from '@intlayer/api';\nimport {\n type ListGitFilesOptions,\n listGitFiles,\n listGitLines,\n logConfigDetails,\n} from '@intlayer/chokidar/cli';\nimport {\n formatLocale,\n formatPath,\n parallelize,\n} from '@intlayer/chokidar/utils';\nimport {\n ANSIColors,\n colorize,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport fg from 'fast-glob';\nimport { checkFileModifiedRange } from '../utils/checkFileModifiedRange';\nimport { getOutputFilePath } from '../utils/getOutputFilePath';\nimport { setupAI } from '../utils/setupAI';\nimport { reviewFileBlockAware } from './reviewDocBlockAware';\n\ntype ReviewDocOptions = {\n docPattern: string[];\n locales: Locale[];\n excludedGlobPattern: string[];\n baseLocale: Locale;\n aiOptions?: AIOptions;\n nbSimultaneousFileProcessed?: number;\n configOptions?: GetConfigurationOptions;\n customInstructions?: string;\n skipIfModifiedBefore?: number | string | Date;\n skipIfModifiedAfter?: number | string | Date;\n skipIfExists?: boolean;\n gitOptions?: ListGitFilesOptions;\n};\n\n/**\n * Main audit function: scans all .md files in \"en/\" (unless you specified DOC_LIST),\n * then audits them to each locale in LOCALE_LIST.\n */\nexport const reviewDoc = async ({\n docPattern,\n locales,\n excludedGlobPattern,\n baseLocale,\n aiOptions,\n nbSimultaneousFileProcessed,\n configOptions,\n customInstructions,\n skipIfModifiedBefore,\n skipIfModifiedAfter,\n skipIfExists,\n gitOptions,\n}: ReviewDocOptions) => {\n const configuration = getConfiguration(configOptions);\n logConfigDetails(configOptions);\n\n const appLogger = getAppLogger(configuration);\n\n const aiResult = await setupAI(configuration, aiOptions);\n\n if (!aiResult?.hasAIAccess) return;\n\n const { aiClient, aiConfig } = aiResult;\n\n if (nbSimultaneousFileProcessed && nbSimultaneousFileProcessed > 10) {\n appLogger(\n `Warning: nbSimultaneousFileProcessed is set to ${nbSimultaneousFileProcessed}, which is greater than 10. Setting it to 10.`\n );\n nbSimultaneousFileProcessed = 10; // Limit the number of simultaneous file processed to 10\n }\n\n let docList: string[] = await fg(docPattern, {\n ignore: excludedGlobPattern,\n });\n\n if (gitOptions) {\n const gitChangedFiles = await listGitFiles(gitOptions);\n\n if (gitChangedFiles) {\n // Convert dictionary file paths to be relative to git root for comparison\n\n // Filter dictionaries based on git changed files\n docList = docList.filter((path) =>\n gitChangedFiles.some((gitFile) => join(process.cwd(), path) === gitFile)\n );\n }\n }\n\n // OAuth handled by API proxy internally\n\n appLogger(`Base locale is ${formatLocale(baseLocale)}`);\n appLogger(\n `Reviewing ${colorizeNumber(locales.length)} locales: [ ${formatLocale(locales)} ]`\n );\n\n appLogger(`Reviewing ${colorizeNumber(docList.length)} files:`);\n appLogger(docList.map((path) => ` - ${formatPath(path)}\\n`));\n\n // Create all tasks to be processed\n const allTasks = docList.flatMap((docPath) =>\n locales.map((locale) => async () => {\n appLogger(\n `Reviewing file: ${formatPath(docPath)} to ${formatLocale(locale)}`\n );\n\n const absoluteBaseFilePath = join(configuration.system.baseDir, docPath);\n const outputFilePath = getOutputFilePath(\n absoluteBaseFilePath,\n locale,\n baseLocale\n );\n\n // Skip if file exists and skipIfExists option is enabled\n if (skipIfExists && existsSync(outputFilePath)) {\n const relativePath = relative(\n configuration.system.baseDir,\n outputFilePath\n );\n appLogger(\n `${colorize('⊘', ANSIColors.YELLOW)} File ${formatPath(relativePath)} already exists, skipping.`\n );\n return;\n }\n\n // Check modification range only if the file exists\n if (existsSync(outputFilePath)) {\n const fileModificationData = checkFileModifiedRange(outputFilePath, {\n skipIfModifiedBefore,\n skipIfModifiedAfter,\n });\n\n if (fileModificationData.isSkipped) {\n appLogger(fileModificationData.message);\n return;\n }\n } else if (skipIfModifiedBefore || skipIfModifiedAfter) {\n // Log if we intended to check modification time but couldn't because the file doesn't exist\n appLogger(\n `${colorize('!', ANSIColors.YELLOW)} File ${formatPath(outputFilePath)} does not exist, skipping modification date check.`\n );\n }\n\n let changedLines: number[] | undefined;\n // FIXED: Enable git optimization that was previously commented out\n if (gitOptions) {\n const gitChangedLines = await listGitLines(\n absoluteBaseFilePath,\n gitOptions\n );\n\n appLogger(`Git changed lines: ${gitChangedLines.join(', ')}`);\n changedLines = gitChangedLines;\n }\n\n await reviewFileBlockAware(\n absoluteBaseFilePath,\n outputFilePath,\n locale as Locale,\n baseLocale,\n aiOptions,\n configOptions,\n customInstructions,\n changedLines,\n aiClient,\n aiConfig\n );\n })\n );\n\n await parallelize(\n allTasks,\n (task) => task(),\n nbSimultaneousFileProcessed ?? 3\n );\n};\n"],"mappings":"ofAkDA,MAAa,EAAY,MAAO,CAC9B,aACA,UACA,sBACA,aACA,YACA,8BACA,gBACA,qBACA,uBACA,sBACA,eACA,gBACsB,CACtB,IAAM,GAAA,EAAA,EAAA,kBAAiC,EAAc,EACrD,EAAA,EAAA,kBAAiB,EAAc,CAE/B,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAc,CAEvC,EAAW,MAAMA,EAAAA,QAAQ,EAAe,EAAU,CAExD,GAAI,CAAC,GAAU,YAAa,OAE5B,GAAM,CAAE,WAAU,YAAa,EAE3B,GAA+B,EAA8B,KAC/D,EACE,kDAAkD,EAA4B,+CAC/E,CACD,EAA8B,IAGhC,IAAI,EAAoB,MAAA,EAAA,EAAA,SAAS,EAAY,CAC3C,OAAQ,EACT,CAAC,CAEF,GAAI,EAAY,CACd,IAAM,EAAkB,MAAA,EAAA,EAAA,cAAmB,EAAW,CAElD,IAIF,EAAU,EAAQ,OAAQ,GACxB,EAAgB,KAAM,IAAA,EAAA,EAAA,MAAiB,QAAQ,KAAK,CAAE,EAAK,GAAK,EAAQ,CACzE,EAML,EAAU,mBAAA,EAAA,EAAA,cAA+B,EAAW,GAAG,CACvD,EACE,cAA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A,EACD,EACD,CACH,CAIE,GAAS,GAAM,CAChB,GAA+B,EAChC"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`),t=require(`../_virtual/_utils_asset.cjs`),n=require(`../translateDoc/validation.cjs`),r=require(`../translation-alignment/rebuildDocument.cjs`),i=require(`../translation-alignment/pipeline.cjs`),a=require(`../utils/chunkInference.cjs`),o=require(`../utils/fixChunkStartEndChars.cjs`);let s=require(`node:fs`),c=require(`node:path`),l=require(`@intlayer/chokidar/utils`),u=require(`@intlayer/config/logger`),d=require(`@intlayer/config/node`),f=require(`@intlayer/config/utils`),p=require(`node:fs/promises`),m=require(`@intlayer/core/localization`),h=require(`@intlayer/types/locales`);h=e.__toESM(h);const g=async(e,g,_,v,y,b,x,S,C,w)=>{let T=(0,d.getConfiguration)(b),E=(0,u.getAppLogger)(T),D=await(0,p.readFile)(e,`utf-8`),O=await(0,p.readFile)(g,`utf-8`).catch(()=>``),k=t.readAsset(`./prompts/REVIEW_PROMPT.md`,`utf-8`).replaceAll(`{{localeName}}`,`${(0,l.formatLocale)(_,!1)}`).replaceAll(`{{baseLocaleName}}`,`${(0,l.formatLocale)(v,!1)}`).replace(`{{applicationContext}}`,y?.applicationContext??`-`).replace(`{{customInstructions}}`,x??`-`),A=[(0,u.colon)(`${u.ANSIColors.GREY_DARK}[${(0,l.formatPath)(e)}${u.ANSIColors.GREY_DARK}] `,{colSize:40}),`→ ${u.ANSIColors.RESET}`].join(``),j=[(0,u.colon)(`${u.ANSIColors.GREY_DARK}[${(0,l.formatPath)(e)}${u.ANSIColors.GREY_DARK}][${(0,l.formatLocale)(_)}${u.ANSIColors.GREY_DARK}] `,{colSize:40}),`→ ${u.ANSIColors.RESET}`].join(``),{englishBlocks:M,frenchBlocks:N,plan:P,segmentsToReview:F}=i.buildAlignmentPlan({englishText:D,frenchText:O,changedLines:S});if(E(`${A}Block-aware alignment complete. Total blocks: EN=${(0,u.colorizeNumber)(M.length)}, FR=${(0,u.colorizeNumber)(N.length)}`),E(`${A}Actions: reuse=${(0,u.colorizeNumber)(P.actions.filter(e=>e.kind===`reuse`).length)}, review=${(0,u.colorizeNumber)(P.actions.filter(e=>e.kind===`review`).length)}, new=${(0,u.colorizeNumber)(P.actions.filter(e=>e.kind===`insert_new`).length)}, delete=${(0,u.colorizeNumber)(P.actions.filter(e=>e.kind===`delete`).length)}`),F.length===0){E(`${A}No segments need review, reusing existing translation`),(0,s.mkdirSync)((0,c.dirname)(g),{recursive:!0}),(0,s.writeFileSync)(g,r.mergeReviewedSegments(P,N,new Map)),E(`${(0,u.colorize)(`✔`,u.ANSIColors.GREEN)} File ${(0,l.formatPath)(g)} updated successfully (no changes needed).`);return}E(`${A}Segments to review: ${(0,u.colorizeNumber)(F.length)}`);let I=new Map;for(let e of F){let t=F.indexOf(e)+1,r=e.englishBlock,i=()=>`**BLOCK ${t} of ${F.length}** is the base block in ${(0,l.formatLocale)(v,!1)} as reference.\n///chunksStart///\n`+r.content+`///chunksEnd///`,s=()=>`**BLOCK ${t} of ${F.length}** is the current block to review in ${(0,l.formatLocale)(_,!1)}.\n///chunksStart///\n`+(e.frenchBlockText??``)+`///chunksEnd///`,c=await(0,f.retryManager)(async()=>{let e=await a.chunkInference([{role:`system`,content:k},{role:`system`,content:i()},{role:`system`,content:s()},{role:`system`,content:`The next user message will be the **BLOCK ${(0,u.colorizeNumber)(t)} of ${(0,u.colorizeNumber)(F.length)}** that should be translated in ${(0,m.getLocaleName)(_,h.ENGLISH)} (${_}).`},{role:`user`,content:r.content}],y,T,C,w);E(`${j}${(0,u.colorizeNumber)(e.tokenUsed)} tokens used - Block ${(0,u.colorizeNumber)(t)} of ${(0,u.colorizeNumber)(F.length)}`);let c=n.sanitizeChunk(e?.fileContent,r.content);if(c=o.fixChunkStartEndChars(c,r.content),!n.validateTranslation(r.content,c,E))throw Error(`Validation failed for chunk (structure or length mismatch). Retrying...`);return c})();I.set(e.actionIndex,c)}let L=r.mergeReviewedSegments(P,N,I);(0,s.mkdirSync)((0,c.dirname)(g),{recursive:!0}),(0,s.writeFileSync)(g,L),E(`${(0,u.colorize)(`✔`,u.ANSIColors.GREEN)} File ${(0,l.formatPath)(g)} created/updated successfully.`)};exports.reviewFileBlockAware=g;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../chunk-Bmb41Sf3.cjs`);const e=require(`../_utils_asset-ghp_Cjwk.cjs`),t=require(`../translateDoc/validation.cjs`),n=require(`../translation-alignment/rebuildDocument.cjs`),r=require(`../translation-alignment/pipeline.cjs`),i=require(`../utils/chunkInference.cjs`),a=require(`../utils/fixChunkStartEndChars.cjs`);let o=require(`node:fs`),s=require(`node:path`),c=require(`@intlayer/chokidar/utils`),l=require(`@intlayer/config/logger`),u=require(`@intlayer/config/node`),d=require(`@intlayer/config/utils`),f=require(`node:fs/promises`),p=require(`@intlayer/core/localization`),m=require(`@intlayer/types/locales`);const h=async(h,g,_,v,y,b,x,S,C,w)=>{let T=(0,u.getConfiguration)(b),E=(0,l.getAppLogger)(T),D=await(0,f.readFile)(h,`utf-8`),O=await(0,f.readFile)(g,`utf-8`).catch(()=>``),k=e.t(`./prompts/REVIEW_PROMPT.md`,`utf-8`).replaceAll(`{{localeName}}`,`${(0,c.formatLocale)(_,!1)}`).replaceAll(`{{baseLocaleName}}`,`${(0,c.formatLocale)(v,!1)}`).replace(`{{applicationContext}}`,y?.applicationContext??`-`).replace(`{{customInstructions}}`,x??`-`),A=[(0,l.colon)(`${l.ANSIColors.GREY_DARK}[${(0,c.formatPath)(h)}${l.ANSIColors.GREY_DARK}] `,{colSize:40}),`→ ${l.ANSIColors.RESET}`].join(``),j=[(0,l.colon)(`${l.ANSIColors.GREY_DARK}[${(0,c.formatPath)(h)}${l.ANSIColors.GREY_DARK}][${(0,c.formatLocale)(_)}${l.ANSIColors.GREY_DARK}] `,{colSize:40}),`→ ${l.ANSIColors.RESET}`].join(``),{englishBlocks:M,frenchBlocks:N,plan:P,segmentsToReview:F}=r.buildAlignmentPlan({englishText:D,frenchText:O,changedLines:S});if(E(`${A}Block-aware alignment complete. Total blocks: EN=${(0,l.colorizeNumber)(M.length)}, FR=${(0,l.colorizeNumber)(N.length)}`),E(`${A}Actions: reuse=${(0,l.colorizeNumber)(P.actions.filter(e=>e.kind===`reuse`).length)}, review=${(0,l.colorizeNumber)(P.actions.filter(e=>e.kind===`review`).length)}, new=${(0,l.colorizeNumber)(P.actions.filter(e=>e.kind===`insert_new`).length)}, delete=${(0,l.colorizeNumber)(P.actions.filter(e=>e.kind===`delete`).length)}`),F.length===0){E(`${A}No segments need review, reusing existing translation`),(0,o.mkdirSync)((0,s.dirname)(g),{recursive:!0}),(0,o.writeFileSync)(g,n.mergeReviewedSegments(P,N,new Map)),E(`${(0,l.colorize)(`✔`,l.ANSIColors.GREEN)} File ${(0,c.formatPath)(g)} updated successfully (no changes needed).`);return}E(`${A}Segments to review: ${(0,l.colorizeNumber)(F.length)}`);let I=new Map;for(let e of F){let n=F.indexOf(e)+1,r=e.englishBlock,o=()=>`**BLOCK ${n} of ${F.length}** is the base block in ${(0,c.formatLocale)(v,!1)} as reference.\n///chunksStart///\n`+r.content+`///chunksEnd///`,s=()=>`**BLOCK ${n} of ${F.length}** is the current block to review in ${(0,c.formatLocale)(_,!1)}.\n///chunksStart///\n`+(e.frenchBlockText??``)+`///chunksEnd///`,u=await(0,d.retryManager)(async()=>{let e=await i.chunkInference([{role:`system`,content:k},{role:`system`,content:o()},{role:`system`,content:s()},{role:`system`,content:`The next user message will be the **BLOCK ${(0,l.colorizeNumber)(n)} of ${(0,l.colorizeNumber)(F.length)}** that should be translated in ${(0,p.getLocaleName)(_,m.ENGLISH)} (${_}).`},{role:`user`,content:r.content}],y,T,C,w);E(`${j}${(0,l.colorizeNumber)(e.tokenUsed)} tokens used - Block ${(0,l.colorizeNumber)(n)} of ${(0,l.colorizeNumber)(F.length)}`);let c=t.sanitizeChunk(e?.fileContent,r.content);if(c=a.fixChunkStartEndChars(c,r.content),!t.validateTranslation(r.content,c,E))throw Error(`Validation failed for chunk (structure or length mismatch). Retrying...`);return c})();I.set(e.actionIndex,u)}let L=n.mergeReviewedSegments(P,N,I);(0,o.mkdirSync)((0,s.dirname)(g),{recursive:!0}),(0,o.writeFileSync)(g,L),E(`${(0,l.colorize)(`✔`,l.ANSIColors.GREEN)} File ${(0,c.formatPath)(g)} created/updated successfully.`)};exports.reviewFileBlockAware=h;
2
2
  //# sourceMappingURL=reviewDocBlockAware.cjs.map