gtx-cli 2.6.31 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (348) hide show
  1. package/CHANGELOG.md +4 -1261
  2. package/README.md +12 -3
  3. package/dist/bin/bin-entry.js +2 -1
  4. package/dist/config/generateSettings.d.ts +1 -9
  5. package/dist/config/generateSettings.js +1 -214
  6. package/dist/config/resolveConfig.d.ts +1 -4
  7. package/dist/config/resolveConfig.js +1 -33
  8. package/dist/fs/config/setupConfig.d.ts +1 -17
  9. package/dist/fs/config/setupConfig.js +1 -50
  10. package/dist/fs/matchFiles.d.ts +1 -1
  11. package/dist/fs/matchFiles.js +1 -8
  12. package/dist/functions.d.ts +1 -7
  13. package/dist/functions.js +1 -6
  14. package/dist/index.d.ts +1 -4
  15. package/dist/index.js +1 -27
  16. package/dist/main.js +2 -2
  17. package/dist/next/parse/handleInitGT.d.ts +1 -7
  18. package/dist/next/parse/handleInitGT.js +1 -157
  19. package/dist/next/parse/wrapContent.d.ts +1 -12
  20. package/dist/next/parse/wrapContent.js +1 -164
  21. package/dist/react/parse/wrapContent.d.ts +1 -12
  22. package/dist/react/parse/wrapContent.js +1 -162
  23. package/dist/types/index.d.ts +1 -243
  24. package/dist/types/index.js +1 -1
  25. package/dist/utils/installPackage.d.ts +1 -3
  26. package/dist/utils/installPackage.js +1 -77
  27. package/dist/utils/packageInfo.d.ts +1 -3
  28. package/dist/utils/packageInfo.js +1 -17
  29. package/dist/utils/packageJson.d.ts +1 -6
  30. package/dist/utils/packageJson.js +1 -68
  31. package/dist/utils/packageManager.d.ts +1 -28
  32. package/dist/utils/packageManager.js +1 -269
  33. package/package.json +11 -97
  34. package/dist/api/collectUserEditDiffs.d.ts +0 -9
  35. package/dist/api/collectUserEditDiffs.js +0 -159
  36. package/dist/api/downloadFileBatch.d.ts +0 -23
  37. package/dist/api/downloadFileBatch.js +0 -190
  38. package/dist/api/saveLocalEdits.d.ts +0 -6
  39. package/dist/api/saveLocalEdits.js +0 -38
  40. package/dist/cli/base.d.ts +0 -59
  41. package/dist/cli/base.js +0 -529
  42. package/dist/cli/commands/download.d.ts +0 -8
  43. package/dist/cli/commands/download.js +0 -51
  44. package/dist/cli/commands/enqueue.d.ts +0 -9
  45. package/dist/cli/commands/enqueue.js +0 -27
  46. package/dist/cli/commands/setupProject.d.ts +0 -7
  47. package/dist/cli/commands/setupProject.js +0 -37
  48. package/dist/cli/commands/stage.d.ts +0 -9
  49. package/dist/cli/commands/stage.js +0 -59
  50. package/dist/cli/commands/translate.d.ts +0 -7
  51. package/dist/cli/commands/translate.js +0 -70
  52. package/dist/cli/commands/upload.d.ts +0 -13
  53. package/dist/cli/commands/upload.js +0 -142
  54. package/dist/cli/commands/utils/validation.d.ts +0 -13
  55. package/dist/cli/commands/utils/validation.js +0 -38
  56. package/dist/cli/flags.d.ts +0 -15
  57. package/dist/cli/flags.js +0 -70
  58. package/dist/cli/inline.d.ts +0 -17
  59. package/dist/cli/inline.js +0 -135
  60. package/dist/cli/next.d.ts +0 -10
  61. package/dist/cli/next.js +0 -12
  62. package/dist/cli/node.d.ts +0 -10
  63. package/dist/cli/node.js +0 -9
  64. package/dist/cli/react.d.ts +0 -12
  65. package/dist/cli/react.js +0 -72
  66. package/dist/config/optionPresets.d.ts +0 -3
  67. package/dist/config/optionPresets.js +0 -65
  68. package/dist/config/utils.d.ts +0 -2
  69. package/dist/config/utils.js +0 -4
  70. package/dist/config/validateSettings.d.ts +0 -3
  71. package/dist/config/validateSettings.js +0 -32
  72. package/dist/console/colors.d.ts +0 -6
  73. package/dist/console/colors.js +0 -19
  74. package/dist/console/displayTranslateSummary.d.ts +0 -1
  75. package/dist/console/displayTranslateSummary.js +0 -42
  76. package/dist/console/formatting.d.ts +0 -1
  77. package/dist/console/formatting.js +0 -7
  78. package/dist/console/index.d.ts +0 -34
  79. package/dist/console/index.js +0 -46
  80. package/dist/console/logger.d.ts +0 -35
  81. package/dist/console/logger.js +0 -250
  82. package/dist/console/logging.d.ts +0 -52
  83. package/dist/console/logging.js +0 -175
  84. package/dist/formats/files/aggregateFiles.d.ts +0 -4
  85. package/dist/formats/files/aggregateFiles.js +0 -156
  86. package/dist/formats/files/collectFiles.d.ts +0 -6
  87. package/dist/formats/files/collectFiles.js +0 -49
  88. package/dist/formats/files/convertToFileTranslationData.d.ts +0 -15
  89. package/dist/formats/files/convertToFileTranslationData.js +0 -21
  90. package/dist/formats/files/fileMapping.d.ts +0 -11
  91. package/dist/formats/files/fileMapping.js +0 -115
  92. package/dist/formats/files/preprocess/mdx.d.ts +0 -6
  93. package/dist/formats/files/preprocess/mdx.js +0 -14
  94. package/dist/formats/files/preprocess/mintlify.d.ts +0 -5
  95. package/dist/formats/files/preprocess/mintlify.js +0 -15
  96. package/dist/formats/files/preprocessContent.d.ts +0 -8
  97. package/dist/formats/files/preprocessContent.js +0 -23
  98. package/dist/formats/files/save.d.ts +0 -5
  99. package/dist/formats/files/save.js +0 -17
  100. package/dist/formats/files/supportedFiles.d.ts +0 -11
  101. package/dist/formats/files/supportedFiles.js +0 -20
  102. package/dist/formats/json/extractJson.d.ts +0 -15
  103. package/dist/formats/json/extractJson.js +0 -101
  104. package/dist/formats/json/flattenJson.d.ts +0 -14
  105. package/dist/formats/json/flattenJson.js +0 -64
  106. package/dist/formats/json/mergeJson.d.ts +0 -13
  107. package/dist/formats/json/mergeJson.js +0 -367
  108. package/dist/formats/json/parseJson.d.ts +0 -2
  109. package/dist/formats/json/parseJson.js +0 -109
  110. package/dist/formats/json/utils.d.ts +0 -47
  111. package/dist/formats/json/utils.js +0 -150
  112. package/dist/formats/utils.d.ts +0 -2
  113. package/dist/formats/utils.js +0 -24
  114. package/dist/formats/yaml/mergeYaml.d.ts +0 -5
  115. package/dist/formats/yaml/mergeYaml.js +0 -61
  116. package/dist/formats/yaml/parseYaml.d.ts +0 -5
  117. package/dist/formats/yaml/parseYaml.js +0 -24
  118. package/dist/formats/yaml/utils.d.ts +0 -2
  119. package/dist/formats/yaml/utils.js +0 -23
  120. package/dist/fs/clearLocaleDirs.d.ts +0 -8
  121. package/dist/fs/clearLocaleDirs.js +0 -126
  122. package/dist/fs/config/downloadedVersions.d.ts +0 -21
  123. package/dist/fs/config/downloadedVersions.js +0 -50
  124. package/dist/fs/config/loadConfig.d.ts +0 -1
  125. package/dist/fs/config/loadConfig.js +0 -9
  126. package/dist/fs/config/parseFilesConfig.d.ts +0 -27
  127. package/dist/fs/config/parseFilesConfig.js +0 -150
  128. package/dist/fs/config/updateConfig.d.ts +0 -21
  129. package/dist/fs/config/updateConfig.js +0 -57
  130. package/dist/fs/config/updateVersions.d.ts +0 -11
  131. package/dist/fs/config/updateVersions.js +0 -30
  132. package/dist/fs/copyFile.d.ts +0 -7
  133. package/dist/fs/copyFile.js +0 -39
  134. package/dist/fs/createLoadTranslationsFile.d.ts +0 -1
  135. package/dist/fs/createLoadTranslationsFile.js +0 -49
  136. package/dist/fs/determineFramework.d.ts +0 -5
  137. package/dist/fs/determineFramework.js +0 -53
  138. package/dist/fs/findFilepath.d.ts +0 -36
  139. package/dist/fs/findFilepath.js +0 -90
  140. package/dist/fs/index.d.ts +0 -1
  141. package/dist/fs/index.js +0 -1
  142. package/dist/fs/loadJSON.d.ts +0 -6
  143. package/dist/fs/loadJSON.js +0 -17
  144. package/dist/fs/saveJSON.d.ts +0 -1
  145. package/dist/fs/saveJSON.js +0 -7
  146. package/dist/fs/utils.d.ts +0 -1
  147. package/dist/fs/utils.js +0 -16
  148. package/dist/generated/version.d.ts +0 -1
  149. package/dist/generated/version.js +0 -2
  150. package/dist/git/branches.d.ts +0 -7
  151. package/dist/git/branches.js +0 -88
  152. package/dist/hooks/postProcess.d.ts +0 -4
  153. package/dist/hooks/postProcess.js +0 -110
  154. package/dist/locadex/setupFlow.d.ts +0 -2
  155. package/dist/locadex/setupFlow.js +0 -9
  156. package/dist/next/config/parseNextConfig.d.ts +0 -10
  157. package/dist/next/config/parseNextConfig.js +0 -53
  158. package/dist/next/jsx/utils.d.ts +0 -7
  159. package/dist/next/jsx/utils.js +0 -42
  160. package/dist/react/config/createESBuildConfig.d.ts +0 -2
  161. package/dist/react/config/createESBuildConfig.js +0 -119
  162. package/dist/react/jsx/evaluateJsx.d.ts +0 -24
  163. package/dist/react/jsx/evaluateJsx.js +0 -123
  164. package/dist/react/jsx/utils/buildImportMap.d.ts +0 -9
  165. package/dist/react/jsx/utils/buildImportMap.js +0 -30
  166. package/dist/react/jsx/utils/constants.d.ts +0 -15
  167. package/dist/react/jsx/utils/constants.js +0 -49
  168. package/dist/react/jsx/utils/getCalleeNameFromExpression.d.ts +0 -9
  169. package/dist/react/jsx/utils/getCalleeNameFromExpression.js +0 -32
  170. package/dist/react/jsx/utils/getPathsAndAliases.d.ts +0 -21
  171. package/dist/react/jsx/utils/getPathsAndAliases.js +0 -91
  172. package/dist/react/jsx/utils/isNumberLiteral.d.ts +0 -7
  173. package/dist/react/jsx/utils/isNumberLiteral.js +0 -13
  174. package/dist/react/jsx/utils/jsxParsing/addGTIdentifierToSyntaxTree.d.ts +0 -9
  175. package/dist/react/jsx/utils/jsxParsing/addGTIdentifierToSyntaxTree.js +0 -138
  176. package/dist/react/jsx/utils/jsxParsing/handleChildrenWhitespace.d.ts +0 -6
  177. package/dist/react/jsx/utils/jsxParsing/handleChildrenWhitespace.js +0 -197
  178. package/dist/react/jsx/utils/jsxParsing/multiplication/findMultiplicationNode.d.ts +0 -13
  179. package/dist/react/jsx/utils/jsxParsing/multiplication/findMultiplicationNode.js +0 -42
  180. package/dist/react/jsx/utils/jsxParsing/multiplication/multiplyJsxTree.d.ts +0 -5
  181. package/dist/react/jsx/utils/jsxParsing/multiplication/multiplyJsxTree.js +0 -69
  182. package/dist/react/jsx/utils/jsxParsing/parseJsx.d.ts +0 -33
  183. package/dist/react/jsx/utils/jsxParsing/parseJsx.js +0 -918
  184. package/dist/react/jsx/utils/jsxParsing/parseTProps.d.ts +0 -8
  185. package/dist/react/jsx/utils/jsxParsing/parseTProps.js +0 -65
  186. package/dist/react/jsx/utils/jsxParsing/removeNullChildrenFields.d.ts +0 -2
  187. package/dist/react/jsx/utils/jsxParsing/removeNullChildrenFields.js +0 -61
  188. package/dist/react/jsx/utils/jsxParsing/types.d.ts +0 -48
  189. package/dist/react/jsx/utils/jsxParsing/types.js +0 -34
  190. package/dist/react/jsx/utils/mapAttributeName.d.ts +0 -11
  191. package/dist/react/jsx/utils/mapAttributeName.js +0 -12
  192. package/dist/react/jsx/utils/parseAst.d.ts +0 -31
  193. package/dist/react/jsx/utils/parseAst.js +0 -278
  194. package/dist/react/jsx/utils/parseDeclareStatic.d.ts +0 -15
  195. package/dist/react/jsx/utils/parseDeclareStatic.js +0 -540
  196. package/dist/react/jsx/utils/parseString.d.ts +0 -25
  197. package/dist/react/jsx/utils/parseString.js +0 -540
  198. package/dist/react/jsx/utils/parseStringFunction.d.ts +0 -30
  199. package/dist/react/jsx/utils/parseStringFunction.js +0 -348
  200. package/dist/react/jsx/utils/resolveImportPath.d.ts +0 -11
  201. package/dist/react/jsx/utils/resolveImportPath.js +0 -111
  202. package/dist/react/jsx/utils/stringParsing/processTranslationCall/extractStringEntryMetadata.d.ts +0 -29
  203. package/dist/react/jsx/utils/stringParsing/processTranslationCall/extractStringEntryMetadata.js +0 -86
  204. package/dist/react/jsx/utils/stringParsing/processTranslationCall/handleInvalidTranslationCall.d.ts +0 -14
  205. package/dist/react/jsx/utils/stringParsing/processTranslationCall/handleInvalidTranslationCall.js +0 -24
  206. package/dist/react/jsx/utils/stringParsing/processTranslationCall/handleLiteralTranslationCall.d.ts +0 -19
  207. package/dist/react/jsx/utils/stringParsing/processTranslationCall/handleLiteralTranslationCall.js +0 -31
  208. package/dist/react/jsx/utils/stringParsing/processTranslationCall/handleStaticTranslationCall.d.ts +0 -22
  209. package/dist/react/jsx/utils/stringParsing/processTranslationCall/handleStaticTranslationCall.js +0 -51
  210. package/dist/react/jsx/utils/stringParsing/processTranslationCall/index.d.ts +0 -18
  211. package/dist/react/jsx/utils/stringParsing/processTranslationCall/index.js +0 -39
  212. package/dist/react/jsx/utils/stringParsing/processTranslationCall/routeTranslationCall.d.ts +0 -24
  213. package/dist/react/jsx/utils/stringParsing/processTranslationCall/routeTranslationCall.js +0 -68
  214. package/dist/react/jsx/utils/stringParsing/types.d.ts +0 -41
  215. package/dist/react/jsx/utils/stringParsing/types.js +0 -1
  216. package/dist/react/jsx/utils/types.d.ts +0 -14
  217. package/dist/react/jsx/utils/types.js +0 -1
  218. package/dist/react/jsx/utils/validateStringFunction.d.ts +0 -7
  219. package/dist/react/jsx/utils/validateStringFunction.js +0 -31
  220. package/dist/react/jsx/wrapJsx.d.ts +0 -51
  221. package/dist/react/jsx/wrapJsx.js +0 -387
  222. package/dist/react/parse/addVitePlugin/index.d.ts +0 -22
  223. package/dist/react/parse/addVitePlugin/index.js +0 -41
  224. package/dist/react/parse/addVitePlugin/installCompiler.d.ts +0 -8
  225. package/dist/react/parse/addVitePlugin/installCompiler.js +0 -22
  226. package/dist/react/parse/addVitePlugin/updateViteConfig.d.ts +0 -19
  227. package/dist/react/parse/addVitePlugin/updateViteConfig.js +0 -120
  228. package/dist/react/parse/addVitePlugin/utils/addCompilerImport.d.ts +0 -9
  229. package/dist/react/parse/addVitePlugin/utils/addCompilerImport.js +0 -34
  230. package/dist/react/parse/addVitePlugin/utils/addPluginInvocation.d.ts +0 -11
  231. package/dist/react/parse/addVitePlugin/utils/addPluginInvocation.js +0 -48
  232. package/dist/react/parse/addVitePlugin/utils/checkCompilerImport.d.ts +0 -15
  233. package/dist/react/parse/addVitePlugin/utils/checkCompilerImport.js +0 -113
  234. package/dist/react/parse/addVitePlugin/utils/checkPluginInvocation.d.ts +0 -12
  235. package/dist/react/parse/addVitePlugin/utils/checkPluginInvocation.js +0 -32
  236. package/dist/react/parse/createDictionaryUpdates.d.ts +0 -3
  237. package/dist/react/parse/createDictionaryUpdates.js +0 -187
  238. package/dist/react/parse/createInlineUpdates.d.ts +0 -13
  239. package/dist/react/parse/createInlineUpdates.js +0 -161
  240. package/dist/react/utils/flattenDictionary.d.ts +0 -20
  241. package/dist/react/utils/flattenDictionary.js +0 -75
  242. package/dist/react/utils/getEntryAndMetadata.d.ts +0 -5
  243. package/dist/react/utils/getEntryAndMetadata.js +0 -11
  244. package/dist/react/utils/getVariableName.d.ts +0 -25
  245. package/dist/react/utils/getVariableName.js +0 -37
  246. package/dist/setup/agentInstructions.d.ts +0 -24
  247. package/dist/setup/agentInstructions.js +0 -138
  248. package/dist/setup/detectFramework.d.ts +0 -31
  249. package/dist/setup/detectFramework.js +0 -106
  250. package/dist/setup/frameworkUtils.d.ts +0 -3
  251. package/dist/setup/frameworkUtils.js +0 -30
  252. package/dist/setup/instructions/base.md +0 -29
  253. package/dist/setup/instructions/gt-next.md +0 -107
  254. package/dist/setup/instructions/gt-react.md +0 -98
  255. package/dist/setup/userInput.d.ts +0 -4
  256. package/dist/setup/userInput.js +0 -32
  257. package/dist/setup/wizard.d.ts +0 -3
  258. package/dist/setup/wizard.js +0 -147
  259. package/dist/state/recentDownloads.d.ts +0 -12
  260. package/dist/state/recentDownloads.js +0 -18
  261. package/dist/state/translateWarnings.d.ts +0 -10
  262. package/dist/state/translateWarnings.js +0 -13
  263. package/dist/translation/parse.d.ts +0 -17
  264. package/dist/translation/parse.js +0 -77
  265. package/dist/translation/stage.d.ts +0 -3
  266. package/dist/translation/stage.js +0 -44
  267. package/dist/translation/validate.d.ts +0 -14
  268. package/dist/translation/validate.js +0 -100
  269. package/dist/types/branch.d.ts +0 -14
  270. package/dist/types/branch.js +0 -1
  271. package/dist/types/data/json.d.ts +0 -6
  272. package/dist/types/data/json.js +0 -1
  273. package/dist/types/data.d.ts +0 -37
  274. package/dist/types/data.js +0 -1
  275. package/dist/types/files.d.ts +0 -8
  276. package/dist/types/files.js +0 -1
  277. package/dist/types/libraries.d.ts +0 -31
  278. package/dist/types/libraries.js +0 -72
  279. package/dist/types/parsing.d.ts +0 -3
  280. package/dist/types/parsing.js +0 -1
  281. package/dist/utils/addExplicitAnchorIds.d.ts +0 -24
  282. package/dist/utils/addExplicitAnchorIds.js +0 -416
  283. package/dist/utils/constants.d.ts +0 -5
  284. package/dist/utils/constants.js +0 -6
  285. package/dist/utils/credentials.d.ts +0 -12
  286. package/dist/utils/credentials.js +0 -120
  287. package/dist/utils/flattenJsonFiles.d.ts +0 -2
  288. package/dist/utils/flattenJsonFiles.js +0 -36
  289. package/dist/utils/gitDiff.d.ts +0 -8
  290. package/dist/utils/gitDiff.js +0 -34
  291. package/dist/utils/gt.d.ts +0 -2
  292. package/dist/utils/gt.js +0 -2
  293. package/dist/utils/hash.d.ts +0 -6
  294. package/dist/utils/hash.js +0 -11
  295. package/dist/utils/headers.d.ts +0 -1
  296. package/dist/utils/headers.js +0 -14
  297. package/dist/utils/localizeRelativeAssets.d.ts +0 -8
  298. package/dist/utils/localizeRelativeAssets.js +0 -166
  299. package/dist/utils/localizeStaticImports.d.ts +0 -15
  300. package/dist/utils/localizeStaticImports.js +0 -397
  301. package/dist/utils/localizeStaticUrls.d.ts +0 -19
  302. package/dist/utils/localizeStaticUrls.js +0 -450
  303. package/dist/utils/mintlifyTitleFallback.d.ts +0 -6
  304. package/dist/utils/mintlifyTitleFallback.js +0 -80
  305. package/dist/utils/parse/needsCJS.d.ts +0 -20
  306. package/dist/utils/parse/needsCJS.js +0 -72
  307. package/dist/utils/persistPostprocessHashes.d.ts +0 -12
  308. package/dist/utils/persistPostprocessHashes.js +0 -39
  309. package/dist/utils/processAnchorIds.d.ts +0 -6
  310. package/dist/utils/processAnchorIds.js +0 -56
  311. package/dist/utils/processOpenApi.d.ts +0 -8
  312. package/dist/utils/processOpenApi.js +0 -651
  313. package/dist/utils/sanitizeFileContent.d.ts +0 -6
  314. package/dist/utils/sanitizeFileContent.js +0 -29
  315. package/dist/utils/sharedStaticAssets.d.ts +0 -9
  316. package/dist/utils/sharedStaticAssets.js +0 -384
  317. package/dist/utils/validateMdx.d.ts +0 -10
  318. package/dist/utils/validateMdx.js +0 -25
  319. package/dist/utils/wrapPlainUrls.d.ts +0 -8
  320. package/dist/utils/wrapPlainUrls.js +0 -72
  321. package/dist/workflows/download.d.ts +0 -32
  322. package/dist/workflows/download.js +0 -131
  323. package/dist/workflows/enqueue.d.ts +0 -17
  324. package/dist/workflows/enqueue.js +0 -59
  325. package/dist/workflows/setupProject.d.ts +0 -13
  326. package/dist/workflows/setupProject.js +0 -48
  327. package/dist/workflows/stage.d.ts +0 -18
  328. package/dist/workflows/stage.js +0 -59
  329. package/dist/workflows/steps/BranchStep.d.ts +0 -13
  330. package/dist/workflows/steps/BranchStep.js +0 -161
  331. package/dist/workflows/steps/DownloadStep.d.ts +0 -19
  332. package/dist/workflows/steps/DownloadStep.js +0 -131
  333. package/dist/workflows/steps/EnqueueStep.d.ts +0 -15
  334. package/dist/workflows/steps/EnqueueStep.js +0 -33
  335. package/dist/workflows/steps/PollJobsStep.d.ts +0 -31
  336. package/dist/workflows/steps/PollJobsStep.js +0 -288
  337. package/dist/workflows/steps/SetupStep.d.ts +0 -16
  338. package/dist/workflows/steps/SetupStep.js +0 -72
  339. package/dist/workflows/steps/UploadSourcesStep.d.ts +0 -27
  340. package/dist/workflows/steps/UploadSourcesStep.js +0 -131
  341. package/dist/workflows/steps/UploadTranslationsStep.d.ts +0 -22
  342. package/dist/workflows/steps/UploadTranslationsStep.js +0 -71
  343. package/dist/workflows/steps/UserEditDiffsStep.d.ts +0 -11
  344. package/dist/workflows/steps/UserEditDiffsStep.js +0 -30
  345. package/dist/workflows/steps/WorkflowStep.d.ts +0 -4
  346. package/dist/workflows/steps/WorkflowStep.js +0 -2
  347. package/dist/workflows/upload.d.ts +0 -15
  348. package/dist/workflows/upload.js +0 -47
@@ -1,367 +0,0 @@
1
- import JSONPointer from 'jsonpointer';
2
- import { exitSync } from '../../console/logging.js';
3
- import { logger } from '../../console/logger.js';
4
- import { findMatchingItemArray, findMatchingItemObject, generateSourceObjectPointers, getIdentifyingLocaleProperty, getSourceObjectOptionsArray, validateJsonSchema, } from './utils.js';
5
- import { JSONPath } from 'jsonpath-plus';
6
- import { getLocaleProperties } from 'generaltranslation';
7
- import { replaceLocalePlaceholders } from '../utils.js';
8
- import { gt } from '../../utils/gt.js';
9
- export function mergeJson(originalContent, inputPath, options, targets, defaultLocale, localeOrder = []) {
10
- const jsonSchema = validateJsonSchema(options, inputPath);
11
- if (!jsonSchema) {
12
- return targets.map((target) => target.translatedContent);
13
- }
14
- let originalJson;
15
- try {
16
- originalJson = JSON.parse(originalContent);
17
- }
18
- catch {
19
- logger.error(`Invalid JSON file: ${inputPath}`);
20
- return exitSync(1);
21
- }
22
- const useCanonicalLocaleKeys = options?.experimentalCanonicalLocaleKeys ?? false;
23
- const canonicalDefaultLocale = useCanonicalLocaleKeys
24
- ? gt.resolveCanonicalLocale(defaultLocale)
25
- : defaultLocale;
26
- const canonicalLocaleOrder = useCanonicalLocaleKeys
27
- ? localeOrder.map((locale) => gt.resolveCanonicalLocale(locale))
28
- : localeOrder;
29
- // Handle include
30
- if (jsonSchema.include) {
31
- const output = [];
32
- for (const target of targets) {
33
- // Must clone the original JSON to avoid mutations
34
- const mergedJson = structuredClone(originalJson);
35
- const translatedJson = JSON.parse(target.translatedContent);
36
- for (const [jsonPointer, translatedValue] of Object.entries(translatedJson)) {
37
- try {
38
- const value = JSONPointer.get(mergedJson, jsonPointer);
39
- if (!value)
40
- continue;
41
- JSONPointer.set(mergedJson, jsonPointer, translatedValue);
42
- }
43
- catch {
44
- /* empty */
45
- }
46
- }
47
- output.push(JSON.stringify(mergedJson, null, 2));
48
- }
49
- return output;
50
- }
51
- if (!jsonSchema.composite) {
52
- logger.error('No composite property found in JSON schema');
53
- return exitSync(1);
54
- }
55
- // Handle composite
56
- // Create a deep copy of the original JSON to avoid mutations
57
- const mergedJson = structuredClone(originalJson);
58
- // Create mapping of sourceObjectPointer to SourceObjectOptions
59
- const sourceObjectPointers = generateSourceObjectPointers(jsonSchema.composite, originalJson);
60
- // Find the source object
61
- for (const [sourceObjectPointer, { sourceObjectValue, sourceObjectOptions },] of Object.entries(sourceObjectPointers)) {
62
- // Find the source item
63
- if (sourceObjectOptions.type === 'array') {
64
- // Validate type
65
- if (!Array.isArray(sourceObjectValue)) {
66
- logger.error(`Source object value is not an array at path: ${sourceObjectPointer}`);
67
- return exitSync(1);
68
- }
69
- // Get source item for default locale
70
- const matchingDefaultLocaleItems = findMatchingItemArray(canonicalDefaultLocale, sourceObjectOptions, sourceObjectPointer, sourceObjectValue);
71
- if (!Object.keys(matchingDefaultLocaleItems).length) {
72
- logger.warn(`Matching sourceItems not found at path: ${sourceObjectPointer}. Please check your JSON file includes the key field. Skipping this target`);
73
- continue;
74
- }
75
- const matchingDefaultLocaleItemKeys = new Set(Object.keys(matchingDefaultLocaleItems));
76
- // For each target:
77
- // 1. Get the target items
78
- // 2. Track all array indecies to remove (will be overwritten)
79
- // 3. Merge matchingDefaultLocaleItems and targetItems
80
- // 4. Validate that the mergedItems is not empty
81
- // For each target item:
82
- // 5. Validate that all the array indecies are still present in the source json
83
- // 6. Override the source item with the translated values
84
- // 7. Apply additional mutations to the sourceItem
85
- // 8. Track all items to add
86
- // 9. Check that items to add is >= items to remove
87
- // 10. Remove all items for the target locale (they can be identified by the key)
88
- const indiciesToRemove = new Set();
89
- const itemsToAdd = [];
90
- for (const target of targets) {
91
- const targetJson = JSON.parse(target.translatedContent);
92
- let targetItems = targetJson[sourceObjectPointer];
93
- // 1. Get the target items
94
- if (!targetItems) {
95
- // If no translation can be found, a transformation may need to happen still
96
- targetItems = {};
97
- }
98
- // 2. Track all array indecies to remove (will be overwritten)
99
- const targetItemsToRemove = findMatchingItemArray(useCanonicalLocaleKeys
100
- ? gt.resolveCanonicalLocale(target.targetLocale)
101
- : target.targetLocale, sourceObjectOptions, sourceObjectPointer, sourceObjectValue);
102
- Object.values(targetItemsToRemove).forEach(({ index }) => indiciesToRemove.add(index));
103
- // Remap mismatched positional keys to current source positions
104
- const sourceKeys = [...matchingDefaultLocaleItemKeys];
105
- const remappedTargetItems = {};
106
- for (const [key, value] of Object.entries(targetItems)) {
107
- if (matchingDefaultLocaleItemKeys.has(key)) {
108
- remappedTargetItems[key] = value;
109
- }
110
- else if (sourceKeys.length === 1 &&
111
- !(sourceKeys[0] in remappedTargetItems)) {
112
- remappedTargetItems[sourceKeys[0]] = value;
113
- }
114
- else {
115
- logger.warn(`Skipping translated item at ${key}: cannot map to source item at path ${sourceObjectPointer}`);
116
- }
117
- }
118
- // Merge matchingDefaultLocaleItems and remapped targetItems
119
- const mergedItems = {
120
- ...(sourceObjectOptions.transform ? matchingDefaultLocaleItems : {}),
121
- ...remappedTargetItems,
122
- };
123
- // 4. Validate that the mergedItems is not empty
124
- if (Object.keys(mergedItems).length === 0) {
125
- logger.warn(`Translated JSON for locale: ${target.targetLocale} does not have a valid sourceObjectPointer: ${sourceObjectPointer}. Skipping this target`);
126
- continue;
127
- }
128
- for (const [sourceItemPointer, targetItem] of Object.entries(mergedItems)) {
129
- // 5. Validate that all the array indecies are still present in the source json
130
- if (!matchingDefaultLocaleItemKeys.has(sourceItemPointer)) {
131
- logger.warn(`Skipping translated item at ${sourceItemPointer}: not present in source json at path ${sourceObjectPointer}`);
132
- continue;
133
- }
134
- // 6. Override the source item with the translated values
135
- const defaultLocaleSourceItem = matchingDefaultLocaleItems[sourceItemPointer].sourceItem;
136
- const defaultLocaleKeyPointer = matchingDefaultLocaleItems[sourceItemPointer].keyPointer;
137
- const mutatedSourceItem = structuredClone(defaultLocaleSourceItem);
138
- const { identifyingLocaleProperty: targetLocaleKeyProperty } = getSourceObjectOptionsArray(useCanonicalLocaleKeys
139
- ? gt.resolveCanonicalLocale(target.targetLocale)
140
- : target.targetLocale, sourceObjectPointer, sourceObjectOptions);
141
- JSONPointer.set(mutatedSourceItem, defaultLocaleKeyPointer, targetLocaleKeyProperty);
142
- for (const [translatedKeyJsonPointer, translatedValue,] of Object.entries(targetItem || {})) {
143
- const valueToSet = useCanonicalLocaleKeys &&
144
- defaultLocaleKeyPointer &&
145
- translatedKeyJsonPointer === defaultLocaleKeyPointer
146
- ? targetLocaleKeyProperty
147
- : translatedValue;
148
- try {
149
- const value = JSONPointer.get(mutatedSourceItem, translatedKeyJsonPointer);
150
- if (!value)
151
- continue;
152
- JSONPointer.set(mutatedSourceItem, translatedKeyJsonPointer, valueToSet);
153
- }
154
- catch {
155
- /* empty */
156
- }
157
- }
158
- // 7. Apply additional mutations to the sourceItem
159
- applyTransformations(mutatedSourceItem, sourceObjectOptions.transform, target.targetLocale, defaultLocale);
160
- itemsToAdd.push(mutatedSourceItem);
161
- }
162
- }
163
- // 8. Check that items to add is >= items to remove
164
- if (itemsToAdd.length < indiciesToRemove.size) {
165
- logger.warn(`Items to add (${itemsToAdd.length}) is less than items to remove (${indiciesToRemove.size}) at path: ${sourceObjectPointer}. Some translated items may have been skipped.`);
166
- }
167
- // 9. Remove all items for the target locale (they can be identified by the key)
168
- const filteredSourceObjectValue = sourceObjectValue.filter((_, index) => !indiciesToRemove.has(index));
169
- // 10. Add all items to the original JSON
170
- filteredSourceObjectValue.push(...itemsToAdd);
171
- JSONPointer.set(mergedJson, sourceObjectPointer, sortByLocaleOrder(filteredSourceObjectValue, sourceObjectOptions, canonicalLocaleOrder, sourceObjectPointer, canonicalDefaultLocale));
172
- }
173
- else {
174
- // Validate type
175
- if (typeof sourceObjectValue !== 'object' || sourceObjectValue === null) {
176
- logger.error(`Source object value is not an object at path: ${sourceObjectPointer}`);
177
- return exitSync(1);
178
- }
179
- // Validate localeProperty
180
- const matchingDefaultLocaleItem = findMatchingItemObject(canonicalDefaultLocale, sourceObjectPointer, sourceObjectOptions, sourceObjectValue);
181
- // Validate source item exists
182
- if (!matchingDefaultLocaleItem.sourceItem) {
183
- logger.error(`Source item not found at path: ${sourceObjectPointer}. You must specify a source item where its key matches the default locale`);
184
- return exitSync(1);
185
- }
186
- const { sourceItem: defaultLocaleSourceItem } = matchingDefaultLocaleItem;
187
- // For each target:
188
- // 1. Get the target items
189
- // 2. Find the source item for the target locale
190
- // 3. Merge the target items with the source item
191
- // 4. Validate that the mergedItems is not empty
192
- // 5. Override the source item with the translated values
193
- // 6. Apply additional mutations to the sourceItem
194
- // 7. Merge the source item with the original JSON (if the source item is not a new item)
195
- for (const target of targets) {
196
- const targetJson = JSON.parse(target.translatedContent);
197
- // 1. Get the target items
198
- let targetItems = targetJson[sourceObjectPointer];
199
- if (!targetItems) {
200
- targetItems = {};
201
- }
202
- // 2. Find the source item for the target locale
203
- const matchingTargetItem = findMatchingItemObject(useCanonicalLocaleKeys
204
- ? gt.resolveCanonicalLocale(target.targetLocale)
205
- : target.targetLocale, sourceObjectPointer, sourceObjectOptions, sourceObjectValue);
206
- // If the target locale has a matching source item, use it to mutate the source item
207
- // Otherwise, fallback to the default locale source item
208
- const mutateSourceItem = structuredClone(defaultLocaleSourceItem);
209
- const mutateSourceItemKey = matchingTargetItem.keyParentProperty;
210
- // 3. Merge the target items with the source item (if there are transformations to perform)
211
- const mergedItems = {
212
- ...(sourceObjectOptions.transform ? defaultLocaleSourceItem : {}),
213
- ...targetItems,
214
- };
215
- // 4. Validate that the mergedItems is not empty
216
- if (Object.keys(mergedItems).length === 0) {
217
- logger.warn(`Translated JSON for locale: ${target.targetLocale} does not have a valid sourceObjectPointer: ${sourceObjectPointer}. Skipping this target`);
218
- continue;
219
- }
220
- // 5. Override the source item with the translated values
221
- for (const [translatedKeyJsonPointer, translatedValue,] of Object.entries(mergedItems || {})) {
222
- try {
223
- const value = JSONPointer.get(mutateSourceItem, translatedKeyJsonPointer);
224
- if (!value)
225
- continue;
226
- JSONPointer.set(mutateSourceItem, translatedKeyJsonPointer, translatedValue);
227
- }
228
- catch {
229
- /* empty */
230
- }
231
- }
232
- // 6. Apply additional mutations to the sourceItem
233
- applyTransformations(mutateSourceItem, sourceObjectOptions.transform, target.targetLocale, defaultLocale);
234
- // 7. Merge the source item with the original JSON
235
- sourceObjectValue[mutateSourceItemKey] = mutateSourceItem;
236
- }
237
- JSONPointer.set(mergedJson, sourceObjectPointer, sourceObjectValue);
238
- }
239
- }
240
- return [JSON.stringify(mergedJson, null, 2)];
241
- }
242
- function sortByLocaleOrder(items, sourceObjectOptions, localeOrder, sourceObjectPointer, defaultLocale) {
243
- const sortMode = sourceObjectOptions.experimentalSort;
244
- if (!sortMode || !sourceObjectOptions.key) {
245
- return items;
246
- }
247
- const itemsWithLocale = items.map((item) => {
248
- let localeValue;
249
- try {
250
- const values = JSONPath({
251
- json: item,
252
- path: sourceObjectOptions.key,
253
- resultType: 'value',
254
- flatten: true,
255
- wrap: true,
256
- });
257
- const value = values?.[0];
258
- if (typeof value === 'string') {
259
- localeValue = value;
260
- }
261
- }
262
- catch {
263
- /* empty */
264
- }
265
- return { item, localeValue };
266
- });
267
- if (sortMode === 'locales') {
268
- if (!localeOrder.length) {
269
- return items;
270
- }
271
- const orderedLocaleList = [
272
- defaultLocale,
273
- ...localeOrder.filter((locale) => locale !== defaultLocale),
274
- ];
275
- const localeOrderValues = orderedLocaleList.map((locale) => getIdentifyingLocaleProperty(locale, sourceObjectPointer, sourceObjectOptions));
276
- const orderedItems = [];
277
- const remainingItems = [...itemsWithLocale];
278
- for (const localeValue of localeOrderValues) {
279
- for (let i = 0; i < remainingItems.length;) {
280
- const entry = remainingItems[i];
281
- if (entry.localeValue === localeValue) {
282
- orderedItems.push(entry.item);
283
- remainingItems.splice(i, 1);
284
- continue;
285
- }
286
- i += 1;
287
- }
288
- }
289
- remainingItems.forEach((entry) => orderedItems.push(entry.item));
290
- return orderedItems;
291
- }
292
- if (sortMode === 'localesAlphabetical') {
293
- const defaultLocaleValue = getIdentifyingLocaleProperty(defaultLocale, sourceObjectPointer, sourceObjectOptions);
294
- const defaultItems = [];
295
- const sortableItems = [];
296
- const remainingItems = [];
297
- for (const entry of itemsWithLocale) {
298
- if (entry.localeValue === defaultLocaleValue) {
299
- defaultItems.push(entry);
300
- continue;
301
- }
302
- if (entry.localeValue) {
303
- sortableItems.push(entry);
304
- continue;
305
- }
306
- remainingItems.push(entry);
307
- }
308
- sortableItems.sort((a, b) => {
309
- if (!a.localeValue || !b.localeValue) {
310
- return 0;
311
- }
312
- return a.localeValue.localeCompare(b.localeValue);
313
- });
314
- return [...defaultItems, ...sortableItems, ...remainingItems].map((entry) => entry.item);
315
- }
316
- return items;
317
- }
318
- /**
319
- * Apply transformations to the sourceItem in-place
320
- * @param sourceItem - The source item to apply transformations to
321
- * @param transform - The transformations to apply
322
- * @param targetLocale - The target locale
323
- * @param defaultLocale - The default locale
324
- */
325
- export function applyTransformations(sourceItem, transform, targetLocale, defaultLocale) {
326
- if (!transform)
327
- return;
328
- const targetLocaleProperties = getLocaleProperties(targetLocale);
329
- const defaultLocaleProperties = getLocaleProperties(defaultLocale);
330
- for (const [transformPath, transformOptions] of Object.entries(transform)) {
331
- if (!transformOptions.replace ||
332
- typeof transformOptions.replace !== 'string') {
333
- continue;
334
- }
335
- const results = JSONPath({
336
- json: sourceItem,
337
- path: transformPath,
338
- resultType: 'all',
339
- flatten: true,
340
- wrap: true,
341
- });
342
- if (!results || results.length === 0) {
343
- continue;
344
- }
345
- results.forEach((result) => {
346
- if (typeof result.value !== 'string') {
347
- return;
348
- }
349
- // Replace locale placeholders in the replace string
350
- let replaceString = transformOptions.replace;
351
- // Replace all locale property placeholders
352
- replaceString = replaceLocalePlaceholders(replaceString, targetLocaleProperties);
353
- if (transformOptions.match &&
354
- typeof transformOptions.match === 'string') {
355
- // Replace locale placeholders in the match string using defaultLocale properties
356
- let matchString = transformOptions.match;
357
- matchString = replaceLocalePlaceholders(matchString, defaultLocaleProperties);
358
- result.value = result.value.replace(new RegExp(matchString, 'g'), replaceString);
359
- }
360
- else {
361
- result.value = replaceString;
362
- }
363
- // Update the actual sourceItem using JSONPointer
364
- JSONPointer.set(sourceItem, result.pointer, result.value);
365
- });
366
- }
367
- }
@@ -1,2 +0,0 @@
1
- import { AdditionalOptions } from '../../types/index.js';
2
- export declare function parseJson(content: string, filePath: string, options: AdditionalOptions, defaultLocale: string): string;
@@ -1,109 +0,0 @@
1
- import { flattenJsonWithStringFilter } from './flattenJson.js';
2
- import { JSONPath } from 'jsonpath-plus';
3
- import { exitSync } from '../../console/logging.js';
4
- import { logger } from '../../console/logger.js';
5
- import { findMatchingItemArray, findMatchingItemObject, generateSourceObjectPointers, validateJsonSchema, } from './utils.js';
6
- // Parse a JSON file according to a JSON schema
7
- export function parseJson(content, filePath, options, defaultLocale) {
8
- const jsonSchema = validateJsonSchema(options, filePath);
9
- if (!jsonSchema) {
10
- return content;
11
- }
12
- let json;
13
- try {
14
- json = JSON.parse(content);
15
- }
16
- catch {
17
- logger.error(`Invalid JSON file: ${filePath}`);
18
- return exitSync(1);
19
- }
20
- // Handle include
21
- if (jsonSchema.include) {
22
- const flattenedJson = flattenJsonWithStringFilter(json, jsonSchema.include);
23
- return JSON.stringify(flattenedJson);
24
- }
25
- if (!jsonSchema.composite) {
26
- logger.error('No composite property found in JSON schema');
27
- return exitSync(1);
28
- }
29
- // Construct lvl 1
30
- // Create mapping of sourceObjectPointer to SourceObjectOptions
31
- const sourceObjectPointers = generateSourceObjectPointers(jsonSchema.composite, json);
32
- // Construct lvl 2
33
- const sourceObjectsToTranslate = {};
34
- for (const [sourceObjectPointer, { sourceObjectValue, sourceObjectOptions },] of Object.entries(sourceObjectPointers)) {
35
- // Skip if no includes
36
- if (!sourceObjectOptions.include.length) {
37
- continue;
38
- }
39
- // Find the default locale in each source item in each sourceObjectValue
40
- // Array: use key field
41
- if (sourceObjectOptions.type === 'array') {
42
- // Validate type
43
- if (!Array.isArray(sourceObjectValue)) {
44
- logger.error(`Source object value is not an array at path: ${sourceObjectPointer}`);
45
- return exitSync(1);
46
- }
47
- // Find matching source items
48
- const matchingItems = findMatchingItemArray(defaultLocale, sourceObjectOptions, sourceObjectPointer, sourceObjectValue);
49
- if (!Object.keys(matchingItems).length) {
50
- logger.error(`Matching sourceItem not found at path: ${sourceObjectPointer} for locale: ${defaultLocale}. Please check your JSON schema`);
51
- return exitSync(1);
52
- }
53
- // Construct lvl 3
54
- const sourceItemsToTranslate = {};
55
- for (const [arrayPointer, matchingItem] of Object.entries(matchingItems)) {
56
- const { sourceItem, keyPointer } = matchingItem;
57
- // Get the fields to translate from the includes
58
- const matchingItemsToTranslate = [];
59
- for (const include of sourceObjectOptions.include) {
60
- try {
61
- const matchingItems = JSONPath({
62
- json: sourceItem,
63
- path: include,
64
- resultType: 'all',
65
- flatten: true,
66
- wrap: true,
67
- });
68
- if (matchingItems) {
69
- matchingItemsToTranslate.push(...matchingItems);
70
- }
71
- }
72
- catch {
73
- /* empty */
74
- }
75
- }
76
- // Filter out the key pointer
77
- sourceItemsToTranslate[arrayPointer] = Object.fromEntries(matchingItemsToTranslate
78
- .filter((item) => item.pointer !== keyPointer)
79
- .map((item) => [
80
- item.pointer,
81
- item.value,
82
- ]));
83
- }
84
- // Add the items to translate to the result
85
- sourceObjectsToTranslate[sourceObjectPointer] = sourceItemsToTranslate;
86
- }
87
- else {
88
- // Object: use the key in this object with the matching locale property
89
- // Validate type
90
- if (typeof sourceObjectValue !== 'object' || sourceObjectValue === null) {
91
- logger.error(`Source object value is not an object at path: ${sourceObjectPointer}`);
92
- return exitSync(1);
93
- }
94
- // Validate localeProperty
95
- const matchingItem = findMatchingItemObject(defaultLocale, sourceObjectPointer, sourceObjectOptions, sourceObjectValue);
96
- // Validate source item exists
97
- if (!matchingItem.sourceItem) {
98
- logger.error(`Source item not found at path: ${sourceObjectPointer}. You must specify a source item where its key matches the default locale`);
99
- return exitSync(1);
100
- }
101
- const { sourceItem } = matchingItem;
102
- // Get the fields to translate from the includes
103
- const itemsToTranslate = flattenJsonWithStringFilter(sourceItem, sourceObjectOptions.include);
104
- // Add the items to translate to the result
105
- sourceObjectsToTranslate[sourceObjectPointer] = itemsToTranslate;
106
- }
107
- }
108
- return JSON.stringify(sourceObjectsToTranslate);
109
- }
@@ -1,47 +0,0 @@
1
- import { AdditionalOptions, JsonSchema, SourceObjectOptions } from '../../types/index.js';
2
- export declare function findMatchingItemArray(locale: string, sourceObjectOptions: SourceObjectOptions, sourceObjectPointer: string, sourceObjectValue: any): Record<string, {
3
- sourceItem: any;
4
- keyParentProperty: string;
5
- keyPointer: string;
6
- index: number;
7
- }>;
8
- export declare function findMatchingItemObject(locale: string, sourceObjectPointer: string, sourceObjectOptions: SourceObjectOptions, sourceObjectValue: any): {
9
- sourceItem: any | undefined;
10
- keyParentProperty: string;
11
- };
12
- /**
13
- * Get the identifying locale property for an object
14
- * @param locale - The locale to get the identifying locale property for
15
- * @param sourceObjectPointer - The path to the source object
16
- * @param sourceObjectOptions - The source object options
17
- * @returns The identifying locale property
18
- */
19
- export declare function getIdentifyingLocaleProperty(locale: string, sourceObjectPointer: string, sourceObjectOptions: SourceObjectOptions): string;
20
- /**
21
- * Get the identifying locale property and the json path to the key for an array
22
- * @param locale - The locale to get the identifying locale property for
23
- * @param sourceObjectPointer - The path to the source object
24
- * @param sourceObjectOptions - The source object options
25
- * @returns The identifying locale property and the json path to the key
26
- */
27
- export declare function getSourceObjectOptionsArray(locale: string, sourceObjectPointer: string, sourceObjectOptions: SourceObjectOptions): {
28
- identifyingLocaleProperty: string;
29
- localeKeyJsonPath: string;
30
- };
31
- export declare function getSourceObjectOptionsObject(defaultLocale: string, sourceObjectPointer: string, sourceObjectOptions: SourceObjectOptions): {
32
- identifyingLocaleProperty: string;
33
- };
34
- /**
35
- * Generate a mapping of sourceObjectPointer to SourceObjectOptions
36
- * where the sourceObjectPointer is a jsonpointer to the array or object containing
37
- * @param jsonSchema - The json schema to generate the mapping from
38
- * @param originalJson - The original json to generate the mapping from
39
- * @returns A mapping of sourceObjectPointer to SourceObjectOptions
40
- */
41
- export declare function generateSourceObjectPointers(jsonSchema: {
42
- [sourceObjectPath: string]: SourceObjectOptions;
43
- }, originalJson: any): Record<string, {
44
- sourceObjectValue: any;
45
- sourceObjectOptions: SourceObjectOptions;
46
- }>;
47
- export declare function validateJsonSchema(options: AdditionalOptions, filePath: string): JsonSchema | null;
@@ -1,150 +0,0 @@
1
- import { getLocaleProperties } from 'generaltranslation';
2
- import { exitSync } from '../../console/logging.js';
3
- import { logger } from '../../console/logger.js';
4
- import { JSONPath } from 'jsonpath-plus';
5
- import { flattenJson } from './flattenJson.js';
6
- import path from 'node:path';
7
- import micromatch from 'micromatch';
8
- const { isMatch } = micromatch;
9
- // Find the matching source item in an array
10
- // where the key matches the identifying locale property
11
- // If no matching item is found, exit with an error
12
- export function findMatchingItemArray(locale, sourceObjectOptions, sourceObjectPointer, sourceObjectValue) {
13
- const { identifyingLocaleProperty, localeKeyJsonPath } = getSourceObjectOptionsArray(locale, sourceObjectPointer, sourceObjectOptions);
14
- // Use the json pointer key to locate the source item
15
- const matchingItems = {};
16
- for (const [index, item] of sourceObjectValue.entries()) {
17
- // Get the key candidates
18
- const keyCandidates = JSONPath({
19
- json: item,
20
- path: localeKeyJsonPath,
21
- resultType: 'all',
22
- flatten: true,
23
- wrap: true,
24
- });
25
- if (!keyCandidates) {
26
- logger.error(`Source item at path: ${sourceObjectPointer} does not have a key value at path: ${localeKeyJsonPath}`);
27
- return exitSync(1);
28
- }
29
- else if (keyCandidates.length === 0) {
30
- // If no key candidates, skip the item
31
- continue;
32
- }
33
- else if (keyCandidates.length > 1) {
34
- // If multiple key candidates, exit with an error
35
- logger.error(`Source item at path: ${sourceObjectPointer} has multiple matching keys with path: ${localeKeyJsonPath}`);
36
- return exitSync(1);
37
- }
38
- else if (identifyingLocaleProperty !== keyCandidates[0].value) {
39
- // Validate the key is the identifying locale property
40
- continue;
41
- }
42
- // Map the index to the source item
43
- matchingItems[`/${index}`] = {
44
- sourceItem: item,
45
- keyParentProperty: keyCandidates[0].parentProperty,
46
- keyPointer: keyCandidates[0].pointer,
47
- index,
48
- };
49
- }
50
- return matchingItems;
51
- }
52
- export function findMatchingItemObject(locale, sourceObjectPointer, sourceObjectOptions, sourceObjectValue) {
53
- const { identifyingLocaleProperty } = getSourceObjectOptionsObject(locale, sourceObjectPointer, sourceObjectOptions);
54
- // Locate the source item
55
- if (sourceObjectValue[identifyingLocaleProperty]) {
56
- return {
57
- sourceItem: sourceObjectValue[identifyingLocaleProperty],
58
- keyParentProperty: identifyingLocaleProperty,
59
- };
60
- }
61
- return {
62
- sourceItem: undefined,
63
- keyParentProperty: identifyingLocaleProperty,
64
- };
65
- }
66
- /**
67
- * Get the identifying locale property for an object
68
- * @param locale - The locale to get the identifying locale property for
69
- * @param sourceObjectPointer - The path to the source object
70
- * @param sourceObjectOptions - The source object options
71
- * @returns The identifying locale property
72
- */
73
- export function getIdentifyingLocaleProperty(locale, sourceObjectPointer, sourceObjectOptions) {
74
- // Validate localeProperty
75
- const localeProperty = sourceObjectOptions.localeProperty || 'code';
76
- const identifyingLocaleProperty = getLocaleProperties(locale)[localeProperty];
77
- if (!identifyingLocaleProperty) {
78
- logger.error(`Source object options localeProperty is not a valid locale property at path: ${sourceObjectPointer}`);
79
- return exitSync(1);
80
- }
81
- return identifyingLocaleProperty;
82
- }
83
- /**
84
- * Get the identifying locale property and the json path to the key for an array
85
- * @param locale - The locale to get the identifying locale property for
86
- * @param sourceObjectPointer - The path to the source object
87
- * @param sourceObjectOptions - The source object options
88
- * @returns The identifying locale property and the json path to the key
89
- */
90
- export function getSourceObjectOptionsArray(locale, sourceObjectPointer, sourceObjectOptions) {
91
- const identifyingLocaleProperty = getIdentifyingLocaleProperty(locale, sourceObjectPointer, sourceObjectOptions);
92
- const localeKeyJsonPath = sourceObjectOptions.key;
93
- if (!localeKeyJsonPath) {
94
- logger.error(`Source object options key is required for array at path: ${sourceObjectPointer}`);
95
- return exitSync(1);
96
- }
97
- return { identifyingLocaleProperty, localeKeyJsonPath };
98
- }
99
- export function getSourceObjectOptionsObject(defaultLocale, sourceObjectPointer, sourceObjectOptions) {
100
- const identifyingLocaleProperty = getIdentifyingLocaleProperty(defaultLocale, sourceObjectPointer, sourceObjectOptions);
101
- const jsonPathKey = sourceObjectOptions.key;
102
- if (jsonPathKey) {
103
- logger.error(`Source object options key is not allowed for object at path: ${sourceObjectPointer}`);
104
- return exitSync(1);
105
- }
106
- return { identifyingLocaleProperty };
107
- }
108
- /**
109
- * Generate a mapping of sourceObjectPointer to SourceObjectOptions
110
- * where the sourceObjectPointer is a jsonpointer to the array or object containing
111
- * @param jsonSchema - The json schema to generate the mapping from
112
- * @param originalJson - The original json to generate the mapping from
113
- * @returns A mapping of sourceObjectPointer to SourceObjectOptions
114
- */
115
- export function generateSourceObjectPointers(jsonSchema, originalJson) {
116
- const sourceObjectPointers = Object.entries(jsonSchema).reduce((acc, [sourceObjectPath, sourceObjectOptions]) => {
117
- const sourceObjects = flattenJson(originalJson, [sourceObjectPath]);
118
- Object.entries(sourceObjects).forEach(([pointer, value]) => {
119
- acc[pointer] = {
120
- sourceObjectValue: value,
121
- sourceObjectOptions,
122
- };
123
- });
124
- return acc;
125
- }, {});
126
- return sourceObjectPointers;
127
- }
128
- export function validateJsonSchema(options, filePath) {
129
- if (!options.jsonSchema) {
130
- return null;
131
- }
132
- const fileGlobs = Object.keys(options.jsonSchema);
133
- const matchingGlob = fileGlobs.find((fileGlob) => isMatch(path.relative(process.cwd(), filePath), fileGlob));
134
- if (!matchingGlob || !options.jsonSchema[matchingGlob]) {
135
- return null;
136
- }
137
- // Validate includes or composite
138
- const jsonSchema = options.jsonSchema[matchingGlob];
139
- if (jsonSchema.include && jsonSchema.composite) {
140
- logger.error('include and composite cannot be used together in the same JSON schema');
141
- return exitSync(1);
142
- return null;
143
- }
144
- if (!jsonSchema.include && !jsonSchema.composite) {
145
- logger.error('No include or composite property found in JSON schema');
146
- return exitSync(1);
147
- return null;
148
- }
149
- return jsonSchema;
150
- }