@intlayer/chokidar 8.1.11 → 8.2.1

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 (104) hide show
  1. package/dist/assets/installSkills/skills/astro.md +1 -1
  2. package/dist/assets/installSkills/skills/cli.md +2 -2
  3. package/dist/cjs/cli.cjs +1 -1
  4. package/dist/cjs/createDictionaryEntryPoint/generateDictionaryListContent.cjs +1 -1
  5. package/dist/cjs/createDictionaryEntryPoint/generateDictionaryListContent.cjs.map +1 -1
  6. package/dist/cjs/createType/createModuleAugmentation.cjs +3 -3
  7. package/dist/cjs/createType/createModuleAugmentation.cjs.map +1 -1
  8. package/dist/cjs/init/utils/configManipulation.cjs +1 -1
  9. package/dist/cjs/init/utils/configManipulation.cjs.map +1 -1
  10. package/dist/cjs/installMCP/installMCP.cjs +2 -0
  11. package/dist/cjs/installMCP/installMCP.cjs.map +1 -0
  12. package/dist/cjs/installSkills/index.cjs +1 -1
  13. package/dist/cjs/installSkills/index.cjs.map +1 -1
  14. package/dist/cjs/loadDictionaries/loadRemoteDictionaries.cjs +1 -1
  15. package/dist/cjs/loadDictionaries/log.cjs +1 -1
  16. package/dist/cjs/loadDictionaries/log.cjs.map +1 -1
  17. package/dist/cjs/prepareIntlayer.cjs +1 -1
  18. package/dist/cjs/utils/getPathHash.cjs +2 -0
  19. package/dist/cjs/utils/getPathHash.cjs.map +1 -0
  20. package/dist/cjs/utils/index.cjs +1 -1
  21. package/dist/cjs/watcher.cjs +1 -1
  22. package/dist/cjs/watcher.cjs.map +1 -1
  23. package/dist/cjs/writeContentDeclaration/transformJSFile.cjs +1 -2
  24. package/dist/cjs/writeContentDeclaration/transformJSFile.cjs.map +1 -1
  25. package/dist/cjs/writeContentDeclaration/transformJSONFile.cjs +1 -1
  26. package/dist/cjs/writeContentDeclaration/transformJSONFile.cjs.map +1 -1
  27. package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs +1 -1
  28. package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs.map +1 -1
  29. package/dist/cjs/writeContentDeclaration/writeJSFile.cjs +1 -1
  30. package/dist/esm/cli.mjs +1 -1
  31. package/dist/esm/createDictionaryEntryPoint/generateDictionaryListContent.mjs +1 -1
  32. package/dist/esm/createDictionaryEntryPoint/generateDictionaryListContent.mjs.map +1 -1
  33. package/dist/esm/createType/createModuleAugmentation.mjs +9 -9
  34. package/dist/esm/createType/createModuleAugmentation.mjs.map +1 -1
  35. package/dist/esm/init/utils/configManipulation.mjs +1 -1
  36. package/dist/esm/init/utils/configManipulation.mjs.map +1 -1
  37. package/dist/esm/installMCP/installMCP.mjs +2 -0
  38. package/dist/esm/installMCP/installMCP.mjs.map +1 -0
  39. package/dist/esm/installSkills/index.mjs +1 -1
  40. package/dist/esm/installSkills/index.mjs.map +1 -1
  41. package/dist/esm/loadDictionaries/loadRemoteDictionaries.mjs +1 -1
  42. package/dist/esm/loadDictionaries/log.mjs +2 -2
  43. package/dist/esm/loadDictionaries/log.mjs.map +1 -1
  44. package/dist/esm/prepareIntlayer.mjs +1 -1
  45. package/dist/esm/utils/getPathHash.mjs +2 -0
  46. package/dist/esm/utils/getPathHash.mjs.map +1 -0
  47. package/dist/esm/utils/index.mjs +1 -1
  48. package/dist/esm/utils/runParallel/pidTree.mjs.map +1 -1
  49. package/dist/esm/utils/runParallel/ps.mjs.map +1 -1
  50. package/dist/esm/utils/runParallel/wmic.mjs.map +1 -1
  51. package/dist/esm/watcher.mjs +1 -1
  52. package/dist/esm/watcher.mjs.map +1 -1
  53. package/dist/esm/writeContentDeclaration/transformJSFile.mjs +1 -2
  54. package/dist/esm/writeContentDeclaration/transformJSFile.mjs.map +1 -1
  55. package/dist/esm/writeContentDeclaration/transformJSONFile.mjs +1 -1
  56. package/dist/esm/writeContentDeclaration/transformJSONFile.mjs.map +1 -1
  57. package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs +1 -1
  58. package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs.map +1 -1
  59. package/dist/esm/writeContentDeclaration/writeJSFile.mjs +1 -1
  60. package/dist/types/build.d.ts +0 -5
  61. package/dist/types/cli.d.ts +8 -5
  62. package/dist/types/createType/createModuleAugmentation.d.ts.map +1 -1
  63. package/dist/types/fetchDistantDictionaries.d.ts +0 -1
  64. package/dist/types/fetchDistantDictionaries.d.ts.map +1 -1
  65. package/dist/types/init/utils/configManipulation.d.ts +0 -12
  66. package/dist/types/init/utils/configManipulation.d.ts.map +1 -1
  67. package/dist/types/installMCP/installMCP.d.ts +11 -0
  68. package/dist/types/installMCP/installMCP.d.ts.map +1 -0
  69. package/dist/types/installSkills/index.d.ts +23 -49
  70. package/dist/types/installSkills/index.d.ts.map +1 -1
  71. package/dist/types/loadDictionaries/log.d.ts.map +1 -1
  72. package/dist/types/utils/getPathHash.d.ts +5 -0
  73. package/dist/types/utils/getPathHash.d.ts.map +1 -0
  74. package/dist/types/utils/index.d.ts +2 -2
  75. package/dist/types/watcher.d.ts.map +1 -1
  76. package/dist/types/writeContentDeclaration/transformJSFile.d.ts +1 -26
  77. package/dist/types/writeContentDeclaration/transformJSFile.d.ts.map +1 -1
  78. package/dist/types/writeContentDeclaration/transformJSONFile.d.ts.map +1 -1
  79. package/dist/types/writeContentDeclaration/writeContentDeclaration.d.ts.map +1 -1
  80. package/package.json +9 -23
  81. package/dist/cjs/index.cjs +0 -1
  82. package/dist/cjs/transformFiles/extractDictionaryKey.cjs +0 -2
  83. package/dist/cjs/transformFiles/extractDictionaryKey.cjs.map +0 -1
  84. package/dist/cjs/transformFiles/index.cjs +0 -1
  85. package/dist/cjs/transformFiles/transformFiles.cjs +0 -2
  86. package/dist/cjs/transformFiles/transformFiles.cjs.map +0 -1
  87. package/dist/cjs/utils/getFileHash.cjs +0 -2
  88. package/dist/cjs/utils/getFileHash.cjs.map +0 -1
  89. package/dist/esm/index.mjs +0 -1
  90. package/dist/esm/transformFiles/extractDictionaryKey.mjs +0 -2
  91. package/dist/esm/transformFiles/extractDictionaryKey.mjs.map +0 -1
  92. package/dist/esm/transformFiles/index.mjs +0 -1
  93. package/dist/esm/transformFiles/transformFiles.mjs +0 -2
  94. package/dist/esm/transformFiles/transformFiles.mjs.map +0 -1
  95. package/dist/esm/utils/getFileHash.mjs +0 -2
  96. package/dist/esm/utils/getFileHash.mjs.map +0 -1
  97. package/dist/types/index.d.ts +0 -57
  98. package/dist/types/transformFiles/extractDictionaryKey.d.ts +0 -5
  99. package/dist/types/transformFiles/extractDictionaryKey.d.ts.map +0 -1
  100. package/dist/types/transformFiles/index.d.ts +0 -3
  101. package/dist/types/transformFiles/transformFiles.d.ts +0 -24
  102. package/dist/types/transformFiles/transformFiles.d.ts.map +0 -1
  103. package/dist/types/utils/getFileHash.d.ts +0 -5
  104. package/dist/types/utils/getFileHash.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"transformJSONFile.cjs","names":["Node","Project","IndentationText","QuoteKind","SyntaxKind"],"sources":["../../../src/writeContentDeclaration/transformJSONFile.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types';\nimport {\n IndentationText,\n Node,\n type ObjectLiteralExpression,\n Project,\n QuoteKind,\n SyntaxKind,\n} from 'ts-morph';\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 * Safely formats a key for use in object literals.\n * Always quotes keys to ensure compatibility with standard JSON files.\n */\nconst stringifyKey = (objectKey: string): string => {\n return JSON.stringify(objectKey);\n};\n\n/**\n * Robustly finds a property in an ObjectLiteralExpression.\n * Handles cases where the property name in the source file is quoted (\"key\") or unquoted (key).\n */\nconst getMatchingProperty = (node: ObjectLiteralExpression, key: string) => {\n return node.getProperties().find((prop) => {\n // We only care about property assignments (key: value)\n if (Node.isPropertyAssignment(prop)) {\n const propName = prop.getName();\n // Check for strict match (unquoted identifier) or quoted match (string literal)\n // We check both double and single quotes to handle JSONC/JSON5 variations.\n return (\n propName === key || propName === `\"${key}\"` || propName === `'${key}'`\n );\n }\n return false;\n });\n};\n\n/**\n * Recursively updates the AST object literal with new data.\n */\nconst updateObjectLiteral = (\n node: ObjectLiteralExpression,\n data: Record<string, any>\n) => {\n for (const [key, val] of Object.entries(data)) {\n // Skip undefined values.\n if (val === undefined) continue;\n\n const stringifiedValue = JSON.stringify(val, null, 2);\n\n // Safety check: ensure we have a string unless we are recursing into an object\n if (stringifiedValue === undefined && !isPlainObject(val)) continue;\n\n // Use robust lookup instead of node.getProperty(key)\n const existingProp = getMatchingProperty(node, key);\n\n if (isPlainObject(val)) {\n if (existingProp && Node.isPropertyAssignment(existingProp)) {\n const initializer = existingProp.getInitializer();\n\n if (Node.isObjectLiteralExpression(initializer)) {\n // Recurse into nested object\n updateObjectLiteral(initializer, val);\n } else {\n // Property exists but is not an object (e.g. was null or number), overwrite with new object\n existingProp.setInitializer(stringifiedValue!);\n }\n } else if (existingProp) {\n // Property exists but isn't a simple assignment, overwrite it safely\n existingProp.replaceWithText(\n `${stringifyKey(key)}: ${stringifiedValue}`\n );\n } else {\n // Property doesn't exist, add it\n node.addPropertyAssignment({\n name: stringifyKey(key),\n initializer: stringifiedValue!,\n });\n }\n } else {\n // Handling Primitives / Arrays\n if (existingProp && Node.isPropertyAssignment(existingProp)) {\n existingProp.setInitializer(stringifiedValue!);\n } else if (existingProp) {\n existingProp.replaceWithText(\n `${stringifyKey(key)}: ${stringifiedValue}`\n );\n } else {\n node.addPropertyAssignment({\n name: stringifyKey(key),\n initializer: stringifiedValue!,\n });\n }\n }\n }\n};\n\nexport const transformJSONFile = (\n fileContent: string,\n dictionary: Dictionary\n): string => {\n // Initialize a virtual project\n const project = new Project({\n useInMemoryFileSystem: true,\n manipulationSettings: {\n indentationText: IndentationText.TwoSpaces,\n quoteKind: QuoteKind.Double,\n },\n });\n\n // Wrap content in a variable declaration so it acts as a valid SourceFile\n const dummyFileName = 'temp.ts';\n const wrappedContent = `const _config = ${fileContent.trim() || '{}'}`;\n const sourceFile = project.createSourceFile(dummyFileName, wrappedContent);\n\n // Locate the object literal\n const varDecl = sourceFile.getVariableDeclaration('_config');\n const objectLiteral = varDecl?.getInitializerIfKind(\n SyntaxKind.ObjectLiteralExpression\n );\n\n if (!objectLiteral) {\n // Fallback if parsing failed\n return JSON.stringify(dictionary, null, 2);\n }\n\n // Update the AST\n updateObjectLiteral(objectLiteral, dictionary);\n\n // Format text to ensure new properties are aligned\n sourceFile.formatText();\n\n // Extract the object literal text.\n return objectLiteral.getText();\n};\n"],"mappings":"0IAaA,MAAM,EAAiB,GACd,OAAO,GAAU,YAAY,GAAkB,CAAC,MAAM,QAAQ,EAAM,CAOvE,EAAgB,GACb,KAAK,UAAU,EAAU,CAO5B,GAAuB,EAA+B,IACnD,EAAK,eAAe,CAAC,KAAM,GAAS,CAEzC,GAAIA,EAAAA,KAAK,qBAAqB,EAAK,CAAE,CACnC,IAAM,EAAW,EAAK,SAAS,CAG/B,OACE,IAAa,GAAO,IAAa,IAAI,EAAI,IAAM,IAAa,IAAI,EAAI,GAGxE,MAAO,IACP,CAME,GACJ,EACA,IACG,CACH,IAAK,GAAM,CAAC,EAAK,KAAQ,OAAO,QAAQ,EAAK,CAAE,CAE7C,GAAI,IAAQ,IAAA,GAAW,SAEvB,IAAM,EAAmB,KAAK,UAAU,EAAK,KAAM,EAAE,CAGrD,GAAI,IAAqB,IAAA,IAAa,CAAC,EAAc,EAAI,CAAE,SAG3D,IAAM,EAAe,EAAoB,EAAM,EAAI,CAEnD,GAAI,EAAc,EAAI,CACpB,GAAI,GAAgBA,EAAAA,KAAK,qBAAqB,EAAa,CAAE,CAC3D,IAAM,EAAc,EAAa,gBAAgB,CAE7CA,EAAAA,KAAK,0BAA0B,EAAY,CAE7C,EAAoB,EAAa,EAAI,CAGrC,EAAa,eAAe,EAAkB,MAEvC,EAET,EAAa,gBACX,GAAG,EAAa,EAAI,CAAC,IAAI,IAC1B,CAGD,EAAK,sBAAsB,CACzB,KAAM,EAAa,EAAI,CACvB,YAAa,EACd,CAAC,MAIA,GAAgBA,EAAAA,KAAK,qBAAqB,EAAa,CACzD,EAAa,eAAe,EAAkB,CACrC,EACT,EAAa,gBACX,GAAG,EAAa,EAAI,CAAC,IAAI,IAC1B,CAED,EAAK,sBAAsB,CACzB,KAAM,EAAa,EAAI,CACvB,YAAa,EACd,CAAC,GAMG,GACX,EACA,IACW,CAEX,IAAM,EAAU,IAAIC,EAAAA,QAAQ,CAC1B,sBAAuB,GACvB,qBAAsB,CACpB,gBAAiBC,EAAAA,gBAAgB,UACjC,UAAWC,EAAAA,UAAU,OACtB,CACF,CAAC,CAII,EAAiB,mBAAmB,EAAY,MAAM,EAAI,OAC1D,EAAa,EAAQ,iBAAiB,UAAe,EAAe,CAIpE,EADU,EAAW,uBAAuB,UAAU,EAC7B,qBAC7BC,EAAAA,WAAW,wBACZ,CAcD,OAZK,GAML,EAAoB,EAAe,EAAW,CAG9C,EAAW,YAAY,CAGhB,EAAc,SAAS,EAVrB,KAAK,UAAU,EAAY,KAAM,EAAE"}
1
+ {"version":3,"file":"transformJSONFile.cjs","names":[],"sources":["../../../src/writeContentDeclaration/transformJSONFile.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types';\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 * 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) continue;\n\n const existingProp = getMatchingProperty(node, key);\n\n if (isPlainObject(val)) {\n if (existingProp && n.ObjectExpression.check(existingProp.value)) {\n updateObjectLiteral(existingProp.value, val);\n } else {\n const valueNode = buildASTNode(val);\n if (existingProp) {\n existingProp.value = valueNode;\n } else {\n node.properties.push(\n b.property('init', b.stringLiteral(key), valueNode)\n );\n }\n }\n } else {\n const valueNode = buildASTNode(val);\n if (existingProp) {\n existingProp.value = valueNode;\n } else {\n node.properties.push(\n b.property('init', b.stringLiteral(key), valueNode)\n );\n }\n }\n }\n};\n\nexport const transformJSONFile = (\n fileContent: string,\n dictionary: Dictionary\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(dictionary, null, 2);\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 (!objectLiteral) {\n // Fallback if the AST structure isn't what we expect\n return JSON.stringify(dictionary, null, 2);\n }\n\n // Update the AST in place\n updateObjectLiteral(objectLiteral, dictionary);\n\n // Print only the target object literal node\n return recast.print(objectLiteral, {\n tabWidth: 2,\n quote: 'double',\n trailingComma: false,\n }).code;\n};\n"],"mappings":"+JAGA,MAAM,EAAI,EAAO,MAAM,SACjB,EAAI,EAAO,MAAM,WAKjB,EAAiB,GACd,OAAO,GAAU,YAAY,GAAkB,CAAC,MAAM,QAAQ,EAAM,CAOvE,GAAuB,EAAW,IAC/B,EAAK,WAAW,KAAM,GAC3B,IAAI,EAAE,SAAS,MAAM,EAAK,EAAI,EAAE,eAAe,MAAM,EAAK,IACpD,EAAE,WAAW,MAAM,EAAK,IAAI,EAAI,EAAK,IAAI,OAAS,GAClD,EAAE,cAAc,MAAM,EAAK,IAAI,EAAI,EAAK,IAAI,QAAU,GAEtD,EAAE,QAAQ,MAAM,EAAK,IAAI,EAAI,EAAK,IAAI,QAAU,IAGtD,CAOE,EAAgB,GAChB,IAAQ,KAAa,EAAE,QAAQ,KAAK,CAGtC,OAAO,GAAQ,UACf,OAAO,GAAQ,UACf,OAAO,GAAQ,UAER,EAAE,QAAQ,EAAI,CAGnB,MAAM,QAAQ,EAAI,CACb,EAAE,gBAAgB,EAAI,IAAK,GAAS,EAAa,EAAK,CAAC,CAAC,CAG7D,EAAc,EAAI,CACb,EAAE,iBACP,OAAO,QAAQ,EAAI,CAChB,QAAQ,EAAG,KAAO,IAAM,IAAA,GAAU,CAClC,KAAK,CAAC,EAAG,KACR,EAAE,SAAS,OAAQ,EAAE,cAAc,EAAE,CAAE,EAAa,EAAE,CAAC,CACxD,CACJ,CAGI,EAAE,QAAQ,KAAK,CAMlB,GAAuB,EAAW,IAA8B,CACpE,IAAK,GAAM,CAAC,EAAK,KAAQ,OAAO,QAAQ,EAAK,CAAE,CAC7C,GAAI,IAAQ,IAAA,GAAW,SAEvB,IAAM,EAAe,EAAoB,EAAM,EAAI,CAEnD,GAAI,EAAc,EAAI,CACpB,GAAI,GAAgB,EAAE,iBAAiB,MAAM,EAAa,MAAM,CAC9D,EAAoB,EAAa,MAAO,EAAI,KACvC,CACL,IAAM,EAAY,EAAa,EAAI,CAC/B,EACF,EAAa,MAAQ,EAErB,EAAK,WAAW,KACd,EAAE,SAAS,OAAQ,EAAE,cAAc,EAAI,CAAE,EAAU,CACpD,KAGA,CACL,IAAM,EAAY,EAAa,EAAI,CAC/B,EACF,EAAa,MAAQ,EAErB,EAAK,WAAW,KACd,EAAE,SAAS,OAAQ,EAAE,cAAc,EAAI,CAAE,EAAU,CACpD,IAMI,GACX,EACA,IACW,CAEX,IAAM,EAAiB,mBAAmB,EAAY,MAAM,EAAI,KAAK,GAEjE,EACJ,GAAI,CACF,EAAM,EAAO,MAAM,EAAe,MAC5B,CAEN,OAAO,KAAK,UAAU,EAAY,KAAM,EAAE,CAI5C,IAAM,EAAc,EAAI,QAAQ,KAAK,GACjC,EAoBJ,OAjBE,EAAE,oBAAoB,MAAM,EAAY,EACxC,EAAY,aAAa,OAAS,GAClC,EAAE,mBAAmB,MAAM,EAAY,aAAa,GAAG,EACvD,EAAE,iBAAiB,MAAM,EAAY,aAAa,GAAG,KAAK,GAE1D,EAAgB,EAAY,aAAa,GAAG,MAGzC,GAML,EAAoB,EAAe,EAAW,CAGvC,EAAO,MAAM,EAAe,CACjC,SAAU,EACV,MAAO,SACP,cAAe,GAChB,CAAC,CAAC,MAXM,KAAK,UAAU,EAAY,KAAM,EAAE"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`../utils/getFormatFromExtension.cjs`),t=require(`./processContentDeclarationContent.cjs`),n=require(`./transformJSONFile.cjs`),r=require(`./writeJSFile.cjs`);let i=require(`@intlayer/unmerged-dictionaries-entry`),a=require(`node:fs/promises`),o=require(`node:path`),s=require(`@intlayer/core/plugins`),c=require(`node:fs`),l=require(`node:util`);const u=async(n,r,i)=>{let a=await t.processContentDeclarationContent(n),c=a.content;n.locale?c=(0,s.getPerLocaleDictionary)(a,n.locale).content:i&&(c=(0,s.getFilteredLocalesDictionary)(a,i).content);let l={...n,content:c};for await(let e of r.plugins??[])if(e.formatOutput){let t=await e.formatOutput?.({dictionary:l,configuration:r});t&&(l=t)}if(!(l.content&&l.key))return l;let u={key:n.key,id:n.id,title:n.title,description:n.description,tags:n.tags,locale:n.locale,fill:n.fill,filled:n.filled,priority:n.priority,importMode:n.importMode,version:n.version,content:c};return e.getFormatFromExtension(n.filePath?(0,o.extname)(n.filePath):`.json`)===`json`&&l.content&&l.key&&(u={$schema:`https://intlayer.org/schema.json`,...u}),u},d={newDictionariesPath:`intlayer-dictionaries`},f=async(e,t,n)=>{let{content:r}=t,{baseDir:a}=r,{newDictionariesPath:s,localeList:c}={...d,...n},f=(0,o.join)(a,s),m=(0,i.getUnmergedDictionaries)(t)[e.key]?.find(t=>t.localId===e.localId),h=await u(e,t,c);if(m?.filePath){let n=(0,l.isDeepStrictEqual)(m,e),r=(0,o.resolve)(t.content.baseDir,m.filePath);return n?{status:`up-to-date`,path:r}:(await p(r,h,t),{status:`updated`,path:r})}if(e.filePath){let n=(0,o.resolve)(t.content.baseDir,e.filePath);return await p(n,h,t),{status:`created`,path:n}}let g=(0,o.join)(f,`${e.key}.content.json`);return await p(g,h,t),{status:`imported`,path:g}},p=async(e,t,i)=>{await(0,a.mkdir)((0,o.dirname)(e),{recursive:!0});let s=(0,o.extname)(e);if(!i.content.fileExtensions.map(e=>(0,o.extname)(e)).includes(s))throw Error(`Invalid file extension: ${s}, file: ${e}`);if(s===`.json`){let n=JSON.stringify(t,null,2),r=i.system?.tempDir;r&&await(0,a.mkdir)(r,{recursive:!0});let s=`${(0,o.basename)(e)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,c=r?(0,o.join)(r,s):`${e}.${s}`;try{await(0,a.writeFile)(c,`${n}\n`),await(0,a.rename)(c,e)}catch(e){try{await(0,a.rm)(c,{force:!0})}catch{}throw e}return}if([`.jsonc`,`.json5`].includes(s)){let r=`{}`;if((0,c.existsSync)(e))try{r=await(0,a.readFile)(e,`utf-8`)}catch{}let s=n.transformJSONFile(r,t),l=i.system?.tempDir;l&&await(0,a.mkdir)(l,{recursive:!0});let u=`${(0,o.basename)(e)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,d=l?(0,o.join)(l,u):`${e}.${u}`;try{await(0,a.writeFile)(d,s,`utf-8`),await(0,a.rename)(d,e)}catch(e){try{await(0,a.rm)(d,{force:!0})}catch{}throw e}return}await r.writeJSFile(e,t,i);try{await(0,a.rm)((0,o.join)(i.system.cacheDir,`intlayer-prepared.lock`),{recursive:!0})}catch{}};exports.writeContentDeclaration=f;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`../utils/getFormatFromExtension.cjs`),t=require(`../detectFormatCommand.cjs`),n=require(`./processContentDeclarationContent.cjs`),r=require(`./transformJSONFile.cjs`),i=require(`./writeJSFile.cjs`);let a=require(`@intlayer/unmerged-dictionaries-entry`),o=require(`node:fs/promises`),s=require(`node:path`),c=require(`@intlayer/core/plugins`),l=require(`node:fs`),u=require(`node:child_process`),d=require(`node:util`);const f=async(t,r,i)=>{let a=await n.processContentDeclarationContent(t),o=a.content;t.locale?o=(0,c.getPerLocaleDictionary)(a,t.locale).content:i&&(o=(0,c.getFilteredLocalesDictionary)(a,i).content);let l={...t,content:o};for await(let e of r.plugins??[])if(e.formatOutput){let t=await e.formatOutput?.({dictionary:l,configuration:r});t&&(l=t)}if(!(l.content&&l.key))return l;let u={key:t.key,id:t.id,title:t.title,description:t.description,tags:t.tags,locale:t.locale,fill:t.fill,filled:t.filled,priority:t.priority,importMode:t.importMode,version:t.version,content:o};return e.getFormatFromExtension(t.filePath?(0,s.extname)(t.filePath):`.json`)===`json`&&l.content&&l.key&&(u={$schema:`https://intlayer.org/schema.json`,...u}),u},p={newDictionariesPath:`intlayer-dictionaries`},m=async(e,t,n)=>{let{content:r}=t,{baseDir:i}=r,{newDictionariesPath:o,localeList:c}={...p,...n},l=(0,s.join)(i,o),u=(0,a.getUnmergedDictionaries)(t)[e.key]?.find(t=>t.localId===e.localId),m=await f(e,t,c);if(u?.filePath){let n=(0,d.isDeepStrictEqual)(u,e),r=(0,s.resolve)(t.content.baseDir,u.filePath);return n?{status:`up-to-date`,path:r}:(await h(r,m,t),{status:`updated`,path:r})}if(e.filePath){let n=(0,s.resolve)(t.content.baseDir,e.filePath);return await h(n,m,t),{status:`created`,path:n}}let g=(0,s.join)(l,`${e.key}.content.json`);return await h(g,m,t),{status:`imported`,path:g}},h=async(e,n,a)=>{await(0,o.mkdir)((0,s.dirname)(e),{recursive:!0});let c=(0,s.extname)(e);if(!a.content.fileExtensions.map(e=>(0,s.extname)(e)).includes(c))throw Error(`Invalid file extension: ${c}, file: ${e}`);if(c===`.json`){let r=JSON.stringify(n,null,2),i=a.system?.tempDir;i&&await(0,o.mkdir)(i,{recursive:!0});let c=`${(0,s.basename)(e)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,l=i?(0,s.join)(i,c):`${e}.${c}`;try{await(0,o.writeFile)(l,`${r}\n`),await(0,o.rename)(l,e)}catch(e){try{await(0,o.rm)(l,{force:!0})}catch{}throw e}let d=t.detectFormatCommand(a);if(d)try{(0,u.execSync)(d.replace(`{{file}}`,e),{stdio:`inherit`,cwd:a.content.baseDir})}catch(e){console.error(e)}return}if([`.jsonc`,`.json5`].includes(c)){let i=`{}`;if((0,l.existsSync)(e))try{i=await(0,o.readFile)(e,`utf-8`)}catch{}let c=r.transformJSONFile(i,n),d=a.system?.tempDir;d&&await(0,o.mkdir)(d,{recursive:!0});let f=`${(0,s.basename)(e)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,p=d?(0,s.join)(d,f):`${e}.${f}`;try{await(0,o.writeFile)(p,c,`utf-8`),await(0,o.rename)(p,e)}catch(e){try{await(0,o.rm)(p,{force:!0})}catch{}throw e}let m=t.detectFormatCommand(a);if(m)try{(0,u.execSync)(m.replace(`{{file}}`,e),{stdio:`inherit`,cwd:a.content.baseDir})}catch(e){console.error(e)}return}await i.writeJSFile(e,n,a);try{await(0,o.rm)((0,s.join)(a.system.cacheDir,`intlayer-prepared.lock`),{recursive:!0})}catch{}};exports.writeContentDeclaration=m;
2
2
  //# sourceMappingURL=writeContentDeclaration.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"writeContentDeclaration.cjs","names":["processContentDeclarationContent","getFormatFromExtension","transformJSONFile","writeJSFile"],"sources":["../../../src/writeContentDeclaration/writeContentDeclaration.ts"],"sourcesContent":["import { 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 {\n getFilteredLocalesDictionary,\n getPerLocaleDictionary,\n} from '@intlayer/core/plugins';\nimport type {\n Dictionary,\n IntlayerConfig,\n Locale,\n LocalesValues,\n} from '@intlayer/types';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport type { DictionaryStatus } from './dictionaryStatus';\nimport { processContentDeclarationContent } from './processContentDeclarationContent';\nimport { transformJSONFile } from './transformJSONFile';\nimport { writeJSFile } from './writeJSFile';\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 let result: Dictionary = {\n key: dictionary.key,\n id: dictionary.id,\n title: dictionary.title,\n description: dictionary.description,\n tags: dictionary.tags,\n locale: dictionary.locale,\n fill: dictionary.fill,\n filled: dictionary.filled,\n priority: dictionary.priority,\n importMode: dictionary.importMode,\n version: dictionary.version,\n content,\n };\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 { content } = configuration;\n const { baseDir } = content;\n const { newDictionariesPath, localeList } = {\n ...defaultOptions,\n ...options,\n };\n\n const newDictionaryLocationPath = join(baseDir, newDictionariesPath);\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\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.content.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 );\n\n return { status: 'updated', path: filePath };\n }\n\n if (dictionary.filePath) {\n const filePath = resolve(\n configuration.content.baseDir,\n dictionary.filePath\n );\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration\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 );\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): 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 const acceptedExtensions = configuration.content.fileExtensions.map(\n (extension) => extname(extension)\n );\n\n if (!acceptedExtensions.includes(extension)) {\n throw new Error(\n `Invalid file extension: ${extension}, file: ${absoluteFilePath}`\n );\n }\n\n if (extension === '.json') {\n const jsonDictionary = JSON.stringify(dictionary, null, 2);\n\n // Write the file\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, `${jsonDictionary}\\n`); // Add a new line at the end of the file to avoid formatting issues with VSCode\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 return;\n }\n\n // Handle JSONC, and JSON5 via the AST transformer\n if (['.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(fileContent, dictionary);\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 return;\n }\n\n await writeJSFile(absoluteFilePath, dictionary, configuration);\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":"2dAwBA,MAAM,EAA2B,MAC/B,EACA,EACA,IACG,CAIH,IAAM,EACJ,MAAMA,EAAAA,iCAAiC,EAAW,CAEhD,EAAU,EAAoB,QAM9B,EAAW,OACb,GAAA,EAAA,EAAA,wBACE,EACA,EAAW,OACZ,CAAC,QACO,IACT,GAAA,EAAA,EAA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MAC7B,EAGR,MAAM,EAGR,OAIF,GAAI,CAAC,SAAU,SAAS,CAAC,SAAS,EAAU,CAAE,CAC5C,IAAI,EAAc,KAElB,IAAA,EAAA,EAAA,YAAe,EAAiB,CAC9B,GAAI,CACF,EAAc,MAAA,EAAA,EAAA,UAAe,EAAkB,QAAQ,MACjD,EAKV,IAAM,EAAqBC,EAAAA,kBAAkB,EAAa,EAAW,CAG/D,EAAU,EAAc,QAAQ,QAClC,GACF,MAAA,EAAA,EAAA,OAAY,EAAS,CAAE,UAAW,GAAM,CAAC,CAG3C,IAAM,EAAe,IAAA,EAAA,EAAA,UAAY,EAAiB,CAAC,GAAG,KAAK,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE,CAAC,MAClG,EAAW,GAAA,EAAA,EAAA,MACR,EAAS,EAAa,CAC3B,GAAG,EAAiB,GAAG,IAC3B,GAAI,CACF,MAAA,EAAA,EAAA,WAAgB,EAAU,EAAoB,QAAQ,CACtD,MAAA,EAAA,EAAA,QAAa,EAAU,EAAiB,OACjC,EAAO,CACd,GAAI,CACF,MAAA,EAAA,EAAA,IAAS,EAAU,CAAE,MAAO,GAAM,CAAC,MAC7B,EAGR,MAAM,EAER,OAGF,MAAMC,EAAAA,YAAY,EAAkB,EAAY,EAAc,CAI9D,GAAI,CAKF,MAAA,EAAA,EAAA,KAAA,EAAA,EAAA,MAHE,EAAc,OAAO,SACrB,yBACD,CACsB,CAAE,UAAW,GAAM,CAAC,MACrC"}
1
+ {"version":3,"file":"writeContentDeclaration.cjs","names":["processContentDeclarationContent","getFormatFromExtension","detectFormatCommand","transformJSONFile","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 {\n getFilteredLocalesDictionary,\n getPerLocaleDictionary,\n} from '@intlayer/core/plugins';\nimport type {\n Dictionary,\n IntlayerConfig,\n Locale,\n LocalesValues,\n} from '@intlayer/types';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport type { DictionaryStatus } from './dictionaryStatus';\nimport { processContentDeclarationContent } from './processContentDeclarationContent';\nimport { transformJSONFile } from './transformJSONFile';\nimport { writeJSFile } from './writeJSFile';\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 let result: Dictionary = {\n key: dictionary.key,\n id: dictionary.id,\n title: dictionary.title,\n description: dictionary.description,\n tags: dictionary.tags,\n locale: dictionary.locale,\n fill: dictionary.fill,\n filled: dictionary.filled,\n priority: dictionary.priority,\n importMode: dictionary.importMode,\n version: dictionary.version,\n content,\n };\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 { content } = configuration;\n const { baseDir } = content;\n const { newDictionariesPath, localeList } = {\n ...defaultOptions,\n ...options,\n };\n\n const newDictionaryLocationPath = join(baseDir, newDictionariesPath);\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\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.content.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 );\n\n return { status: 'updated', path: filePath };\n }\n\n if (dictionary.filePath) {\n const filePath = resolve(\n configuration.content.baseDir,\n dictionary.filePath\n );\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration\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 );\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): 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 const acceptedExtensions = configuration.content.fileExtensions.map(\n (extension) => extname(extension)\n );\n\n if (!acceptedExtensions.includes(extension)) {\n throw new Error(\n `Invalid file extension: ${extension}, file: ${absoluteFilePath}`\n );\n }\n\n if (extension === '.json') {\n const jsonDictionary = JSON.stringify(dictionary, null, 2);\n\n // Write the file\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, `${jsonDictionary}\\n`); // Add a new line at the end of the file to avoid formatting issues with VSCode\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.content.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n\n return;\n }\n\n // Handle JSONC, and JSON5 via the AST transformer\n if (['.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(fileContent, dictionary);\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.content.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n\n return;\n }\n\n await writeJSFile(absoluteFilePath, dictionary, configuration);\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":"miBA0BA,MAAM,EAA2B,MAC/B,EACA,EACA,IACG,CAIH,IAAM,EACJ,MAAMA,EAAAA,iCAAiC,EAAW,CAEhD,EAAU,EAAoB,QAM9B,EAAW,OACb,GAAA,EAAA,EAAA,wBACE,EACA,EAAW,OACZ,CAAC,QACO,IACT,GAAA,EAAA,EAAA,8BACE,EACA,EACD,CAAC,SAGJ,IAAI,EAA0B,CAC5B,GAAG,EACH,UACD,CAMD,UAAW,IAAM,KAAU,EAAc,SAAW,EAAE,CACpD,GAAI,EAAO,aAAc,CACvB,IAAM,EAAkB,MAAM,EAAO,eAAe,CAClD,WAAY,EACZ,gBACD,CAAC,CAEE,IACF,EAAqB,GAQ3B,GAAI,EAFF,EAAmB,SAAW,EAAmB,KAE1B,OAAO,EAEhC,IAAI,EAAqB,CACvB,IAAK,EAAW,I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AAA,EAAA,EAAA,YAAe,EAAiB,CAC9B,GAAI,CACF,EAAc,MAAA,EAAA,EAAA,UAAe,EAAkB,QAAQ,MACjD,EAKV,IAAM,EAAqBC,EAAAA,kBAAkB,EAAa,EAAW,CAG/D,EAAU,EAAc,QAAQ,QAClC,GACF,MAAA,EAAA,EAAA,OAAY,EAAS,CAAE,UAAW,GAAM,CAAC,CAG3C,IAAM,EAAe,IAAA,EAAA,EAAA,UAAY,EAAiB,CAAC,GAAG,KAAK,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE,CAAC,MAClG,EAAW,GAAA,EAAA,EAAA,MACR,EAAS,EAAa,CAC3B,GAAG,EAAiB,GAAG,IAC3B,GAAI,CACF,MAAA,EAAA,EAAA,WAAgB,EAAU,EAAoB,QAAQ,CACtD,MAAA,EAAA,EAAA,QAAa,EAAU,EAAiB,OACjC,EAAO,CACd,GAAI,CACF,MAAA,EAAA,EAAA,IAAS,EAAU,CAAE,MAAO,GAAM,CAAC,MAC7B,EAGR,MAAM,EAGR,IAAM,EAAgBD,EAAAA,oBAAoB,EAAc,CAExD,GAAI,EACF,GAAI,EACF,EAAA,EAAA,UAAS,EAAc,QAAQ,WAAY,EAAiB,CAAE,CAC5D,MAAO,UACP,IAAK,EAAc,QAAQ,QAC5B,CAAC,OACK,EAAO,CACd,QAAQ,MAAM,EAAM,CAIxB,OAGF,MAAME,EAAAA,YAAY,EAAkB,EAAY,EAAc,CAI9D,GAAI,CAKF,MAAA,EAAA,EAAA,KAAA,EAAA,EAAA,MAHE,EAAc,OAAO,SACrB,yBACD,CACsB,CAAE,UAAW,GAAM,CAAC,MACrC"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`./transformJSFile.cjs`),t=require(`../utils/getFormatFromExtension.cjs`),n=require(`../detectFormatCommand.cjs`),r=require(`../getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.cjs`);let i=require(`node:fs/promises`),a=require(`node:path`),o=require(`@intlayer/config/logger`),s=require(`node:fs`),c=require(`node:child_process`);const l=async(l,u,d)=>{let f={...d.dictionary,...u},p=(0,o.getAppLogger)(d);if(!(0,s.existsSync)(l)){let e=t.getFormatFromExtension((0,a.extname)(l));p(`File does not exist, creating it`,{isVerbose:!0});let n=await r.getContentDeclarationFileTemplate(f.key,e,Object.fromEntries(Object.entries({id:f.id,locale:f.locale,filled:f.filled,fill:f.fill,description:f.description,title:f.title,tags:f.tags,version:f.version,priority:f.priority,importMode:f.importMode}).filter(([,e])=>e!==void 0))),o=d.system?.tempDir;o&&await(0,i.mkdir)(o,{recursive:!0});let s=`${(0,a.basename)(l)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,c=o?(0,a.join)(o,s):`${l}.${s}`;try{await(0,i.writeFile)(c,n,`utf-8`),await(0,i.rename)(c,l)}catch(e){try{await(0,i.rm)(c,{force:!0})}catch{}throw e}}let m=await(0,i.readFile)(l,`utf-8`);if(m===``){let e=t.getFormatFromExtension((0,a.extname)(l));m=await r.getContentDeclarationFileTemplate(f.key,e)}let h=await e.transformJSFile(m,u),g=d.system?.tempDir;g&&await(0,i.mkdir)(g,{recursive:!0});let _=`${(0,a.basename)(l)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,v=g?(0,a.join)(g,_):`${l}.${_}`;try{await(0,i.writeFile)(v,h,`utf-8`),await(0,i.rename)(v,l),(0,o.logger)(`Successfully updated ${l}`,{level:`info`,isVerbose:!0})}catch(e){try{await(0,i.rm)(v,{force:!0})}catch{}let t=e;throw(0,o.logger)(`Failed to write updated file: ${l}`,{level:`error`}),Error(`Failed to write updated file ${l}: ${t.message}`)}let y=n.detectFormatCommand(d);if(y)try{(0,c.execSync)(y.replace(`{{file}}`,l),{stdio:`inherit`,cwd:d.content.baseDir})}catch(e){console.error(e)}};exports.writeJSFile=l;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`../utils/getFormatFromExtension.cjs`),t=require(`./transformJSFile.cjs`),n=require(`../detectFormatCommand.cjs`),r=require(`../getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.cjs`);let i=require(`node:fs/promises`),a=require(`node:path`),o=require(`@intlayer/config/logger`),s=require(`node:fs`),c=require(`node:child_process`);const l=async(l,u,d)=>{let f={...d.dictionary,...u},p=(0,o.getAppLogger)(d);if(!(0,s.existsSync)(l)){let t=e.getFormatFromExtension((0,a.extname)(l));p(`File does not exist, creating it`,{isVerbose:!0});let n=await r.getContentDeclarationFileTemplate(f.key,t,Object.fromEntries(Object.entries({id:f.id,locale:f.locale,filled:f.filled,fill:f.fill,description:f.description,title:f.title,tags:f.tags,version:f.version,priority:f.priority,importMode:f.importMode}).filter(([,e])=>e!==void 0))),o=d.system?.tempDir;o&&await(0,i.mkdir)(o,{recursive:!0});let s=`${(0,a.basename)(l)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,c=o?(0,a.join)(o,s):`${l}.${s}`;try{await(0,i.writeFile)(c,n,`utf-8`),await(0,i.rename)(c,l)}catch(e){try{await(0,i.rm)(c,{force:!0})}catch{}throw e}}let m=await(0,i.readFile)(l,`utf-8`);if(m===``){let t=e.getFormatFromExtension((0,a.extname)(l));m=await r.getContentDeclarationFileTemplate(f.key,t)}let h=await t.transformJSFile(m,u),g=d.system?.tempDir;g&&await(0,i.mkdir)(g,{recursive:!0});let _=`${(0,a.basename)(l)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,v=g?(0,a.join)(g,_):`${l}.${_}`;try{await(0,i.writeFile)(v,h,`utf-8`),await(0,i.rename)(v,l),(0,o.logger)(`Successfully updated ${l}`,{level:`info`,isVerbose:!0})}catch(e){try{await(0,i.rm)(v,{force:!0})}catch{}let t=e;throw(0,o.logger)(`Failed to write updated file: ${l}`,{level:`error`}),Error(`Failed to write updated file ${l}: ${t.message}`)}let y=n.detectFormatCommand(d);if(y)try{(0,c.execSync)(y.replace(`{{file}}`,l),{stdio:`inherit`,cwd:d.content.baseDir})}catch(e){console.error(e)}};exports.writeJSFile=l;
2
2
  //# sourceMappingURL=writeJSFile.cjs.map
package/dist/esm/cli.mjs CHANGED
@@ -1 +1 @@
1
- import{listDictionaries as e,listDictionariesWithStats as t}from"./listDictionariesPath.mjs";import{detectFormatCommand as n}from"./detectFormatCommand.mjs";import{getContentDeclarationFileTemplate as r}from"./getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.mjs";import{initIntlayer as i}from"./init/index.mjs";import{SKILLS as a,SKILLS_METADATA as o,installSkills as s}from"./installSkills/index.mjs";import{listGitFiles as c,listGitLines as l}from"./listGitFiles.mjs";import{listProjects as u}from"./listProjects.mjs";import{extractDictionaryKey as d}from"./transformFiles/extractDictionaryKey.mjs";import{ATTRIBUTES_TO_EXTRACT as f,extractIntlayer as p,shouldExtract as m,transformFiles as h}from"./transformFiles/transformFiles.mjs";export{f as ATTRIBUTES_TO_EXTRACT,a as SKILLS,o as SKILLS_METADATA,n as detectFormatCommand,d as extractDictionaryKey,p as extractIntlayer,r as getContentDeclarationFileTemplate,i as initIntlayer,s as installSkills,e as listDictionaries,t as listDictionariesWithStats,c as listGitFiles,l as listGitLines,u as listProjects,m as shouldExtract,h as transformFiles};
1
+ import{listDictionaries as e,listDictionariesWithStats as t}from"./listDictionariesPath.mjs";import{detectExportedComponentName as n}from"./writeContentDeclaration/detectExportedComponentName.mjs";import{transformJSFile as r}from"./writeContentDeclaration/transformJSFile.mjs";import{detectFormatCommand as i}from"./detectFormatCommand.mjs";import{getContentDeclarationFileTemplate as a}from"./getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.mjs";import{writeJSFile as o}from"./writeContentDeclaration/writeJSFile.mjs";import{writeContentDeclaration as s}from"./writeContentDeclaration/writeContentDeclaration.mjs";import{initIntlayer as c}from"./init/index.mjs";import{PLATFORMS as l,PLATFORMS_METADATA as u,SKILLS as d,SKILLS_METADATA as f,getInitialSkills as p,installSkills as m}from"./installSkills/index.mjs";import{installMCP as h}from"./installMCP/installMCP.mjs";import{listGitFiles as g,listGitLines as _}from"./listGitFiles.mjs";import{listProjects as v}from"./listProjects.mjs";export{l as PLATFORMS,u as PLATFORMS_METADATA,d as SKILLS,f as SKILLS_METADATA,n as detectExportedComponentName,i as detectFormatCommand,a as getContentDeclarationFileTemplate,p as getInitialSkills,c as initIntlayer,h as installMCP,m as installSkills,e as listDictionaries,t as listDictionariesWithStats,g as listGitFiles,_ as listGitLines,v as listProjects,r as transformJSFile,s as writeContentDeclaration,o as writeJSFile};
@@ -1,4 +1,4 @@
1
- import{getFileHash as e}from"../utils/getFileHash.mjs";import{getConfiguration as t}from"@intlayer/config/node";import{basename as n,extname as r,relative as i}from"node:path";import{normalizePath as a}from"@intlayer/config/utils";const o=(o,s,c,l=`esm`,u=t())=>{let{mainDir:d}=u.system,f=``,p=o.map(t=>({relativePath:a(i(d,t)),id:n(t,r(t)),hash:`_${e(t)}`}));p.forEach(e=>{l===`esm`&&(f+=`import ${e.hash} from '${e.relativePath}'${c===`json`?` with { type: 'json' }`:``};\n`),l===`cjs`&&(f+=`const ${e.hash} = require('${e.relativePath}');\n`)}),f+=`
1
+ import{getPathHash as e}from"../utils/getPathHash.mjs";import{getConfiguration as t}from"@intlayer/config/node";import{basename as n,extname as r,relative as i}from"node:path";import{normalizePath as a}from"@intlayer/config/utils";const o=(o,s,c,l=`esm`,u=t())=>{let{mainDir:d}=u.system,f=``,p=o.map(t=>({relativePath:a(i(d,t)),id:n(t,r(t)),hash:`_${e(t)}`}));p.forEach(e=>{l===`esm`&&(f+=`import ${e.hash} from '${e.relativePath}'${c===`json`?` with { type: 'json' }`:``};\n`),l===`cjs`&&(f+=`const ${e.hash} = require('${e.relativePath}');\n`)}),f+=`
2
2
  `;let m=p.map(e=>` "${e.id}": ${e.hash}`).join(`,
3
3
  `);return f+=`const dictionaries = {\n${m}\n};\n`,f+=`const ${s} = () => dictionaries;\n`,l===`esm`&&(f+=`
4
4
  `,f+=`export { ${s} };\n`,f+=`export default dictionaries;
@@ -1 +1 @@
1
- {"version":3,"file":"generateDictionaryListContent.mjs","names":[],"sources":["../../../src/createDictionaryEntryPoint/generateDictionaryListContent.ts"],"sourcesContent":["import { basename, extname, relative } from 'node:path';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { normalizePath } from '@intlayer/config/utils';\nimport { getFileHash } from '../utils/getFileHash';\n\n/**\n * This function generates the content of the dictionary list file\n */\nexport const generateDictionaryListContent = (\n dictionaries: string[],\n functionName: string,\n importType: 'json' | 'javascript',\n format: 'cjs' | 'esm' = 'esm',\n configuration = getConfiguration()\n): string => {\n const { mainDir } = configuration.system;\n\n let content = '';\n\n const dictionariesRef = dictionaries.map((dictionaryPath) => ({\n relativePath: normalizePath(relative(mainDir, dictionaryPath)),\n id: basename(dictionaryPath, extname(dictionaryPath)), // Get the base name as the dictionary id\n hash: `_${getFileHash(dictionaryPath)}`, // Get the hash of the dictionary to avoid conflicts\n }));\n\n // Import all dictionaries\n dictionariesRef.forEach((dictionary) => {\n if (format === 'esm')\n content += `import ${dictionary.hash} from '${dictionary.relativePath}'${importType === 'json' ? \" with { type: 'json' }\" : ''};\\n`;\n if (format === 'cjs')\n content += `const ${dictionary.hash} = require('${dictionary.relativePath}');\\n`;\n });\n\n content += '\\n';\n\n // Format Dictionary Map\n const formattedDictionaryMap: string = dictionariesRef\n .map((dictionary) => ` \"${dictionary.id}\": ${dictionary.hash}`)\n .join(',\\n');\n\n content += `const dictionaries = {\\n${formattedDictionaryMap}\\n};\\n`;\n content += `const ${functionName} = () => dictionaries;\\n`;\n\n if (format === 'esm') {\n content += `\\n`;\n content += `export { ${functionName} };\\n`;\n content += `export default dictionaries;\\n`;\n }\n\n if (format === 'cjs') {\n content += `\\n`;\n content += `module.exports.${functionName} = ${functionName};\\n`;\n content += `module.exports = dictionaries;\\n`;\n }\n\n return content;\n};\n"],"mappings":"uOAQA,MAAa,GACX,EACA,EACA,EACA,EAAwB,MACxB,EAAgB,GAAkB,GACvB,CACX,GAAM,CAAE,WAAY,EAAc,OAE9B,EAAU,GAER,EAAkB,EAAa,IAAK,IAAoB,CAC5D,aAAc,EAAc,EAAS,EAAS,EAAe,CAAC,CAC9D,GAAI,EAAS,EAAgB,EAAQ,EAAe,CAAC,CACrD,KAAM,IAAI,EAAY,EAAe,GACtC,EAAE,CAGH,EAAgB,QAAS,GAAe,CAClC,IAAW,QACb,GAAW,UAAU,EAAW,KAAK,SAAS,EAAW,aAAa,GAAG,IAAe,OAAS,yBAA2B,GAAG,MAC7H,IAAW,QACb,GAAW,SAAS,EAAW,KAAK,cAAc,EAAW,aAAa,SAC5E,CAEF,GAAW;EAGX,IAAM,EAAiC,EACpC,IAAK,GAAe,MAAM,EAAW,GAAG,KAAK,EAAW,OAAO,CAC/D,KAAK;EAAM,CAiBd,MAfA,IAAW,2BAA2B,EAAuB,QAC7D,GAAW,SAAS,EAAa,0BAE7B,IAAW,QACb,GAAW;EACX,GAAW,YAAY,EAAa,OACpC,GAAW;GAGT,IAAW,QACb,GAAW;EACX,GAAW,kBAAkB,EAAa,KAAK,EAAa,KAC5D,GAAW;GAGN"}
1
+ {"version":3,"file":"generateDictionaryListContent.mjs","names":[],"sources":["../../../src/createDictionaryEntryPoint/generateDictionaryListContent.ts"],"sourcesContent":["import { basename, extname, relative } from 'node:path';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { normalizePath } from '@intlayer/config/utils';\nimport { getPathHash } from '../utils/getPathHash';\n\n/**\n * This function generates the content of the dictionary list file\n */\nexport const generateDictionaryListContent = (\n dictionaries: string[],\n functionName: string,\n importType: 'json' | 'javascript',\n format: 'cjs' | 'esm' = 'esm',\n configuration = getConfiguration()\n): string => {\n const { mainDir } = configuration.system;\n\n let content = '';\n\n const dictionariesRef = dictionaries.map((dictionaryPath) => ({\n relativePath: normalizePath(relative(mainDir, dictionaryPath)),\n id: basename(dictionaryPath, extname(dictionaryPath)), // Get the base name as the dictionary id\n hash: `_${getPathHash(dictionaryPath)}`, // Get the hash of the dictionary to avoid conflicts\n }));\n\n // Import all dictionaries\n dictionariesRef.forEach((dictionary) => {\n if (format === 'esm')\n content += `import ${dictionary.hash} from '${dictionary.relativePath}'${importType === 'json' ? \" with { type: 'json' }\" : ''};\\n`;\n if (format === 'cjs')\n content += `const ${dictionary.hash} = require('${dictionary.relativePath}');\\n`;\n });\n\n content += '\\n';\n\n // Format Dictionary Map\n const formattedDictionaryMap: string = dictionariesRef\n .map((dictionary) => ` \"${dictionary.id}\": ${dictionary.hash}`)\n .join(',\\n');\n\n content += `const dictionaries = {\\n${formattedDictionaryMap}\\n};\\n`;\n content += `const ${functionName} = () => dictionaries;\\n`;\n\n if (format === 'esm') {\n content += `\\n`;\n content += `export { ${functionName} };\\n`;\n content += `export default dictionaries;\\n`;\n }\n\n if (format === 'cjs') {\n content += `\\n`;\n content += `module.exports.${functionName} = ${functionName};\\n`;\n content += `module.exports = dictionaries;\\n`;\n }\n\n return content;\n};\n"],"mappings":"uOAQA,MAAa,GACX,EACA,EACA,EACA,EAAwB,MACxB,EAAgB,GAAkB,GACvB,CACX,GAAM,CAAE,WAAY,EAAc,OAE9B,EAAU,GAER,EAAkB,EAAa,IAAK,IAAoB,CAC5D,aAAc,EAAc,EAAS,EAAS,EAAe,CAAC,CAC9D,GAAI,EAAS,EAAgB,EAAQ,EAAe,CAAC,CACrD,KAAM,IAAI,EAAY,EAAe,GACtC,EAAE,CAGH,EAAgB,QAAS,GAAe,CAClC,IAAW,QACb,GAAW,UAAU,EAAW,KAAK,SAAS,EAAW,aAAa,GAAG,IAAe,OAAS,yBAA2B,GAAG,MAC7H,IAAW,QACb,GAAW,SAAS,EAAW,KAAK,cAAc,EAAW,aAAa,SAC5E,CAEF,GAAW;EAGX,IAAM,EAAiC,EACpC,IAAK,GAAe,MAAM,EAAW,GAAG,KAAK,EAAW,OAAO,CAC/D,KAAK;EAAM,CAiBd,MAfA,IAAW,2BAA2B,EAAuB,QAC7D,GAAW,SAAS,EAAa,0BAE7B,IAAW,QACb,GAAW;EACX,GAAW,YAAY,EAAa,OACpC,GAAW;GAGT,IAAW,QACb,GAAW;EACX,GAAW,kBAAkB,EAAa,KAAK,EAAa,KAC5D,GAAW;GAGN"}
@@ -1,10 +1,10 @@
1
- import{writeFileIfChanged as e}from"../writeFileIfChanged.mjs";import{getFileHash as t}from"../utils/getFileHash.mjs";import{mkdir as n}from"node:fs/promises";import{basename as r,extname as i,join as a,relative as o}from"node:path";import{kebabCaseToCamelCase as s,normalizePath as c}from"@intlayer/config/utils";import l from"fast-glob";import{printNode as u,zodToTs as d}from"zod-to-ts";const f=e=>`${s(e)}Content`,p=e=>e.map(e=>` "${e}": 1;`).join(`
2
- `),m=e=>{if(!e)return`any`;let t=e._def??e.def??e;switch(t.typeName??t.type){case`ZodString`:case`string`:return`string`;case`ZodNumber`:case`number`:return`number`;case`ZodBoolean`:case`boolean`:return`boolean`;case`ZodNull`:case`null`:return`null`;case`ZodUndefined`:case`undefined`:return`undefined`;case`ZodArray`:case`array`:return`${m(t.type??t.element)}[]`;case`ZodObject`:case`object`:{let e=typeof t.shape==`function`?t.shape():t.shape;return e?`{\n${Object.entries(e).map(([e,t])=>` "${e}": ${m(t)};`).join(`
3
- `)}\n }`:`Record<string, any>`}case`ZodOptional`:case`optional`:return`${m(t.innerType??t.wrapped)} | undefined`;case`ZodNullable`:case`nullable`:return`${m(t.innerType??t.wrapped)} | null`;case`ZodUnion`:case`union`:return(t.options??[]).map(m).join(` | `);case`ZodIntersection`:case`intersection`:return`${m(t.left)} & ${m(t.right)}`;case`ZodEnum`:case`enum`:return(t.values??[]).map(e=>`"${e}"`).join(` | `);case`ZodLiteral`:case`literal`:{let e=t.value;return typeof e==`string`?`"${e}"`:String(e)}default:return`any`}},h=(e,n)=>{let{internationalization:a,system:s}=n,{moduleAugmentationDir:c}=s,{locales:l,requiredLocales:f,strictMode:h}=a,g=`import "intlayer";
4
- `,_=e.map(e=>({relativePath:`./${o(c,e)}`,id:r(e,i(e)),hash:`_${t(e)}`}));for(let e of _)g+=`import ${e.hash} from '${e.relativePath}';\n`;g+=`
5
- `;let v=_.map(e=>` "${e.id}": typeof ${e.hash};`).join(`
6
- `),y=l,b=f?.length?f.filter(e=>y.includes(e)):y,x=p(y),S=p(b),C=n.schemas??{},w=Object.entries(C).map(([e,t])=>{let n=`any`;if(t)try{let{node:r}=d(t,e);n=r.kind===133?m(t):u(r)}catch{n=m(t)}return` "${e}": ${n};`}).join(`
7
- `),T=h===`strict`?`strict`:h===`inclusive`?`inclusive`:`loose`;return g+=`declare module 'intlayer' {
8
- `,g+=` interface __DictionaryRegistry {\n${v}\n }\n\n`,g+=` interface __DeclaredLocalesRegistry {\n${x}\n }\n\n`,g+=` interface __RequiredLocalesRegistry {\n${S}\n }\n\n`,g+=` interface __SchemaRegistry {\n${w}\n }\n\n`,g+=` interface __StrictModeRegistry { mode: '${T}' }\n`,g+=`}
9
- `,g},g=async t=>{let{moduleAugmentationDir:r,typesDir:i}=t.system;await n(r,{recursive:!0});let o=h(await l(c(`${i}/*.ts`),{ignore:[`**/*.d.ts`]}),t);await e(a(r,`intlayer.d.ts`),o)};export{g as createModuleAugmentation,f as getTypeName};
1
+ import{writeFileIfChanged as e}from"../writeFileIfChanged.mjs";import{getPathHash as t}from"../utils/getPathHash.mjs";import{mkdir as n}from"node:fs/promises";import{basename as r,extname as i,join as a,relative as o}from"node:path";import{kebabCaseToCamelCase as s,normalizePath as c}from"@intlayer/config/utils";import l from"fast-glob";import{createAuxiliaryTypeStore as u,printNode as d,zodToTs as f}from"zod-to-ts";const p=e=>`${s(e)}Content`,m=e=>e.map(e=>` "${e}": 1;`).join(`
2
+ `),h=e=>{if(!e)return`any`;let t=e._def??e.def??e;switch(t.typeName??t.type){case`ZodString`:case`string`:return`string`;case`ZodNumber`:case`number`:return`number`;case`ZodBoolean`:case`boolean`:return`boolean`;case`ZodNull`:case`null`:return`null`;case`ZodUndefined`:case`undefined`:return`undefined`;case`ZodArray`:case`array`:return`${h(t.type??t.element)}[]`;case`ZodObject`:case`object`:{let e=typeof t.shape==`function`?t.shape():t.shape;return e?`{\n${Object.entries(e).map(([e,t])=>` "${e}": ${h(t)};`).join(`
3
+ `)}\n }`:`Record<string, any>`}case`ZodOptional`:case`optional`:return`${h(t.innerType??t.wrapped)} | undefined`;case`ZodNullable`:case`nullable`:return`${h(t.innerType??t.wrapped)} | null`;case`ZodUnion`:case`union`:return(t.options??[]).map(h).join(` | `);case`ZodIntersection`:case`intersection`:return`${h(t.left)} & ${h(t.right)}`;case`ZodEnum`:case`enum`:return(t.values??[]).map(e=>`"${e}"`).join(` | `);case`ZodLiteral`:case`literal`:{let e=t.value;return typeof e==`string`?`"${e}"`:String(e)}default:return`any`}},g=(e,n)=>{let{internationalization:a,system:s}=n,{moduleAugmentationDir:c}=s,{locales:l,requiredLocales:p,strictMode:g}=a,_=`import "intlayer";
4
+ `,v=e.map(e=>({relativePath:`./${o(c,e)}`,id:r(e,i(e)),hash:`_${t(e)}`}));for(let e of v)_+=`import ${e.hash} from '${e.relativePath}';\n`;_+=`
5
+ `;let y=v.map(e=>` "${e.id}": typeof ${e.hash};`).join(`
6
+ `),b=l,x=p?.length?p.filter(e=>b.includes(e)):b,S=m(b),C=m(x),w=n.schemas??{},T=Object.entries(w).map(([e,t])=>{let n=`any`;if(t)try{let{node:e}=f(t,{auxiliaryTypeStore:u()});n=e.kind===133?h(t):d(e)}catch{n=h(t)}return` "${e}": ${n};`}).join(`
7
+ `),E=g===`strict`?`strict`:g===`inclusive`?`inclusive`:`loose`;return _+=`declare module 'intlayer' {
8
+ `,_+=` interface __DictionaryRegistry {\n${y}\n }\n\n`,_+=` interface __DeclaredLocalesRegistry {\n${S}\n }\n\n`,_+=` interface __RequiredLocalesRegistry {\n${C}\n }\n\n`,_+=` interface __SchemaRegistry {\n${T}\n }\n\n`,_+=` interface __StrictModeRegistry { mode: '${E}' }\n`,_+=`}
9
+ `,_},_=async t=>{let{moduleAugmentationDir:r,typesDir:i}=t.system;await n(r,{recursive:!0});let o=g(await l(c(`${i}/*.ts`),{ignore:[`**/*.d.ts`]}),t);await e(a(r,`intlayer.d.ts`),o)};export{_ as createModuleAugmentation,p as getTypeName};
10
10
  //# sourceMappingURL=createModuleAugmentation.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"createModuleAugmentation.mjs","names":[],"sources":["../../../src/createType/createModuleAugmentation.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { basename, extname, join, relative } from 'node:path';\nimport { kebabCaseToCamelCase, normalizePath } from '@intlayer/config/utils';\nimport type { IntlayerConfig, Locale } from '@intlayer/types';\nimport fg from 'fast-glob';\nimport { printNode, zodToTs } from 'zod-to-ts';\nimport { getFileHash } from '../utils/getFileHash';\nimport { writeFileIfChanged } from '../writeFileIfChanged';\n\nexport const getTypeName = (key: string): string =>\n `${kebabCaseToCamelCase(key)}Content`;\n\n/** Returns lines like: [Locales.FRENCH]: 1; */\nconst formatLocales = (locales: Locale[]) =>\n locales.map((locale) => ` \"${locale}\": 1;`).join('\\n');\n\nconst zodToTsString = (schema: any): string => {\n if (!schema) return 'any';\n\n // Support both real Zod objects (_def) and serialized versions (def or nested)\n const def = schema._def ?? schema.def ?? schema;\n\n // Handle serialized type names (sometimes 'type' instead of 'typeName')\n const typeName = def.typeName ?? def.type;\n\n switch (typeName) {\n case 'ZodString':\n case 'string':\n return 'string';\n case 'ZodNumber':\n case 'number':\n return 'number';\n case 'ZodBoolean':\n case 'boolean':\n return 'boolean';\n case 'ZodNull':\n case 'null':\n return 'null';\n case 'ZodUndefined':\n case 'undefined':\n return 'undefined';\n case 'ZodArray':\n case 'array':\n return `${zodToTsString(def.type ?? def.element)}[]`;\n case 'ZodObject':\n case 'object': {\n const shape = typeof def.shape === 'function' ? def.shape() : def.shape;\n if (!shape) return 'Record<string, any>';\n\n const entries = Object.entries(shape)\n .map(([k, v]) => ` \"${k}\": ${zodToTsString(v)};`)\n .join('\\n');\n return `{\\n${entries}\\n }`;\n }\n case 'ZodOptional':\n case 'optional':\n return `${zodToTsString(def.innerType ?? def.wrapped)} | undefined`;\n case 'ZodNullable':\n case 'nullable':\n return `${zodToTsString(def.innerType ?? def.wrapped)} | null`;\n case 'ZodUnion':\n case 'union': {\n const options = def.options ?? [];\n return options.map(zodToTsString).join(' | ');\n }\n case 'ZodIntersection':\n case 'intersection':\n return `${zodToTsString(def.left)} & ${zodToTsString(def.right)}`;\n case 'ZodEnum':\n case 'enum': {\n const values = def.values ?? [];\n return values.map((v: string) => `\"${v}\"`).join(' | ');\n }\n case 'ZodLiteral':\n case 'literal': {\n const value = def.value;\n return typeof value === 'string' ? `\"${value}\"` : String(value);\n }\n default:\n return 'any';\n }\n};\n\n/** Generate the content of the module augmentation file */\nconst generateTypeIndexContent = (\n typeFiles: string[],\n configuration: IntlayerConfig\n): string => {\n const { internationalization, system } = configuration;\n const { moduleAugmentationDir } = system;\n const { locales, requiredLocales, strictMode } = internationalization;\n\n let fileContent = 'import \"intlayer\";\\n';\n\n // Build dictionary refs\n const dictionariesRef = typeFiles.map((dictionaryPath) => ({\n relativePath: `./${relative(moduleAugmentationDir, dictionaryPath)}`,\n id: basename(dictionaryPath, extname(dictionaryPath)),\n hash: `_${getFileHash(dictionaryPath)}`,\n }));\n\n // Import all dictionaries\n for (const dictionary of dictionariesRef) {\n fileContent += `import ${dictionary.hash} from '${dictionary.relativePath}';\\n`;\n }\n fileContent += '\\n';\n\n // Dictionary map entries (id: typeof <hash>)\n const formattedDictionaryMap: string = dictionariesRef\n .map((dictionary) => ` \"${dictionary.id}\": typeof ${dictionary.hash};`)\n .join('\\n');\n\n // Ensure required ⊆ declared; if empty, default required = declared\n const declared = locales;\n const requiredSanitized = requiredLocales?.length\n ? requiredLocales.filter((requiredLocales) =>\n declared.includes(requiredLocales)\n )\n : declared;\n\n const formattedDeclaredLocales = formatLocales(declared);\n const formattedRequiredLocales = formatLocales(requiredSanitized);\n\n // Build schema registry\n const schemas = configuration.schemas ?? {};\n const formattedSchemas = Object.entries(schemas)\n .map(([key, schema]) => {\n let typeStr = 'any';\n\n if (schema) {\n try {\n const { node } = zodToTs(schema as any, key);\n // 133 is the kind for AnyKeyword in TypeScript\n if ((node as any).kind !== 133) {\n typeStr = printNode(node);\n } else {\n // Fallback to custom string generator if zodToTs returns any\n typeStr = zodToTsString(schema);\n }\n } catch (_e) {\n // Fallback to custom string generator\n typeStr = zodToTsString(schema);\n }\n }\n return ` \"${key}\": ${typeStr};`;\n })\n .join('\\n');\n\n // Choose strict mode registry key\n const strictKey =\n strictMode === 'strict'\n ? 'strict'\n : strictMode === 'inclusive'\n ? 'inclusive'\n : 'loose';\n\n /**\n * Module augmentation that ONLY adds keys to registries.\n * No types/aliases redefined here—avoids merge conflicts.\n */\n fileContent += `declare module 'intlayer' {\\n`;\n // Dictionaries registry\n fileContent += ` interface __DictionaryRegistry {\\n${formattedDictionaryMap}\\n }\\n\\n`;\n // Locales registries\n fileContent += ` interface __DeclaredLocalesRegistry {\\n${formattedDeclaredLocales}\\n }\\n\\n`;\n fileContent += ` interface __RequiredLocalesRegistry {\\n${formattedRequiredLocales}\\n }\\n\\n`;\n // Schema registry\n fileContent += ` interface __SchemaRegistry {\\n${formattedSchemas}\\n }\\n\\n`;\n // Resolved strict mode (narrow the literal at build time)\n fileContent += ` interface __StrictModeRegistry { mode: '${strictKey}' }\\n`;\n fileContent += `}\\n`;\n\n return fileContent;\n};\n\n/** Generate the index file merging all the types */\nexport const createModuleAugmentation = async (\n configuration: IntlayerConfig\n) => {\n const { moduleAugmentationDir, typesDir } = configuration.system;\n\n await mkdir(moduleAugmentationDir, { recursive: true });\n\n const dictionariesTypesDefinitions: string[] = await fg(\n normalizePath(`${typesDir}/*.ts`),\n { ignore: ['**/*.d.ts'] }\n );\n\n const tsContent = generateTypeIndexContent(\n dictionariesTypesDefinitions,\n configuration\n );\n\n const tsFilePath = join(moduleAugmentationDir, 'intlayer.d.ts');\n await writ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,EAAiB,WAEnE,GAAe,6CAA6C,EAAU,OACtE,GAAe;EAER,GAII,EAA2B,KACtC,IACG,CACH,GAAM,CAAE,wBAAuB,YAAa,EAAc,OAE1D,MAAM,EAAM,EAAuB,CAAE,UAAW,GAAM,CAAC,CAOvD,IAAM,EAAY,EAL6B,MAAM,EACnD,EAAc,GAAG,EAAS,OAAO,CACjC,CAAE,OAAQ,CAAC,YAAY,CAAE,CAC1B,CAIC,EACD,CAGD,MAAM,EADa,EAAK,EAAuB,gBAAgB,CAC1B,EAAU"}
1
+ {"version":3,"file":"createModuleAugmentation.mjs","names":[],"sources":["../../../src/createType/createModuleAugmentation.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { basename, extname, join, relative } from 'node:path';\nimport { kebabCaseToCamelCase, normalizePath } from '@intlayer/config/utils';\nimport type { IntlayerConfig, Locale } from '@intlayer/types';\nimport fg from 'fast-glob';\nimport { createAuxiliaryTypeStore, printNode, zodToTs } from 'zod-to-ts';\nimport { getPathHash } from '../utils';\nimport { writeFileIfChanged } from '../writeFileIfChanged';\n\nexport const getTypeName = (key: string): string =>\n `${kebabCaseToCamelCase(key)}Content`;\n\n/** Returns lines like: [Locales.FRENCH]: 1; */\nconst formatLocales = (locales: Locale[]) =>\n locales.map((locale) => ` \"${locale}\": 1;`).join('\\n');\n\nconst zodToTsString = (schema: any): string => {\n if (!schema) return 'any';\n\n // Support both real Zod objects (_def) and serialized versions (def or nested)\n const def = schema._def ?? schema.def ?? schema;\n\n // Handle serialized type names (sometimes 'type' instead of 'typeName')\n const typeName = def.typeName ?? def.type;\n\n switch (typeName) {\n case 'ZodString':\n case 'string':\n return 'string';\n case 'ZodNumber':\n case 'number':\n return 'number';\n case 'ZodBoolean':\n case 'boolean':\n return 'boolean';\n case 'ZodNull':\n case 'null':\n return 'null';\n case 'ZodUndefined':\n case 'undefined':\n return 'undefined';\n case 'ZodArray':\n case 'array':\n return `${zodToTsString(def.type ?? def.element)}[]`;\n case 'ZodObject':\n case 'object': {\n const shape = typeof def.shape === 'function' ? def.shape() : def.shape;\n if (!shape) return 'Record<string, any>';\n\n const entries = Object.entries(shape)\n .map(([k, v]) => ` \"${k}\": ${zodToTsString(v)};`)\n .join('\\n');\n return `{\\n${entries}\\n }`;\n }\n case 'ZodOptional':\n case 'optional':\n return `${zodToTsString(def.innerType ?? def.wrapped)} | undefined`;\n case 'ZodNullable':\n case 'nullable':\n return `${zodToTsString(def.innerType ?? def.wrapped)} | null`;\n case 'ZodUnion':\n case 'union': {\n const options = def.options ?? [];\n return options.map(zodToTsString).join(' | ');\n }\n case 'ZodIntersection':\n case 'intersection':\n return `${zodToTsString(def.left)} & ${zodToTsString(def.right)}`;\n case 'ZodEnum':\n case 'enum': {\n const values = def.values ?? [];\n return values.map((v: string) => `\"${v}\"`).join(' | ');\n }\n case 'ZodLiteral':\n case 'literal': {\n const value = def.value;\n return typeof value === 'string' ? `\"${value}\"` : String(value);\n }\n default:\n return 'any';\n }\n};\n\n/** Generate the content of the module augmentation file */\nconst generateTypeIndexContent = (\n typeFiles: string[],\n configuration: IntlayerConfig\n): string => {\n const { internationalization, system } = configuration;\n const { moduleAugmentationDir } = system;\n const { locales, requiredLocales, strictMode } = internationalization;\n\n let fileContent = 'import \"intlayer\";\\n';\n\n // Build dictionary refs\n const dictionariesRef = typeFiles.map((dictionaryPath) => ({\n relativePath: `./${relative(moduleAugmentationDir, dictionaryPath)}`,\n id: basename(dictionaryPath, extname(dictionaryPath)),\n hash: `_${getPathHash(dictionaryPath)}`,\n }));\n\n // Import all dictionaries\n for (const dictionary of dictionariesRef) {\n fileContent += `import ${dictionary.hash} from '${dictionary.relativePath}';\\n`;\n }\n fileContent += '\\n';\n\n // Dictionary map entries (id: typeof <hash>)\n const formattedDictionaryMap: string = dictionariesRef\n .map((dictionary) => ` \"${dictionary.id}\": typeof ${dictionary.hash};`)\n .join('\\n');\n\n // Ensure required ⊆ declared; if empty, default required = declared\n const declared = locales;\n const requiredSanitized = requiredLocales?.length\n ? requiredLocales.filter((requiredLocales) =>\n declared.includes(requiredLocales)\n )\n : declared;\n\n const formattedDeclaredLocales = formatLocales(declared);\n const formattedRequiredLocales = formatLocales(requiredSanitized);\n\n // Build schema registry\n const schemas = configuration.schemas ?? {};\n const formattedSchemas = Object.entries(schemas)\n .map(([key, schema]) => {\n let typeStr = 'any';\n\n if (schema) {\n try {\n const { node } = zodToTs(schema, {\n auxiliaryTypeStore: createAuxiliaryTypeStore(),\n });\n // 133 is the kind for AnyKeyword in TypeScript\n if ((node as any).kind !== 133) {\n typeStr = printNode(node);\n } else {\n // Fallback to custom string generator if zodToTs returns any\n typeStr = zodToTsString(schema);\n }\n } catch (_e) {\n // Fallback to custom string generator\n typeStr = zodToTsString(schema);\n }\n }\n return ` \"${key}\": ${typeStr};`;\n })\n .join('\\n');\n\n // Choose strict mode registry key\n const strictKey =\n strictMode === 'strict'\n ? 'strict'\n : strictMode === 'inclusive'\n ? 'inclusive'\n : 'loose';\n\n /**\n * Module augmentation that ONLY adds keys to registries.\n * No types/aliases redefined here—avoids merge conflicts.\n */\n fileContent += `declare module 'intlayer' {\\n`;\n // Dictionaries registry\n fileContent += ` interface __DictionaryRegistry {\\n${formattedDictionaryMap}\\n }\\n\\n`;\n // Locales registries\n fileContent += ` interface __DeclaredLocalesRegistry {\\n${formattedDeclaredLocales}\\n }\\n\\n`;\n fileContent += ` interface __RequiredLocalesRegistry {\\n${formattedRequiredLocales}\\n }\\n\\n`;\n // Schema registry\n fileContent += ` interface __SchemaRegistry {\\n${formattedSchemas}\\n }\\n\\n`;\n // Resolved strict mode (narrow the literal at build time)\n fileContent += ` interface __StrictModeRegistry { mode: '${strictKey}' }\\n`;\n fileContent += `}\\n`;\n\n return fileContent;\n};\n\n/** Generate the index file merging all the types */\nexport const createModuleAugmentation = async (\n configuration: IntlayerConfig\n) => {\n const { moduleAugmentationDir, typesDir } = configuration.system;\n\n await mkdir(moduleAugmentationDir, { recursive: true });\n\n const dictionariesTypesDefinitions: string[] = await fg(\n normalizePath(`${typesDir}/*.ts`),\n { ignore: ['**/*.d.ts'] }\n );\n\n const tsContent = generateTypeIndexContent(\n dictionariesTypesDefinitions,\n configuration\n );\n\n const tsFilePath = join(moduleAugmentationDir, 'intlayer.d.ts');\n await writeFileIfChanged(tsFilePath, tsContent);\n};\n"],"mappings":"oaASA,MAAa,EAAe,GAC1B,GAAG,EAAqB,EAAI,CAAC,SAGzB,EAAiB,GACrB,EAAQ,IAAK,GAAW,QAAQ,EAAO,OAAO,CAAC,KAAK;EAAK,CAErD,EAAiB,GAAwB,CAC7C,GAAI,CAAC,EAAQ,MAAO,MAGpB,IAAM,EAAM,EAAO,MAAQ,EAAO,KAAO,EAKzC,OAFiB,EAAI,UAAY,EAAI,KAErC,CACE,IAAK,YACL,IAAK,SACH,MAAO,SACT,IAAK,YACL,IAAK,SACH,MAAO,SACT,IAAK,aACL,IAAK,UACH,MAAO,UACT,IAAK,UACL,IAAK,OACH,MAAO,OACT,IAAK,eACL,IAAK,YACH,MAAO,YACT,IAAK,WACL,IAAK,QACH,MAAO,GAAG,EAAc,EAAI,MAAQ,EAAI,QAAQ,CAAC,IACnD,IAAK,YACL,IAAK,SAAU,CACb,IAAM,EAAQ,OAAO,EAAI,OAAU,WAAa,EAAI,OAAO,CAAG,EAAI,MAMlE,OALK,EAKE,MAHS,OAAO,QAAQ,EAAM,CAClC,KAAK,CAAC,EAAG,KAAO,UAAU,EAAE,KAAK,EAAc,EAAE,CAAC,GAAG,CACrD,KAAK;EAAK,CACQ,SALF,sBAOrB,IAAK,cACL,IAAK,WACH,MAAO,GAAG,EAAc,EAAI,WAAa,EAAI,QAAQ,CAAC,cACxD,IAAK,cACL,IAAK,WACH,MAAO,GAAG,EAAc,EAAI,WAAa,EAAI,QAAQ,CAAC,SACxD,IAAK,WACL,IAAK,QAEH,OADgB,EAAI,SAAW,EAAE,EAClB,IAAI,EAAc,CAAC,KAAK,MAAM,CAE/C,IAAK,kBACL,IAAK,eACH,MAAO,GA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AQ,IAChC,CACD,KAAK;EAAK,CAGP,EACJ,IAAe,SACX,SACA,IAAe,YACb,YACA,QAkBR,MAZA,IAAe;EAEf,GAAe,uCAAuC,EAAuB,WAE7E,GAAe,4CAA4C,EAAyB,WACpF,GAAe,4CAA4C,EAAyB,WAEpF,GAAe,mCAAmC,EAAiB,WAEnE,GAAe,6CAA6C,EAAU,OACtE,GAAe;EAER,GAII,EAA2B,KACtC,IACG,CACH,GAAM,CAAE,wBAAuB,YAAa,EAAc,OAE1D,MAAM,EAAM,EAAuB,CAAE,UAAW,GAAM,CAAC,CAOvD,IAAM,EAAY,EAL6B,MAAM,EACnD,EAAc,GAAG,EAAS,OAAO,CACjC,CAAE,OAAQ,CAAC,YAAY,CAAE,CAC1B,CAIC,EACD,CAGD,MAAM,EADa,EAAK,EAAuB,gBAAgB,CAC1B,EAAU"}
@@ -1,2 +1,2 @@
1
- import{Project as e,SyntaxKind as t}from"ts-morph";const n=(e,n)=>{let r=e.getImportDeclarations().some(e=>e.getModuleSpecifierValue()===n),i=e.getDescendantsOfKind(t.CallExpression).some(e=>e.getExpression().getText()===`require`&&e.getArguments()[0]?.asKind(t.StringLiteral)?.getLiteralValue()===n);return r||i},r=(e,t)=>t===`cjs`?!0:[`mjs`,`ts`].includes(t)?!1:e.includes(`module.exports`)&&!e.includes(`import `)&&!e.includes(`export `),i=(i,a)=>{let o=new e({useInMemoryFileSystem:!0}).createSourceFile(`vite.config.${a}`,i),s=r(i,a);n(o,`vite-intlayer`)||(s?o.insertVariableStatement(0,{declarationKind:`const`,declarations:[{name:`{ intlayer }`,initializer:`require("vite-intlayer")`}]}):o.addImportDeclaration({moduleSpecifier:`vite-intlayer`,namedImports:[`intlayer`]}));let c,l=o.getExportAssignment(e=>!e.isExportEquals());if(l){let e=l.getExpression();if(e.getKind()===t.CallExpression){let n=e.asKind(t.CallExpression);if(n?.getExpression().getText()===`defineConfig`){let e=n.getArguments()[0];e?.getKind()===t.ObjectLiteralExpression&&(c=e.asKind(t.ObjectLiteralExpression))}}else if(e.getKind()===t.ObjectLiteralExpression)c=e.asKind(t.ObjectLiteralExpression);else if(e.getKind()===t.Identifier){let n=e.asKind(t.Identifier)?.getDefinitions();if(n&&n.length>0){let e=n[0].getDeclarationNode();if(e?.getKind()===t.VariableDeclaration){let n=e.asKind(t.VariableDeclaration)?.getInitializer();n?.getKind()===t.ObjectLiteralExpression&&(c=n.asKind(t.ObjectLiteralExpression))}}}}if(!c){let e=o.getStatements();for(let n of e)if(n.getKind()===t.ExpressionStatement){let e=n.asKind(t.ExpressionStatement)?.getExpression();if(e?.getKind()===t.BinaryExpression){let n=e.asKind(t.BinaryExpression);if(n?.getLeft().getText()===`module.exports`&&n.getOperatorToken().getKind()===t.EqualsToken){let e=n.getRight();if(e.getKind()===t.ObjectLiteralExpression)c=e.asKind(t.ObjectLiteralExpression);else if(e.getKind()===t.CallExpression){let n=e.asKind(t.CallExpression);if(n?.getExpression().getText()===`defineConfig`){let e=n.getArguments()[0];e?.getKind()===t.ObjectLiteralExpression&&(c=e.asKind(t.ObjectLiteralExpression))}}else if(e.getKind()===t.Identifier){let n=e.asKind(t.Identifier)?.getDefinitions();if(n&&n.length>0){let e=n[0].getDeclarationNode();if(e?.getKind()===t.VariableDeclaration){let n=e.asKind(t.VariableDeclaration)?.getInitializer();n?.getKind()===t.ObjectLiteralExpression&&(c=n.asKind(t.ObjectLiteralExpression))}}}}}}}if(c){let e=c.getProperty(`plugins`);if(e||=(c.addPropertyAssignment({name:`plugins`,initializer:`[]`}),c.getProperty(`plugins`)),e?.getKind()===t.PropertyAssignment){let n=e.asKind(t.PropertyAssignment)?.getInitializer();if(n?.getKind()===t.ArrayLiteralExpression){let e=n.asKind(t.ArrayLiteralExpression);e?.getElements().some(e=>e.getText().includes(`intlayer(`))||e?.addElement(`intlayer()`)}}}return o.getFullText()},a=(i,a)=>{let o=new e({useInMemoryFileSystem:!0}).createSourceFile(`next.config.${a}`,i),s=r(i,a);n(o,`next-intlayer/server`)||(s?o.insertVariableStatement(0,{declarationKind:`const`,declarations:[{name:`{ withIntlayer }`,initializer:`require("next-intlayer/server")`}]}):o.addImportDeclaration({moduleSpecifier:`next-intlayer/server`,namedImports:[`withIntlayer`]}));let c=!1,l=o.getExportAssignment(e=>!e.isExportEquals());if(l){let e=l.getExpression();e.getText().includes(`withIntlayer`)||(l.setExpression(`withIntlayer(${e.getText()})`),c=!0)}if(!c){let e=o.getStatements();for(let n of e)if(n.getKind()===t.ExpressionStatement){let e=n.asKind(t.ExpressionStatement)?.getExpression();if(e?.getKind()===t.BinaryExpression){let n=e.asKind(t.BinaryExpression);if(n?.getLeft().getText()===`module.exports`&&n.getOperatorToken().getKind()===t.EqualsToken){let e=n.getRight();e.getText().includes(`withIntlayer`)||(e.replaceWithText(`withIntlayer(${e.getText()})`),c=!0)}}}}return o.getFullText()};export{a as updateNextConfig,i as updateViteConfig};
1
+ import{__require as e}from"../../_virtual/_rolldown/runtime.mjs";import*as t from"recast";const n=t.types.builders,r=t.types.namedTypes,i=(e,n)=>{let i=!1;return t.visit(e,{visitImportDeclaration(e){return e.node.source.value===n&&(i=!0),!1},visitCallExpression(e){let{callee:t,arguments:a}=e.node;return r.Identifier.check(t)&&t.name===`require`&&a[0]&&r.StringLiteral.check(a[0])&&a[0].value===n&&(i=!0),!1}}),i},a=(e,t,r,a)=>{if(i(e,a))return;let o=t?n.variableDeclaration(`const`,[n.variableDeclarator(n.objectPattern([n.objectProperty.from({key:n.identifier(r),value:n.identifier(r),shorthand:!0})]),n.callExpression(n.identifier(`require`),[n.stringLiteral(a)]))]):n.importDeclaration([n.importSpecifier(n.identifier(r))],n.stringLiteral(a));e.program.body.unshift(o)},o=(i,o)=>{let s=t.parse(i,{parser:e(`recast/parsers/typescript`)});a(s,o===`cjs`||i.includes(`module.exports`)&&!i.includes(`import `),`intlayer`,`vite-intlayer`);let c=e=>{if(!e||e.type!==`ObjectExpression`&&!r.ObjectExpression.check(e))return;let t=e.properties.find(e=>!e||!e.key?!1:(e.key.name||e.key.value)===`plugins`);t||(t=n.property(`init`,n.identifier(`plugins`),n.arrayExpression([])),e.properties.push(t));let i=t.value;i&&(i.type===`ArrayExpression`||r.ArrayExpression.check(i))&&(i.elements.some(e=>{let t=e?.callee;if(!t)return!1;let n=t.name||t.id?.name;return n===`intlayer`||n===`il`})||i.elements.push(n.callExpression(n.identifier(`intlayer`),[])))};return t.visit(s,{visitExportDefaultDeclaration(e){let t=e.node.declaration;if(r.ObjectExpression.check(t))c(t);else if(r.CallExpression.check(t)&&r.Identifier.check(t.callee)&&t.callee.name===`defineConfig`)r.ObjectExpression.check(t.arguments[0])&&c(t.arguments[0]);else if(r.Identifier.check(t)){let e=t.name;s.program.body.forEach(t=>{r.VariableDeclaration.check(t)&&t.declarations.forEach(t=>{r.VariableDeclarator.check(t)&&r.Identifier.check(t.id)&&t.id.name===e&&r.ObjectExpression.check(t.init)&&c(t.init)})})}return!1},visitAssignmentExpression(e){let{left:n,right:i}=e.node;return r.MemberExpression.check(n)&&t.print(n).code===`module.exports`&&(r.ObjectExpression.check(i)?c(i):r.CallExpression.check(i)&&r.Identifier.check(i.callee)&&i.callee.name===`defineConfig`&&r.ObjectExpression.check(i.arguments[0])&&c(i.arguments[0])),!1}}),t.print(s).code},s=(i,o)=>{let s=t.parse(i,{parser:e(`recast/parsers/typescript`)});return a(s,o===`cjs`||i.includes(`module.exports`),`withIntlayer`,`next-intlayer/server`),t.visit(s,{visitExportDefaultDeclaration(e){let t=e.node.declaration;return r.Expression.check(t)&&!(r.CallExpression.check(t)&&r.Identifier.check(t.callee)&&t.callee.name===`withIntlayer`)&&e.get(`declaration`).replace(n.callExpression(n.identifier(`withIntlayer`),[t])),!1},visitAssignmentExpression(e){let{left:i,right:a}=e.node;return r.MemberExpression.check(i)&&t.print(i).code===`module.exports`&&!(r.CallExpression.check(a)&&r.Identifier.check(a.callee)&&a.callee.name===`withIntlayer`)&&e.get(`right`).replace(n.callExpression(n.identifier(`withIntlayer`),[a])),!1}}),t.print(s).code};export{s as updateNextConfig,o as updateViteConfig};
2
2
  //# sourceMappingURL=configManipulation.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"configManipulation.mjs","names":[],"sources":["../../../../src/init/utils/configManipulation.ts"],"sourcesContent":["import {\n type ObjectLiteralExpression,\n Project,\n type SourceFile,\n SyntaxKind,\n} from 'ts-morph';\n\n/**\n * Checks if a module is already imported or required in the source file.\n */\nconst isModuleImported = (\n sourceFile: SourceFile,\n moduleName: string\n): boolean => {\n const hasImport = sourceFile\n .getImportDeclarations()\n .some((i) => i.getModuleSpecifierValue() === moduleName);\n\n const hasRequire = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .some((c) => {\n const expression = c.getExpression();\n return (\n expression.getText() === 'require' &&\n c\n .getArguments()[0]\n ?.asKind(SyntaxKind.StringLiteral)\n ?.getLiteralValue() === moduleName\n );\n });\n\n return hasImport || hasRequire;\n};\n\n/**\n * Checks if the file should be treated as CommonJS.\n */\nconst isCJS = (content: string, extension: string): boolean => {\n if (extension === 'cjs') return true;\n if (['mjs', 'ts'].includes(extension)) return false;\n\n return (\n content.includes('module.exports') &&\n !content.includes('import ') &&\n !content.includes('export ')\n );\n};\n\n/**\n * Updates a Vite configuration file to include the Intlayer plugin.\n * @param content The content of the vite.config file\n * @param extension The file extension (ts, js, mjs, cjs)\n * @returns The updated content\n */\nexport const updateViteConfig = (\n content: string,\n extension: string\n): string => {\n const project = new Project({ useInMemoryFileSystem: true });\n const sourceFile = project.createSourceFile(\n `vite.config.${extension}`,\n content\n );\n\n const isCJSFile = isCJS(content, extension);\n\n // Add import if missing\n const hasIntlayerImport = isModuleImported(sourceFile, 'vite-intlayer');\n\n if (!hasIntlayerImport) {\n if (isCJSFile) {\n sourceFile.insertVariableStatement(0, {\n declarationKind: 'const' as any,\n declarations: [\n {\n name: '{ intlayer }',\n initializer: 'require(\"vite-intlayer\")',\n },\n ],\n });\n } else {\n sourceFile.addImportDeclaration({\n moduleSpecifier: 'vite-intlayer',\n namedImports: ['intlayer'],\n });\n }\n }\n\n // Find the configuration object\n let configObject: ObjectLiteralExpression | undefined;\n\n // Case: export default defineConfig({...})\n const exportDefault = sourceFile.getExportAssignment(\n (e) => !e.isExportEquals()\n );\n if (exportDefault) {\n const expression = exportDefault.getExpression();\n\n if (expression.getKind() === SyntaxKind.CallExpression) {\n const call = expression.asKind(SyntaxKind.CallExpression);\n\n if (call?.getExpression().getText() === 'defineConfig') {\n const arg = call.getArguments()[0];\n\n if (arg?.getKind() === SyntaxKind.ObjectLiteralExpression) {\n configObject = arg.asKind(SyntaxKind.ObjectLiteralExpression);\n }\n }\n } else if (expression.getKind() === SyntaxKind.ObjectLiteralExpression) {\n // Case: export default {...}\n configObject = expression.asKind(SyntaxKind.ObjectLiteralExpression);\n } else if (expression.getKind() === SyntaxKind.Identifier) {\n // Case: const config = {...}; export default config;\n const identifier = expression.asKind(SyntaxKind.Identifier);\n const definitions = identifier?.getDefinitions();\n\n if (definitions && definitions.length > 0) {\n const node = definitions[0].getDeclarationNode();\n\n if (node?.getKind() === SyntaxKind.VariableDeclaration) {\n const init = node\n .asKind(SyntaxKind.VariableDeclaration)\n ?.getInitializer();\n\n if (init?.getKind() === SyntaxKind.ObjectLiteralExpression) {\n configObject = init.asKind(SyntaxKind.ObjectLiteralExpression);\n }\n }\n }\n }\n }\n\n // Case: module.exports = {...}\n if (!configObject) {\n const expressionStatements = sourceFile.getStatements();\n for (const statement of expressionStatements) {\n if (statement.getKind() === SyntaxKind.ExpressionStatement) {\n const expr = statement\n .asKind(SyntaxKind.ExpressionStatement)\n ?.getExpression();\n\n if (expr?.getKind() === SyntaxKind.BinaryExpression) {\n const binary = expr.asKind(SyntaxKind.BinaryExpression);\n\n if (\n binary?.getLeft().getText() === 'module.exports' &&\n binary.getOperatorToken().getKind() === SyntaxKind.EqualsToken\n ) {\n const right = binary.getRight();\n\n if (right.getKind() === SyntaxKind.ObjectLiteralExpression) {\n configObject = right.asKind(SyntaxKind.ObjectLiteralExpression);\n } else if (right.getKind() === SyntaxKind.CallExpression) {\n // Case: module.exports = defineConfig({...})\n const call = right.asKind(SyntaxKind.CallExpression);\n\n if (call?.getExpression().getText() === 'defineConfig') {\n const arg = call.getArguments()[0];\n\n if (arg?.getKind() === SyntaxKind.ObjectLiteralExpression) {\n configObject = arg.asKind(SyntaxKind.ObjectLiteralExpression);\n }\n }\n } else if (right.getKind() === SyntaxKind.Identifier) {\n // Case: const config = {...}; module.exports = config;\n const identifier = right.asKind(SyntaxKind.Identifier);\n const definitions = identifier?.getDefinitions();\n\n if (definitions && definitions.length > 0) {\n const node = definitions[0].getDeclarationNode();\n\n if (node?.getKind() === SyntaxKind.VariableDeclaration) {\n const init = node\n .asKind(SyntaxKind.VariableDeclaration)\n ?.getInitializer();\n\n if (init?.getKind() === SyntaxKind.ObjectLiteralExpression) {\n configObject = init.asKind(\n SyntaxKind.ObjectLiteralExpression\n );\n }\n }\n }\n }\n }\n }\n }\n }\n }\n\n // 3. Update plugins array\n if (configObject) {\n let pluginsProp = configObject.getProperty('plugins');\n\n if (!pluginsProp) {\n configObject.addPropertyAssignment({\n name: 'plugins',\n initializer: '[]',\n });\n pluginsProp = configObject.getProperty('plugins');\n }\n\n if (pluginsProp?.getKind() === SyntaxKind.PropertyAssignment) {\n const initializer = pluginsProp\n .asKind(SyntaxKind.PropertyAssignment)\n ?.getInitializer();\n\n if (initializer?.getKind() === SyntaxKind.ArrayLiteralExpression) {\n const array = initializer.asKind(SyntaxKind.ArrayLiteralExpression);\n const hasIntlayer = array\n ?.getElements()\n .some((el) => el.getText().includes('intlayer('));\n\n if (!hasIntlayer) {\n array?.addElement('intlayer()');\n }\n }\n }\n }\n\n return sourceFile.getFullText();\n};\n\n/**\n * Updates a Next.js configuration file to wrap the export with withIntlayer.\n * @param content The content of the next.config file\n * @param extension The file extension (ts, js, mjs, cjs)\n * @returns The updated content\n */\nexport const updateNextConfig = (\n content: string,\n extension: string\n): string => {\n const project = new Project({ useInMemoryFileSystem: true });\n const sourceFile = project.createSourceFile(\n `next.config.${extension}`,\n content\n );\n\n const isCJSFile = isCJS(content, extension);\n\n // 1. Add import if missing\n const hasIntlayerImport = isModuleImported(\n sourceFile,\n 'next-intlayer/server'\n );\n\n if (!hasIntlayerImport) {\n if (isCJSFile) {\n sourceFile.insertVariableStatement(0, {\n declarationKind: 'const' as any,\n declarations: [\n {\n name: '{ withIntlayer }',\n initializer: 'require(\"next-intlayer/server\")',\n },\n ],\n });\n } else {\n sourceFile.addImportDeclaration({\n moduleSpecifier: 'next-intlayer/server',\n namedImports: ['withIntlayer'],\n });\n }\n }\n\n // 2. Wrap export\n let updated = false;\n\n // Case: export default ...\n const exportDefault = sourceFile.getExportAssignment(\n (e) => !e.isExportEquals()\n );\n if (exportDefault) {\n const expression = exportDefault.getExpression();\n\n if (!expression.getText().includes('withIntlayer')) {\n exportDefault.setExpression(`withIntlayer(${expression.getText()})`);\n updated = true;\n }\n }\n\n // Case: module.exports = ...\n if (!updated) {\n const expressionStatements = sourceFile.getStatements();\n for (const statement of expressionStatements) {\n if (statement.getKind() === SyntaxKind.ExpressionStatement) {\n const expr = statement\n .asKind(SyntaxKind.ExpressionStatement)\n ?.getExpression();\n\n if (expr?.getKind() === SyntaxKind.BinaryExpression) {\n const binary = expr.asKind(SyntaxKind.BinaryExpression);\n\n if (\n binary?.getLeft().getText() === 'module.exports' &&\n binary.getOperatorToken().getKind() === SyntaxKind.EqualsToken\n ) {\n const right = binary.getRight();\n\n if (!right.getText().includes('withIntlayer')) {\n right.replaceWithText(`withIntlayer(${right.getText()})`);\n updated = true;\n }\n }\n }\n }\n }\n }\n\n return sourceFile.getFullText();\n};\n"],"mappings":"mDAUA,MAAM,GACJ,EACA,IACY,CACZ,IAAM,EAAY,EACf,uBAAuB,CACvB,KAAM,GAAM,EAAE,yBAAyB,GAAK,EAAW,CAEpD,EAAa,EAChB,qBAAqB,EAAW,eAAe,CAC/C,KAAM,GACc,EAAE,eAAe,CAEvB,SAAS,GA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SAAS,GAAK,EAAW,iBAAkB,CACnD,IAAM,EAAS,EAAK,OAAO,EAAW,iBAAiB,CAEvD,GACE,GAAQ,SAAS,CAAC,SAAS,GAAK,kBAChC,EAAO,kBAAkB,CAAC,SAAS,GAAK,EAAW,YACnD,CACA,IAAM,EAAQ,EAAO,UAAU,CAE1B,EAAM,SAAS,CAAC,SAAS,eAAe,GAC3C,EAAM,gBAAgB,gBAAgB,EAAM,SAAS,CAAC,GAAG,CACzD,EAAU,OAQtB,OAAO,EAAW,aAAa"}
1
+ {"version":3,"file":"configManipulation.mjs","names":[],"sources":["../../../../src/init/utils/configManipulation.ts"],"sourcesContent":["import * as recast from 'recast';\n\nconst b = recast.types.builders;\nconst n = recast.types.namedTypes;\n\n/**\n * Checks if a module is already imported or required.\n */\nconst isModuleImported = (ast: any, moduleName: string): boolean => {\n let found = false;\n recast.visit(ast, {\n visitImportDeclaration(path) {\n if (path.node.source.value === moduleName) {\n found = true;\n }\n return false;\n },\n visitCallExpression(path) {\n const { callee, arguments: args } = path.node;\n\n if (\n n.Identifier.check(callee) &&\n callee.name === 'require' &&\n args[0] &&\n n.StringLiteral.check(args[0]) &&\n args[0].value === moduleName\n ) {\n found = true;\n }\n return false;\n },\n });\n return found;\n};\n\n/**\n * Injects import/require at the top of the file.\n */\nconst injectImport = (\n ast: any,\n isCJS: boolean,\n importName: string,\n source: string\n) => {\n if (isModuleImported(ast, source)) return;\n\n const declaration = isCJS\n ? b.variableDeclaration('const', [\n b.variableDeclarator(\n b.objectPattern([\n b.objectProperty.from({\n key: b.identifier(importName),\n value: b.identifier(importName),\n shorthand: true,\n }),\n ]),\n b.callExpression(b.identifier('require'), [b.stringLiteral(source)])\n ),\n ])\n : b.importDeclaration(\n [b.importSpecifier(b.identifier(importName))],\n b.stringLiteral(source)\n );\n\n ast.program.body.unshift(declaration);\n};\n\nexport const updateViteConfig = (\n content: string,\n extension: string\n): string => {\n const ast = recast.parse(content, {\n parser: require('recast/parsers/typescript'),\n });\n const isCJSFile =\n extension === 'cjs' ||\n (content.includes('module.exports') && !content.includes('import '));\n\n injectImport(ast, isCJSFile, 'intlayer', 'vite-intlayer');\n\n const updateConfigObject = (objExpr: any) => {\n if (\n !objExpr ||\n (objExpr.type !== 'ObjectExpression' &&\n !n.ObjectExpression.check(objExpr))\n )\n return;\n\n let pluginsProp = objExpr.properties.find((p: any) => {\n if (!p || !p.key) return false;\n const keyName = p.key.name || p.key.value;\n return keyName === 'plugins';\n }) as any;\n\n if (!pluginsProp) {\n pluginsProp = b.property(\n 'init',\n b.identifier('plugins'),\n b.arrayExpression([])\n );\n objExpr.properties.push(pluginsProp);\n }\n\n const pluginsValue = pluginsProp.value;\n\n if (\n pluginsValue &&\n (pluginsValue.type === 'ArrayExpression' ||\n n.ArrayExpression.check(pluginsValue))\n ) {\n const hasPlugin = pluginsValue.elements.some((el: any) => {\n const callee = el?.callee;\n\n if (!callee) return false;\n const name = callee.name || callee.id?.name;\n return name === 'intlayer' || name === 'il';\n });\n\n if (!hasPlugin) {\n pluginsValue.elements.push(\n b.callExpression(b.identifier('intlayer'), [])\n );\n }\n }\n };\n\n recast.visit(ast, {\n visitExportDefaultDeclaration(path) {\n const decl = path.node.declaration;\n\n if (n.ObjectExpression.check(decl)) {\n updateConfigObject(decl);\n } else if (\n n.CallExpression.check(decl) &&\n n.Identifier.check(decl.callee) &&\n decl.callee.name === 'defineConfig'\n ) {\n if (n.ObjectExpression.check(decl.arguments[0])) {\n updateConfigObject(decl.arguments[0]);\n }\n } else if (n.Identifier.check(decl)) {\n const name = decl.name;\n ast.program.body.forEach((stmt: any) => {\n if (n.VariableDeclaration.check(stmt)) {\n stmt.declarations.forEach((vdecl: any) => {\n if (\n n.VariableDeclarator.check(vdecl) &&\n n.Identifier.check(vdecl.id) &&\n vdecl.id.name === name &&\n n.ObjectExpression.check(vdecl.init)\n ) {\n updateConfigObject(vdecl.init);\n }\n });\n }\n });\n }\n return false;\n },\n visitAssignmentExpression(path) {\n const { left, right } = path.node;\n\n if (\n n.MemberExpression.check(left) &&\n recast.print(left).code === 'module.exports'\n ) {\n if (n.ObjectExpression.check(right)) {\n updateConfigObject(right);\n } else if (\n n.CallExpression.check(right) &&\n n.Identifier.check(right.callee) &&\n right.callee.name === 'defineConfig'\n ) {\n if (n.ObjectExpression.check(right.arguments[0])) {\n updateConfigObject(right.arguments[0]);\n }\n }\n }\n return false;\n },\n });\n\n return recast.print(ast).code;\n};\n\nexport const updateNextConfig = (\n content: string,\n extension: string\n): string => {\n const ast = recast.parse(content, {\n parser: require('recast/parsers/typescript'),\n });\n const isCJSFile = extension === 'cjs' || content.includes('module.exports');\n\n injectImport(ast, isCJSFile, 'withIntlayer', 'next-intlayer/server');\n\n recast.visit(ast, {\n visitExportDefaultDeclaration(path) {\n const declaration = path.node.declaration;\n if (\n n.Expression.check(declaration) &&\n !(\n n.CallExpression.check(declaration) &&\n n.Identifier.check(declaration.callee) &&\n declaration.callee.name === 'withIntlayer'\n )\n ) {\n path\n .get('declaration')\n .replace(\n b.callExpression(b.identifier('withIntlayer'), [declaration as any])\n );\n }\n return false;\n },\n visitAssignmentExpression(path) {\n const { left, right } = path.node;\n\n if (\n n.MemberExpression.check(left) &&\n recast.print(left).code === 'module.exports' &&\n !(\n n.CallExpression.check(right) &&\n n.Identifier.check(right.callee) &&\n right.callee.name === 'withIntlayer'\n )\n ) {\n path\n .get('right')\n .replace(b.callExpression(b.identifier('withIntlayer'), [right]));\n }\n return false;\n },\n });\n\n return recast.print(ast).code;\n};\n"],"mappings":"0FAEA,MAAM,EAAI,EAAO,MAAM,SACjB,EAAI,EAAO,MAAM,WAKjB,GAAoB,EAAU,IAAgC,CAClE,IAAI,EAAQ,GAuBZ,OAtBA,EAAO,MAAM,EAAK,CAChB,uBAAuB,EAAM,CAI3B,OAHI,EAAK,KAAK,OAAO,QAAU,IAC7B,EAAQ,IAEH,IAET,oBAAoB,EAAM,CACxB,GAAM,CAAE,SAAQ,UAAW,GAAS,EAAK,KAWzC,OARE,EA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AS,gBAElB,EAAE,iBAAiB,MAAM,EAAM,UAAU,GAAG,EAC9C,EAAmB,EAAM,UAAU,GAAG,EAIrC,IAEV,CAAC,CAEK,EAAO,MAAM,EAAI,CAAC,MAGd,GACX,EACA,IACW,CACX,IAAM,EAAM,EAAO,MAAM,EAAS,CAChC,OAAA,EAAgB,4BAA4B,CAC7C,CAAC,CA4CF,OAzCA,EAAa,EAFK,IAAc,OAAS,EAAQ,SAAS,iBAAiB,CAE9C,eAAgB,uBAAuB,CAEpE,EAAO,MAAM,EAAK,CAChB,8BAA8B,EAAM,CAClC,IAAM,EAAc,EAAK,KAAK,YAe9B,OAbE,EAAE,WAAW,MAAM,EAAY,EAC/B,EACE,EAAE,eAAe,MAAM,EAAY,EACnC,EAAE,WAAW,MAAM,EAAY,OAAO,EACtC,EAAY,OAAO,OAAS,iBAG9B,EACG,IAAI,cAAc,CAClB,QACC,EAAE,eAAe,EAAE,WAAW,eAAe,CAAE,CAAC,EAAmB,CAAC,CACrE,CAEE,IAET,0BAA0B,EAAM,CAC9B,GAAM,CAAE,OAAM,SAAU,EAAK,KAe7B,OAZE,EAAE,iBAAiB,MAAM,EAAK,EAC9B,EAAO,MAAM,EAAK,CAAC,OAAS,kBAC5B,EACE,EAAE,eAAe,MAAM,EAAM,EAC7B,EAAE,WAAW,MAAM,EAAM,OAAO,EAChC,EAAM,OAAO,OAAS,iBAGxB,EACG,IAAI,QAAQ,CACZ,QAAQ,EAAE,eAAe,EAAE,WAAW,eAAe,CAAE,CAAC,EAAM,CAAC,CAAC,CAE9D,IAEV,CAAC,CAEK,EAAO,MAAM,EAAI,CAAC"}
@@ -0,0 +1,2 @@
1
+ import{PLATFORMS_METADATA as e}from"../installSkills/index.mjs";import t from"node:path";import{promises as n}from"node:fs";import r from"node:os";const i=process.platform===`win32`?t.join(process.env.APPDATA||``,`Claude`,`claude_desktop_config.json`):t.join(r.homedir(),`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`),a=async(r,a,o)=>{let s,c=`mcpServers`;if(a===`Claude`)s=i;else{let n=t.dirname(e[a].dir);s=t.join(r,n,`mcp.json`),a===`VSCode`&&(c=`servers`)}await n.mkdir(t.dirname(s),{recursive:!0});let l={};try{let e=await n.readFile(s,`utf-8`);l=JSON.parse(e)}catch{}if(l[c]||(l[c]={}),o===`stdio`){let e={command:`npx`,args:[`-y`,`@intlayer/mcp`]};a===`VSCode`&&(e.type=`stdio`),l[c].intlayer=e}else{let e={url:`https://mcp.intlayer.org`};a===`VSCode`?e.type=`sse`:e.transport=`sse`,l[c].intlayer=e}return await n.writeFile(s,JSON.stringify(l,null,2),`utf-8`),`MCP server configuration updated in ${s}`};export{a as installMCP};
2
+ //# sourceMappingURL=installMCP.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"installMCP.mjs","names":["fs"],"sources":["../../../src/installMCP/installMCP.ts"],"sourcesContent":["import { promises as fs } from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { PLATFORMS_METADATA, type Platform } from '../installSkills';\n\nexport type MCPTransport = 'stdio' | 'sse';\n\nconst MCP_CONFIG_FILENAME = 'mcp.json';\n\nconst CLAUDE_DESKTOP_CONFIG_PATH =\n process.platform === 'win32'\n ? path.join(\n process.env.APPDATA || '',\n 'Claude',\n 'claude_desktop_config.json'\n )\n : path.join(\n os.homedir(),\n 'Library',\n 'Application Support',\n 'Claude',\n 'claude_desktop_config.json'\n );\n\n/**\n * Installs the Intlayer MCP server configuration for a specific platform.\n */\nexport const installMCP = async (\n projectRoot: string,\n platform: Platform,\n transport: MCPTransport\n): Promise<string> => {\n let configPath: string;\n let configKey = 'mcpServers';\n\n if (platform === 'Claude') {\n configPath = CLAUDE_DESKTOP_CONFIG_PATH;\n } else {\n const relativeDir = path.dirname(PLATFORMS_METADATA[platform].dir); // e.g. .cursor or .vscode\n configPath = path.join(projectRoot, relativeDir, MCP_CONFIG_FILENAME);\n\n if (platform === 'VSCode') {\n configKey = 'servers';\n }\n }\n\n // Ensure the configuration directory exists\n await fs.mkdir(path.dirname(configPath), { recursive: true });\n\n let config: any = {};\n try {\n const content = await fs.readFile(configPath, 'utf-8');\n config = JSON.parse(content);\n } catch {\n // File doesn't exist or is invalid JSON, start fresh\n }\n\n if (!config[configKey]) {\n config[configKey] = {};\n }\n\n if (transport === 'stdio') {\n const mcpConfig: any = {\n command: 'npx',\n args: ['-y', '@intlayer/mcp'],\n };\n\n if (platform === 'VSCode') {\n mcpConfig.type = 'stdio';\n }\n\n config[configKey].intlayer = mcpConfig;\n } else {\n const mcpConfig: any = {\n url: 'https://mcp.intlayer.org',\n };\n\n if (platform === 'VSCode') {\n mcpConfig.type = 'sse';\n } else {\n mcpConfig.transport = 'sse';\n }\n\n config[configKey].intlayer = mcpConfig;\n }\n\n await fs.writeFile(configPath, JSON.stringify(config, null, 2), 'utf-8');\n\n return `MCP server configuration updated in ${configPath}`;\n};\n"],"mappings":"mJAOA,MAEM,EACJ,QAAQ,WAAa,QACjB,EAAK,KACH,QAAQ,IAAI,SAAW,GACvB,SACA,6BACD,CACD,EAAK,KACH,EAAG,SAAS,CACZ,UACA,sBACA,SACA,6BACD,CAKM,EAAa,MACxB,EACA,EACA,IACoB,CACpB,IAAI,EACA,EAAY,aAEhB,GAAI,IAAa,SACf,EAAa,MACR,CACL,IAAM,EAAc,EAAK,QAAQ,EAAmB,GAAU,IAAI,CAClE,EAAa,EAAK,KAAK,EAAa,EAAa,WAAoB,CAEjE,IAAa,WACf,EAAY,WAKhB,MAAMA,EAAG,MAAM,EAAK,QAAQ,EAAW,CAAE,CAAE,UAAW,GAAM,CAAC,CAE7D,IAAI,EAAc,EAAE,CACpB,GAAI,CACF,IAAM,EAAU,MAAMA,EAAG,SAAS,EAAY,QAAQ,CACtD,EAAS,KAAK,MAAM,EAAQ,MACtB,EAQR,GAJK,EAAO,KACV,EAAO,GAAa,EAAE,EAGpB,IAAc,QAAS,CACzB,IAAM,EAAiB,CACrB,QAAS,MACT,KAAM,CAAC,KAAM,gBAAgB,CAC9B,CAEG,IAAa,WACf,EAAU,KAAO,SAGnB,EAAO,GAAW,SAAW,MACxB,CACL,IAAM,EAAiB,CACrB,IAAK,2BACN,CAEG,IAAa,SACf,EAAU,KAAO,MAEjB,EAAU,UAAY,MAGxB,EAAO,GAAW,SAAW,EAK/B,OAFA,MAAMA,EAAG,UAAU,EAAY,KAAK,UAAU,EAAQ,KAAM,EAAE,CAAE,QAAQ,CAEjE,uCAAuC"}
@@ -1,2 +1,2 @@
1
- import{readAsset as e}from"../_virtual/_utils_asset.mjs";import t from"node:path";import{promises as n}from"node:fs";import{getMarkdownMetadata as r}from"@intlayer/core/markdown";const i={Usage:`How to use Intlayer in your project`,RemoteContent:`How to use Intlayer with Remote/CMS/Server-side content`,Config:`Intlayer configuration documentation`,Content:`Reference for all Intlayer content node types (t, enu, etc.)`,React:`React-specific syntax and hooks usage`,Angular:`Angular-specific syntax and Injectable Function usage`,NextJS:`Next.js-specific usage (Server & Client components)`,Vue:`Vue-specific composables and syntax`,Preact:`Preact-specific syntax and hooks usage`,Solid:`Integrates Intlayer internationalization with SolidJS components. Use when the user asks to "setup SolidJS i18n", use the "useIntlayer" hook in Solid, or manage locales in a SolidJS application.`,Svelte:`Svelte-specific stores and syntax`,Astro:`Astro-specific usage and getIntlayer`,CLI:`Intlayer CLI commands and usage`,Compiler:`Intlayer Compiler setup and usage for automatic content extraction without .content files`},a=Object.keys(i),o={},s={Cursor:`.cursor/skills`,Windsurf:`.windsurf/skills`,Trae:`.trae/skills`,OpenCode:`.opencode/skills`,GitHub:`.github/skills`,Claude:`.claude/skills`,VSCode:`.vscode/skills`,Antigravity:`.agent/skills`,Augment:`.augment/skills`,OpenClaw:`skills`,Cline:`.cline/skills`,CodeBuddy:`.codebuddy/skills`,CommandCode:`.commandcode/skills`,Continue:`.continue/skills`,Crush:`.crush/skills`,Droid:`.factory/skills`,Goose:`.goose/skills`,Junie:`.junie/skills`,IFlow:`.iflow/skills`,KiloCode:`.kilocode/skills`,Kiro:`.kiro/skills`,Kode:`.kode/skills`,MCPJam:`.mcpjam/skills`,MistralVibe:`.vibe/skills`,Mux:`.mux/skills`,OpenHands:`.openhands/skills`,Pi:`.pi/skills`,Qoder:`.qoder/skills`,Qwen:`.qwen/skills`,RooCode:`.roo/skills`,TraeCN:`.trae/skills`,Zencoder:`.zencoder/skills`,Neovate:`.neovate/skills`,Pochi:`.pochi/skills`,Other:`skills`},c=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),l=t=>{let n=`./skills/${o[t]??c(t)}.md`;try{return e(n)}catch{return console.warn(`Warning: Could not read asset for skill: ${t} at ${n}`),``}},u=()=>{try{return e(`./LICENCE.md`)}catch{return console.warn(`Warning: Could not read LICENCE.md asset`),``}},d=async e=>{let t=await fetch(e);if(!t.ok)throw Error(`Failed to fetch ${e}: ${t.statusText}`);return t.text()},f=async(e,i,a)=>{let f=s[i]??`skills`,p=t.join(e,f),m=i!==`VSCode`;await n.mkdir(p,{recursive:!0});let h=[],g=u();for(let e of a){let i=`intlayer-${o[e]??c(e)}`,a=l(e);if(!a)continue;let s=Array.from(new Set(a.match(/https:\/\/intlayer\.org\/doc\/[^\s)]+\.md/g)||[]));if(m){let o=t.join(p,i),c=t.join(o,`references`);await n.mkdir(c,{recursive:!0}),g&&await n.writeFile(t.join(o,`LICENCE.md`),g,`utf-8`);let l=a,u=s.map(async t=>{try{let e=await d(t),n=r(e),i=``;return i=Array.isArray(n.slugs)?n.slugs.filter(e=>e!==`doc`).join(`_`):new URL(t).pathname.split(`/`).filter(e=>e&&e!==`doc`).map(e=>e.replace(`.md`,``)).join(`_`),i=i?`${i}.md`:`index.md`,{url:t,localRefPath:`references/${i}`,fileName:i,content:e,success:!0}}catch(n){return console.warn(`Warning: Failed to download ref ${t} for skill ${e}`,n),{url:t,success:!1}}}),f=await Promise.all(u);for(let e of f)e.success&&e.fileName&&e.content&&e.localRefPath&&(await n.writeFile(t.join(c,e.fileName),e.content,`utf-8`),l=l.replaceAll(e.url,e.localRefPath));let m=t.join(o,`SKILL.md`);await n.writeFile(m,l,`utf-8`),h.push(`${i}/SKILL.md`)}else{let e=`${i}.md`,r=t.join(p,e);await n.writeFile(r,a,`utf-8`),h.push(e)}}return h.length===0?`No skill files were created. Check your asset paths.`:`Created ${h.length} skills in ${p}`};export{a as SKILLS,i as SKILLS_METADATA,f as installSkills};
1
+ import{readAsset as e}from"../_virtual/_utils_asset.mjs";import t from"node:path";import{promises as n}from"node:fs";import{getMarkdownMetadata as r}from"@intlayer/core/markdown";const i={Config:`Intlayer configuration documentation`,Content:`Reference for all Intlayer content node types (t, enu, etc.)`,Usage:`How to use Intlayer in your project`,CLI:`Intlayer CLI commands and usage`,Compiler:`Intlayer Compiler setup and usage for automatic content extraction without .content files`,RemoteContent:`How to use Intlayer with Remote/CMS/Server-side content`,NextJS:`Next.js-specific usage (Server & Client components)`,React:`React-specific syntax and hooks usage`,Vue:`Vue-specific composables and syntax`,Svelte:`Svelte-specific stores and syntax`,Angular:`Angular-specific syntax and Injectable Function usage`,Preact:`Preact-specific syntax and hooks usage`,Solid:`Integrates Intlayer internationalization with SolidJS components. Use when the user asks to "setup SolidJS i18n", use the "useIntlayer" hook in Solid, or manage locales in a SolidJS application.`,Astro:`Astro-specific usage and getIntlayer`},a=Object.keys(i),o=e=>{let t=[`Usage`,`Content`,`Config`,`CLI`,`Compiler`];return e.next&&t.push(`NextJS`),(e.react||!e.next)&&t.push(`React`),e.preact&&t.push(`Preact`),e[`solid-js`]&&t.push(`Solid`),(e.vue||e.nuxt)&&t.push(`Vue`),(e.svelte||e[`@sveltejs/kit`])&&t.push(`Svelte`),e.astro&&t.push(`Astro`),t},s={Cursor:{label:`Cursor`,dir:`.cursor/skills`,check:()=>process.env.CURSOR===`true`||process.env.TERM_PROGRAM===`cursor`},Windsurf:{label:`Windsurf`,dir:`.windsurf/skills`,check:()=>process.env.WINDSURF===`true`||process.env.TERM_PROGRAM===`windsurf`},Trae:{label:`Trae`,dir:`.trae/skills`,check:()=>process.env.TRAE===`true`||process.env.TERM_PROGRAM===`trae`},TraeCN:{label:`Trae CN`,dir:`.trae/skills`,check:()=>process.env.TRAE_CN===`true`},VSCode:{label:`VS Code`,dir:`.vscode/skills`,check:()=>process.env.VSCODE===`true`||process.env.TERM_PROGRAM===`vscode`},OpenCode:{label:`OpenCode`,dir:`.opencode/skills`,check:()=>process.env.OPENCODE===`true`},Claude:{label:`Claude Code`,dir:`.claude/skills`,check:()=>process.env.CLAUDE===`true`},GitHub:{label:`GitHub Copilot Workspace`,dir:`.github/skills`,check:()=>process.env.GITHUB_ACTIONS===`true`||!!process.env.GITHUB_WORKSPACE},Antigravity:{label:`Antigravity`,dir:`.agent/skills`},Augment:{label:`Augment`,dir:`.augment/skills`},OpenClaw:{label:`OpenClaw`,dir:`skills`},Cline:{label:`Cline`,dir:`.cline/skills`},CodeBuddy:{label:`CodeBuddy`,dir:`.codebuddy/skills`},CommandCode:{label:`Command Code`,dir:`.commandcode/skills`},Continue:{label:`Continue`,dir:`.continue/skills`},Crush:{label:`Crush`,dir:`.crush/skills`},Droid:{label:`Droid`,dir:`.factory/skills`},Goose:{label:`Goose`,dir:`.goose/skills`},IFlow:{label:`iFlow CLI`,dir:`.iflow/skills`},Junie:{label:`Junie`,dir:`.junie/skills`},KiloCode:{label:`Kilo Code`,dir:`.kilocode/skills`},Kiro:{label:`Kiro CLI`,dir:`.kiro/skills`},Kode:{label:`Kode`,dir:`.kode/skills`},MCPJam:{label:`MCPJam`,dir:`.mcpjam/skills`},MistralVibe:{label:`Mistral Vibe`,dir:`.vibe/skills`},Mux:{label:`Mux`,dir:`.mux/skills`},OpenHands:{label:`OpenHands`,dir:`.openhands/skills`},Pi:{label:`Pi`,dir:`.pi/skills`},Qoder:{label:`Qoder`,dir:`.qoder/skills`},Qwen:{label:`Qwen Code`,dir:`.qwen/skills`},RooCode:{label:`Roo Code`,dir:`.roo/skills`},Zencoder:{label:`Zencoder`,dir:`.zencoder/skills`},Neovate:{label:`Neovate`,dir:`.neovate/skills`},Pochi:{label:`Pochi`,dir:`.pochi/skills`},Other:{label:`Other`,dir:`skills`}},c=Object.keys(s),l={},u=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),d=t=>{let n=`./skills/${l[t]??u(t)}.md`;try{return e(n)}catch{return console.warn(`Warning: Could not read asset for skill: ${t} at ${n}`),``}},f=()=>{try{return e(`./LICENCE.md`)}catch{return console.warn(`Warning: Could not read LICENCE.md asset`),``}},p=async e=>{let t=await fetch(e);if(!t.ok)throw Error(`Failed to fetch ${e}: ${t.statusText}`);return t.text()},m=async(e,i,a)=>{let o=s[i].dir??`skills`,c=t.join(e,o);await n.mkdir(c,{recursive:!0});let m=[],h=f();for(let e of a){let i=`intlayer-${l[e]??u(e)}`,a=d(e);if(!a)continue;let o=Array.from(new Set(a.match(/https:\/\/intlayer\.org\/doc\/[^\s)]+\.md/g)||[])),s=t.join(c,i),f=t.join(s,`references`);await n.mkdir(f,{recursive:!0}),h&&await n.writeFile(t.join(s,`LICENCE.md`),h,`utf-8`);let g=a,_=o.map(async t=>{try{let e=await p(t),n=r(e),i=``;return i=Array.isArray(n.slugs)?n.slugs.filter(e=>e!==`doc`).join(`_`):new URL(t).pathname.split(`/`).filter(e=>e&&e!==`doc`).map(e=>e.replace(`.md`,``)).join(`_`),i=i?`${i}.md`:`index.md`,{url:t,localRefPath:`references/${i}`,fileName:i,content:e,success:!0}}catch(n){return console.warn(`Warning: Failed to download ref ${t} for skill ${e}`,n),{url:t,success:!1}}}),v=await Promise.all(_);for(let e of v)e.success&&e.fileName&&e.content&&e.localRefPath&&(await n.writeFile(t.join(f,e.fileName),e.content,`utf-8`),g=g.replaceAll(e.url,e.localRefPath));let y=t.join(s,`SKILL.md`);await n.writeFile(y,g,`utf-8`),m.push(`${i}/SKILL.md`)}return m.length===0?`No skill files were created. Check your asset paths.`:`Created ${m.length} skills in ${c}`};export{c as PLATFORMS,s as PLATFORMS_METADATA,a as SKILLS,i as SKILLS_METADATA,o as getInitialSkills,m as installSkills};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["fs"],"sources":["../../../src/installSkills/index.ts"],"sourcesContent":["import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { readAsset } from 'utils:asset';\nimport { getMarkdownMetadata } from '@intlayer/core/markdown';\n\nexport const SKILLS_METADATA = {\n Usage: 'How to use Intlayer in your project',\n RemoteContent: 'How to use Intlayer with Remote/CMS/Server-side content',\n Config: 'Intlayer configuration documentation',\n Content: 'Reference for all Intlayer content node types (t, enu, etc.)',\n React: 'React-specific syntax and hooks usage',\n Angular: 'Angular-specific syntax and Injectable Function usage',\n NextJS: 'Next.js-specific usage (Server & Client components)',\n Vue: 'Vue-specific composables and syntax',\n Preact: 'Preact-specific syntax and hooks usage',\n Solid:\n 'Integrates Intlayer internationalization with SolidJS components. Use when the user asks to \"setup SolidJS i18n\", use the \"useIntlayer\" hook in Solid, or manage locales in a SolidJS application.',\n Svelte: 'Svelte-specific stores and syntax',\n Astro: 'Astro-specific usage and getIntlayer',\n CLI: 'Intlayer CLI commands and usage',\n Compiler:\n 'Intlayer Compiler setup and usage for automatic content extraction without .content files',\n} as const;\n\nexport const SKILLS = Object.keys(\n SKILLS_METADATA\n) as (keyof typeof SKILLS_METADATA)[];\n\nexport type Skill = (typeof SKILLS)[number];\n\n/**\n * Maps specific skill keys to special filenames if they differ from standard snake_case.\n */\nconst SKILL_FILENAME_MAP: Partial<Record<Skill, string>> = {};\n\n/**\n * Configuration for Platform paths to keep code clean.\n */\nconst PLATFORM_DIRS = {\n Cursor: '.cursor/skills',\n Windsurf: '.windsurf/skills',\n Trae: '.trae/skills',\n OpenCode: '.opencode/skills',\n GitHub: '.github/skills',\n Claude: '.claude/skills',\n VSCode: '.vscode/skills', // Fixed: VSCode usually uses .vscode, not .github\n Antigravity: '.agent/skills',\n Augment: '.augment/skills',\n OpenClaw: 'skills',\n Cline: '.cline/skills',\n CodeBuddy: '.codebuddy/skills',\n CommandCode: '.commandcode/skills',\n Continue: '.continue/skills',\n Crush: '.crush/skills',\n Droid: '.factory/skills',\n Goose: '.goose/skills',\n Junie: '.junie/skills',\n IFlow: '.iflow/skills',\n KiloCode: '.kilocode/skills',\n Kiro: '.kiro/skills',\n Kode: '.kode/skills',\n MCPJam: '.mcpjam/skills',\n MistralVibe: '.vibe/skills',\n Mux: '.mux/skills',\n OpenHands: '.openhands/skills',\n Pi: '.pi/skills',\n Qoder: '.qoder/skills',\n Qwen: '.qwen/skills',\n RooCode: '.roo/skills',\n TraeCN: '.trae/skills',\n Zencoder: '.zencoder/skills',\n Neovate: '.neovate/skills',\n Pochi: '.pochi/skills',\n Other: 'skills',\n};\n\nexport type Platform = keyof typeof PLATFORM_DIRS;\n\n/**\n * Helper to convert CamelCase to kebab-case for directory naming\n */\nconst camelToKebabCase = (str: string) =>\n str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();\n\n/**\n * Reads the raw markdown content for a specific skill from the assets folder.\n */\nconst getSkillContent = (skill: Skill): string => {\n const baseName = SKILL_FILENAME_MAP[skill] ?? camelToKebabCase(skill);\n const fileName = `./skills/${baseName}.md`;\n\n try {\n return readAsset(fileName);\n } catch {\n console.warn(\n `Warning: Could not read asset for skill: ${skill} at ${fileName}`\n );\n return '';\n }\n};\n\n/**\n * Reads the licence content from the assets folder.\n */\nconst getLicenceContent = (): string => {\n try {\n return readAsset('./LICENCE.md');\n } catch {\n console.warn('Warning: Could not read LICENCE.md asset');\n return '';\n }\n};\n\n/**\n * Fetches the content of a URL using native fetch.\n */\nconst fetchUrlContent = async (url: string): Promise<string> => {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`Failed to fetch ${url}: ${response.statusText}`);\n }\n return response.text();\n};\n\n/**\n * Installs skills using the \"Agent Skills\" directory standard.\n * Standard: <PROJECT_ROOT>/<CONFIG_DIR>/skills/<SKILL_NAME>/SKILL.md\n */\nexport const installSkills = async (\n projectRoot: string,\n platform: Platform,\n skills: Skill[]\n): Promise<string> => {\n // 1. Determine destination directory\n const relativeDir = PLATFORM_DIRS[platform] ?? 'skills';\n const skillsBaseDir = path.join(projectRoot, relativeDir);\n\n const useAgentStructure = platform !== 'VSCode';\n\n // Ensure the base directory exists\n await fs.mkdir(skillsBaseDir, { recursive: true });\n\n const createdSkills: string[] = [];\n const licenceContent = getLicenceContent();\n\n for (const skill of skills) {\n const baseName = SKILL_FILENAME_MAP[skill] ?? camelToKebabCase(skill);\n const skillName = `intlayer-${baseName}`;\n const skillContent = getSkillContent(skill);\n\n if (!skillContent) continue;\n\n // Extract unique URLs\n const urls = Array.from(\n new Set(\n skillContent.match(/https:\\/\\/intlayer\\.org\\/doc\\/[^\\s)]+\\.md/g) || []\n )\n );\n\n if (useAgentStructure) {\n // Agent Standard: .../skills/<skill-name>/SKILL.md\n const skillDir = path.join(skillsBaseDir, skillName);\n const referenceDir = path.join(skillDir, 'references');\n\n // Ensure directories exist\n await fs.mkdir(referenceDir, { recursive: true });\n\n // Write License\n if (licenceContent) {\n await fs.writeFile(\n path.join(skillDir, 'LICENCE.md'),\n licenceContent,\n 'utf-8'\n );\n }\n\n let updatedSkillContent = skillContent;\n\n // Parallel download of references\n const downloadPromises = urls.map(async (url) => {\n try {\n const content = await fetchUrlContent(url);\n const metadata = getMarkdownMetadata<{ slugs?: string[] }>(content);\n\n let fileName = '';\n\n // Determine filename from slugs or URL path\n if (Array.isArray(metadata.slugs)) {\n fileName = metadata.slugs\n .filter((slug) => slug !== 'doc')\n .join('_');\n } else {\n const urlPath = new URL(url).pathname;\n fileName = urlPath\n .split('/')\n .filter((part) => part && part !== 'doc')\n .map((part) => part.replace('.md', '')) // Clean extension for joining\n .join('_');\n }\n\n // Ensure it ends with .md\n fileName = fileName ? `${fileName}.md` : 'index.md';\n const localRefPath = `references/${fileName}`;\n\n return {\n url,\n localRefPath,\n fileName,\n content,\n success: true,\n };\n } catch (error) {\n console.warn(\n `Warning: Failed to download ref ${url} for skill ${skill}`,\n error\n );\n return { url, success: false };\n }\n });\n\n const results = await Promise.all(downloadPromises);\n\n // Process results: Write files and update content string\n for (const res of results) {\n if (res.success && res.fileName && res.content && res.localRefPath) {\n // Write the reference file\n await fs.writeFile(\n path.join(referenceDir, res.fileName),\n res.content,\n 'utf-8'\n );\n\n // Update the main content to point to local file\n updatedSkillContent = updatedSkillContent.replaceAll(\n res.url,\n res.localRefPath\n );\n }\n }\n\n // Write the main SKILL.md\n const filePath = path.join(skillDir, 'SKILL.md');\n await fs.writeFile(filePath, updatedSkillContent, 'utf-8');\n createdSkills.push(`${skillName}/SKILL.md`);\n } else {\n // Flat Structure (Generic/VSCode): .../skills/<skill-name>.md\n const fileName = `${skillName}.md`;\n const filePath = path.join(skillsBaseDir, fileName);\n\n await fs.writeFile(filePath, skillContent, 'utf-8');\n createdSkills.push(fileName);\n }\n }\n\n if (createdSkills.length === 0) {\n return `No skill files were created. Check your asset paths.`;\n }\n\n return `Created ${createdSkills.length} skills in ${skillsBaseDir}`;\n};\n"],"mappings":"mLAKA,MAAa,EAAkB,CAC7B,MAAO,sCACP,cAAe,0DACf,OAAQ,uCACR,QAAS,+DACT,MAAO,wCACP,QAAS,wDACT,OAAQ,sDACR,IAAK,sCACL,OAAQ,yCACR,MACE,qMACF,OAAQ,oCACR,MAAO,uCACP,IAAK,kCACL,SACE,4FACH,CAEY,EAAS,OAAO,KAC3B,EACD,CAOK,EAAqD,EAAE,CAKvD,EAAgB,CACpB,OAAQ,iBACR,SAAU,mBACV,KAAM,eACN,SAAU,mBACV,OAAQ,iBACR,OAAQ,iBACR,OAAQ,iBACR,YAAa,gBACb,QAAS,kBACT,SAAU,SACV,MAAO,gBACP,UAAW,oBACX,YAAa,sBACb,SAAU,mBACV,MAAO,gBACP,MAAO,kBACP,MAAO,gBACP,MAAO,gBACP,MAAO,gBACP,SAAU,mBACV,KAAM,eACN,KAAM,eACN,OAAQ,iBACR,YAAa,eACb,IAAK,cACL,UAAW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"version":3,"file":"index.mjs","names":["fs"],"sources":["../../../src/installSkills/index.ts"],"sourcesContent":["import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { readAsset } from 'utils:asset';\nimport { getMarkdownMetadata } from '@intlayer/core/markdown';\n\n/**\n * Metadata for each available documentation skill.\n */\nexport const SKILLS_METADATA = {\n Config: 'Intlayer configuration documentation',\n Content: 'Reference for all Intlayer content node types (t, enu, etc.)',\n Usage: 'How to use Intlayer in your project',\n CLI: 'Intlayer CLI commands and usage',\n Compiler:\n 'Intlayer Compiler setup and usage for automatic content extraction without .content files',\n RemoteContent: 'How to use Intlayer with Remote/CMS/Server-side content',\n NextJS: 'Next.js-specific usage (Server & Client components)',\n React: 'React-specific syntax and hooks usage',\n Vue: 'Vue-specific composables and syntax',\n Svelte: 'Svelte-specific stores and syntax',\n Angular: 'Angular-specific syntax and Injectable Function usage',\n Preact: 'Preact-specific syntax and hooks usage',\n Solid:\n 'Integrates Intlayer internationalization with SolidJS components. Use when the user asks to \"setup SolidJS i18n\", use the \"useIntlayer\" hook in Solid, or manage locales in a SolidJS application.',\n Astro: 'Astro-specific usage and getIntlayer',\n} as const;\n\nexport type Skill = keyof typeof SKILLS_METADATA;\n\nexport const SKILLS = Object.keys(SKILLS_METADATA) as Skill[];\n\nexport const getInitialSkills = (\n deps: Record<string, string>\n): (keyof typeof SKILLS_METADATA)[] => {\n const skills: (keyof typeof SKILLS_METADATA)[] = [\n 'Usage',\n 'Content',\n 'Config',\n 'CLI',\n 'Compiler',\n ];\n\n if (deps.next) skills.push('NextJS');\n if (deps.react || !deps.next) skills.push('React');\n if (deps.preact) skills.push('Preact');\n if (deps['solid-js']) skills.push('Solid');\n if (deps.vue || deps.nuxt) skills.push('Vue');\n if (deps.svelte || deps['@sveltejs/kit']) skills.push('Svelte');\n if (deps.astro) skills.push('Astro');\n\n return skills;\n};\n\nexport interface PlatformMetadata {\n label: string;\n dir: string;\n check?: () => boolean;\n}\n\n/**\n * Metadata and configuration for each supported platform.\n */\nexport const PLATFORMS_METADATA: Record<string, PlatformMetadata> = {\n Cursor: {\n label: 'Cursor',\n dir: '.cursor/skills',\n check: () =>\n process.env.CURSOR === 'true' || process.env.TERM_PROGRAM === 'cursor',\n },\n Windsurf: {\n label: 'Windsurf',\n dir: '.windsurf/skills',\n check: () =>\n process.env.WINDSURF === 'true' ||\n process.env.TERM_PROGRAM === 'windsurf',\n },\n Trae: {\n label: 'Trae',\n dir: '.trae/skills',\n check: () =>\n process.env.TRAE === 'true' || process.env.TERM_PROGRAM === 'trae',\n },\n TraeCN: {\n label: 'Trae CN',\n dir: '.trae/skills',\n check: () => process.env.TRAE_CN === 'true',\n },\n VSCode: {\n label: 'VS Code',\n dir: '.vscode/skills',\n check: () =>\n process.env.VSCODE === 'true' || process.env.TERM_PROGRAM === 'vscode',\n },\n OpenCode: {\n label: 'OpenCode',\n dir: '.opencode/skills',\n check: () => process.env.OPENCODE === 'true',\n },\n Claude: {\n label: 'Claude Code',\n dir: '.claude/skills',\n check: () => process.env.CLAUDE === 'true',\n },\n GitHub: {\n label: 'GitHub Copilot Workspace',\n dir: '.github/skills',\n check: () =>\n process.env.GITHUB_ACTIONS === 'true' || !!process.env.GITHUB_WORKSPACE,\n },\n Antigravity: {\n label: 'Antigravity',\n dir: '.agent/skills',\n },\n Augment: {\n label: 'Augment',\n dir: '.augment/skills',\n },\n OpenClaw: {\n label: 'OpenClaw',\n dir: 'skills',\n },\n Cline: {\n label: 'Cline',\n dir: '.cline/skills',\n },\n CodeBuddy: {\n label: 'CodeBuddy',\n dir: '.codebuddy/skills',\n },\n CommandCode: {\n label: 'Command Code',\n dir: '.commandcode/skills',\n },\n Continue: {\n label: 'Continue',\n dir: '.continue/skills',\n },\n Crush: {\n label: 'Crush',\n dir: '.crush/skills',\n },\n Droid: {\n label: 'Droid',\n dir: '.factory/skills',\n },\n Goose: {\n label: 'Goose',\n dir: '.goose/skills',\n },\n IFlow: {\n label: 'iFlow CLI',\n dir: '.iflow/skills',\n },\n Junie: {\n label: 'Junie',\n dir: '.junie/skills',\n },\n KiloCode: {\n label: 'Kilo Code',\n dir: '.kilocode/skills',\n },\n Kiro: {\n label: 'Kiro CLI',\n dir: '.kiro/skills',\n },\n Kode: {\n label: 'Kode',\n dir: '.kode/skills',\n },\n MCPJam: {\n label: 'MCPJam',\n dir: '.mcpjam/skills',\n },\n MistralVibe: {\n label: 'Mistral Vibe',\n dir: '.vibe/skills',\n },\n Mux: {\n label: 'Mux',\n dir: '.mux/skills',\n },\n OpenHands: {\n label: 'OpenHands',\n dir: '.openhands/skills',\n },\n Pi: {\n label: 'Pi',\n dir: '.pi/skills',\n },\n Qoder: {\n label: 'Qoder',\n dir: '.qoder/skills',\n },\n Qwen: {\n label: 'Qwen Code',\n dir: '.qwen/skills',\n },\n RooCode: {\n label: 'Roo Code',\n dir: '.roo/skills',\n },\n Zencoder: {\n label: 'Zencoder',\n dir: '.zencoder/skills',\n },\n Neovate: {\n label: 'Neovate',\n dir: '.neovate/skills',\n },\n Pochi: {\n label: 'Pochi',\n dir: '.pochi/skills',\n },\n Other: {\n label: 'Other',\n dir: 'skills',\n },\n} as const;\n\nexport type Platform = keyof typeof PLATFORMS_METADATA;\n\nexport const PLATFORMS = Object.keys(PLATFORMS_METADATA) as Platform[];\n\n/**\n * Maps specific skill keys to special filenames if they differ from standard snake_case.\n */\nconst SKILL_FILENAME_MAP: Partial<Record<Skill, string>> = {};\n\n/**\n * Helper to convert CamelCase to kebab-case for directory naming\n */\nconst camelToKebabCase = (str: string) =>\n str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();\n\n/**\n * Reads the raw markdown content for a specific skill from the assets folder.\n */\nconst getSkillContent = (skill: Skill): string => {\n const baseName = SKILL_FILENAME_MAP[skill] ?? camelToKebabCase(skill);\n const fileName = `./skills/${baseName}.md`;\n\n try {\n return readAsset(fileName);\n } catch {\n console.warn(\n `Warning: Could not read asset for skill: ${skill} at ${fileName}`\n );\n return '';\n }\n};\n\n/**\n * Reads the licence content from the assets folder.\n */\nconst getLicenceContent = (): string => {\n try {\n return readAsset('./LICENCE.md');\n } catch {\n console.warn('Warning: Could not read LICENCE.md asset');\n return '';\n }\n};\n\n/**\n * Fetches the content of a URL using native fetch.\n */\nconst fetchUrlContent = async (url: string): Promise<string> => {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`Failed to fetch ${url}: ${response.statusText}`);\n }\n return response.text();\n};\n\n/**\n * Installs skills using the \"Agent Skills\" directory standard.\n * Standard: <PROJECT_ROOT>/<CONFIG_DIR>/skills/<SKILL_NAME>/SKILL.md\n */\nexport const installSkills = async (\n projectRoot: string,\n platform: Platform,\n skills: Skill[]\n): Promise<string> => {\n // Determine destination directory\n const relativeDir = PLATFORMS_METADATA[platform].dir ?? 'skills';\n const skillsBaseDir = path.join(projectRoot, relativeDir);\n\n // Ensure the base directory exists\n await fs.mkdir(skillsBaseDir, { recursive: true });\n\n const createdSkills: string[] = [];\n const licenceContent = getLicenceContent();\n\n for (const skill of skills) {\n const baseName = SKILL_FILENAME_MAP[skill] ?? camelToKebabCase(skill);\n const skillName = `intlayer-${baseName}`;\n const skillContent = getSkillContent(skill);\n\n if (!skillContent) continue;\n\n // Extract unique URLs\n const urls = Array.from(\n new Set(\n skillContent.match(/https:\\/\\/intlayer\\.org\\/doc\\/[^\\s)]+\\.md/g) || []\n )\n );\n\n // Agent Standard: .../skills/<skill-name>/SKILL.md\n const skillDir = path.join(skillsBaseDir, skillName);\n const referenceDir = path.join(skillDir, 'references');\n\n // Ensure directories exist\n await fs.mkdir(referenceDir, { recursive: true });\n\n // Write License\n if (licenceContent) {\n await fs.writeFile(\n path.join(skillDir, 'LICENCE.md'),\n licenceContent,\n 'utf-8'\n );\n }\n\n let updatedSkillContent = skillContent;\n\n // Parallel download of references\n const downloadPromises = urls.map(async (url) => {\n try {\n const content = await fetchUrlContent(url);\n const metadata = getMarkdownMetadata<{ slugs?: string[] }>(content);\n\n let fileName = '';\n\n // Determine filename from slugs or URL path\n if (Array.isArray(metadata.slugs)) {\n fileName = metadata.slugs.filter((slug) => slug !== 'doc').join('_');\n } else {\n const urlPath = new URL(url).pathname;\n fileName = urlPath\n .split('/')\n .filter((part) => part && part !== 'doc')\n .map((part) => part.replace('.md', '')) // Clean extension for joining\n .join('_');\n }\n\n // Ensure it ends with .md\n fileName = fileName ? `${fileName}.md` : 'index.md';\n const localRefPath = `references/${fileName}`;\n\n return {\n url,\n localRefPath,\n fileName,\n content,\n success: true,\n };\n } catch (error) {\n console.warn(\n `Warning: Failed to download ref ${url} for skill ${skill}`,\n error\n );\n return { url, success: false };\n }\n });\n\n const results = await Promise.all(downloadPromises);\n\n // Process results: Write files and update content string\n for (const res of results) {\n if (res.success && res.fileName && res.content && res.localRefPath) {\n // Write the reference file\n await fs.writeFile(\n path.join(referenceDir, res.fileName),\n res.content,\n 'utf-8'\n );\n\n // Update the main content to point to local file\n updatedSkillContent = updatedSkillContent.replaceAll(\n res.url,\n res.localRefPath\n );\n }\n }\n\n // Write the main SKILL.md\n const filePath = path.join(skillDir, 'SKILL.md');\n await fs.writeFile(filePath, updatedSkillContent, 'utf-8');\n createdSkills.push(`${skillName}/SKILL.md`);\n }\n\n if (createdSkills.length === 0) {\n return `No skill files were created. Check your asset paths.`;\n }\n\n return `Created ${createdSkills.length} skills in ${skillsBaseDir}`;\n};\n"],"mappings":"mLAQA,MAAa,EAAkB,CAC7B,OAAQ,uCACR,QAAS,+DACT,MAAO,sCACP,IAAK,kCACL,SACE,4FACF,cAAe,0DACf,OAAQ,sDACR,MAAO,wCACP,IAAK,sCACL,OAAQ,oCACR,QAAS,wDACT,OAAQ,yCACR,MACE,qMACF,MAAO,uCACR,CAIY,EAAS,OAAO,KAAK,EAAgB,CAErC,EACX,GACqC,CACrC,IAAM,EAA2C,CAC/C,QACA,UACA,SACA,MACA,WACD,CAUD,OARI,EAAK,MAAM,EAAO,KAAK,SAAS,EAChC,EAAK,OAAS,CAAC,EAAK,OAAM,EAAO,KAAK,QA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Q,KACN,mCAAmC,EAAI,aAAa,IACpD,EACD,CACM,CAAE,MAAK,QAAS,GAAO,GAEhC,CAEI,EAAU,MAAM,QAAQ,IAAI,EAAiB,CAGnD,IAAK,IAAM,KAAO,EACZ,EAAI,SAAW,EAAI,UAAY,EAAI,SAAW,EAAI,eAEpD,MAAMA,EAAG,UACP,EAAK,KAAK,EAAc,EAAI,SAAS,CACrC,EAAI,QACJ,QACD,CAGD,EAAsB,EAAoB,WACxC,EAAI,IACJ,EAAI,aACL,EAKL,IAAM,EAAW,EAAK,KAAK,EAAU,WAAW,CAChD,MAAMA,EAAG,UAAU,EAAU,EAAqB,QAAQ,CAC1D,EAAc,KAAK,GAAG,EAAU,WAAW,CAO7C,OAJI,EAAc,SAAW,EACpB,uDAGF,WAAW,EAAc,OAAO,aAAa"}
@@ -1,2 +1,2 @@
1
- import{fetchDistantDictionaries as e}from"../fetchDistantDictionaries.mjs";import{sortAlphabetically as t}from"../utils/sortAlphabetically.mjs";import{getConfiguration as n}from"@intlayer/config/node";import{getIntlayerAPIProxy as r}from"@intlayer/api";import{getRemoteDictionaries as i}from"@intlayer/remote-dictionaries-entry";const a=e=>e.map(e=>({...e,localId:`${e.key}::remote::${e.id}`,location:`remote`})),o=async(o=n(),s,c)=>{let{editor:l}=o,u=i(o);if(!(l.clientId&&l.clientSecret))return[];try{c?.onStartRemoteCheck?.();let n=(await r(void 0,o).dictionary.getDictionariesUpdateTimestamp()).data;if(!n)throw Error(`No distant dictionaries found`);let i=Object.entries(n).filter(([e,t])=>{if(!t.updatedAt)return!0;let n=u[t.key]?.find(t=>t.id===e);if(!n)return!0;let r=n?.updatedAt,i=typeof r==`number`?r:r?new Date(r).getTime():void 0;return typeof i==`number`?t.updatedAt>i:!0}),l=Object.values(u).flat().filter(e=>{let t=n[e.id].updatedAt,r=e.updatedAt,i=typeof r==`number`?r:r?new Date(r).getTime():void 0;return typeof i==`number`&&typeof t==`number`&&i>=t});l.length>0&&s?.(l.map(e=>({dictionaryKey:e.key,type:`remote`,status:`imported`})));let d=i.map(([,e])=>e.key).sort(t);d.length>0&&s?.(d.map(e=>({dictionaryKey:e,type:`remote`,status:`pending`})));let f=a(await e({dictionaryKeys:d},s));return[...l,...f]}catch(e){return c?.onError?.(e),[]}finally{c?.onStopRemoteCheck?.()}};export{a as formatDistantDictionaries,o as loadRemoteDictionaries};
1
+ import{sortAlphabetically as e}from"../utils/sortAlphabetically.mjs";import{fetchDistantDictionaries as t}from"../fetchDistantDictionaries.mjs";import{getConfiguration as n}from"@intlayer/config/node";import{getIntlayerAPIProxy as r}from"@intlayer/api";import{getRemoteDictionaries as i}from"@intlayer/remote-dictionaries-entry";const a=e=>e.map(e=>({...e,localId:`${e.key}::remote::${e.id}`,location:`remote`})),o=async(o=n(),s,c)=>{let{editor:l}=o,u=i(o);if(!(l.clientId&&l.clientSecret))return[];try{c?.onStartRemoteCheck?.();let n=(await r(void 0,o).dictionary.getDictionariesUpdateTimestamp()).data;if(!n)throw Error(`No distant dictionaries found`);let i=Object.entries(n).filter(([e,t])=>{if(!t.updatedAt)return!0;let n=u[t.key]?.find(t=>t.id===e);if(!n)return!0;let r=n?.updatedAt,i=typeof r==`number`?r:r?new Date(r).getTime():void 0;return typeof i==`number`?t.updatedAt>i:!0}),l=Object.values(u).flat().filter(e=>{let t=n[e.id].updatedAt,r=e.updatedAt,i=typeof r==`number`?r:r?new Date(r).getTime():void 0;return typeof i==`number`&&typeof t==`number`&&i>=t});l.length>0&&s?.(l.map(e=>({dictionaryKey:e.key,type:`remote`,status:`imported`})));let d=i.map(([,e])=>e.key).sort(e);d.length>0&&s?.(d.map(e=>({dictionaryKey:e,type:`remote`,status:`pending`})));let f=a(await t({dictionaryKeys:d},s));return[...l,...f]}catch(e){return c?.onError?.(e),[]}finally{c?.onStopRemoteCheck?.()}};export{a as formatDistantDictionaries,o as loadRemoteDictionaries};
2
2
  //# sourceMappingURL=loadRemoteDictionaries.mjs.map
@@ -1,4 +1,4 @@
1
- import{ANSIColors as e,colorize as t,extractErrorMessage as n,spinnerFrames as r,v as i,x as a}from"@intlayer/config/client";import o from"@intlayer/config/built";var s=class{statuses=[];spinnerTimer=null;spinnerIndex=0;renderedLines=0;spinnerFrames=r;isFinished=!1;prefix;lastRenderedState=``;remoteCheckInProgress=!1;expectRemote=!1;remoteError;pluginTotal=0;pluginDone=0;pluginError;constructor(){this.prefix=o?.log?.prefix??``}setExpectRemote(e){this.expectRemote=e}startRemoteCheck(){this.isFinished||(this.remoteCheckInProgress=!0,this.startSpinner(),this.render())}stopRemoteCheck(){this.remoteCheckInProgress=!1}update(e){if(this.isFinished)return;for(let t of e){let e=this.statuses.findIndex(e=>e.dictionaryKey===t.dictionaryKey&&e.type===t.type);e>=0?this.statuses[e]=t:this.statuses.push(t)}let{remoteTotal:t}=this.computeProgress();this.expectRemote&&!this.remoteCheckInProgress&&t===0||(this.startSpinner(),this.render())}finish(){this.isFinished=!0,this.stopSpinner(),this.render()}startSpinner(){this.spinnerTimer||this.isFinished||(this.spinnerTimer=setInterval(()=>{this.spinnerIndex=(this.spinnerIndex+1)%this.spinnerFrames.length,this.render()},100))}stopSpinner(){this.spinnerTimer&&=(clearInterval(this.spinnerTimer),null)}setRemoteError=e=>{this.remoteError=n(e),this.stopRemoteCheck(),this.render()};setPluginTotal(e){this.isFinished||(this.pluginTotal=e,e>0&&this.startSpinner(),this.render())}setPluginDone(e){this.isFinished||(this.pluginDone=e,this.render())}setPluginError(e){this.isFinished||(this.pluginError=n(e),this.render())}render(){let{localTotal:n,localDone:r,remoteTotal:o,remoteDone:s,pluginTotal:c,pluginDone:l}=this.computeProgress(),u=this.spinnerFrames[this.spinnerIndex],d=t(u,e.BLUE),f=[],p=r===n,m=s===o,h=l===c;this.expectRemote&&this.remoteCheckInProgress&&o===0||(p?f.push(`${this.prefix} ${i} Local content: ${t(`${r}`,e.GREEN)}${t(`/${n}`,e.GREY)}`):f.push(`${this.prefix} ${d} Local content: ${t(`${r}`,e.BLUE)}${t(`/${n}`,e.GREY)}`)),(o>0||this.remoteCheckInProgress||this.remoteError)&&(this.remoteError?f.push(`${this.prefix} ${a} Remote content: ${t(this.remoteError,e.RED)}`):o===0?f.push(`${this.prefix} ${d} Remote content: ${t(`Check server`,e.BLUE)}`):m?f.push(`${this.prefix} ${i} Remote content: ${t(`${s}`,e.GREEN)}${t(`/${o}`,e.GREY)}`):f.push(`${this.prefix} ${d} Remote content: ${t(`${s}`,e.BLUE)}${t(`/${o}`,e.GREY)}`)),(c>0||this.pluginError)&&(this.pluginError?f.push(`${this.prefix} ${a} Plugin content: ${t(this.pluginError,e.RED)}`):h?f.push(`${this.prefix} ${i} Plugin content: ${t(`${l}`,e.GREEN)}${t(`/${c}`,e.GREY)}`):f.push(`${this.prefix} ${d} Plugin content: ${t(`${l}`,e.BLUE)}${t(`/${c}`,e.GREY)}`));let g=f.join(`
1
+ import{ANSIColors as e,colorize as t,extractErrorMessage as n,getPrefix as r,spinnerFrames as i,v as a,x as o}from"@intlayer/config/client";import s from"@intlayer/config/built";var c=class{statuses=[];spinnerTimer=null;spinnerIndex=0;renderedLines=0;spinnerFrames=i;isFinished=!1;prefix;lastRenderedState=``;remoteCheckInProgress=!1;expectRemote=!1;remoteError;pluginTotal=0;pluginDone=0;pluginError;constructor(){this.prefix=r(s?.log?.prefix)??``}setExpectRemote(e){this.expectRemote=e}startRemoteCheck(){this.isFinished||(this.remoteCheckInProgress=!0,this.startSpinner(),this.render())}stopRemoteCheck(){this.remoteCheckInProgress=!1}update(e){if(this.isFinished)return;for(let t of e){let e=this.statuses.findIndex(e=>e.dictionaryKey===t.dictionaryKey&&e.type===t.type);e>=0?this.statuses[e]=t:this.statuses.push(t)}let{remoteTotal:t}=this.computeProgress();this.expectRemote&&!this.remoteCheckInProgress&&t===0||(this.startSpinner(),this.render())}finish(){this.isFinished=!0,this.stopSpinner(),this.render()}startSpinner(){this.spinnerTimer||this.isFinished||(this.spinnerTimer=setInterval(()=>{this.spinnerIndex=(this.spinnerIndex+1)%this.spinnerFrames.length,this.render()},100))}stopSpinner(){this.spinnerTimer&&=(clearInterval(this.spinnerTimer),null)}setRemoteError=e=>{this.remoteError=n(e),this.stopRemoteCheck(),this.render()};setPluginTotal(e){this.isFinished||(this.pluginTotal=e,e>0&&this.startSpinner(),this.render())}setPluginDone(e){this.isFinished||(this.pluginDone=e,this.render())}setPluginError(e){this.isFinished||(this.pluginError=n(e),this.render())}render(){let{localTotal:n,localDone:r,remoteTotal:i,remoteDone:s,pluginTotal:c,pluginDone:l}=this.computeProgress(),u=this.spinnerFrames[this.spinnerIndex],d=t(u,e.BLUE),f=[],p=r===n,m=s===i,h=l===c;this.expectRemote&&this.remoteCheckInProgress&&i===0||(p?f.push(`${this.prefix} ${a} Local content: ${t(`${r}`,e.GREEN)}${t(`/${n}`,e.GREY)}`):f.push(`${this.prefix} ${d} Local content: ${t(`${r}`,e.BLUE)}${t(`/${n}`,e.GREY)}`)),(i>0||this.remoteCheckInProgress||this.remoteError)&&(this.remoteError?f.push(`${this.prefix} ${o} Remote content: ${t(this.remoteError,e.RED)}`):i===0?f.push(`${this.prefix} ${d} Remote content: ${t(`Check server`,e.BLUE)}`):m?f.push(`${this.prefix} ${a} Remote content: ${t(`${s}`,e.GREEN)}${t(`/${i}`,e.GREY)}`):f.push(`${this.prefix} ${d} Remote content: ${t(`${s}`,e.BLUE)}${t(`/${i}`,e.GREY)}`)),(c>0||this.pluginError)&&(this.pluginError?f.push(`${this.prefix} ${o} Plugin content: ${t(this.pluginError,e.RED)}`):h?f.push(`${this.prefix} ${a} Plugin content: ${t(`${l}`,e.GREEN)}${t(`/${c}`,e.GREY)}`):f.push(`${this.prefix} ${d} Plugin content: ${t(`${l}`,e.BLUE)}${t(`/${c}`,e.GREY)}`));let g=f.join(`
2
2
  `);if(g===this.lastRenderedState)return;this.lastRenderedState=g,this.renderedLines>0&&process.stdout.write(`\x1b[${this.renderedLines}F`);let _=Math.max(this.renderedLines,f.length);for(let e=0;e<_;e++){process.stdout.write(`\x1B[2K`);let t=f[e];t!==void 0&&process.stdout.write(t),process.stdout.write(`
3
- `)}this.renderedLines=f.length}computeProgress(){let e=new Set(this.statuses.filter(e=>e.type===`local`).map(e=>e.dictionaryKey)),t=new Set(this.statuses.filter(e=>e.type===`local`&&(e.status===`built`||e.status===`error`)).map(e=>e.dictionaryKey)),n=new Set(this.statuses.filter(e=>e.type===`remote`).map(e=>e.dictionaryKey)),r=new Set(this.statuses.filter(e=>e.type===`remote`&&(e.status===`fetched`||e.status===`imported`||e.status===`error`)).map(e=>e.dictionaryKey));return{localTotal:e.size,localDone:t.size,remoteTotal:n.size,remoteDone:r.size,pluginTotal:this.pluginTotal,pluginDone:this.pluginDone}}};export{s as DictionariesLogger};
3
+ `)}this.renderedLines=f.length}computeProgress(){let e=new Set(this.statuses.filter(e=>e.type===`local`).map(e=>e.dictionaryKey)),t=new Set(this.statuses.filter(e=>e.type===`local`&&(e.status===`built`||e.status===`error`)).map(e=>e.dictionaryKey)),n=new Set(this.statuses.filter(e=>e.type===`remote`).map(e=>e.dictionaryKey)),r=new Set(this.statuses.filter(e=>e.type===`remote`&&(e.status===`fetched`||e.status===`imported`||e.status===`error`)).map(e=>e.dictionaryKey));return{localTotal:e.size,localDone:t.size,remoteTotal:n.size,remoteDone:r.size,pluginTotal:this.pluginTotal,pluginDone:this.pluginDone}}};export{c as DictionariesLogger};
4
4
  //# sourceMappingURL=log.mjs.map