@intlayer/chokidar 8.1.6 → 8.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +37 -28
  2. package/dist/assets/installSkills/skills/astro.md +2 -2
  3. package/dist/assets/installSkills/skills/cli.md +1 -1
  4. package/dist/assets/installSkills/skills/compiler.md +32 -0
  5. package/dist/assets/installSkills/skills/{next_js.md → next-js.md} +1 -2
  6. package/dist/cjs/build.cjs +1 -1
  7. package/dist/cjs/cli.cjs +1 -1
  8. package/dist/cjs/detectFormatCommand.cjs +2 -0
  9. package/dist/cjs/detectFormatCommand.cjs.map +1 -0
  10. package/dist/cjs/index.cjs +1 -1
  11. package/dist/cjs/init/index.cjs +1 -1
  12. package/dist/cjs/init/index.cjs.map +1 -1
  13. package/dist/cjs/init/utils/fileSystem.cjs +1 -1
  14. package/dist/cjs/init/utils/fileSystem.cjs.map +1 -1
  15. package/dist/cjs/init/utils/index.cjs +1 -1
  16. package/dist/cjs/installSkills/index.cjs +1 -1
  17. package/dist/cjs/installSkills/index.cjs.map +1 -1
  18. package/dist/cjs/transformFiles/transformFiles.cjs +1 -1
  19. package/dist/cjs/transformFiles/transformFiles.cjs.map +1 -1
  20. package/dist/cjs/writeContentDeclaration/index.cjs +1 -1
  21. package/dist/cjs/writeContentDeclaration/writeJSFile.cjs +1 -1
  22. package/dist/cjs/writeContentDeclaration/writeJSFile.cjs.map +1 -1
  23. package/dist/esm/build.mjs +1 -1
  24. package/dist/esm/cli.mjs +1 -1
  25. package/dist/esm/detectFormatCommand.mjs.map +1 -0
  26. package/dist/esm/index.mjs +1 -1
  27. package/dist/esm/init/index.mjs +1 -1
  28. package/dist/esm/init/index.mjs.map +1 -1
  29. package/dist/esm/init/utils/fileSystem.mjs +1 -1
  30. package/dist/esm/init/utils/fileSystem.mjs.map +1 -1
  31. package/dist/esm/init/utils/index.mjs +1 -1
  32. package/dist/esm/installSkills/index.mjs +1 -1
  33. package/dist/esm/installSkills/index.mjs.map +1 -1
  34. package/dist/esm/transformFiles/transformFiles.mjs +1 -1
  35. package/dist/esm/transformFiles/transformFiles.mjs.map +1 -1
  36. package/dist/esm/writeContentDeclaration/index.mjs +1 -1
  37. package/dist/esm/writeContentDeclaration/writeJSFile.mjs +1 -1
  38. package/dist/esm/writeContentDeclaration/writeJSFile.mjs.map +1 -1
  39. package/dist/types/build.d.ts +1 -2
  40. package/dist/types/cli.d.ts +2 -1
  41. package/dist/types/{writeContentDeclaration/detectFormatCommand.d.ts → detectFormatCommand.d.ts} +1 -1
  42. package/dist/types/detectFormatCommand.d.ts.map +1 -0
  43. package/dist/types/index.d.ts +1 -1
  44. package/dist/types/init/index.d.ts.map +1 -1
  45. package/dist/types/init/utils/fileSystem.d.ts +5 -1
  46. package/dist/types/init/utils/fileSystem.d.ts.map +1 -1
  47. package/dist/types/init/utils/index.d.ts +2 -2
  48. package/dist/types/installSkills/index.d.ts +1 -0
  49. package/dist/types/installSkills/index.d.ts.map +1 -1
  50. package/dist/types/writeContentDeclaration/index.d.ts +1 -2
  51. package/package.json +11 -12
  52. package/dist/cjs/writeContentDeclaration/detectFormatCommand.cjs +0 -2
  53. package/dist/cjs/writeContentDeclaration/detectFormatCommand.cjs.map +0 -1
  54. package/dist/esm/writeContentDeclaration/detectFormatCommand.mjs.map +0 -1
  55. package/dist/types/writeContentDeclaration/detectFormatCommand.d.ts.map +0 -1
  56. /package/dist/assets/installSkills/skills/{remote_content.md → remote-content.md} +0 -0
  57. /package/dist/esm/{writeContentDeclaration/detectFormatCommand.mjs → detectFormatCommand.mjs} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"transformFiles.mjs","names":[],"sources":["../../../src/transformFiles/transformFiles.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport fs from 'node:fs/promises';\nimport { basename, dirname, extname, join, relative, resolve } from 'node:path';\nimport {\n ANSIColors,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { camelCaseToKebabCase } from '@intlayer/config/utils';\nimport { generateKey } from '@intlayer/core/utils';\nimport type { Dictionary, IntlayerConfig } from '@intlayer/types';\nimport { Node, Project, type SourceFile, SyntaxKind } from 'ts-morph';\nimport { writeContentDeclaration } from '../writeContentDeclaration';\nimport { detectFormatCommand } from '../writeContentDeclaration/detectFormatCommand';\nimport { extractDictionaryKey } from './extractDictionaryKey';\n\n// ==========================================\n// Shared Utilities (exported for reuse in babel plugin)\n// ==========================================\n\n/**\n * Attributes that should be extracted for localization\n */\nexport const ATTRIBUTES_TO_EXTRACT = [\n 'title',\n 'placeholder',\n 'alt',\n 'aria-label',\n 'label',\n];\n\n/**\n * Default function to determine if a string should be extracted for localization\n */\nexport const shouldExtract = (text: string): boolean => {\n const trimmed = text.trim();\n if (!trimmed) return false;\n if (!trimmed.includes(' ')) return false;\n // Starts with Capital letter\n if (!/^[A-Z]/.test(trimmed)) return false;\n // Filter out template logic identifiers (simple check)\n if (trimmed.startsWith('{') || trimmed.startsWith('v-')) return false;\n return true;\n};\n\n/**\n * Translation node structure used in multilingual dictionaries\n */\ntype TranslationNode = {\n nodeType: 'translation';\n translation: Record<string, string>;\n};\n\nconst writeContentHelper = async (\n extractedContent: Record<string, string>,\n componentKey: string,\n filePath: string,\n configuration: IntlayerConfig,\n outputDir?: string\n) => {\n const { defaultLocale } = configuration.internationalization;\n const { baseDir, fileExtensions } = configuration.content;\n\n const isPerLocaleFile = configuration?.dictionary?.locale;\n\n const dirName = outputDir ? resolve(outputDir) : dirname(filePath);\n const ext = extname(filePath);\n const baseName = basename(filePath, ext);\n const contentBaseName = baseName.charAt(0).toLowerCase() + baseName.slice(1);\n\n const contentFilePath = join(\n dirName,\n `${contentBaseName}.${fileExtensions[0]}`\n );\n const relativeContentFilePath = relative(baseDir, contentFilePath);\n\n let dictionary: Dictionary;\n\n if (isPerLocaleFile) {\n // Per-locale format: simple string content with locale property\n dictionary = {\n key: componentKey,\n content: extractedContent,\n locale: defaultLocale,\n filePath: relativeContentFilePath,\n };\n } else {\n // Multilingual format: content wrapped in translation nodes, no locale property\n const multilingualContent: Record<string, TranslationNode> = {};\n for (const [key, value] of Object.entries(extractedContent)) {\n multilingualContent[key] = {\n nodeType: 'translation',\n translation: {\n [defaultLocale]: value,\n },\n };\n }\n\n dictionary = {\n key: componentKey,\n content: multilingualContent,\n filePath: relativeContentFilePath,\n };\n }\n\n const relativeDir = relative(baseDir, dirName);\n await writeContentDeclaration(dictionary, configuration, {\n newDictionariesPath: relativeDir,\n });\n\n return contentFilePath;\n};\n\ntype TsReplacement = {\n node: Node;\n key: string;\n type: 'jsx-text' | 'jsx-attribute' | 'string-literal';\n};\n\nconst extractTsContent = (\n sourceFile: SourceFile,\n existingKeys: Set<string>\n): {\n extractedContent: Record<string, string>;\n replacements: TsReplacement[];\n} => {\n const extractedContent: Record<string, string> = {};\n const replacements: TsReplacement[] = [];\n\n sourceFile.forEachDescendant((node) => {\n // 1. JSX Text\n if (Node.isJsxText(node)) {\n const text = node.getText();\n if (shouldExtract(text)) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n extractedContent[key] = text.replace(/\\s+/g, ' ').trim();\n replacements.push({ node, key, type: 'jsx-text' });\n }\n }\n\n // 2. JSX Attributes\n else if (Node.isJsxAttribute(node)) {\n const name = node.getNameNode().getText();\n if (ATTRIBUTES_TO_EXTRACT.includes(name)) {\n const initializer = node.getInitializer();\n if (Node.isStringLiteral(initializer)) {\n const text = initializer.getLiteralValue();\n if (shouldExtract(text)) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n extractedContent[key] = text.trim();\n replacements.push({ node, key, type: 'jsx-attribute' });\n }\n }\n }\n }\n\n // 3. String Literals (Variables, Arrays, etc.)\n else if (Node.isStringLiteral(node)) {\n const text = node.getLiteralValue();\n if (shouldExtract(text)) {\n const parent = node.getParent();\n\n // Skip if inside ImportDeclaration\n if (\n parent?.getKindName() === 'ImportDeclaration' ||\n parent?.getKindName() === 'ImportSpecifier' ||\n parent?.getKindName() === 'ModuleSpecifier'\n ) {\n return;\n }\n\n // Skip if it's a JSX Attribute value (handled above)\n if (Node.isJsxAttribute(parent)) return;\n\n // Skip console.log\n if (Node.isCallExpression(parent)) {\n const expression = parent.getExpression();\n if (expression.getText().includes('console.log')) return;\n }\n\n // Skip Object Keys: { key: \"value\" } -> \"key\" is PropertyAssignment name if not computed\n if (Node.isPropertyAssignment(parent)) {\n if (parent.getNameNode() === node) return; // It's the key\n }\n\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n extractedContent[key] = text.trim();\n replacements.push({ node, key, type: 'string-literal' });\n }\n }\n });\n\n return { extractedContent, replacements };\n};\n\n// ==========================================\n// React (TS-Morph) Strategy\n// ==========================================\n\nconst processTsxFile = async (\n filePath: string,\n componentKey: string,\n packageName: PackageName,\n project: Project,\n save: boolean = true\n) => {\n let sourceFile: SourceFile;\n try {\n sourceFile = project.addSourceFileAtPath(filePath);\n } catch {\n sourceFile = project.getSourceFileOrThrow(filePath);\n }\n\n const isSolid = packageName === 'solid-intlayer';\n\n const existingKeys = new Set<string>();\n const { extractedContent, replacements } = extractTsContent(\n sourceFile,\n existingKeys\n );\n\n if (Object.keys(extractedContent).length === 0) return null;\n\n for (const { node, key, type } of replacements) {\n const contentAccess = isSolid ? `content().${key}` : `content.${key}`;\n\n if (type === 'jsx-text' && Node.isJsxText(node)) {\n node.replaceWithText(`{${contentAccess}}`);\n } else if (type === 'jsx-attribute' && Node.isJsxAttribute(node)) {\n node.setInitializer(`{${contentAccess}.value}`);\n } else if (type === 'string-literal' && Node.isStringLiteral(node)) {\n // For React/JS variables, we usually want the value\n node.replaceWithText(`${contentAccess}.value`);\n }\n }\n\n // Inject hook\n const importDecl = sourceFile.getImportDeclaration(\n (d) => d.getModuleSpecifierValue() === packageName\n );\n if (!importDecl) {\n sourceFile.addImportDeclaration({\n namedImports: ['useIntlayer'],\n moduleSpecifier: packageName,\n });\n } else if (\n !importDecl.getNamedImports().some((n) => n.getName() === 'useIntlayer')\n ) {\n importDecl.addNamedImport('useIntlayer');\n }\n\n // Insert hook at start of component\n sourceFile.getFunctions().forEach((f) => {\n f.getBody()\n ?.asKind(SyntaxKind.Block)\n ?.insertStatements(0, `const content = useIntlayer(\"${componentKey}\");`);\n });\n\n // Also handle const/arrow components\n sourceFile.getVariableDeclarations().forEach((v) => {\n const init = v.getInitializer();\n if (Node.isArrowFunction(init) || Node.isFunctionExpression(init)) {\n const body = init.getBody();\n if (Node.isBlock(body)) {\n // Heuristic: check if it returns JSX or uses hooks\n if (\n body.getText().includes('return') ||\n body.getText().includes('use')\n ) {\n body.insertStatements(\n 0,\n `const content = useIntlayer(\"${componentKey}\");`\n );\n }\n }\n }\n });\n\n if (save) {\n await sourceFile.save();\n }\n return extractedContent;\n};\n\n// ==========================================\n// 5. Main Dispatcher\n// ==========================================\n\nexport type PackageName =\n | 'next-intlayer'\n | 'react-intlayer'\n | 'vue-intlayer'\n | 'svelte-intlayer'\n | 'preact-intlayer'\n | 'solid-intlayer'\n | 'angular-intlayer'\n | 'express-intlayer';\n\nexport type ExtractIntlayerOptions = {\n configOptions?: GetConfigurationOptions;\n outputDir?: string;\n codeOnly?: boolean;\n declarationOnly?: boolean;\n};\n\nexport const extractIntlayer = async (\n filePath: string,\n packageName: PackageName,\n options?: ExtractIntlayerOptions,\n project?: Project\n) => {\n const saveComponent = !options?.declarationOnly;\n const writeContent = !options?.codeOnly;\n\n const configuration = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n const { baseDir } = configuration.content;\n\n // Setup Project for TS/React files if needed\n const _project =\n project || new Project({ skipAddingFilesFromTsConfig: true });\n\n const baseName = extractDictionaryKey(\n filePath,\n (await fs.readFile(filePath)).toString()\n );\n const componentKey = camelCaseToKebabCase(baseName);\n const ext = extname(filePath);\n\n let extractedContent: Record<string, string> | null = null;\n\n if (ext === '.vue') {\n try {\n const { processVueFile } = await import('@intlayer/vue-transformer');\n extractedContent = await processVueFile(\n filePath,\n componentKey,\n packageName,\n {\n generateKey,\n shouldExtract,\n extractTsContent,\n },\n saveComponent\n );\n } catch (error: any) {\n if (\n error.code === 'ERR_MODULE_NOT_FOUND' ||\n error.message?.includes('Cannot find module')\n ) {\n throw new Error(\n `Please install ${colorizePath('@intlayer/vue-transformer', ANSIColors.YELLOW)} to process Vue files.`\n );\n }\n throw error;\n }\n } else if (ext === '.svelte') {\n try {\n const { processSvelteFile } = (await import(\n '@intlayer/svelte-transformer'\n )) as any;\n extractedContent = await processSvelteFile(\n filePath,\n componentKey,\n packageName,\n {\n generateKey,\n shouldExtract,\n extractTsContent,\n },\n saveComponent\n );\n } catch (error: any) {\n if (\n error.code === 'ERR_MODULE_NOT_FOUND' ||\n error.message?.includes('Cannot find module')\n ) {\n throw new Error(\n `Please install ${colorizePath('@intlayer/svelte-transformer', ANSIColors.YELLOW)} to process Svelte files.`\n );\n }\n throw error;\n }\n } else if (['.tsx', '.jsx', '.ts', '.js'].includes(ext)) {\n extractedContent = await processTsxFile(\n filePath,\n componentKey,\n packageName,\n _project,\n saveComponent\n );\n }\n\n if (!extractedContent) {\n appLogger(`No extractable text found in ${baseName}`);\n return;\n }\n\n // Shared Write Logic\n if (writeContent) {\n const contentFilePath = await writeContentHelper(\n extractedContent,\n componentKey,\n filePath,\n configuration,\n options?.outputDir\n );\n\n const relativeContentFilePath = relative(\n configuration.content.baseDir,\n contentFilePath\n );\n appLogger(`Created content file: ${colorizePath(relativeContentFilePath)}`);\n }\n\n // Optional: Format\n if (saveComponent) {\n try {\n const formatCommand = detectFormatCommand(configuration);\n if (formatCommand) {\n execSync(formatCommand.replace('{{file}}', filePath), {\n stdio: 'ignore', // Silent\n cwd: baseDir,\n });\n }\n } catch {\n // Ignore format errors\n }\n\n appLogger(\n `Updated component: ${colorizePath(relative(baseDir, filePath))}`\n );\n }\n};\n\nexport const transformFiles = async (\n filePaths: string[],\n packageName: PackageName,\n options?: ExtractIntlayerOptions\n) => {\n const configuration = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n });\n\n for (const filePath of filePaths) {\n try {\n await extractIntlayer(filePath, packageName, options, project);\n } catch (error) {\n appLogger(`Failed to transform ${filePath}: ${(error as Error).message}`);\n }\n }\n};\n"],"mappings":"8uBA2BA,MAAa,EAAwB,CACnC,QACA,cACA,MACA,aACA,QACD,CAKY,EAAiB,GAA0B,CACtD,IAAM,EAAU,EAAK,MAAM,CAO3B,MADA,EALI,CAAC,GACD,CAAC,EAAQ,SAAS,IAAI,EAEtB,CAAC,SAAS,KAAK,EAAQ,EAEvB,EAAQ,WAAW,IAAI,EAAI,EAAQ,WAAW,KAAK,GAYnD,EAAqB,MACzB,EACA,EACA,EACA,EACA,IACG,CACH,GAAM,CAAE,iBAAkB,EAAc,qBAClC,CAAE,UAAS,kBAAmB,EAAc,QAE5C,EAAkB,GAAe,YAAY,OAE7C,EAAU,EAAY,EAAQ,EAAU,CAAG,EAAQ,EAAS,CAE5D,EAAW,EAAS,EADd,EAAQ,EAAS,CACW,CAGlC,EAAkB,EACtB,EACA,GAJsB,EAAS,OAAO,EAAE,CAAC,aAAa,CAAG,EAAS,MAAM,EAAE,CAIvD,GAAG,EAAe,KACtC,CACK,EAA0B,EAAS,EAAS,EAAgB,CAE9D,EAEJ,GAAI,EAEF,EAAa,CACX,IAAK,EACL,QAAS,EACT,OAAQ,EACR,SAAU,EACX,KACI,CAEL,IAAM,EAAuD,EAAE,CAC/D,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,EAAiB,CACzD,EAAoB,GAAO,CACzB,SAAU,cACV,YAAa,EACV,GAAgB,EAClB,CACF,CAGH,EAAa,CACX,IAAK,EACL,QAAS,EACT,SAAU,EACX,CAGH,IAAM,EAAc,EAAS,EAAS,EAAQ,CAK9C,OAJA,MAAM,EAAwB,EAAY,EAAe,CACvD,oBAAqB,EACtB,CAAC,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AI,CAAC,EAAkB,CACrB,EAAU,gCAAgC,IAAW,CACrD,OAIF,GAAI,EAAc,CAChB,IAAM,EAAkB,MAAM,EAC5B,EACA,EACA,EACA,EACA,GAAS,UACV,CAMD,EAAU,yBAAyB,EAJH,EAC9B,EAAc,QAAQ,QACtB,EACD,CACuE,GAAG,CAI7E,GAAI,EAAe,CACjB,GAAI,CACF,IAAM,EAAgB,EAAoB,EAAc,CACpD,GACF,EAAS,EAAc,QAAQ,WAAY,EAAS,CAAE,CACpD,MAAO,SACP,IAAK,EACN,CAAC,MAEE,EAIR,EACE,sBAAsB,EAAa,EAAS,EAAS,EAAS,CAAC,GAChE,GAIQ,EAAiB,MAC5B,EACA,EACA,IACG,CAEH,IAAM,EAAY,EADI,EAAiB,GAAS,cAAc,CACjB,CAEvC,EAAU,IAAI,EAAQ,CAC1B,4BAA6B,GAC9B,CAAC,CAEF,IAAK,IAAM,KAAY,EACrB,GAAI,CACF,MAAM,EAAgB,EAAU,EAAa,EAAS,EAAQ,OACvD,EAAO,CACd,EAAU,uBAAuB,EAAS,IAAK,EAAgB,UAAU"}
1
+ {"version":3,"file":"transformFiles.mjs","names":[],"sources":["../../../src/transformFiles/transformFiles.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport fs from 'node:fs/promises';\nimport { basename, dirname, extname, join, relative, resolve } from 'node:path';\nimport {\n ANSIColors,\n colorizePath,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { camelCaseToKebabCase } from '@intlayer/config/utils';\nimport { generateKey } from '@intlayer/core/utils';\nimport type { Dictionary, IntlayerConfig } from '@intlayer/types';\nimport { Node, Project, type SourceFile, SyntaxKind } from 'ts-morph';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport { writeContentDeclaration } from '../writeContentDeclaration';\nimport { extractDictionaryKey } from './extractDictionaryKey';\n\n// ==========================================\n// Shared Utilities (exported for reuse in babel plugin)\n// ==========================================\n\n/**\n * Attributes that should be extracted for localization\n */\nexport const ATTRIBUTES_TO_EXTRACT = [\n 'title',\n 'placeholder',\n 'alt',\n 'aria-label',\n 'label',\n];\n\n/**\n * Default function to determine if a string should be extracted for localization\n */\nexport const shouldExtract = (text: string): boolean => {\n const trimmed = text.trim();\n if (!trimmed) return false;\n if (!trimmed.includes(' ')) return false;\n // Starts with Capital letter\n if (!/^[A-Z]/.test(trimmed)) return false;\n // Filter out template logic identifiers (simple check)\n if (trimmed.startsWith('{') || trimmed.startsWith('v-')) return false;\n return true;\n};\n\n/**\n * Translation node structure used in multilingual dictionaries\n */\ntype TranslationNode = {\n nodeType: 'translation';\n translation: Record<string, string>;\n};\n\nconst writeContentHelper = async (\n extractedContent: Record<string, string>,\n componentKey: string,\n filePath: string,\n configuration: IntlayerConfig,\n outputDir?: string\n) => {\n const { defaultLocale } = configuration.internationalization;\n const { baseDir, fileExtensions } = configuration.content;\n\n const isPerLocaleFile = configuration?.dictionary?.locale;\n\n const dirName = outputDir ? resolve(outputDir) : dirname(filePath);\n const ext = extname(filePath);\n const baseName = basename(filePath, ext);\n const contentBaseName = baseName.charAt(0).toLowerCase() + baseName.slice(1);\n\n const contentFilePath = join(\n dirName,\n `${contentBaseName}.${fileExtensions[0]}`\n );\n const relativeContentFilePath = relative(baseDir, contentFilePath);\n\n let dictionary: Dictionary;\n\n if (isPerLocaleFile) {\n // Per-locale format: simple string content with locale property\n dictionary = {\n key: componentKey,\n content: extractedContent,\n locale: defaultLocale,\n filePath: relativeContentFilePath,\n };\n } else {\n // Multilingual format: content wrapped in translation nodes, no locale property\n const multilingualContent: Record<string, TranslationNode> = {};\n for (const [key, value] of Object.entries(extractedContent)) {\n multilingualContent[key] = {\n nodeType: 'translation',\n translation: {\n [defaultLocale]: value,\n },\n };\n }\n\n dictionary = {\n key: componentKey,\n content: multilingualContent,\n filePath: relativeContentFilePath,\n };\n }\n\n const relativeDir = relative(baseDir, dirName);\n await writeContentDeclaration(dictionary, configuration, {\n newDictionariesPath: relativeDir,\n });\n\n return contentFilePath;\n};\n\ntype TsReplacement = {\n node: Node;\n key: string;\n type: 'jsx-text' | 'jsx-attribute' | 'string-literal';\n};\n\nconst extractTsContent = (\n sourceFile: SourceFile,\n existingKeys: Set<string>\n): {\n extractedContent: Record<string, string>;\n replacements: TsReplacement[];\n} => {\n const extractedContent: Record<string, string> = {};\n const replacements: TsReplacement[] = [];\n\n sourceFile.forEachDescendant((node) => {\n // 1. JSX Text\n if (Node.isJsxText(node)) {\n const text = node.getText();\n if (shouldExtract(text)) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n extractedContent[key] = text.replace(/\\s+/g, ' ').trim();\n replacements.push({ node, key, type: 'jsx-text' });\n }\n }\n\n // 2. JSX Attributes\n else if (Node.isJsxAttribute(node)) {\n const name = node.getNameNode().getText();\n if (ATTRIBUTES_TO_EXTRACT.includes(name)) {\n const initializer = node.getInitializer();\n if (Node.isStringLiteral(initializer)) {\n const text = initializer.getLiteralValue();\n if (shouldExtract(text)) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n extractedContent[key] = text.trim();\n replacements.push({ node, key, type: 'jsx-attribute' });\n }\n }\n }\n }\n\n // 3. String Literals (Variables, Arrays, etc.)\n else if (Node.isStringLiteral(node)) {\n const text = node.getLiteralValue();\n if (shouldExtract(text)) {\n const parent = node.getParent();\n\n // Skip if inside ImportDeclaration\n if (\n parent?.getKindName() === 'ImportDeclaration' ||\n parent?.getKindName() === 'ImportSpecifier' ||\n parent?.getKindName() === 'ModuleSpecifier'\n ) {\n return;\n }\n\n // Skip if it's a JSX Attribute value (handled above)\n if (Node.isJsxAttribute(parent)) return;\n\n // Skip console.log\n if (Node.isCallExpression(parent)) {\n const expression = parent.getExpression();\n if (expression.getText().includes('console.log')) return;\n }\n\n // Skip Object Keys: { key: \"value\" } -> \"key\" is PropertyAssignment name if not computed\n if (Node.isPropertyAssignment(parent)) {\n if (parent.getNameNode() === node) return; // It's the key\n }\n\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n extractedContent[key] = text.trim();\n replacements.push({ node, key, type: 'string-literal' });\n }\n }\n });\n\n return { extractedContent, replacements };\n};\n\n// ==========================================\n// React (TS-Morph) Strategy\n// ==========================================\n\nconst processTsxFile = async (\n filePath: string,\n componentKey: string,\n packageName: PackageName,\n project: Project,\n save: boolean = true\n) => {\n let sourceFile: SourceFile;\n try {\n sourceFile = project.addSourceFileAtPath(filePath);\n } catch {\n sourceFile = project.getSourceFileOrThrow(filePath);\n }\n\n const isSolid = packageName === 'solid-intlayer';\n\n const existingKeys = new Set<string>();\n const { extractedContent, replacements } = extractTsContent(\n sourceFile,\n existingKeys\n );\n\n if (Object.keys(extractedContent).length === 0) return null;\n\n for (const { node, key, type } of replacements) {\n const contentAccess = isSolid ? `content().${key}` : `content.${key}`;\n\n if (type === 'jsx-text' && Node.isJsxText(node)) {\n node.replaceWithText(`{${contentAccess}}`);\n } else if (type === 'jsx-attribute' && Node.isJsxAttribute(node)) {\n node.setInitializer(`{${contentAccess}.value}`);\n } else if (type === 'string-literal' && Node.isStringLiteral(node)) {\n // For React/JS variables, we usually want the value\n node.replaceWithText(`${contentAccess}.value`);\n }\n }\n\n // Inject hook\n const importDecl = sourceFile.getImportDeclaration(\n (d) => d.getModuleSpecifierValue() === packageName\n );\n if (!importDecl) {\n sourceFile.addImportDeclaration({\n namedImports: ['useIntlayer'],\n moduleSpecifier: packageName,\n });\n } else if (\n !importDecl.getNamedImports().some((n) => n.getName() === 'useIntlayer')\n ) {\n importDecl.addNamedImport('useIntlayer');\n }\n\n // Insert hook at start of component\n sourceFile.getFunctions().forEach((f) => {\n f.getBody()\n ?.asKind(SyntaxKind.Block)\n ?.insertStatements(0, `const content = useIntlayer(\"${componentKey}\");`);\n });\n\n // Also handle const/arrow components\n sourceFile.getVariableDeclarations().forEach((v) => {\n const init = v.getInitializer();\n if (Node.isArrowFunction(init) || Node.isFunctionExpression(init)) {\n const body = init.getBody();\n if (Node.isBlock(body)) {\n // Heuristic: check if it returns JSX or uses hooks\n if (\n body.getText().includes('return') ||\n body.getText().includes('use')\n ) {\n body.insertStatements(\n 0,\n `const content = useIntlayer(\"${componentKey}\");`\n );\n }\n }\n }\n });\n\n if (save) {\n await sourceFile.save();\n }\n return extractedContent;\n};\n\n// ==========================================\n// 5. Main Dispatcher\n// ==========================================\n\nexport type PackageName =\n | 'next-intlayer'\n | 'react-intlayer'\n | 'vue-intlayer'\n | 'svelte-intlayer'\n | 'preact-intlayer'\n | 'solid-intlayer'\n | 'angular-intlayer'\n | 'express-intlayer';\n\nexport type ExtractIntlayerOptions = {\n configOptions?: GetConfigurationOptions;\n outputDir?: string;\n codeOnly?: boolean;\n declarationOnly?: boolean;\n};\n\nexport const extractIntlayer = async (\n filePath: string,\n packageName: PackageName,\n options?: ExtractIntlayerOptions,\n project?: Project\n) => {\n const saveComponent = !options?.declarationOnly;\n const writeContent = !options?.codeOnly;\n\n const configuration = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n const { baseDir } = configuration.content;\n\n // Setup Project for TS/React files if needed\n const _project =\n project || new Project({ skipAddingFilesFromTsConfig: true });\n\n const baseName = extractDictionaryKey(\n filePath,\n (await fs.readFile(filePath)).toString()\n );\n const componentKey = camelCaseToKebabCase(baseName);\n const ext = extname(filePath);\n\n let extractedContent: Record<string, string> | null = null;\n\n if (ext === '.vue') {\n try {\n const { processVueFile } = await import('@intlayer/vue-transformer');\n extractedContent = await processVueFile(\n filePath,\n componentKey,\n packageName,\n {\n generateKey,\n shouldExtract,\n extractTsContent,\n },\n saveComponent\n );\n } catch (error: any) {\n if (\n error.code === 'ERR_MODULE_NOT_FOUND' ||\n error.message?.includes('Cannot find module')\n ) {\n throw new Error(\n `Please install ${colorizePath('@intlayer/vue-transformer', ANSIColors.YELLOW)} to process Vue files.`\n );\n }\n throw error;\n }\n } else if (ext === '.svelte') {\n try {\n const { processSvelteFile } = (await import(\n '@intlayer/svelte-transformer'\n )) as any;\n extractedContent = await processSvelteFile(\n filePath,\n componentKey,\n packageName,\n {\n generateKey,\n shouldExtract,\n extractTsContent,\n },\n saveComponent\n );\n } catch (error: any) {\n if (\n error.code === 'ERR_MODULE_NOT_FOUND' ||\n error.message?.includes('Cannot find module')\n ) {\n throw new Error(\n `Please install ${colorizePath('@intlayer/svelte-transformer', ANSIColors.YELLOW)} to process Svelte files.`\n );\n }\n throw error;\n }\n } else if (['.tsx', '.jsx', '.ts', '.js'].includes(ext)) {\n extractedContent = await processTsxFile(\n filePath,\n componentKey,\n packageName,\n _project,\n saveComponent\n );\n }\n\n if (!extractedContent) {\n appLogger(`No extractable text found in ${baseName}`);\n return;\n }\n\n // Shared Write Logic\n if (writeContent) {\n const contentFilePath = await writeContentHelper(\n extractedContent,\n componentKey,\n filePath,\n configuration,\n options?.outputDir\n );\n\n const relativeContentFilePath = relative(\n configuration.content.baseDir,\n contentFilePath\n );\n appLogger(`Created content file: ${colorizePath(relativeContentFilePath)}`);\n }\n\n // Optional: Format\n if (saveComponent) {\n try {\n const formatCommand = detectFormatCommand(configuration);\n if (formatCommand) {\n execSync(formatCommand.replace('{{file}}', filePath), {\n stdio: 'ignore', // Silent\n cwd: baseDir,\n });\n }\n } catch {\n // Ignore format errors\n }\n\n appLogger(\n `Updated component: ${colorizePath(relative(baseDir, filePath))}`\n );\n }\n};\n\nexport const transformFiles = async (\n filePaths: string[],\n packageName: PackageName,\n options?: ExtractIntlayerOptions\n) => {\n const configuration = getConfiguration(options?.configOptions);\n const appLogger = getAppLogger(configuration);\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n });\n\n for (const filePath of filePaths) {\n try {\n await extractIntlayer(filePath, packageName, options, project);\n } catch (error) {\n appLogger(`Failed to transform ${filePath}: ${(error as Error).message}`);\n }\n }\n};\n"],"mappings":"stBA2BA,MAAa,EAAwB,CACnC,QACA,cACA,MACA,aACA,QACD,CAKY,EAAiB,GAA0B,CACtD,IAAM,EAAU,EAAK,MAAM,CAO3B,MADA,EAL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EAIR,EACE,sBAAsB,EAAa,EAAS,EAAS,EAAS,CAAC,GAChE,GAIQ,EAAiB,MAC5B,EACA,EACA,IACG,CAEH,IAAM,EAAY,EADI,EAAiB,GAAS,cAAc,CACjB,CAEvC,EAAU,IAAI,EAAQ,CAC1B,4BAA6B,GAC9B,CAAC,CAEF,IAAK,IAAM,KAAY,EACrB,GAAI,CACF,MAAM,EAAgB,EAAU,EAAa,EAAS,EAAQ,OACvD,EAAO,CACd,EAAU,uBAAuB,EAAS,IAAK,EAAgB,UAAU"}
@@ -1 +1 @@
1
- import{detectExportedComponentName as e}from"./detectExportedComponentName.mjs";import{detectFormatCommand as t}from"./detectFormatCommand.mjs";import{transformJSFile as n}from"./transformJSFile.mjs";import{writeJSFile as r}from"./writeJSFile.mjs";import{writeContentDeclaration as i}from"./writeContentDeclaration.mjs";export{e as detectExportedComponentName,t as detectFormatCommand,n as transformJSFile,i as writeContentDeclaration,r as writeJSFile};
1
+ import{detectExportedComponentName as e}from"./detectExportedComponentName.mjs";import{transformJSFile as t}from"./transformJSFile.mjs";import{writeJSFile as n}from"./writeJSFile.mjs";import{writeContentDeclaration as r}from"./writeContentDeclaration.mjs";export{e as detectExportedComponentName,t as transformJSFile,r as writeContentDeclaration,n as writeJSFile};
@@ -1,2 +1,2 @@
1
- import{detectFormatCommand as e}from"./detectFormatCommand.mjs";import{transformJSFile as t}from"./transformJSFile.mjs";import{getFormatFromExtension as n}from"../utils/getFormatFromExtension.mjs";import{getContentDeclarationFileTemplate as r}from"../getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.mjs";import{mkdir as i,readFile as a,rename as o,rm as s,writeFile as c}from"node:fs/promises";import{basename as l,extname as u,join as d}from"node:path";import{getAppLogger as f,logger as p}from"@intlayer/config/logger";import{existsSync as m}from"node:fs";import{execSync as h}from"node:child_process";const g=async(g,_,v)=>{let y={...v.dictionary,..._},b=f(v);if(!m(g)){let e=n(u(g));b(`File does not exist, creating it`,{isVerbose:!0});let t=await r(y.key,e,Object.fromEntries(Object.entries({id:y.id,locale:y.locale,filled:y.filled,fill:y.fill,description:y.description,title:y.title,tags:y.tags,version:y.version,priority:y.priority,importMode:y.importMode}).filter(([,e])=>e!==void 0))),a=v.system?.tempDir;a&&await i(a,{recursive:!0});let f=`${l(g)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,p=a?d(a,f):`${g}.${f}`;try{await c(p,t,`utf-8`),await o(p,g)}catch(e){try{await s(p,{force:!0})}catch{}throw e}}let x=await a(g,`utf-8`);if(x===``){let e=n(u(g));x=await r(y.key,e)}let S=await t(x,_),C=v.system?.tempDir;C&&await i(C,{recursive:!0});let w=`${l(g)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,T=C?d(C,w):`${g}.${w}`;try{await c(T,S,`utf-8`),await o(T,g),p(`Successfully updated ${g}`,{level:`info`,isVerbose:!0})}catch(e){try{await s(T,{force:!0})}catch{}let t=e;throw p(`Failed to write updated file: ${g}`,{level:`error`}),Error(`Failed to write updated file ${g}: ${t.message}`)}let E=e(v);if(E)try{h(E.replace(`{{file}}`,g),{stdio:`inherit`,cwd:v.content.baseDir})}catch(e){console.error(e)}};export{g as writeJSFile};
1
+ import{transformJSFile as e}from"./transformJSFile.mjs";import{getFormatFromExtension as t}from"../utils/getFormatFromExtension.mjs";import{detectFormatCommand as n}from"../detectFormatCommand.mjs";import{getContentDeclarationFileTemplate as r}from"../getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.mjs";import{mkdir as i,readFile as a,rename as o,rm as s,writeFile as c}from"node:fs/promises";import{basename as l,extname as u,join as d}from"node:path";import{getAppLogger as f,logger as p}from"@intlayer/config/logger";import{existsSync as m}from"node:fs";import{execSync as h}from"node:child_process";const g=async(g,_,v)=>{let y={...v.dictionary,..._},b=f(v);if(!m(g)){let e=t(u(g));b(`File does not exist, creating it`,{isVerbose:!0});let n=await r(y.key,e,Object.fromEntries(Object.entries({id:y.id,locale:y.locale,filled:y.filled,fill:y.fill,description:y.description,title:y.title,tags:y.tags,version:y.version,priority:y.priority,importMode:y.importMode}).filter(([,e])=>e!==void 0))),a=v.system?.tempDir;a&&await i(a,{recursive:!0});let f=`${l(g)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,p=a?d(a,f):`${g}.${f}`;try{await c(p,n,`utf-8`),await o(p,g)}catch(e){try{await s(p,{force:!0})}catch{}throw e}}let x=await a(g,`utf-8`);if(x===``){let e=t(u(g));x=await r(y.key,e)}let S=await e(x,_),C=v.system?.tempDir;C&&await i(C,{recursive:!0});let w=`${l(g)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,T=C?d(C,w):`${g}.${w}`;try{await c(T,S,`utf-8`),await o(T,g),p(`Successfully updated ${g}`,{level:`info`,isVerbose:!0})}catch(e){try{await s(T,{force:!0})}catch{}let t=e;throw p(`Failed to write updated file: ${g}`,{level:`error`}),Error(`Failed to write updated file ${g}: ${t.message}`)}let E=n(v);if(E)try{h(E.replace(`{{file}}`,g),{stdio:`inherit`,cwd:v.content.baseDir})}catch(e){console.error(e)}};export{g as writeJSFile};
2
2
  //# sourceMappingURL=writeJSFile.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"writeJSFile.mjs","names":[],"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 { Dictionary, IntlayerConfig } from '@intlayer/types';\nimport { getContentDeclarationFileTemplate } from '../getContentDeclarationFileTemplate/getContentDeclarationFileTemplate';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport { detectFormatCommand } from './detectFormatCommand';\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): 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: mergedDictionary.id,\n locale: mergedDictionary.locale,\n filled: mergedDictionary.filled,\n fill: mergedDictionary.fill,\n description: mergedDictionary.description,\n title: mergedDictionary.title,\n tags: mergedDictionary.tags,\n version: mergedDictionary.version,\n priority: mergedDictionary.priority,\n importMode: mergedDictionary.importMode,\n }).filter(([, value]) => value !== undefined)\n )\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 }\n\n const finalCode = await transformJSFile(fileContent, dictionary);\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.content.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n};\n"],"mappings":"gnBAoBA,MAAa,EAAc,MACzB,EACA,EACA,IACkB,CAClB,IAAM,EAAmB,CACvB,GAAG,EAAc,WACjB,GAAG,EACJ,CAEK,EAAY,EAAa,EAAc,CAG7C,GAAI,CAAC,EAAW,EAAS,CAAE,CAGzB,IAAM,EAAS,EAFO,EAAQ,EAAS,CAEa,CAEpD,EAAU,mCAAoC,CAC5C,UAAW,GACZ,CAAC,CACF,IAAM,EAAW,MAAM,EACrB,EAAiB,IACjB,EAEA,OAAO,YACL,OAAO,QAAQ,CACb,GAAI,EAAiB,GACrB,OAAQ,EAAiB,OACzB,OAAQ,EAAiB,OACzB,KAAM,EAAiB,KACvB,YAAa,EAAiB,YAC9B,MAAO,EAAiB,MACxB,KAAM,EAAiB,KACvB,QAAS,EAAiB,QAC1B,SAAU,EAAiB,SAC3B,WAAY,EAAiB,WAC9B,CAAC,CAAC,QAAQ,EAAG,KAAW,IAAU,IAAA,GAAU,CAC9C,CACF,CAEK,EAAU,EAAc,QAAQ,QAClC,GACF,MAAM,EAAM,EAAS,CAAE,UAAW,GAAM,CAAC,CAG3C,IAAM,EAAe,GAAG,EAAS,EAAS,CAAC,GAAG,KAAK,KAAK,CAAC,GAAG,KAAK,QAAQ,C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O,CACd,QAAQ,MAAM,EAAM"}
1
+ {"version":3,"file":"writeJSFile.mjs","names":[],"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 { Dictionary, IntlayerConfig } from '@intlayer/types';\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): 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: mergedDictionary.id,\n locale: mergedDictionary.locale,\n filled: mergedDictionary.filled,\n fill: mergedDictionary.fill,\n description: mergedDictionary.description,\n title: mergedDictionary.title,\n tags: mergedDictionary.tags,\n version: mergedDictionary.version,\n priority: mergedDictionary.priority,\n importMode: mergedDictionary.importMode,\n }).filter(([, value]) => value !== undefined)\n )\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 }\n\n const finalCode = await transformJSFile(fileContent, dictionary);\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.content.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n};\n"],"mappings":"inBAoBA,MAAa,EAAc,MACzB,EACA,EACA,IACkB,CAClB,IAAM,EAAmB,CACvB,GAAG,EAAc,WACjB,GAAG,EACJ,CAEK,EAAY,EAAa,EAAc,CAG7C,GAAI,CAAC,EAAW,EAAS,CAAE,CAGzB,IAAM,EAAS,EAFO,EAAQ,EAAS,CAEa,CAE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,EAAW,EACb,EAAK,EAAS,EAAa,CAC3B,GAAG,EAAS,GAAG,IACnB,GAAI,CACF,MAAM,EAAU,EAAU,EAAW,QAAQ,CAC7C,MAAM,EAAO,EAAU,EAAS,CAChC,EAAO,wBAAwB,IAAY,CACzC,MAAO,OACP,UAAW,GACZ,CAAC,OACK,EAAO,CACd,GAAI,CACF,MAAM,EAAG,EAAU,CAAE,MAAO,GAAM,CAAC,MAC7B,EAGR,IAAM,EAAM,EAIZ,MAHA,EAAO,iCAAiC,IAAY,CAClD,MAAO,QACR,CAAC,CACQ,MAAM,gCAAgC,EAAS,IAAI,EAAI,UAAU,CAG7E,IAAM,EAAgB,EAAoB,EAAc,CAExD,GAAI,EACF,GAAI,CACF,EAAS,EAAc,QAAQ,WAAY,EAAS,CAAE,CACpD,MAAO,UACP,IAAK,EAAc,QAAQ,QAC5B,CAAC,OACK,EAAO,CACd,QAAQ,MAAM,EAAM"}
@@ -22,10 +22,9 @@ import "./loadDictionaries/index.js";
22
22
  import { prepareIntlayer } from "./prepareIntlayer.js";
23
23
  import { isCachedConfigurationUpToDate, writeConfiguration } from "./writeConfiguration/index.js";
24
24
  import { detectExportedComponentName } from "./writeContentDeclaration/detectExportedComponentName.js";
25
- import { detectFormatCommand } from "./writeContentDeclaration/detectFormatCommand.js";
26
25
  import { DictionaryStatus } from "./writeContentDeclaration/dictionaryStatus.js";
27
26
  import { transformJSFile } from "./writeContentDeclaration/transformJSFile.js";
28
27
  import { writeContentDeclaration } from "./writeContentDeclaration/writeContentDeclaration.js";
29
28
  import { writeJSFile } from "./writeContentDeclaration/writeJSFile.js";
30
29
  import "./writeContentDeclaration/index.js";
31
- export { CreateDictionaryEntryPointOptions, DictionariesStatus, DictionaryStatus, buildDictionary, cleanOutputDir, createDictionaryEntryPoint, createModuleAugmentation, createTypes, detectExportedComponentName, detectFormatCommand, formatDictionaries, formatDictionariesOutput, formatDictionary, formatDictionaryOutput, formatDistantDictionaries, formatLocalDictionaries, generateDictionaryListContent, generateTypeScriptType, getBuiltDictionariesPath, getBuiltDynamicDictionariesPath, getBuiltFetchDictionariesPath, getBuiltRemoteDictionariesPath, getBuiltUnmergedDictionariesPath, getTypeName, isCachedConfigurationUpToDate, loadContentDeclarations, loadDictionaries, loadLocalDictionaries, loadRemoteDictionaries, prepareIntlayer, processContentDeclaration, transformJSFile, writeConfiguration, writeContentDeclaration, writeJSFile };
30
+ export { CreateDictionaryEntryPointOptions, DictionariesStatus, DictionaryStatus, buildDictionary, cleanOutputDir, createDictionaryEntryPoint, createModuleAugmentation, createTypes, detectExportedComponentName, formatDictionaries, formatDictionariesOutput, formatDictionary, formatDictionaryOutput, formatDistantDictionaries, formatLocalDictionaries, generateDictionaryListContent, generateTypeScriptType, getBuiltDictionariesPath, getBuiltDynamicDictionariesPath, getBuiltFetchDictionariesPath, getBuiltRemoteDictionariesPath, getBuiltUnmergedDictionariesPath, getTypeName, isCachedConfigurationUpToDate, loadContentDeclarations, loadDictionaries, loadLocalDictionaries, loadRemoteDictionaries, prepareIntlayer, processContentDeclaration, transformJSFile, writeConfiguration, writeContentDeclaration, writeJSFile };
@@ -1,3 +1,4 @@
1
+ import { detectFormatCommand } from "./detectFormatCommand.js";
1
2
  import { getContentDeclarationFileTemplate } from "./getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.js";
2
3
  import { initIntlayer } from "./init/index.js";
3
4
  import { Platform, SKILLS, SKILLS_METADATA, Skill, installSkills } from "./installSkills/index.js";
@@ -7,4 +8,4 @@ import { ListProjectsOptions, listProjects } from "./listProjects.js";
7
8
  import { extractDictionaryKey } from "./transformFiles/extractDictionaryKey.js";
8
9
  import { ATTRIBUTES_TO_EXTRACT, ExtractIntlayerOptions, PackageName, extractIntlayer, shouldExtract, transformFiles } from "./transformFiles/transformFiles.js";
9
10
  import "./transformFiles/index.js";
10
- export { ATTRIBUTES_TO_EXTRACT, DiffMode, ExtractIntlayerOptions, ListGitFilesOptions, ListGitLinesOptions, ListProjectsOptions, PackageName, Platform, SKILLS, SKILLS_METADATA, Skill, extractDictionaryKey, extractIntlayer, getContentDeclarationFileTemplate, initIntlayer, installSkills, listDictionaries, listDictionariesWithStats, listGitFiles, listGitLines, listProjects, shouldExtract, transformFiles };
11
+ export { ATTRIBUTES_TO_EXTRACT, DiffMode, ExtractIntlayerOptions, ListGitFilesOptions, ListGitLinesOptions, ListProjectsOptions, PackageName, Platform, SKILLS, SKILLS_METADATA, Skill, detectFormatCommand, extractDictionaryKey, extractIntlayer, getContentDeclarationFileTemplate, initIntlayer, installSkills, listDictionaries, listDictionariesWithStats, listGitFiles, listGitLines, listProjects, shouldExtract, transformFiles };
@@ -1,6 +1,6 @@
1
1
  import { IntlayerConfig } from "@intlayer/types";
2
2
 
3
- //#region src/writeContentDeclaration/detectFormatCommand.d.ts
3
+ //#region src/detectFormatCommand.d.ts
4
4
  declare const detectFormatCommand: (configuration: IntlayerConfig, projectRequireProp?: NodeJS.Require) => string;
5
5
  //#endregion
6
6
  export { detectFormatCommand };
@@ -0,0 +1 @@
1
+ {"version":3,"file":"detectFormatCommand.d.ts","names":[],"sources":["../../src/detectFormatCommand.ts"],"mappings":";;;cAKa,mBAAA,GACX,aAAA,EAAe,cAAA,EACf,kBAAA,GAAqB,MAAA,CAAO,OAAA"}
@@ -18,12 +18,12 @@ import { formatDistantDictionaries, loadRemoteDictionaries } from "./loadDiction
18
18
  import { prepareIntlayer } from "./prepareIntlayer.js";
19
19
  import { isCachedConfigurationUpToDate, writeConfiguration } from "./writeConfiguration/index.js";
20
20
  import { detectExportedComponentName } from "./writeContentDeclaration/detectExportedComponentName.js";
21
- import { detectFormatCommand } from "./writeContentDeclaration/detectFormatCommand.js";
22
21
  import { DictionaryStatus } from "./writeContentDeclaration/dictionaryStatus.js";
23
22
  import { transformJSFile } from "./writeContentDeclaration/transformJSFile.js";
24
23
  import { writeContentDeclaration } from "./writeContentDeclaration/writeContentDeclaration.js";
25
24
  import { writeJSFile } from "./writeContentDeclaration/writeJSFile.js";
26
25
  import "./build.js";
26
+ import { detectFormatCommand } from "./detectFormatCommand.js";
27
27
  import { Extension, Format, getExtensionFromFormat, getFormatFromExtension } from "./utils/getFormatFromExtension.js";
28
28
  import { getContentDeclarationFileTemplate } from "./getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.js";
29
29
  import { initIntlayer } from "./init/index.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/init/index.ts"],"mappings":";;AAgKA;;cAAa,YAAA,GAAsB,OAAA,aAAe,OAAA"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/init/index.ts"],"mappings":";;AAmKA;;cAAa,YAAA,GAAsB,OAAA,aAAe,OAAA"}
@@ -11,6 +11,10 @@ declare const readFileFromRoot: (rootDir: string, filePath: string) => Promise<s
11
11
  * Helper to write a file
12
12
  */
13
13
  declare const writeFileToRoot: (rootDir: string, filePath: string, content: string) => Promise<void>;
14
+ /**
15
+ * Helper to ensure a directory exists
16
+ */
17
+ declare const ensureDirectory: (rootDir: string, dirPath: string) => Promise<void>;
14
18
  //#endregion
15
- export { exists, readFileFromRoot, writeFileToRoot };
19
+ export { ensureDirectory, exists, readFileFromRoot, writeFileToRoot };
16
20
  //# sourceMappingURL=fileSystem.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"fileSystem.d.ts","names":[],"sources":["../../../../src/init/utils/fileSystem.ts"],"mappings":";;AAMA;;cAAa,MAAA,GAAgB,OAAA,UAAiB,QAAA,aAAgB,OAAA;;;;cAYjD,gBAAA,GAA0B,OAAA,UAAiB,QAAA,aAAgB,OAAA;;;AAAxE;cAMa,eAAA,GACX,OAAA,UACA,QAAA,UACA,OAAA,aAAe,OAAA"}
1
+ {"version":3,"file":"fileSystem.d.ts","names":[],"sources":["../../../../src/init/utils/fileSystem.ts"],"mappings":";;AAMA;;cAAa,MAAA,GAAgB,OAAA,UAAiB,QAAA,aAAgB,OAAA;;;;cAYjD,gBAAA,GAA0B,OAAA,UAAiB,QAAA,aAAgB,OAAA;;;AAAxE;cAMa,eAAA,GACX,OAAA,UACA,QAAA,UACA,OAAA,aAAe,OAAA;;;;cAMJ,eAAA,GAAyB,OAAA,UAAiB,OAAA,aAAe,OAAA"}
@@ -1,5 +1,5 @@
1
1
  import { updateNextConfig, updateViteConfig } from "./configManipulation.js";
2
- import { exists, readFileFromRoot, writeFileToRoot } from "./fileSystem.js";
2
+ import { ensureDirectory, exists, readFileFromRoot, writeFileToRoot } from "./fileSystem.js";
3
3
  import { parseJSONWithComments } from "./jsonParser.js";
4
4
  import { findTsConfigFiles } from "./tsConfig.js";
5
- export { exists, findTsConfigFiles, parseJSONWithComments, readFileFromRoot, updateNextConfig, updateViteConfig, writeFileToRoot };
5
+ export { ensureDirectory, exists, findTsConfigFiles, parseJSONWithComments, readFileFromRoot, updateNextConfig, updateViteConfig, writeFileToRoot };
@@ -13,6 +13,7 @@ declare const SKILLS_METADATA: {
13
13
  readonly Svelte: "Svelte-specific stores and syntax";
14
14
  readonly Astro: "Astro-specific usage and getIntlayer";
15
15
  readonly CLI: "Intlayer CLI commands and usage";
16
+ readonly Compiler: "Intlayer Compiler setup and usage for automatic content extraction without .content files";
16
17
  };
17
18
  declare const SKILLS: (keyof typeof SKILLS_METADATA)[];
18
19
  type Skill = (typeof SKILLS)[number];
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/installSkills/index.ts"],"mappings":";cAKa,eAAA;EAAA;;;;;;;;;;;;;;cAiBA,MAAA,gBAEM,eAAA;AAAA,KAEP,KAAA,WAAgB,MAAA;;;;cAUtB,aAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAsCM,QAAA,gBAAwB,aAAA;;;;;cAoDvB,aAAA,GACX,WAAA,UACA,QAAA,EAAU,QAAA,EACV,MAAA,EAAQ,KAAA,OACP,OAAA"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/installSkills/index.ts"],"mappings":";cAKa,eAAA;EAAA;;;;;;;;;;;;;;;cAmBA,MAAA,gBAEM,eAAA;AAAA,KAEP,KAAA,WAAgB,MAAA;;;;cAUtB,aAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAsCM,QAAA,gBAAwB,aAAA;;;;;cAoDvB,aAAA,GACX,WAAA,UACA,QAAA,EAAU,QAAA,EACV,MAAA,EAAQ,KAAA,OACP,OAAA"}
@@ -1,7 +1,6 @@
1
1
  import { detectExportedComponentName } from "./detectExportedComponentName.js";
2
- import { detectFormatCommand } from "./detectFormatCommand.js";
3
2
  import { DictionaryStatus } from "./dictionaryStatus.js";
4
3
  import { transformJSFile } from "./transformJSFile.js";
5
4
  import { writeContentDeclaration } from "./writeContentDeclaration.js";
6
5
  import { writeJSFile } from "./writeJSFile.js";
7
- export { DictionaryStatus, detectExportedComponentName, detectFormatCommand, transformJSFile, writeContentDeclaration, writeJSFile };
6
+ export { DictionaryStatus, detectExportedComponentName, transformJSFile, writeContentDeclaration, writeJSFile };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intlayer/chokidar",
3
- "version": "8.1.6",
3
+ "version": "8.1.8",
4
4
  "private": false,
5
5
  "description": "Uses chokidar to scan and build Intlayer declaration files into dictionaries based on Intlayer configuration.",
6
6
  "keywords": [
@@ -84,7 +84,6 @@
84
84
  "./package.json"
85
85
  ],
86
86
  "scripts": {
87
- "_prepublish": "cp -f ../../../README.md ./README.md",
88
87
  "build": "tsdown --config tsdown.config.ts",
89
88
  "build:ci": "tsdown --config tsdown.config.ts",
90
89
  "clean": "rimraf ./dist .turbo",
@@ -93,7 +92,7 @@
93
92
  "format:fix": "biome format --write .",
94
93
  "lint": "biome lint .",
95
94
  "lint:fix": "biome lint --write .",
96
- "prepublish": "echo prepublish temporally disabled to avoid rewrite readme",
95
+ "prepublish": "cp -f ../../../README.md ./README.md",
97
96
  "publish": "bun publish || true",
98
97
  "publish:canary": "bun publish --access public --tag canary || true",
99
98
  "publish:latest": "bun publish --access public --tag latest || true",
@@ -102,13 +101,13 @@
102
101
  "typecheck": "tsc --noEmit --project tsconfig.types.json"
103
102
  },
104
103
  "dependencies": {
105
- "@intlayer/api": "8.1.6",
106
- "@intlayer/config": "8.1.6",
107
- "@intlayer/core": "8.1.6",
108
- "@intlayer/dictionaries-entry": "8.1.6",
109
- "@intlayer/remote-dictionaries-entry": "8.1.6",
110
- "@intlayer/types": "8.1.6",
111
- "@intlayer/unmerged-dictionaries-entry": "8.1.6",
104
+ "@intlayer/api": "8.1.8",
105
+ "@intlayer/config": "8.1.8",
106
+ "@intlayer/core": "8.1.8",
107
+ "@intlayer/dictionaries-entry": "8.1.8",
108
+ "@intlayer/remote-dictionaries-entry": "8.1.8",
109
+ "@intlayer/types": "8.1.8",
110
+ "@intlayer/unmerged-dictionaries-entry": "8.1.8",
112
111
  "chokidar": "3.6.0",
113
112
  "crypto-js": "4.2.0",
114
113
  "defu": "6.1.4",
@@ -130,8 +129,8 @@
130
129
  "zod": "4.3.6"
131
130
  },
132
131
  "peerDependencies": {
133
- "@intlayer/svelte-transformer": "8.1.6",
134
- "@intlayer/vue-transformer": "8.1.6"
132
+ "@intlayer/svelte-transformer": "8.1.8",
133
+ "@intlayer/vue-transformer": "8.1.8"
135
134
  },
136
135
  "peerDependenciesMeta": {
137
136
  "@intlayer/svelte-transformer": {
@@ -1,2 +0,0 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);let e=require(`@intlayer/config/utils`),t=null;const n=(n,r)=>{let{formatCommand:i,baseDir:a}=n.content,o=r??(0,e.getProjectRequire)(a);if(i)return i;if(t!==null)return t;try{return o.resolve(`prettier`),t=`prettier --write "{{file}}" --log-level silent`,t}catch{}try{return o.resolve(`biome`),t=`biome format "{{file}}" --write --log-level none`,t}catch{}try{return o.resolve(`eslint`),t=`eslint --fix "{{file}}" --quiet`,t}catch{}t=void 0};exports.detectFormatCommand=n;
2
- //# sourceMappingURL=detectFormatCommand.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"detectFormatCommand.cjs","names":[],"sources":["../../../src/writeContentDeclaration/detectFormatCommand.ts"],"sourcesContent":["import { getProjectRequire } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types';\n\nlet cachedFormatCommand: string | undefined | null = null;\n\nexport const detectFormatCommand = (\n configuration: IntlayerConfig,\n projectRequireProp?: NodeJS.Require\n) => {\n const { formatCommand, baseDir } = configuration.content;\n const projectRequire = projectRequireProp ?? getProjectRequire(baseDir);\n\n // Priority: Explicit configuration\n // We do not cache this because the user might change their config file active-session.\n if (formatCommand) {\n return formatCommand;\n }\n\n // Priority: Cached detection\n // If not null, we have already performed the expensive checks.\n if (cachedFormatCommand !== null) {\n return cachedFormatCommand;\n }\n\n // Perform Detection\n\n // Try Prettier\n try {\n projectRequire.resolve('prettier');\n cachedFormatCommand = 'prettier --write \"{{file}}\" --log-level silent';\n return cachedFormatCommand;\n } catch (_error) {\n // Prettier not found, continue\n }\n\n // Try Biome\n try {\n projectRequire.resolve('biome');\n cachedFormatCommand = 'biome format \"{{file}}\" --write --log-level none';\n return cachedFormatCommand;\n } catch (_error) {\n // Biome not found, continue\n }\n\n // Try ESLint\n try {\n projectRequire.resolve('eslint');\n cachedFormatCommand = 'eslint --fix \"{{file}}\" --quiet';\n return cachedFormatCommand;\n } catch (_error) {\n // ESLint not found\n }\n\n // No formatter found\n // Set to undefined (not null) so we know we checked and found nothing.\n cachedFormatCommand = undefined;\n return undefined;\n};\n"],"mappings":"wJAGI,EAAiD,KAErD,MAAa,GACX,EACA,IACG,CACH,GAAM,CAAE,gBAAe,WAAY,EAAc,QAC3C,EAAiB,IAAA,EAAA,EAAA,mBAAwC,EAAQ,CAIvE,GAAI,EACF,OAAO,EAKT,GAAI,IAAwB,KAC1B,OAAO,EAMT,GAAI,CAGF,OAFA,EAAe,QAAQ,WAAW,CAClC,EAAsB,iDACf,OACQ,EAKjB,GAAI,CAGF,OAFA,EAAe,QAAQ,QAAQ,CAC/B,EAAsB,mDACf,OACQ,EAKjB,GAAI,CAGF,OAFA,EAAe,QAAQ,SAAS,CAChC,EAAsB,kCACf,OACQ,EAMjB,EAAsB,IAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"detectFormatCommand.mjs","names":[],"sources":["../../../src/writeContentDeclaration/detectFormatCommand.ts"],"sourcesContent":["import { getProjectRequire } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types';\n\nlet cachedFormatCommand: string | undefined | null = null;\n\nexport const detectFormatCommand = (\n configuration: IntlayerConfig,\n projectRequireProp?: NodeJS.Require\n) => {\n const { formatCommand, baseDir } = configuration.content;\n const projectRequire = projectRequireProp ?? getProjectRequire(baseDir);\n\n // Priority: Explicit configuration\n // We do not cache this because the user might change their config file active-session.\n if (formatCommand) {\n return formatCommand;\n }\n\n // Priority: Cached detection\n // If not null, we have already performed the expensive checks.\n if (cachedFormatCommand !== null) {\n return cachedFormatCommand;\n }\n\n // Perform Detection\n\n // Try Prettier\n try {\n projectRequire.resolve('prettier');\n cachedFormatCommand = 'prettier --write \"{{file}}\" --log-level silent';\n return cachedFormatCommand;\n } catch (_error) {\n // Prettier not found, continue\n }\n\n // Try Biome\n try {\n projectRequire.resolve('biome');\n cachedFormatCommand = 'biome format \"{{file}}\" --write --log-level none';\n return cachedFormatCommand;\n } catch (_error) {\n // Biome not found, continue\n }\n\n // Try ESLint\n try {\n projectRequire.resolve('eslint');\n cachedFormatCommand = 'eslint --fix \"{{file}}\" --quiet';\n return cachedFormatCommand;\n } catch (_error) {\n // ESLint not found\n }\n\n // No formatter found\n // Set to undefined (not null) so we know we checked and found nothing.\n cachedFormatCommand = undefined;\n return undefined;\n};\n"],"mappings":"2DAGA,IAAI,EAAiD,KAErD,MAAa,GACX,EACA,IACG,CACH,GAAM,CAAE,gBAAe,WAAY,EAAc,QAC3C,EAAiB,GAAsB,EAAkB,EAAQ,CAIvE,GAAI,EACF,OAAO,EAKT,GAAI,IAAwB,KAC1B,OAAO,EAMT,GAAI,CAGF,OAFA,EAAe,QAAQ,WAAW,CAClC,EAAsB,iDACf,OACQ,EAKjB,GAAI,CAGF,OAFA,EAAe,QAAQ,QAAQ,CAC/B,EAAsB,mDACf,OACQ,EAKjB,GAAI,CAGF,OAFA,EAAe,QAAQ,SAAS,CAChC,EAAsB,kCACf,OACQ,EAMjB,EAAsB,IAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"detectFormatCommand.d.ts","names":[],"sources":["../../../src/writeContentDeclaration/detectFormatCommand.ts"],"mappings":";;;cAKa,mBAAA,GACX,aAAA,EAAe,cAAA,EACf,kBAAA,GAAqB,MAAA,CAAO,OAAA"}