@intlayer/engine 9.3.0 → 9.3.2
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/README.md +24 -24
- package/dist/assets/initConfig/templates/cjs.txt +1 -1
- package/dist/assets/initConfig/templates/mjs.txt +1 -1
- package/dist/assets/initConfig/templates/ts.txt +1 -1
- package/dist/cjs/_virtual/_rolldown/runtime.cjs +1 -2
- package/dist/cjs/_virtual/_utils_asset.cjs +2 -1
- package/dist/cjs/buildIntlayerDictionary/buildIntlayerDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeDynamicDictionary.cjs +2 -1
- package/dist/cjs/buildIntlayerDictionary/writeDynamicDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeFetchDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeMergedDictionary.cjs +2 -1
- package/dist/cjs/buildIntlayerDictionary/writeMergedDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeNestedDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeRemoteDictionary.cjs +4 -2
- package/dist/cjs/buildIntlayerDictionary/writeRemoteDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeUnmergedDictionary.cjs.map +1 -1
- package/dist/cjs/cleanOutputDir.cjs.map +1 -1
- package/dist/cjs/cleanRemovedContentDeclaration.cjs +7 -4
- package/dist/cjs/cleanRemovedContentDeclaration.cjs.map +1 -1
- package/dist/cjs/cli.cjs +2 -0
- package/dist/cjs/createDictionaryEntryPoint/createDictionaryEntryPoint.cjs +5 -3
- package/dist/cjs/createDictionaryEntryPoint/createDictionaryEntryPoint.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/generateDictionaryListContent.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltRemoteDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltUnmergedDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createType/createModuleAugmentation.cjs +2 -1
- package/dist/cjs/createType/createModuleAugmentation.cjs.map +1 -1
- package/dist/cjs/createType/createType.cjs.map +1 -1
- package/dist/cjs/detectFormatCommand.cjs.map +1 -1
- package/dist/cjs/docReview/alignBlocks.cjs +1 -1
- package/dist/cjs/docReview/alignBlocks.cjs.map +1 -1
- package/dist/cjs/docReview/computeSimilarity.cjs +0 -1
- package/dist/cjs/docReview/computeSimilarity.cjs.map +1 -1
- package/dist/cjs/docReview/mapChangedLinesToBlocks.cjs +0 -1
- package/dist/cjs/docReview/mapChangedLinesToBlocks.cjs.map +1 -1
- package/dist/cjs/docReview/normalizeBlock.cjs +0 -1
- package/dist/cjs/docReview/normalizeBlock.cjs.map +1 -1
- package/dist/cjs/docReview/planActions.cjs +0 -1
- package/dist/cjs/docReview/planActions.cjs.map +1 -1
- package/dist/cjs/docReview/rebuildDocument.cjs +0 -1
- package/dist/cjs/docReview/rebuildDocument.cjs.map +1 -1
- package/dist/cjs/docReview/reviewReport.cjs +2 -1
- package/dist/cjs/docReview/reviewReport.cjs.map +1 -1
- package/dist/cjs/docReview/segmentDocument.cjs +0 -1
- package/dist/cjs/docReview/segmentDocument.cjs.map +1 -1
- package/dist/cjs/fetchDistantDictionaries.cjs.map +1 -1
- package/dist/cjs/filterInvalidDictionaries.cjs.map +1 -1
- package/dist/cjs/formatDictionary.cjs.map +1 -1
- package/dist/cjs/getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.cjs.map +1 -1
- package/dist/cjs/handleAdditionalContentDeclarationFile.cjs +4 -2
- package/dist/cjs/handleAdditionalContentDeclarationFile.cjs.map +1 -1
- package/dist/cjs/handleContentDeclarationFileChange.cjs +6 -2
- package/dist/cjs/handleContentDeclarationFileChange.cjs.map +1 -1
- package/dist/cjs/handleContentDeclarationFileMoved.cjs.map +1 -1
- package/dist/cjs/handleUnlinkedContentDeclarationFile.cjs +4 -2
- package/dist/cjs/handleUnlinkedContentDeclarationFile.cjs.map +1 -1
- package/dist/cjs/init/cms.cjs.map +1 -1
- package/dist/cjs/init/frameworkSetup/nextAppRouter/detect.cjs.map +1 -1
- package/dist/cjs/init/frameworkSetup/nextAppRouter/index.cjs +1 -3
- package/dist/cjs/init/frameworkSetup/nextAppRouter/index.cjs.map +1 -1
- package/dist/cjs/init/frameworkSetup/nextAppRouter/restructure.cjs +2 -1
- package/dist/cjs/init/frameworkSetup/nextAppRouter/restructure.cjs.map +1 -1
- package/dist/cjs/init/frameworkSetup/nextAppRouter/templates.cjs +0 -1
- package/dist/cjs/init/frameworkSetup/nextAppRouter/templates.cjs.map +1 -1
- package/dist/cjs/init/frameworkSetup/tanstackStart/detect.cjs.map +1 -1
- package/dist/cjs/init/frameworkSetup/tanstackStart/index.cjs +3 -5
- package/dist/cjs/init/frameworkSetup/tanstackStart/index.cjs.map +1 -1
- package/dist/cjs/init/frameworkSetup/tanstackStart/restructure.cjs +2 -1
- package/dist/cjs/init/frameworkSetup/tanstackStart/restructure.cjs.map +1 -1
- package/dist/cjs/init/frameworkSetup/tanstackStart/templates.cjs +18 -12
- package/dist/cjs/init/frameworkSetup/tanstackStart/templates.cjs.map +1 -1
- package/dist/cjs/init/frameworkSetup/tanstackStart/transforms.cjs +57 -14
- package/dist/cjs/init/frameworkSetup/tanstackStart/transforms.cjs.map +1 -1
- package/dist/cjs/init/index.cjs +124 -45
- package/dist/cjs/init/index.cjs.map +1 -1
- package/dist/cjs/init/utils/configManipulation.cjs.map +1 -1
- package/dist/cjs/init/utils/fileSystem.cjs +3 -1
- package/dist/cjs/init/utils/fileSystem.cjs.map +1 -1
- package/dist/cjs/init/utils/githubActions.cjs.map +1 -1
- package/dist/cjs/init/utils/index.cjs +3 -0
- package/dist/cjs/init/utils/jsonParser.cjs +0 -1
- package/dist/cjs/init/utils/jsonParser.cjs.map +1 -1
- package/dist/cjs/init/utils/nextCompilerBabel.cjs.map +1 -1
- package/dist/cjs/init/utils/packageManager.cjs +105 -7
- package/dist/cjs/init/utils/packageManager.cjs.map +1 -1
- package/dist/cjs/init/utils/tsConfig.cjs.map +1 -1
- package/dist/cjs/init/utils/version.cjs +0 -1
- package/dist/cjs/init/utils/version.cjs.map +1 -1
- package/dist/cjs/initConfig/index.cjs +12 -8
- package/dist/cjs/initConfig/index.cjs.map +1 -1
- package/dist/cjs/installSkills/index.cjs.map +1 -1
- package/dist/cjs/listDictionariesPath.cjs +6 -5
- package/dist/cjs/listDictionariesPath.cjs.map +1 -1
- package/dist/cjs/listGitFiles.cjs.map +1 -1
- package/dist/cjs/listProjects.cjs +2 -1
- package/dist/cjs/listProjects.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/getIntlayerBundle.cjs +2 -1
- package/dist/cjs/loadDictionaries/getIntlayerBundle.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadContentDeclaration.cjs +8 -5
- package/dist/cjs/loadDictionaries/loadContentDeclaration.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadDictionaries.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadLocalDictionaries.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadMarkdownContentDeclaration.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadRemoteDictionaries.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadYamlContentDeclaration.cjs +2 -1
- package/dist/cjs/loadDictionaries/loadYamlContentDeclaration.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/log.cjs +10 -6
- package/dist/cjs/loadDictionaries/log.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/logTypeScriptErrors.cjs.map +1 -1
- package/dist/cjs/logConfigDetails.cjs +4 -3
- package/dist/cjs/logConfigDetails.cjs.map +1 -1
- package/dist/cjs/prepareIntlayer.cjs +5 -3
- package/dist/cjs/prepareIntlayer.cjs.map +1 -1
- package/dist/cjs/reduceDictionaryContent/applyMask.cjs +0 -1
- package/dist/cjs/reduceDictionaryContent/applyMask.cjs.map +1 -1
- package/dist/cjs/reduceDictionaryContent/reduceDictionaryContent.cjs +2 -1
- package/dist/cjs/reduceDictionaryContent/reduceDictionaryContent.cjs.map +1 -1
- package/dist/cjs/scan/calculateScore.cjs +0 -1
- package/dist/cjs/scan/calculateScore.cjs.map +1 -1
- package/dist/cjs/scan/checks.cjs +1 -1
- package/dist/cjs/scan/checks.cjs.map +1 -1
- package/dist/cjs/scan/parseHtml.cjs +0 -1
- package/dist/cjs/scan/parseHtml.cjs.map +1 -1
- package/dist/cjs/scan/scanWebsite.cjs.map +1 -1
- package/dist/cjs/syncPluginKit/createFileAdapter.cjs +2 -1
- package/dist/cjs/syncPluginKit/createFileAdapter.cjs.map +1 -1
- package/dist/cjs/syncPluginKit/createSyncPlugin.cjs +4 -1
- package/dist/cjs/syncPluginKit/createSyncPlugin.cjs.map +1 -1
- package/dist/cjs/syncPluginKit/extractKeyAndLocaleFromPath.cjs +0 -1
- package/dist/cjs/syncPluginKit/extractKeyAndLocaleFromPath.cjs.map +1 -1
- package/dist/cjs/syncPluginKit/filePathPatternHelpers.cjs +0 -1
- package/dist/cjs/syncPluginKit/filePathPatternHelpers.cjs.map +1 -1
- package/dist/cjs/utils/autoDecorateContent.cjs.map +1 -1
- package/dist/cjs/utils/babelParser.cjs.map +1 -1
- package/dist/cjs/utils/buildComponentFilesList.cjs.map +1 -1
- package/dist/cjs/utils/buildFilesList.cjs.map +1 -1
- package/dist/cjs/utils/chunkArray.cjs +0 -1
- package/dist/cjs/utils/chunkArray.cjs.map +1 -1
- package/dist/cjs/utils/formatter.cjs.map +1 -1
- package/dist/cjs/utils/getContentExtension.cjs +1 -4
- package/dist/cjs/utils/getContentExtension.cjs.map +1 -1
- package/dist/cjs/utils/getFormatFromExtension.cjs +0 -1
- package/dist/cjs/utils/getFormatFromExtension.cjs.map +1 -1
- package/dist/cjs/utils/getPathHash.cjs +0 -1
- package/dist/cjs/utils/getPathHash.cjs.map +1 -1
- package/dist/cjs/utils/mergeChunks.cjs +0 -1
- package/dist/cjs/utils/mergeChunks.cjs.map +1 -1
- package/dist/cjs/utils/pLimit.cjs +0 -1
- package/dist/cjs/utils/pLimit.cjs.map +1 -1
- package/dist/cjs/utils/readDictionariesFromDisk.cjs.map +1 -1
- package/dist/cjs/utils/reduceObjectFormat.cjs +0 -1
- package/dist/cjs/utils/reduceObjectFormat.cjs.map +1 -1
- package/dist/cjs/utils/resolveObjectPromises.cjs +0 -1
- package/dist/cjs/utils/resolveObjectPromises.cjs.map +1 -1
- package/dist/cjs/utils/resolveRelativePath.cjs +4 -1
- package/dist/cjs/utils/resolveRelativePath.cjs.map +1 -1
- package/dist/cjs/utils/runOnce.cjs +2 -2
- package/dist/cjs/utils/runOnce.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/bin.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/bootstrap.cjs +0 -1
- package/dist/cjs/utils/runParallel/bootstrap.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/index.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/spawnPosix.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/spawnWin32.cjs.map +1 -1
- package/dist/cjs/utils/sortAlphabetically.cjs +0 -1
- package/dist/cjs/utils/sortAlphabetically.cjs.map +1 -1
- package/dist/cjs/utils/splitTextByLine.cjs +0 -1
- package/dist/cjs/utils/splitTextByLine.cjs.map +1 -1
- package/dist/cjs/utils/verifyIdenticObjectFormat.cjs +0 -1
- package/dist/cjs/utils/verifyIdenticObjectFormat.cjs.map +1 -1
- package/dist/cjs/watcher.cjs +4 -2
- package/dist/cjs/watcher.cjs.map +1 -1
- package/dist/cjs/writeConfiguration/index.cjs +2 -1
- package/dist/cjs/writeConfiguration/index.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/detectExportedComponentName.cjs +0 -1
- package/dist/cjs/writeContentDeclaration/detectExportedComponentName.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/processContentDeclarationContent.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/transformJSFile.cjs +26 -23
- package/dist/cjs/writeContentDeclaration/transformJSFile.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/transformJSONFile.cjs +6 -5
- package/dist/cjs/writeContentDeclaration/transformJSONFile.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs +9 -3
- package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/writeJSFile.cjs +2 -1
- package/dist/cjs/writeContentDeclaration/writeJSFile.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/writeMarkdownFile.cjs +2 -1
- package/dist/cjs/writeContentDeclaration/writeMarkdownFile.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/writeYamlFile.cjs +4 -2
- package/dist/cjs/writeContentDeclaration/writeYamlFile.cjs.map +1 -1
- package/dist/cjs/writeFileIfChanged.cjs.map +1 -1
- package/dist/esm/_virtual/_utils_asset.mjs +2 -1
- package/dist/esm/buildIntlayerDictionary/writeDynamicDictionary.mjs +2 -1
- package/dist/esm/buildIntlayerDictionary/writeDynamicDictionary.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/writeMergedDictionary.mjs +2 -1
- package/dist/esm/buildIntlayerDictionary/writeMergedDictionary.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/writeRemoteDictionary.mjs +4 -2
- package/dist/esm/buildIntlayerDictionary/writeRemoteDictionary.mjs.map +1 -1
- package/dist/esm/cleanRemovedContentDeclaration.mjs +7 -4
- package/dist/esm/cleanRemovedContentDeclaration.mjs.map +1 -1
- package/dist/esm/cli.mjs +2 -2
- package/dist/esm/createDictionaryEntryPoint/createDictionaryEntryPoint.mjs +5 -3
- package/dist/esm/createDictionaryEntryPoint/createDictionaryEntryPoint.mjs.map +1 -1
- package/dist/esm/createType/createModuleAugmentation.mjs +2 -1
- package/dist/esm/createType/createModuleAugmentation.mjs.map +1 -1
- package/dist/esm/docReview/alignBlocks.mjs +1 -1
- package/dist/esm/docReview/alignBlocks.mjs.map +1 -1
- package/dist/esm/docReview/reviewReport.mjs +2 -1
- package/dist/esm/docReview/reviewReport.mjs.map +1 -1
- package/dist/esm/handleAdditionalContentDeclarationFile.mjs +4 -2
- package/dist/esm/handleAdditionalContentDeclarationFile.mjs.map +1 -1
- package/dist/esm/handleContentDeclarationFileChange.mjs +6 -2
- package/dist/esm/handleContentDeclarationFileChange.mjs.map +1 -1
- package/dist/esm/handleUnlinkedContentDeclarationFile.mjs +4 -2
- package/dist/esm/handleUnlinkedContentDeclarationFile.mjs.map +1 -1
- package/dist/esm/init/frameworkSetup/nextAppRouter/index.mjs +1 -3
- package/dist/esm/init/frameworkSetup/nextAppRouter/index.mjs.map +1 -1
- package/dist/esm/init/frameworkSetup/nextAppRouter/restructure.mjs +2 -1
- package/dist/esm/init/frameworkSetup/nextAppRouter/restructure.mjs.map +1 -1
- package/dist/esm/init/frameworkSetup/tanstackStart/index.mjs +4 -6
- package/dist/esm/init/frameworkSetup/tanstackStart/index.mjs.map +1 -1
- package/dist/esm/init/frameworkSetup/tanstackStart/restructure.mjs +2 -1
- package/dist/esm/init/frameworkSetup/tanstackStart/restructure.mjs.map +1 -1
- package/dist/esm/init/frameworkSetup/tanstackStart/templates.mjs +17 -10
- package/dist/esm/init/frameworkSetup/tanstackStart/templates.mjs.map +1 -1
- package/dist/esm/init/frameworkSetup/tanstackStart/transforms.mjs +58 -15
- package/dist/esm/init/frameworkSetup/tanstackStart/transforms.mjs.map +1 -1
- package/dist/esm/init/index.mjs +125 -46
- package/dist/esm/init/index.mjs.map +1 -1
- package/dist/esm/init/utils/configManipulation.mjs.map +1 -1
- package/dist/esm/init/utils/fileSystem.mjs +3 -1
- package/dist/esm/init/utils/fileSystem.mjs.map +1 -1
- package/dist/esm/init/utils/index.mjs +2 -2
- package/dist/esm/init/utils/packageManager.mjs +103 -8
- package/dist/esm/init/utils/packageManager.mjs.map +1 -1
- package/dist/esm/initConfig/index.mjs +12 -8
- package/dist/esm/initConfig/index.mjs.map +1 -1
- package/dist/esm/listDictionariesPath.mjs +6 -5
- package/dist/esm/listDictionariesPath.mjs.map +1 -1
- package/dist/esm/listProjects.mjs +2 -1
- package/dist/esm/listProjects.mjs.map +1 -1
- package/dist/esm/loadDictionaries/getIntlayerBundle.mjs +2 -1
- package/dist/esm/loadDictionaries/getIntlayerBundle.mjs.map +1 -1
- package/dist/esm/loadDictionaries/loadContentDeclaration.mjs +8 -5
- package/dist/esm/loadDictionaries/loadContentDeclaration.mjs.map +1 -1
- package/dist/esm/loadDictionaries/loadYamlContentDeclaration.mjs +2 -1
- package/dist/esm/loadDictionaries/loadYamlContentDeclaration.mjs.map +1 -1
- package/dist/esm/loadDictionaries/log.mjs +10 -6
- package/dist/esm/loadDictionaries/log.mjs.map +1 -1
- package/dist/esm/logConfigDetails.mjs +4 -3
- package/dist/esm/logConfigDetails.mjs.map +1 -1
- package/dist/esm/prepareIntlayer.mjs +5 -3
- package/dist/esm/prepareIntlayer.mjs.map +1 -1
- package/dist/esm/reduceDictionaryContent/reduceDictionaryContent.mjs +2 -1
- package/dist/esm/reduceDictionaryContent/reduceDictionaryContent.mjs.map +1 -1
- package/dist/esm/scan/checks.mjs +1 -1
- package/dist/esm/scan/checks.mjs.map +1 -1
- package/dist/esm/syncPluginKit/createFileAdapter.mjs +2 -1
- package/dist/esm/syncPluginKit/createFileAdapter.mjs.map +1 -1
- package/dist/esm/syncPluginKit/createSyncPlugin.mjs +4 -1
- package/dist/esm/syncPluginKit/createSyncPlugin.mjs.map +1 -1
- package/dist/esm/utils/babelParser.mjs.map +1 -1
- package/dist/esm/utils/getContentExtension.mjs +1 -3
- package/dist/esm/utils/getContentExtension.mjs.map +1 -1
- package/dist/esm/utils/resolveRelativePath.mjs +4 -1
- package/dist/esm/utils/resolveRelativePath.mjs.map +1 -1
- package/dist/esm/utils/runOnce.mjs +2 -2
- package/dist/esm/utils/runOnce.mjs.map +1 -1
- package/dist/esm/watcher.mjs +4 -2
- package/dist/esm/watcher.mjs.map +1 -1
- package/dist/esm/writeConfiguration/index.mjs +2 -1
- package/dist/esm/writeConfiguration/index.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/transformJSFile.mjs +26 -23
- package/dist/esm/writeContentDeclaration/transformJSFile.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/transformJSONFile.mjs +6 -5
- package/dist/esm/writeContentDeclaration/transformJSONFile.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs +9 -3
- package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/writeJSFile.mjs +2 -1
- package/dist/esm/writeContentDeclaration/writeJSFile.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/writeMarkdownFile.mjs +2 -1
- package/dist/esm/writeContentDeclaration/writeMarkdownFile.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/writeYamlFile.mjs +4 -2
- package/dist/esm/writeContentDeclaration/writeYamlFile.mjs.map +1 -1
- package/dist/types/cli.d.ts +2 -2
- package/dist/types/init/frameworkSetup/tanstackStart/templates.d.ts +9 -4
- package/dist/types/init/frameworkSetup/tanstackStart/templates.d.ts.map +1 -1
- package/dist/types/init/frameworkSetup/tanstackStart/transforms.d.ts +6 -2
- package/dist/types/init/frameworkSetup/tanstackStart/transforms.d.ts.map +1 -1
- package/dist/types/init/index.d.ts +2 -7
- package/dist/types/init/index.d.ts.map +1 -1
- package/dist/types/init/utils/index.d.ts +2 -2
- package/dist/types/init/utils/packageManager.d.ts +39 -6
- package/dist/types/init/utils/packageManager.d.ts.map +1 -1
- package/package.json +10 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transformJSFile.cjs","names":["NodeTypes","babelTsParser"],"sources":["../../../src/writeContentDeclaration/transformJSFile.ts"],"sourcesContent":["import { getNodeType } from '@intlayer/core/dictionaryManipulator';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { ContentNode, Dictionary } from '@intlayer/types/dictionary';\nimport type { NodeType } from '@intlayer/types/nodeType';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport * as recast from 'recast';\nimport { babelTsParser } from '../utils/babelParser';\n\nconst b = recast.types.builders;\nconst n = recast.types.namedTypes;\n\n/**\n * Name of an `intlayer` helper function a node type is printed as.\n *\n * Mirrors the transpiler helpers re-exported by the `intlayer` package\n * (`@intlayer/core/transpiler`).\n */\ntype HelperName =\n | 't'\n | 'enu'\n | 'plural'\n | 'cond'\n | 'gender'\n | 'select'\n | 'insert'\n | 'md'\n | 'html'\n | 'file'\n | 'nest';\n\n/**\n * How a {@link NodeType} is materialized back into source code.\n *\n * - `helperRecord` — printed as `helper({ … })`. The node data is a record of\n * variants (locales, plural categories, conditions, cases…) whose values are\n * rebuilt recursively and merged into the existing object literal.\n * - `helperValue` — printed as `helper(value)`. The node data is a single\n * content, itself possibly another node (e.g. `md(t({ … }))`).\n * - `nesting` — printed as `nest(dictionaryKey, path?)`.\n * - `unwrap` — not a source-level helper: the wrapped value replaces the node,\n * so `{ nodeType: 'text', text: 'Hello' }` is printed as `\"Hello\"`.\n * - `preserve` — framework elements have no data representation, so the\n * existing source expression is kept untouched and nothing is written when\n * there is none.\n * - `structural` — plain objects, arrays and unrecognized nodes, rebuilt by the\n * generic object/array branches.\n */\ntype NodeTypeStrategy =\n | {\n kind: 'helperRecord';\n helper: HelperName;\n /**\n * Extra arguments appended after the record argument, rebuilt from the\n * node attributes (e.g. the variable name carried by a `select` node).\n */\n getExtraArguments?: (\n node: Record<string, unknown>\n ) => recast.types.namedTypes.Literal[];\n }\n | { kind: 'helperValue'; helper: HelperName }\n | { kind: 'nesting'; helper: HelperName }\n | { kind: 'unwrap' }\n | { kind: 'preserve' }\n | { kind: 'structural' };\n\n/**\n * Every {@link NodeType} and how it is written back to a JS/TS declaration file.\n *\n * Typed as `Record<NodeType, NodeTypeStrategy>` so that adding a node type to\n * `@intlayer/types` without registering it here becomes a compile-time error —\n * the same guarantee `getNodeType` gives on the read side.\n */\nconst nodeTypeStrategies: Record<NodeType, NodeTypeStrategy> = {\n [NodeTypes.TRANSLATION]: { kind: 'helperRecord', helper: 't' },\n [NodeTypes.ENUMERATION]: { kind: 'helperRecord', helper: 'enu' },\n [NodeTypes.PLURAL]: { kind: 'helperRecord', helper: 'plural' },\n [NodeTypes.CONDITION]: { kind: 'helperRecord', helper: 'cond' },\n [NodeTypes.GENDER]: { kind: 'helperRecord', helper: 'gender' },\n [NodeTypes.SELECT]: {\n kind: 'helperRecord',\n helper: 'select',\n getExtraArguments: (node) =>\n typeof node.variable === 'string' && node.variable.length > 0\n ? [b.literal(node.variable)]\n : [],\n },\n [NodeTypes.INSERTION]: { kind: 'helperValue', helper: 'insert' },\n [NodeTypes.MARKDOWN]: { kind: 'helperValue', helper: 'md' },\n [NodeTypes.HTML]: { kind: 'helperValue', helper: 'html' },\n [NodeTypes.FILE]: { kind: 'helperValue', helper: 'file' },\n [NodeTypes.NESTED]: { kind: 'nesting', helper: 'nest' },\n [NodeTypes.TEXT]: { kind: 'unwrap' },\n [NodeTypes.NUMBER]: { kind: 'unwrap' },\n [NodeTypes.BOOLEAN]: { kind: 'unwrap' },\n [NodeTypes.NULL]: { kind: 'unwrap' },\n [NodeTypes.REACT_NODE]: { kind: 'preserve' },\n [NodeTypes.PREACT_NODE]: { kind: 'preserve' },\n [NodeTypes.SOLID_NODE]: { kind: 'preserve' },\n [NodeTypes.OBJECT]: { kind: 'structural' },\n [NodeTypes.ARRAY]: { kind: 'structural' },\n [NodeTypes.UNKNOWN]: { kind: 'structural' },\n};\n\n/** Every `intlayer` helper the transform is allowed to rewrite. */\nconst helperNames = new Set<string>(\n Object.values(nodeTypeStrategies).flatMap((strategy) =>\n 'helper' in strategy ? [strategy.helper] : []\n )\n);\n\n/** Helpers wrapping a single content, e.g. `md(t({ … }))`. */\nconst wrapperHelperNames = new Set<string>(\n Object.values(nodeTypeStrategies).flatMap((strategy) =>\n strategy.kind === 'helperValue' ? [strategy.helper] : []\n )\n);\n\n/**\n * Returned by {@link buildNodeForValue} when a value must not be written to the\n * source file — framework elements and functions have no data representation,\n * so the original expression (when there is one) is left untouched and no new\n * property is created otherwise.\n */\nconst SKIP_WRITE = Symbol('intlayer.skipWrite');\n\n/**\n * Unwraps TypeScript/Babel expression wrappers (satisfies, as, !, <Type>).\n * Uses string fallbacks to bypass outdated ast-types definitions.\n */\nconst unwrap = (node: any) => {\n while (\n node &&\n (n.TSSatisfiesExpression?.check(node) ||\n n.TSAsExpression?.check(node) ||\n n.TSTypeAssertion?.check(node) ||\n n.TSNonNullExpression?.check(node) ||\n [\n 'TSSatisfiesExpression',\n 'TSAsExpression',\n 'TSTypeAssertion',\n 'TSNonNullExpression',\n ].includes(node.type))\n ) {\n node = node.expression;\n }\n return node;\n};\n\n/**\n * Robustly finds a property in a recast ObjectExpression.\n * Handles quoted (\"key\") or unquoted (key) properties.\n */\nconst getMatchingProperty = (node: any, key: string) => {\n return node.properties.find((prop: any) => {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n if (n.Identifier.check(prop.key) && prop.key.name === key) return true;\n\n if (n.StringLiteral.check(prop.key) && prop.key.value === key)\n return true;\n\n if (n.Literal.check(prop.key) && prop.key.value === key) return true;\n }\n\n return false;\n });\n};\n\n/**\n * Synchronizes numeric suffixes across locales.\n * E.g. \"Hello 1\" -> \"Hello 3\" updates \"Bonjour 1\" to \"Bonjour 3\".\n */\nconst syncNumericSuffixAcrossLocales = (\n existingNode: any,\n fallbackLocaleCode: string,\n newFallbackValue: string\n) => {\n const trailingNumberMatch = newFallbackValue.match(/\\d+(?!.*\\d)/);\n if (!trailingNumberMatch) return;\n const newTrailingNumber = trailingNumberMatch[0];\n\n if (n.ObjectExpression.check(existingNode)) {\n for (const prop of existingNode.properties) {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n let propName = '';\n\n if (n.Identifier.check(prop.key)) propName = prop.key.name;\n else if (\n n.Literal.check(prop.key) &&\n typeof prop.key.value === 'string'\n )\n propName = prop.key.value;\n else if (n.StringLiteral.check(prop.key)) propName = prop.key.value;\n\n if (propName && propName !== fallbackLocaleCode) {\n if (\n n.Literal.check(prop.value) &&\n typeof prop.value.value === 'string'\n ) {\n const currentValue = prop.value.value;\n const currentTrailingNumberMatch =\n currentValue.match(/\\d+(?!.*\\d)/);\n\n if (currentTrailingNumberMatch) {\n prop.value = b.literal(\n currentValue.replace(/(\\d+)(?!.*\\d)/, newTrailingNumber)\n );\n }\n } else if (n.StringLiteral.check(prop.value)) {\n const currentValue = prop.value.value;\n const currentTrailingNumberMatch =\n currentValue.match(/\\d+(?!.*\\d)/);\n\n if (currentTrailingNumberMatch) {\n prop.value = b.stringLiteral(\n currentValue.replace(/(\\d+)(?!.*\\d)/, newTrailingNumber)\n );\n }\n }\n }\n }\n }\n }\n};\n\n/**\n * Checks if a value represents a multilingual Intlayer node.\n *\n * A node is multilingual if it is a Translation node, if it wraps one\n * (Markdown, HTML, Insertion…), or if any of its variants contains one\n * (Enumeration, Plural, Condition, Gender, Select…).\n */\nconst isMultilingualNode = (val: any): boolean => {\n if (typeof val !== 'object' || val === null || Array.isArray(val)) {\n return false;\n }\n\n const nodeType = getNodeType(val as ContentNode);\n\n if (nodeType === NodeTypes.TRANSLATION) {\n return true;\n }\n\n const strategy = nodeTypeStrategies[nodeType];\n const nodeData = (val as any)[nodeType];\n\n if (strategy.kind === 'helperValue' || strategy.kind === 'unwrap') {\n return isMultilingualNode(nodeData);\n }\n\n if (\n strategy.kind === 'helperRecord' &&\n nodeData &&\n typeof nodeData === 'object'\n ) {\n return Object.values(nodeData).some((variant) =>\n isMultilingualNode(variant)\n );\n }\n\n return false;\n};\n\n/**\n * Checks whether two AST nodes are literals holding the same value.\n */\nconst isEquivalentLiteral = (left: any, right: any): boolean => {\n const isLiteral = (node: any) =>\n n.Literal.check(node) ||\n n.StringLiteral.check(node) ||\n n.NumericLiteral.check(node) ||\n n.BooleanLiteral.check(node);\n\n return isLiteral(left) && isLiteral(right) && left.value === right.value;\n};\n\n/**\n * Aligns the arguments of an existing call expression with the desired ones.\n *\n * Mutates the call only when the arguments actually differ, so Recast keeps the\n * original formatting (and quote style) of calls that did not change.\n */\nconst syncCallArguments = (callNode: any, desiredArguments: any[]) => {\n const isUnchanged =\n callNode.arguments.length === desiredArguments.length &&\n desiredArguments.every((desired, index) => {\n const current = callNode.arguments[index];\n\n return current === desired || isEquivalentLiteral(current, desired);\n });\n\n if (!isUnchanged) {\n callNode.arguments = desiredArguments;\n }\n};\n\n/**\n * Recursively builds or updates an AST node for a given dictionary value.\n *\n * Returns {@link SKIP_WRITE} when the value cannot be represented in source and\n * no existing expression can be kept.\n */\nconst buildNodeForValue = (\n val: any,\n existingNode: any,\n fallbackLocale: string | undefined, // In per-locale mode, this is the locale of the file\n requiredImports: Set<string>\n): any => {\n // Values with no source representation must never overwrite existing code.\n if (val === undefined || typeof val === 'function') {\n return existingNode ?? SKIP_WRITE;\n }\n\n const unwrappedExisting = unwrap(existingNode);\n\n // --- CRITICAL GUARD: STRICT AST PRESERVATION ---\n // If the existing node is code (JSX, Variables, standard functions), leave it alone.\n // Only allow updates to literals, plain objects, arrays, and Intlayer helpers.\n if (unwrappedExisting) {\n const isUpdatableNode =\n n.Literal.check(unwrappedExisting) ||\n n.StringLiteral.check(unwrappedExisting) ||\n n.NumericLiteral.check(unwrappedExisting) ||\n n.BooleanLiteral.check(unwrappedExisting) ||\n n.TemplateLiteral.check(unwrappedExisting) ||\n n.ObjectExpression.check(unwrappedExisting) ||\n n.ArrayExpression.check(unwrappedExisting) ||\n (n.CallExpression.check(unwrappedExisting) &&\n n.Identifier.check(unwrappedExisting.callee) &&\n helperNames.has(unwrappedExisting.callee.name));\n\n if (!isUpdatableNode) {\n return existingNode;\n }\n }\n\n // If we are in per-locale mode (fallbackLocale is set)\n // and the value is not already a complex translation node,\n // we want to store it as a simple literal, NOT wrapped in t().\n if (fallbackLocale && !existingNode && !isMultilingualNode(val)) {\n if (val === null) return b.literal(null);\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n if (typeof val === 'string' && val.includes('\\n')) {\n return b.templateLiteral(\n [b.templateElement({ raw: val, cooked: val }, true)],\n []\n );\n }\n return b.literal(val);\n }\n }\n\n if (fallbackLocale && existingNode && !isMultilingualNode(val)) {\n if (\n n.CallExpression.check(existingNode) &&\n n.Identifier.check(existingNode.callee) &&\n existingNode.callee.name === 't'\n ) {\n const arg = unwrap(existingNode.arguments[0]);\n\n if (n.ObjectExpression.check(arg)) {\n if (typeof val === 'string') {\n syncNumericSuffixAcrossLocales(arg, fallbackLocale, val);\n }\n updateObjectLiteral(\n arg,\n { [fallbackLocale]: val },\n fallbackLocale,\n requiredImports\n );\n\n if (!fallbackLocale) {\n requiredImports.add('t');\n }\n\n return existingNode;\n }\n }\n\n // Wrapped translations — `md(t({ … }))`, `html(t({ … }))`, `insert(t({ … }))`:\n // update the inner translation in place instead of replacing the wrapper.\n if (\n (!val || typeof val !== 'object') &&\n n.CallExpression.check(existingNode) &&\n n.Identifier.check(existingNode.callee) &&\n wrapperHelperNames.has(existingNode.callee.name)\n ) {\n const wrapperName = existingNode.callee.name;\n const innerArg = existingNode.arguments[0];\n\n if (\n n.CallExpression.check(innerArg) &&\n n.Identifier.check(innerArg.callee) &&\n innerArg.callee.name === 't'\n ) {\n const tArg = unwrap(innerArg.arguments[0]);\n\n if (n.ObjectExpression.check(tArg)) {\n if (typeof val === 'string') {\n syncNumericSuffixAcrossLocales(tArg, fallbackLocale, val);\n }\n updateObjectLiteral(\n tArg,\n { [fallbackLocale]: val },\n fallbackLocale,\n requiredImports\n );\n requiredImports.add(wrapperName);\n requiredImports.add('t');\n\n return existingNode;\n }\n }\n }\n }\n\n // 1. Primitives\n if (val === null) return b.literal(null);\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n if (unwrappedExisting) {\n // Preserve existing template literals (backticks)\n if (\n n.TemplateLiteral.check(unwrappedExisting) &&\n unwrappedExisting.quasis[0] &&\n unwrappedExisting.expressions.length === 0\n ) {\n unwrappedExisting.quasis[0].value.raw = String(val);\n unwrappedExisting.quasis[0].value.cooked = String(val);\n return existingNode;\n }\n // Preserve existing standard literals (keeps quote styling)\n if (\n n.Literal.check(unwrappedExisting) ||\n n.StringLiteral.check(unwrappedExisting)\n ) {\n unwrappedExisting.value = val;\n return existingNode;\n }\n }\n\n // Force multiline strings to use Template Literals\n if (typeof val === 'string' && val.includes('\\n')) {\n return b.templateLiteral(\n [b.templateElement({ raw: val, cooked: val }, true)],\n []\n );\n }\n return b.literal(val);\n }\n\n // 2. Arrays\n if (Array.isArray(val)) {\n if (unwrappedExisting && n.ArrayExpression.check(unwrappedExisting)) {\n const elements = [...unwrappedExisting.elements];\n val.forEach((item, i) => {\n const elementNode = buildNodeForValue(\n item,\n elements[i],\n fallbackLocale,\n requiredImports\n );\n\n elements[i] =\n elementNode === SKIP_WRITE\n ? (elements[i] ?? b.literal(null))\n : elementNode;\n });\n\n if (elements.length > val.length) elements.length = val.length;\n unwrappedExisting.elements = elements as any;\n\n return existingNode;\n } else {\n return b.arrayExpression(\n val.map((item) => {\n const elementNode = buildNodeForValue(\n item,\n null,\n fallbackLocale,\n requiredImports\n );\n\n return elementNode === SKIP_WRITE ? b.literal(null) : elementNode;\n })\n );\n }\n }\n\n // 3. Intlayer Specialized Nodes — dispatched through the exhaustive registry\n const nodeType =\n val && typeof val === 'object' && !Array.isArray(val)\n ? getNodeType(val as ContentNode)\n : null;\n\n if (nodeType) {\n const strategy = nodeTypeStrategies[nodeType];\n\n // Framework elements (React/Preact/Solid) cannot be serialized back to\n // source: keep whatever the file already declares.\n if (strategy.kind === 'preserve') {\n return existingNode ?? SKIP_WRITE;\n }\n\n const hasNodeData = Object.hasOwn(val as object, nodeType);\n const nodeData = (val as any)[nodeType];\n\n // A typed node missing its payload is malformed — fall back to the generic\n // object branch rather than printing a broken helper call.\n if (strategy.kind !== 'structural' && hasNodeData) {\n if (strategy.kind === 'unwrap') {\n return buildNodeForValue(\n nodeData,\n existingNode,\n fallbackLocale,\n requiredImports\n );\n }\n\n const { helper } = strategy;\n\n requiredImports.add(helper);\n\n const isMatchingCall =\n existingNode &&\n n.CallExpression.check(existingNode) &&\n n.Identifier.check(existingNode.callee) &&\n existingNode.callee.name === helper;\n\n if (strategy.kind === 'helperRecord') {\n const recordArgument =\n isMatchingCall &&\n existingNode.arguments.length > 0 &&\n n.ObjectExpression.check(existingNode.arguments[0])\n ? existingNode.arguments[0]\n : b.objectExpression([]);\n\n updateObjectLiteral(\n recordArgument,\n nodeData ?? {},\n fallbackLocale,\n requiredImports\n );\n\n const callArguments = [\n recordArgument,\n ...(strategy.getExtraArguments?.(val as Record<string, unknown>) ??\n []),\n ];\n\n if (isMatchingCall) {\n syncCallArguments(existingNode, callArguments);\n\n return existingNode;\n }\n\n return b.callExpression(b.identifier(helper), callArguments);\n }\n\n if (strategy.kind === 'helperValue') {\n const contentArgument = buildNodeForValue(\n nodeData,\n isMatchingCall && existingNode.arguments.length > 0\n ? existingNode.arguments[0]\n : null,\n fallbackLocale,\n requiredImports\n );\n\n if (contentArgument === SKIP_WRITE) {\n return existingNode ?? SKIP_WRITE;\n }\n\n if (isMatchingCall) {\n // Keep any extra argument the source declares (custom components\n // passed to `md()` / `html()`), which the node does not carry back.\n syncCallArguments(existingNode, [\n contentArgument,\n ...existingNode.arguments.slice(1),\n ]);\n\n return existingNode;\n }\n\n return b.callExpression(b.identifier(helper), [contentArgument]);\n }\n\n // strategy.kind === 'nesting'\n const callArguments = [b.literal(nodeData?.dictionaryKey ?? '')];\n\n if (nodeData?.path) callArguments.push(b.literal(nodeData.path));\n\n if (isMatchingCall) {\n syncCallArguments(existingNode, callArguments);\n\n return existingNode;\n }\n\n return b.callExpression(b.identifier(helper), callArguments);\n }\n }\n\n // 4. Plain Object\n const objNode =\n unwrappedExisting && n.ObjectExpression.check(unwrappedExisting)\n ? unwrappedExisting\n : b.objectExpression([]);\n\n updateObjectLiteral(objNode, val, fallbackLocale, requiredImports);\n\n return existingNode && unwrappedExisting === existingNode\n ? objNode\n : existingNode || objNode;\n};\n\n/**\n * Recursively updates the AST object literal properties.\n */\nconst updateObjectLiteral = (\n node: recast.types.namedTypes.ObjectExpression,\n data: Record<string, any>,\n fallbackLocale: string | undefined,\n requiredImports: Set<string>\n) => {\n for (const [key, val] of Object.entries(data)) {\n if (val === undefined) continue;\n\n const existingProp = getMatchingProperty(node, key);\n\n if (existingProp) {\n const valueNode = buildNodeForValue(\n val,\n existingProp.value,\n fallbackLocale,\n requiredImports\n );\n\n if (valueNode !== SKIP_WRITE) {\n existingProp.value = valueNode;\n }\n } else {\n const isValidId = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key);\n const keyNode = isValidId ? b.identifier(key) : b.literal(key);\n const valueNode = buildNodeForValue(\n val,\n null,\n fallbackLocale,\n requiredImports\n );\n\n if (valueNode === SKIP_WRITE) continue;\n\n node.properties.push(b.property('init', keyNode, valueNode));\n }\n }\n};\n\n/**\n * Modifies the AST's top-level imports to inject dynamically needed helper utilities seamlessly.\n */\nconst addImports = (ast: any, requiredImports: Set<string>, isESM: boolean) => {\n if (requiredImports.size === 0) return;\n\n const existingCoreImports = new Set<string>();\n let coreImportPath: any = null;\n\n recast.visit(ast, {\n visitImportDeclaration(path) {\n const source = path.node.source.value;\n\n if (source === 'intlayer') {\n coreImportPath = path;\n path.node.specifiers?.forEach((spec) => {\n if (\n n.ImportSpecifier.check(spec) &&\n typeof spec.imported.name === 'string'\n ) {\n existingCoreImports.add(spec.imported.name);\n }\n });\n }\n\n return false;\n },\n visitVariableDeclaration(path) {\n path.node.declarations.forEach((decl) => {\n if (\n n.VariableDeclarator.check(decl) &&\n n.CallExpression.check(decl.init) &&\n n.Identifier.check(decl.init.callee) &&\n decl.init.callee.name === 'require'\n ) {\n const arg = decl.init.arguments[0];\n\n if (n.Literal.check(arg)) {\n if (arg.value === 'intlayer') {\n if (n.ObjectPattern.check(decl.id)) {\n decl.id.properties.forEach((prop) => {\n if (\n n.Property.check(prop) &&\n (n.Identifier.check(prop.key) ||\n n.Identifier.check(prop.value))\n ) {\n const name = n.Identifier.check(prop.key)\n ? prop.key.name\n : (prop.value as any).name;\n existingCoreImports.add(name);\n }\n });\n } else if (n.Identifier.check(decl.id)) {\n // Handle const intlayer = require('intlayer')\n existingCoreImports.add(decl.id.name);\n }\n }\n }\n }\n });\n\n return false;\n },\n });\n\n const missingCore = Array.from(requiredImports).filter(\n (imp) => !existingCoreImports.has(imp)\n );\n\n if (missingCore.length === 0) return;\n\n if (isESM) {\n if (coreImportPath) {\n missingCore.forEach((imp) => {\n coreImportPath.node.specifiers.push(\n b.importSpecifier(b.identifier(imp))\n );\n });\n coreImportPath.node.specifiers.sort((a: any, b: any) =>\n a.imported.name.localeCompare(b.imported.name)\n );\n } else {\n const specifiers = missingCore\n .sort()\n .map((imp) => b.importSpecifier(b.identifier(imp)));\n const newImport = b.importDeclaration(specifiers, b.literal('intlayer'));\n ast.program.body.unshift(newImport);\n }\n } else {\n let insertIndex = 0;\n\n if (\n ast.program.body.length > 0 &&\n n.ExpressionStatement.check(ast.program.body[0]) &&\n n.Literal.check(ast.program.body[0].expression)\n ) {\n insertIndex = 1; // Insert after 'use strict'\n }\n const cjsLines: any[] = [];\n\n const properties = missingCore.sort().map((imp) => {\n const prop = b.property('init', b.identifier(imp), b.identifier(imp));\n prop.shorthand = true;\n\n return prop;\n });\n cjsLines.push(\n b.variableDeclaration('const', [\n b.variableDeclarator(\n b.objectPattern(properties),\n b.callExpression(b.identifier('require'), [b.literal('intlayer')])\n ),\n ])\n );\n\n ast.program.body.splice(insertIndex, 0, ...cjsLines);\n }\n};\n\n/**\n * Updates a JS/TS file seamlessly to map new localization keys, arrays, complex nodes and nested dictionaries gracefully using AST updates via Recast parser.\n */\nexport const transformJSFile = async (\n fileContent: string,\n dictionary: Dictionary,\n fallbackLocale?: Locale,\n noMetadata?: boolean\n): Promise<string> => {\n if (!dictionary || typeof dictionary !== 'object') return fileContent;\n\n let ast: any;\n try {\n ast = recast.parse(fileContent, {\n parser: babelTsParser,\n });\n } catch (error) {\n console.error({ error });\n return fileContent;\n }\n\n let rootObject: any = null;\n let isESM = false;\n\n recast.visit(ast, {\n visitExportDefaultDeclaration() {\n isESM = true;\n\n return false;\n },\n visitImportDeclaration() {\n isESM = true;\n\n return false;\n },\n });\n\n recast.visit(ast, {\n visitExportDefaultDeclaration(path) {\n const decl = path.node.declaration;\n const unwrappedDecl = unwrap(decl);\n\n if (n.ObjectExpression.check(unwrappedDecl)) {\n rootObject = unwrappedDecl;\n } else if (n.Identifier.check(unwrappedDecl)) {\n const varName = unwrappedDecl.name;\n recast.visit(ast, {\n visitVariableDeclarator(vp) {\n const unwrappedInit = unwrap(vp.node.init);\n\n if (\n n.Identifier.check(vp.node.id) &&\n vp.node.id.name === varName &&\n n.ObjectExpression.check(unwrappedInit)\n ) {\n rootObject = unwrappedInit;\n }\n\n return false;\n },\n });\n }\n\n return false;\n },\n visitAssignmentExpression(path) {\n const left = path.node.left;\n\n if (n.MemberExpression.check(left)) {\n if (\n n.Identifier.check(left.object) &&\n left.object.name === 'module' &&\n n.Identifier.check(left.property) &&\n left.property.name === 'exports'\n ) {\n const unwrappedRight = unwrap(path.node.right);\n\n if (n.ObjectExpression.check(unwrappedRight)) {\n rootObject = unwrappedRight;\n }\n }\n\n if (\n n.Identifier.check(left.object) &&\n left.object.name === 'exports' &&\n n.Identifier.check(left.property) &&\n left.property.name === 'default'\n ) {\n const unwrappedRight = unwrap(path.node.right);\n\n if (n.ObjectExpression.check(unwrappedRight)) {\n rootObject = unwrappedRight;\n }\n }\n }\n this.traverse(path);\n },\n });\n\n if (!rootObject) {\n recast.visit(ast, {\n visitVariableDeclarator(path) {\n const unwrappedInit = unwrap(path.node.init);\n\n if (!rootObject && n.ObjectExpression.check(unwrappedInit)) {\n rootObject = unwrappedInit;\n }\n\n return false;\n },\n });\n }\n\n if (!rootObject) return fileContent;\n\n const requiredImports = new Set<string>();\n const effectiveFallbackLocale = (fallbackLocale as string) ?? 'en';\n\n const metadataProperties = [\n 'id',\n 'locale',\n 'filled',\n 'fill',\n 'title',\n 'description',\n 'tags',\n 'version',\n 'priority',\n 'contentAutoTransformation',\n ];\n\n if (noMetadata) {\n // Remove key, content and metadata properties if they exist\n rootObject.properties = rootObject.properties.filter((prop: any) => {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n let propName = '';\n if (n.Identifier.check(prop.key)) propName = prop.key.name;\n else if (n.StringLiteral.check(prop.key)) propName = prop.key.value;\n else if (n.Literal.check(prop.key)) propName = String(prop.key.value);\n\n return !['key', 'content', ...metadataProperties].includes(propName);\n }\n return true;\n });\n\n // Update satisfies type if exists\n recast.visit(ast, {\n visitNode(path) {\n const node = path.node;\n if (\n (n.TSSatisfiesExpression?.check(node) ||\n node.type === 'TSSatisfiesExpression') &&\n (node as any).typeAnnotation &&\n n.TSTypeReference.check((node as any).typeAnnotation) &&\n n.Identifier.check((node as any).typeAnnotation.typeName) &&\n (node as any).typeAnnotation.typeName.name === 'Dictionary'\n ) {\n (node as any).typeAnnotation = b.tsIndexedAccessType(\n b.tsTypeReference(b.identifier('Dictionary')),\n b.tsLiteralType(b.stringLiteral('content'))\n );\n }\n this.traverse(path);\n },\n });\n } else {\n for (const prop of metadataProperties) {\n if ((dictionary as any)[prop] !== undefined) {\n updateObjectLiteral(\n rootObject,\n { [prop]: (dictionary as any)[prop] },\n undefined,\n requiredImports\n );\n }\n }\n }\n\n if (dictionary.content !== undefined) {\n updateObjectLiteral(\n rootObject,\n noMetadata\n ? (dictionary.content as Record<string, any>)\n : { content: dictionary.content },\n effecti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AI;EACpB,EACF,CAAC;CACH,OACE,KAAK,MAAM,QAAQ,oBACjB,IAAK,WAAmB,UAAU,QAChC,oBACE,YACA,GAAG,OAAQ,WAAmB,MAAM,GACpC,QACA,eACF;CAKN,IAAI,WAAW,YAAY,QACzB,oBACE,YACA,aACK,WAAW,UACZ,EAAE,SAAS,WAAW,QAAQ,GAClC,yBACA,eACF;CAGF,WAAW,KAAK,iBAAiB,KAAK;CAEtC,OAAO,OAAO,MAAM,GAAG,CAAC,CAAC;AAC3B"}
|
|
1
|
+
{"version":3,"file":"transformJSFile.cjs","names":["NodeTypes","getNodeType","babelTsParser"],"sources":["../../../src/writeContentDeclaration/transformJSFile.ts"],"sourcesContent":["import { getNodeType } from '@intlayer/core/dictionaryManipulator';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { ContentNode, Dictionary } from '@intlayer/types/dictionary';\nimport type { NodeType } from '@intlayer/types/nodeType';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport * as recast from 'recast';\nimport { babelTsParser } from '../utils/babelParser';\n\nconst b = recast.types.builders;\nconst n = recast.types.namedTypes;\n\n/**\n * Name of an `intlayer` helper function a node type is printed as.\n *\n * Mirrors the transpiler helpers re-exported by the `intlayer` package\n * (`@intlayer/core/transpiler`).\n */\ntype HelperName =\n | 't'\n | 'enu'\n | 'plural'\n | 'cond'\n | 'gender'\n | 'select'\n | 'insert'\n | 'md'\n | 'html'\n | 'file'\n | 'nest';\n\n/**\n * How a {@link NodeType} is materialized back into source code.\n *\n * - `helperRecord` — printed as `helper({ … })`. The node data is a record of\n * variants (locales, plural categories, conditions, cases…) whose values are\n * rebuilt recursively and merged into the existing object literal.\n * - `helperValue` — printed as `helper(value)`. The node data is a single\n * content, itself possibly another node (e.g. `md(t({ … }))`).\n * - `nesting` — printed as `nest(dictionaryKey, path?)`.\n * - `unwrap` — not a source-level helper: the wrapped value replaces the node,\n * so `{ nodeType: 'text', text: 'Hello' }` is printed as `\"Hello\"`.\n * - `preserve` — framework elements have no data representation, so the\n * existing source expression is kept untouched and nothing is written when\n * there is none.\n * - `structural` — plain objects, arrays and unrecognized nodes, rebuilt by the\n * generic object/array branches.\n */\ntype NodeTypeStrategy =\n | {\n kind: 'helperRecord';\n helper: HelperName;\n /**\n * Extra arguments appended after the record argument, rebuilt from the\n * node attributes (e.g. the variable name carried by a `select` node).\n */\n getExtraArguments?: (\n node: Record<string, unknown>\n ) => recast.types.namedTypes.Literal[];\n }\n | { kind: 'helperValue'; helper: HelperName }\n | { kind: 'nesting'; helper: HelperName }\n | { kind: 'unwrap' }\n | { kind: 'preserve' }\n | { kind: 'structural' };\n\n/**\n * Every {@link NodeType} and how it is written back to a JS/TS declaration file.\n *\n * Typed as `Record<NodeType, NodeTypeStrategy>` so that adding a node type to\n * `@intlayer/types` without registering it here becomes a compile-time error —\n * the same guarantee `getNodeType` gives on the read side.\n */\nconst nodeTypeStrategies: Record<NodeType, NodeTypeStrategy> = {\n [NodeTypes.TRANSLATION]: { kind: 'helperRecord', helper: 't' },\n [NodeTypes.ENUMERATION]: { kind: 'helperRecord', helper: 'enu' },\n [NodeTypes.PLURAL]: { kind: 'helperRecord', helper: 'plural' },\n [NodeTypes.CONDITION]: { kind: 'helperRecord', helper: 'cond' },\n [NodeTypes.GENDER]: { kind: 'helperRecord', helper: 'gender' },\n [NodeTypes.SELECT]: {\n kind: 'helperRecord',\n helper: 'select',\n getExtraArguments: (node) =>\n typeof node.variable === 'string' && node.variable.length > 0\n ? [b.literal(node.variable)]\n : [],\n },\n [NodeTypes.INSERTION]: { kind: 'helperValue', helper: 'insert' },\n [NodeTypes.MARKDOWN]: { kind: 'helperValue', helper: 'md' },\n [NodeTypes.HTML]: { kind: 'helperValue', helper: 'html' },\n [NodeTypes.FILE]: { kind: 'helperValue', helper: 'file' },\n [NodeTypes.NESTED]: { kind: 'nesting', helper: 'nest' },\n [NodeTypes.TEXT]: { kind: 'unwrap' },\n [NodeTypes.NUMBER]: { kind: 'unwrap' },\n [NodeTypes.BOOLEAN]: { kind: 'unwrap' },\n [NodeTypes.NULL]: { kind: 'unwrap' },\n [NodeTypes.REACT_NODE]: { kind: 'preserve' },\n [NodeTypes.PREACT_NODE]: { kind: 'preserve' },\n [NodeTypes.SOLID_NODE]: { kind: 'preserve' },\n [NodeTypes.OBJECT]: { kind: 'structural' },\n [NodeTypes.ARRAY]: { kind: 'structural' },\n [NodeTypes.UNKNOWN]: { kind: 'structural' },\n};\n\n/** Every `intlayer` helper the transform is allowed to rewrite. */\nconst helperNames = new Set<string>(\n Object.values(nodeTypeStrategies).flatMap((strategy) =>\n 'helper' in strategy ? [strategy.helper] : []\n )\n);\n\n/** Helpers wrapping a single content, e.g. `md(t({ … }))`. */\nconst wrapperHelperNames = new Set<string>(\n Object.values(nodeTypeStrategies).flatMap((strategy) =>\n strategy.kind === 'helperValue' ? [strategy.helper] : []\n )\n);\n\n/**\n * Returned by {@link buildNodeForValue} when a value must not be written to the\n * source file — framework elements and functions have no data representation,\n * so the original expression (when there is one) is left untouched and no new\n * property is created otherwise.\n */\nconst SKIP_WRITE = Symbol('intlayer.skipWrite');\n\n/**\n * Unwraps TypeScript/Babel expression wrappers (satisfies, as, !, <Type>).\n * Uses string fallbacks to bypass outdated ast-types definitions.\n */\nconst unwrap = (node: any) => {\n while (\n node &&\n (n.TSSatisfiesExpression?.check(node) ||\n n.TSAsExpression?.check(node) ||\n n.TSTypeAssertion?.check(node) ||\n n.TSNonNullExpression?.check(node) ||\n [\n 'TSSatisfiesExpression',\n 'TSAsExpression',\n 'TSTypeAssertion',\n 'TSNonNullExpression',\n ].includes(node.type))\n ) {\n node = node.expression;\n }\n return node;\n};\n\n/**\n * Robustly finds a property in a recast ObjectExpression.\n * Handles quoted (\"key\") or unquoted (key) properties.\n */\nconst getMatchingProperty = (node: any, key: string) => {\n return node.properties.find((prop: any) => {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n if (n.Identifier.check(prop.key) && prop.key.name === key) return true;\n\n if (n.StringLiteral.check(prop.key) && prop.key.value === key)\n return true;\n\n if (n.Literal.check(prop.key) && prop.key.value === key) return true;\n }\n\n return false;\n });\n};\n\n/**\n * Synchronizes numeric suffixes across locales.\n * E.g. \"Hello 1\" -> \"Hello 3\" updates \"Bonjour 1\" to \"Bonjour 3\".\n */\nconst syncNumericSuffixAcrossLocales = (\n existingNode: any,\n fallbackLocaleCode: string,\n newFallbackValue: string\n) => {\n const trailingNumberMatch = newFallbackValue.match(/\\d+(?!.*\\d)/);\n if (!trailingNumberMatch) return;\n const newTrailingNumber = trailingNumberMatch[0];\n\n if (n.ObjectExpression.check(existingNode)) {\n for (const prop of existingNode.properties) {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n let propName = '';\n\n if (n.Identifier.check(prop.key)) propName = prop.key.name;\n else if (\n n.Literal.check(prop.key) &&\n typeof prop.key.value === 'string'\n )\n propName = prop.key.value;\n else if (n.StringLiteral.check(prop.key)) propName = prop.key.value;\n\n if (propName && propName !== fallbackLocaleCode) {\n if (\n n.Literal.check(prop.value) &&\n typeof prop.value.value === 'string'\n ) {\n const currentValue = prop.value.value;\n const currentTrailingNumberMatch =\n currentValue.match(/\\d+(?!.*\\d)/);\n\n if (currentTrailingNumberMatch) {\n prop.value = b.literal(\n currentValue.replace(/(\\d+)(?!.*\\d)/, newTrailingNumber)\n );\n }\n } else if (n.StringLiteral.check(prop.value)) {\n const currentValue = prop.value.value;\n const currentTrailingNumberMatch =\n currentValue.match(/\\d+(?!.*\\d)/);\n\n if (currentTrailingNumberMatch) {\n prop.value = b.stringLiteral(\n currentValue.replace(/(\\d+)(?!.*\\d)/, newTrailingNumber)\n );\n }\n }\n }\n }\n }\n }\n};\n\n/**\n * Checks if a value represents a multilingual Intlayer node.\n *\n * A node is multilingual if it is a Translation node, if it wraps one\n * (Markdown, HTML, Insertion…), or if any of its variants contains one\n * (Enumeration, Plural, Condition, Gender, Select…).\n */\nconst isMultilingualNode = (val: any): boolean => {\n if (typeof val !== 'object' || val === null || Array.isArray(val)) {\n return false;\n }\n\n const nodeType = getNodeType(val as ContentNode);\n\n if (nodeType === NodeTypes.TRANSLATION) {\n return true;\n }\n\n const strategy = nodeTypeStrategies[nodeType];\n const nodeData = (val as any)[nodeType];\n\n if (strategy.kind === 'helperValue' || strategy.kind === 'unwrap') {\n return isMultilingualNode(nodeData);\n }\n\n if (\n strategy.kind === 'helperRecord' &&\n nodeData &&\n typeof nodeData === 'object'\n ) {\n return Object.values(nodeData).some((variant) =>\n isMultilingualNode(variant)\n );\n }\n\n return false;\n};\n\n/**\n * Checks whether two AST nodes are literals holding the same value.\n */\nconst isEquivalentLiteral = (left: any, right: any): boolean => {\n const isLiteral = (node: any) =>\n n.Literal.check(node) ||\n n.StringLiteral.check(node) ||\n n.NumericLiteral.check(node) ||\n n.BooleanLiteral.check(node);\n\n return isLiteral(left) && isLiteral(right) && left.value === right.value;\n};\n\n/**\n * Aligns the arguments of an existing call expression with the desired ones.\n *\n * Mutates the call only when the arguments actually differ, so Recast keeps the\n * original formatting (and quote style) of calls that did not change.\n */\nconst syncCallArguments = (callNode: any, desiredArguments: any[]) => {\n const isUnchanged =\n callNode.arguments.length === desiredArguments.length &&\n desiredArguments.every((desired, index) => {\n const current = callNode.arguments[index];\n\n return current === desired || isEquivalentLiteral(current, desired);\n });\n\n if (!isUnchanged) {\n callNode.arguments = desiredArguments;\n }\n};\n\n/**\n * Recursively builds or updates an AST node for a given dictionary value.\n *\n * Returns {@link SKIP_WRITE} when the value cannot be represented in source and\n * no existing expression can be kept.\n */\nconst buildNodeForValue = (\n val: any,\n existingNode: any,\n fallbackLocale: string | undefined, // In per-locale mode, this is the locale of the file\n requiredImports: Set<string>\n): any => {\n // Values with no source representation must never overwrite existing code.\n if (val === undefined || typeof val === 'function') {\n return existingNode ?? SKIP_WRITE;\n }\n\n const unwrappedExisting = unwrap(existingNode);\n\n // --- CRITICAL GUARD: STRICT AST PRESERVATION ---\n // If the existing node is code (JSX, Variables, standard functions), leave it alone.\n // Only allow updates to literals, plain objects, arrays, and Intlayer helpers.\n if (unwrappedExisting) {\n const isUpdatableNode =\n n.Literal.check(unwrappedExisting) ||\n n.StringLiteral.check(unwrappedExisting) ||\n n.NumericLiteral.check(unwrappedExisting) ||\n n.BooleanLiteral.check(unwrappedExisting) ||\n n.TemplateLiteral.check(unwrappedExisting) ||\n n.ObjectExpression.check(unwrappedExisting) ||\n n.ArrayExpression.check(unwrappedExisting) ||\n (n.CallExpression.check(unwrappedExisting) &&\n n.Identifier.check(unwrappedExisting.callee) &&\n helperNames.has(unwrappedExisting.callee.name));\n\n if (!isUpdatableNode) {\n return existingNode;\n }\n }\n\n // If we are in per-locale mode (fallbackLocale is set)\n // and the value is not already a complex translation node,\n // we want to store it as a simple literal, NOT wrapped in t().\n if (fallbackLocale && !existingNode && !isMultilingualNode(val)) {\n if (val === null) return b.literal(null);\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n if (typeof val === 'string' && val.includes('\\n')) {\n return b.templateLiteral(\n [b.templateElement({ raw: val, cooked: val }, true)],\n []\n );\n }\n return b.literal(val);\n }\n }\n\n if (fallbackLocale && existingNode && !isMultilingualNode(val)) {\n if (\n n.CallExpression.check(existingNode) &&\n n.Identifier.check(existingNode.callee) &&\n existingNode.callee.name === 't'\n ) {\n const arg = unwrap(existingNode.arguments[0]);\n\n if (n.ObjectExpression.check(arg)) {\n if (typeof val === 'string') {\n syncNumericSuffixAcrossLocales(arg, fallbackLocale, val);\n }\n updateObjectLiteral(\n arg,\n { [fallbackLocale]: val },\n fallbackLocale,\n requiredImports\n );\n\n if (!fallbackLocale) {\n requiredImports.add('t');\n }\n\n return existingNode;\n }\n }\n\n // Wrapped translations — `md(t({ … }))`, `html(t({ … }))`, `insert(t({ … }))`:\n // update the inner translation in place instead of replacing the wrapper.\n if (\n (!val || typeof val !== 'object') &&\n n.CallExpression.check(existingNode) &&\n n.Identifier.check(existingNode.callee) &&\n wrapperHelperNames.has(existingNode.callee.name)\n ) {\n const wrapperName = existingNode.callee.name;\n const innerArg = existingNode.arguments[0];\n\n if (\n n.CallExpression.check(innerArg) &&\n n.Identifier.check(innerArg.callee) &&\n innerArg.callee.name === 't'\n ) {\n const tArg = unwrap(innerArg.arguments[0]);\n\n if (n.ObjectExpression.check(tArg)) {\n if (typeof val === 'string') {\n syncNumericSuffixAcrossLocales(tArg, fallbackLocale, val);\n }\n updateObjectLiteral(\n tArg,\n { [fallbackLocale]: val },\n fallbackLocale,\n requiredImports\n );\n requiredImports.add(wrapperName);\n requiredImports.add('t');\n\n return existingNode;\n }\n }\n }\n }\n\n // 1. Primitives\n if (val === null) return b.literal(null);\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n if (unwrappedExisting) {\n // Preserve existing template literals (backticks)\n if (\n n.TemplateLiteral.check(unwrappedExisting) &&\n unwrappedExisting.quasis[0] &&\n unwrappedExisting.expressions.length === 0\n ) {\n unwrappedExisting.quasis[0].value.raw = String(val);\n unwrappedExisting.quasis[0].value.cooked = String(val);\n return existingNode;\n }\n // Preserve existing standard literals (keeps quote styling)\n if (\n n.Literal.check(unwrappedExisting) ||\n n.StringLiteral.check(unwrappedExisting)\n ) {\n unwrappedExisting.value = val;\n return existingNode;\n }\n }\n\n // Force multiline strings to use Template Literals\n if (typeof val === 'string' && val.includes('\\n')) {\n return b.templateLiteral(\n [b.templateElement({ raw: val, cooked: val }, true)],\n []\n );\n }\n return b.literal(val);\n }\n\n // 2. Arrays\n if (Array.isArray(val)) {\n if (unwrappedExisting && n.ArrayExpression.check(unwrappedExisting)) {\n const elements = [...unwrappedExisting.elements];\n val.forEach((item, i) => {\n const elementNode = buildNodeForValue(\n item,\n elements[i],\n fallbackLocale,\n requiredImports\n );\n\n elements[i] =\n elementNode === SKIP_WRITE\n ? (elements[i] ?? b.literal(null))\n : elementNode;\n });\n\n if (elements.length > val.length) elements.length = val.length;\n unwrappedExisting.elements = elements as any;\n\n return existingNode;\n } else {\n return b.arrayExpression(\n val.map((item) => {\n const elementNode = buildNodeForValue(\n item,\n null,\n fallbackLocale,\n requiredImports\n );\n\n return elementNode === SKIP_WRITE ? b.literal(null) : elementNode;\n })\n );\n }\n }\n\n // 3. Intlayer Specialized Nodes — dispatched through the exhaustive registry\n const nodeType =\n val && typeof val === 'object' && !Array.isArray(val)\n ? getNodeType(val as ContentNode)\n : null;\n\n if (nodeType) {\n const strategy = nodeTypeStrategies[nodeType];\n\n // Framework elements (React/Preact/Solid) cannot be serialized back to\n // source: keep whatever the file already declares.\n if (strategy.kind === 'preserve') {\n return existingNode ?? SKIP_WRITE;\n }\n\n const hasNodeData = Object.hasOwn(val as object, nodeType);\n const nodeData = (val as any)[nodeType];\n\n // A typed node missing its payload is malformed — fall back to the generic\n // object branch rather than printing a broken helper call.\n if (strategy.kind !== 'structural' && hasNodeData) {\n if (strategy.kind === 'unwrap') {\n return buildNodeForValue(\n nodeData,\n existingNode,\n fallbackLocale,\n requiredImports\n );\n }\n\n const { helper } = strategy;\n\n requiredImports.add(helper);\n\n const isMatchingCall =\n existingNode &&\n n.CallExpression.check(existingNode) &&\n n.Identifier.check(existingNode.callee) &&\n existingNode.callee.name === helper;\n\n if (strategy.kind === 'helperRecord') {\n const recordArgument =\n isMatchingCall &&\n existingNode.arguments.length > 0 &&\n n.ObjectExpression.check(existingNode.arguments[0])\n ? existingNode.arguments[0]\n : b.objectExpression([]);\n\n updateObjectLiteral(\n recordArgument,\n nodeData ?? {},\n fallbackLocale,\n requiredImports\n );\n\n const callArguments = [\n recordArgument,\n ...(strategy.getExtraArguments?.(val as Record<string, unknown>) ??\n []),\n ];\n\n if (isMatchingCall) {\n syncCallArguments(existingNode, callArguments);\n\n return existingNode;\n }\n\n return b.callExpression(b.identifier(helper), callArguments);\n }\n\n if (strategy.kind === 'helperValue') {\n const contentArgument = buildNodeForValue(\n nodeData,\n isMatchingCall && existingNode.arguments.length > 0\n ? existingNode.arguments[0]\n : null,\n fallbackLocale,\n requiredImports\n );\n\n if (contentArgument === SKIP_WRITE) {\n return existingNode ?? SKIP_WRITE;\n }\n\n if (isMatchingCall) {\n // Keep any extra argument the source declares (custom components\n // passed to `md()` / `html()`), which the node does not carry back.\n syncCallArguments(existingNode, [\n contentArgument,\n ...existingNode.arguments.slice(1),\n ]);\n\n return existingNode;\n }\n\n return b.callExpression(b.identifier(helper), [contentArgument]);\n }\n\n // strategy.kind === 'nesting'\n const callArguments = [b.literal(nodeData?.dictionaryKey ?? '')];\n\n if (nodeData?.path) callArguments.push(b.literal(nodeData.path));\n\n if (isMatchingCall) {\n syncCallArguments(existingNode, callArguments);\n\n return existingNode;\n }\n\n return b.callExpression(b.identifier(helper), callArguments);\n }\n }\n\n // 4. Plain Object\n const objNode =\n unwrappedExisting && n.ObjectExpression.check(unwrappedExisting)\n ? unwrappedExisting\n : b.objectExpression([]);\n\n updateObjectLiteral(objNode, val, fallbackLocale, requiredImports);\n\n return existingNode && unwrappedExisting === existingNode\n ? objNode\n : existingNode || objNode;\n};\n\n/**\n * Recursively updates the AST object literal properties.\n */\nconst updateObjectLiteral = (\n node: recast.types.namedTypes.ObjectExpression,\n data: Record<string, any>,\n fallbackLocale: string | undefined,\n requiredImports: Set<string>\n) => {\n for (const [key, val] of Object.entries(data)) {\n if (val === undefined) continue;\n\n const existingProp = getMatchingProperty(node, key);\n\n if (existingProp) {\n const valueNode = buildNodeForValue(\n val,\n existingProp.value,\n fallbackLocale,\n requiredImports\n );\n\n if (valueNode !== SKIP_WRITE) {\n existingProp.value = valueNode;\n }\n } else {\n const isValidId = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key);\n const keyNode = isValidId ? b.identifier(key) : b.literal(key);\n const valueNode = buildNodeForValue(\n val,\n null,\n fallbackLocale,\n requiredImports\n );\n\n if (valueNode === SKIP_WRITE) continue;\n\n node.properties.push(b.property('init', keyNode, valueNode));\n }\n }\n};\n\n/**\n * Modifies the AST's top-level imports to inject dynamically needed helper utilities seamlessly.\n */\nconst addImports = (ast: any, requiredImports: Set<string>, isESM: boolean) => {\n if (requiredImports.size === 0) return;\n\n const existingCoreImports = new Set<string>();\n let coreImportPath: any = null;\n\n recast.visit(ast, {\n visitImportDeclaration(path) {\n const source = path.node.source.value;\n\n if (source === 'intlayer') {\n coreImportPath = path;\n path.node.specifiers?.forEach((spec) => {\n if (\n n.ImportSpecifier.check(spec) &&\n typeof spec.imported.name === 'string'\n ) {\n existingCoreImports.add(spec.imported.name);\n }\n });\n }\n\n return false;\n },\n visitVariableDeclaration(path) {\n path.node.declarations.forEach((decl) => {\n if (\n n.VariableDeclarator.check(decl) &&\n n.CallExpression.check(decl.init) &&\n n.Identifier.check(decl.init.callee) &&\n decl.init.callee.name === 'require'\n ) {\n const arg = decl.init.arguments[0];\n\n if (n.Literal.check(arg)) {\n if (arg.value === 'intlayer') {\n if (n.ObjectPattern.check(decl.id)) {\n decl.id.properties.forEach((prop) => {\n if (\n n.Property.check(prop) &&\n (n.Identifier.check(prop.key) ||\n n.Identifier.check(prop.value))\n ) {\n const name = n.Identifier.check(prop.key)\n ? prop.key.name\n : (prop.value as any).name;\n existingCoreImports.add(name);\n }\n });\n } else if (n.Identifier.check(decl.id)) {\n // Handle const intlayer = require('intlayer')\n existingCoreImports.add(decl.id.name);\n }\n }\n }\n }\n });\n\n return false;\n },\n });\n\n const missingCore = Array.from(requiredImports).filter(\n (imp) => !existingCoreImports.has(imp)\n );\n\n if (missingCore.length === 0) return;\n\n if (isESM) {\n if (coreImportPath) {\n missingCore.forEach((imp) => {\n coreImportPath.node.specifiers.push(\n b.importSpecifier(b.identifier(imp))\n );\n });\n coreImportPath.node.specifiers.sort((a: any, b: any) =>\n a.imported.name.localeCompare(b.imported.name)\n );\n } else {\n const specifiers = missingCore\n .sort()\n .map((imp) => b.importSpecifier(b.identifier(imp)));\n const newImport = b.importDeclaration(specifiers, b.literal('intlayer'));\n ast.program.body.unshift(newImport);\n }\n } else {\n let insertIndex = 0;\n\n if (\n ast.program.body.length > 0 &&\n n.ExpressionStatement.check(ast.program.body[0]) &&\n n.Literal.check(ast.program.body[0].expression)\n ) {\n insertIndex = 1; // Insert after 'use strict'\n }\n const cjsLines: any[] = [];\n\n const properties = missingCore.sort().map((imp) => {\n const prop = b.property('init', b.identifier(imp), b.identifier(imp));\n prop.shorthand = true;\n\n return prop;\n });\n cjsLines.push(\n b.variableDeclaration('const', [\n b.variableDeclarator(\n b.objectPattern(properties),\n b.callExpression(b.identifier('require'), [b.literal('intlayer')])\n ),\n ])\n );\n\n ast.program.body.splice(insertIndex, 0, ...cjsLines);\n }\n};\n\n/**\n * Updates a JS/TS file seamlessly to map new localization keys, arrays, complex nodes and nested dictionaries gracefully using AST updates via Recast parser.\n */\nexport const transformJSFile = async (\n fileContent: string,\n dictionary: Dictionary,\n fallbackLocale?: Locale,\n noMetadata?: boolean\n): Promise<string> => {\n if (!dictionary || typeof dictionary !== 'object') return fileContent;\n\n let ast: any;\n try {\n ast = recast.parse(fileContent, {\n parser: babelTsParser,\n });\n } catch (error) {\n console.error({ error });\n return fileContent;\n }\n\n let rootObject: any = null;\n let isESM = false;\n\n recast.visit(ast, {\n visitExportDefaultDeclaration() {\n isESM = true;\n\n return false;\n },\n visitImportDeclaration() {\n isESM = true;\n\n return false;\n },\n });\n\n recast.visit(ast, {\n visitExportDefaultDeclaration(path) {\n const decl = path.node.declaration;\n const unwrappedDecl = unwrap(decl);\n\n if (n.ObjectExpression.check(unwrappedDecl)) {\n rootObject = unwrappedDecl;\n } else if (n.Identifier.check(unwrappedDecl)) {\n const varName = unwrappedDecl.name;\n recast.visit(ast, {\n visitVariableDeclarator(vp) {\n const unwrappedInit = unwrap(vp.node.init);\n\n if (\n n.Identifier.check(vp.node.id) &&\n vp.node.id.name === varName &&\n n.ObjectExpression.check(unwrappedInit)\n ) {\n rootObject = unwrappedInit;\n }\n\n return false;\n },\n });\n }\n\n return false;\n },\n visitAssignmentExpression(path) {\n const left = path.node.left;\n\n if (n.MemberExpression.check(left)) {\n if (\n n.Identifier.check(left.object) &&\n left.object.name === 'module' &&\n n.Identifier.check(left.property) &&\n left.property.name === 'exports'\n ) {\n const unwrappedRight = unwrap(path.node.right);\n\n if (n.ObjectExpression.check(unwrappedRight)) {\n rootObject = unwrappedRight;\n }\n }\n\n if (\n n.Identifier.check(left.object) &&\n left.object.name === 'exports' &&\n n.Identifier.check(left.property) &&\n left.property.name === 'default'\n ) {\n const unwrappedRight = unwrap(path.node.right);\n\n if (n.ObjectExpression.check(unwrappedRight)) {\n rootObject = unwrappedRight;\n }\n }\n }\n this.traverse(path);\n },\n });\n\n if (!rootObject) {\n recast.visit(ast, {\n visitVariableDeclarator(path) {\n const unwrappedInit = unwrap(path.node.init);\n\n if (!rootObject && n.ObjectExpression.check(unwrappedInit)) {\n rootObject = unwrappedInit;\n }\n\n return false;\n },\n });\n }\n\n if (!rootObject) return fileContent;\n\n const requiredImports = new Set<string>();\n const effectiveFallbackLocale = (fallbackLocale as string) ?? 'en';\n\n const metadataProperties = [\n 'id',\n 'locale',\n 'filled',\n 'fill',\n 'title',\n 'description',\n 'tags',\n 'version',\n 'priority',\n 'contentAutoTransformation',\n ];\n\n if (noMetadata) {\n // Remove key, content and metadata properties if they exist\n rootObject.properties = rootObject.properties.filter((prop: any) => {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n let propName = '';\n if (n.Identifier.check(prop.key)) propName = prop.key.name;\n else if (n.StringLiteral.check(prop.key)) propName = prop.key.value;\n else if (n.Literal.check(prop.key)) propName = String(prop.key.value);\n\n return !['key', 'content', ...metadataProperties].includes(propName);\n }\n return true;\n });\n\n // Update satisfies type if exists\n recast.visit(ast, {\n visitNode(path) {\n const node = path.node;\n if (\n (n.TSSatisfiesExpression?.check(node) ||\n node.type === 'TSSatisfiesExpression') &&\n (node as any).typeAnnotation &&\n n.TSTypeReference.check((node as any).typeAnnotation) &&\n n.Identifier.check((node as any).typeAnnotation.typeName) &&\n (node as any).typeAnnotation.typeName.name === 'Dictionary'\n ) {\n (node as any).typeAnnotation = b.tsIndexedAccessType(\n b.tsTypeReference(b.identifier('Dictionary')),\n b.tsLiteralType(b.stringLiteral('content'))\n );\n }\n this.traverse(path);\n },\n });\n } else {\n for (const prop of metadataProperties) {\n if ((dictionary as any)[prop] !== undefined) {\n updateObjectLiteral(\n rootObject,\n { [prop]: (dictionary as any)[prop] },\n undefined,\n requiredImports\n );\n }\n }\n }\n\n if (dictionary.content !== undefined) {\n updateObjectLiteral(\n rootObject,\n noMetadata\n ? (dictionary.content as Record<string, any>)\n : { content: dictionary.content },\n effectiveFallbackLocale,\n requiredImports\n );\n }\n\n addImports(ast, requiredImports, isESM);\n\n return recast.print(ast).code;\n};\n"],"mappings":";;;;;;;;;;AAQA,MAAM,IAAI,OAAO,MAAM;AACvB,MAAM,IAAI,OAAO,MAAM;;;;;;;;AA+DvB,MAAM,qBAAyD;EAC5DA,yBAAU,cAAc;EAAE,MAAM;EAAgB,QAAQ;CAAI;EAC5DA,yBAAU,cAAc;EAAE,MAAM;EAAgB,QAAQ;CAAM;EAC9DA,yBAAU,SAAS;EAAE,MAAM;EAAgB,QAAQ;CAAS;EAC5DA,yBAAU,YAAY;EAAE,MAAM;EAAgB,QAAQ;CAAO;EAC7DA,yBAAU,SAAS;EAAE,MAAM;EAAgB,QAAQ;CAAS;EAC5DA,yBAAU,SAAS;EAClB,MAAM;EACN,QAAQ;EACR,oBAAoB,SAClB,OAAO,KAAK,aAAa,YAAY,KAAK,SAAS,SAAS,IACxD,CAAC,EAAE,QAAQ,KAAK,QAAQ,CAAC,IACzB,CAAC;CACT;EACCA,yBAAU,YAAY;EAAE,MAAM;EAAe,QAAQ;CAAS;EAC9DA,yBAAU,WAAW;EAAE,MAAM;EAAe,QAAQ;CAAK;EACzDA,yBAAU,OAAO;EAAE,MAAM;EAAe,QAAQ;CAAO;EACvDA,yBAAU,OAAO;EAAE,MAAM;EAAe,QAAQ;CAAO;EACvDA,yBAAU,SAAS;EAAE,MAAM;EAAW,QAAQ;CAAO;EACrDA,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AAO,MAAM,KAAK,EAChB,UAAU,MAAM;GACd,MAAM,OAAO,KAAK;GAClB,KACG,EAAE,uBAAuB,MAAM,IAAI,KAClC,KAAK,SAAS,4BACf,KAAa,kBACd,EAAE,gBAAgB,MAAO,KAAa,cAAc,KACpD,EAAE,WAAW,MAAO,KAAa,eAAe,QAAQ,KACvD,KAAa,eAAe,SAAS,SAAS,cAE/C,AAAC,KAAa,iBAAiB,EAAE,oBAC/B,EAAE,gBAAgB,EAAE,WAAW,YAAY,CAAC,GAC5C,EAAE,cAAc,EAAE,cAAc,SAAS,CAAC,CAC5C;GAEF,KAAK,SAAS,IAAI;EACpB,EACF,CAAC;CACH,OACE,KAAK,MAAM,QAAQ,oBACjB,IAAK,WAAmB,UAAU,QAChC,oBACE,YACA,GAAG,OAAQ,WAAmB,MAAM,GACpC,QACA,eACF;CAKN,IAAI,WAAW,YAAY,QACzB,oBACE,YACA,aACK,WAAW,UACZ,EAAE,SAAS,WAAW,QAAQ,GAClC,yBACA,eACF;CAGF,WAAW,KAAK,iBAAiB,KAAK;CAEtC,OAAO,OAAO,MAAM,GAAG,CAAC,CAAC;AAC3B"}
|
|
@@ -60,11 +60,12 @@ const updateObjectLiteral = (node, data) => {
|
|
|
60
60
|
c.trailing = true;
|
|
61
61
|
}
|
|
62
62
|
});
|
|
63
|
-
if (isPlainObject(val))
|
|
64
|
-
|
|
65
|
-
if (
|
|
66
|
-
|
|
67
|
-
|
|
63
|
+
if (isPlainObject(val)) {
|
|
64
|
+
if (existingProp && n.ObjectExpression.check(existingProp.value)) updateObjectLiteral(existingProp.value, val);
|
|
65
|
+
else if (existingProp) {
|
|
66
|
+
if (!(n.Literal.check(existingProp.value) && existingProp.value.value === val)) existingProp.value = buildASTNode(val);
|
|
67
|
+
} else node.properties.push(b.property("init", b.stringLiteral(key), buildASTNode(val)));
|
|
68
|
+
} else if (existingProp) {
|
|
68
69
|
if (!isPrimitiveEqual(existingProp.value, val)) existingProp.value = buildASTNode(val);
|
|
69
70
|
} else node.properties.push(b.property("init", b.stringLiteral(key), buildASTNode(val)));
|
|
70
71
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transformJSONFile.cjs","names":[],"sources":["../../../src/writeContentDeclaration/transformJSONFile.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport * as recast from 'recast';\n\nconst b = recast.types.builders;\nconst n = recast.types.namedTypes;\n\n/**\n * Checks if a value is a plain object (and not null/array)\n */\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n};\n\n/**\n * Checks if a recast AST node value matches the incoming primitive value.\n */\nconst isPrimitiveEqual = (astNode: any, val: unknown): boolean => {\n if (val === null) {\n return n.Literal.check(astNode) && astNode.value === null;\n }\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n return (\n (n.Literal.check(astNode) ||\n n.StringLiteral.check(astNode) ||\n n.NumericLiteral.check(astNode) ||\n n.BooleanLiteral.check(astNode)) &&\n astNode.value === val\n );\n }\n return false;\n};\n\n/**\n * Robustly finds a property in a recast ObjectExpression.\n * Handles quoted (\"key\") or unquoted (key) properties.\n */\nconst getMatchingProperty = (node: any, key: string) => {\n return node.properties.find((prop: any) => {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n if (n.Identifier.check(prop.key) && prop.key.name === key) return true;\n if (n.StringLiteral.check(prop.key) && prop.key.value === key)\n return true;\n if (n.Literal.check(prop.key) && prop.key.value === key) return true;\n }\n return false;\n });\n};\n\n/**\n * Recursively builds a clean recast AST node from a plain JS value.\n * Because these nodes lack `loc` tracking, recast is forced to pretty-print them.\n */\nconst buildASTNode = (val: unknown): any => {\n if (val === null) return b.literal(null);\n\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n return b.literal(val);\n }\n\n if (Array.isArray(val)) {\n return b.arrayExpression(val.map((item) => buildASTNode(item)));\n }\n\n if (isPlainObject(val)) {\n return b.objectExpression(\n Object.entries(val)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]) =>\n b.property('init', b.stringLiteral(k), buildASTNode(v))\n )\n );\n }\n\n return b.literal(null); // Fallback\n};\n\n/**\n * Recursively updates the AST object literal with new data.\n */\nconst updateObjectLiteral = (node: any, data: Record<string, any>) => {\n for (const [key, val] of Object.entries(data)) {\n if (val === undefined) {\n continue;\n }\n\n const existingProp = getMatchingProperty(node, key);\n\n if (existingProp?.comments) {\n existingProp.comments.forEach((c: any) => {\n if ((c.type === 'Line' || c.type === 'CommentLine') && c.trailing) {\n // Convert to block comment and tag it to force Recast to print it inline\n c.type = c.type === 'Line' ? 'Block' : 'CommentBlock';\n c.value = `__INLINE_LINE__${c.value}`;\n c.leading = false;\n c.trailing = true;\n }\n });\n }\n\n if (isPlainObject(val)) {\n if (existingProp && n.ObjectExpression.check(existingProp.value)) {\n updateObjectLiteral(existingProp.value, val);\n } else {\n if (existingProp) {\n // Prevent AST invalidation if the primitive value is identical\n const isIdentical =\n n.Literal.check(existingProp.value) &&\n existingProp.value.value === val;\n\n if (!isIdentical) {\n existingProp.value = buildASTNode(val);\n }\n } else {\n node.properties.push(\n b.property('init', b.stringLiteral(key), buildASTNode(val))\n );\n }\n }\n } else {\n // Handle primitives and arrays\n if (existingProp) {\n // Skip assignment if the primitive value is identical\n if (!isPrimitiveEqual(existingProp.value, val)) {\n existingProp.value = buildASTNode(val);\n }\n } else {\n node.properties.push(\n b.property('init', b.stringLiteral(key), buildASTNode(val))\n );\n }\n }\n }\n};\n\nexport const transformJSONFile = (\n fileContent: string,\n dictionary: Dictionary,\n noMetadata?: boolean\n): string => {\n // Wrap content to create valid syntax for the parser\n const wrappedContent = `const _config = ${fileContent.trim() || '{}'};`;\n\n let ast: ReturnType<typeof recast.parse>;\n try {\n ast = recast.parse(wrappedContent);\n } catch {\n // Fallback if parsing failed\n return JSON.stringify(\n noMetadata ? dictionary.content : dictionary,\n null,\n 2\n );\n }\n\n // Navigate the AST to locate the object literal initialized to `_config`\n const declaration = ast.program.body[0];\n let objectLiteral: any;\n\n if (\n n.VariableDeclaration.check(declaration) &&\n declaration.declarations.length > 0 &&\n n.VariableDeclarator.check(declaration.declarations[0]) &&\n n.ObjectExpression.check(declaration.declarations[0].init)\n ) {\n objectLiteral = declaration.declarations[0].init;\n }\n\n if (noMetadata) {\n const metadataProperties = [\n 'id',\n 'locale',\n 'filled',\n 'fill',\n 'title',\n 'description',\n 'tags',\n 'version',\n 'priority',\n 'contentAutoTransformation',\n '$schema',\n ];\n\n // Mutate the array backwards instead of using .filter() to prevent layout invalidation\n for (let i = objectLiteral.properties.length - 1; i >= 0; i--) {\n const prop = objectLiteral.properties[i];\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n let propName = '';\n if (n.Identifier.check(prop.key)) propName = prop.key.name;\n else if (n.StringLiteral.check(prop.key)) propName = prop.key.value;\n else if (n.Literal.check(prop.key)) propName = String(prop.key.value);\n\n if (['key', 'content', ...metadataProperties].includes(propName)) {\n objectLiteral.properties.splice(i, 1);\n }\n }\n }\n }\n\n // Update the AST in place\n updateObjectLiteral(\n objectLiteral,\n noMetadata ? (dictionary.content as Record<string, any>) : dictionary\n );\n\n // Print the full AST to utilize the global token stream for inline comments\n const printedCode = recast.print(ast, {\n tabWidth: 2,\n quote: 'double',\n trailingComma: false,\n }).code;\n\n // Extract the target object literal cleanly\n const startIndex = printedCode.indexOf('{');\n const endIndex = printedCode.lastIndexOf('}');\n let finalOutput = printedCode.substring(startIndex, endIndex + 1);\n\n // Revert the tagged block comment back to an inline line comment and fix comma placement\n finalOutput = finalOutput.replace(\n /\\s*\\/\\*__INLINE_LINE__(.*?)\\*\\/(\\s*,?)/g,\n '$2 //$1'\n );\n\n // Collapse empty lines injected by Recast around commented properties\n finalOutput = finalOutput.replace(/\\n[ \\t]*\\n/g, '\\n');\n\n return finalOutput;\n};\n"],"mappings":";;;;;;AAGA,MAAM,IAAI,OAAO,MAA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WAAW,CAAC;CAGhE,cAAc,YAAY,QACxB,2CACA,SACF;CAGA,cAAc,YAAY,QAAQ,eAAe,IAAI;CAErD,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"transformJSONFile.cjs","names":[],"sources":["../../../src/writeContentDeclaration/transformJSONFile.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport * as recast from 'recast';\n\nconst b = recast.types.builders;\nconst n = recast.types.namedTypes;\n\n/**\n * Checks if a value is a plain object (and not null/array)\n */\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n};\n\n/**\n * Checks if a recast AST node value matches the incoming primitive value.\n */\nconst isPrimitiveEqual = (astNode: any, val: unknown): boolean => {\n if (val === null) {\n return n.Literal.check(astNode) && astNode.value === null;\n }\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n return (\n (n.Literal.check(astNode) ||\n n.StringLiteral.check(astNode) ||\n n.NumericLiteral.check(astNode) ||\n n.BooleanLiteral.check(astNode)) &&\n astNode.value === val\n );\n }\n return false;\n};\n\n/**\n * Robustly finds a property in a recast ObjectExpression.\n * Handles quoted (\"key\") or unquoted (key) properties.\n */\nconst getMatchingProperty = (node: any, key: string) => {\n return node.properties.find((prop: any) => {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n if (n.Identifier.check(prop.key) && prop.key.name === key) return true;\n if (n.StringLiteral.check(prop.key) && prop.key.value === key)\n return true;\n if (n.Literal.check(prop.key) && prop.key.value === key) return true;\n }\n return false;\n });\n};\n\n/**\n * Recursively builds a clean recast AST node from a plain JS value.\n * Because these nodes lack `loc` tracking, recast is forced to pretty-print them.\n */\nconst buildASTNode = (val: unknown): any => {\n if (val === null) return b.literal(null);\n\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n return b.literal(val);\n }\n\n if (Array.isArray(val)) {\n return b.arrayExpression(val.map((item) => buildASTNode(item)));\n }\n\n if (isPlainObject(val)) {\n return b.objectExpression(\n Object.entries(val)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]) =>\n b.property('init', b.stringLiteral(k), buildASTNode(v))\n )\n );\n }\n\n return b.literal(null); // Fallback\n};\n\n/**\n * Recursively updates the AST object literal with new data.\n */\nconst updateObjectLiteral = (node: any, data: Record<string, any>) => {\n for (const [key, val] of Object.entries(data)) {\n if (val === undefined) {\n continue;\n }\n\n const existingProp = getMatchingProperty(node, key);\n\n if (existingProp?.comments) {\n existingProp.comments.forEach((c: any) => {\n if ((c.type === 'Line' || c.type === 'CommentLine') && c.trailing) {\n // Convert to block comment and tag it to force Recast to print it inline\n c.type = c.type === 'Line' ? 'Block' : 'CommentBlock';\n c.value = `__INLINE_LINE__${c.value}`;\n c.leading = false;\n c.trailing = true;\n }\n });\n }\n\n if (isPlainObject(val)) {\n if (existingProp && n.ObjectExpression.check(existingProp.value)) {\n updateObjectLiteral(existingProp.value, val);\n } else {\n if (existingProp) {\n // Prevent AST invalidation if the primitive value is identical\n const isIdentical =\n n.Literal.check(existingProp.value) &&\n existingProp.value.value === val;\n\n if (!isIdentical) {\n existingProp.value = buildASTNode(val);\n }\n } else {\n node.properties.push(\n b.property('init', b.stringLiteral(key), buildASTNode(val))\n );\n }\n }\n } else {\n // Handle primitives and arrays\n if (existingProp) {\n // Skip assignment if the primitive value is identical\n if (!isPrimitiveEqual(existingProp.value, val)) {\n existingProp.value = buildASTNode(val);\n }\n } else {\n node.properties.push(\n b.property('init', b.stringLiteral(key), buildASTNode(val))\n );\n }\n }\n }\n};\n\nexport const transformJSONFile = (\n fileContent: string,\n dictionary: Dictionary,\n noMetadata?: boolean\n): string => {\n // Wrap content to create valid syntax for the parser\n const wrappedContent = `const _config = ${fileContent.trim() || '{}'};`;\n\n let ast: ReturnType<typeof recast.parse>;\n try {\n ast = recast.parse(wrappedContent);\n } catch {\n // Fallback if parsing failed\n return JSON.stringify(\n noMetadata ? dictionary.content : dictionary,\n null,\n 2\n );\n }\n\n // Navigate the AST to locate the object literal initialized to `_config`\n const declaration = ast.program.body[0];\n let objectLiteral: any;\n\n if (\n n.VariableDeclaration.check(declaration) &&\n declaration.declarations.length > 0 &&\n n.VariableDeclarator.check(declaration.declarations[0]) &&\n n.ObjectExpression.check(declaration.declarations[0].init)\n ) {\n objectLiteral = declaration.declarations[0].init;\n }\n\n if (noMetadata) {\n const metadataProperties = [\n 'id',\n 'locale',\n 'filled',\n 'fill',\n 'title',\n 'description',\n 'tags',\n 'version',\n 'priority',\n 'contentAutoTransformation',\n '$schema',\n ];\n\n // Mutate the array backwards instead of using .filter() to prevent layout invalidation\n for (let i = objectLiteral.properties.length - 1; i >= 0; i--) {\n const prop = objectLiteral.properties[i];\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n let propName = '';\n if (n.Identifier.check(prop.key)) propName = prop.key.name;\n else if (n.StringLiteral.check(prop.key)) propName = prop.key.value;\n else if (n.Literal.check(prop.key)) propName = String(prop.key.value);\n\n if (['key', 'content', ...metadataProperties].includes(propName)) {\n objectLiteral.properties.splice(i, 1);\n }\n }\n }\n }\n\n // Update the AST in place\n updateObjectLiteral(\n objectLiteral,\n noMetadata ? (dictionary.content as Record<string, any>) : dictionary\n );\n\n // Print the full AST to utilize the global token stream for inline comments\n const printedCode = recast.print(ast, {\n tabWidth: 2,\n quote: 'double',\n trailingComma: false,\n }).code;\n\n // Extract the target object literal cleanly\n const startIndex = printedCode.indexOf('{');\n const endIndex = printedCode.lastIndexOf('}');\n let finalOutput = printedCode.substring(startIndex, endIndex + 1);\n\n // Revert the tagged block comment back to an inline line comment and fix comma placement\n finalOutput = finalOutput.replace(\n /\\s*\\/\\*__INLINE_LINE__(.*?)\\*\\/(\\s*,?)/g,\n '$2 //$1'\n );\n\n // Collapse empty lines injected by Recast around commented properties\n finalOutput = finalOutput.replace(/\\n[ \\t]*\\n/g, '\\n');\n\n return finalOutput;\n};\n"],"mappings":";;;;;;AAGA,M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,IAAI,cAAc,YAAY,UAAU,YAAY,WAAW,CAAC;CAGhE,cAAc,YAAY,QACxB,2CACA,SACF;CAGA,cAAc,YAAY,QAAQ,eAAe,IAAI;CAErD,OAAO;AACT"}
|
|
@@ -53,7 +53,11 @@ const formatContentDeclaration = async (dictionary, configuration, localeList) =
|
|
|
53
53
|
...Object.fromEntries(Object.entries(dictionary).filter(([k]) => !INTERNAL_FIELDS.has(k))),
|
|
54
54
|
content
|
|
55
55
|
};
|
|
56
|
-
|
|
56
|
+
/**
|
|
57
|
+
* Add $schema to JSON dictionaries
|
|
58
|
+
*/
|
|
59
|
+
const extension = dictionary.filePath ? (0, node_path.extname)(dictionary.filePath) : ".json";
|
|
60
|
+
if (require_utils_getFormatFromExtension.getFormatFromExtension(extension) === "json" && pluginFormatResult.content && pluginFormatResult.key) result = {
|
|
57
61
|
$schema: "https://intlayer.org/schema.json",
|
|
58
62
|
...result
|
|
59
63
|
};
|
|
@@ -100,7 +104,8 @@ const writeContentDeclaration = async (dictionary, configuration, options) => {
|
|
|
100
104
|
};
|
|
101
105
|
};
|
|
102
106
|
const writeFileWithDirectories = async (absoluteFilePath, dictionary, configuration, noMetadata) => {
|
|
103
|
-
|
|
107
|
+
const dir = (0, node_path.dirname)(absoluteFilePath);
|
|
108
|
+
await (0, node_fs_promises.mkdir)(dir, { recursive: true });
|
|
104
109
|
const extension = (0, node_path.extname)(absoluteFilePath);
|
|
105
110
|
if (extension === ".md" || extension === ".mdx") {
|
|
106
111
|
await require_writeContentDeclaration_writeMarkdownFile.writeMarkdownFile(absoluteFilePath, dictionary, configuration);
|
|
@@ -154,7 +159,8 @@ const writeFileWithDirectories = async (absoluteFilePath, dictionary, configurat
|
|
|
154
159
|
])).has(extension)) return;
|
|
155
160
|
await require_writeContentDeclaration_writeJSFile.writeJSFile(absoluteFilePath, dictionary, configuration, noMetadata);
|
|
156
161
|
try {
|
|
157
|
-
|
|
162
|
+
const sentinelPath = (0, node_path.join)(configuration.system.cacheDir, "intlayer-prepared.lock");
|
|
163
|
+
await (0, node_fs_promises.rm)(sentinelPath, { recursive: true });
|
|
158
164
|
} catch {}
|
|
159
165
|
};
|
|
160
166
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writeContentDeclaration.cjs","names":["processContentDeclarationContent","getFormatFromExtension","COMPILER_NO_METADATA","readDictionariesFromDisk","writeMarkdownFile","writeYamlFile","transformJSONFile","detectFormatCommand","writeJSFile"],"sources":["../../../src/writeContentDeclaration/writeContentDeclaration.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, extname, join, resolve } from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\nimport { COMPILER_NO_METADATA } from '@intlayer/config/defaultValues';\nimport {\n getFilteredLocalesDictionary,\n getPerLocaleDictionary,\n} from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport { readDictionariesFromDisk } from '../utils/readDictionariesFromDisk';\nimport type { DictionaryStatus } from './dictionaryStatus';\nimport { processContentDeclarationContent } from './processContentDeclarationContent';\nimport { transformJSONFile } from './transformJSONFile';\nimport { writeJSFile } from './writeJSFile';\nimport { writeMarkdownFile } from './writeMarkdownFile';\nimport { writeYamlFile } from './writeYamlFile';\n\nconst formatContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n localeList?: LocalesValues[]\n) => {\n /**\n * Clean Markdown, Insertion, File, etc. node metadata\n */\n const processedDictionary =\n await processContentDeclarationContent(dictionary);\n\n let content = processedDictionary.content;\n\n /**\n * Filter locales content\n */\n\n if (dictionary.locale) {\n content = getPerLocaleDictionary(\n processedDictionary,\n dictionary.locale\n ).content;\n } else if (localeList) {\n content = getFilteredLocalesDictionary(\n processedDictionary,\n localeList\n ).content;\n }\n\n let pluginFormatResult: any = {\n ...dictionary,\n content,\n } satisfies Dictionary;\n\n /**\n * Format the dictionary with the plugins\n */\n\n for await (const plugin of configuration.plugins ?? []) {\n if (plugin.formatOutput) {\n const formattedResult = await plugin.formatOutput?.({\n dictionary: pluginFormatResult,\n configuration,\n });\n\n if (formattedResult) {\n pluginFormatResult = formattedResult;\n }\n }\n }\n\n const isDictionaryFormat =\n pluginFormatResult.content && pluginFormatResult.key;\n\n if (!isDictionaryFormat) return pluginFormatResult;\n\n // Build result from the original dictionary so that extra user-defined fields\n // (e.g. custom frontmatter in markdown files) are preserved.\n // Strip internal-only fields that must never appear in persisted output.\n const INTERNAL_FIELDS = new Set([\n '$schema',\n 'filePath',\n 'localId',\n 'localIds',\n 'projectIds',\n ]);\n\n const preservedFields = Object.fromEntries(\n Object.entries(dictionary as Record<string, unknown>).filter(\n ([k]) => !INTERNAL_FIELDS.has(k)\n )\n );\n\n let result: Dictionary = {\n ...preservedFields,\n content,\n } as Dictionary;\n\n /**\n * Add $schema to JSON dictionaries\n */\n const extension = (\n dictionary.filePath ? extname(dictionary.filePath) : '.json'\n ) as Extension;\n const format = getFormatFromExtension(extension);\n\n if (\n format === 'json' &&\n pluginFormatResult.content &&\n pluginFormatResult.key\n ) {\n result = {\n $schema: 'https://intlayer.org/schema.json',\n ...result,\n };\n }\n\n return result;\n};\n\ntype WriteContentDeclarationOptions = {\n newDictionariesPath?: string;\n localeList?: LocalesValues[];\n fallbackLocale?: Locale;\n};\n\nconst defaultOptions = {\n newDictionariesPath: 'intlayer-dictionaries',\n} satisfies WriteContentDeclarationOptions;\n\nexport const writeContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n options?: WriteContentDeclarationOptions\n): Promise<{ status: DictionaryStatus; path: string }> => {\n const { system, compiler } = configuration;\n const { baseDir } = system;\n\n const noMetadata = compiler?.noMetadata ?? COMPILER_NO_METADATA;\n const { newDictionariesPath, localeList } = {\n ...defaultOptions,\n ...options,\n };\n\n const newDictionaryLocationPath = join(baseDir, newDictionariesPath);\n\n const unmergedDictionariesRecord = readDictionariesFromDisk<\n Record<string, Dictionary[]>\n >(configuration.system.unmergedDictionariesDir);\n const unmergedDictionaries = unmergedDictionariesRecord[\n dictionary.key\n ] as Dictionary[];\n\n const existingDictionary = unmergedDictionaries?.find(\n (el) => el.localId === dictionary.localId\n );\n\n const formattedContentDeclaration = await formatContentDeclaration(\n dictionary,\n configuration,\n localeList\n );\n\n if (existingDictionary?.filePath) {\n // Compare existing dictionary content with new dictionary content\n const isSameContent = isDeepStrictEqual(existingDictionary, dictionary);\n\n const filePath = resolve(\n configuration.system.baseDir,\n existingDictionary.filePath\n );\n\n // Up to date, nothing to do\n if (isSameContent) {\n return {\n status: 'up-to-date',\n path: filePath,\n };\n }\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'updated', path: filePath };\n }\n\n if (dictionary.filePath) {\n const filePath = resolve(configuration.system.baseDir, dictionary.filePath);\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'created', path: filePath };\n }\n\n // No existing dictionary, write to new location\n const contentDeclarationPath = join(\n newDictionaryLocationPath,\n `${dictionary.key}.content.json`\n );\n\n await writeFileWithDirectories(\n contentDeclarationPath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return {\n status: 'imported',\n path: contentDeclarationPath,\n };\n};\n\nconst writeFileWithDirectories = async (\n absoluteFilePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n noMetadata?: boolean\n): Promise<void> => {\n // Extract the directory from the file path\n const dir = dirname(absoluteFilePath);\n\n // Create the directory recursively\n await mkdir(dir, { recursive: true });\n\n const extension = extname(absoluteFilePath);\n\n if (extension === '.md' || extension === '.mdx') {\n await writeMarkdownFile(absoluteFilePath, dictionary, configuration);\n return;\n }\n\n if (extension === '.yaml' || extension === '.yml') {\n await writeYamlFile(absoluteFilePath, dictionary, configuration);\n return;\n }\n\n // Handle JSON, JSONC, and JSON5 via the AST transformer\n if (['.json', '.jsonc', '.json5'].includes(extension)) {\n let fileContent = '{}';\n\n if (existsSync(absoluteFilePath)) {\n try {\n fileContent = await readFile(absoluteFilePath, 'utf-8');\n } catch {\n // ignore read errors, start with empty object\n }\n }\n\n const transformedContent = transformJSONFile(\n fileContent,\n dictionary,\n noMetadata\n );\n\n // We use standard writeFile because transformedContent is already a string\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${absoluteFilePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, transformedContent, 'utf-8');\n await rename(tempPath, absoluteFilePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', absoluteFilePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n\n return;\n }\n\n const knownJsExtensions = new Set([\n '.ts',\n '.tsx',\n '.js',\n '.jsx',\n '.mjs',\n '.cjs',\n ]);\n\n if (!knownJsExtensions.has(extension)) {\n // Unknown extension (e.g. .po managed by a plugin) — skip; the plugin\n // owns this file format and writeJSFile / prettier would corrupt it.\n return;\n }\n\n await writeJSFile(absoluteFilePath, dictionary, configuration, noMetadata);\n\n // remove the cache as content has changed\n // Will force a new preparation of the intlayer on next build\n try {\n const sentinelPath = join(\n configuration.system.cacheDir,\n 'intlayer-prepared.lock'\n );\n await rm(sentinelPath, { recurs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;EACtC,IAAI,SACF,kCAAY,SAAS,EAAE,WAAW,KAAK,CAAC;EAG1C,MAAM,eAAe,2BAAY,gBAAgB,EAAE,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC,EAAE;EACxG,MAAM,WAAW,8BACR,SAAS,YAAY,IAC1B,GAAG,iBAAiB,GAAG;EAC3B,IAAI;GACF,sCAAgB,UAAU,oBAAoB,OAAO;GACrD,mCAAa,UAAU,gBAAgB;EACzC,SAAS,OAAO;GACd,IAAI;IACF,+BAAS,UAAU,EAAE,OAAO,KAAK,CAAC;GACpC,QAAQ,CAER;GACA,MAAM;EACR;EAEA,MAAM,gBAAgBC,gDAAoB,aAAa;EAEvD,IAAI,eACF,IAAI;GACF,iCAAS,cAAc,QAAQ,YAAY,gBAAgB,GAAG;IAC5D,OAAO;IACP,KAAK,cAAc,OAAO;GAC5B,CAAC;EACH,SAAS,OAAO;GACd,QAAQ,MAAM,KAAK;EACrB;EAGF;CACF;CAWA,IAAI,kBAAC,IATyB,IAAI;EAChC;EACA;EACA;EACA;EACA;EACA;CACF,CAEqB,EAAC,CAAC,IAAI,SAAS,GAGlC;CAGF,MAAMC,wDAAY,kBAAkB,YAAY,eAAe,UAAU;CAIzE,IAAI;EAKF,mDAHE,cAAc,OAAO,UACrB,wBAEkB,GAAG,EAAE,WAAW,KAAK,CAAC;CAC5C,QAAQ,CAAC;AACX"}
|
|
1
|
+
{"version":3,"file":"writeContentDeclaration.cjs","names":["processContentDeclarationContent","getPerLocaleDictionary","getFilteredLocalesDictionary","extname","getFormatFromExtension","COMPILER_NO_METADATA","join","readDictionariesFromDisk","isDeepStrictEqual","resolve","dirname","mkdir","writeMarkdownFile","writeYamlFile","existsSync","readFile","transformJSONFile","basename","writeFile","rename","rm","detectFormatCommand","writeJSFile"],"sources":["../../../src/writeContentDeclaration/writeContentDeclaration.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, extname, join, resolve } from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\nimport { COMPILER_NO_METADATA } from '@intlayer/config/defaultValues';\nimport {\n getFilteredLocalesDictionary,\n getPerLocaleDictionary,\n} from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport { readDictionariesFromDisk } from '../utils/readDictionariesFromDisk';\nimport type { DictionaryStatus } from './dictionaryStatus';\nimport { processContentDeclarationContent } from './processContentDeclarationContent';\nimport { transformJSONFile } from './transformJSONFile';\nimport { writeJSFile } from './writeJSFile';\nimport { writeMarkdownFile } from './writeMarkdownFile';\nimport { writeYamlFile } from './writeYamlFile';\n\nconst formatContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n localeList?: LocalesValues[]\n) => {\n /**\n * Clean Markdown, Insertion, File, etc. node metadata\n */\n const processedDictionary =\n await processContentDeclarationContent(dictionary);\n\n let content = processedDictionary.content;\n\n /**\n * Filter locales content\n */\n\n if (dictionary.locale) {\n content = getPerLocaleDictionary(\n processedDictionary,\n dictionary.locale\n ).content;\n } else if (localeList) {\n content = getFilteredLocalesDictionary(\n processedDictionary,\n localeList\n ).content;\n }\n\n let pluginFormatResult: any = {\n ...dictionary,\n content,\n } satisfies Dictionary;\n\n /**\n * Format the dictionary with the plugins\n */\n\n for await (const plugin of configuration.plugins ?? []) {\n if (plugin.formatOutput) {\n const formattedResult = await plugin.formatOutput?.({\n dictionary: pluginFormatResult,\n configuration,\n });\n\n if (formattedResult) {\n pluginFormatResult = formattedResult;\n }\n }\n }\n\n const isDictionaryFormat =\n pluginFormatResult.content && pluginFormatResult.key;\n\n if (!isDictionaryFormat) return pluginFormatResult;\n\n // Build result from the original dictionary so that extra user-defined fields\n // (e.g. custom frontmatter in markdown files) are preserved.\n // Strip internal-only fields that must never appear in persisted output.\n const INTERNAL_FIELDS = new Set([\n '$schema',\n 'filePath',\n 'localId',\n 'localIds',\n 'projectIds',\n ]);\n\n const preservedFields = Object.fromEntries(\n Object.entries(dictionary as Record<string, unknown>).filter(\n ([k]) => !INTERNAL_FIELDS.has(k)\n )\n );\n\n let result: Dictionary = {\n ...preservedFields,\n content,\n } as Dictionary;\n\n /**\n * Add $schema to JSON dictionaries\n */\n const extension = (\n dictionary.filePath ? extname(dictionary.filePath) : '.json'\n ) as Extension;\n const format = getFormatFromExtension(extension);\n\n if (\n format === 'json' &&\n pluginFormatResult.content &&\n pluginFormatResult.key\n ) {\n result = {\n $schema: 'https://intlayer.org/schema.json',\n ...result,\n };\n }\n\n return result;\n};\n\ntype WriteContentDeclarationOptions = {\n newDictionariesPath?: string;\n localeList?: LocalesValues[];\n fallbackLocale?: Locale;\n};\n\nconst defaultOptions = {\n newDictionariesPath: 'intlayer-dictionaries',\n} satisfies WriteContentDeclarationOptions;\n\nexport const writeContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n options?: WriteContentDeclarationOptions\n): Promise<{ status: DictionaryStatus; path: string }> => {\n const { system, compiler } = configuration;\n const { baseDir } = system;\n\n const noMetadata = compiler?.noMetadata ?? COMPILER_NO_METADATA;\n const { newDictionariesPath, localeList } = {\n ...defaultOptions,\n ...options,\n };\n\n const newDictionaryLocationPath = join(baseDir, newDictionariesPath);\n\n const unmergedDictionariesRecord = readDictionariesFromDisk<\n Record<string, Dictionary[]>\n >(configuration.system.unmergedDictionariesDir);\n const unmergedDictionaries = unmergedDictionariesRecord[\n dictionary.key\n ] as Dictionary[];\n\n const existingDictionary = unmergedDictionaries?.find(\n (el) => el.localId === dictionary.localId\n );\n\n const formattedContentDeclaration = await formatContentDeclaration(\n dictionary,\n configuration,\n localeList\n );\n\n if (existingDictionary?.filePath) {\n // Compare existing dictionary content with new dictionary content\n const isSameContent = isDeepStrictEqual(existingDictionary, dictionary);\n\n const filePath = resolve(\n configuration.system.baseDir,\n existingDictionary.filePath\n );\n\n // Up to date, nothing to do\n if (isSameContent) {\n return {\n status: 'up-to-date',\n path: filePath,\n };\n }\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'updated', path: filePath };\n }\n\n if (dictionary.filePath) {\n const filePath = resolve(configuration.system.baseDir, dictionary.filePath);\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'created', path: filePath };\n }\n\n // No existing dictionary, write to new location\n const contentDeclarationPath = join(\n newDictionaryLocationPath,\n `${dictionary.key}.content.json`\n );\n\n await writeFileWithDirectories(\n contentDeclarationPath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return {\n status: 'imported',\n path: contentDeclarationPath,\n };\n};\n\nconst writeFileWithDirectories = async (\n absoluteFilePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n noMetadata?: boolean\n): Promise<void> => {\n // Extract the directory from the file path\n const dir = dirname(absoluteFilePath);\n\n // Create the directory recursively\n await mkdir(dir, { recursive: true });\n\n const extension = extname(absoluteFilePath);\n\n if (extension === '.md' || extension === '.mdx') {\n await writeMarkdownFile(absoluteFilePath, dictionary, configuration);\n return;\n }\n\n if (extension === '.yaml' || extension === '.yml') {\n await writeYamlFile(absoluteFilePath, dictionary, configuration);\n return;\n }\n\n // Handle JSON, JSONC, and JSON5 via the AST transformer\n if (['.json', '.jsonc', '.json5'].includes(extension)) {\n let fileContent = '{}';\n\n if (existsSync(absoluteFilePath)) {\n try {\n fileContent = await readFile(absoluteFilePath, 'utf-8');\n } catch {\n // ignore read errors, start with empty object\n }\n }\n\n const transformedContent = transformJSONFile(\n fileContent,\n dictionary,\n noMetadata\n );\n\n // We use standard writeFile because transformedContent is already a string\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${absoluteFilePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, transformedContent, 'utf-8');\n await rename(tempPath, absoluteFilePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', absoluteFilePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n\n return;\n }\n\n const knownJsExtensions = new Set([\n '.ts',\n '.tsx',\n '.js',\n '.jsx',\n '.mjs',\n '.cjs',\n ]);\n\n if (!knownJsExtensions.has(extension)) {\n // Unknown extension (e.g. .po managed by a plugin) — skip; the plugin\n // owns this file format and writeJSFile / prettier would corrupt it.\n return;\n }\n\n await writeJSFile(absoluteFilePath, dictionary, configuration, noMetadata);\n\n // remove the cache as content has changed\n // Will force a new preparation of the intlayer on next build\n try {\n const sentinelPath = join(\n configuration.system.cacheDir,\n 'intlayer-prepared.lock'\n );\n await rm(sentinelPath, { recursive: true });\n } catch {}\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2BA,MAAM,2BAA2B,OAC/B,YACA,eACA,eACG;;;;CAIH,MAAM,sBACJ,MAAMA,kGAAiC,UAAU;CAEnD,IAAI,UAAU,oBAAoB;;;;CAMlC,IAAI,WAAW,QACb,cAAUC,+CACR,qBACA,WAAW,MACb,CAAC,CAAC;MACG,IAAI,YACT,cAAUC,qDACR,qBACA,UACF,CAAC,CAAC;CAGJ,IAAI,qBAA0B;EAC5B,GAAG;EACH;CACF;;;;CAMA,WAAW,MAAM,UAA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G,MAAM,WAAW,cACbX,gBAAK,SAAS,YAAY,IAC1B,GAAG,iBAAiB,GAAG;EAC3B,IAAI;GACF,UAAMY,4BAAU,UAAU,oBAAoB,OAAO;GACrD,UAAMC,yBAAO,UAAU,gBAAgB;EACzC,SAAS,OAAO;GACd,IAAI;IACF,UAAMC,qBAAG,UAAU,EAAE,OAAO,KAAK,CAAC;GACpC,QAAQ,CAER;GACA,MAAM;EACR;EAEA,MAAM,gBAAgBC,gDAAoB,aAAa;EAEvD,IAAI,eACF,IAAI;GACF,iCAAS,cAAc,QAAQ,YAAY,gBAAgB,GAAG;IAC5D,OAAO;IACP,KAAK,cAAc,OAAO;GAC5B,CAAC;EACH,SAAS,OAAO;GACd,QAAQ,MAAM,KAAK;EACrB;EAGF;CACF;CAWA,IAAI,kBAAC,IATyB,IAAI;EAChC;EACA;EACA;EACA;EACA;EACA;CACF,CAEqB,EAAC,CAAC,IAAI,SAAS,GAGlC;CAGF,MAAMC,wDAAY,kBAAkB,YAAY,eAAe,UAAU;CAIzE,IAAI;EACF,MAAM,mBAAehB,gBACnB,cAAc,OAAO,UACrB,wBACF;EACA,UAAMc,qBAAG,cAAc,EAAE,WAAW,KAAK,CAAC;CAC5C,QAAQ,CAAC;AACX"}
|
|
@@ -23,7 +23,8 @@ const writeJSFile = async (filePath, dictionary, configuration, noMetadata) => {
|
|
|
23
23
|
};
|
|
24
24
|
const appLogger = (0, _intlayer_config_logger.getAppLogger)(configuration);
|
|
25
25
|
if (!(0, node_fs.existsSync)(filePath)) {
|
|
26
|
-
const
|
|
26
|
+
const fileExtension = (0, node_path.extname)(filePath);
|
|
27
|
+
const format = require_utils_getFormatFromExtension.getFormatFromExtension(fileExtension);
|
|
27
28
|
appLogger("File does not exist, creating it", { isVerbose: true });
|
|
28
29
|
const template = await require_getContentDeclarationFileTemplate_getContentDeclarationFileTemplate.getContentDeclarationFileTemplate(mergedDictionary.key, format, Object.fromEntries(Object.entries({
|
|
29
30
|
id: noMetadata ? void 0 : mergedDictionary.id,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writeJSFile.cjs","names":["getFormatFromExtension","getContentDeclarationFileTemplate","transformJSFile","detectFormatCommand"],"sources":["../../../src/writeContentDeclaration/writeJSFile.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, extname, join } from 'node:path';\nimport { getAppLogger, logger } from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport { getContentDeclarationFileTemplate } from '../getContentDeclarationFileTemplate/getContentDeclarationFileTemplate';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport { transformJSFile } from './transformJSFile';\n\n/**\n * Updates a JavaScript/TypeScript file based on the provided JSON instructions.\n * It targets a specific dictionary object within the file (identified by its 'key' property)\n * and updates its 'content' entries. Currently, it focuses on modifying arguments\n * of 't' (translation) function calls.\n */\nexport const writeJSFile = async (\n filePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n noMetadata?: boolean\n): Promise<void> => {\n const mergedDictionary = {\n ...configuration.dictionary,\n ...dictionary,\n };\n\n const appLogger = getAppLogger(configuration);\n\n // Check if the file exist\n if (!existsSync(filePath)) {\n const fileExtension = extname(filePath) as Extension;\n\n const format = getFormatFromExtension(fileExtension);\n\n appLogger('File does not exist, creating it', {\n isVerbose: true,\n });\n const template = await getContentDeclarationFileTemplate(\n mergedDictionary.key,\n format,\n // Filter out undefined values\n Object.fromEntries(\n Object.entries({\n id: noMetadata ? undefined : mergedDictionary.id,\n locale: noMetadata ? undefined : mergedDictionary.locale,\n filled: noMetadata ? undefined : mergedDictionary.filled,\n fill: noMetadata ? undefined : mergedDictionary.fill,\n description: noMetadata ? undefined : mergedDictionary.description,\n title: noMetadata ? undefined : mergedDictionary.title,\n tags: noMetadata ? undefined : mergedDictionary.tags,\n version: noMetadata ? undefined : mergedDictionary.version,\n priority: noMetadata ? undefined : mergedDictionary.priority,\n importMode: noMetadata ? undefined : mergedDictionary.importMode,\n }).filter(([, value]) => value !== undefined)\n ),\n noMetadata\n );\n\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(filePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${filePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, template, 'utf-8');\n await rename(tempPath, filePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n }\n\n let fileContent = await readFile(filePath, 'utf-8');\n\n if (fileContent === '') {\n const format = getFormatFromExtension(extname(filePath) as Extension);\n\n fileContent = await getContentDeclarationFileTemplate(\n mergedDictionary.key,\n format,\n {},\n noMetadata\n );\n }\n\n const finalCode = await transformJSFile(\n fileContent,\n dictionary,\n dictionary.locale as any,\n noMetadata\n );\n\n // Write the modified code back to the file\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(filePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${filePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, finalCode, 'utf-8');\n await rename(tempPath, filePath);\n logger(`Successfully updated ${filePath}`, {\n level: 'info',\n isVerbose: true,\n });\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n const err = error as Error;\n logger(`Failed to write updated file: ${filePath}`, {\n level: 'error',\n });\n throw new Error(`Failed to write updated file ${filePath}: ${err.message}`);\n }\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', filePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAqBA,MAAa,cAAc,OACzB,UACA,YACA,eACA,eACkB;CAClB,MAAM,mBAAmB;EACvB,GAAG,cAAc;EACjB,GAAG;CACL;CAEA,MAAM,
|
|
1
|
+
{"version":3,"file":"writeJSFile.cjs","names":["getAppLogger","existsSync","extname","getFormatFromExtension","getContentDeclarationFileTemplate","mkdir","basename","join","writeFile","rename","rm","readFile","transformJSFile","detectFormatCommand"],"sources":["../../../src/writeContentDeclaration/writeJSFile.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, extname, join } from 'node:path';\nimport { getAppLogger, logger } from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport { getContentDeclarationFileTemplate } from '../getContentDeclarationFileTemplate/getContentDeclarationFileTemplate';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport { transformJSFile } from './transformJSFile';\n\n/**\n * Updates a JavaScript/TypeScript file based on the provided JSON instructions.\n * It targets a specific dictionary object within the file (identified by its 'key' property)\n * and updates its 'content' entries. Currently, it focuses on modifying arguments\n * of 't' (translation) function calls.\n */\nexport const writeJSFile = async (\n filePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n noMetadata?: boolean\n): Promise<void> => {\n const mergedDictionary = {\n ...configuration.dictionary,\n ...dictionary,\n };\n\n const appLogger = getAppLogger(configuration);\n\n // Check if the file exist\n if (!existsSync(filePath)) {\n const fileExtension = extname(filePath) as Extension;\n\n const format = getFormatFromExtension(fileExtension);\n\n appLogger('File does not exist, creating it', {\n isVerbose: true,\n });\n const template = await getContentDeclarationFileTemplate(\n mergedDictionary.key,\n format,\n // Filter out undefined values\n Object.fromEntries(\n Object.entries({\n id: noMetadata ? undefined : mergedDictionary.id,\n locale: noMetadata ? undefined : mergedDictionary.locale,\n filled: noMetadata ? undefined : mergedDictionary.filled,\n fill: noMetadata ? undefined : mergedDictionary.fill,\n description: noMetadata ? undefined : mergedDictionary.description,\n title: noMetadata ? undefined : mergedDictionary.title,\n tags: noMetadata ? undefined : mergedDictionary.tags,\n version: noMetadata ? undefined : mergedDictionary.version,\n priority: noMetadata ? undefined : mergedDictionary.priority,\n importMode: noMetadata ? undefined : mergedDictionary.importMode,\n }).filter(([, value]) => value !== undefined)\n ),\n noMetadata\n );\n\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(filePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${filePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, template, 'utf-8');\n await rename(tempPath, filePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n }\n\n let fileContent = await readFile(filePath, 'utf-8');\n\n if (fileContent === '') {\n const format = getFormatFromExtension(extname(filePath) as Extension);\n\n fileContent = await getContentDeclarationFileTemplate(\n mergedDictionary.key,\n format,\n {},\n noMetadata\n );\n }\n\n const finalCode = await transformJSFile(\n fileContent,\n dictionary,\n dictionary.locale as any,\n noMetadata\n );\n\n // Write the modified code back to the file\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(filePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${filePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, finalCode, 'utf-8');\n await rename(tempPath, filePath);\n logger(`Successfully updated ${filePath}`, {\n level: 'info',\n isVerbose: true,\n });\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n const err = error as Error;\n logger(`Failed to write updated file: ${filePath}`, {\n level: 'error',\n });\n throw new Error(`Failed to write updated file ${filePath}: ${err.message}`);\n }\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', filePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAqBA,MAAa,cAAc,OACzB,UACA,YACA,eACA,eACkB;CAClB,MAAM,mBAAmB;EACvB,GAAG,cAAc;EACjB,GAAG;CACL;CAEA,MAAM,gBAAYA,sCAAa,aAAa;CAG5C,IAAI,KAACC,oBAAW,QAAQ,GAAG;EACzB,MAAM,oBAAgBC,mBAAQ,QAAQ;EAEtC,MAAM,SAASC,4DAAuB,aAAa;EAEnD,UAAU,oCAAoC,EAC5C,WAAW,KACb,CAAC;EACD,MAAM,WAAW,MAAMC,8GACrB,iBAAiB,KACjB,QAEA,OAAO,YACL,OAAO,QAAQ;GACb,IAAI,aAAa,SAAY,iBAAiB;GAC9C,QAAQ,aAAa,SAAY,iBAAiB;GAClD,QAAQ,aAAa,SAAY,iBAAiB;GAClD,MAAM,aAAa,SAAY,iBAAiB;GAChD,aAAa,aAAa,SAAY,iBAAiB;GACvD,OAAO,aAAa,SAAY,iBAAiB;GACjD,MAAM,aAAa,SAAY,iBAAiB;GAChD,SAAS,aAAa,SAAY,iBAAiB;GACnD,UAAU,aAAa,SAAY,iBAAiB;GACpD,YAAY,aAAa,SAAY,iBAAiB;EACxD,CAAC,CAAC,CAAC,QAAQ,GAAG,WAAW,UAAU,MAAS,CAC9C,GACA,UACF;EAEA,MAAM,UAAU,cAAc,QAAQ;EACtC,IAAI,SACF,UAAMC,wBAAM,SAAS,EAAE,WAAW,KAAK,CAAC;EAG1C,MAAM,eAAe,OAAGC,oBAAS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,CAAC;EACD,MAAM,IAAI,MAAM,gCAAgC,SAAS,IAAI,IAAI,SAAS;CAC5E;CAEA,MAAM,gBAAgBG,gDAAoB,aAAa;CAEvD,IAAI,eACF,IAAI;EACF,iCAAS,cAAc,QAAQ,YAAY,QAAQ,GAAG;GACpD,OAAO;GACP,KAAK,cAAc,OAAO;EAC5B,CAAC;CACH,SAAS,OAAO;EACd,QAAQ,MAAM,KAAK;CACrB;AAEJ"}
|
|
@@ -37,7 +37,8 @@ const writeMarkdownFile = async (absoluteFilePath, dictionary, configuration) =>
|
|
|
37
37
|
const markdownBody = getMarkdownBody(markdownRaw);
|
|
38
38
|
const frontmatterFields = Object.fromEntries(Object.entries(dictionary).filter(([k, v]) => !EXCLUDED_FRONTMATTER_KEYS.has(k) && v !== void 0));
|
|
39
39
|
const fileContent = `---\n${stringifyYamlFrontmatter(frontmatterFields)}\n---\n\n${markdownBody}`;
|
|
40
|
-
|
|
40
|
+
const dir = (0, node_path.dirname)(absoluteFilePath);
|
|
41
|
+
await (0, node_fs_promises.mkdir)(dir, { recursive: true });
|
|
41
42
|
const tempDir = configuration.system?.tempDir;
|
|
42
43
|
if (tempDir) await (0, node_fs_promises.mkdir)(tempDir, { recursive: true });
|
|
43
44
|
const tempFileName = `${(0, node_path.basename)(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writeMarkdownFile.cjs","names":["MARKDOWN","detectFormatCommand"],"sources":["../../../src/writeContentDeclaration/writeMarkdownFile.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { mkdir, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { MARKDOWN } from '@intlayer/types/nodeType';\nimport { detectFormatCommand } from '../detectFormatCommand';\n\nconst stringifyYamlFrontmatter = (fields: Record<string, any>): string =>\n Object.entries(fields)\n .filter(([, value]) => value !== undefined && value !== null)\n .map(([key, value]) => {\n if (Array.isArray(value)) {\n return `${key}:\\n${value.map((item) => ` - ${JSON.stringify(item)}`).join('\\n')}`;\n }\n if (\n typeof value === 'string' &&\n (value.includes(':') || value.includes('\\n') || value.includes('#'))\n ) {\n return `${key}: ${JSON.stringify(value)}`;\n }\n return `${key}: ${value}`;\n })\n .join('\\n');\n\n// Strips YAML frontmatter from a markdown string, returning only the body\nconst getMarkdownBody = (content: string): string => {\n const lines = content.split(/\\r?\\n/);\n const firstNonEmptyIndex = lines.findIndex((line) => line.trim() !== '');\n\n if (firstNonEmptyIndex === -1 || lines[firstNonEmptyIndex].trim() !== '---') {\n return content;\n }\n\n let endIndex = -1;\n for (let i = firstNonEmptyIndex + 1; i < lines.length; i++) {\n if (lines[i].trim() === '---') {\n endIndex = i;\n break;\n }\n }\n\n if (endIndex === -1) return content;\n\n return lines\n .slice(endIndex + 1)\n .join('\\n')\n .trimStart();\n};\n\n// Fields that are auto-generated / internal and must not appear in frontmatter\nconst EXCLUDED_FRONTMATTER_KEYS = new Set<string>([\n 'content',\n '$schema',\n 'filePath',\n 'localId',\n 'localIds',\n 'projectIds',\n]);\n\nexport const writeMarkdownFile = async (\n absoluteFilePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig\n): Promise<void> => {\n const content = dictionary.content as any;\n const markdownRaw =\n typeof content === 'object' && content?.nodeType === MARKDOWN\n ? (content[MARKDOWN] ?? '')\n : '';\n // content.markdown now stores the full file (frontmatter + body); extract only the body\n const markdownBody = getMarkdownBody(markdownRaw);\n\n const frontmatterFields = Object.fromEntries(\n Object.entries(dictionary).filter(\n ([k, v]) => !EXCLUDED_FRONTMATTER_KEYS.has(k) && v !== undefined\n )\n );\n\n const frontmatterStr = stringifyYamlFrontmatter(frontmatterFields);\n const fileContent = `---\\n${frontmatterStr}\\n---\\n\\n${markdownBody}`;\n\n const dir = dirname(absoluteFilePath);\n await mkdir(dir, { recursive: true });\n\n const tempDir = configuration.system?.tempDir;\n if (tempDir) await mkdir(tempDir, { recursive: true });\n\n const tempFileName = `${basename(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${absoluteFilePath}.${tempFileName}`;\n\n try {\n await writeFile(tempPath, fileContent, 'utf-8');\n await rename(tempPath, absoluteFilePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // ignore\n }\n throw error;\n }\n\n const formatCommand = detectFormatCommand(configuration);\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', absoluteFilePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n};\n"],"mappings":";;;;;;;;AAQA,MAAM,4BAA4B,WAChC,OAAO,QAAQ,MAAM,CAAC,CACnB,QAAQ,GAAG,WAAW,UAAU,UAAa,UAAU,IAAI,CAAC,CAC5D,KAAK,CAAC,KAAK,WAAW;CACrB,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,GAAG,IAAI,KAAK,MAAM,KAAK,SAAS,OAAO,KAAK,UAAU,IAAI,GAAG,CAAC,CAAC,KAAK,IAAI;CAEjF,IACE,OAAO,UAAU,aAChB,MAAM,SAAS,GAAG,KAAK,MAAM,SAAS,IAAI,KAAK,MAAM,SAAS,GAAG,IAElE,OAAO,GAAG,IAAI,IAAI,KAAK,UAAU,KAAK;CAExC,OAAO,GAAG,IAAI,IAAI;AACpB,CAAC,CAAC,CACD,KAAK,IAAI;AAGd,MAAM,mBAAmB,YAA4B;CACnD,MAAM,QAAQ,QAAQ,MAAM,OAAO;CACnC,MAAM,qBAAqB,MAAM,WAAW,SAAS,KAAK,KAAK,MAAM,EAAE;CAEvE,IAAI,uBAAuB,MAAM,MAAM,mBAAmB,CAAC,KAAK,MAAM,OACpE,OAAO;CAGT,IAAI,WAAW;CACf,KAAK,IAAI,IAAI,qBAAqB,GAAG,IAAI,MAAM,QAAQ,KACrD,IAAI,MAAM,EAAE,CAAC,KAAK,MAAM,OAAO;EAC7B,WAAW;EACX;CACF;CAGF,IAAI,aAAa,IAAI,OAAO;CAE5B,OAAO,MACJ,MAAM,WAAW,CAAC,CAAC,CACnB,KAAK,IAAI,CAAC,CACV,UAAU;AACf;AAGA,MAAM,4CAA4B,IAAI,IAAY;CAChD;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAa,oBAAoB,OAC/B,kBACA,YACA,kBACkB;CAClB,MAAM,UAAU,WAAW;CAC3B,MAAM,cACJ,OAAO,YAAY,YAAY,SAAS,aAAaA,oCAChD,QAAQA,sCAAa,KACtB;CAEN,MAAM,eAAe,gBAAgB,WAAW;CAEhD,MAAM,oBAAoB,OAAO,YAC/B,OAAO,QAAQ,UAAU,CAAC,CAAC,QACxB,CAAC,GAAG,OAAO,CAAC,0BAA0B,IAAI,CAAC,KAAK,MAAM,MACzD,CACF;CAGA,MAAM,cAAc,QADG,yBAAyB,iBACP,EAAE,WAAW;
|
|
1
|
+
{"version":3,"file":"writeMarkdownFile.cjs","names":["MARKDOWN","dirname","mkdir","basename","join","writeFile","rename","rm","detectFormatCommand"],"sources":["../../../src/writeContentDeclaration/writeMarkdownFile.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { mkdir, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { MARKDOWN } from '@intlayer/types/nodeType';\nimport { detectFormatCommand } from '../detectFormatCommand';\n\nconst stringifyYamlFrontmatter = (fields: Record<string, any>): string =>\n Object.entries(fields)\n .filter(([, value]) => value !== undefined && value !== null)\n .map(([key, value]) => {\n if (Array.isArray(value)) {\n return `${key}:\\n${value.map((item) => ` - ${JSON.stringify(item)}`).join('\\n')}`;\n }\n if (\n typeof value === 'string' &&\n (value.includes(':') || value.includes('\\n') || value.includes('#'))\n ) {\n return `${key}: ${JSON.stringify(value)}`;\n }\n return `${key}: ${value}`;\n })\n .join('\\n');\n\n// Strips YAML frontmatter from a markdown string, returning only the body\nconst getMarkdownBody = (content: string): string => {\n const lines = content.split(/\\r?\\n/);\n const firstNonEmptyIndex = lines.findIndex((line) => line.trim() !== '');\n\n if (firstNonEmptyIndex === -1 || lines[firstNonEmptyIndex].trim() !== '---') {\n return content;\n }\n\n let endIndex = -1;\n for (let i = firstNonEmptyIndex + 1; i < lines.length; i++) {\n if (lines[i].trim() === '---') {\n endIndex = i;\n break;\n }\n }\n\n if (endIndex === -1) return content;\n\n return lines\n .slice(endIndex + 1)\n .join('\\n')\n .trimStart();\n};\n\n// Fields that are auto-generated / internal and must not appear in frontmatter\nconst EXCLUDED_FRONTMATTER_KEYS = new Set<string>([\n 'content',\n '$schema',\n 'filePath',\n 'localId',\n 'localIds',\n 'projectIds',\n]);\n\nexport const writeMarkdownFile = async (\n absoluteFilePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig\n): Promise<void> => {\n const content = dictionary.content as any;\n const markdownRaw =\n typeof content === 'object' && content?.nodeType === MARKDOWN\n ? (content[MARKDOWN] ?? '')\n : '';\n // content.markdown now stores the full file (frontmatter + body); extract only the body\n const markdownBody = getMarkdownBody(markdownRaw);\n\n const frontmatterFields = Object.fromEntries(\n Object.entries(dictionary).filter(\n ([k, v]) => !EXCLUDED_FRONTMATTER_KEYS.has(k) && v !== undefined\n )\n );\n\n const frontmatterStr = stringifyYamlFrontmatter(frontmatterFields);\n const fileContent = `---\\n${frontmatterStr}\\n---\\n\\n${markdownBody}`;\n\n const dir = dirname(absoluteFilePath);\n await mkdir(dir, { recursive: true });\n\n const tempDir = configuration.system?.tempDir;\n if (tempDir) await mkdir(tempDir, { recursive: true });\n\n const tempFileName = `${basename(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${absoluteFilePath}.${tempFileName}`;\n\n try {\n await writeFile(tempPath, fileContent, 'utf-8');\n await rename(tempPath, absoluteFilePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // ignore\n }\n throw error;\n }\n\n const formatCommand = detectFormatCommand(configuration);\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', absoluteFilePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n};\n"],"mappings":";;;;;;;;AAQA,MAAM,4BAA4B,WAChC,OAAO,QAAQ,MAAM,CAAC,CACnB,QAAQ,GAAG,WAAW,UAAU,UAAa,UAAU,IAAI,CAAC,CAC5D,KAAK,CAAC,KAAK,WAAW;CACrB,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,GAAG,IAAI,KAAK,MAAM,KAAK,SAAS,OAAO,KAAK,UAAU,IAAI,GAAG,CAAC,CAAC,KAAK,IAAI;CAEjF,IACE,OAAO,UAAU,aAChB,MAAM,SAAS,GAAG,KAAK,MAAM,SAAS,IAAI,KAAK,MAAM,SAAS,GAAG,IAElE,OAAO,GAAG,IAAI,IAAI,KAAK,UAAU,KAAK;CAExC,OAAO,GAAG,IAAI,IAAI;AACpB,CAAC,CAAC,CACD,KAAK,IAAI;AAGd,MAAM,mBAAmB,YAA4B;CACnD,MAAM,QAAQ,QAAQ,MAAM,OAAO;CACnC,MAAM,qBAAqB,MAAM,WAAW,SAAS,KAAK,KAAK,MAAM,EAAE;CAEvE,IAAI,uBAAuB,MAAM,MAAM,mBAAmB,CAAC,KAAK,MAAM,OACpE,OAAO;CAGT,IAAI,WAAW;CACf,KAAK,IAAI,IAAI,qBAAqB,GAAG,IAAI,MAAM,QAAQ,KACrD,IAAI,MAAM,EAAE,CAAC,KAAK,MAAM,OAAO;EAC7B,WAAW;EACX;CACF;CAGF,IAAI,aAAa,IAAI,OAAO;CAE5B,OAAO,MACJ,MAAM,WAAW,CAAC,CAAC,CACnB,KAAK,I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O;EACd,QAAQ,MAAM,KAAK;CACrB;AAEJ"}
|
|
@@ -12,8 +12,10 @@ const EXCLUDED_YAML_KEYS = /* @__PURE__ */ new Set([
|
|
|
12
12
|
"filePath"
|
|
13
13
|
]);
|
|
14
14
|
const writeYamlFile = async (absoluteFilePath, dictionary, configuration) => {
|
|
15
|
-
const
|
|
16
|
-
|
|
15
|
+
const filtered = Object.fromEntries(Object.entries(dictionary).filter(([k, v]) => !EXCLUDED_YAML_KEYS.has(k) && v !== void 0));
|
|
16
|
+
const fileContent = (0, _intlayer_core_utils.stringifyYaml)(filtered);
|
|
17
|
+
const dir = (0, node_path.dirname)(absoluteFilePath);
|
|
18
|
+
await (0, node_fs_promises.mkdir)(dir, { recursive: true });
|
|
17
19
|
const tempDir = configuration.system?.tempDir;
|
|
18
20
|
if (tempDir) await (0, node_fs_promises.mkdir)(tempDir, { recursive: true });
|
|
19
21
|
const tempFileName = `${(0, node_path.basename)(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writeYamlFile.cjs","names":["detectFormatCommand"],"sources":["../../../src/writeContentDeclaration/writeYamlFile.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { mkdir, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\nimport { stringifyYaml } from '@intlayer/core/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { detectFormatCommand } from '../detectFormatCommand';\n\n// Fields that are auto-generated or runtime-only, not persisted in the file\nconst EXCLUDED_YAML_KEYS = new Set<string>(['$schema', 'id', 'filePath']);\n\nexport const writeYamlFile = async (\n absoluteFilePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig\n): Promise<void> => {\n const filtered = Object.fromEntries(\n Object.entries(dictionary).filter(\n ([k, v]) => !EXCLUDED_YAML_KEYS.has(k) && v !== undefined\n )\n );\n\n const fileContent = stringifyYaml(filtered);\n\n const dir = dirname(absoluteFilePath);\n await mkdir(dir, { recursive: true });\n\n const tempDir = configuration.system?.tempDir;\n if (tempDir) await mkdir(tempDir, { recursive: true });\n\n const tempFileName = `${basename(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${absoluteFilePath}.${tempFileName}`;\n\n try {\n await writeFile(tempPath, fileContent, 'utf-8');\n await rename(tempPath, absoluteFilePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // ignore\n }\n throw error;\n }\n\n const formatCommand = detectFormatCommand(configuration);\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', absoluteFilePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n};\n"],"mappings":";;;;;;;;AASA,MAAM,qCAAqB,IAAI,IAAY;CAAC;CAAW;CAAM;AAAU,CAAC;AAExE,MAAa,gBAAgB,OAC3B,kBACA,YACA,kBACkB;
|
|
1
|
+
{"version":3,"file":"writeYamlFile.cjs","names":["stringifyYaml","dirname","mkdir","basename","join","writeFile","rename","rm","detectFormatCommand"],"sources":["../../../src/writeContentDeclaration/writeYamlFile.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { mkdir, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\nimport { stringifyYaml } from '@intlayer/core/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { detectFormatCommand } from '../detectFormatCommand';\n\n// Fields that are auto-generated or runtime-only, not persisted in the file\nconst EXCLUDED_YAML_KEYS = new Set<string>(['$schema', 'id', 'filePath']);\n\nexport const writeYamlFile = async (\n absoluteFilePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig\n): Promise<void> => {\n const filtered = Object.fromEntries(\n Object.entries(dictionary).filter(\n ([k, v]) => !EXCLUDED_YAML_KEYS.has(k) && v !== undefined\n )\n );\n\n const fileContent = stringifyYaml(filtered);\n\n const dir = dirname(absoluteFilePath);\n await mkdir(dir, { recursive: true });\n\n const tempDir = configuration.system?.tempDir;\n if (tempDir) await mkdir(tempDir, { recursive: true });\n\n const tempFileName = `${basename(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${absoluteFilePath}.${tempFileName}`;\n\n try {\n await writeFile(tempPath, fileContent, 'utf-8');\n await rename(tempPath, absoluteFilePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // ignore\n }\n throw error;\n }\n\n const formatCommand = detectFormatCommand(configuration);\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', absoluteFilePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n};\n"],"mappings":";;;;;;;;AASA,MAAM,qCAAqB,IAAI,IAAY;CAAC;CAAW;CAAM;AAAU,CAAC;AAExE,MAAa,gBAAgB,OAC3B,kBACA,YACA,kBACkB;CAClB,MAAM,WAAW,OAAO,YACtB,OAAO,QAAQ,UAAU,CAAC,CAAC,QACxB,CAAC,GAAG,OAAO,CAAC,mBAAmB,IAAI,CAAC,KAAK,MAAM,MAClD,CACF;CAEA,MAAM,kBAAcA,oCAAc,QAAQ;CAE1C,MAAM,UAAMC,mBAAQ,gBAAgB;CACpC,UAAMC,wBAAM,KAAK,EAAE,WAAW,KAAK,CAAC;CAEpC,MAAM,UAAU,cAAc,QAAQ;CACtC,IAAI,SAAS,UAAMA,wBAAM,SAAS,EAAE,WAAW,KAAK,CAAC;CAErD,MAAM,eAAe,OAAGC,oBAAS,gBAAgB,EAAE,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC,EAAE;CACxG,MAAM,WAAW,cACbC,gBAAK,SAAS,YAAY,IAC1B,GAAG,iBAAiB,GAAG;CAE3B,IAAI;EACF,UAAMC,4BAAU,UAAU,aAAa,OAAO;EAC9C,UAAMC,yBAAO,UAAU,gBAAgB;CACzC,SAAS,OAAO;EACd,IAAI;GACF,UAAMC,qBAAG,UAAU,EAAE,OAAO,KAAK,CAAC;EACpC,QAAQ,CAER;EACA,MAAM;CACR;CAEA,MAAM,gBAAgBC,gDAAoB,aAAa;CACvD,IAAI,eACF,IAAI;EACF,iCAAS,cAAc,QAAQ,YAAY,gBAAgB,GAAG;GAC5D,OAAO;GACP,KAAK,cAAc,OAAO;EAC5B,CAAC;CACH,SAAS,OAAO;EACd,QAAQ,MAAM,KAAK;CACrB;AAEJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writeFileIfChanged.cjs","names":[],"sources":["../../src/writeFileIfChanged.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto';\nimport { rmSync } from 'node:fs';\nimport {\n chmod,\n mkdir,\n readFile,\n rename,\n rm,\n stat,\n writeFile,\n} from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\n\nconst activeTempFiles = new Set<string>();\n\n// Synchronous cleanup on process exit\nprocess.on('exit', () => {\n for (const file of activeTempFiles) {\n try {\n rmSync(file, { force: true });\n } catch {}\n }\n});\n\n/**\n * Permission bits a freshly created file receives on this system. Detected once\n * from the first temp file we actually write (`process.umask()` with no\n * argument is deprecated and thread-unsafe) and cached, so the atomic path can\n * skip restoring the mode whenever the source file already uses the default\n * mode — which is the case for essentially every generated file.\n */\nlet defaultFileMode: number | undefined;\n\n/**\n * Options for {@link writeFileIfChanged}.\n */\nexport type WriteFileIfChangedOptions = {\n /** Encoding used to turn `data` into bytes. Defaults to `'utf8'`. */\n encoding?: BufferEncoding;\n /** Directory to hold the temporary file used for the atomic swap. */\n tempDir?: string;\n /**\n * Write atomically via a temp file + `rename` so readers never observe a\n * half-written file. This creates a fresh inode on every write, which roughly\n * doubles the cost of a changed write compared to overwriting in place. Set to\n * `false` for callers whose consumers tolerate torn reads to write directly.\n * Defaults to `true`.\n */\n atomic?: boolean;\n};\n\n/**\n * Write `data` to `path` only when it differs from the file already on disk,\n * preserving the existing file's permission mode.\n *\n * The whole file is read back and byte-compared because the files written here\n * (dictionaries, entry points, types) are small, so reading beats streaming a\n * hash. When the content is unchanged the write is skipped entirely, which both\n * avoids inode churn and prevents downstream watchers from rebuilding.\n *\n * @returns `true` when the file was written, `false` when it was already up to date.\n */\nexport const writeFileIfChanged = async (\n path: string,\n data: string,\n { encoding = 'utf8', tempDir, atomic = true }: WriteFileIfChangedOptions = {}\n): Promise<boolean> => {\n const newData = Buffer.from(data, encoding);\n\n // Read the current content first: the common case is an unchanged file, and\n // this single read is the whole fast path (no stat/chmod needed to bail out).\n let existingData: Buffer | null = null;\n try {\n existingData = await readFile(path);\n } catch {}\n\n if (existingData?.equals(newData)) {\n return false;\n }\n\n // Fast path: overwrite in place. Truncating an existing file keeps its inode,\n // so its permission mode is preserved automatically (no chmod needed). This\n // skips the temp-file inode churn at the cost of exposing readers to a\n // partially written file.\n if (!atomic) {\n await writeFile(path, newData);\n return true;\n }\n\n // The atomic swap replaces the inode, so the existing mode is not preserved\n // and must be reapplied. Only a file that already exists has a mode to keep.\n let modeToRestore: number | undefined;\n if (existingData !== null) {\n try {\n modeToRestore = (await stat(path)).mode & 0o777;\n } catch {}\n }\n\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(path)}.${Date.now()}-${randomBytes(4).toString('hex')}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${path}.${tempFileName}`;\n activeTempFiles.add(tempPath);\n\n try {\n for (let attempt = 0; ; attempt++) {\n try {\n await writeFile(tempPath, newData);\n\n if (modeToRestore !== undefined) {\n // Learn the ambient default mode once from a real temp file, then only\n // chmod when the source file used a non-default mode.\n if (defaultFileMode === undefined) {\n try {\n defaultFileMode = (await stat(tempPath)).mode & 0o777;\n } catch {}\n }\n if (modeToRestore !== defaultFileMode) {\n await chmod(tempPath, modeToRestore);\n }\n }\n\n await rename(tempPath, path);\n break;\n } catch (error) {\n const isMissingDirectory =\n (error as NodeJS.ErrnoException).code === 'ENOENT';\n\n if (!isMissingDirectory || attempt > 0) throw error;\n\n await mkdir(dirname(path), { recursive: true });\n if (tempDir) await mkdir(tempDir, { recursive: true });\n }\n }\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {}\n throw error;\n } finally {\n activeTempFiles.delete(tempPath);\n }\n\n return true;\n};\n"],"mappings":";;;;;;;AAaA,MAAM,kCAAkB,IAAI,IAAY;AAGxC,QAAQ,GAAG,cAAc;CACvB,KAAK,MAAM,QAAQ,iBACjB,IAAI;EACF,oBAAO,MAAM,EAAE,OAAO,KAAK,CAAC;CAC9B,QAAQ,CAAC;AAEb,CAAC;;;;;;;;AASD,IAAI;;;;;;;;;;;;AA+BJ,MAAa,qBAAqB,OAChC,MACA,MACA,EAAE,WAAW,QAAQ,SAAS,SAAS,SAAoC,CAAC,MACvD;CACrB,MAAM,UAAU,OAAO,KAAK,MAAM,QAAQ;CAI1C,IAAI,eAA8B;CAClC,IAAI;EACF,eAAe,
|
|
1
|
+
{"version":3,"file":"writeFileIfChanged.cjs","names":["readFile","writeFile","stat","mkdir","basename","randomBytes","join","chmod","rename","dirname","rm"],"sources":["../../src/writeFileIfChanged.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto';\nimport { rmSync } from 'node:fs';\nimport {\n chmod,\n mkdir,\n readFile,\n rename,\n rm,\n stat,\n writeFile,\n} from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\n\nconst activeTempFiles = new Set<string>();\n\n// Synchronous cleanup on process exit\nprocess.on('exit', () => {\n for (const file of activeTempFiles) {\n try {\n rmSync(file, { force: true });\n } catch {}\n }\n});\n\n/**\n * Permission bits a freshly created file receives on this system. Detected once\n * from the first temp file we actually write (`process.umask()` with no\n * argument is deprecated and thread-unsafe) and cached, so the atomic path can\n * skip restoring the mode whenever the source file already uses the default\n * mode — which is the case for essentially every generated file.\n */\nlet defaultFileMode: number | undefined;\n\n/**\n * Options for {@link writeFileIfChanged}.\n */\nexport type WriteFileIfChangedOptions = {\n /** Encoding used to turn `data` into bytes. Defaults to `'utf8'`. */\n encoding?: BufferEncoding;\n /** Directory to hold the temporary file used for the atomic swap. */\n tempDir?: string;\n /**\n * Write atomically via a temp file + `rename` so readers never observe a\n * half-written file. This creates a fresh inode on every write, which roughly\n * doubles the cost of a changed write compared to overwriting in place. Set to\n * `false` for callers whose consumers tolerate torn reads to write directly.\n * Defaults to `true`.\n */\n atomic?: boolean;\n};\n\n/**\n * Write `data` to `path` only when it differs from the file already on disk,\n * preserving the existing file's permission mode.\n *\n * The whole file is read back and byte-compared because the files written here\n * (dictionaries, entry points, types) are small, so reading beats streaming a\n * hash. When the content is unchanged the write is skipped entirely, which both\n * avoids inode churn and prevents downstream watchers from rebuilding.\n *\n * @returns `true` when the file was written, `false` when it was already up to date.\n */\nexport const writeFileIfChanged = async (\n path: string,\n data: string,\n { encoding = 'utf8', tempDir, atomic = true }: WriteFileIfChangedOptions = {}\n): Promise<boolean> => {\n const newData = Buffer.from(data, encoding);\n\n // Read the current content first: the common case is an unchanged file, and\n // this single read is the whole fast path (no stat/chmod needed to bail out).\n let existingData: Buffer | null = null;\n try {\n existingData = await readFile(path);\n } catch {}\n\n if (existingData?.equals(newData)) {\n return false;\n }\n\n // Fast path: overwrite in place. Truncating an existing file keeps its inode,\n // so its permission mode is preserved automatically (no chmod needed). This\n // skips the temp-file inode churn at the cost of exposing readers to a\n // partially written file.\n if (!atomic) {\n await writeFile(path, newData);\n return true;\n }\n\n // The atomic swap replaces the inode, so the existing mode is not preserved\n // and must be reapplied. Only a file that already exists has a mode to keep.\n let modeToRestore: number | undefined;\n if (existingData !== null) {\n try {\n modeToRestore = (await stat(path)).mode & 0o777;\n } catch {}\n }\n\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(path)}.${Date.now()}-${randomBytes(4).toString('hex')}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${path}.${tempFileName}`;\n activeTempFiles.add(tempPath);\n\n try {\n for (let attempt = 0; ; attempt++) {\n try {\n await writeFile(tempPath, newData);\n\n if (modeToRestore !== undefined) {\n // Learn the ambient default mode once from a real temp file, then only\n // chmod when the source file used a non-default mode.\n if (defaultFileMode === undefined) {\n try {\n defaultFileMode = (await stat(tempPath)).mode & 0o777;\n } catch {}\n }\n if (modeToRestore !== defaultFileMode) {\n await chmod(tempPath, modeToRestore);\n }\n }\n\n await rename(tempPath, path);\n break;\n } catch (error) {\n const isMissingDirectory =\n (error as NodeJS.ErrnoException).code === 'ENOENT';\n\n if (!isMissingDirectory || attempt > 0) throw error;\n\n await mkdir(dirname(path), { recursive: true });\n if (tempDir) await mkdir(tempDir, { recursive: true });\n }\n }\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {}\n throw error;\n } finally {\n activeTempFiles.delete(tempPath);\n }\n\n return true;\n};\n"],"mappings":";;;;;;;AAaA,MAAM,kCAAkB,IAAI,IAAY;AAGxC,QAAQ,GAAG,cAAc;CACvB,KAAK,MAAM,QAAQ,iBACjB,IAAI;EACF,oBAAO,MAAM,EAAE,OAAO,KAAK,CAAC;CAC9B,QAAQ,CAAC;AAEb,CAAC;;;;;;;;AASD,IAAI;;;;;;;;;;;;AA+BJ,MAAa,qBAAqB,OAChC,MACA,MACA,EAAE,WAAW,QAAQ,SAAS,SAAS,SAAoC,CAAC,MACvD;CACrB,MAAM,UAAU,OAAO,KAAK,MAAM,QAAQ;CAI1C,IAAI,eAA8B;CAClC,IAAI;EACF,eAAe,UAAMA,2BAAS,IAAI;CACpC,QAAQ,CAAC;CAET,IAAI,cAAc,OAAO,OAAO,GAC9B,OAAO;CAOT,IAAI,CAAC,QAAQ;EACX,UAAMC,4BAAU,MAAM,OAAO;EAC7B,OAAO;CACT;CAIA,IAAI;CACJ,IAAI,iBAAiB,MACnB,IAAI;EACF,iBAAiB,UAAMC,uBAAK,IAAI,EAAC,CAAE,OAAO;CAC5C,QAAQ,CAAC;CAGX,IAAI,SACF,UAAMC,wBAAM,SAAS,EAAE,WAAW,KAAK,CAAC;CAG1C,MAAM,eAAe,OAAGC,oBAAS,IAAI,EAAE,GAAG,KAAK,IAAI,EAAE,OAAGC,yBAAY,CAAC,CAAC,CAAC,SAAS,KAAK,EAAE;CACvF,MAAM,WAAW,cACbC,gBAAK,SAAS,YAAY,IAC1B,GAAG,KAAK,GAAG;CACf,gBAAgB,IAAI,QAAQ;CAE5B,IAAI;EACF,KAAK,IAAI,UAAU,IAAK,WACtB,IAAI;GACF,UAAML,4BAAU,UAAU,OAAO;GAEjC,IAAI,kBAAkB,QAAW;IAG/B,IAAI,oBAAoB,QACtB,IAAI;KACF,mBAAmB,UAAMC,uBAAK,QAAQ,EAAC,CAAE,OAAO;IAClD,QAAQ,CAAC;IAEX,IAAI,kBAAkB,iBACpB,UAAMK,wBAAM,UAAU,aAAa;GAEvC;GAEA,UAAMC,yBAAO,UAAU,IAAI;GAC3B;EACF,SAAS,OAAO;GAId,IAAI,EAFD,MAAgC,SAAS,aAEjB,UAAU,GAAG,MAAM;GAE9C,UAAML,4BAAMM,mBAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;GAC9C,IAAI,SAAS,UAAMN,wBAAM,SAAS,EAAE,WAAW,KAAK,CAAC;EACvD;CAEJ,SAAS,OAAO;EACd,IAAI;GACF,UAAMO,qBAAG,UAAU,EAAE,OAAO,KAAK,CAAC;EACpC,QAAQ,CAAC;EACT,MAAM;CACR,UAAU;EACR,gBAAgB,OAAO,QAAQ;CACjC;CAEA,OAAO;AACT"}
|
|
@@ -70,10 +70,11 @@ const readAsset = (relPath, encoding = "utf8") => {
|
|
|
70
70
|
const distRoot = findDistRoot(here) ?? resolve(here, "..", "..", "dist");
|
|
71
71
|
const assetsRoot = join(distRoot, "assets");
|
|
72
72
|
const tried = [];
|
|
73
|
+
const callerDirAbs = getCallerDir();
|
|
73
74
|
/**
|
|
74
75
|
* Transform dist/(esm|cjs)/... and _virtual/ prefix to clean subpath (Windows-safe)
|
|
75
76
|
*/
|
|
76
|
-
const callerSubpath = relative(distRoot,
|
|
77
|
+
const callerSubpath = relative(distRoot, callerDirAbs).split("\\").join("/").replace(/^(?:dist\/)?(?:esm|cjs)\//, "").replace(/^_virtual\//, "");
|
|
77
78
|
if (relPath.startsWith("./") || relPath.startsWith("../")) {
|
|
78
79
|
const fromCallerAbs = resolve(assetsRoot, callerSubpath, relPath);
|
|
79
80
|
tried.push(fromCallerAbs);
|
|
@@ -199,7 +199,8 @@ const writeDynamicQualifiedDictionaries = async (qualifiedDictionaries, configur
|
|
|
199
199
|
await mkdir(entryDir, { recursive: true });
|
|
200
200
|
await parallelize(locales, async (locale) => {
|
|
201
201
|
const localizedDictionary = getPerLocaleDictionary(entry, locale, defaultLocale);
|
|
202
|
-
|
|
202
|
+
const resultFilePath = resolve(entryDir, `${locale}.json`);
|
|
203
|
+
await writeJsonIfChanged(resultFilePath, localizedDictionary).catch((err) => {
|
|
203
204
|
console.error(`Error creating localized ${key}/${segments.join("/")}/${locale}.json:`, err);
|
|
204
205
|
});
|
|
205
206
|
});
|