@intlayer/cli 8.4.2 → 8.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/auth/login.cjs +2 -2
- package/dist/cjs/auth/login.cjs.map +1 -1
- package/dist/cjs/extract.cjs +1 -1
- package/dist/cjs/extract.cjs.map +1 -1
- package/dist/cjs/fill/fill.cjs +1 -1
- package/dist/cjs/fill/fill.cjs.map +1 -1
- package/dist/cjs/fill/listTranslationsTasks.cjs +1 -1
- package/dist/cjs/fill/listTranslationsTasks.cjs.map +1 -1
- package/dist/cjs/fill/translateDictionary.cjs +1 -1
- package/dist/cjs/fill/translateDictionary.cjs.map +1 -1
- package/dist/cjs/pull.cjs +1 -1
- package/dist/cjs/pull.cjs.map +1 -1
- package/dist/cjs/push/pullLog.cjs +3 -3
- package/dist/cjs/push/pullLog.cjs.map +1 -1
- package/dist/cjs/push/push.cjs +1 -1
- package/dist/cjs/push/push.cjs.map +1 -1
- package/dist/cjs/pushLog.cjs +3 -3
- package/dist/cjs/pushLog.cjs.map +1 -1
- package/dist/cjs/reviewDoc/reviewDoc.cjs +1 -1
- package/dist/cjs/reviewDoc/reviewDoc.cjs.map +1 -1
- package/dist/cjs/reviewDoc/reviewDocBlockAware.cjs +1 -1
- package/dist/cjs/reviewDoc/reviewDocBlockAware.cjs.map +1 -1
- package/dist/cjs/test/test.cjs +1 -1
- package/dist/cjs/test/test.cjs.map +1 -1
- package/dist/cjs/translateDoc/translateDoc.cjs +1 -1
- package/dist/cjs/translateDoc/translateDoc.cjs.map +1 -1
- package/dist/cjs/translateDoc/translateFile.cjs +2 -2
- package/dist/cjs/translateDoc/translateFile.cjs.map +1 -1
- package/dist/cjs/utils/checkAccess.cjs +1 -1
- package/dist/cjs/utils/checkAccess.cjs.map +1 -1
- package/dist/cjs/utils/setupAI.cjs +1 -1
- package/dist/cjs/utils/setupAI.cjs.map +1 -1
- package/dist/esm/auth/login.mjs +1 -1
- package/dist/esm/auth/login.mjs.map +1 -1
- package/dist/esm/extract.mjs +1 -1
- package/dist/esm/extract.mjs.map +1 -1
- package/dist/esm/fill/fill.mjs +1 -1
- package/dist/esm/fill/fill.mjs.map +1 -1
- package/dist/esm/fill/listTranslationsTasks.mjs +1 -1
- package/dist/esm/fill/listTranslationsTasks.mjs.map +1 -1
- package/dist/esm/fill/translateDictionary.mjs +1 -1
- package/dist/esm/fill/translateDictionary.mjs.map +1 -1
- package/dist/esm/pull.mjs +1 -1
- package/dist/esm/pull.mjs.map +1 -1
- package/dist/esm/push/pullLog.mjs +1 -1
- package/dist/esm/push/pullLog.mjs.map +1 -1
- package/dist/esm/push/push.mjs +1 -1
- package/dist/esm/push/push.mjs.map +1 -1
- package/dist/esm/pushLog.mjs +1 -1
- package/dist/esm/pushLog.mjs.map +1 -1
- package/dist/esm/reviewDoc/reviewDoc.mjs +1 -1
- package/dist/esm/reviewDoc/reviewDoc.mjs.map +1 -1
- package/dist/esm/reviewDoc/reviewDocBlockAware.mjs +1 -1
- package/dist/esm/reviewDoc/reviewDocBlockAware.mjs.map +1 -1
- package/dist/esm/test/test.mjs +1 -1
- package/dist/esm/test/test.mjs.map +1 -1
- package/dist/esm/translateDoc/translateDoc.mjs +1 -1
- package/dist/esm/translateDoc/translateDoc.mjs.map +1 -1
- package/dist/esm/translateDoc/translateFile.mjs +1 -1
- package/dist/esm/translateDoc/translateFile.mjs.map +1 -1
- package/dist/esm/utils/checkAccess.mjs +1 -1
- package/dist/esm/utils/checkAccess.mjs.map +1 -1
- package/dist/esm/utils/setupAI.mjs +1 -1
- package/dist/esm/utils/setupAI.mjs.map +1 -1
- package/dist/types/auth/login.d.ts.map +1 -1
- package/dist/types/extract.d.ts.map +1 -1
- package/dist/types/pull.d.ts.map +1 -1
- package/dist/types/push/pullLog.d.ts.map +1 -1
- package/dist/types/push/push.d.ts.map +1 -1
- package/dist/types/setupAI-Bosjx7ah.d.ts.map +1 -1
- package/dist/types/utils/checkAccess.d.ts.map +1 -1
- package/package.json +12 -12
|
@@ -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
|
|
1
|
+
{"version":3,"file":"pullLog.cjs","names":["spinnerFrames","ANSIColors"],"sources":["../../../src/push/pullLog.ts"],"sourcesContent":["import type { DictionaryStatus } from '@intlayer/chokidar/build';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { 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":"0OAWA,IAAa,EAAb,KAAwB,CACtB,SAAiC,EAAE,CACnC,aAA8C,KAC9C,aAAuB,EACvB,cAAwB,EACxB,cAAiCA,EAAAA,cACjC,WAAqB,GACrB,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CACrC,GAAI,IAAiB,KAAK,kBACxB,OAEF,KAAK,kBAAoB,EAErB,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"}
|
package/dist/cjs/push/push.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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`),
|
|
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/colors`);s=e.t(s);let c=require(`@intlayer/config/logger`),l=require(`@intlayer/config/node`),u=require(`@intlayer/unmerged-dictionaries-entry`),d=require(`@intlayer/api`),f=require(`node:fs/promises`);f=e.t(f);const p={pushed:{icon:`✔`,color:s.GREEN},modified:{icon:`✔`,color:s.GREEN},error:{icon:`✖`,color:s.RED},default:{icon:`⏲`,color:s.BLUE}},m=e=>p[e]??p.default,h=async e=>{let f=(0,l.getConfiguration)(e?.configOptions);(0,a.logConfigDetails)(e?.configOptions);let p=(0,c.getAppLogger)(f);e?.build===!0?await(0,i.prepareIntlayer)(f,{forceRun:!0}):e?.build===void 0&&await(0,i.prepareIntlayer)(f);try{if(!await t.checkCMSAuth(f))return;let l=(0,d.getIntlayerAPIProxy)(void 0,f),h=(0,u.getUnmergedDictionaries)(f),_=Object.values(h).flat(),v=Array.from(new Set(_.map(e=>e.location).filter(e=>e&&![`remote`,`local`,`hybrid`].includes(e)))),y=[];if(v.length>0){let{multiselect:e,confirm:t,isCancel:n}=await import(`@clack/prompts`);if(v.length===1){let e=await t({message:`Do you want to push dictionaries with custom location ${(0,c.colorize)(v[0],s.BLUE,s.RESET)}?`,initialValue:!1});if(n(e))return;e&&(y=[v[0]])}else{let t=await e({message:`Select custom locations to push:`,options:v.map(e=>({value:e,label:e})),required:!1});if(n(t))return;y=t}}let b=_.filter(e=>{let t=e.location??f.dictionary?.location??`local`;return t===`remote`||t===`hybrid`||y.includes(t)});if(b.length===0){p(`No dictionaries found to push. Only dictionaries with location ${(0,c.colorize)(`remote`,s.BLUE,s.RESET)}, ${(0,c.colorize)(`hybrid`,s.BLUE,s.RESET)} or selected custom locations are pushed.`,{level:`warn`}),p(`You can set the location in your dictionary file (e.g. ${(0,c.colorize)(`{ key: 'my-key', location: 'hybrid', ... }`,s.BLUE,s.RESET)} or globally in your intlayer.config.ts file (e.g. ${(0,c.colorize)(`{ dictionary: { location: 'hybrid' } }`,s.BLUE,s.RESET)}).`,{level:`info`});return}let x=Object.keys(h);if(e?.dictionaries){let t=e.dictionaries.filter(e=>!x.includes(e));t.length>0&&p(`The following dictionaries do not exist: ${t.join(`, `)} and have been ignored.`,{level:`error`}),b=b.filter(t=>e.dictionaries?.includes(t.key))}if(e?.gitOptions){let t=await(0,a.listGitFiles)(e.gitOptions);b=b.filter(e=>t.includes((0,r.join)(f.system.baseDir,e.filePath??``)))}if(b.length===0){p(`No local dictionaries found`,{level:`error`});return}p(`Pushing dictionaries:`);let S=b.map(e=>({dictionary:e,status:`pending`})),C=new n.PushLogger;C.update(S.map(e=>({dictionaryKey:e.dictionary.key,status:`pending`})));let w=[];await(0,o.parallelize)(S,async e=>{e.status=`pushing`,C.update([{dictionaryKey:e.dictionary.key,status:`pushing`}]);try{let t=await l.dictionary.pushDictionaries([e.dictionary]),n=t.data?.updatedDictionaries??[],r=t.data?.newDictionaries??[],a=[...n,...r];for(let e of a){let t=h[e.key]?.find(t=>t.localId===e.localId);t&&await(0,i.writeContentDeclaration)({...t,id:e.id},f)}n.some(t=>t.key===e.dictionary.key)?(e.status=`modified`,w.push(e.dictionary),C.update([{dictionaryKey:e.dictionary.key,status:`modified`}])):r.some(t=>t.key===e.dictionary.key)?(e.status=`pushed`,w.push(e.dictionary),C.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}`,C.update([{dictionaryKey:e.dictionary.key,status:`error`}])}},5),C.finish();for(let e of S){let{icon:t,color:n}=m(e.status);p(` - ${(0,c.colorizeKey)(e.dictionary.key)} ${s.GREY}[${n}${t} ${e.status}${s.GREY}]${s.RESET}`)}for(let e of S)e.errorMessage&&p(e.errorMessage,{level:`error`});let T=e?.deleteLocaleDictionary,E=e?.keepLocaleDictionary;if(T&&E)throw Error(`Cannot specify both --deleteLocaleDictionary and --keepLocaleDictionary options.`);if(T)await g(w,e);else if(!E){let t=w.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,c.colorize)(`(Dictionaries:`,s.GREY,s.RESET)} ${(0,c.colorizeKey)(n)}${(0,c.colorize)(`)`,s.GREY,s.RESET)}`,initialValue:!1});if(i(a))return;a&&await g(t,e)}}}catch(e){p(e,{level:`error`})}},g=async(e,t)=>{let n=(0,c.getAppLogger)((0,l.getConfiguration)(t?.configOptions)),r=new Set;for(let t of e){let{filePath:e}=t;if(!e){n(`Dictionary ${(0,c.colorizeKey)(t.key)} does not have a file path`,{level:`error`});continue}r.add(e)}for(let e of r)try{let t=await f.lstat(e);t.isFile()?(await f.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=h;
|
|
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":"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,CA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EAAA,EAAA,kBAD0B,GAAS,cAAc,CACjB,CAGhC,EAA4B,IAAI,IAEtC,IAAK,IAAM,KAAc,EAAsB,CAC7C,GAAM,CAAE,YAAa,EAErB,GAAI,CAAC,EAAU,CACb,EACE,eAAA,EAAA,EAAA,aAA0B,EAAW,IAAI,CAAC,4BAC1C,CACE,MAAO,QACR,CACF,CACD,SAGF,EAAa,IAAI,EAAS,CAG5B,IAAK,IAAM,KAAY,EACrB,GAAI,CACF,IAAM,EAAQ,MAAMG,EAAW,MAAM,EAAS,CAE1C,EAAM,QAAQ,EAChB,MAAMA,EAAW,OAAO,EAAS,CACjC,EAAU,iBAAA,EAAA,EAAA,YAA2B,EAAS,GAAI,EAAE,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 * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, colorizeKey, getAppLogger } 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":"wiBAyCA,MAAM,EAAuB,CAC3B,OAAQ,CAAE,KAAM,IAAK,MAAOA,EAAW,MAAO,CAC9C,SAAU,CAAE,KAAM,IAAK,MAAOA,EAAW,MAAO,CAChD,MAAO,CAAE,KAAM,IAAK,MAAOA,EAAW,IAAK,CAC3C,QAAS,CAAE,KAAM,IAAK,MAAOA,EAAW,KAAM,CAC/C,CAEK,EAAmB,GAErB,EAAqB,IACrB,EAAqB,QAOZ,EAAO,KAAO,IAAyC,CAClE,IAAM,GAAA,EAAA,EAAA,kBA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AI,CACF,IAAM,EAAQ,MAAMG,EAAW,MAAM,EAAS,CAE1C,EAAM,QAAQ,EAChB,MAAMA,EAAW,OAAO,EAAS,CACjC,EAAU,iBAAA,EAAA,EAAA,YAA2B,EAAS,GAAI,EAAE,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"}
|
package/dist/cjs/pushLog.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`})
|
|
2
|
-
`);if(
|
|
3
|
-
`)}this.renderedLines=
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./chunk-Bmb41Sf3.cjs`);let t=require(`@intlayer/config/colors`);t=e.t(t);let n=require(`@intlayer/config/logger`);var r=class{statuses=[];spinnerTimer=null;spinnerIndex=0;renderedLines=0;spinnerFrames=n.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:e,done:r,pushed:i,modified:a,errors:o}=this.computeProgress(),s=this.spinnerFrames[this.spinnerIndex],c=[],l=r===e,u=`dictionaries: ${(0,n.colorizeNumber)(r)}/${(0,n.colorizeNumber)(e)}`,d=[];i>0&&d.push(`new: ${(0,n.colorizeNumber)(i)}`),a>0&&d.push(`modified: ${(0,n.colorizeNumber)(a)}`),o>0&&d.push((0,n.colorize)(`errors: ${(0,n.colorizeNumber)(o)}`,t.RED));let f=d.length>0?` (${d.join(`, `)})`:``;l?c.push(`${(0,n.colorize)(`✔`,t.GREEN)} pushed ${u}${f}`):c.push(`${(0,n.colorize)(s,t.BLUE)} pushing ${u}${f}`);let p=c.join(`
|
|
2
|
+
`);if(p===this.lastRenderedState)return;this.lastRenderedState=p,this.renderedLines>0&&process.stdout.write(`\x1b[${this.renderedLines}F`);let m=Math.max(this.renderedLines,c.length);for(let e=0;e<m;e++){process.stdout.write(`\x1B[2K`);let t=c[e];t!==void 0&&process.stdout.write(t),process.stdout.write(`
|
|
3
|
+
`)}this.renderedLines=c.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=r;
|
|
4
4
|
//# sourceMappingURL=pushLog.cjs.map
|
package/dist/cjs/pushLog.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pushLog.cjs","names":["spinnerFrames","ANSIColors"],"sources":["../../src/pushLog.ts"],"sourcesContent":["import {\n
|
|
1
|
+
{"version":3,"file":"pushLog.cjs","names":["spinnerFrames","ANSIColors"],"sources":["../../src/pushLog.ts"],"sourcesContent":["import * as ANSIColors from '@intlayer/config/colors';\nimport {\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":"sMAaA,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,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AAE,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(`../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`),
|
|
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/colors`);l=e.t(l);let u=require(`@intlayer/config/logger`),d=require(`@intlayer/config/node`),f=require(`fast-glob`);f=e.t(f);const p=async({docPattern:e,locales:p,excludedGlobPattern:m,baseLocale:h,aiOptions:g,nbSimultaneousFileProcessed:_,configOptions:v,customInstructions:y,skipIfModifiedBefore:b,skipIfModifiedAfter:x,skipIfExists:S,gitOptions:C})=>{let w=(0,d.getConfiguration)(v);(0,s.logConfigDetails)(v);let T=(0,u.getAppLogger)(w),E=await t.setupAI(w,g);if(!E?.hasAIAccess)return;let{aiClient:D,aiConfig:O}=E;_&&_>10&&(T(`Warning: nbSimultaneousFileProcessed is set to ${_}, which is greater than 10. Setting it to 10.`),_=10);let k=await(0,f.default)(e,{ignore:m});if(C){let e=await(0,s.listGitFiles)(C);e&&(k=k.filter(t=>e.some(e=>(0,o.join)(process.cwd(),t)===e)))}T(`Base locale is ${(0,c.formatLocale)(h)}`),T(`Reviewing ${(0,u.colorizeNumber)(p.length)} locales: [ ${(0,c.formatLocale)(p)} ]`),T(`Reviewing ${(0,u.colorizeNumber)(k.length)} files:`),T(k.map(e=>` - ${(0,c.formatPath)(e)}\n`)),await(0,c.parallelize)(k.flatMap(e=>p.map(t=>async()=>{T(`Reviewing file: ${(0,c.formatPath)(e)} to ${(0,c.formatLocale)(t)}`);let d=(0,o.join)(w.system.baseDir,e),f=r.getOutputFilePath(d,t,h);if(S&&(0,a.existsSync)(f)){let e=(0,o.relative)(w.system.baseDir,f);T(`${(0,u.colorize)(`⊘`,l.YELLOW)} File ${(0,c.formatPath)(e)} already exists, skipping.`);return}if((0,a.existsSync)(f)){let e=n.checkFileModifiedRange(f,{skipIfModifiedBefore:b,skipIfModifiedAfter:x});if(e.isSkipped){T(e.message);return}}else (b||x)&&T(`${(0,u.colorize)(`!`,l.YELLOW)} File ${(0,c.formatPath)(f)} does not exist, skipping modification date check.`);let p;if(C){let e=await(0,s.listGitLines)(d,C);T(`Git changed lines: ${e.join(`, `)}`),p=e}await i.reviewFileBlockAware(d,f,t,h,g,v,y,p,D,O)})),e=>e(),_??3)};exports.reviewDoc=p;
|
|
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
|
|
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 * as ANSIColors from '@intlayer/config/colors';\nimport {\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":"siBAkDA,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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D,CACH,CAIE,GAAS,GAAM,CAChB,GAA+B,EAChC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`})
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../chunk-Bmb41Sf3.cjs`),t=require(`../_utils_asset-ghp_Cjwk.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/colors`);u=e.t(u);let d=require(`@intlayer/config/logger`),f=require(`@intlayer/config/node`),p=require(`@intlayer/config/utils`),m=require(`node:fs/promises`),h=require(`@intlayer/core/localization`),g=require(`@intlayer/types/locales`);const _=async(e,_,v,y,b,x,S,C,w,T)=>{let E=(0,f.getConfiguration)(x),D=(0,d.getAppLogger)(E),O=await(0,m.readFile)(e,`utf-8`),k=await(0,m.readFile)(_,`utf-8`).catch(()=>``),A=t.t(`./prompts/REVIEW_PROMPT.md`,`utf-8`).replaceAll(`{{localeName}}`,`${(0,l.formatLocale)(v,!1)}`).replaceAll(`{{baseLocaleName}}`,`${(0,l.formatLocale)(y,!1)}`).replace(`{{applicationContext}}`,b?.applicationContext??`-`).replace(`{{customInstructions}}`,S??`-`),j=[(0,d.colon)(`${u.GREY_DARK}[${(0,l.formatPath)(e)}${u.GREY_DARK}] `,{colSize:40}),`→ ${u.RESET}`].join(``),M=[(0,d.colon)(`${u.GREY_DARK}[${(0,l.formatPath)(e)}${u.GREY_DARK}][${(0,l.formatLocale)(v)}${u.GREY_DARK}] `,{colSize:40}),`→ ${u.RESET}`].join(``),{englishBlocks:N,frenchBlocks:P,plan:F,segmentsToReview:I}=i.buildAlignmentPlan({englishText:O,frenchText:k,changedLines:C});if(D(`${j}Block-aware alignment complete. Total blocks: EN=${(0,d.colorizeNumber)(N.length)}, FR=${(0,d.colorizeNumber)(P.length)}`),D(`${j}Actions: reuse=${(0,d.colorizeNumber)(F.actions.filter(e=>e.kind===`reuse`).length)}, review=${(0,d.colorizeNumber)(F.actions.filter(e=>e.kind===`review`).length)}, new=${(0,d.colorizeNumber)(F.actions.filter(e=>e.kind===`insert_new`).length)}, delete=${(0,d.colorizeNumber)(F.actions.filter(e=>e.kind===`delete`).length)}`),I.length===0){D(`${j}No segments need review, reusing existing translation`),(0,s.mkdirSync)((0,c.dirname)(_),{recursive:!0}),(0,s.writeFileSync)(_,r.mergeReviewedSegments(F,P,new Map)),D(`${(0,d.colorize)(`✔`,u.GREEN)} File ${(0,l.formatPath)(_)} updated successfully (no changes needed).`);return}D(`${j}Segments to review: ${(0,d.colorizeNumber)(I.length)}`);let L=new Map;for(let e of I){let t=I.indexOf(e)+1,r=e.englishBlock,i=()=>`**BLOCK ${t} of ${I.length}** is the base block in ${(0,l.formatLocale)(y,!1)} as reference.\n///chunksStart///\n`+r.content+`///chunksEnd///`,s=()=>`**BLOCK ${t} of ${I.length}** is the current block to review in ${(0,l.formatLocale)(v,!1)}.\n///chunksStart///\n`+(e.frenchBlockText??``)+`///chunksEnd///`,c=await(0,p.retryManager)(async()=>{let e=await a.chunkInference([{role:`system`,content:A},{role:`system`,content:i()},{role:`system`,content:s()},{role:`system`,content:`The next user message will be the **BLOCK ${(0,d.colorizeNumber)(t)} of ${(0,d.colorizeNumber)(I.length)}** that should be translated in ${(0,h.getLocaleName)(v,g.ENGLISH)} (${v}).`},{role:`user`,content:r.content}],b,E,w,T);D(`${M}${(0,d.colorizeNumber)(e.tokenUsed)} tokens used - Block ${(0,d.colorizeNumber)(t)} of ${(0,d.colorizeNumber)(I.length)}`);let c=n.sanitizeChunk(e?.fileContent,r.content);if(c=o.fixChunkStartEndChars(c,r.content),!n.validateTranslation(r.content,c,D))throw Error(`Validation failed for chunk (structure or length mismatch). Retrying...`);return c})();L.set(e.actionIndex,c)}let R=r.mergeReviewedSegments(F,P,L);(0,s.mkdirSync)((0,c.dirname)(_),{recursive:!0}),(0,s.writeFileSync)(_,R),D(`${(0,d.colorize)(`✔`,u.GREEN)} File ${(0,l.formatPath)(_)} created/updated successfully.`)};exports.reviewFileBlockAware=_;
|
|
2
2
|
//# sourceMappingURL=reviewDocBlockAware.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reviewDocBlockAware.cjs","names":["readAsset","ANSIColors","buildAlignmentPlan","mergeReviewedSegments","chunkInference","ENGLISH","sanitizeChunk","fixChunkStartEndChars","validateTranslation"],"sources":["../../../src/reviewDoc/reviewDocBlockAware.ts"],"sourcesContent":["import { mkdirSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { readAsset } from 'utils:asset';\nimport type { AIConfig } from '@intlayer/ai';\nimport type { AIOptions } from '@intlayer/api';\nimport { formatLocale, formatPath } from '@intlayer/chokidar/utils';\nimport {\n ANSIColors,\n colon,\n colorize,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { retryManager } from '@intlayer/config/utils';\nimport { getLocaleName } from '@intlayer/core/localization';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { ENGLISH } from '@intlayer/types/locales';\nimport { sanitizeChunk, validateTranslation } from '../translateDoc/validation';\nimport {\n buildAlignmentPlan,\n mergeReviewedSegments,\n} from '../translation-alignment/pipeline';\nimport { chunkInference } from '../utils/chunkInference';\nimport { fixChunkStartEndChars } from '../utils/fixChunkStartEndChars';\nimport type { AIClient } from '../utils/setupAI';\n\n/**\n * Review a file using block-aware alignment.\n * This approach:\n * 1. Segments both English and French documents into semantic blocks\n * 2. Aligns blocks using structure (special chars, numbers) and context\n * 3. Detects which blocks changed, were added, or deleted\n * 4. Only sends changed/new blocks to AI for translation\n * 5. Handles reordering automatically\n */\nexport const reviewFileBlockAware = async (\n baseFilePath: string,\n outputFilePath: string,\n locale: Locale,\n baseLocale: Locale,\n aiOptions?: AIOptions,\n configOptions?: GetConfigurationOptions,\n customInstructions?: string,\n changedLines?: number[],\n aiClient?: AIClient,\n aiConfig?: AIConfig\n) => {\n const configuration = getConfiguration(configOptions);\n const applicationLogger = getAppLogger(configuration);\n\n const englishText = await readFile(baseFilePath, 'utf-8');\n const frenchText = await readFile(outputFilePath, 'utf-8').catch(() => '');\n\n const basePrompt = readAsset('./prompts/REVIEW_PROMPT.md', 'utf-8')\n .replaceAll('{{localeName}}', `${formatLocale(locale, false)}`)\n .replaceAll('{{baseLocaleName}}', `${formatLocale(baseLocale, false)}`)\n .replace('{{applicationContext}}', aiOptions?.applicationContext ?? '-')\n .replace('{{customInstructions}}', customInstructions ?? '-');\n\n const filePrefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}] `;\n const filePrefix = [\n colon(filePrefixText, { colSize: 40 }),\n `→ ${ANSIColors.RESET}`,\n ].join('');\n const prefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}][${formatLocale(locale)}${ANSIColors.GREY_DARK}] `;\n const prefix = [\n colon(prefixText, { colSize: 40 }),\n `→ ${ANSIColors.RESET}`,\n ].join('');\n\n // Build block-aware alignment and plan\n const { englishBlocks, frenchBlocks, plan, segmentsToReview } =\n buildAlignmentPlan({\n englishText,\n frenchText,\n changedLines,\n });\n\n applicationLogger(\n `${filePrefix}Block-aware alignment complete. Total blocks: EN=${colorizeNumber(englishBlocks.length)}, FR=${colorizeNumber(frenchBlocks.length)}`\n );\n applicationLogger(\n `${filePrefix}Actions: reuse=${colorizeNumber(plan.actions.filter((a) => a.kind === 'reuse').length)}, review=${colorizeNumber(plan.actions.filter((a) => a.kind === 'review').length)}, new=${colorizeNumber(plan.actions.filter((a) => a.kind === 'insert_new').length)}, delete=${colorizeNumber(plan.actions.filter((a) => a.kind === 'delete').length)}`\n );\n\n if (segmentsToReview.length === 0) {\n applicationLogger(\n `${filePrefix}No segments need review, reusing existing translation`\n );\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(\n outputFilePath,\n mergeReviewedSegments(plan, frenchBlocks, new Map())\n );\n applicationLogger(\n `${colorize('✔', ANSIColors.GREEN)} File ${formatPath(outputFilePath)} updated successfully (no changes needed).`\n );\n return;\n }\n\n applicationLogger(\n `${filePrefix}Segments to review: ${colorizeNumber(segmentsToReview.length)}`\n );\n\n // Review segments that need AI translation\n const reviewedSegmentsMap = new Map<number, string>();\n\n for (const segment of segmentsToReview) {\n const segmentNumber = segmentsToReview.indexOf(segment) + 1;\n const englishBlock = segment.englishBlock;\n\n const getBaseChunkContextPrompt = () =>\n `**BLOCK ${segmentNumber} of ${segmentsToReview.length}** is the base block in ${formatLocale(baseLocale, false)} as reference.\\n` +\n `///chunksStart///\\n` +\n englishBlock.content +\n `///chunksEnd///`;\n\n const getFrenchChunkPrompt = () =>\n `**BLOCK ${segmentNumber} of ${segmentsToReview.length}** is the current block to review in ${formatLocale(locale, false)}.\\n` +\n `///chunksStart///\\n` +\n (segment.frenchBlockText ?? '') +\n `///chunksEnd///`;\n\n const reviewedChunkResult = await retryManager(async () => {\n const result = await chunkInference(\n [\n { role: 'system', content: basePrompt },\n { role: 'system', content: getBaseChunkContextPrompt() },\n { role: 'system', content: getFrenchChunkPrompt() },\n {\n role: 'system',\n content: `The next user message will be the **BLOCK ${colorizeNumber(segmentNumber)} of ${colorizeNumber(segmentsToReview.length)}** that should be translated in ${getLocaleName(locale, ENGLISH)} (${locale}).`,\n },\n { role: 'user', content: englishBlock.content },\n ],\n aiOptions,\n configuration,\n aiClient,\n aiConfig\n );\n\n applicationLogger(\n `${prefix}${colorizeNumber(result.tokenUsed)} tokens used - Block ${colorizeNumber(segmentNumber)} of ${colorizeNumber(segmentsToReview.length)}`\n );\n\n // Sanitize artifacts (e.g. Markdown code block wrappers)\n let processedChunk = sanitizeChunk(\n result?.fileContent,\n englishBlock.content\n );\n\n // Fix start/end characters\n processedChunk = fixChunkStartEndChars(\n processedChunk,\n englishBlock.content\n );\n\n // Validate Translation (YAML, Code fences, Length ratio)\n const isValid = validateTranslation(\n englishBlock.content,\n processedChunk,\n applicationLogger\n );\n\n if (!isValid) {\n throw new Error(\n 'Validation failed for chunk (structure or length mismatch). Retrying...'\n );\n }\n\n return processedChunk;\n })();\n\n reviewedSegmentsMap.set(segment.actionIndex, reviewedChunkResult);\n }\n\n // Merge reviewed segments back into final document\n const finalFrenchOutput = mergeReviewedSegments(\n plan,\n frenchBlocks,\n reviewedSegmentsMap\n );\n\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, finalFrenchOutput);\n\n applicationLogger(\n `${colorize('✔', ANSIColors.GREEN)} File ${formatPath(outputFilePath)} created/updated successfully.`\n );\n};\n"],"mappings":"orBAwCA,MAAa,EAAuB,MAClC,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,IACG,CACH,IAAM,GAAA,EAAA,EAAA,kBAAiC,EAAc,CAC/C,GAAA,EAAA,EAAA,cAAiC,EAAc,CAE/C,EAAc,MAAA,EAAA,EAAA,UAAe,EAAc,QAAQ,CACnD,EAAa,MAAA,EAAA,EAAA,UAAe,EAAgB,QAAQ,CAAC,UAAY,GAAG,CAEpE,EAAaA,EAAAA,EAAU,6BAA8B,QAAQ,CAChE,WAAW,iBAAkB,IAAA,EAAA,EAAA,cAAgB,EAAQ,GAAM,GAAG,CAC9D,WAAW,qBAAsB,IAAA,EAAA,EAAA,cAAgB,EAAY,GAAM,GAAG,CACtE,QAAQ,yBAA0B,GAAW,oBAAsB,IAAI,CACvE,QAAQ,yBAA0B,GAAsB,IAAI,CAGzD,EAAa,EAAA,EAAA,EAAA,OADI,GAAGC,EAAAA,WAAW,UAAU,IAAA,EAAA,EAAA,YAAc,EAAa,GAAGA,EAAAA,WAAW,UAAU,IAE1E,C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,EAAE,CAEJ,EAAoB,IAAI,EAAQ,YAAa,EAAoB,CAInE,IAAM,EAAoBL,EAAAA,sBACxB,EACA,EACA,EACD,EAED,EAAA,EAAA,YAAA,EAAA,EAAA,SAAkB,EAAe,CAAE,CAAE,UAAW,GAAM,CAAC,EACvD,EAAA,EAAA,eAAc,EAAgB,EAAkB,CAEhD,EACE,IAAA,EAAA,EAAA,UAAY,IAAKF,EAAAA,WAAW,MAAM,CAAC,SAAA,EAAA,EAAA,YAAmB,EAAe,CAAC,gCACvE"}
|
|
1
|
+
{"version":3,"file":"reviewDocBlockAware.cjs","names":["readAsset","ANSIColors","buildAlignmentPlan","mergeReviewedSegments","chunkInference","ENGLISH","sanitizeChunk","fixChunkStartEndChars","validateTranslation"],"sources":["../../../src/reviewDoc/reviewDocBlockAware.ts"],"sourcesContent":["import { mkdirSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { readAsset } from 'utils:asset';\nimport type { AIConfig } from '@intlayer/ai';\nimport type { AIOptions } from '@intlayer/api';\nimport { formatLocale, formatPath } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { retryManager } from '@intlayer/config/utils';\nimport { getLocaleName } from '@intlayer/core/localization';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { ENGLISH } from '@intlayer/types/locales';\nimport { sanitizeChunk, validateTranslation } from '../translateDoc/validation';\nimport {\n buildAlignmentPlan,\n mergeReviewedSegments,\n} from '../translation-alignment/pipeline';\nimport { chunkInference } from '../utils/chunkInference';\nimport { fixChunkStartEndChars } from '../utils/fixChunkStartEndChars';\nimport type { AIClient } from '../utils/setupAI';\n\n/**\n * Review a file using block-aware alignment.\n * This approach:\n * 1. Segments both English and French documents into semantic blocks\n * 2. Aligns blocks using structure (special chars, numbers) and context\n * 3. Detects which blocks changed, were added, or deleted\n * 4. Only sends changed/new blocks to AI for translation\n * 5. Handles reordering automatically\n */\nexport const reviewFileBlockAware = async (\n baseFilePath: string,\n outputFilePath: string,\n locale: Locale,\n baseLocale: Locale,\n aiOptions?: AIOptions,\n configOptions?: GetConfigurationOptions,\n customInstructions?: string,\n changedLines?: number[],\n aiClient?: AIClient,\n aiConfig?: AIConfig\n) => {\n const configuration = getConfiguration(configOptions);\n const applicationLogger = getAppLogger(configuration);\n\n const englishText = await readFile(baseFilePath, 'utf-8');\n const frenchText = await readFile(outputFilePath, 'utf-8').catch(() => '');\n\n const basePrompt = readAsset('./prompts/REVIEW_PROMPT.md', 'utf-8')\n .replaceAll('{{localeName}}', `${formatLocale(locale, false)}`)\n .replaceAll('{{baseLocaleName}}', `${formatLocale(baseLocale, false)}`)\n .replace('{{applicationContext}}', aiOptions?.applicationContext ?? '-')\n .replace('{{customInstructions}}', customInstructions ?? '-');\n\n const filePrefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}] `;\n const filePrefix = [\n colon(filePrefixText, { colSize: 40 }),\n `→ ${ANSIColors.RESET}`,\n ].join('');\n const prefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}][${formatLocale(locale)}${ANSIColors.GREY_DARK}] `;\n const prefix = [\n colon(prefixText, { colSize: 40 }),\n `→ ${ANSIColors.RESET}`,\n ].join('');\n\n // Build block-aware alignment and plan\n const { englishBlocks, frenchBlocks, plan, segmentsToReview } =\n buildAlignmentPlan({\n englishText,\n frenchText,\n changedLines,\n });\n\n applicationLogger(\n `${filePrefix}Block-aware alignment complete. Total blocks: EN=${colorizeNumber(englishBlocks.length)}, FR=${colorizeNumber(frenchBlocks.length)}`\n );\n applicationLogger(\n `${filePrefix}Actions: reuse=${colorizeNumber(plan.actions.filter((a) => a.kind === 'reuse').length)}, review=${colorizeNumber(plan.actions.filter((a) => a.kind === 'review').length)}, new=${colorizeNumber(plan.actions.filter((a) => a.kind === 'insert_new').length)}, delete=${colorizeNumber(plan.actions.filter((a) => a.kind === 'delete').length)}`\n );\n\n if (segmentsToReview.length === 0) {\n applicationLogger(\n `${filePrefix}No segments need review, reusing existing translation`\n );\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(\n outputFilePath,\n mergeReviewedSegments(plan, frenchBlocks, new Map())\n );\n applicationLogger(\n `${colorize('✔', ANSIColors.GREEN)} File ${formatPath(outputFilePath)} updated successfully (no changes needed).`\n );\n return;\n }\n\n applicationLogger(\n `${filePrefix}Segments to review: ${colorizeNumber(segmentsToReview.length)}`\n );\n\n // Review segments that need AI translation\n const reviewedSegmentsMap = new Map<number, string>();\n\n for (const segment of segmentsToReview) {\n const segmentNumber = segmentsToReview.indexOf(segment) + 1;\n const englishBlock = segment.englishBlock;\n\n const getBaseChunkContextPrompt = () =>\n `**BLOCK ${segmentNumber} of ${segmentsToReview.length}** is the base block in ${formatLocale(baseLocale, false)} as reference.\\n` +\n `///chunksStart///\\n` +\n englishBlock.content +\n `///chunksEnd///`;\n\n const getFrenchChunkPrompt = () =>\n `**BLOCK ${segmentNumber} of ${segmentsToReview.length}** is the current block to review in ${formatLocale(locale, false)}.\\n` +\n `///chunksStart///\\n` +\n (segment.frenchBlockText ?? '') +\n `///chunksEnd///`;\n\n const reviewedChunkResult = await retryManager(async () => {\n const result = await chunkInference(\n [\n { role: 'system', content: basePrompt },\n { role: 'system', content: getBaseChunkContextPrompt() },\n { role: 'system', content: getFrenchChunkPrompt() },\n {\n role: 'system',\n content: `The next user message will be the **BLOCK ${colorizeNumber(segmentNumber)} of ${colorizeNumber(segmentsToReview.length)}** that should be translated in ${getLocaleName(locale, ENGLISH)} (${locale}).`,\n },\n { role: 'user', content: englishBlock.content },\n ],\n aiOptions,\n configuration,\n aiClient,\n aiConfig\n );\n\n applicationLogger(\n `${prefix}${colorizeNumber(result.tokenUsed)} tokens used - Block ${colorizeNumber(segmentNumber)} of ${colorizeNumber(segmentsToReview.length)}`\n );\n\n // Sanitize artifacts (e.g. Markdown code block wrappers)\n let processedChunk = sanitizeChunk(\n result?.fileContent,\n englishBlock.content\n );\n\n // Fix start/end characters\n processedChunk = fixChunkStartEndChars(\n processedChunk,\n englishBlock.content\n );\n\n // Validate Translation (YAML, Code fences, Length ratio)\n const isValid = validateTranslation(\n englishBlock.content,\n processedChunk,\n applicationLogger\n );\n\n if (!isValid) {\n throw new Error(\n 'Validation failed for chunk (structure or length mismatch). Retrying...'\n );\n }\n\n return processedChunk;\n })();\n\n reviewedSegmentsMap.set(segment.actionIndex, reviewedChunkResult);\n }\n\n // Merge reviewed segments back into final document\n const finalFrenchOutput = mergeReviewedSegments(\n plan,\n frenchBlocks,\n reviewedSegmentsMap\n );\n\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, finalFrenchOutput);\n\n applicationLogger(\n `${colorize('✔', ANSIColors.GREEN)} File ${formatPath(outputFilePath)} created/updated successfully.`\n );\n};\n"],"mappings":"wuBAwCA,MAAa,EAAuB,MAClC,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,IACG,CACH,IAAM,GAAA,EAAA,EAAA,kBAAiC,EAAc,CAC/C,GAAA,EAAA,EAAA,cAAiC,EAAc,CAE/C,EAAc,MAAA,EAAA,EAAA,UAAe,EAAc,QAAQ,CACnD,EAAa,MAAA,EAAA,EAAA,UAAe,EAAgB,QAAQ,CAAC,UAAY,GAAG,CAEpE,EAAaA,EAAAA,EAAU,6BAA8B,QAAQ,CAChE,WAAW,iBAAkB,IAAA,EAAA,EAAA,cAAgB,EAAQ,GAAM,GAAG,CAC9D,WAAW,qBAAsB,IAAA,EAAA,EAAA,cAAgB,EAAY,GAAM,GAAG,CACtE,QAAQ,yBAA0B,GAAW,oBAAsB,IAAI,CACvE,QAAQ,yBAA0B,GAAsB,IAAI,CAGzD,EAAa,EAAA,EAAA,EAAA,OADI,GA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AAU,MACR,0EACD,CAGH,OAAO,GACP,EAAE,CAEJ,EAAoB,IAAI,EAAQ,YAAa,EAAoB,CAInE,IAAM,EAAoBL,EAAAA,sBACxB,EACA,EACA,EACD,EAED,EAAA,EAAA,YAAA,EAAA,EAAA,SAAkB,EAAe,CAAE,CAAE,UAAW,GAAM,CAAC,EACvD,EAAA,EAAA,eAAc,EAAgB,EAAkB,CAEhD,EACE,IAAA,EAAA,EAAA,UAAY,IAAKF,EAAW,MAAM,CAAC,SAAA,EAAA,EAAA,YAAmB,EAAe,CAAC,gCACvE"}
|
package/dist/cjs/test/test.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`})
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../chunk-Bmb41Sf3.cjs`),t=require(`./listMissingTranslations.cjs`);let n=require(`@intlayer/chokidar/build`),r=require(`@intlayer/chokidar/utils`),i=require(`@intlayer/config/colors`);i=e.t(i);let a=require(`@intlayer/config/logger`),o=require(`@intlayer/config/node`);const s=async e=>{let s=(0,o.getConfiguration)(e?.configOptions),{locales:c,requiredLocales:l}=s.internationalization,u=(0,a.getAppLogger)(s);e?.build===!0?await(0,n.prepareIntlayer)(s,{forceRun:!0}):e?.build===void 0&&await(0,n.prepareIntlayer)(s);let d=t.listMissingTranslations(e?.configOptions),f=d.missingTranslations.map(e=>` - ${e.key}`).reduce((e,t)=>Math.max(e,t.length),0),p=d.missingTranslations.map(e=>(0,r.formatLocale)(e.locales,!1)).reduce((e,t)=>Math.max(e,t.length),0),m=d.missingTranslations.map(e=>[(0,a.colon)(` - ${(0,a.colorizeKey)(e.key)}`,{colSize:f,maxSize:40}),` - `,(0,a.colon)((0,r.formatLocale)(e.locales,i.RED),{colSize:p,maxSize:40}),e.filePath?` - ${(0,r.formatPath)(e.filePath)}`:``,e.id?` - remote`:``].join(``));u(`Missing translations:`,{level:`info`}),m.forEach(e=>{u(e,{level:`info`})}),u(`Locales: ${(0,r.formatLocale)(c)}`),u(`Required locales: ${(0,r.formatLocale)(l??c)}`),u(`Missing locales: ${d.missingLocales.length===0?(0,a.colorize)(`-`,i.GREEN):(0,r.formatLocale)(d.missingLocales,i.RED)}`),u(`Missing required locales: ${d.missingRequiredLocales.length===0?(0,a.colorize)(`-`,i.GREEN):(0,r.formatLocale)(d.missingRequiredLocales,i.RED)}`),u(`Total missing locales: ${(0,a.colorizeNumber)(d.missingLocales.length,{one:i.RED,other:i.RED,zero:i.GREEN})}`),u(`Total missing required locales: ${(0,a.colorizeNumber)(d.missingRequiredLocales.length,{one:i.RED,other:i.RED,zero:i.GREEN})}`),d.missingRequiredLocales.length>0&&process.exit(1)};exports.testMissingTranslations=s;
|
|
2
2
|
//# sourceMappingURL=test.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"test.cjs","names":["listMissingTranslations","ANSIColors"],"sources":["../../../src/test/test.ts"],"sourcesContent":["import { prepareIntlayer } from '@intlayer/chokidar/build';\nimport { formatLocale, formatPath } from '@intlayer/chokidar/utils';\nimport {\n
|
|
1
|
+
{"version":3,"file":"test.cjs","names":["listMissingTranslations","ANSIColors"],"sources":["../../../src/test/test.ts"],"sourcesContent":["import { prepareIntlayer } from '@intlayer/chokidar/build';\nimport { formatLocale, formatPath } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeKey,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { listMissingTranslations } from './listMissingTranslations';\n\ntype ListMissingTranslationsOptions = {\n configOptions?: GetConfigurationOptions;\n build?: boolean;\n};\n\nexport const testMissingTranslations = async (\n options?: ListMissingTranslationsOptions\n) => {\n const config = getConfiguration(options?.configOptions);\n const { locales, requiredLocales } = config.internationalization;\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 const result = listMissingTranslations(options?.configOptions);\n\n const maxKeyColSize = result.missingTranslations\n .map((t) => ` - ${t.key}`)\n .reduce((max, t) => Math.max(max, t.length), 0);\n const maxLocalesColSize = result.missingTranslations\n .map((t) => formatLocale(t.locales, false))\n .reduce((max, t) => Math.max(max, t.length), 0);\n\n const formattedMissingTranslations = result.missingTranslations.map(\n (translation) =>\n [\n colon(` - ${colorizeKey(translation.key)}`, {\n colSize: maxKeyColSize,\n maxSize: 40,\n }),\n ' - ',\n colon(formatLocale(translation.locales, ANSIColors.RED), {\n colSize: maxLocalesColSize,\n maxSize: 40,\n }),\n\n translation.filePath ? ` - ${formatPath(translation.filePath)}` : '',\n translation.id ? ' - remote' : '',\n ].join('')\n );\n\n appLogger(`Missing translations:`, {\n level: 'info',\n });\n\n formattedMissingTranslations.forEach((t) => {\n appLogger(t, {\n level: 'info',\n });\n });\n\n appLogger(`Locales: ${formatLocale(locales)}`);\n appLogger(`Required locales: ${formatLocale(requiredLocales ?? locales)}`);\n appLogger(\n `Missing locales: ${result.missingLocales.length === 0 ? colorize('-', ANSIColors.GREEN) : formatLocale(result.missingLocales, ANSIColors.RED)}`\n );\n\n appLogger(\n `Missing required locales: ${result.missingRequiredLocales.length === 0 ? colorize('-', ANSIColors.GREEN) : formatLocale(result.missingRequiredLocales, ANSIColors.RED)}`\n );\n appLogger(\n `Total missing locales: ${colorizeNumber(result.missingLocales.length, {\n one: ANSIColors.RED,\n other: ANSIColors.RED,\n zero: ANSIColors.GREEN,\n })}`\n );\n appLogger(\n `Total missing required locales: ${colorizeNumber(\n result.missingRequiredLocales.length,\n {\n one: ANSIColors.RED,\n other: ANSIColors.RED,\n zero: ANSIColors.GREEN,\n }\n )}`\n );\n\n if (result.missingRequiredLocales.length > 0) {\n process.exit(1);\n }\n};\n"],"mappings":"iWAqBA,MAAa,EAA0B,KACr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AAgB,EAAO,eAAgBA,EAAW,IAAI,GAC/I,CAED,EACE,6BAA6B,EAAO,uBAAuB,SAAW,GAAA,EAAA,EAAA,UAAa,IAAKA,EAAW,MAAM,EAAA,EAAA,EAAA,cAAgB,EAAO,uBAAwBA,EAAW,IAAI,GACxK,CACD,EACE,2BAAA,EAAA,EAAA,gBAAyC,EAAO,eAAe,OAAQ,CACrE,IAAKA,EAAW,IAChB,MAAOA,EAAW,IAClB,KAAMA,EAAW,MAClB,CAAC,GACH,CACD,EACE,oCAAA,EAAA,EAAA,gBACE,EAAO,uBAAuB,OAC9B,CACE,IAAKA,EAAW,IAChB,MAAOA,EAAW,IAClB,KAAMA,EAAW,MAClB,CACF,GACF,CAEG,EAAO,uBAAuB,OAAS,GACzC,QAAQ,KAAK,EAAE"}
|
|
@@ -1,2 +1,2 @@
|
|
|
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(`./translateFile.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`),
|
|
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(`./translateFile.cjs`);let a=require(`node:fs`),o=require(`node:path`),s=require(`@intlayer/chokidar/cli`),c=require(`@intlayer/chokidar/utils`),l=require(`@intlayer/config/colors`);l=e.t(l);let u=require(`@intlayer/config/logger`),d=require(`@intlayer/config/node`),f=require(`fast-glob`);f=e.t(f);let p=require(`node:perf_hooks`);const m=async({docPattern:e,locales:m,excludedGlobPattern:h,baseLocale:g,aiOptions:_,nbSimultaneousFileProcessed:v=20,configOptions:y,customInstructions:b,skipIfModifiedBefore:x,skipIfModifiedAfter:S,skipIfExists:C,gitOptions:w,flushStrategy:T=`incremental`})=>{let E=(0,d.getConfiguration)(y);(0,s.logConfigDetails)(y);let D=(0,u.getAppLogger)(E),O=v,k=(0,c.pLimit)(O),A=await(0,f.default)(e,{ignore:h}),j=await t.setupAI(E,_);if(!j?.hasAIAccess)return;let{aiClient:M,aiConfig:N}=j;if(w){let e=await(0,s.listGitFiles)(w);e&&(A=A.filter(t=>e.some(e=>(0,o.join)(process.cwd(),t)===e)))}let P=p.performance.now();D(`Translating ${(0,u.colorizeNumber)(A.length)} files to ${(0,u.colorizeNumber)(m.length)} locales. \nGlobal Concurrency: ${(0,u.colorizeNumber)(O)} chunks in parallel.`);let F={count:0,maxErrors:5,shouldStop:!1};await(0,c.parallelize)(A.flatMap(e=>m.map(t=>async()=>{if(F.shouldStop)return;let s=(0,o.join)(E.system.baseDir,e),c=r.getOutputFilePath(s,t,g);if(C&&(0,a.existsSync)(c))return;T===`incremental`&&!(0,a.existsSync)(c)&&((0,a.mkdirSync)((0,o.dirname)(c),{recursive:!0}),(0,a.writeFileSync)(c,``));let l=n.checkFileModifiedRange(c,{skipIfModifiedBefore:x,skipIfModifiedAfter:S});if(l.isSkipped){D(l.message);return}await i.translateFile({baseFilePath:s,outputFilePath:c,locale:t,baseLocale:g,configuration:E,errorState:F,aiOptions:_,customInstructions:b,aiClient:M,aiConfig:N,flushStrategy:T,limit:k})})),e=>e(),50);let I=((p.performance.now()-P)/1e3).toFixed(2);F.count>0?D(`Finished with ${F.count} errors in ${I}s.`):D(`${(0,u.colorize)(`✔`,l.GREEN)} Batch completed successfully in ${(0,u.colorizeNumber)(I)}s.`)};exports.translateDoc=m;
|
|
2
2
|
//# sourceMappingURL=translateDoc.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translateDoc.cjs","names":["setupAI","performance","getOutputFilePath","checkFileModifiedRange","translateFile","ANSIColors"],"sources":["../../../src/translateDoc/translateDoc.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { performance } from 'node:perf_hooks';\nimport { listGitFiles, logConfigDetails } from '@intlayer/chokidar/cli';\nimport { parallelize, pLimit } from '@intlayer/chokidar/utils';\nimport {\n
|
|
1
|
+
{"version":3,"file":"translateDoc.cjs","names":["setupAI","performance","getOutputFilePath","checkFileModifiedRange","translateFile","ANSIColors"],"sources":["../../../src/translateDoc/translateDoc.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { performance } from 'node:perf_hooks';\nimport { listGitFiles, logConfigDetails } from '@intlayer/chokidar/cli';\nimport { parallelize, pLimit } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colorize,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { getConfiguration } 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 { translateFile } from './translateFile';\nimport type { ErrorState, TranslateDocOptions } from './types';\n\nexport const translateDoc = async ({\n docPattern,\n locales,\n excludedGlobPattern,\n baseLocale,\n aiOptions,\n nbSimultaneousFileProcessed = 20, // Default to a higher concurrency for chunks\n configOptions,\n customInstructions,\n skipIfModifiedBefore,\n skipIfModifiedAfter,\n skipIfExists,\n gitOptions,\n flushStrategy = 'incremental',\n}: TranslateDocOptions) => {\n const configuration = getConfiguration(configOptions);\n logConfigDetails(configOptions);\n\n const appLogger = getAppLogger(configuration);\n\n // 1. GLOBAL QUEUE SETUP\n // We use pLimit to create a single bottleneck for AI requests.\n // This queue is shared across all files and locales.\n const maxConcurrentChunks = nbSimultaneousFileProcessed;\n const globalChunkLimiter = pLimit(maxConcurrentChunks);\n\n let docList: string[] = await fg(docPattern, {\n ignore: excludedGlobPattern,\n });\n\n const aiResult = await setupAI(configuration, aiOptions);\n if (!aiResult?.hasAIAccess) return;\n const { aiClient, aiConfig } = aiResult;\n\n if (gitOptions) {\n const gitChangedFiles = await listGitFiles(gitOptions);\n if (gitChangedFiles) {\n docList = docList.filter((path) =>\n gitChangedFiles.some((gitFile) => join(process.cwd(), path) === gitFile)\n );\n }\n }\n\n const batchStartTime = performance.now();\n\n appLogger(\n `Translating ${colorizeNumber(docList.length)} files to ${colorizeNumber(locales.length)} locales. \\n` +\n `Global Concurrency: ${colorizeNumber(maxConcurrentChunks)} chunks in parallel.`\n );\n\n const errorState: ErrorState = {\n count: 0,\n maxErrors: 5,\n shouldStop: false,\n };\n\n // 2. FLATTENED TASK LIST\n // We create a task for every File x Locale combination.\n const allTasks = docList.flatMap((docPath) =>\n locales.map((locale) => async () => {\n if (errorState.shouldStop) return;\n\n const absoluteBaseFilePath = join(configuration.system.baseDir, docPath);\n const outputFilePath = getOutputFilePath(\n absoluteBaseFilePath,\n locale,\n baseLocale\n );\n\n // Skip logic\n if (skipIfExists && existsSync(outputFilePath)) return;\n\n if (flushStrategy === 'incremental' && !existsSync(outputFilePath)) {\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, '');\n }\n\n const fileModificationData = checkFileModifiedRange(outputFilePath, {\n skipIfModifiedBefore,\n skipIfModifiedAfter,\n });\n\n if (fileModificationData.isSkipped) {\n appLogger(fileModificationData.message);\n return;\n }\n\n // Execute translation using the SHARED limiter\n await translateFile({\n baseFilePath: absoluteBaseFilePath,\n outputFilePath,\n locale: locale as Locale,\n baseLocale,\n configuration,\n errorState,\n aiOptions,\n customInstructions,\n aiClient,\n aiConfig,\n flushStrategy,\n limit: globalChunkLimiter, // Pass the global queue\n });\n })\n );\n\n // 3. HIGH-THROUGHPUT FILE OPENER\n // We open many files simultaneously (e.g., 50) to ensure the global chunk queue\n // is always saturated with work.\n // If we open too few files, the chunk queue might drain faster than we can read new files.\n const FILE_OPEN_LIMIT = 50;\n\n await parallelize(allTasks, (task) => task(), FILE_OPEN_LIMIT);\n\n const batchEndTime = performance.now();\n const batchDuration = ((batchEndTime - batchStartTime) / 1000).toFixed(2);\n\n if (errorState.count > 0) {\n appLogger(`Finished with ${errorState.count} errors in ${batchDuration}s.`);\n } else {\n appLogger(\n `${colorize('✔', ANSIColors.GREEN)} Batch completed successfully in ${colorizeNumber(batchDuration)}s.`\n );\n }\n};\n"],"mappings":"ikBAoBA,MAAa,EAAe,MAAO,CACjC,aACA,UACA,sBACA,aACA,YACA,8BAA8B,GAC9B,gBACA,qBACA,uBACA,sBACA,eACA,aACA,gBAAgB,iBACS,CACzB,IAAM,GAAA,EAAA,EAAA,kBAAiC,EAAc,EACrD,EAAA,EAAA,kBAAiB,EAAc,CAE/B,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAc,CAKvC,EAAsB,EACtB,GAAA,EAAA,EAAA,QAA4B,EAAoB,CAElD,EAAoB,MAAA,EAAA,EAAA,SAAS,EAAY,CAC3C,OAAQ,EACT,CAAC,CAEI,EAAW,MAAMA,EAAAA,QAAQ,EAAe,EAAU,CACxD,GAAI,CAAC,GAAU,YAAa,OAC5B,GAAM,CAAE,WAAU,YAAa,EAE/B,GAAI,EAAY,CACd,IAAM,EAAkB,MAAA,EAAA,EAAA,cAAmB,EAAW,CAClD,IACF,EAAU,EAAQ,OAAQ,GACxB,EAAgB,KAAM,IAAA,EAAA,EAAA,MAAiB,QAAQ,KAAK,CAAE,EAAK,GAAK,EAAQ,CACzE,EAIL,IAAM,EAAiBC,EAAAA,YAAY,KAAK,CAExC,EACE,gBAAA,EAAA,EAAA,gBAA8B,EAAQ,OAAO,CAAC,aAAA,EAAA,EAAA,gBAA2B,EAAQ,OAAO,CAAC,mCAAA,EAAA,EAAA,gBACjD,EAAoB,CAAC,sBAC9D,CAED,IAAM,EAAyB,CAC7B,MAAO,EACP,UAAW,EACX,WAAY,GACb,CAyDD,MAAA,EAAA,EAAA,aArDiB,EAAQ,QAAS,GAChC,EAAQ,IAAK,GAAW,SAAY,CAClC,GAAI,EAAW,WAAY,OAE3B,IAAM,GAAA,EAAA,EAAA,MAA4B,EAAc,OAAO,QAAS,EAAQ,CAClE,EAAiBC,EAAAA,kBACrB,EACA,EACA,EACD,CAGD,GAAI,IAAA,EAAA,EAAA,YAA2B,EAAe,CAAE,OAE5C,IAAkB,eAAiB,EAAA,EAAA,EAAA,YAAY,EAAe,IAChE,EAAA,EAAA,YAAA,EAAA,EAAA,SAAkB,EAAe,CAAE,CAAE,UAAW,GAAM,CAAC,EACvD,EAAA,EAAA,eAAc,EAAgB,GAAG,EAGnC,IAAM,EAAuBC,EAAAA,uBAAuB,EAAgB,CAClE,uBACA,sBACD,CAAC,CAEF,GAAI,EAAqB,UAAW,CAClC,EAAU,EAAqB,QAAQ,CACvC,OAIF,MAAMC,EAAAA,cAAc,CAClB,aAAc,EACd,iBACQ,SACR,aACA,gBACA,aACA,YACA,qBACA,WACA,WACA,gBACA,MAAO,EACR,CAAC,EACF,CACH,CAQ4B,GAAS,GAAM,CAFpB,GAEsC,CAG9D,IAAM,IADeH,EAAAA,YAAY,KAAK,CACC,GAAkB,KAAM,QAAQ,EAAE,CAErE,EAAW,MAAQ,EACrB,EAAU,iBAAiB,EAAW,MAAM,aAAa,EAAc,IAAI,CAE3E,EACE,IAAA,EAAA,EAAA,UAAY,IAAKI,EAAW,MAAM,CAAC,oCAAA,EAAA,EAAA,gBAAkD,EAAc,CAAC,IACrG"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`})
|
|
2
|
-
`)},{role:`user`,content:`>>> TARGET CHUNK START <<<\n${
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../chunk-Bmb41Sf3.cjs`),t=require(`../_utils_asset-ghp_Cjwk.cjs`),n=require(`./validation.cjs`),r=require(`../utils/chunkInference.cjs`),i=require(`../utils/fixChunkStartEndChars.cjs`),a=require(`../utils/calculateChunks.cjs`);let o=require(`node:fs`),s=require(`node:path`),c=require(`@intlayer/chokidar/utils`),l=require(`@intlayer/config/colors`);l=e.t(l);let u=require(`@intlayer/config/logger`),d=require(`@intlayer/config/utils`),f=require(`node:fs/promises`),p=require(`node:perf_hooks`);const m=async({baseFilePath:e,outputFilePath:m,locale:h,baseLocale:g,configuration:_,errorState:v,aiOptions:y,customInstructions:b,aiClient:x,aiConfig:S,flushStrategy:C=`incremental`,onChunkReceive:w,limit:T})=>{if(v.shouldStop)return null;let E=(0,u.getAppLogger)(_,{config:{prefix:``}}),D=p.performance.now();try{let O=a.chunkText(await(0,f.readFile)(e,`utf-8`)),k=O.length,A=`${(0,u.colon)(`${l.GREY_DARK}[${(0,c.formatPath)(e)}${l.GREY_DARK}] `,{colSize:40})}${l.RESET}`,j=`${(0,u.colon)(`${l.GREY_DARK}[${(0,c.formatPath)(e)}${l.GREY_DARK}][${(0,c.formatLocale)(h)}${l.GREY_DARK}] `,{colSize:40})}${l.RESET}`;E(`${A}Split into ${(0,u.colorizeNumber)(k)} chunks. Queuing...`);let M=t.t(`./prompts/TRANSLATE_PROMPT.md`,`utf-8`).replaceAll(`{{localeName}}`,`${(0,c.formatLocale)(h,!1)}`).replaceAll(`{{baseLocaleName}}`,`${(0,c.formatLocale)(g,!1)}`).replace(`{{applicationContext}}`,y?.applicationContext??`-`).replace(`{{customInstructions}}`,b??`-`),N=Array(k).fill(``),P=T??(e=>e()),F=O.map((e,t)=>P(async()=>{if(v.shouldStop)return null;let a=(0,u.getAppLogger)(_,{config:{prefix:`${j} ${l.GREY_DARK}[${t+1}/${k}] ${l.RESET}`}}),c=p.performance.now(),f=t===0,h=e.content,g=()=>">>> CONTEXT: PREVIOUS SOURCE CONTENT <<<\n```\n"+(O[t-1]?.content??``)+"\n```\n>>> END PREVIOUS CONTEXT <<<",b=()=>">>> CONTEXT: NEXT CONTENT <<<\n```\n"+(O[t+1]?.content??``)+"\n```\n>>> END NEXT CONTEXT <<<";a(`Process started`);let{content:T,tokens:E}=await(0,d.retryManager)(async()=>{let e=await r.chunkInference([{role:`system`,content:M},...O[t+1]?[{role:`system`,content:b()}]:[],...f?[]:[{role:`system`,content:g()}],{role:`system`,content:[`You are translating TARGET CHUNK (${t+1}/${k}).`,`Translate ONLY the target chunk. Preserve frontmatter/code exactly.`].join(`
|
|
2
|
+
`)},{role:`user`,content:`>>> TARGET CHUNK START <<<\n${h}\n>>> TARGET CHUNK END <<<`}],y,_,x,S),o=n.sanitizeChunk(e?.fileContent,h);if(o=i.fixChunkStartEndChars(o,h),!n.validateTranslation(h,o,a))throw Error(`Validation failed for chunk ${t+1}/${k}`);return{content:o,tokens:e.tokenUsed}})(),D=(p.performance.now()-c).toFixed(0);if(N[t]=T,w&&w(T,t,k),C===`incremental`&&N.slice(0,t+1).every(e=>e&&e!==``)){let e=0;for(;e<k&&N[e]&&N[e]!==``;)e++;let t=N.slice(0,e).join(``);(0,o.mkdirSync)((0,s.dirname)(m),{recursive:!0}),(0,o.writeFileSync)(m,t)}a([`${(0,u.colorizeNumber)(E)} tokens used `,`${l.GREY_DARK}in ${(0,u.colorizeNumber)(D)}ms${l.RESET}`].join(``))}));await Promise.all(F);let I=N.join(``);(C===`end`||C===`incremental`)&&((0,o.mkdirSync)((0,s.dirname)(m),{recursive:!0}),(0,o.writeFileSync)(m,I));let L=((p.performance.now()-D)/1e3).toFixed(2),R=(0,s.relative)(_.system.baseDir,m);return E(`${(0,u.colorize)(`✔`,l.GREEN)} File ${(0,c.formatPath)(R)} completed in ${(0,u.colorizeNumber)(L)}s.`),I}catch(e){v.count++;let t=e?.message??JSON.stringify(e);return E(`${(0,u.colorize)(`✖`,l.RED)} Error: ${t}`),v.count>=v.maxErrors&&(v.shouldStop=!0),null}};exports.translateFile=m;
|
|
3
3
|
//# sourceMappingURL=translateFile.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translateFile.cjs","names":["performance","chunkText","ANSIColors","readAsset","chunkInference","sanitizeChunk","fixChunkStartEndChars","validateTranslation"],"sources":["../../../src/translateDoc/translateFile.ts"],"sourcesContent":["import { mkdirSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { dirname, relative } from 'node:path';\nimport { performance } from 'node:perf_hooks';\nimport { readAsset } from 'utils:asset';\nimport { formatLocale, formatPath } from '@intlayer/chokidar/utils';\nimport {\n ANSIColors,\n colon,\n colorize,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { retryManager } from '@intlayer/config/utils';\nimport { chunkText } from '../utils/calculateChunks';\nimport { chunkInference } from '../utils/chunkInference';\nimport { fixChunkStartEndChars } from '../utils/fixChunkStartEndChars';\nimport type { TranslateFileOptions } from './types';\nimport { sanitizeChunk, validateTranslation } from './validation';\n\nexport const translateFile = async ({\n baseFilePath,\n outputFilePath,\n locale,\n baseLocale,\n configuration,\n errorState,\n aiOptions,\n customInstructions,\n aiClient,\n aiConfig,\n flushStrategy = 'incremental',\n onChunkReceive,\n limit, // The Global Limiter\n}: TranslateFileOptions): Promise<string | null> => {\n if (errorState.shouldStop) return null;\n\n const appLogger = getAppLogger(configuration, { config: { prefix: '' } });\n const fileStartTime = performance.now();\n\n try {\n const fileContent = await readFile(baseFilePath, 'utf-8');\n const chunks = chunkText(fileContent);\n const totalChunks = chunks.length;\n\n const filePrefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}] `;\n const filePrefix = `${colon(filePrefixText, { colSize: 40 })}${ANSIColors.RESET}`;\n const prefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}][${formatLocale(locale)}${ANSIColors.GREY_DARK}] `;\n const prefix = `${colon(prefixText, { colSize: 40 })}${ANSIColors.RESET}`;\n\n appLogger(\n `${filePrefix}Split into ${colorizeNumber(totalChunks)} chunks. Queuing...`\n );\n\n const basePrompt = readAsset('./prompts/TRANSLATE_PROMPT.md', 'utf-8')\n .replaceAll('{{localeName}}', `${formatLocale(locale, false)}`)\n .replaceAll('{{baseLocaleName}}', `${formatLocale(baseLocale, false)}`)\n .replace('{{applicationContext}}', aiOptions?.applicationContext ?? '-')\n .replace('{{customInstructions}}', customInstructions ?? '-');\n\n const translatedParts: string[] = new Array(totalChunks).fill('');\n\n // Fallback if no limiter is provided (runs immediately)\n const runTask = limit ?? ((fn) => fn());\n\n // MAP CHUNKS TO GLOBAL TASKS\n // This pushes ALL chunks for this file into the Global Queue immediately.\n // They will execute whenever the global concurrency slots open up.\n const tasks = chunks.map((chunk, i) =>\n runTask(async () => {\n if (errorState.shouldStop) return null;\n\n const chunkLogger = getAppLogger(configuration, {\n config: {\n prefix: `${prefix} ${ANSIColors.GREY_DARK}[${i + 1}/${totalChunks}] ${ANSIColors.RESET}`,\n },\n });\n\n const chunkStartTime = performance.now();\n const isFirstChunk = i === 0;\n const fileToTranslateCurrentChunk = chunk.content;\n\n // Context Preparation\n const getPrevChunkPrompt = () =>\n `>>> CONTEXT: PREVIOUS SOURCE CONTENT <<<\\n\\`\\`\\`\\n` +\n (chunks[i - 1]?.content ?? '') +\n `\\n\\`\\`\\`\\n>>> END PREVIOUS CONTEXT <<<`;\n\n const getBaseChunkContextPrompt = () =>\n `>>> CONTEXT: NEXT CONTENT <<<\\n\\`\\`\\`\\n` +\n (chunks[i + 1]?.content ?? '') +\n `\\n\\`\\`\\`\\n>>> END NEXT CONTEXT <<<`;\n\n chunkLogger('Process started');\n\n const chunkTranslation = retryManager(async () => {\n const result = await chunkInference(\n [\n { role: 'system', content: basePrompt },\n ...(chunks[i + 1]\n ? [\n {\n role: 'system',\n content: getBaseChunkContextPrompt(),\n } as const,\n ]\n : []),\n ...(isFirstChunk\n ? []\n : [{ role: 'system', content: getPrevChunkPrompt() } as const]),\n {\n role: 'system',\n content: [\n `You are translating TARGET CHUNK (${i + 1}/${totalChunks}).`,\n `Translate ONLY the target chunk. Preserve frontmatter/code exactly.`,\n ].join('\\n'),\n },\n {\n role: 'user',\n content: `>>> TARGET CHUNK START <<<\\n${fileToTranslateCurrentChunk}\\n>>> TARGET CHUNK END <<<`,\n },\n ],\n aiOptions,\n configuration,\n aiClient,\n aiConfig\n );\n\n let processedChunk = sanitizeChunk(\n result?.fileContent,\n fileToTranslateCurrentChunk\n );\n processedChunk = fixChunkStartEndChars(\n processedChunk,\n fileToTranslateCurrentChunk\n );\n\n const isValid = validateTranslation(\n fileToTranslateCurrentChunk,\n processedChunk,\n chunkLogger\n );\n\n if (!isValid) {\n // Throwing an error here signals retryManager to try again\n throw new Error(\n `Validation failed for chunk ${i + 1}/${totalChunks}`\n );\n }\n\n return { content: processedChunk, tokens: result.tokenUsed };\n });\n\n const { content: translatedChunk, tokens } = await chunkTranslation();\n const chunkEndTime = performance.now();\n const chunkDuration = (chunkEndTime - chunkStartTime).toFixed(0);\n\n // Store Result\n translatedParts[i] = translatedChunk;\n\n if (onChunkReceive) {\n onChunkReceive(translatedChunk, i, totalChunks);\n }\n\n // Incremental Flush Strategy\n if (flushStrategy === 'incremental') {\n const isContiguous = translatedParts\n .slice(0, i + 1)\n .every((p) => p && p !== '');\n\n if (isContiguous) {\n let endIdx = 0;\n while (\n endIdx < totalChunks &&\n translatedParts[endIdx] &&\n translatedParts[endIdx] !== ''\n ) {\n endIdx++;\n }\n const currentContent = translatedParts.slice(0, endIdx).join('');\n // Write asynchronously/sync is fine here as node handles file locks reasonably well for single process\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, currentContent);\n }\n }\n\n chunkLogger(\n [\n `${colorizeNumber(tokens)} tokens used `,\n `${ANSIColors.GREY_DARK}in ${colorizeNumber(chunkDuration)}ms${ANSIColors.RESET}`,\n ].join('')\n );\n })\n );\n\n // Wait for all chunks for this specific file/locale to finish\n await Promise.all(tasks);\n\n // Final Flush\n const fullContent = translatedParts.join('');\n if (flushStrategy === 'end' || flushStrategy === 'incremental') {\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, fullContent);\n }\n\n const fileEndTime = performance.now();\n const totalDuration = ((fileEndTime - fileStartTime) / 1000).toFixed(2);\n const relativePath = relative(configuration.system.baseDir, outputFilePath);\n\n appLogger(\n `${colorize('✔', ANSIColors.GREEN)} File ${formatPath(relativePath)} completed in ${colorizeNumber(totalDuration)}s.`\n );\n\n return fullContent;\n } catch (error: any) {\n errorState.count++;\n const errorMessage = error?.message ?? JSON.stringify(error);\n appLogger(`${colorize('✖', ANSIColors.RED)} Error: ${errorMessage}`);\n if (errorState.count >= errorState.maxErrors) errorState.shouldStop = true;\n return null;\n }\n};\n"],"mappings":"+gBAoBA,MAAa,EAAgB,MAAO,CAClC,eACA,iBACA,SACA,aACA,gBACA,aACA,YACA,qBACA,WACA,WACA,gBAAgB,cAChB,iBACA,WACkD,CAClD,GAAI,EAAW,WAAY,OAAO,KAElC,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAe,CAAE,OAAQ,CAAE,OAAQ,GAAI,CAAE,CAAC,CACnE,EAAgBA,EAAAA,YAAY,KAAK,CAEvC,GAAI,CAEF,IAAM,EAASC,EAAAA,UADK,MAAA,EAAA,EAAA,UAAe,EAAc,QAAQ,CACpB,CAC/B,EAAc,EAAO,OAGrB,EAAa,IAAA,EAAA,EAAA,OADI,GAAGC,EAAAA,WAAW,UAAU,IAAA,EAAA,EAAA,YAAc,EAAa,GAAGA,EAAAA,WAAW,UAAU,IACtD,CAAE,QAAS,GAAI,CAAC,GAAGA,EAAAA,WAAW,QAEpE,EAAS,IAAA,EAAA,EAAA,OADI,GAAGA,EAAAA,WAAW,UAAU,IAAA,EAAA,EAAA,YAAc,EAAa,GAAGA,EAAAA,WAAW,UAAU,KAAA,EAAA,EAAA,cAAiB,EAAO,GAAGA,EAAAA,WAAW,UAAU,IAC1G,CAAE,QAAS,GAAI,CAAC,GAAGA,EAAAA,WAAW,QAElE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,YAAY,KAAK,CACC,GAAiB,KAAM,QAAQ,EAAE,CACjE,GAAA,EAAA,EAAA,UAAwB,EAAc,OAAO,QAAS,EAAe,CAM3E,OAJA,EACE,IAAA,EAAA,EAAA,UAAY,IAAKE,EAAAA,WAAW,MAAM,CAAC,SAAA,EAAA,EAAA,YAAmB,EAAa,CAAC,iBAAA,EAAA,EAAA,gBAA+B,EAAc,CAAC,IACnH,CAEM,QACA,EAAY,CACnB,EAAW,QACX,IAAM,EAAe,GAAO,SAAW,KAAK,UAAU,EAAM,CAG5D,OAFA,EAAU,IAAA,EAAA,EAAA,UAAY,IAAKA,EAAAA,WAAW,IAAI,CAAC,UAAU,IAAe,CAChE,EAAW,OAAS,EAAW,YAAW,EAAW,WAAa,IAC/D"}
|
|
1
|
+
{"version":3,"file":"translateFile.cjs","names":["performance","chunkText","ANSIColors","readAsset","chunkInference","sanitizeChunk","fixChunkStartEndChars","validateTranslation"],"sources":["../../../src/translateDoc/translateFile.ts"],"sourcesContent":["import { mkdirSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { dirname, relative } from 'node:path';\nimport { performance } from 'node:perf_hooks';\nimport { readAsset } from 'utils:asset';\nimport { formatLocale, formatPath } from '@intlayer/chokidar/utils';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeNumber,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport { retryManager } from '@intlayer/config/utils';\nimport { chunkText } from '../utils/calculateChunks';\nimport { chunkInference } from '../utils/chunkInference';\nimport { fixChunkStartEndChars } from '../utils/fixChunkStartEndChars';\nimport type { TranslateFileOptions } from './types';\nimport { sanitizeChunk, validateTranslation } from './validation';\n\nexport const translateFile = async ({\n baseFilePath,\n outputFilePath,\n locale,\n baseLocale,\n configuration,\n errorState,\n aiOptions,\n customInstructions,\n aiClient,\n aiConfig,\n flushStrategy = 'incremental',\n onChunkReceive,\n limit, // The Global Limiter\n}: TranslateFileOptions): Promise<string | null> => {\n if (errorState.shouldStop) return null;\n\n const appLogger = getAppLogger(configuration, { config: { prefix: '' } });\n const fileStartTime = performance.now();\n\n try {\n const fileContent = await readFile(baseFilePath, 'utf-8');\n const chunks = chunkText(fileContent);\n const totalChunks = chunks.length;\n\n const filePrefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}] `;\n const filePrefix = `${colon(filePrefixText, { colSize: 40 })}${ANSIColors.RESET}`;\n const prefixText = `${ANSIColors.GREY_DARK}[${formatPath(baseFilePath)}${ANSIColors.GREY_DARK}][${formatLocale(locale)}${ANSIColors.GREY_DARK}] `;\n const prefix = `${colon(prefixText, { colSize: 40 })}${ANSIColors.RESET}`;\n\n appLogger(\n `${filePrefix}Split into ${colorizeNumber(totalChunks)} chunks. Queuing...`\n );\n\n const basePrompt = readAsset('./prompts/TRANSLATE_PROMPT.md', 'utf-8')\n .replaceAll('{{localeName}}', `${formatLocale(locale, false)}`)\n .replaceAll('{{baseLocaleName}}', `${formatLocale(baseLocale, false)}`)\n .replace('{{applicationContext}}', aiOptions?.applicationContext ?? '-')\n .replace('{{customInstructions}}', customInstructions ?? '-');\n\n const translatedParts: string[] = new Array(totalChunks).fill('');\n\n // Fallback if no limiter is provided (runs immediately)\n const runTask = limit ?? ((fn) => fn());\n\n // MAP CHUNKS TO GLOBAL TASKS\n // This pushes ALL chunks for this file into the Global Queue immediately.\n // They will execute whenever the global concurrency slots open up.\n const tasks = chunks.map((chunk, i) =>\n runTask(async () => {\n if (errorState.shouldStop) return null;\n\n const chunkLogger = getAppLogger(configuration, {\n config: {\n prefix: `${prefix} ${ANSIColors.GREY_DARK}[${i + 1}/${totalChunks}] ${ANSIColors.RESET}`,\n },\n });\n\n const chunkStartTime = performance.now();\n const isFirstChunk = i === 0;\n const fileToTranslateCurrentChunk = chunk.content;\n\n // Context Preparation\n const getPrevChunkPrompt = () =>\n `>>> CONTEXT: PREVIOUS SOURCE CONTENT <<<\\n\\`\\`\\`\\n` +\n (chunks[i - 1]?.content ?? '') +\n `\\n\\`\\`\\`\\n>>> END PREVIOUS CONTEXT <<<`;\n\n const getBaseChunkContextPrompt = () =>\n `>>> CONTEXT: NEXT CONTENT <<<\\n\\`\\`\\`\\n` +\n (chunks[i + 1]?.content ?? '') +\n `\\n\\`\\`\\`\\n>>> END NEXT CONTEXT <<<`;\n\n chunkLogger('Process started');\n\n const chunkTranslation = retryManager(async () => {\n const result = await chunkInference(\n [\n { role: 'system', content: basePrompt },\n ...(chunks[i + 1]\n ? [\n {\n role: 'system',\n content: getBaseChunkContextPrompt(),\n } as const,\n ]\n : []),\n ...(isFirstChunk\n ? []\n : [{ role: 'system', content: getPrevChunkPrompt() } as const]),\n {\n role: 'system',\n content: [\n `You are translating TARGET CHUNK (${i + 1}/${totalChunks}).`,\n `Translate ONLY the target chunk. Preserve frontmatter/code exactly.`,\n ].join('\\n'),\n },\n {\n role: 'user',\n content: `>>> TARGET CHUNK START <<<\\n${fileToTranslateCurrentChunk}\\n>>> TARGET CHUNK END <<<`,\n },\n ],\n aiOptions,\n configuration,\n aiClient,\n aiConfig\n );\n\n let processedChunk = sanitizeChunk(\n result?.fileContent,\n fileToTranslateCurrentChunk\n );\n processedChunk = fixChunkStartEndChars(\n processedChunk,\n fileToTranslateCurrentChunk\n );\n\n const isValid = validateTranslation(\n fileToTranslateCurrentChunk,\n processedChunk,\n chunkLogger\n );\n\n if (!isValid) {\n // Throwing an error here signals retryManager to try again\n throw new Error(\n `Validation failed for chunk ${i + 1}/${totalChunks}`\n );\n }\n\n return { content: processedChunk, tokens: result.tokenUsed };\n });\n\n const { content: translatedChunk, tokens } = await chunkTranslation();\n const chunkEndTime = performance.now();\n const chunkDuration = (chunkEndTime - chunkStartTime).toFixed(0);\n\n // Store Result\n translatedParts[i] = translatedChunk;\n\n if (onChunkReceive) {\n onChunkReceive(translatedChunk, i, totalChunks);\n }\n\n // Incremental Flush Strategy\n if (flushStrategy === 'incremental') {\n const isContiguous = translatedParts\n .slice(0, i + 1)\n .every((p) => p && p !== '');\n\n if (isContiguous) {\n let endIdx = 0;\n while (\n endIdx < totalChunks &&\n translatedParts[endIdx] &&\n translatedParts[endIdx] !== ''\n ) {\n endIdx++;\n }\n const currentContent = translatedParts.slice(0, endIdx).join('');\n // Write asynchronously/sync is fine here as node handles file locks reasonably well for single process\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, currentContent);\n }\n }\n\n chunkLogger(\n [\n `${colorizeNumber(tokens)} tokens used `,\n `${ANSIColors.GREY_DARK}in ${colorizeNumber(chunkDuration)}ms${ANSIColors.RESET}`,\n ].join('')\n );\n })\n );\n\n // Wait for all chunks for this specific file/locale to finish\n await Promise.all(tasks);\n\n // Final Flush\n const fullContent = translatedParts.join('');\n if (flushStrategy === 'end' || flushStrategy === 'incremental') {\n mkdirSync(dirname(outputFilePath), { recursive: true });\n writeFileSync(outputFilePath, fullContent);\n }\n\n const fileEndTime = performance.now();\n const totalDuration = ((fileEndTime - fileStartTime) / 1000).toFixed(2);\n const relativePath = relative(configuration.system.baseDir, outputFilePath);\n\n appLogger(\n `${colorize('✔', ANSIColors.GREEN)} File ${formatPath(relativePath)} completed in ${colorizeNumber(totalDuration)}s.`\n );\n\n return fullContent;\n } catch (error: any) {\n errorState.count++;\n const errorMessage = error?.message ?? JSON.stringify(error);\n appLogger(`${colorize('✖', ANSIColors.RED)} Error: ${errorMessage}`);\n if (errorState.count >= errorState.maxErrors) errorState.shouldStop = true;\n return null;\n }\n};\n"],"mappings":"mkBAoBA,MAAa,EAAgB,MAAO,CAClC,eACA,iBACA,SACA,aACA,gBACA,aACA,YACA,qBACA,WACA,WACA,gBAAgB,cAChB,iBACA,WACkD,CAClD,GAAI,EAAW,WAAY,OAAO,KAElC,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAe,CAAE,OAAQ,CAAE,OAAQ,GAAI,CAAE,CAAC,CACnE,EAAgBA,EAAAA,YAAY,KAAK,CAEvC,GAAI,CAEF,IAA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EACE,CACE,IAAA,EAAA,EAAA,gBAAkB,EAAO,CAAC,eAC1B,GAAGE,EAAW,UAAU,MAAA,EAAA,EAAA,gBAAoB,EAAc,CAAC,IAAIA,EAAW,QAC3E,CAAC,KAAK,GAAG,CACX,EACD,CACH,CAGD,MAAM,QAAQ,IAAI,EAAM,CAGxB,IAAM,EAAc,EAAgB,KAAK,GAAG,EACxC,IAAkB,OAAS,IAAkB,kBAC/C,EAAA,EAAA,YAAA,EAAA,EAAA,SAAkB,EAAe,CAAE,CAAE,UAAW,GAAM,CAAC,EACvD,EAAA,EAAA,eAAc,EAAgB,EAAY,EAI5C,IAAM,IADcF,EAAAA,YAAY,KAAK,CACC,GAAiB,KAAM,QAAQ,EAAE,CACjE,GAAA,EAAA,EAAA,UAAwB,EAAc,OAAO,QAAS,EAAe,CAM3E,OAJA,EACE,IAAA,EAAA,EAAA,UAAY,IAAKE,EAAW,MAAM,CAAC,SAAA,EAAA,EAAA,YAAmB,EAAa,CAAC,iBAAA,EAAA,EAAA,gBAA+B,EAAc,CAAC,IACnH,CAEM,QACA,EAAY,CACnB,EAAW,QACX,IAAM,EAAe,GAAO,SAAW,KAAK,UAAU,EAAM,CAG5D,OAFA,EAAU,IAAA,EAAA,EAAA,UAAY,IAAKA,EAAW,IAAI,CAAC,UAAU,IAAe,CAChE,EAAW,OAAS,EAAW,YAAW,EAAW,WAAa,IAC/D"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`})
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../chunk-Bmb41Sf3.cjs`),t=require(`./checkConfigConsistency.cjs`);let n=require(`@intlayer/config/colors`);n=e.t(n);let r=require(`@intlayer/config/logger`),i=require(`@intlayer/api`),a=require(`@intlayer/config/utils`);const o=async(e,o=!0)=>{let s=(0,r.getAppLogger)(e);if(!(e.editor.clientId&&e.editor.clientSecret))return s([`CMS auth not provided. You can either retreive the CMS access key on`,(0,r.colorize)(`https://intlayer.org/dahboard`,n.GREY),(0,r.colorize)(`(see doc:`,n.GREY_DARK),(0,r.colorize)(`https://intlayer.org/doc/concept/cms`,n.GREY),(0,r.colorize)(`)`,n.GREY_DARK),`.`],{level:`error`}),!1;let c=(0,i.getIntlayerAPIProxy)(void 0,e);try{let i=(await c.oAuth.getOAuth2AccessToken()).data?.project;if(!i)return s(`Project not found`),!0;if(i.configuration&&o)try{let n=i.configuration;if(n.ai&&`apiKeyConfigured`in n.ai){let{apiKeyConfigured:e,...t}=n.ai;n={...n,ai:t}}t.checkConfigConsistency(n,e)}catch{s([`Remote configuration is not up to date. The project configuration does not match the local configuration.`,`You can push the configuration by running`,(0,r.colorize)(`npx intlayer configuration push`,n.CYAN),(0,r.colorize)(`(see doc:`,n.GREY_DARK),(0,r.colorize)(`https://intlayer.org/doc/concept/cli/push`,n.GREY),(0,r.colorize)(`)`,n.GREY_DARK),`.`],{level:`warn`})}}catch(e){return s((0,a.extractErrorMessage)(e),{level:`error`}),!1}return!0},s=async(e,t,i=!0)=>{let a=(0,r.getAppLogger)(e),s=!!(e.editor.clientId&&e.editor.clientSecret),c=e.ai?.provider===`ollama`||t?.provider===`ollama`;return e.ai?.apiKey||t?.apiKey||c?!0:s?await o(e,i):(a([`AI options or API key not provided. You can either retreive the CMS access key on`,(0,r.colorize)(`https://intlayer.org/dahboard`,n.GREY),(0,r.colorize)(`(see doc:`,n.GREY_DARK),(0,r.colorize)(`https://intlayer.org/doc/concept/cms`,n.GREY),(0,r.colorize)(`)`,n.GREY_DARK),`. Alternatively, you can add your own OpenAI API key in the settings`,(0,r.colorize)(`(see doc:`,n.GREY_DARK),(0,r.colorize)(`https://intlayer.org/doc/concept/configuration`,n.GREY),(0,r.colorize)(`)`,n.GREY_DARK),`.`],{level:`error`}),!1)};exports.checkAIAccess=s,exports.checkCMSAuth=o;
|
|
2
2
|
//# sourceMappingURL=checkAccess.cjs.map
|