@intlayer/cli 8.4.2 → 8.4.4
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/cli.cjs +1 -1
- package/dist/cjs/cli.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/cli.mjs +1 -1
- package/dist/esm/cli.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,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,EAAA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,CANYC,EAAAA,oBACd,EAAa,QACb,EACA,EACD,CAGC,MAAU,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,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,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AAAA,sBACf,EACA,EAAa,QACd,CASG,CANYC,EAAAA,oBACd,EAAa,QACb,EACA,EACD,CAGC,MAAU,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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AAO,eAAe,SAAW,GAAA,EAAA,EAAA,UAAa,IAAKA,EAAW,MAAM,EAAA,EAAA,EAAA,cAAgB,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,GAA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AAW,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,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,OA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AAe,CAAE,CAAE,UAAW,GAAM,CAAC,EACvD,EAAA,EAAA,eAAc,EAAgB,EAAe,CAIjD,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
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkAccess.cjs","names":["ANSIColors"],"sources":["../../../src/utils/checkAccess.ts"],"sourcesContent":["import type { AIOptions } from '@intlayer/api';\nimport { getIntlayerAPIProxy } from '@intlayer/api';\nimport
|
|
1
|
+
{"version":3,"file":"checkAccess.cjs","names":["ANSIColors"],"sources":["../../../src/utils/checkAccess.ts"],"sourcesContent":["import type { AIOptions } from '@intlayer/api';\nimport { getIntlayerAPIProxy } from '@intlayer/api';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport { extractErrorMessage } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { checkConfigConsistency } from './checkConfigConsistency';\n\nexport const checkCMSAuth = async (\n configuration: IntlayerConfig,\n shouldCheckConfigConsistency: boolean = true\n): Promise<boolean> => {\n const appLogger = getAppLogger(configuration);\n\n const hasCMSAuth =\n configuration.editor.clientId && configuration.editor.clientSecret;\n if (!hasCMSAuth) {\n appLogger(\n [\n 'CMS auth not provided. You can either retreive the CMS access key on',\n colorize('https://intlayer.org/dahboard', ANSIColors.GREY),\n colorize('(see doc:', ANSIColors.GREY_DARK),\n colorize('https://intlayer.org/doc/concept/cms', ANSIColors.GREY),\n colorize(')', ANSIColors.GREY_DARK),\n '.',\n ],\n {\n level: 'error',\n }\n );\n\n return false;\n }\n const intlayerAPI = getIntlayerAPIProxy(undefined, configuration);\n\n try {\n const result = await intlayerAPI.oAuth.getOAuth2AccessToken();\n\n const project = result.data?.project;\n\n if (!project) {\n appLogger('Project not found');\n\n return true;\n }\n\n if (project.configuration && shouldCheckConfigConsistency) {\n try {\n let remoteConfigToCheck = project.configuration;\n\n // Remove server-side computed flags (apiKeyConfigured)\n // We use destructuring + spread to avoid the 'delete' operator (performance)\n if (\n remoteConfigToCheck.ai &&\n 'apiKeyConfigured' in remoteConfigToCheck.ai\n ) {\n const { apiKeyConfigured, ...restAi } = remoteConfigToCheck.ai as any;\n\n remoteConfigToCheck = {\n ...remoteConfigToCheck,\n ai: restAi,\n };\n }\n\n // Recursively check if project.configuration (subset) matches configuration (superset)\n checkConfigConsistency(remoteConfigToCheck, configuration);\n } catch {\n appLogger(\n [\n 'Remote configuration is not up to date. The project configuration does not match the local configuration.',\n 'You can push the configuration by running',\n colorize('npx intlayer configuration push', ANSIColors.CYAN),\n colorize('(see doc:', ANSIColors.GREY_DARK),\n colorize(\n 'https://intlayer.org/doc/concept/cli/push',\n ANSIColors.GREY\n ),\n colorize(')', ANSIColors.GREY_DARK),\n '.',\n ],\n {\n level: 'warn',\n }\n );\n }\n }\n } catch (error) {\n const message = extractErrorMessage(error);\n\n appLogger(message, {\n level: 'error',\n });\n return false;\n }\n\n return true;\n};\n\nexport const checkAIAccess = async (\n configuration: IntlayerConfig,\n aiOptions?: AIOptions,\n shouldCheckConfigConsistency: boolean = true\n): Promise<boolean> => {\n const appLogger = getAppLogger(configuration);\n\n const hasCMSAuth = Boolean(\n configuration.editor.clientId && configuration.editor.clientSecret\n );\n const isOllama =\n configuration.ai?.provider === 'ollama' || aiOptions?.provider === 'ollama';\n const hasHisOwnAIAPIKey = Boolean(\n configuration.ai?.apiKey || aiOptions?.apiKey\n );\n\n if (hasHisOwnAIAPIKey || isOllama) {\n return true;\n }\n\n // User need to provide either his own AI API key or the CMS auth\n if (!hasCMSAuth) {\n appLogger(\n [\n 'AI options or API key not provided. You can either retreive the CMS access key on',\n colorize('https://intlayer.org/dahboard', ANSIColors.GREY),\n colorize('(see doc:', ANSIColors.GREY_DARK),\n colorize('https://intlayer.org/doc/concept/cms', ANSIColors.GREY),\n colorize(')', ANSIColors.GREY_DARK),\n '. Alternatively, you can add your own OpenAI API key in the settings',\n colorize('(see doc:', ANSIColors.GREY_DARK),\n colorize(\n 'https://intlayer.org/doc/concept/configuration',\n ANSIColors.GREY\n ),\n colorize(')', ANSIColors.GREY_DARK),\n '.',\n ],\n {\n level: 'error',\n }\n );\n\n return false;\n }\n\n // If the user do not have his own AI API key, we need to check the CMS auth\n return await checkCMSAuth(configuration, shouldCheckConfigConsistency);\n};\n"],"mappings":"gTAQA,MAAa,EAAe,MAC1B,EACA,EAAwC,KACnB,CACrB,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAc,CAI7C,GAAI,EADF,EAAc,OAAO,UAAY,EAAc,OAAO,cAgBtD,OAdA,EACE,CACE,sFACS,gCAAiCA,EAAW,KAAK,gBACjD,YAAaA,EAAW,UAAU,gBAClC,uCAAwCA,EAAW,KAAK,gBACxD,IAAKA,EAAW,UAAU,CACnC,IACD,CACD,CACE,MAAO,QACR,CACF,CAEM,GAET,IAAM,GAAA,EAAA,EAAA,qBAAkC,IAAA,GAAW,EAAc,CAEjE,GAAI,CAGF,IAAM,GAFS,MAAM,EAAY,MAAM,sBAAsB,EAEtC,MAAM,QAE7B,GAAI,CAAC,EAGH,OAFA,EAAU,oBAAoB,CAEvB,GAGT,GAAI,EAAQ,eAAiB,EAC3B,GAAI,CACF,IAAI,EAAsB,EAAQ,cAIlC,GACE,EAAoB,IACpB,qBAAsB,EAAoB,GAC1C,CACA,GAAM,CAAE,mBAAkB,GAAG,GAAW,EAAoB,GAE5D,EAAsB,CACpB,GAAG,EACH,GAAI,EACL,CAIH,EAAA,uBAAuB,EAAqB,EAAc,MACpD,CACN,EACE,CACE,4GACA,2DACS,kCAAmCA,EAAW,KAAK,gBACnD,YAAaA,EAAW,UAAU,gBAEzC,4CACAA,EAAW,KACZ,gBACQ,IAAKA,EAAW,UAAU,CACnC,IACD,CACD,CACE,MAAO,OACR,CACF,QAGE,EAAO,CAMd,OAHA,GAAA,EAAA,EAAA,qBAFoC,EAAM,CAEvB,CACjB,MAAO,QACR,CAAC,CACK,GAGT,MAAO,IAGI,EAAgB,MAC3B,EACA,EACA,EAAwC,KACnB,CACrB,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAc,CAEvC,EAAa,GACjB,EAAc,OAAO,UAAY,EAAc,OAAO,cAElD,EACJ,EAAc,IAAI,WAAa,UAAY,GAAW,WAAa,SAoCrE,OAlCE,EAAc,IAAI,QAAU,GAAW,QAGhB,EAChB,GAIJ,EA0BE,MAAM,EAAa,EAAe,EAA6B,EAzBpE,EACE,CACE,mGACS,gCAAiCA,EAAW,KAAK,gBACjD,YAAaA,EAAW,UAAU,gBAClC,uCAAwCA,EAAW,KAAK,gBACxD,IAAKA,EAAW,UAAU,CACnC,sFACS,YAAaA,EAAW,UAAU,gBAEzC,iDACAA,EAAW,KACZ,gBACQ,IAAKA,EAAW,UAAU,CACnC,IACD,CACD,CACE,MAAO,QACR,CACF,CAEM"}
|
|
@@ -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(`./checkAccess.cjs`);let n=require(`@intlayer/config/colors`);n=e.t(n);let r=require(`@intlayer/config/logger`);globalThis.AI_SDK_LOG_WARNINGS=!1;const i=(e,t)=>{t([(0,r.colorize)(`Provider:`,n.GREY_DARK),(0,r.colorize)(e?.provider??`(default)`,n.BLUE),(0,r.colorize)(`- Model:`,n.GREY_DARK),(0,r.colorize)(e?.model??`(default)`,n.BLUE),(0,r.colorize)(`- API Key:`,n.GREY_DARK),(0,r.colorize)(e?.apiKey?`✓`:`(not set)`,n.BLUE)])},a=async(e,a)=>{let o=(0,r.getAppLogger)(e);if(a?.apiKey||a?.provider===`ollama`||e.ai?.apiKey||e.ai?.provider===`ollama`){let s;try{s=await import(`@intlayer/ai`)}catch{o([(0,r.colorize)(`Using your API key, you can install the`,n.GREY),(0,r.colorize)(`@intlayer/ai`,n.GREY_LIGHT),(0,r.colorize)(`package to run the process locally, with no dependency on the Intlayer server`,n.GREY)],{level:`warn`});let s=await t.checkAIAccess(e,a);return i(a??{},o),{isCustomAI:!1,hasAIAccess:s}}o([(0,r.colorize)(`@intlayer/ai`,n.GREY_LIGHT),(0,r.colorize)(`found - Run process locally`,n.GREY_DARK)]);let c=await s.getAIConfig({userOptions:a,accessType:[`public`]});return i(a??{},o),{aiClient:s,aiConfig:c,isCustomAI:!0,hasAIAccess:!0}}let s=await t.checkAIAccess(e,a);return i(a??{},o),{isCustomAI:!1,hasAIAccess:s}};exports.setupAI=a;
|
|
2
2
|
//# sourceMappingURL=setupAI.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"setupAI.cjs","names":["ANSIColors","checkAIAccess"],"sources":["../../../src/utils/setupAI.ts"],"sourcesContent":["import type { AIConfig, AIOptions } from '@intlayer/ai';\nimport {
|
|
1
|
+
{"version":3,"file":"setupAI.cjs","names":["ANSIColors","checkAIAccess"],"sources":["../../../src/utils/setupAI.ts"],"sourcesContent":["import type { AIConfig, AIOptions } from '@intlayer/ai';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger, type logger } from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { checkAIAccess } from './checkAccess';\n\nexport type AIClient = typeof import('@intlayer/ai');\n\ntype SetupAIResult = {\n aiClient?: AIClient;\n aiConfig?: AIConfig;\n isCustomAI: boolean;\n hasAIAccess: boolean;\n};\n\n// Disable warnings from the AI SDK\nglobalThis.AI_SDK_LOG_WARNINGS = false;\n\nconst logAIConfig = (aiOptions: AIOptions, appLogger: typeof logger) => {\n appLogger([\n colorize('Provider:', ANSIColors.GREY_DARK),\n colorize(aiOptions?.provider ?? '(default)', ANSIColors.BLUE),\n colorize('- Model:', ANSIColors.GREY_DARK),\n colorize(aiOptions?.model ?? '(default)', ANSIColors.BLUE),\n colorize('- API Key:', ANSIColors.GREY_DARK),\n colorize(aiOptions?.apiKey ? '✓' : '(not set)', ANSIColors.BLUE),\n ]);\n};\n\n/**\n * Checks if the @intlayer/ai package is available and configured when an API key is provided.\n * If API key is present but package is missing, logs a warning.\n * Also checks if the user has access to AI (either via local key or CMS auth).\n */\nexport const setupAI = async (\n configuration: IntlayerConfig,\n aiOptions?: AIOptions\n): Promise<SetupAIResult | undefined> => {\n const appLogger = getAppLogger(configuration);\n\n const isLocalAI =\n aiOptions?.apiKey ||\n aiOptions?.provider === 'ollama' ||\n configuration.ai?.apiKey ||\n configuration.ai?.provider === 'ollama';\n\n if (isLocalAI) {\n // Try to import the AI package for local AI usage\n let aiClient: AIClient | undefined;\n\n try {\n aiClient = await import('@intlayer/ai');\n } catch {\n // Package not installed - log warning and fall back to backend\n appLogger(\n [\n colorize('Using your API key, you can install the', ANSIColors.GREY),\n colorize('@intlayer/ai', ANSIColors.GREY_LIGHT),\n colorize(\n 'package to run the process locally, with no dependency on the Intlayer server',\n ANSIColors.GREY\n ),\n ],\n {\n level: 'warn',\n }\n );\n\n // Fall back to backend API check\n const hasAIAccess = await checkAIAccess(configuration, aiOptions);\n logAIConfig(aiOptions ?? {}, appLogger);\n return {\n isCustomAI: false,\n hasAIAccess,\n };\n }\n\n // Package found - now configure it (errors here should propagate, not fall back)\n appLogger([\n colorize('@intlayer/ai', ANSIColors.GREY_LIGHT),\n colorize('found - Run process locally', ANSIColors.GREY_DARK),\n ]);\n\n const aiConfig = await aiClient.getAIConfig({\n userOptions: aiOptions,\n accessType: ['public'],\n });\n\n logAIConfig(aiOptions ?? {}, appLogger);\n\n return {\n aiClient,\n aiConfig,\n isCustomAI: true,\n hasAIAccess: true, // Local AI always has access\n };\n }\n\n // No local AI configured - use backend API\n const hasAIAccess = await checkAIAccess(configuration, aiOptions);\n logAIConfig(aiOptions ?? {}, appLogger);\n\n return {\n isCustomAI: false,\n hasAIAccess,\n };\n};\n"],"mappings":"sOAgBA,WAAW,oBAAsB,GAEjC,MAAM,GAAe,EAAsB,IAA6B,CACtE,EAAU,gBACC,YAAaA,EAAW,UAAU,gBAClC,GAAW,UAAY,YAAaA,EAAW,KAAK,gBACpD,WAAYA,EAAW,UAAU,gBACjC,GAAW,OAAS,YAAaA,EAAW,KAAK,gBACjD,aAAcA,EAAW,UAAU,gBACnC,GAAW,OAAS,IAAM,YAAaA,EAAW,KAAK,CACjE,CAAC,EAQS,EAAU,MACrB,EACA,IACuC,CACvC,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAc,CAQ7C,GALE,GAAW,QACX,GAAW,WAAa,UACxB,EAAc,IAAI,QAClB,EAAc,IAAI,WAAa,SAElB,CAEb,IAAI,EAEJ,GAAI,CACF,EAAW,MAAM,OAAO,qBAClB,CAEN,EACE,gBACW,0CAA2CA,EAAW,KAAK,gBAC3D,eAAgBA,EAAW,WAAW,gBAE7C,gFACAA,EAAW,KACZ,CACF,CACD,CACE,MAAO,OACR,CACF,CAGD,IAAM,EAAc,MAAMC,EAAAA,cAAc,EAAe,EAAU,CAEjE,OADA,EAAY,GAAa,EAAE,CAAE,EAAU,CAChC,CACL,WAAY,GACZ,cACD,CAIH,EAAU,EAAA,EAAA,EAAA,UACC,eAAgBD,EAAW,WAAW,EAAA,EAAA,EAAA,UACtC,8BAA+BA,EAAW,UAAU,CAC9D,CAAC,CAEF,IAAM,EAAW,MAAM,EAAS,YAAY,CAC1C,YAAa,EACb,WAAY,CAAC,SAAS,CACvB,CAAC,CAIF,OAFA,EAAY,GAAa,EAAE,CAAE,EAAU,CAEhC,CACL,WACA,WACA,WAAY,GACZ,YAAa,GACd,CAIH,IAAM,EAAc,MAAMC,EAAAA,cAAc,EAAe,EAAU,CAGjE,OAFA,EAAY,GAAa,EAAE,CAAE,EAAU,CAEhC,CACL,WAAY,GACZ,cACD"}
|
package/dist/esm/auth/login.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{openBrowser as e}from"../utils/openBrowser.mjs";import{logConfigDetails as t}from"@intlayer/chokidar/cli";import
|
|
1
|
+
import{openBrowser as e}from"../utils/openBrowser.mjs";import{logConfigDetails as t}from"@intlayer/chokidar/cli";import*as n from"@intlayer/config/colors";import{colorize as r,colorizePath as i,getAppLogger as a}from"@intlayer/config/logger";import{getConfiguration as o}from"@intlayer/config/node";import s from"node:http";import{URL as c}from"node:url";const l=async l=>{let u=o(l.configOptions);t(l?.configOptions);let d=a(u),f=l.cmsUrl??u.editor.cmsURL;return new Promise(t=>{let a=s.createServer((e,o)=>{let s=new c(e.url??``,`http://${e.headers.host}`);if(o.setHeader(`Access-Control-Allow-Origin`,`*`),o.setHeader(`Access-Control-Allow-Methods`,`GET, OPTIONS`),o.setHeader(`Access-Control-Allow-Headers`,`Content-Type`),e.method===`OPTIONS`){o.writeHead(204),o.end();return}if(s.pathname===`/callback`){let e=s.searchParams.get(`clientId`),c=s.searchParams.get(`clientSecret`);e&&c?(d(``),d(`Log in successful. Client ID and Client Secret received.`),d(``),d([`1. Insert the Client ID and Client Secret in your`,i(`.env`),`file:`]),d(r(`--------------------------------`,n.GREY_DARK)),d([r(`INTLAYER_CLIENT_ID=`,n.GREY_LIGHT),r(e,n.BLUE)].join(``)),d([r(`INTLAYER_CLIENT_SECRET=`,n.GREY_LIGHT),r(c,n.BLUE)].join(``)),d(r(`--------------------------------`,n.GREY_DARK)),d(``),d(`2. Insert in your Intlayer configuration file:`),d(r(`--------------------------------`,n.GREY_DARK)),[`${n.GREY_LIGHT}{`,` editor: {`,` cmsURL: '${i(f,void 0,n.GREY_LIGHT)}',`,` clientId: '${r(`process.env.INTLAYER_CLIENT_ID`,n.BLUE,n.GREY_LIGHT)}',`,` clientSecret: '${r(`process.env.INTLAYER_CLIENT_SECRET`,n.BLUE,n.GREY_LIGHT)}',`,` },`,`}`].forEach(e=>{d(e)}),d(r(`--------------------------------`,n.GREY_DARK)),o.writeHead(200,{"Content-Type":`text/html`}),o.end(`
|
|
2
2
|
<!DOCTYPE html>
|
|
3
3
|
<html lang="en" data-theme="dark">
|
|
4
4
|
<head>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"login.mjs","names":[],"sources":["../../../src/auth/login.ts"],"sourcesContent":["import http from 'node:http';\nimport { URL } from 'node:url';\nimport { logConfigDetails } from '@intlayer/chokidar/cli';\nimport {
|
|
1
|
+
{"version":3,"file":"login.mjs","names":[],"sources":["../../../src/auth/login.ts"],"sourcesContent":["import http from 'node:http';\nimport { URL } from 'node:url';\nimport { logConfigDetails } from '@intlayer/chokidar/cli';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, colorizePath, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { openBrowser } from '../utils/openBrowser';\n\ntype LoginOptions = {\n cmsUrl?: string;\n configOptions?: GetConfigurationOptions;\n};\n\nexport const login = async (options: LoginOptions) => {\n const configuration = getConfiguration(options.configOptions);\n logConfigDetails(options?.configOptions);\n\n const logger = getAppLogger(configuration);\n\n const cmsUrl = options.cmsUrl ?? configuration.editor.cmsURL;\n\n return new Promise<void>((resolve) => {\n const server = http.createServer((req, res) => {\n const url = new URL(req.url ?? '', `http://${req.headers.host}`);\n\n // Set CORS headers\n res.setHeader('Access-Control-Allow-Origin', '*');\n res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');\n res.setHeader('Access-Control-Allow-Headers', 'Content-Type');\n\n if (req.method === 'OPTIONS') {\n res.writeHead(204);\n res.end();\n return;\n }\n\n if (url.pathname === '/callback') {\n const clientId = url.searchParams.get('clientId');\n const clientSecret = url.searchParams.get('clientSecret');\n\n if (clientId && clientSecret) {\n logger('');\n logger('Log in successful. Client ID and Client Secret received.');\n\n logger('');\n logger([\n '1. Insert the Client ID and Client Secret in your',\n colorizePath('.env'),\n 'file:',\n ]);\n logger(\n colorize('--------------------------------', ANSIColors.GREY_DARK)\n );\n logger(\n [\n colorize('INTLAYER_CLIENT_ID=', ANSIColors.GREY_LIGHT),\n colorize(clientId, ANSIColors.BLUE),\n ].join('')\n );\n logger(\n [\n colorize('INTLAYER_CLIENT_SECRET=', ANSIColors.GREY_LIGHT),\n colorize(clientSecret, ANSIColors.BLUE),\n ].join('')\n );\n logger(\n colorize('--------------------------------', ANSIColors.GREY_DARK)\n );\n logger('');\n logger('2. Insert in your Intlayer configuration file:');\n logger(\n colorize('--------------------------------', ANSIColors.GREY_DARK)\n );\n [\n `${ANSIColors.GREY_LIGHT}{`,\n ` editor: {`,\n ` cmsURL: '${colorizePath(cmsUrl, undefined, ANSIColors.GREY_LIGHT)}',`,\n ` clientId: '${colorize('process.env.INTLAYER_CLIENT_ID', ANSIColors.BLUE, ANSIColors.GREY_LIGHT)}',`,\n ` clientSecret: '${colorize('process.env.INTLAYER_CLIENT_SECRET', ANSIColors.BLUE, ANSIColors.GREY_LIGHT)}',`,\n ` },`,\n `}`,\n ].forEach((line) => {\n logger(line);\n });\n logger(\n colorize('--------------------------------', ANSIColors.GREY_DARK)\n );\n\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(`\n <!DOCTYPE html>\n <html lang=\"en\" data-theme=\"dark\">\n <head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Intlayer CLI Login</title>\n <style>\n :root {\n --color-background: rgba(23, 23, 23);\n --color-card: rgba(39, 39, 39);\n --color-text: rgba(255, 245, 237);\n --color-neutral: rgba(93, 93, 93);\n --font-sans: \"Inter\", -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;\n }\n \n * {\n box-sizing: border-box;\n }\n \n body {\n font-family: var(--font-sans);\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n margin: 0;\n padding: 1rem;\n background-color: var(--color-background);\n color: var(--color-text);\n }\n \n .container {\n text-align: center;\n padding: 2rem;\n border-radius: 1rem;\n background-color: var(--color-card);\n box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);\n max-width: 400px;\n width: 100%;\n }\n \n h1 {\n margin: 0 0 1rem 0;\n font-size: 1.5rem;\n font-weight: 700;\n color: var(--color-text);\n }\n \n p {\n color: var(--color-neutral);\n margin: 0 0 1.5rem 0;\n line-height: 1.5;\n }\n </style>\n </head>\n <body>\n <div class=\"container\">\n <h1>Login Successful</h1>\n <p>You have successfully logged in to Intlayer CLI. You can now close this tab and return to your terminal.</p>\n </div>\n <script>\n // Attempt to close the window\n window.close();\n \n // Fallback: if window.close() doesn't work, show a message\n setTimeout(() => {\n window.close();\n }, 1000);\n </script>\n </body>\n </html>\n `);\n\n server.close(() => {\n resolve();\n process.exit(0);\n });\n } else {\n res.writeHead(400, { 'Content-Type': 'text/plain' });\n res.end('Missing parameters');\n }\n } else {\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Not found');\n }\n });\n\n server.listen(0, () => {\n const address = server.address();\n const port = typeof address === 'object' && address ? address.port : 0;\n const state = Math.random().toString(36).substring(7);\n\n const websiteUrl =\n cmsUrl ?? process.env.INTLAYER_SITE_URL ?? 'http://localhost:3000';\n const loginUrl = `${websiteUrl}/en/auth/cli-login?port=${port}&state=${state}`;\n\n logger('Opening browser for login...');\n logger(`If browser does not open, visit: ${colorizePath(loginUrl)}`);\n\n openBrowser(loginUrl);\n });\n });\n};\n"],"mappings":"mWAgBA,MAAa,EAAQ,KAAO,IAA0B,CACpD,IAAM,EAAgB,EAAiB,EAAQ,cAAc,CAC7D,EAAiB,GAAS,cAAc,CAExC,IAAM,EAAS,EAAa,EAAc,CAEpC,EAAS,EAAQ,QAAU,EAAc,OAAO,OAEtD,OAAO,IAAI,QAAe,GAAY,CACpC,IAAM,EAAS,EAAK,cAAc,EAAK,IAAQ,CAC7C,IAAM,EAAM,IAAI,EAAI,EAAI,KAAO,GAAI,UAAU,EAAI,QAAQ,OAAO,CAOhE,GAJA,EAAI,UAAU,8BAA+B,IAAI,CACjD,EAAI,UAAU,+BAAgC,eAAe,CAC7D,EAAI,UAAU,+BAAgC,eAAe,CAEzD,EAAI,SAAW,UAAW,CAC5B,EAAI,UAAU,IAAI,CAClB,EAAI,KAAK,CACT,OAGF,GAAI,EAAI,WAAa,YAAa,CACh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Y,EAEtB,CAEF,EAAO,OAAO,MAAS,CACrB,IAAM,EAAU,EAAO,SAAS,CAC1B,EAAO,OAAO,GAAY,UAAY,EAAU,EAAQ,KAAO,EAC/D,EAAQ,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,UAAU,EAAE,CAI/C,EAAW,GADf,GAAU,QAAQ,IAAI,mBAAqB,wBACd,0BAA0B,EAAK,SAAS,IAEvE,EAAO,+BAA+B,CACtC,EAAO,oCAAoC,EAAa,EAAS,GAAG,CAEpE,EAAY,EAAS,EACrB,EACF"}
|
package/dist/esm/cli.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./editor-D8BGlLzF.mjs";import{extract as t}from"./extract.mjs";import{listProjectsCommand as n}from"./listProjects.mjs";import{liveSync as r}from"./liveSync.mjs";import{listContentDeclaration as i}from"./listContentDeclaration.mjs";import{init as a}from"./init.mjs";import{watchContentDeclaration as o}from"./watch.mjs";import{login as s}from"./auth/login.mjs";import{build as c}from"./build.mjs";import{runCI as l}from"./ci.mjs";import{getConfig as ee}from"./config.mjs";import{testMissingTranslations as u}from"./test/test.mjs";import{fill as te}from"./fill/fill.mjs";import{initSkills as d}from"./initSkills.mjs";import{initMCP as ne}from"./initMCP.mjs";import{pull as f}from"./pull.mjs";import{push as p}from"./push/push.mjs";import{pushConfig as re}from"./pushConfig.mjs";import"./_utils_asset-B187VPMw.mjs";import{reviewDoc as ie}from"./reviewDoc/reviewDoc.mjs";import{searchDoc as ae}from"./searchDoc.mjs";import{translateDoc as oe}from"./translateDoc/translateDoc.mjs";import{getParentPackageJSON as m}from"./utils/getParentPackageJSON.mjs";import{dirname as h}from"node:path";import{setPrefix as se}from"@intlayer/config/logger";import{getConfiguration as g}from"@intlayer/config/node";import{fileURLToPath as _}from"node:url";import{Command as v}from"commander";const y=typeof import.meta.url==`string`?h(_(import.meta.url)):__dirname,b=m(y),x=[[`--env-file [envFile]`,`Environment file`],[`-e, --env [env]`,`Environment`],[`--base-dir [baseDir]`,`Base directory`],[`--no-cache [noCache]`,`No cache`],...[[`--verbose`,`Verbose (default to true using CLI)`],[`--prefix [prefix]`,`Prefix`]]],S=[[`--provider [provider]`,`Provider`],[`--temperature [temperature]`,`Temperature`],[`--model [model]`,`Model`],[`--api-key [apiKey]`,`Provider API key`],[`--custom-prompt [prompt]`,`Custom prompt`],[`--application-context [applicationContext]`,`Application context`],[`--data-serialization [dataSerialization]`,`Data serialization`]],C=[[`--git-diff [gitDiff]`,`Git diff mode - Check git diff between two refs`],[`--git-diff-base [gitDiffBase]`,`Git diff base ref`],[`--git-diff-current [gitDiffCurrent]`,`Git diff current ref`],[`--uncommitted [uncommitted]`,`Uncommitted`],[`--unpushed [unpushed]`,`Unpushed`],[`--untracked [untracked]`,`Untracked`]],w=(e,t)=>t.filter(t=>e[t]!==void 0),T=(e,t)=>(t.forEach(([t,n])=>{e.option(t,n)}),e),E=e=>Object.fromEntries(Object.entries(e).filter(([e,t])=>t!==void 0)),D=e=>T(e,x),O=e=>T(e,S),k=e=>T(e,C),A=e=>{let{apiKey:t,provider:n,model:r,temperature:i,applicationContext:a,customPrompt:o,dataSerialization:s}=e,c=g(),{ai:l}=c;return E({...l,apiKey:t??c.ai?.apiKey,provider:n??c.ai?.provider,model:r??c.ai?.model,temperature:i??c.ai?.temperature,applicationContext:a??c.ai?.applicationContext,customPrompt:o??c.ai?.customPrompt,dataSerialization:s??c.ai?.dataSerialization})},j=[`gitDiff`,`gitDiffBase`,`gitDiffCurrent`,`uncommitted`,`unpushed`,`untracked`],M=e=>{if(w(e,j).length===0)return;let{gitDiff:t,gitDiffBase:n,gitDiffCurrent:r,uncommitted:i,unpushed:a,untracked:o}=e;return E({mode:[t&&`gitDiff`,i&&`uncommitted`,a&&`unpushed`,o&&`untracked`].filter(Boolean),baseRef:n,currentRef:r,absolute:!0})},N=[`baseDir`,`env`,`envFile`,`verbose`,`prefix`,`checkTypes`],P=e=>{if(w(e,N).length===0)return;let{baseDir:t,env:n,envFile:r,verbose:i,noCache:a,checkTypes:o}=e,s=E({mode:i===void 0?void 0:i?`verbose`:`default`}),c=E({checkTypes:o}),l=E({log:Object.keys(s).length>0?s:void 0,build:Object.keys(c).length>0?c:void 0});return E({baseDir:t,env:n,envFile:r,override:Object.keys(l).length>0?l:void 0,cache:a===void 0?void 0:!a})},F=()=>{process.argv.includes(`--with`)||se(``);let m=new v;m.version(b.version).description(`Intlayer CLI`),m.command(`version`).description(`Print the Intlayer CLI version`).action(()=>{console.log(b.version??`unknown`)});let h=m.command(`login`).description(`Login to Intlayer`).option(`--cms-url [cmsUrl]`,`CMS URL`);D(h),h.action(e=>{let t=P(e)??{override:{log:{prefix:``,mode:`verbose`}}};return s({cmsUrl:e.cmsUrl,configOptions:t})});let g=m.command(`init`).description(`Initialize Intlayer in the project`).option(`--project-root [projectRoot]`,`Project root directory`).action(e=>a(e.projectRoot));g.command(`skills`).description(`Initialize Intlayer skills in the project`).option(`--project-root [projectRoot]`,`Project root directory`).action(e=>d(e.projectRoot)),g.command(`mcp`).description(`Initialize Intlayer MCP server in the project`).option(`--project-root [projectRoot]`,`Project root directory`).action(e=>ne(e.projectRoot));let _=m.command(`dictionary`).alias(`dictionaries`).alias(`dic`).description(`Dictionaries operations`),y={description:`Build the dictionaries`,options:[[`-w, --watch`,`Watch for changes`],[`--skip-prepare`,`Skip the prepare step`],[`--with [with...]`,`Start command in parallel with the build`],[`--check-types`,`Check TypeScript type and log errors`]]},x=_.command(`build`).description(y.description);T(x,y.options),D(x),x.action(e=>{c({...e,configOptions:P(e)})});let S=m.command(`build`).description(y.description);T(S,y.options),D(S),S.action(e=>{c({...e,configOptions:P(e)})});let C={description:`Watch the dictionaries changes`,options:[[`--with [with...]`,`Start command in parallel with the build`]]},w=_.command(`watch`).description(y.description);T(w,C.options),D(w),w.action(e=>{o({...e,configOptions:P(e)})});let E=m.command(`watch`).description(y.description);T(E,C.options),D(E),E.action(e=>{o({...e,configOptions:P(e)})});let j={description:`Pull dictionaries from the server`,options:[[`-d, --dictionaries [ids...]`,`List of dictionary IDs to pull`],[`--dictionary [ids...]`,`List of dictionary IDs to pull (alias for --dictionaries)`],[`--new-dictionaries-path [path]`,`Path to save the new dictionaries`],[`--newDictionariesPath [path]`,`[alias] Path to save the new dictionaries`]]},N=_.command(`pull`).description(j.description);T(N,j.options),D(N),N.action(e=>{let t=[...e.dictionaries??[],...e.dictionary??[]];f({...e,dictionaries:t.length>0?t:void 0,configOptions:{...e.configOptions,baseDir:e.baseDir}})});let F=m.command(`pull`).description(j.description);T(F,j.options),D(F),F.action(e=>{let t=[...e.dictionaries??[],...e.dictionary??[]];f({...e,dictionaries:t.length>0?t:void 0,configOptions:P(e)})});let I={description:`Push all dictionaries. Create or update the pushed dictionaries`,options:[[`-d, --dictionaries [ids...]`,`List of dictionary IDs to push`],[`--dictionary [ids...]`,`List of dictionary IDs to push (alias for --dictionaries)`],[`-r, --delete-locale-dictionary`,`Delete the local dictionaries after pushing`],[`-k, --keep-locale-dictionary`,`Keep the local dictionaries after pushing`],[`--deleteLocaleDictionary`,`[alias] Delete the local dictionaries after pushing`],[`--keepLocaleDictionary`,`[alias] Keep the local dictionaries after pushing`],[`--build [build]`,`Build the dictionaries before pushing to ensure the content is up to date. True will force the build, false will skip the build, undefined will allow using the cache of the build`]]},L=_.command(`push`).description(I.description);T(L,I.options),D(L),k(L),L.action(e=>{let t=[...e.dictionaries||[],...e.dictionary||[]];return p({...e,dictionaries:t.length>0?t:void 0,gitOptions:M(e),configOptions:P(e)})});let R=m.command(`push`).description(I.description);T(R,I.options),D(R),k(R),R.action(e=>{let t=[...e.dictionaries||[],...e.dictionary||[]];return p({...e,dictionaries:t.length>0?t:void 0,gitOptions:M(e),configOptions:P(e)})});let z=m.command(`configuration`).alias(`config`).alias(`conf`).description(`Configuration operations`),B=z.command(`get`).description(`Get the configuration`);D(B),B.action(e=>{ee({...e,configOptions:P(e)})});let V=z.command(`push`).description(`Push the configuration`);D(V),V.action(e=>{re({...e,configOptions:P(e)})}),m.command(`projects`).alias(`project`).description(`List Intlayer projects`).command(`list`).description(`List all Intlayer projects in the directory`).option(`--base-dir [baseDir]`,`Base directory to search from`).option(`--git-root`,`Search from the git root directory instead of the base directory`).option(`--json`,`Output the results as JSON`).action(e=>{n({baseDir:e.baseDir,gitRoot:e.gitRoot,json:e.json})}),m.command(`projects-list`).alias(`pl`).description(`List all Intlayer projects in the directory`).option(`--base-dir [baseDir]`,`Base directory to search from`).option(`--git-root`,`Search from the git root directory instead of the base directory`).option(`--absolute`,`Output the results as absolute paths`).option(`--json`,`Output the results as JSON`).action(e=>{n({baseDir:e.baseDir,gitRoot:e.gitRoot,json:e.json,absolute:e.absolute})});let H=m.command(`content`).description(`Content declaration operations`);H.command(`list`).description(`List the content declaration files`).option(`--json`,`Output the results as JSON`).option(`--absolute`,`Output the results as absolute paths`).action(e=>{i({json:e.json,absolute:e.absolute})}),m.command(`list`).description(`List the content declaration files`).option(`--json`,`Output the results as JSON`).option(`--absolute`,`Output the results as absolute paths`).action(e=>{i({json:e.json,absolute:e.absolute})});let U=H.command(`test`).description(`Test if there are missing translations`).option(`--build [build]`,`Build the dictionaries before testing to ensure the content is up to date. True will force the build, false will skip the build, undefined will allow using the cache of the build`);D(U),U.action(e=>{u({...e,configOptions:P(e)})});let W=m.command(`test`).description(`Test if there are missing translations`).option(`--build [build]`,`Build the dictionaries before testing to ensure the content is up to date. True will force the build, false will skip the build, undefined will allow using the cache of the build`);D(W),W.action(e=>{u({...e,configOptions:P(e)})});let G=m.command(`fill`).description(`Fill the dictionaries`).option(`-f, --file [files...]`,`List of Dictionary files to fill`).option(`--source-locale [sourceLocale]`,`Source locale to translate from`).option(`--output-locales [outputLocales...]`,`Target locales to translate to`).option(`--mode [mode]`,`Fill mode: complete, review. Complete will fill all missing content, review will fill missing content and review existing keys`,`complete`).option(`-k, --keys [keys...]`,`Filter dictionaries based on keys`).option(`--key [keys...]`,`Filter dictionaries based on keys (alias for --keys)`).option(`--excluded-keys [excludedKeys...]`,`Filter out dictionaries based on keys`).option(`--excluded-key [excludedKeys...]`,`Filter out dictionaries based on keys (alias for --excluded-keys)`).option(`--path-filter [pathFilters...]`,`Filter dictionaries based on glob pattern`).option(`--build [build]`,`Build the dictionaries before filling to ensure the content is up to date. True will force the build, false will skip the build, undefined will allow using the cache of the build`).option(`--skip-metadata`,`Skip filling missing metadata (description, title, tags) for dictionaries`);D(G),O(G),k(G),G.action(e=>{let t=[...e.keys??[],...e.key??[]],n=[...e.excludedKeys??[],...e.excludedKey??[]],r=[...e.dictionaries??[],...e.dictionary??[]];return te({...e,keys:t.length>0?t:void 0,excludedKeys:n.length>0?n:void 0,dictionaries:r.length>0?r:void 0,aiOptions:A(e),gitOptions:M(e),configOptions:P(e)})});let K=[[`--doc-pattern [docPattern...]`,`Documentation pattern`],[`--excluded-glob-pattern [excludedGlobPattern...]`,`Excluded glob pattern`],[`--nb-simultaneous-file-processed [nbSimultaneousFileProcessed]`,`Number of simultaneous file processed`],[`--locales [locales...]`,`Locales`],[`--base-locale [baseLocale]`,`Base locale`],[`--custom-instructions [customInstructions]`,`Custom instructions added to the prompt. Usefull to apply specific rules regarding formatting, urls translation, etc.`],[`--skip-if-modified-before [skipIfModifiedBefore]`,'Skip the file if it has been modified before the given time. Can be an absolute time as "2025-12-05" (string or Date) or a relative time in ms `1 * 60 * 60 * 1000` (1 hour). This option check update time of the file using the `fs.stat` method. So it could be impacted by Git or other tools that modify the file.'],[`--skip-if-modified-after [skipIfModifiedAfter]`,'Skip the file if it has been modified within the given time. Can be an absolute time as "2025-12-05" (string or Date) or a relative time in ms `1 * 60 * 60 * 1000` (1 hour). This option check update time of the file using the `fs.stat` method. So it could be impacted by Git or other tools that modify the file.'],[`--skip-if-exists`,`Skip the file if it already exists`]],q=m.command(`doc`).description(`Documentation operations`),J=q.command(`translate`).description(`Translate the documentation`);D(J),O(J),k(J),T(J,K),J.action(e=>oe({docPattern:e.docPattern,excludedGlobPattern:e.excludedGlobPattern,locales:e.locales,baseLocale:e.baseLocale,aiOptions:A(e),gitOptions:M(e),nbSimultaneousFileProcessed:e.nbSimultaneousFileProcessed,configOptions:P(e),customInstructions:e.customInstructions,skipIfModifiedBefore:e.skipIfModifiedBefore,skipIfModifiedAfter:e.skipIfModifiedAfter,skipIfExists:e.skipIfExists}));let Y=q.command(`review`).description(`Review the documentation`);D(Y),O(Y),k(Y),T(Y,K),Y.action(e=>ie({docPattern:e.docPattern,excludedGlobPattern:e.excludedGlobPattern,locales:e.locales,baseLocale:e.baseLocale,aiOptions:A(e),gitOptions:M(e),nbSimultaneousFileProcessed:e.nbSimultaneousFileProcessed,configOptions:P(e),customInstructions:e.customInstructions,skipIfModifiedBefore:e.skipIfModifiedBefore,skipIfModifiedAfter:e.skipIfModifiedAfter,skipIfExists:e.skipIfExists}));let X=q.command(`search`).description(`Search the documentation`).argument(`<query>`,`Search query`).option(`--limit [limit]`,`Limit the number of results`,`10`);D(X),X.action((e,t)=>ae({query:e,limit:t.limit?parseInt(t.limit,10):10,configOptions:P(t)}));let ce=[[`--with [with...]`,`Start command in parallel with the live sync`]],Z=m.command(`live`).description(`Live sync - Watch for changes made on the CMS and update the application content accordingly`);T(Z,ce),D(Z),Z.action(e=>r(e));let Q=m.command(`editor`).description(`Visual editor operations`).command(`start`).description(`Start the Intlayer visual editor`);D(Q),Q.action(t=>{e({env:t.env,envFile:t.envFile})});let $=m.command(`extract`).alias(`ext`).description(`Extract strings from components to be placed in a .content file close to the component`);return $.option(`-f, --file [files...]`,`List of files to extract`).option(`-o, --output-content-declarations [outputContentDeclarations]`,`Path to output content declaration files`).option(`--code-only`,`Only extract the component code`,!1).option(`--declaration-only`,`Only generate content declaration`,!1).action(e=>{t({files:e.file,outputContentDeclarations:e.outputContentDeclarations,configOptions:P(e),codeOnly:e.codeOnly,declarationOnly:e.declarationOnly})}),D($),m.parse(process.argv),m.command(`ci`).description(`Run Intlayer commands with auto-injected credentials from INTLAYER_PROJECT_CREDENTIALS. Detects current project or iterates over all projects.`).argument(`<command...>`,`The intlayer command to execute (e.g., "fill", "push")`).allowUnknownOption().action(e=>{l(e)}),m};export{y as dirname,F as setAPI};
|
|
1
|
+
import{t as e}from"./editor-D8BGlLzF.mjs";import{extract as t}from"./extract.mjs";import{listProjectsCommand as n}from"./listProjects.mjs";import{liveSync as r}from"./liveSync.mjs";import{listContentDeclaration as i}from"./listContentDeclaration.mjs";import{init as a}from"./init.mjs";import{watchContentDeclaration as o}from"./watch.mjs";import{login as s}from"./auth/login.mjs";import{build as c}from"./build.mjs";import{runCI as l}from"./ci.mjs";import{getConfig as ee}from"./config.mjs";import{testMissingTranslations as u}from"./test/test.mjs";import{fill as te}from"./fill/fill.mjs";import{initSkills as d}from"./initSkills.mjs";import{initMCP as ne}from"./initMCP.mjs";import{pull as f}from"./pull.mjs";import{push as p}from"./push/push.mjs";import{pushConfig as re}from"./pushConfig.mjs";import"./_utils_asset-B187VPMw.mjs";import{reviewDoc as ie}from"./reviewDoc/reviewDoc.mjs";import{searchDoc as ae}from"./searchDoc.mjs";import{translateDoc as oe}from"./translateDoc/translateDoc.mjs";import{getParentPackageJSON as m}from"./utils/getParentPackageJSON.mjs";import{dirname as h}from"node:path";import{setPrefix as se}from"@intlayer/config/logger";import{getConfiguration as g}from"@intlayer/config/node";import{fileURLToPath as _}from"node:url";import{Command as v}from"commander";const y=typeof import.meta.url==`string`?h(_(import.meta.url)):__dirname,b=m(y),x=[[`--env-file [envFile]`,`Environment file`],[`-e, --env [env]`,`Environment`],[`--base-dir [baseDir]`,`Base directory`],[`--no-cache [noCache]`,`No cache`],...[[`--verbose`,`Verbose (default to true using CLI)`],[`--prefix [prefix]`,`Prefix`]]],S=[[`--provider [provider]`,`Provider`],[`--temperature [temperature]`,`Temperature`],[`--model [model]`,`Model`],[`--api-key [apiKey]`,`Provider API key`],[`--custom-prompt [prompt]`,`Custom prompt`],[`--application-context [applicationContext]`,`Application context`],[`--data-serialization [dataSerialization]`,`Data serialization`]],C=[[`--git-diff [gitDiff]`,`Git diff mode - Check git diff between two refs`],[`--git-diff-base [gitDiffBase]`,`Git diff base ref`],[`--git-diff-current [gitDiffCurrent]`,`Git diff current ref`],[`--uncommitted [uncommitted]`,`Uncommitted`],[`--unpushed [unpushed]`,`Unpushed`],[`--untracked [untracked]`,`Untracked`]],w=(e,t)=>t.filter(t=>e[t]!==void 0),T=(e,t)=>(t.forEach(([t,n])=>{e.option(t,n)}),e),E=e=>Object.fromEntries(Object.entries(e).filter(([e,t])=>t!==void 0)),D=e=>T(e,x),O=e=>T(e,S),k=e=>T(e,C),A=e=>{let{apiKey:t,provider:n,model:r,temperature:i,applicationContext:a,customPrompt:o,dataSerialization:s}=e,c=g(),{ai:l}=c;return E({...l,apiKey:t??c.ai?.apiKey,provider:n??c.ai?.provider,model:r??c.ai?.model,temperature:i??c.ai?.temperature,applicationContext:a??c.ai?.applicationContext,customPrompt:o??c.ai?.customPrompt,dataSerialization:s??c.ai?.dataSerialization})},j=[`gitDiff`,`gitDiffBase`,`gitDiffCurrent`,`uncommitted`,`unpushed`,`untracked`],M=e=>{if(w(e,j).length===0)return;let{gitDiff:t,gitDiffBase:n,gitDiffCurrent:r,uncommitted:i,unpushed:a,untracked:o}=e;return E({mode:[t&&`gitDiff`,i&&`uncommitted`,a&&`unpushed`,o&&`untracked`].filter(Boolean),baseRef:n,currentRef:r,absolute:!0})},N=[`baseDir`,`env`,`envFile`,`verbose`,`prefix`,`checkTypes`],P=e=>{if(w(e,N).length===0)return;let{baseDir:t,env:n,envFile:r,verbose:i,noCache:a,checkTypes:o}=e,s=E({mode:i===void 0?void 0:i?`verbose`:`default`}),c=E({checkTypes:o}),l=E({log:Object.keys(s).length>0?s:void 0,build:Object.keys(c).length>0?c:void 0});return E({baseDir:t,env:n,envFile:r,override:Object.keys(l).length>0?l:void 0,cache:a===void 0?void 0:!a})},F=()=>{process.argv.includes(`--with`)||se(``);let m=new v;m.version(b.version).description(`Intlayer CLI`),m.command(`version`).description(`Print the Intlayer CLI version`).action(()=>{console.log(b.version??`unknown`)});let h=m.command(`login`).description(`Login to Intlayer`).option(`--cms-url [cmsUrl]`,`CMS URL`);D(h),h.action(e=>{let t=P(e)??{override:{log:{prefix:``,mode:`verbose`}}};return s({cmsUrl:e.cmsUrl,configOptions:t})});let g=m.command(`init`).description(`Initialize Intlayer in the project`).option(`--project-root [projectRoot]`,`Project root directory`).action(e=>a(e.projectRoot));g.command(`skills`).description(`Initialize Intlayer skills in the project`).option(`--project-root [projectRoot]`,`Project root directory`).action(e=>d(e.projectRoot)),g.command(`mcp`).description(`Initialize Intlayer MCP server in the project`).option(`--project-root [projectRoot]`,`Project root directory`).action(e=>ne(e.projectRoot));let _=m.command(`dictionary`).alias(`dictionaries`).alias(`dic`).description(`Dictionaries operations`),y={description:`Build the dictionaries`,options:[[`-w, --watch`,`Watch for changes`],[`--skip-prepare`,`Skip the prepare step`],[`--with [with...]`,`Start command in parallel with the build`],[`--check-types`,`Check TypeScript type and log errors`]]},x=_.command(`build`).description(y.description);T(x,y.options),D(x),x.action(e=>{c({...e,configOptions:P(e)})});let S=m.command(`build`).description(y.description);T(S,y.options),D(S),S.action(e=>{c({...e,configOptions:P(e)})});let C={description:`Watch the dictionaries changes`,options:[[`--with [with...]`,`Start command in parallel with the build`]]},w=_.command(`watch`).description(y.description);T(w,C.options),D(w),w.action(e=>{o({...e,configOptions:P(e)})});let E=m.command(`watch`).description(y.description);T(E,C.options),D(E),E.action(e=>{o({...e,configOptions:P(e)})});let j={description:`Pull dictionaries from the server`,options:[[`-d, --dictionaries [ids...]`,`List of dictionary IDs to pull`],[`--dictionary [ids...]`,`List of dictionary IDs to pull (alias for --dictionaries)`],[`--new-dictionaries-path [path]`,`Path to save the new dictionaries`],[`--newDictionariesPath [path]`,`[alias] Path to save the new dictionaries`]]},N=_.command(`pull`).description(j.description);T(N,j.options),D(N),N.action(e=>{let t=[...e.dictionaries??[],...e.dictionary??[]];f({...e,dictionaries:t.length>0?t:void 0,configOptions:{...e.configOptions,baseDir:e.baseDir}})});let F=m.command(`pull`).description(j.description);T(F,j.options),D(F),F.action(e=>{let t=[...e.dictionaries??[],...e.dictionary??[]];f({...e,dictionaries:t.length>0?t:void 0,configOptions:P(e)})});let I={description:`Push all dictionaries. Create or update the pushed dictionaries`,options:[[`-d, --dictionaries [ids...]`,`List of dictionary IDs to push`],[`--dictionary [ids...]`,`List of dictionary IDs to push (alias for --dictionaries)`],[`-r, --delete-locale-dictionary`,`Delete the local dictionaries after pushing`],[`-k, --keep-locale-dictionary`,`Keep the local dictionaries after pushing`],[`--deleteLocaleDictionary`,`[alias] Delete the local dictionaries after pushing`],[`--keepLocaleDictionary`,`[alias] Keep the local dictionaries after pushing`],[`--build [build]`,`Build the dictionaries before pushing to ensure the content is up to date. True will force the build, false will skip the build, undefined will allow using the cache of the build`]]},L=_.command(`push`).description(I.description);T(L,I.options),D(L),k(L),L.action(e=>{let t=[...e.dictionaries||[],...e.dictionary||[]];return p({...e,dictionaries:t.length>0?t:void 0,gitOptions:M(e),configOptions:P(e)})});let R=m.command(`push`).description(I.description);T(R,I.options),D(R),k(R),R.action(e=>{let t=[...e.dictionaries||[],...e.dictionary||[]];return p({...e,dictionaries:t.length>0?t:void 0,gitOptions:M(e),configOptions:P(e)})});let z=m.command(`configuration`).alias(`config`).alias(`conf`).description(`Configuration operations`),B=z.command(`get`).description(`Get the configuration`);D(B),B.action(e=>{ee({...e,configOptions:P(e)})});let V=z.command(`push`).description(`Push the configuration`);D(V),V.action(e=>{re({...e,configOptions:P(e)})}),m.command(`projects`).alias(`project`).description(`List Intlayer projects`).command(`list`).description(`List all Intlayer projects in the directory`).option(`--base-dir [baseDir]`,`Base directory to search from`).option(`--git-root`,`Search from the git root directory instead of the base directory`).option(`--json`,`Output the results as JSON`).action(e=>{n({baseDir:e.baseDir,gitRoot:e.gitRoot,json:e.json})}),m.command(`projects-list`).alias(`pl`).description(`List all Intlayer projects in the directory`).option(`--base-dir [baseDir]`,`Base directory to search from`).option(`--git-root`,`Search from the git root directory instead of the base directory`).option(`--absolute`,`Output the results as absolute paths`).option(`--json`,`Output the results as JSON`).action(e=>{n({baseDir:e.baseDir,gitRoot:e.gitRoot,json:e.json,absolute:e.absolute})});let H=m.command(`content`).description(`Content declaration operations`);H.command(`list`).description(`List the content declaration files`).option(`--json`,`Output the results as JSON`).option(`--absolute`,`Output the results as absolute paths`).action(e=>{i({json:e.json,absolute:e.absolute})}),m.command(`list`).description(`List the content declaration files`).option(`--json`,`Output the results as JSON`).option(`--absolute`,`Output the results as absolute paths`).action(e=>{i({json:e.json,absolute:e.absolute})});let U=H.command(`test`).description(`Test if there are missing translations`).option(`--build [build]`,`Build the dictionaries before testing to ensure the content is up to date. True will force the build, false will skip the build, undefined will allow using the cache of the build`);D(U),U.action(e=>{u({...e,configOptions:P(e)})});let W=m.command(`test`).description(`Test if there are missing translations`).option(`--build [build]`,`Build the dictionaries before testing to ensure the content is up to date. True will force the build, false will skip the build, undefined will allow using the cache of the build`);D(W),W.action(e=>{u({...e,configOptions:P(e)})});let G=m.command(`fill`).description(`Fill the dictionaries`).option(`-f, --file [files...]`,`List of Dictionary files to fill`).option(`--source-locale [sourceLocale]`,`Source locale to translate from`).option(`--output-locales [outputLocales...]`,`Target locales to translate to`).option(`--mode [mode]`,`Fill mode: complete, review. Complete will fill all missing content, review will fill missing content and review existing keys`,`complete`).option(`-k, --keys [keys...]`,`Filter dictionaries based on keys`).option(`--key [keys...]`,`Filter dictionaries based on keys (alias for --keys)`).option(`--excluded-keys [excludedKeys...]`,`Filter out dictionaries based on keys`).option(`--excluded-key [excludedKeys...]`,`Filter out dictionaries based on keys (alias for --excluded-keys)`).option(`--path-filter [pathFilters...]`,`Filter dictionaries based on glob pattern`).option(`--build [build]`,`Build the dictionaries before filling to ensure the content is up to date. True will force the build, false will skip the build, undefined will allow using the cache of the build`).option(`--skip-metadata`,`Skip filling missing metadata (description, title, tags) for dictionaries`);D(G),O(G),k(G),G.action(e=>{let t=[...e.keys??[],...e.key??[]],n=[...e.excludedKeys??[],...e.excludedKey??[]],r=[...e.dictionaries??[],...e.dictionary??[]];return te({...e,keys:t.length>0?t:void 0,excludedKeys:n.length>0?n:void 0,dictionaries:r.length>0?r:void 0,aiOptions:A(e),gitOptions:M(e),configOptions:P(e)})});let K=[[`--doc-pattern [docPattern...]`,`Documentation pattern`],[`--excluded-glob-pattern [excludedGlobPattern...]`,`Excluded glob pattern`],[`--nb-simultaneous-file-processed [nbSimultaneousFileProcessed]`,`Number of simultaneous file processed`],[`--locales [locales...]`,`Locales`],[`--base-locale [baseLocale]`,`Base locale`],[`--custom-instructions [customInstructions]`,`Custom instructions added to the prompt. Usefull to apply specific rules regarding formatting, urls translation, etc.`],[`--skip-if-modified-before [skipIfModifiedBefore]`,'Skip the file if it has been modified before the given time. Can be an absolute time as "2025-12-05" (string or Date) or a relative time in ms `1 * 60 * 60 * 1000` (1 hour). This option check update time of the file using the `fs.stat` method. So it could be impacted by Git or other tools that modify the file.'],[`--skip-if-modified-after [skipIfModifiedAfter]`,'Skip the file if it has been modified within the given time. Can be an absolute time as "2025-12-05" (string or Date) or a relative time in ms `1 * 60 * 60 * 1000` (1 hour). This option check update time of the file using the `fs.stat` method. So it could be impacted by Git or other tools that modify the file.'],[`--skip-if-exists`,`Skip the file if it already exists`]],q=m.command(`doc`).description(`Documentation operations`),J=q.command(`translate`).description(`Translate the documentation`);D(J),O(J),k(J),T(J,K),J.action(e=>oe({docPattern:e.docPattern,excludedGlobPattern:e.excludedGlobPattern,locales:e.locales,baseLocale:e.baseLocale,aiOptions:A(e),gitOptions:M(e),nbSimultaneousFileProcessed:e.nbSimultaneousFileProcessed,configOptions:P(e),customInstructions:e.customInstructions,skipIfModifiedBefore:e.skipIfModifiedBefore,skipIfModifiedAfter:e.skipIfModifiedAfter,skipIfExists:e.skipIfExists}));let Y=q.command(`review`).description(`Review the documentation`);D(Y),O(Y),k(Y),T(Y,K),Y.action(e=>ie({docPattern:e.docPattern,excludedGlobPattern:e.excludedGlobPattern,locales:e.locales,baseLocale:e.baseLocale,aiOptions:A(e),gitOptions:M(e),nbSimultaneousFileProcessed:e.nbSimultaneousFileProcessed,configOptions:P(e),customInstructions:e.customInstructions,skipIfModifiedBefore:e.skipIfModifiedBefore,skipIfModifiedAfter:e.skipIfModifiedAfter,skipIfExists:e.skipIfExists}));let X=q.command(`search`).description(`Search the documentation`).argument(`<query>`,`Search query`).option(`--limit [limit]`,`Limit the number of results`,`10`);D(X),X.action((e,t)=>ae({query:e,limit:t.limit?parseInt(t.limit,10):10,configOptions:P(t)}));let ce=[[`--with [with...]`,`Start command in parallel with the live sync`]],Z=m.command(`live`).description(`Live sync - Watch for changes made on the CMS and update the application content accordingly`);T(Z,ce),D(Z),Z.action(e=>r(e));let Q=m.command(`editor`).description(`Visual editor operations`).command(`start`).description(`Start the Intlayer visual editor`);D(Q),Q.action(t=>{e({env:t.env,envFile:t.envFile})});let $=m.command(`extract`).alias(`ext`).description(`Extract strings from components to be placed in a .content file close to the component`);return $.option(`-f, --file [files...]`,`List of files to extract`).option(`--code-only`,`Only extract the component code`,!1).option(`--declaration-only`,`Only generate content declaration`,!1).action(e=>{t({files:e.file,configOptions:P(e),codeOnly:e.codeOnly,declarationOnly:e.declarationOnly})}),D($),m.parse(process.argv),m.command(`ci`).description(`Run Intlayer commands with auto-injected credentials from INTLAYER_PROJECT_CREDENTIALS. Detects current project or iterates over all projects.`).argument(`<command...>`,`The intlayer command to execute (e.g., "fill", "push")`).allowUnknownOption().action(e=>{l(e)}),m};export{y as dirname,F as setAPI};
|
|
2
2
|
//# sourceMappingURL=cli.mjs.map
|