@intlayer/engine 9.5.11 → 9.6.0

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 (111) hide show
  1. package/dist/assets/installSkills/skills/bundle-optimization.md +123 -0
  2. package/dist/assets/installSkills/skills/cli.md +28 -1
  3. package/dist/assets/installSkills/skills/compat.md +1 -5
  4. package/dist/assets/installSkills/skills/content.md +8 -2
  5. package/dist/assets/installSkills/skills/dev-tools.md +8 -6
  6. package/dist/assets/installSkills/skills/next-js.md +2 -2
  7. package/dist/assets/installSkills/skills/usage.md +1 -1
  8. package/dist/cjs/build.cjs +5 -0
  9. package/dist/cjs/cli.cjs +3 -0
  10. package/dist/cjs/init/index.cjs +14 -14
  11. package/dist/cjs/init/index.cjs.map +1 -1
  12. package/dist/cjs/init/utils/backendPackages.cjs +15 -0
  13. package/dist/cjs/init/utils/backendPackages.cjs.map +1 -0
  14. package/dist/cjs/init/utils/index.cjs +2 -3
  15. package/dist/cjs/init/utils/packageManager.cjs +1 -1
  16. package/dist/cjs/init/utils/packageManager.cjs.map +1 -1
  17. package/dist/cjs/installMCP/installMCP.cjs +35 -25
  18. package/dist/cjs/installMCP/installMCP.cjs.map +1 -1
  19. package/dist/cjs/installSkills/index.cjs +28 -1
  20. package/dist/cjs/installSkills/index.cjs.map +1 -1
  21. package/dist/cjs/listGitFiles.cjs +3 -5
  22. package/dist/cjs/listGitFiles.cjs.map +1 -1
  23. package/dist/cjs/listProjects.cjs +1 -2
  24. package/dist/cjs/listProjects.cjs.map +1 -1
  25. package/dist/cjs/loadDictionaries/loadDictionaries.cjs +9 -8
  26. package/dist/cjs/loadDictionaries/loadDictionaries.cjs.map +1 -1
  27. package/dist/cjs/loadDictionaries/loadRemoteDictionaries.cjs +3 -5
  28. package/dist/cjs/loadDictionaries/loadRemoteDictionaries.cjs.map +1 -1
  29. package/dist/cjs/loadDictionaries/remoteDictionaryClient.cjs +18 -0
  30. package/dist/cjs/loadDictionaries/remoteDictionaryClient.cjs.map +1 -0
  31. package/dist/cjs/prepareIntlayerServer.cjs +132 -0
  32. package/dist/cjs/prepareIntlayerServer.cjs.map +1 -0
  33. package/dist/cjs/utils/getProcessChainCommands.cjs +117 -0
  34. package/dist/cjs/utils/getProcessChainCommands.cjs.map +1 -0
  35. package/dist/cjs/utils/index.cjs +2 -0
  36. package/dist/cjs/utils/startContentWatcher.cjs +99 -0
  37. package/dist/cjs/utils/startContentWatcher.cjs.map +1 -0
  38. package/dist/cjs/watcher.cjs +2 -2
  39. package/dist/cjs/watcher.cjs.map +1 -1
  40. package/dist/cjs/writeJsonIfChanged.cjs.map +1 -1
  41. package/dist/esm/build.mjs +2 -1
  42. package/dist/esm/cli.mjs +4 -4
  43. package/dist/esm/init/index.mjs +13 -13
  44. package/dist/esm/init/index.mjs.map +1 -1
  45. package/dist/esm/init/utils/backendPackages.mjs +14 -0
  46. package/dist/esm/init/utils/backendPackages.mjs.map +1 -0
  47. package/dist/esm/init/utils/index.mjs +2 -2
  48. package/dist/esm/init/utils/packageManager.mjs +1 -1
  49. package/dist/esm/init/utils/packageManager.mjs.map +1 -1
  50. package/dist/esm/installMCP/installMCP.mjs +35 -25
  51. package/dist/esm/installMCP/installMCP.mjs.map +1 -1
  52. package/dist/esm/installSkills/index.mjs +29 -3
  53. package/dist/esm/installSkills/index.mjs.map +1 -1
  54. package/dist/esm/listGitFiles.mjs +1 -1
  55. package/dist/esm/listGitFiles.mjs.map +1 -1
  56. package/dist/esm/listProjects.mjs +1 -1
  57. package/dist/esm/listProjects.mjs.map +1 -1
  58. package/dist/esm/loadDictionaries/loadDictionaries.mjs +9 -8
  59. package/dist/esm/loadDictionaries/loadDictionaries.mjs.map +1 -1
  60. package/dist/esm/loadDictionaries/loadRemoteDictionaries.mjs +2 -4
  61. package/dist/esm/loadDictionaries/loadRemoteDictionaries.mjs.map +1 -1
  62. package/dist/esm/loadDictionaries/remoteDictionaryClient.mjs +16 -0
  63. package/dist/esm/loadDictionaries/remoteDictionaryClient.mjs.map +1 -0
  64. package/dist/esm/prepareIntlayerServer.mjs +128 -0
  65. package/dist/esm/prepareIntlayerServer.mjs.map +1 -0
  66. package/dist/esm/utils/getProcessChainCommands.mjs +115 -0
  67. package/dist/esm/utils/getProcessChainCommands.mjs.map +1 -0
  68. package/dist/esm/utils/index.mjs +2 -1
  69. package/dist/esm/utils/runParallel/pidTree.mjs +3 -3
  70. package/dist/esm/utils/runParallel/pidTree.mjs.map +1 -1
  71. package/dist/esm/utils/runParallel/ps.mjs +2 -2
  72. package/dist/esm/utils/runParallel/ps.mjs.map +1 -1
  73. package/dist/esm/utils/runParallel/wmic.mjs +2 -2
  74. package/dist/esm/utils/runParallel/wmic.mjs.map +1 -1
  75. package/dist/esm/utils/startContentWatcher.mjs +98 -0
  76. package/dist/esm/utils/startContentWatcher.mjs.map +1 -0
  77. package/dist/esm/watcher.mjs +1 -1
  78. package/dist/esm/watcher.mjs.map +1 -1
  79. package/dist/esm/writeJsonIfChanged.mjs +1 -1
  80. package/dist/esm/writeJsonIfChanged.mjs.map +1 -1
  81. package/dist/types/build.d.ts +2 -1
  82. package/dist/types/cli.d.ts +4 -4
  83. package/dist/types/init/index.d.ts +1 -1
  84. package/dist/types/init/index.d.ts.map +1 -1
  85. package/dist/types/init/utils/backendPackages.d.ts +5 -0
  86. package/dist/types/init/utils/backendPackages.d.ts.map +1 -0
  87. package/dist/types/init/utils/index.d.ts +2 -2
  88. package/dist/types/init/utils/packageManager.d.ts +5 -0
  89. package/dist/types/init/utils/packageManager.d.ts.map +1 -1
  90. package/dist/types/installMCP/installMCP.d.ts +4 -0
  91. package/dist/types/installMCP/installMCP.d.ts.map +1 -1
  92. package/dist/types/installSkills/index.d.ts +7 -0
  93. package/dist/types/installSkills/index.d.ts.map +1 -1
  94. package/dist/types/loadDictionaries/loadRemoteDictionaries.d.ts.map +1 -1
  95. package/dist/types/loadDictionaries/remoteDictionaryClient.d.ts +14 -0
  96. package/dist/types/loadDictionaries/remoteDictionaryClient.d.ts.map +1 -0
  97. package/dist/types/prepareIntlayerServer.d.ts +67 -0
  98. package/dist/types/prepareIntlayerServer.d.ts.map +1 -0
  99. package/dist/types/utils/getProcessChainCommands.d.ts +35 -0
  100. package/dist/types/utils/getProcessChainCommands.d.ts.map +1 -0
  101. package/dist/types/utils/index.d.ts +2 -1
  102. package/dist/types/utils/startContentWatcher.d.ts +40 -0
  103. package/dist/types/utils/startContentWatcher.d.ts.map +1 -0
  104. package/dist/types/watcher.d.ts.map +1 -1
  105. package/package.json +9 -9
  106. package/dist/cjs/init/utils/devScript.cjs +0 -57
  107. package/dist/cjs/init/utils/devScript.cjs.map +0 -1
  108. package/dist/esm/init/utils/devScript.mjs +0 -55
  109. package/dist/esm/init/utils/devScript.mjs.map +0 -1
  110. package/dist/types/init/utils/devScript.d.ts +0 -48
  111. package/dist/types/init/utils/devScript.d.ts.map +0 -1
@@ -4,48 +4,58 @@ const require_installSkills_index = require('../installSkills/index.cjs');
4
4
  let node_path = require("node:path");
5
5
  node_path = require_runtime.__toESM(node_path);
6
6
  let node_fs = require("node:fs");
7
- let node_os = require("node:os");
8
- node_os = require_runtime.__toESM(node_os);
9
7
 
10
8
  //#region src/installMCP/installMCP.ts
9
+ /** Transports accepted by `intlayer init mcp --transport`. */
10
+ const MCP_TRANSPORTS = ["stdio", "sse"];
11
11
  const MCP_CONFIG_FILENAME = "mcp.json";
12
- const CLAUDE_DESKTOP_CONFIG_PATH = process.platform === "win32" ? node_path.default.join(process.env.APPDATA || "", "Claude", "claude_desktop_config.json") : node_path.default.join(node_os.default.homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
12
+ /** Project-scoped MCP configuration file read by Claude Code. */
13
+ const CLAUDE_CODE_MCP_CONFIG_FILENAME = ".mcp.json";
14
+ /** Platforms whose MCP entries declare their transport as `type`. */
15
+ const TYPED_TRANSPORT_PLATFORMS = ["VSCode", "Claude"];
16
+ /** Resolves the MCP configuration file written for a platform. */
17
+ const getMCPConfigPath = (projectRoot, platform) => {
18
+ if (platform === "Claude") return node_path.default.join(projectRoot, CLAUDE_CODE_MCP_CONFIG_FILENAME);
19
+ const relativeDir = node_path.default.dirname(require_installSkills_index.PLATFORMS_METADATA[platform]?.dir ?? ".");
20
+ return node_path.default.join(projectRoot, relativeDir, MCP_CONFIG_FILENAME);
21
+ };
22
+ /** Builds the Intlayer MCP server entry for a platform and transport. */
23
+ const getMCPServerConfig = (platform, transport) => {
24
+ const isTypedTransport = TYPED_TRANSPORT_PLATFORMS.includes(platform);
25
+ if (transport === "stdio") return {
26
+ command: "npx",
27
+ args: ["-y", "@intlayer/mcp"],
28
+ ...isTypedTransport ? { type: "stdio" } : {}
29
+ };
30
+ return {
31
+ url: "https://mcp.intlayer.org",
32
+ ...isTypedTransport ? { type: "sse" } : { transport: "sse" }
33
+ };
34
+ };
13
35
  /**
14
36
  * Installs the Intlayer MCP server configuration for a specific platform.
37
+ * Every platform is configured at the project level (Claude Code included,
38
+ * through `.mcp.json`), so nothing outside the project is modified.
15
39
  */
16
40
  const installMCP = async (projectRoot, platform, transport) => {
17
- let configPath;
18
- let configKey = "mcpServers";
19
- if (platform === "Claude") configPath = CLAUDE_DESKTOP_CONFIG_PATH;
20
- else {
21
- const relativeDir = node_path.default.dirname(require_installSkills_index.PLATFORMS_METADATA[platform]?.dir ?? ".");
22
- configPath = node_path.default.join(projectRoot, relativeDir, MCP_CONFIG_FILENAME);
23
- if (platform === "VSCode") configKey = "servers";
24
- }
41
+ const configPath = getMCPConfigPath(projectRoot, platform);
42
+ const serversKey = platform === "VSCode" ? "servers" : "mcpServers";
25
43
  await node_fs.promises.mkdir(node_path.default.dirname(configPath), { recursive: true });
26
44
  let config = {};
27
45
  try {
28
46
  const content = await node_fs.promises.readFile(configPath, "utf-8");
29
47
  config = JSON.parse(content);
30
48
  } catch {}
31
- if (!config[configKey]) config[configKey] = {};
32
- if (transport === "stdio") {
33
- const mcpConfig = {
34
- command: "npx",
35
- args: ["-y", "@intlayer/mcp"]
36
- };
37
- if (platform === "VSCode") mcpConfig.type = "stdio";
38
- config[configKey].intlayer = mcpConfig;
39
- } else {
40
- const mcpConfig = { url: "https://mcp.intlayer.org" };
41
- if (platform === "VSCode") mcpConfig.type = "sse";
42
- else mcpConfig.transport = "sse";
43
- config[configKey].intlayer = mcpConfig;
44
- }
49
+ const servers = config[serversKey] ?? {};
50
+ config[serversKey] = {
51
+ ...servers,
52
+ intlayer: getMCPServerConfig(platform, transport)
53
+ };
45
54
  await node_fs.promises.writeFile(configPath, JSON.stringify(config, null, 2), "utf-8");
46
55
  return `MCP server configuration updated in ${configPath}`;
47
56
  };
48
57
 
49
58
  //#endregion
59
+ exports.MCP_TRANSPORTS = MCP_TRANSPORTS;
50
60
  exports.installMCP = installMCP;
51
61
  //# sourceMappingURL=installMCP.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"installMCP.cjs","names":["path","os","PLATFORMS_METADATA","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":";;;;;;;;;;AAOA,MAAM,sBAAsB;AAE5B,MAAM,6BACJ,QAAQ,aAAa,UACjBA,kBAAK,KACH,QAAQ,IAAI,WAAW,IACvB,UACA,4BACF,IACAA,kBAAK,KACHC,gBAAG,QAAQ,GACX,WACA,uBACA,UACA,4BACF;;;;AAKN,MAAa,aAAa,OACxB,aACA,UACA,cACoB;CACpB,IAAI;CACJ,IAAI,YAAY;CAEhB,IAAI,aAAa,UACf,aAAa;MACR;EACL,MAAM,cAAcD,kBAAK,QAAQE,+CAAmB,SAAS,EAAE,OAAO,GAAG;EACzE,aAAaF,kBAAK,KAAK,aAAa,aAAa,mBAAmB;EAEpE,IAAI,aAAa,UACf,YAAY;CAEhB;CAGA,MAAMG,iBAAG,MAAMH,kBAAK,QAAQ,UAAU,GAAG,EAAE,WAAW,KAAK,CAAC;CAE5D,IAAI,SAAc,CAAC;CACnB,IAAI;EACF,MAAM,UAAU,MAAMG,iBAAG,SAAS,YAAY,OAAO;EACrD,SAAS,KAAK,MAAM,OAAO;CAC7B,QAAQ,CAER;CAEA,IAAI,CAAC,OAAO,YACV,OAAO,aAAa,CAAC;CAGvB,IAAI,cAAc,SAAS;EACzB,MAAM,YAAiB;GACrB,SAAS;GACT,MAAM,CAAC,MAAM,eAAe;EAC9B;EAEA,IAAI,aAAa,UACf,UAAU,OAAO;EAGnB,OAAO,UAAU,CAAC,WAAW;CAC/B,OAAO;EACL,MAAM,YAAiB,EACrB,KAAK,2BACP;EAEA,IAAI,aAAa,UACf,UAAU,OAAO;OAEjB,UAAU,YAAY;EAGxB,OAAO,UAAU,CAAC,WAAW;CAC/B;CAEA,MAAMA,iBAAG,UAAU,YAAY,KAAK,UAAU,QAAQ,MAAM,CAAC,GAAG,OAAO;CAEvE,OAAO,uCAAuC;AAChD"}
1
+ {"version":3,"file":"installMCP.cjs","names":["path","PLATFORMS_METADATA","fs"],"sources":["../../../src/installMCP/installMCP.ts"],"sourcesContent":["import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { PLATFORMS_METADATA, type Platform } from '../installSkills';\n\nexport type MCPTransport = 'stdio' | 'sse';\n\n/** Transports accepted by `intlayer init mcp --transport`. */\nexport const MCP_TRANSPORTS: MCPTransport[] = ['stdio', 'sse'];\n\nconst MCP_CONFIG_FILENAME = 'mcp.json';\n\n/** Project-scoped MCP configuration file read by Claude Code. */\nconst CLAUDE_CODE_MCP_CONFIG_FILENAME = '.mcp.json';\n\n/** One MCP server entry, as written under the platform's servers key. */\ntype MCPServerConfig = {\n command?: string;\n args?: string[];\n url?: string;\n type?: MCPTransport;\n transport?: MCPTransport;\n};\n\n/** Parsed MCP configuration file, keeping any unrelated keys untouched. */\ntype MCPConfigFile = Record<string, unknown>;\n\n/** Platforms whose MCP entries declare their transport as `type`. */\nconst TYPED_TRANSPORT_PLATFORMS: Platform[] = ['VSCode', 'Claude'];\n\n/** Resolves the MCP configuration file written for a platform. */\nconst getMCPConfigPath = (projectRoot: string, platform: Platform): string => {\n if (platform === 'Claude') {\n return path.join(projectRoot, CLAUDE_CODE_MCP_CONFIG_FILENAME);\n }\n\n // e.g. `.cursor/skills` → `.cursor/mcp.json`\n const relativeDir = path.dirname(PLATFORMS_METADATA[platform]?.dir ?? '.');\n\n return path.join(projectRoot, relativeDir, MCP_CONFIG_FILENAME);\n};\n\n/** Builds the Intlayer MCP server entry for a platform and transport. */\nconst getMCPServerConfig = (\n platform: Platform,\n transport: MCPTransport\n): MCPServerConfig => {\n const isTypedTransport = TYPED_TRANSPORT_PLATFORMS.includes(platform);\n\n if (transport === 'stdio') {\n return {\n command: 'npx',\n args: ['-y', '@intlayer/mcp'],\n ...(isTypedTransport ? { type: 'stdio' } : {}),\n };\n }\n\n return {\n url: 'https://mcp.intlayer.org',\n ...(isTypedTransport ? { type: 'sse' } : { transport: 'sse' }),\n };\n};\n\n/**\n * Installs the Intlayer MCP server configuration for a specific platform.\n * Every platform is configured at the project level (Claude Code included,\n * through `.mcp.json`), so nothing outside the project is modified.\n */\nexport const installMCP = async (\n projectRoot: string,\n platform: Platform,\n transport: MCPTransport\n): Promise<string> => {\n const configPath = getMCPConfigPath(projectRoot, platform);\n const serversKey = platform === 'VSCode' ? 'servers' : 'mcpServers';\n\n // Ensure the configuration directory exists\n await fs.mkdir(path.dirname(configPath), { recursive: true });\n\n let config: MCPConfigFile = {};\n try {\n const content = await fs.readFile(configPath, 'utf-8');\n config = JSON.parse(content) as MCPConfigFile;\n } catch {\n // File doesn't exist or is invalid JSON, start fresh\n }\n\n const servers = (config[serversKey] ?? {}) as Record<string, MCPServerConfig>;\n\n config[serversKey] = {\n ...servers,\n intlayer: getMCPServerConfig(platform, transport),\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":";;;;;;;;;AAOA,MAAa,iBAAiC,CAAC,SAAS,KAAK;AAE7D,MAAM,sBAAsB;;AAG5B,MAAM,kCAAkC;;AAexC,MAAM,4BAAwC,CAAC,UAAU,QAAQ;;AAGjE,MAAM,oBAAoB,aAAqB,aAA+B;CAC5E,IAAI,aAAa,UACf,OAAOA,kBAAK,KAAK,aAAa,+BAA+B;CAI/D,MAAM,cAAcA,kBAAK,QAAQC,+CAAmB,SAAS,EAAE,OAAO,GAAG;CAEzE,OAAOD,kBAAK,KAAK,aAAa,aAAa,mBAAmB;AAChE;;AAGA,MAAM,sBACJ,UACA,cACoB;CACpB,MAAM,mBAAmB,0BAA0B,SAAS,QAAQ;CAEpE,IAAI,cAAc,SAChB,OAAO;EACL,SAAS;EACT,MAAM,CAAC,MAAM,eAAe;EAC5B,GAAI,mBAAmB,EAAE,MAAM,QAAQ,IAAI,CAAC;CAC9C;CAGF,OAAO;EACL,KAAK;EACL,GAAI,mBAAmB,EAAE,MAAM,MAAM,IAAI,EAAE,WAAW,MAAM;CAC9D;AACF;;;;;;AAOA,MAAa,aAAa,OACxB,aACA,UACA,cACoB;CACpB,MAAM,aAAa,iBAAiB,aAAa,QAAQ;CACzD,MAAM,aAAa,aAAa,WAAW,YAAY;CAGvD,MAAME,iBAAG,MAAMF,kBAAK,QAAQ,UAAU,GAAG,EAAE,WAAW,KAAK,CAAC;CAE5D,IAAI,SAAwB,CAAC;CAC7B,IAAI;EACF,MAAM,UAAU,MAAME,iBAAG,SAAS,YAAY,OAAO;EACrD,SAAS,KAAK,MAAM,OAAO;CAC7B,QAAQ,CAER;CAEA,MAAM,UAAW,OAAO,eAAe,CAAC;CAExC,OAAO,cAAc;EACnB,GAAG;EACH,UAAU,mBAAmB,UAAU,SAAS;CAClD;CAEA,MAAMA,iBAAG,UAAU,YAAY,KAAK,UAAU,QAAQ,MAAM,CAAC,GAAG,OAAO;CAEvE,OAAO,uCAAuC;AAChD"}
@@ -18,6 +18,7 @@ const SKILLS_METADATA = {
18
18
  Usage: "How to use Intlayer in your project",
19
19
  CLI: "Intlayer CLI commands and usage",
20
20
  Compiler: "Intlayer Compiler setup and usage for automatic content extraction without .content files",
21
+ BundleOptimization: "Purge, minify and import modes; writing code the bundle optimizer can follow",
21
22
  RemoteContent: "How to use Intlayer with Remote/CMS/Server-side content",
22
23
  DevTools: "ESLint, LSP, VS Code & Chrome extensions, MCP server and CI/CD",
23
24
  Compat: "Migrate from i18next, next-intl, react-intl, vue-i18n, Lingui… keeping their API",
@@ -42,6 +43,7 @@ const BASE_SKILLS = [
42
43
  "Config",
43
44
  "CLI",
44
45
  "Compiler",
46
+ "BundleOptimization",
45
47
  "DevTools"
46
48
  ];
47
49
  /**
@@ -173,7 +175,7 @@ const PLATFORMS_METADATA = {
173
175
  Claude: {
174
176
  label: "Claude Code",
175
177
  dir: ".claude/skills",
176
- check: () => process.env.CLAUDE === "true"
178
+ check: () => process.env.CLAUDE === "true" || process.env.CLAUDECODE === "1"
177
179
  },
178
180
  GitHub: {
179
181
  label: "GitHub Copilot Workspace",
@@ -291,6 +293,30 @@ const PLATFORMS_METADATA = {
291
293
  };
292
294
  const PLATFORMS = Object.keys(PLATFORMS_METADATA);
293
295
  /**
296
+ * Root folders too common to identify a platform on their own (e.g. `.github`
297
+ * exists in most repositories regardless of the AI tool in use).
298
+ */
299
+ const AMBIGUOUS_PLATFORM_DIRECTORIES = /* @__PURE__ */ new Set([
300
+ ".github",
301
+ ".vscode",
302
+ "skills"
303
+ ]);
304
+ /** Root config folder of a platform (e.g. `.cursor`), if it identifies it. */
305
+ const getPlatformDirectory = (platform) => {
306
+ const [rootDirectory] = (PLATFORMS_METADATA[platform]?.dir ?? "").split("/");
307
+ if (!rootDirectory || AMBIGUOUS_PLATFORM_DIRECTORIES.has(rootDirectory)) return;
308
+ return rootDirectory;
309
+ };
310
+ /**
311
+ * Detects the AI platform in use. The environment of the running tool wins;
312
+ * otherwise the first platform whose config folder (`.claude`, `.cursor`…)
313
+ * exists in the project root is returned.
314
+ */
315
+ const detectPlatform = (projectRoot) => PLATFORMS.find((platform) => PLATFORMS_METADATA[platform]?.check?.()) ?? PLATFORMS.find((platform) => {
316
+ const platformDirectory = getPlatformDirectory(platform);
317
+ return platformDirectory !== void 0 && (0, node_fs.existsSync)(node_path.default.join(projectRoot, platformDirectory));
318
+ });
319
+ /**
294
320
  * Maps specific skill keys to special filenames if they differ from standard snake_case.
295
321
  */
296
322
  const SKILL_FILENAME_MAP = {};
@@ -424,6 +450,7 @@ exports.PLATFORMS = PLATFORMS;
424
450
  exports.PLATFORMS_METADATA = PLATFORMS_METADATA;
425
451
  exports.SKILLS = SKILLS;
426
452
  exports.SKILLS_METADATA = SKILLS_METADATA;
453
+ exports.detectPlatform = detectPlatform;
427
454
  exports.getInitialSkills = getInitialSkills;
428
455
  exports.installSkills = installSkills;
429
456
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["readAsset","path","fs","getMarkdownMetadata","v"],"sources":["../../../src/installSkills/index.ts"],"sourcesContent":["import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { readAsset } from 'utils:asset';\nimport { v } from '@intlayer/config/logger';\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 Markdown:\n 'Markdown / rich text content: md(), MDX components, MarkdownProvider, SSR',\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 DevTools: 'ESLint, LSP, VS Code & Chrome extensions, MCP server and CI/CD',\n Compat:\n 'Migrate from i18next, next-intl, react-intl, vue-i18n, Lingui… keeping their API',\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: 'Solid-specific syntax and hooks usage',\n Astro: 'Astro-specific usage, middleware and islands',\n Lit: 'Lit-specific ReactiveController usage (useIntlayer, useLocale)',\n Vanilla: 'Framework-less JavaScript usage (vanilla-intlayer)',\n Remix: 'Remix 3 router middleware and request-scoped hooks',\n Backend:\n 'Server-side usage for Express, Fastify, Hono, NestJS, AdonisJS and Elysia',\n} as const;\n\nexport type Skill = keyof typeof SKILLS_METADATA;\n\nexport const SKILLS = Object.keys(SKILLS_METADATA) as Skill[];\n\n/** Skills preselected for every project, whatever its stack. */\nconst BASE_SKILLS: Skill[] = [\n 'Usage',\n 'Content',\n 'Config',\n 'CLI',\n 'Compiler',\n 'DevTools',\n];\n\n/**\n * Packages whose presence in `package.json` preselects a framework skill.\n * Both the framework itself and its Intlayer adapter are listed, so a skill is\n * suggested before and after the adapter is installed.\n */\nconst SKILL_TRIGGER_PACKAGES: Partial<Record<Skill, string[]>> = {\n NextJS: ['next', 'next-intlayer'],\n React: [\n 'react',\n 'react-intlayer',\n 'react-native-intlayer',\n 'react-scripts-intlayer',\n 'lynx-intlayer',\n ],\n Preact: ['preact', 'preact-intlayer'],\n Solid: ['solid-js', '@solidjs/start', 'solid-intlayer'],\n Vue: ['vue', 'nuxt', 'vue-intlayer', 'nuxt-intlayer'],\n Svelte: ['svelte', '@sveltejs/kit', 'svelte-intlayer'],\n Angular: ['@angular/core', '@analogjs/platform', 'angular-intlayer'],\n Astro: ['astro', 'astro-intlayer'],\n Lit: ['lit', 'lit-intlayer'],\n Vanilla: ['vanilla-intlayer'],\n Remix: ['remix', 'remix-intlayer'],\n Compat: [\n 'i18next',\n 'react-i18next',\n 'next-i18next',\n 'next-intl',\n 'use-intl',\n 'react-intl',\n 'vue-i18n',\n '@lingui/core',\n '@lingui/react',\n '@nuxtjs/i18n',\n '@ngx-translate/core',\n '@jsverse/transloco',\n 'svelte-i18n',\n 'next-translate',\n 'node-polyglot',\n 'i18n-js',\n '@intlayer/i18next',\n '@intlayer/react-i18next',\n '@intlayer/next-i18next',\n '@intlayer/next-intl',\n '@intlayer/use-intl',\n '@intlayer/react-intl',\n '@intlayer/vue-i18n',\n '@intlayer/lingui',\n '@intlayer/sync-json-plugin',\n '@intlayer/sync-po-plugin',\n ],\n Backend: [\n 'express',\n 'fastify',\n 'hono',\n 'elysia',\n '@nestjs/core',\n '@adonisjs/core',\n 'express-intlayer',\n 'fastify-intlayer',\n 'hono-intlayer',\n 'elysia-intlayer',\n 'adonis-intlayer',\n ],\n};\n\n/**\n * Resolves the skills to preselect from the project's installed packages.\n *\n * @param dependencies - Merged `dependencies` and `devDependencies` of `package.json`.\n * @returns The base skills plus every framework skill whose packages are installed.\n */\nexport const getInitialSkills = (\n dependencies: Record<string, string>\n): Skill[] => {\n const detectedSkills = SKILLS.filter((skill) =>\n SKILL_TRIGGER_PACKAGES[skill]?.some(\n (packageName) => packageName in dependencies\n )\n );\n\n return [...BASE_SKILLS, ...detectedSkills];\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\nconst ALLOWED_FETCH_HOSTS = new Set(['intlayer.org']);\n\n/** Upper bound on the redirect chain a reference URL may take. */\nconst MAX_FETCH_REDIRECTS = 5;\n\n/**\n * Parses a URL and rejects it unless it is an HTTPS address on an allowed host.\n *\n * @param url - Absolute URL to validate.\n * @returns The parsed URL.\n * @throws When the protocol or host is not allowed.\n */\nconst parseAllowedUrl = (url: string | URL): URL => {\n const parsed = new URL(url);\n\n if (\n parsed.protocol !== 'https:' ||\n !ALLOWED_FETCH_HOSTS.has(parsed.hostname)\n ) {\n throw new Error(`Blocked fetch to disallowed host: ${parsed.hostname}`);\n }\n\n return parsed;\n};\n\n/**\n * Fetches the content of a URL using native fetch.\n *\n * Redirects are followed manually so every hop is re-checked against the host\n * allowlist — a redirect off `intlayer.org` is refused rather than silently\n * followed. Letting `fetch` refuse them outright (`redirect: 'error'`) instead\n * reported an unhelpful `TypeError: fetch failed` for a documentation URL that\n * merely moved.\n *\n * @param url - Absolute URL to read.\n * @returns The response body as text.\n */\nconst fetchUrlContent = async (url: string): Promise<string> => {\n let target = parseAllowedUrl(url);\n\n for (let hop = 0; hop <= MAX_FETCH_REDIRECTS; hop++) {\n const response = await fetch(target, { redirect: 'manual' });\n\n if (response.status >= 300 && response.status < 400) {\n const location = response.headers.get('location');\n\n if (!location) {\n throw new Error(`Failed to fetch ${url}: redirect without a location`);\n }\n\n target = parseAllowedUrl(new URL(location, target));\n continue;\n }\n\n if (!response.ok) {\n throw new Error(`Failed to fetch ${url}: ${response.statusText}`);\n }\n\n return response.text();\n }\n\n throw new Error(`Failed to fetch ${url}: too many redirects`);\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(skillContent.match(/https:\\/\\/intlayer\\.org\\/[^\\s)]+\\.md/g) || [])\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\n .filter((slug) => slug !== 'doc')\n .join('_')\n // Scoped package slugs (`@intlayer/babel`) must not create subfolders\n .replaceAll('/', '_');\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 `${v} Created ${createdSkills.length} skills in ${skillsBaseDir}`;\n};\n"],"mappings":";;;;;;;;;;;;;AASA,MAAa,kBAAk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.cjs","names":["existsSync","path","readAsset","fs","getMarkdownMetadata","v"],"sources":["../../../src/installSkills/index.ts"],"sourcesContent":["import { existsSync, promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { readAsset } from 'utils:asset';\nimport { v } from '@intlayer/config/logger';\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 Markdown:\n 'Markdown / rich text content: md(), MDX components, MarkdownProvider, SSR',\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 BundleOptimization:\n 'Purge, minify and import modes; writing code the bundle optimizer can follow',\n RemoteContent: 'How to use Intlayer with Remote/CMS/Server-side content',\n DevTools: 'ESLint, LSP, VS Code & Chrome extensions, MCP server and CI/CD',\n Compat:\n 'Migrate from i18next, next-intl, react-intl, vue-i18n, Lingui… keeping their API',\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: 'Solid-specific syntax and hooks usage',\n Astro: 'Astro-specific usage, middleware and islands',\n Lit: 'Lit-specific ReactiveController usage (useIntlayer, useLocale)',\n Vanilla: 'Framework-less JavaScript usage (vanilla-intlayer)',\n Remix: 'Remix 3 router middleware and request-scoped hooks',\n Backend:\n 'Server-side usage for Express, Fastify, Hono, NestJS, AdonisJS and Elysia',\n} as const;\n\nexport type Skill = keyof typeof SKILLS_METADATA;\n\nexport const SKILLS = Object.keys(SKILLS_METADATA) as Skill[];\n\n/** Skills preselected for every project, whatever its stack. */\nconst BASE_SKILLS: Skill[] = [\n 'Usage',\n 'Content',\n 'Config',\n 'CLI',\n 'Compiler',\n 'BundleOptimization',\n 'DevTools',\n];\n\n/**\n * Packages whose presence in `package.json` preselects a framework skill.\n * Both the framework itself and its Intlayer adapter are listed, so a skill is\n * suggested before and after the adapter is installed.\n */\nconst SKILL_TRIGGER_PACKAGES: Partial<Record<Skill, string[]>> = {\n NextJS: ['next', 'next-intlayer'],\n React: [\n 'react',\n 'react-intlayer',\n 'react-native-intlayer',\n 'react-scripts-intlayer',\n 'lynx-intlayer',\n ],\n Preact: ['preact', 'preact-intlayer'],\n Solid: ['solid-js', '@solidjs/start', 'solid-intlayer'],\n Vue: ['vue', 'nuxt', 'vue-intlayer', 'nuxt-intlayer'],\n Svelte: ['svelte', '@sveltejs/kit', 'svelte-intlayer'],\n Angular: ['@angular/core', '@analogjs/platform', 'angular-intlayer'],\n Astro: ['astro', 'astro-intlayer'],\n Lit: ['lit', 'lit-intlayer'],\n Vanilla: ['vanilla-intlayer'],\n Remix: ['remix', 'remix-intlayer'],\n Compat: [\n 'i18next',\n 'react-i18next',\n 'next-i18next',\n 'next-intl',\n 'use-intl',\n 'react-intl',\n 'vue-i18n',\n '@lingui/core',\n '@lingui/react',\n '@nuxtjs/i18n',\n '@ngx-translate/core',\n '@jsverse/transloco',\n 'svelte-i18n',\n 'next-translate',\n 'node-polyglot',\n 'i18n-js',\n '@intlayer/i18next',\n '@intlayer/react-i18next',\n '@intlayer/next-i18next',\n '@intlayer/next-intl',\n '@intlayer/use-intl',\n '@intlayer/react-intl',\n '@intlayer/vue-i18n',\n '@intlayer/lingui',\n '@intlayer/sync-json-plugin',\n '@intlayer/sync-po-plugin',\n ],\n Backend: [\n 'express',\n 'fastify',\n 'hono',\n 'elysia',\n '@nestjs/core',\n '@adonisjs/core',\n 'express-intlayer',\n 'fastify-intlayer',\n 'hono-intlayer',\n 'elysia-intlayer',\n 'adonis-intlayer',\n ],\n};\n\n/**\n * Resolves the skills to preselect from the project's installed packages.\n *\n * @param dependencies - Merged `dependencies` and `devDependencies` of `package.json`.\n * @returns The base skills plus every framework skill whose packages are installed.\n */\nexport const getInitialSkills = (\n dependencies: Record<string, string>\n): Skill[] => {\n const detectedSkills = SKILLS.filter((skill) =>\n SKILL_TRIGGER_PACKAGES[skill]?.some(\n (packageName) => packageName in dependencies\n )\n );\n\n return [...BASE_SKILLS, ...detectedSkills];\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: () =>\n process.env.CLAUDE === 'true' || process.env.CLAUDECODE === '1',\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 * Root folders too common to identify a platform on their own (e.g. `.github`\n * exists in most repositories regardless of the AI tool in use).\n */\nconst AMBIGUOUS_PLATFORM_DIRECTORIES = new Set([\n '.github',\n '.vscode',\n 'skills',\n]);\n\n/** Root config folder of a platform (e.g. `.cursor`), if it identifies it. */\nconst getPlatformDirectory = (platform: Platform): string | undefined => {\n const [rootDirectory] = (PLATFORMS_METADATA[platform]?.dir ?? '').split('/');\n\n if (!rootDirectory || AMBIGUOUS_PLATFORM_DIRECTORIES.has(rootDirectory)) {\n return undefined;\n }\n\n return rootDirectory;\n};\n\n/**\n * Detects the AI platform in use. The environment of the running tool wins;\n * otherwise the first platform whose config folder (`.claude`, `.cursor`…)\n * exists in the project root is returned.\n */\nexport const detectPlatform = (projectRoot: string): Platform | undefined =>\n PLATFORMS.find((platform) => PLATFORMS_METADATA[platform]?.check?.()) ??\n PLATFORMS.find((platform) => {\n const platformDirectory = getPlatformDirectory(platform);\n\n return (\n platformDirectory !== undefined &&\n existsSync(path.join(projectRoot, platformDirectory))\n );\n });\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\nconst ALLOWED_FETCH_HOSTS = new Set(['intlayer.org']);\n\n/** Upper bound on the redirect chain a reference URL may take. */\nconst MAX_FETCH_REDIRECTS = 5;\n\n/**\n * Parses a URL and rejects it unless it is an HTTPS address on an allowed host.\n *\n * @param url - Absolute URL to validate.\n * @returns The parsed URL.\n * @throws When the protocol or host is not allowed.\n */\nconst parseAllowedUrl = (url: string | URL): URL => {\n const parsed = new URL(url);\n\n if (\n parsed.protocol !== 'https:' ||\n !ALLOWED_FETCH_HOSTS.has(parsed.hostname)\n ) {\n throw new Error(`Blocked fetch to disallowed host: ${parsed.hostname}`);\n }\n\n return parsed;\n};\n\n/**\n * Fetches the content of a URL using native fetch.\n *\n * Redirects are followed manually so every hop is re-checked against the host\n * allowlist — a redirect off `intlayer.org` is refused rather than silently\n * followed. Letting `fetch` refuse them outright (`redirect: 'error'`) instead\n * reported an unhelpful `TypeError: fetch failed` for a documentation URL that\n * merely moved.\n *\n * @param url - Absolute URL to read.\n * @returns The response body as text.\n */\nconst fetchUrlContent = async (url: string): Promise<string> => {\n let target = parseAllowedUrl(url);\n\n for (let hop = 0; hop <= MAX_FETCH_REDIRECTS; hop++) {\n const response = await fetch(target, { redirect: 'manual' });\n\n if (response.status >= 300 && response.status < 400) {\n const location = response.headers.get('location');\n\n if (!location) {\n throw new Error(`Failed to fetch ${url}: redirect without a location`);\n }\n\n target = parseAllowedUrl(new URL(location, target));\n continue;\n }\n\n if (!response.ok) {\n throw new Error(`Failed to fetch ${url}: ${response.statusText}`);\n }\n\n return response.text();\n }\n\n throw new Error(`Failed to fetch ${url}: too many redirects`);\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(skillContent.match(/https:\\/\\/intlayer\\.org\\/[^\\s)]+\\.md/g) || [])\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\n .filter((slug) => slug !== 'doc')\n .join('_')\n // Scoped package slugs (`@intlayer/babel`) must not create subfolders\n .replaceAll('/', '_');\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 `${v} Created ${createdSkills.length} skills in ${skillsBaseDir}`;\n};\n"],"mappings":";;;;;;;;;;;;;AASA,MAAa,kBAAkB;CAC7B,QAAQ;CACR,SAAS;CACT,UACE;CACF,OAAO;CACP,KAAK;CACL,UACE;CACF,oBACE;CACF,eAAe;CACf,UAAU;CACV,QACE;CACF,QAAQ;CACR,OAAO;CACP,KAAK;CACL,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,OAAO;CACP,OAAO;CACP,KAAK;CACL,SAAS;CACT,OAAO;CACP,SACE;AACJ;AAIA,MAAa,SAAS,OAAO,KAAK,eAAe;;AAGjD,MAAM,cAAuB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;AAOA,MAAM,yBAA2D;CAC/D,QAAQ,CAAC,QAAQ,eAAe;CAChC,OAAO;EACL;EACA;EACA;EACA;EACA;CACF;CACA,QAAQ,CAAC,UAAU,iBAAiB;CACpC,OAAO;EAAC;EAAY;EAAkB;CAAgB;CACtD,KAAK;EAAC;EAAO;EAAQ;EAAgB;CAAe;CACpD,QAAQ;EAAC;EAAU;EAAiB;CAAiB;CACrD,SAAS;EAAC;EAAiB;EAAsB;CAAkB;CACnE,OAAO,CAAC,SAAS,gBAAgB;CACjC,KAAK,CAAC,OAAO,cAAc;CAC3B,SAAS,CAAC,kBAAkB;CAC5B,OAAO,CAAC,SAAS,gBAAgB;CACjC,QAAQ;EACN;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;CACA,SAAS;EACP;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAC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AAO,EAAE,CAAC,CAAC,CACtC,KAAK,GAAG;IAIb,WAAW,WAAW,GAAG,SAAS,OAAO;IAGzC,OAAO;KACL;KACA,4BAJiC;KAKjC;KACA;KACA,SAAS;IACX;GACF,SAAS,OAAO;IACd,QAAQ,KACN,mCAAmC,IAAI,aAAa,SACpD,KACF;IACA,OAAO;KAAE;KAAK,SAAS;IAAM;GAC/B;EACF,CAAC;EAED,MAAM,UAAU,MAAM,QAAQ,IAAI,gBAAgB;EAGlD,KAAK,MAAM,OAAO,SAChB,IAAI,IAAI,WAAW,IAAI,YAAY,IAAI,WAAW,IAAI,cAAc;GAElE,MAAMD,iBAAG,UACPF,kBAAK,KAAK,cAAc,IAAI,QAAQ,GACpC,IAAI,SACJ,OACF;GAGA,sBAAsB,oBAAoB,WACxC,IAAI,KACJ,IAAI,YACN;EACF;EAIF,MAAM,WAAWA,kBAAK,KAAK,UAAU,UAAU;EAC/C,MAAME,iBAAG,UAAU,UAAU,qBAAqB,OAAO;EACzD,cAAc,KAAK,GAAG,UAAU,UAAU;CAC5C;CAEA,IAAI,cAAc,WAAW,GAC3B,OAAO;CAGT,OAAO,GAAGE,0BAAE,WAAW,cAAc,OAAO,aAAa;AAC3D"}
@@ -1,16 +1,14 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
3
2
  let node_path = require("node:path");
4
3
  let _intlayer_config_logger = require("@intlayer/config/logger");
5
4
  let node_fs = require("node:fs");
6
5
  let _intlayer_config_built = require("@intlayer/config/built");
7
6
  let simple_git = require("simple-git");
8
- simple_git = require_runtime.__toESM(simple_git);
9
7
 
10
8
  //#region src/listGitFiles.ts
11
9
  const getGitRootDir = async () => {
12
10
  try {
13
- return (await (0, simple_git.default)().revparse(["--show-toplevel"])).trim();
11
+ return (await (0, simple_git.simpleGit)().revparse(["--show-toplevel"])).trim();
14
12
  } catch (error) {
15
13
  (0, _intlayer_config_logger.getAppLogger)({ log: _intlayer_config_built.log })(`Error getting git root directory: ${error}`, { level: "error" });
16
14
  return null;
@@ -18,7 +16,7 @@ const getGitRootDir = async () => {
18
16
  };
19
17
  const listGitFiles = async ({ mode, baseRef = "origin/main", currentRef = "HEAD", absolute = true }) => {
20
18
  try {
21
- const git = (0, simple_git.default)();
19
+ const git = (0, simple_git.simpleGit)();
22
20
  const diff = /* @__PURE__ */ new Set();
23
21
  if (mode.includes("untracked")) (await git.status()).not_added.forEach((file) => {
24
22
  diff.add(file);
@@ -46,7 +44,7 @@ const listGitFiles = async ({ mode, baseRef = "origin/main", currentRef = "HEAD"
46
44
  }
47
45
  };
48
46
  const listGitLines = async (filePath, { mode, baseRef = "origin/main", currentRef = "HEAD" }) => {
49
- const git = (0, simple_git.default)();
47
+ const git = (0, simple_git.simpleGit)();
50
48
  const changedLines = /* @__PURE__ */ new Set();
51
49
  /**
52
50
  * Extracts line numbers from a diff generated with `--unified=0`.
@@ -1 +1 @@
1
- {"version":3,"file":"listGitFiles.cjs","names":["simpleGit","getAppLogger","join","readFileSync"],"sources":["../../src/listGitFiles.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { log } from '@intlayer/config/built';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport simpleGit from 'simple-git';\n\nexport type DiffMode = 'gitDiff' | 'uncommitted' | 'unpushed' | 'untracked';\n\nconst getGitRootDir = async (): Promise<string | null> => {\n try {\n const git = simpleGit();\n const rootDir = await git.revparse(['--show-toplevel']);\n return rootDir.trim();\n } catch (error) {\n const appLogger = getAppLogger({ log });\n appLogger(`Error getting git root directory: ${error}`, {\n level: 'error',\n });\n return null;\n }\n};\n\nexport type ListGitFilesOptions = {\n mode: DiffMode[];\n baseRef?: string;\n currentRef?: string;\n absolute?: boolean;\n};\n\nexport const listGitFiles = async ({\n mode,\n baseRef = 'origin/main',\n currentRef = 'HEAD', // HEAD points to the current branch's latest commit\n absolute = true,\n}: ListGitFilesOptions) => {\n try {\n const git = simpleGit();\n const diff: Set<string> = new Set();\n\n if (mode.includes('untracked')) {\n const status = await git.status();\n status.not_added.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (mode.includes('uncommitted')) {\n // Get uncommitted changes\n const uncommittedDiff = await git.diff(['--name-only', 'HEAD']);\n\n const uncommittedFiles = uncommittedDiff.split('\\n').filter(Boolean);\n\n uncommittedFiles.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (mode.includes('unpushed')) {\n // Get unpushed commits\n const unpushedDiff = await git.diff(['--name-only', '@{push}...HEAD']);\n\n const unpushedFiles = unpushedDiff.split('\\n').filter(Boolean);\n\n unpushedFiles.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (mode.includes('gitDiff')) {\n // Get the base branch (usually main/master) from CI environment\n\n await git.fetch(baseRef);\n\n const diffBranch = await git.diff([\n '--name-only',\n `${baseRef}...${currentRef}`,\n ]);\n\n const gitDiffFiles = diffBranch.split('\\n').filter(Boolean);\n\n gitDiffFiles.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (absolute) {\n const gitRootDir = await getGitRootDir();\n if (!gitRootDir) {\n return [];\n }\n return Array.from(diff).map((file) => join(gitRootDir, file));\n }\n\n return Array.from(diff);\n } catch (error) {\n console.warn('Failed to get changes list:', error);\n }\n};\n\nexport type ListGitLinesOptions = {\n mode: DiffMode[];\n baseRef?: string;\n currentRef?: string;\n};\n\nexport const listGitLines = async (\n filePath: string,\n {\n mode,\n baseRef = 'origin/main',\n currentRef = 'HEAD', // HEAD points to the current branch's latest commit\n }: ListGitLinesOptions\n): Promise<number[]> => {\n const git = simpleGit();\n // We collect **line numbers** (1-based) that were modified/added by the diff.\n // Using a Set ensures uniqueness when the same line is reported by several modes.\n const changedLines: Set<number> = new Set();\n\n /**\n * Extracts line numbers from a diff generated with `--unified=0`.\n * Each hunk header looks like: @@ -<oldStart>,<oldCount> +<newStart>,<newCount> @@\n * We consider both the \"+\" (new) side for additions and the \"-\" (old) side for deletions.\n * For deletions, we add the line before and after the deletion point in the current file.\n */\n const collectLinesFromDiff = (diffOutput: string) => {\n const hunkRegex = /@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@/g;\n let match: RegExpExecArray | null;\n\n // biome-ignore lint/suspicious/noAssignInExpressions: Used in while loop condition\n while ((match = hunkRegex.exec(diffOutput)) !== null) {\n const oldCount = match[2] ? Number(match[2]) : 1;\n const newStart = Number(match[3]);\n const newCount = match[4] ? Number(match[4]) : 1;\n\n // Handle additions/modifications (+ side)\n if (newCount > 0) {\n for (let i = 0; i < newCount; i++) {\n changedLines.add(newStart + i);\n }\n }\n\n // Handle deletions (- side)\n if (oldCount > 0 && newCount === 0) {\n // For deletions, add the line before and after the deletion point\n // The deletion point in the new file is at newStart\n if (newStart > 1) {\n changedLines.add(newStart - 1); // Line before deletion\n }\n changedLines.add(newStart); // Line after deletion (if it exists)\n }\n }\n };\n\n // 1. Handle untracked files – when a file is untracked its entire content is new.\n if (mode.includes('untracked')) {\n const status = await git.status();\n const isUntracked = status.not_added.includes(filePath);\n if (isUntracked) {\n try {\n const content = readFileSync(filePath, 'utf-8');\n content.split('\\n').forEach((_, idx) => {\n changedLines.add(idx + 1);\n });\n } catch {\n // ignore read errors – file may have been deleted, etc.\n }\n }\n }\n\n // 2. Uncommitted changes (working tree vs HEAD)\n if (mode.includes('uncommitted')) {\n const diffOutput = await git.diff(['--unified=0', 'HEAD', '--', filePath]);\n collectLinesFromDiff(diffOutput);\n }\n\n // 3. Unpushed commits – compare local branch to its upstream\n if (mode.includes('unpushed')) {\n const diffOutput = await git.diff([\n '--unified=0',\n '@{push}...HEAD',\n '--',\n filePath,\n ]);\n collectLinesFromDiff(diffOutput);\n }\n\n // 4. Regular git diff between baseRef and currentRef (e.g., CI pull-request diff)\n if (mode.includes('gitDiff')) {\n await git.fetch(baseRef);\n const diffOutput = await git.diff([\n '--unified=0',\n `${baseRef}...${currentRef}`,\n '--',\n filePath,\n ]);\n collectLinesFromDiff(diffOutput);\n }\n\n // Return the list sorted for convenience\n return Array.from(changedLines).sort((a, b) => a - b);\n};\n"],"mappings":";;;;;;;;;;AAQA,MAAM,gBAAgB,YAAoC;CACxD,IAAI;EAGF,QAAO,UAFKA,oBACY,CAAC,CAAC,SAAS,CAAC,iBAAiB,CAAC,EACxC,CAAC,KAAK;CACtB,SAAS,OAAO;EAEd,IADkBC,sCAAa,EAAE,gCAAI,CAC7B,CAAC,CAAC,qCAAqC,SAAS,EACtD,OAAO,QACT,CAAC;EACD,OAAO;CACT;AACF;AASA,MAAa,eAAe,OAAO,EACjC,MACA,UAAU,eACV,aAAa,QACb,WAAW,WACc;CACzB,IAAI;EACF,MAAM,UAAMD,oBAAU;EACtB,MAAM,uBAAoB,IAAI,IAAI;EAElC,IAAI,KAAK,SAAS,WAAW,GAE3B,OADqB,IAAI,OAAO,EAC1B,CAAC,UAAU,SAAS,SAAS;GACjC,KAAK,IAAI,IAAI;EACf,CAAC;EAGH,IAAI,KAAK,SAAS,aAAa,GAM7B,CAFyB,MAFK,IAAI,KAAK,CAAC,eAAe,MAAM,CAAC,EAEtB,CAAC,MAAM,IAAI,CAAC,CAAC,OAAO,OAE7C,CAAC,CAAC,SAAS,SAAS;GACjC,KAAK,IAAI,IAAI;EACf,CAAC;EAGH,IAAI,KAAK,SAAS,UAAU,GAM1B,CAFsB,MAFK,IAAI,KAAK,CAAC,eAAe,gBAAgB,CAAC,EAEnC,CAAC,MAAM,IAAI,CAAC,CAAC,OAAO,OAE1C,CAAC,CAAC,SAAS,SAAS;GAC9B,KAAK,IAAI,IAAI;EACf,CAAC;EAGH,IAAI,KAAK,SAAS,SAAS,GAAG;GAG5B,MAAM,IAAI,MAAM,OAAO;GASvB,CAFqB,MALI,IAAI,KAAK,CAChC,eACA,GAAG,QAAQ,KAAK,YAClB,CAAC,EAE8B,CAAC,MAAM,IAAI,CAAC,CAAC,OAAO,OAExC,CAAC,CAAC,SAAS,SAAS;IAC7B,KAAK,IAAI,IAAI;GACf,CAAC;E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C;CAIjC,IAAI,KAAK,SAAS,UAAU,GAO1B,qBAAqB,MANI,IAAI,KAAK;EAChC;EACA;EACA;EACA;CACF,CAAC,CAC8B;CAIjC,IAAI,KAAK,SAAS,SAAS,GAAG;EAC5B,MAAM,IAAI,MAAM,OAAO;EAOvB,qBAAqB,MANI,IAAI,KAAK;GAChC;GACA,GAAG,QAAQ,KAAK;GAChB;GACA;EACF,CAAC,CAC8B;CACjC;CAGA,OAAO,MAAM,KAAK,YAAY,CAAC,CAAC,MAAM,GAAG,MAAM,IAAI,CAAC;AACtD"}
1
+ {"version":3,"file":"listGitFiles.cjs","names":["simpleGit","getAppLogger","join","readFileSync"],"sources":["../../src/listGitFiles.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { log } from '@intlayer/config/built';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport { simpleGit } from 'simple-git';\n\nexport type DiffMode = 'gitDiff' | 'uncommitted' | 'unpushed' | 'untracked';\n\nconst getGitRootDir = async (): Promise<string | null> => {\n try {\n const git = simpleGit();\n const rootDir = await git.revparse(['--show-toplevel']);\n return rootDir.trim();\n } catch (error) {\n const appLogger = getAppLogger({ log });\n appLogger(`Error getting git root directory: ${error}`, {\n level: 'error',\n });\n return null;\n }\n};\n\nexport type ListGitFilesOptions = {\n mode: DiffMode[];\n baseRef?: string;\n currentRef?: string;\n absolute?: boolean;\n};\n\nexport const listGitFiles = async ({\n mode,\n baseRef = 'origin/main',\n currentRef = 'HEAD', // HEAD points to the current branch's latest commit\n absolute = true,\n}: ListGitFilesOptions) => {\n try {\n const git = simpleGit();\n const diff: Set<string> = new Set();\n\n if (mode.includes('untracked')) {\n const status = await git.status();\n status.not_added.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (mode.includes('uncommitted')) {\n // Get uncommitted changes\n const uncommittedDiff = await git.diff(['--name-only', 'HEAD']);\n\n const uncommittedFiles = uncommittedDiff.split('\\n').filter(Boolean);\n\n uncommittedFiles.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (mode.includes('unpushed')) {\n // Get unpushed commits\n const unpushedDiff = await git.diff(['--name-only', '@{push}...HEAD']);\n\n const unpushedFiles = unpushedDiff.split('\\n').filter(Boolean);\n\n unpushedFiles.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (mode.includes('gitDiff')) {\n // Get the base branch (usually main/master) from CI environment\n\n await git.fetch(baseRef);\n\n const diffBranch = await git.diff([\n '--name-only',\n `${baseRef}...${currentRef}`,\n ]);\n\n const gitDiffFiles = diffBranch.split('\\n').filter(Boolean);\n\n gitDiffFiles.forEach((file) => {\n diff.add(file);\n });\n }\n\n if (absolute) {\n const gitRootDir = await getGitRootDir();\n if (!gitRootDir) {\n return [];\n }\n return Array.from(diff).map((file) => join(gitRootDir, file));\n }\n\n return Array.from(diff);\n } catch (error) {\n console.warn('Failed to get changes list:', error);\n }\n};\n\nexport type ListGitLinesOptions = {\n mode: DiffMode[];\n baseRef?: string;\n currentRef?: string;\n};\n\nexport const listGitLines = async (\n filePath: string,\n {\n mode,\n baseRef = 'origin/main',\n currentRef = 'HEAD', // HEAD points to the current branch's latest commit\n }: ListGitLinesOptions\n): Promise<number[]> => {\n const git = simpleGit();\n // We collect **line numbers** (1-based) that were modified/added by the diff.\n // Using a Set ensures uniqueness when the same line is reported by several modes.\n const changedLines: Set<number> = new Set();\n\n /**\n * Extracts line numbers from a diff generated with `--unified=0`.\n * Each hunk header looks like: @@ -<oldStart>,<oldCount> +<newStart>,<newCount> @@\n * We consider both the \"+\" (new) side for additions and the \"-\" (old) side for deletions.\n * For deletions, we add the line before and after the deletion point in the current file.\n */\n const collectLinesFromDiff = (diffOutput: string) => {\n const hunkRegex = /@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@/g;\n let match: RegExpExecArray | null;\n\n // biome-ignore lint/suspicious/noAssignInExpressions: Used in while loop condition\n while ((match = hunkRegex.exec(diffOutput)) !== null) {\n const oldCount = match[2] ? Number(match[2]) : 1;\n const newStart = Number(match[3]);\n const newCount = match[4] ? Number(match[4]) : 1;\n\n // Handle additions/modifications (+ side)\n if (newCount > 0) {\n for (let i = 0; i < newCount; i++) {\n changedLines.add(newStart + i);\n }\n }\n\n // Handle deletions (- side)\n if (oldCount > 0 && newCount === 0) {\n // For deletions, add the line before and after the deletion point\n // The deletion point in the new file is at newStart\n if (newStart > 1) {\n changedLines.add(newStart - 1); // Line before deletion\n }\n changedLines.add(newStart); // Line after deletion (if it exists)\n }\n }\n };\n\n // 1. Handle untracked files – when a file is untracked its entire content is new.\n if (mode.includes('untracked')) {\n const status = await git.status();\n const isUntracked = status.not_added.includes(filePath);\n if (isUntracked) {\n try {\n const content = readFileSync(filePath, 'utf-8');\n content.split('\\n').forEach((_, idx) => {\n changedLines.add(idx + 1);\n });\n } catch {\n // ignore read errors – file may have been deleted, etc.\n }\n }\n }\n\n // 2. Uncommitted changes (working tree vs HEAD)\n if (mode.includes('uncommitted')) {\n const diffOutput = await git.diff(['--unified=0', 'HEAD', '--', filePath]);\n collectLinesFromDiff(diffOutput);\n }\n\n // 3. Unpushed commits – compare local branch to its upstream\n if (mode.includes('unpushed')) {\n const diffOutput = await git.diff([\n '--unified=0',\n '@{push}...HEAD',\n '--',\n filePath,\n ]);\n collectLinesFromDiff(diffOutput);\n }\n\n // 4. Regular git diff between baseRef and currentRef (e.g., CI pull-request diff)\n if (mode.includes('gitDiff')) {\n await git.fetch(baseRef);\n const diffOutput = await git.diff([\n '--unified=0',\n `${baseRef}...${currentRef}`,\n '--',\n filePath,\n ]);\n collectLinesFromDiff(diffOutput);\n }\n\n // Return the list sorted for convenience\n return Array.from(changedLines).sort((a, b) => a - b);\n};\n"],"mappings":";;;;;;;;AAQA,MAAM,gBAAgB,YAAoC;CACxD,IAAI;EAGF,QAAO,UAFKA,sBACY,CAAC,CAAC,SAAS,CAAC,iBAAiB,CAAC,EACxC,CAAC,KAAK;CACtB,SAAS,OAAO;EAEd,IADkBC,sCAAa,EAAE,gC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EACF,CAAC,CAC8B;CACjC;CAGA,OAAO,MAAM,KAAK,YAAY,CAAC,CAAC,MAAM,GAAG,MAAM,IAAI,CAAC;AACtD"}
@@ -5,7 +5,6 @@ let _intlayer_config_node = require("@intlayer/config/node");
5
5
  let fast_glob = require("fast-glob");
6
6
  fast_glob = require_runtime.__toESM(fast_glob);
7
7
  let simple_git = require("simple-git");
8
- simple_git = require_runtime.__toESM(simple_git);
9
8
 
10
9
  //#region src/listProjects.ts
11
10
  /**
@@ -14,7 +13,7 @@ simple_git = require_runtime.__toESM(simple_git);
14
13
  */
15
14
  const getGitRootDir = async (cwd) => {
16
15
  try {
17
- return (await (cwd ? (0, simple_git.default)(cwd) : (0, simple_git.default)()).revparse(["--show-toplevel"])).trim();
16
+ return (await (cwd ? (0, simple_git.simpleGit)(cwd) : (0, simple_git.simpleGit)()).revparse(["--show-toplevel"])).trim();
18
17
  } catch (_error) {
19
18
  return null;
20
19
  }
@@ -1 +1 @@
1
- {"version":3,"file":"listProjects.cjs","names":["simpleGit","configurationFilesCandidates","fg","dirname"],"sources":["../../src/listProjects.ts"],"sourcesContent":["import { dirname } from 'node:path';\nimport { configurationFilesCandidates } from '@intlayer/config/node';\nimport fg from 'fast-glob';\nimport simpleGit from 'simple-git';\n\nexport type ListProjectsOptions = {\n /**\n * Base directory to search from\n * @default process.cwd()\n */\n baseDir?: string;\n /**\n * If true, search from the git root directory instead of baseDir\n * @default false\n */\n gitRoot?: boolean;\n};\n\n/**\n * Returns the git repository root directory, or `null` when the given\n * directory is not inside a git repository.\n */\nexport const getGitRootDir = async (cwd?: string): Promise<string | null> => {\n try {\n const git = cwd ? simpleGit(cwd) : simpleGit();\n const rootDir = await git.revparse(['--show-toplevel']);\n return rootDir.trim();\n } catch (_error) {\n return null;\n }\n};\n\n/**\n * List all Intlayer projects by searching for configuration files\n *\n * @param options - Options for listing projects\n * @returns Array of absolute paths to project directories containing Intlayer config\n */\nexport const listProjects = async (\n options?: ListProjectsOptions\n): Promise<{ searchDir: string; projectsPath: string[] }> => {\n let searchDir = options?.baseDir ?? process.cwd();\n\n // If gitRoot option is enabled, try to get the git root directory\n if (options?.gitRoot) {\n const gitRootDir = await getGitRootDir(searchDir);\n if (gitRootDir) {\n searchDir = gitRootDir;\n }\n }\n\n // Build glob patterns for all config file candidates\n const configPatterns = configurationFilesCandidates.map(\n (fileName) => `**/${fileName}`\n );\n\n // Search for all config files\n const configFiles = await fg(configPatterns, {\n cwd: searchDir,\n absolute: true,\n ignore: ['**/node_modules/**', '**/.git/**'],\n dot: true, // Include dot files like .intlayerrc\n });\n\n // Extract unique directory paths from config files\n const projectDirs = [...new Set(configFiles.map((file) => dirname(file)))];\n\n // Sort alphabetically for consistent output\n return { searchDir, projectsPath: projectDirs.sort() };\n};\n"],"mappings":";;;;;;;;;;;;;;AAsBA,MAAa,gBAAgB,OAAO,QAAyC;CAC3E,IAAI;EAGF,QAAO,OAFK,UAAMA,oBAAU,GAAG,QAAIA,oBAAU,EACpB,CAAC,SAAS,CAAC,iBAAiB,CAAC,EACxC,CAAC,KAAK;CACtB,SAAS,QAAQ;EACf,OAAO;CACT;AACF;;;;;;;AAQA,MAAa,eAAe,OAC1B,YAC2D;CAC3D,IAAI,YAAY,SAAS,WAAW,QAAQ,IAAI;CAGhD,IAAI,SAAS,SAAS;EACpB,MAAM,aAAa,MAAM,cAAc,SAAS;EAChD,IAAI,YACF,YAAY;CAEhB;CAGA,MAAM,iBAAiBC,mDAA6B,KACjD,aAAa,MAAM,UACtB;CAGA,MAAM,cAAc,UAAMC,mBAAG,gBAAgB;EAC3C,KAAK;EACL,UAAU;EACV,QAAQ,CAAC,sBAAsB,YAAY;EAC3C,KAAK;CACP,CAAC;CAGD,MAAM,cAAc,CAAC,GAAG,IAAI,IAAI,YAAY,KAAK,aAASC,mBAAQ,IAAI,CAAC,CAAC,CAAC;CAGzE,OAAO;EAAE;EAAW,cAAc,YAAY,KAAK;CAAE;AACvD"}
1
+ {"version":3,"file":"listProjects.cjs","names":["simpleGit","configurationFilesCandidates","fg","dirname"],"sources":["../../src/listProjects.ts"],"sourcesContent":["import { dirname } from 'node:path';\nimport { configurationFilesCandidates } from '@intlayer/config/node';\nimport fg from 'fast-glob';\nimport { simpleGit } from 'simple-git';\n\nexport type ListProjectsOptions = {\n /**\n * Base directory to search from\n * @default process.cwd()\n */\n baseDir?: string;\n /**\n * If true, search from the git root directory instead of baseDir\n * @default false\n */\n gitRoot?: boolean;\n};\n\n/**\n * Returns the git repository root directory, or `null` when the given\n * directory is not inside a git repository.\n */\nexport const getGitRootDir = async (cwd?: string): Promise<string | null> => {\n try {\n const git = cwd ? simpleGit(cwd) : simpleGit();\n const rootDir = await git.revparse(['--show-toplevel']);\n return rootDir.trim();\n } catch (_error) {\n return null;\n }\n};\n\n/**\n * List all Intlayer projects by searching for configuration files\n *\n * @param options - Options for listing projects\n * @returns Array of absolute paths to project directories containing Intlayer config\n */\nexport const listProjects = async (\n options?: ListProjectsOptions\n): Promise<{ searchDir: string; projectsPath: string[] }> => {\n let searchDir = options?.baseDir ?? process.cwd();\n\n // If gitRoot option is enabled, try to get the git root directory\n if (options?.gitRoot) {\n const gitRootDir = await getGitRootDir(searchDir);\n if (gitRootDir) {\n searchDir = gitRootDir;\n }\n }\n\n // Build glob patterns for all config file candidates\n const configPatterns = configurationFilesCandidates.map(\n (fileName) => `**/${fileName}`\n );\n\n // Search for all config files\n const configFiles = await fg(configPatterns, {\n cwd: searchDir,\n absolute: true,\n ignore: ['**/node_modules/**', '**/.git/**'],\n dot: true, // Include dot files like .intlayerrc\n });\n\n // Extract unique directory paths from config files\n const projectDirs = [...new Set(configFiles.map((file) => dirname(file)))];\n\n // Sort alphabetically for consistent output\n return { searchDir, projectsPath: projectDirs.sort() };\n};\n"],"mappings":";;;;;;;;;;;;;AAsBA,MAAa,gBAAgB,OAAO,QAAyC;CAC3E,IAAI;EAGF,QAAO,OAFK,UAAMA,sBAAU,GAAG,QAAIA,sBAAU,EACpB,CAAC,SAAS,CAAC,iBAAiB,CAAC,EACxC,CAAC,KAAK;CACtB,SAAS,QAAQ;EACf,OAAO;CACT;AACF;;;;;;;AAQA,MAAa,eAAe,OAC1B,YAC2D;CAC3D,IAAI,YAAY,SAAS,WAAW,QAAQ,IAAI;CAGhD,IAAI,SAAS,SAAS;EACpB,MAAM,aAAa,MAAM,cAAc,SAAS;EAChD,IAAI,YACF,YAAY;CAEhB;CAGA,MAAM,iBAAiBC,mDAA6B,KACjD,aAAa,MAAM,UACtB;CAGA,MAAM,cAAc,UAAMC,mBAAG,gBAAgB;EAC3C,KAAK;EACL,UAAU;EACV,QAAQ,CAAC,sBAAsB,YAAY;EAC3C,KAAK;CACP,CAAC;CAGD,MAAM,cAAc,CAAC,GAAG,IAAI,IAAI,YAAY,KAAK,aAASC,mBAAQ,IAAI,CAAC,CAAC,CAAC;CAGzE,OAAO;EAAE;EAAW,cAAc,YAAY,KAAK;CAAE;AACvD"}
@@ -81,6 +81,14 @@ const loadDictionaries = async (contentDeclarationsPaths, configuration) => {
81
81
  const { plugins } = configuration;
82
82
  const loadDictionariesStartTime = Date.now();
83
83
  (0, _intlayer_config_logger.getAppLogger)(configuration)("Dictionaries:", { isVerbose: true });
84
+ const hasRemoteDictionaries = Boolean(configuration.editor.clientId && configuration.editor.clientSecret);
85
+ if (hasRemoteDictionaries) logger.setExpectRemote(true);
86
+ const remoteDictionariesPromise = hasRemoteDictionaries ? require_loadDictionaries_loadRemoteDictionaries.loadRemoteDictionaries(configuration, setLoadDictionariesStatus, {
87
+ onStartRemoteCheck: () => logger.startRemoteCheck(),
88
+ onStopRemoteCheck: () => logger.stopRemoteCheck(),
89
+ onError: (error) => logger.setRemoteError(error)
90
+ }).then((dictionaries) => require_filterInvalidDictionaries.filterInvalidDictionaries(dictionaries, configuration)).then((dictionaries) => require_formatDictionary.formatDictionaries(dictionaries)) : Promise.resolve([]);
91
+ remoteDictionariesPromise.catch(() => void 0);
84
92
  const pluginsWithLoadDictionaries = (await Promise.all(plugins ?? [])).filter((plugin) => plugin.loadDictionaries);
85
93
  logger.setPluginNames(pluginsWithLoadDictionaries.map(({ name }) => name));
86
94
  const loadPluginDictionariesPromise = pluginsWithLoadDictionaries.map(async (plugin) => {
@@ -103,14 +111,7 @@ const loadDictionaries = async (contentDeclarationsPaths, configuration) => {
103
111
  status: "built"
104
112
  }));
105
113
  setLoadDictionariesStatus(localDictionariesStatus);
106
- const hasRemoteDictionaries = Boolean(configuration.editor.clientId && configuration.editor.clientSecret);
107
- if (hasRemoteDictionaries) logger.setExpectRemote(true);
108
- let remoteDictionaries = [];
109
- if (hasRemoteDictionaries) remoteDictionaries = await require_loadDictionaries_loadRemoteDictionaries.loadRemoteDictionaries(configuration, setLoadDictionariesStatus, {
110
- onStartRemoteCheck: () => logger.startRemoteCheck(),
111
- onStopRemoteCheck: () => logger.stopRemoteCheck(),
112
- onError: (e) => logger.setRemoteError(e)
113
- }).then((dictionaries) => require_filterInvalidDictionaries.filterInvalidDictionaries(dictionaries, configuration)).then((dictionaries) => require_formatDictionary.formatDictionaries(dictionaries));
114
+ const remoteDictionaries = await remoteDictionariesPromise;
114
115
  const remoteDictionariesTime = Date.now();
115
116
  logger.finish();
116
117
  printSummary(configuration);
@@ -1 +1 @@
1
- {"version":3,"file":"loadDictionaries.cjs","names":["DictionariesLogger","ANSIColors","getAppLogger","colorize","colon","colorizeKey","filterInvalidDictionaries","formatDictionaries","loadContentDeclarations","loadRemoteDictionaries"],"sources":["../../../src/loadDictionaries/loadDictionaries.ts"],"sourcesContent":["import * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeKey,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { filterInvalidDictionaries } from '../filterInvalidDictionaries';\nimport { formatDictionaries } from '../formatDictionary';\nimport { loadContentDeclarations } from './loadContentDeclaration';\nimport { loadRemoteDictionaries } from './loadRemoteDictionaries';\nimport { DictionariesLogger } from './log';\n\nexport type DictionariesStatus = {\n dictionaryKey: string;\n type: 'local' | 'remote';\n status:\n | 'pending' // Key found but not fetched yet\n | 'fetching' // If dictionary fetch is in progress\n | 'fetched' // If dictionary fetch succeeded\n | 'error' // If dictionary fetch failed\n | 'imported' // If dictionary already fetched and still up to date\n | 'found' // If dictionary key is found but promise is not resolved yet (ex: fetching distant content)\n | 'building' // If dictionary is being built\n | 'built'; // If dictionary is built;\n error?: string;\n};\n\nlet loadDictionariesStatus: DictionariesStatus[] = [];\nconst logger = new DictionariesLogger();\n\nconst setLoadDictionariesStatus = (statuses: DictionariesStatus[]) => {\n const updated: DictionariesStatus[] = [...loadDictionariesStatus];\n\n for (const incoming of statuses) {\n const index = updated.findIndex(\n (s) =>\n s.dictionaryKey === incoming.dictionaryKey && s.type === incoming.type\n );\n if (index >= 0) {\n updated[index] = incoming;\n } else {\n updated.push(incoming);\n }\n }\n\n loadDictionariesStatus = updated;\n logger.update(statuses);\n\n return updated;\n};\n\ntype StatusRecord = {\n local?: DictionariesStatus['status'];\n remote?: DictionariesStatus['status'];\n};\n\nconst iconFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'built':\n case 'imported':\n case 'fetched':\n return '✔';\n case 'error':\n return '✖';\n default:\n return '⏲';\n }\n};\n\nconst colorFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'built':\n case 'imported':\n case 'fetched':\n return ANSIColors.GREEN;\n case 'error':\n return ANSIColors.RED;\n default:\n return ANSIColors.BLUE;\n }\n};\n\nconst printSummary = (configuration: IntlayerConfig) => {\n if (configuration.log.mode !== 'verbose') return;\n\n const appLogger = getAppLogger(configuration);\n\n // Aggregate by dictionary key\n const byKey = new Map<string, StatusRecord>();\n for (const status of loadDictionariesStatus) {\n const rec = byKey.get(status.dictionaryKey) ?? {};\n if (status.type === 'local') rec.local = status.status;\n if (status.type === 'remote') rec.remote = status.status;\n byKey.set(status.dictionaryKey, rec);\n }\n\n const keys = Array.from(byKey.keys()).sort((a, b) => a.localeCompare(b));\n\n // Compute the max visible length of the local label to align distant labels\n let maxLocalLabelLen = 0;\n for (const key of keys) {\n const rec = byKey.get(key)!;\n if (rec.local) {\n const visibleLocal = `[local: ${iconFor(rec.local)} ${rec.local}]`;\n if (visibleLocal.length > maxLocalLabelLen) {\n maxLocalLabelLen = visibleLocal.length;\n }\n }\n }\n\n for (const key of keys) {\n const rec = byKey.get(key)!;\n const labels: string[] = [];\n\n if (rec.local) {\n const inner = colorize(\n `${iconFor(rec.local)} ${rec.local}`,\n colorFor(rec.local)\n );\n const coloredLocal =\n `${ANSIColors.GREY}[` +\n colorize('local: ', ANSIColors.GREY) +\n inner +\n `${ANSIColors.GREY}]${ANSIColors.RESET}`;\n\n // Pad to align distant label across rows\n const visibleLocal = `[local: ${iconFor(rec.local)} ${rec.local}]`;\n const pad = Math.max(0, maxLocalLabelLen - visibleLocal.length);\n labels.push(coloredLocal + ' '.repeat(pad));\n } else {\n // If no local label, insert spaces to keep distant aligned\n labels.push(' '.repeat(maxLocalLabelLen));\n }\n\n if (rec.remote) {\n const inner = colorize(\n `${iconFor(rec.remote)} ${rec.remote}`,\n colorFor(rec.remote)\n );\n labels.push(\n `${ANSIColors.GREY}[` +\n colorize('distant: ', ANSIColors.GREY) +\n inner +\n `${ANSIColors.GREY}]${ANSIColors.RESET}`\n );\n }\n\n appLogger(\n ` - ${colon(colorizeKey(key), { colSize: keys })} ${labels.join(' ')}`\n );\n }\n};\n\nexport const loadDictionaries = async (\n contentDeclarationsPaths: string[] | string,\n configuration: IntlayerConfig\n): Promise<{\n localDictionaries: Dictionary[];\n remoteDictionaries: Dictionary[];\n pluginDictionaries: Dictionary[];\n time: {\n localDictionaries: number;\n remoteDictionaries: number;\n pluginDictionaries: number;\n };\n}> => {\n const { plugins } = configuration;\n const loadDictionariesStartTime = Date.now();\n const appLogger = getAppLogger(configuration);\n\n appLogger('Dictionaries:', { isVerbose: true });\n\n // Load additional dictionaries via plugins (e.g., ICU JSON ingestion)\n const resolvedPlugins = await Promise.all(plugins ?? []);\n\n const pluginsWithLoadDictionaries = resolvedPlugins.filter(\n (plugin) => plugin.loadDictionaries\n );\n\n logger.setPluginNames(pluginsWithLoadDictionaries.map(({ name }) => name));\n\n const loadPluginDictionariesPromise = pluginsWithLoadDictionaries.map(\n async (plugin) => {\n try {\n const res = await plugin.loadDictionaries?.({\n configuration,\n });\n\n return (res as Dictionary[] | undefined) ?? [];\n } catch (error) {\n logger.setPluginError(error as Error, plugin.name);\n\n return [];\n }\n }\n );\n\n const pluginDictionaries: Dictionary[] = await Promise.all(\n loadPluginDictionariesPromise as Promise<Dictionary[]>[]\n )\n .then((dictionaries) => dictionaries.flat())\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n\n logger.setPluginTotal(pluginDictionaries.length);\n logger.setPluginDone(pluginDictionaries.length);\n\n const pluginDictionariesTime = Date.now();\n\n const files = Array.isArray(contentDeclarationsPaths)\n ? contentDeclarationsPaths\n : [contentDeclarationsPaths];\n\n const localDictionaries: Dictionary[] = await loadContentDeclarations(\n files,\n configuration,\n setLoadDictionariesStatus\n )\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n\n const localDictionariesTime = Date.now();\n\n const localDictionariesStatus = localDictionaries.map(\n (dictionary) =>\n ({\n dictionaryKey: dictionary.key,\n type: 'local',\n status: 'built',\n }) as const\n );\n\n setLoadDictionariesStatus(localDictionariesStatus);\n\n const hasRemoteDictionaries = Boolean(\n configuration.editor.clientId && configuration.editor.clientSecret\n );\n\n if (hasRemoteDictionaries) {\n // We expect to fetch remote dictionaries soon; suppress a transient local-only render\n logger.setExpectRemote(true);\n }\n\n let remoteDictionaries: Dictionary[] = [];\n\n if (hasRemoteDictionaries) {\n remoteDictionaries = await loadRemoteDictionaries(\n configuration,\n setLoadDictionariesStatus,\n {\n onStartRemoteCheck: () => logger.startRemoteCheck(),\n onStopRemoteCheck: () => logger.stopRemoteCheck(),\n onError: (e) => logger.setRemoteError(e),\n }\n )\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n }\n\n const remoteDictionariesTime = Date.now();\n\n // Stop spinner and show final progress line(s)\n logger.finish();\n\n printSummary(configuration);\n\n return {\n localDictionaries,\n remoteDictionaries,\n pluginDictionaries,\n time: {\n localDictionaries: localDictionariesTime - pluginDictionariesTime,\n remoteDictionaries: remoteDictionariesTime - localDictionariesTime,\n pluginDictionaries: pluginDictionariesTime - loadDictionariesStartTime,\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;AA8BA,IAAI,yBAA+C,CAAC;AACpD,MAAM,SAAS,IAAIA,gDAAmB;AAEtC,MAAM,6BAA6B,aAAmC;CACpE,MAAM,UAAgC,CAAC,GAAG,sBAAsB;CAEhE,KAAK,MAAM,YAAY,UAAU;EAC/B,MAAM,QAAQ,QAAQ,WACnB,MACC,EAAE,kBAAkB,SAAS,iBAAiB,EAAE,SAAS,SAAS,IACtE;EACA,IAAI,SAAS,GACX,QAAQ,SAAS;OAEjB,QAAQ,KAAK,QAAQ;CAEzB;CAEA,yBAAyB;CACzB,OAAO,OAAO,QAAQ;CAEtB,OAAO;AACT;AAOA,MAAM,WAAW,WAAyC;CACxD,QAAQ,QAAR;EACE,KAAK;EACL,KAAK;EACL,KAAK,WACH,OAAO;EACT,KAAK,SACH,OAAO;EACT,SACE,OAAO;CACX;AACF;AAEA,MAAM,YAAY,WAAyC;CACzD,QAAQ,QAAR;EACE,KAAK;EACL,KAAK;EACL,KAAK,WACH,OAAOC,wBAAW;EACpB,KAAK,SACH,OAAOA,wBAAW;EACpB,SACE,OAAOA,wBAAW;CACtB;AACF;AAEA,MAAM,gBAAgB,kBAAkC;CACtD,IAAI,cAAc,IAAI,SAAS,WAAW;CAE1C,MAAM,gBAAYC,sCAAa,aAAa;CAG5C,MAA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,MAAM,iBACLF,4DAA0B,cAAc,aAAa,CACvD,CAAC,CACA,MAAM,iBAAiBC,4CAAmB,YAAY,CAAC;CAE1D,MAAM,wBAAwB,KAAK,IAAI;CAEvC,MAAM,0BAA0B,kBAAkB,KAC/C,gBACE;EACC,eAAe,WAAW;EAC1B,MAAM;EACN,QAAQ;CACV,EACJ;CAEA,0BAA0B,uBAAuB;CAEjD,MAAM,wBAAwB,QAC5B,cAAc,OAAO,YAAY,cAAc,OAAO,YACxD;CAEA,IAAI,uBAEF,OAAO,gBAAgB,IAAI;CAG7B,IAAI,qBAAmC,CAAC;CAExC,IAAI,uBACF,qBAAqB,MAAME,uEACzB,eACA,2BACA;EACE,0BAA0B,OAAO,iBAAiB;EAClD,yBAAyB,OAAO,gBAAgB;EAChD,UAAU,MAAM,OAAO,eAAe,CAAC;CACzC,CACF,CAAC,CACE,MAAM,iBACLH,4DAA0B,cAAc,aAAa,CACvD,CAAC,CACA,MAAM,iBAAiBC,4CAAmB,YAAY,CAAC;CAG5D,MAAM,yBAAyB,KAAK,IAAI;CAGxC,OAAO,OAAO;CAEd,aAAa,aAAa;CAE1B,OAAO;EACL;EACA;EACA;EACA,MAAM;GACJ,mBAAmB,wBAAwB;GAC3C,oBAAoB,yBAAyB;GAC7C,oBAAoB,yBAAyB;EAC/C;CACF;AACF"}
1
+ {"version":3,"file":"loadDictionaries.cjs","names":["DictionariesLogger","ANSIColors","getAppLogger","colorize","colon","colorizeKey","loadRemoteDictionaries","filterInvalidDictionaries","formatDictionaries","loadContentDeclarations"],"sources":["../../../src/loadDictionaries/loadDictionaries.ts"],"sourcesContent":["import * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeKey,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { filterInvalidDictionaries } from '../filterInvalidDictionaries';\nimport { formatDictionaries } from '../formatDictionary';\nimport { loadContentDeclarations } from './loadContentDeclaration';\nimport { loadRemoteDictionaries } from './loadRemoteDictionaries';\nimport { DictionariesLogger } from './log';\n\nexport type DictionariesStatus = {\n dictionaryKey: string;\n type: 'local' | 'remote';\n status:\n | 'pending' // Key found but not fetched yet\n | 'fetching' // If dictionary fetch is in progress\n | 'fetched' // If dictionary fetch succeeded\n | 'error' // If dictionary fetch failed\n | 'imported' // If dictionary already fetched and still up to date\n | 'found' // If dictionary key is found but promise is not resolved yet (ex: fetching distant content)\n | 'building' // If dictionary is being built\n | 'built'; // If dictionary is built;\n error?: string;\n};\n\nlet loadDictionariesStatus: DictionariesStatus[] = [];\nconst logger = new DictionariesLogger();\n\nconst setLoadDictionariesStatus = (statuses: DictionariesStatus[]) => {\n const updated: DictionariesStatus[] = [...loadDictionariesStatus];\n\n for (const incoming of statuses) {\n const index = updated.findIndex(\n (s) =>\n s.dictionaryKey === incoming.dictionaryKey && s.type === incoming.type\n );\n if (index >= 0) {\n updated[index] = incoming;\n } else {\n updated.push(incoming);\n }\n }\n\n loadDictionariesStatus = updated;\n logger.update(statuses);\n\n return updated;\n};\n\ntype StatusRecord = {\n local?: DictionariesStatus['status'];\n remote?: DictionariesStatus['status'];\n};\n\nconst iconFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'built':\n case 'imported':\n case 'fetched':\n return '✔';\n case 'error':\n return '✖';\n default:\n return '⏲';\n }\n};\n\nconst colorFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'built':\n case 'imported':\n case 'fetched':\n return ANSIColors.GREEN;\n case 'error':\n return ANSIColors.RED;\n default:\n return ANSIColors.BLUE;\n }\n};\n\nconst printSummary = (configuration: IntlayerConfig) => {\n if (configuration.log.mode !== 'verbose') return;\n\n const appLogger = getAppLogger(configuration);\n\n // Aggregate by dictionary key\n const byKey = new Map<string, StatusRecord>();\n for (const status of loadDictionariesStatus) {\n const rec = byKey.get(status.dictionaryKey) ?? {};\n if (status.type === 'local') rec.local = status.status;\n if (status.type === 'remote') rec.remote = status.status;\n byKey.set(status.dictionaryKey, rec);\n }\n\n const keys = Array.from(byKey.keys()).sort((a, b) => a.localeCompare(b));\n\n // Compute the max visible length of the local label to align distant labels\n let maxLocalLabelLen = 0;\n for (const key of keys) {\n const rec = byKey.get(key)!;\n if (rec.local) {\n const visibleLocal = `[local: ${iconFor(rec.local)} ${rec.local}]`;\n if (visibleLocal.length > maxLocalLabelLen) {\n maxLocalLabelLen = visibleLocal.length;\n }\n }\n }\n\n for (const key of keys) {\n const rec = byKey.get(key)!;\n const labels: string[] = [];\n\n if (rec.local) {\n const inner = colorize(\n `${iconFor(rec.local)} ${rec.local}`,\n colorFor(rec.local)\n );\n const coloredLocal =\n `${ANSIColors.GREY}[` +\n colorize('local: ', ANSIColors.GREY) +\n inner +\n `${ANSIColors.GREY}]${ANSIColors.RESET}`;\n\n // Pad to align distant label across rows\n const visibleLocal = `[local: ${iconFor(rec.local)} ${rec.local}]`;\n const pad = Math.max(0, maxLocalLabelLen - visibleLocal.length);\n labels.push(coloredLocal + ' '.repeat(pad));\n } else {\n // If no local label, insert spaces to keep distant aligned\n labels.push(' '.repeat(maxLocalLabelLen));\n }\n\n if (rec.remote) {\n const inner = colorize(\n `${iconFor(rec.remote)} ${rec.remote}`,\n colorFor(rec.remote)\n );\n labels.push(\n `${ANSIColors.GREY}[` +\n colorize('distant: ', ANSIColors.GREY) +\n inner +\n `${ANSIColors.GREY}]${ANSIColors.RESET}`\n );\n }\n\n appLogger(\n ` - ${colon(colorizeKey(key), { colSize: keys })} ${labels.join(' ')}`\n );\n }\n};\n\nexport const loadDictionaries = async (\n contentDeclarationsPaths: string[] | string,\n configuration: IntlayerConfig\n): Promise<{\n localDictionaries: Dictionary[];\n remoteDictionaries: Dictionary[];\n pluginDictionaries: Dictionary[];\n time: {\n localDictionaries: number;\n remoteDictionaries: number;\n pluginDictionaries: number;\n };\n}> => {\n const { plugins } = configuration;\n const loadDictionariesStartTime = Date.now();\n const appLogger = getAppLogger(configuration);\n\n appLogger('Dictionaries:', { isVerbose: true });\n\n const hasRemoteDictionaries = Boolean(\n configuration.editor.clientId && configuration.editor.clientSecret\n );\n\n if (hasRemoteDictionaries) {\n // We expect to fetch remote dictionaries soon; suppress a transient local-only render\n logger.setExpectRemote(true);\n }\n\n // Started first so the CMS round trips (OAuth2 token, update timestamps)\n // overlap plugin and local loading instead of running after them.\n const remoteDictionariesPromise: Promise<Dictionary[]> = hasRemoteDictionaries\n ? loadRemoteDictionaries(configuration, setLoadDictionariesStatus, {\n onStartRemoteCheck: () => logger.startRemoteCheck(),\n onStopRemoteCheck: () => logger.stopRemoteCheck(),\n onError: (error) => logger.setRemoteError(error),\n })\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries))\n : Promise.resolve([]);\n\n // Awaited later; this keeps an early rejection from being reported as unhandled\n remoteDictionariesPromise.catch(() => undefined);\n\n // Load additional dictionaries via plugins (e.g., ICU JSON ingestion)\n const resolvedPlugins = await Promise.all(plugins ?? []);\n\n const pluginsWithLoadDictionaries = resolvedPlugins.filter(\n (plugin) => plugin.loadDictionaries\n );\n\n logger.setPluginNames(pluginsWithLoadDictionaries.map(({ name }) => name));\n\n const loadPluginDictionariesPromise = pluginsWithLoadDictionaries.map(\n async (plugin) => {\n try {\n const res = await plugin.loadDictionaries?.({\n configuration,\n });\n\n return (res as Dictionary[] | undefined) ?? [];\n } catch (error) {\n logger.setPluginError(error as Error, plugin.name);\n\n return [];\n }\n }\n );\n\n const pluginDictionaries: Dictionary[] = await Promise.all(\n loadPluginDictionariesPromise as Promise<Dictionary[]>[]\n )\n .then((dictionaries) => dictionaries.flat())\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n\n logger.setPluginTotal(pluginDictionaries.length);\n logger.setPluginDone(pluginDictionaries.length);\n\n const pluginDictionariesTime = Date.now();\n\n const files = Array.isArray(contentDeclarationsPaths)\n ? contentDeclarationsPaths\n : [contentDeclarationsPaths];\n\n const localDictionaries: Dictionary[] = await loadContentDeclarations(\n files,\n configuration,\n setLoadDictionariesStatus\n )\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n\n const localDictionariesTime = Date.now();\n\n const localDictionariesStatus = localDictionaries.map(\n (dictionary) =>\n ({\n dictionaryKey: dictionary.key,\n type: 'local',\n status: 'built',\n }) as const\n );\n\n setLoadDictionariesStatus(localDictionariesStatus);\n\n const remoteDictionaries: Dictionary[] = await remoteDictionariesPromise;\n\n const remoteDictionariesTime = Date.now();\n\n // Stop spinner and show final progress line(s)\n logger.finish();\n\n printSummary(configuration);\n\n return {\n localDictionaries,\n remoteDictionaries,\n pluginDictionaries,\n time: {\n localDictionaries: localDictionariesTime - pluginDictionariesTime,\n remoteDictionaries: remoteDictionariesTime - localDictionariesTime,\n pluginDictionaries: pluginDictionariesTime - loadDictionariesStartTime,\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;AA8BA,IAAI,yBAA+C,CAAC;AACpD,MAAM,SAAS,IAAIA,gDAAmB;AAEtC,MAAM,6BAA6B,aAAmC;CACpE,MAAM,UAAgC,CAAC,GAAG,sBAAsB;CAEhE,KAAK,MAAM,YAAY,UAAU;EAC/B,MAAM,QAAQ,QAAQ,WACnB,MACC,EAAE,kBAAkB,SAAS,iBAAiB,EAAE,SAAS,SAAS,IACtE;EACA,IAAI,SAAS,GACX,QAAQ,SAAS;OAEjB,QAAQ,KAAK,QAAQ;CAEzB;CAEA,yBAAyB;CACzB,OAAO,OAAO,QAAQ;CAEtB,OAAO;AACT;AAOA,MAAM,WAAW,WAAyC;CACxD,QAAQ,QAAR;EACE,KAAK;EACL,KAAK;EACL,KAAK,WACH,OAAO;EACT,KAAK,SACH,OAAO;EACT,SACE,OAAO;CACX;AACF;AAEA,MAAM,YAAY,WAAyC;CACzD,QAAQ,QAAR;EACE,KAAK;EACL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AE,WAAW,IAAI,CAAC;CAEzE,MAAM,gCAAgC,4BAA4B,IAChE,OAAO,WAAW;EAChB,IAAI;GAKF,OAAQ,MAJU,OAAO,mBAAmB,EAC1C,cACF,CAAC,KAE2C,CAAC;EAC/C,SAAS,OAAO;GACd,OAAO,eAAe,OAAgB,OAAO,IAAI;GAEjD,OAAO,CAAC;EACV;CACF,CACF;CAEA,MAAM,qBAAmC,MAAM,QAAQ,IACrD,6BACF,CAAC,CACE,MAAM,iBAAiB,aAAa,KAAK,CAAC,CAAC,CAC3C,MAAM,iBACLD,4DAA0B,cAAc,aAAa,CACvD,CAAC,CACA,MAAM,iBAAiBC,4CAAmB,YAAY,CAAC;CAE1D,OAAO,eAAe,mBAAmB,MAAM;CAC/C,OAAO,cAAc,mBAAmB,MAAM;CAE9C,MAAM,yBAAyB,KAAK,IAAI;CAMxC,MAAM,oBAAkC,MAAMC,wEAJhC,MAAM,QAAQ,wBAAwB,IAChD,2BACA,CAAC,wBAAwB,GAI3B,eACA,yBACF,CAAC,CACE,MAAM,iBACLF,4DAA0B,cAAc,aAAa,CACvD,CAAC,CACA,MAAM,iBAAiBC,4CAAmB,YAAY,CAAC;CAE1D,MAAM,wBAAwB,KAAK,IAAI;CAEvC,MAAM,0BAA0B,kBAAkB,KAC/C,gBACE;EACC,eAAe,WAAW;EAC1B,MAAM;EACN,QAAQ;CACV,EACJ;CAEA,0BAA0B,uBAAuB;CAEjD,MAAM,qBAAmC,MAAM;CAE/C,MAAM,yBAAyB,KAAK,IAAI;CAGxC,OAAO,OAAO;CAEd,aAAa,aAAa;CAE1B,OAAO;EACL;EACA;EACA;EACA,MAAM;GACJ,mBAAmB,wBAAwB;GAC3C,oBAAoB,yBAAyB;GAC7C,oBAAoB,yBAAyB;EAC/C;CACF;AACF"}
@@ -1,9 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_utils_sortAlphabetically = require('../utils/sortAlphabetically.cjs');
3
- const require_fetchDistantDictionaries = require('../fetchDistantDictionaries.cjs');
4
3
  let _intlayer_config_node = require("@intlayer/config/node");
5
- let _intlayer_api = require("@intlayer/api");
6
- let _intlayer_api_dictionary = require("@intlayer/api/dictionary");
7
4
  let _intlayer_dictionaries_entry_remote = require("@intlayer/dictionaries-entry/remote");
8
5
 
9
6
  //#region src/loadDictionaries/loadRemoteDictionaries.ts
@@ -18,7 +15,8 @@ const loadRemoteDictionaries = async (configuration = (0, _intlayer_config_node.
18
15
  if (!Boolean(editor.clientId && editor.clientSecret)) return [];
19
16
  try {
20
17
  options?.onStartRemoteCheck?.();
21
- const distantDictionaryUpdateTimeStamp = (await (0, _intlayer_api_dictionary.dictionaryEndpoint)((0, _intlayer_api.createIntlayerCMS)(configuration)).getDictionariesUpdateTimestamp()).data;
18
+ const { createRemoteDictionaryClient, fetchDistantDictionaries } = await Promise.resolve().then(() => require("./remoteDictionaryClient.cjs"));
19
+ const distantDictionaryUpdateTimeStamp = (await createRemoteDictionaryClient(configuration).getDictionariesUpdateTimestamp()).data;
22
20
  if (!distantDictionaryUpdateTimeStamp) throw new Error("No distant dictionaries found");
23
21
  const dictionariesIdToFetch = Object.entries(distantDictionaryUpdateTimeStamp).filter(([dictionaryId, data]) => {
24
22
  if (!data.updatedAt) return true;
@@ -46,7 +44,7 @@ const loadRemoteDictionaries = async (configuration = (0, _intlayer_config_node.
46
44
  type: "remote",
47
45
  status: "pending"
48
46
  })));
49
- const distantDictionariesData = await require_fetchDistantDictionaries.fetchDistantDictionaries({ dictionaryKeys: orderedDistantDictionaryKeys }, onStatusUpdate);
47
+ const distantDictionariesData = await fetchDistantDictionaries({ dictionaryKeys: orderedDistantDictionaryKeys }, onStatusUpdate);
50
48
  const distantDictionaries = formatDistantDictionaries(distantDictionariesData);
51
49
  const fetchedDictionaryIds = new Set(distantDictionaries.map((dictionary) => dictionary.id));
52
50
  return [...cachedDictionaries.filter((dictionary) => !fetchedDictionaryIds.has(dictionary.id)), ...distantDictionaries];
@@ -1 +1 @@
1
- {"version":3,"file":"loadRemoteDictionaries.cjs","names":["getConfiguration","getRemoteDictionaries","dictionaryEndpoint","createIntlayerCMS","sortAlphabetically","fetchDistantDictionaries"],"sources":["../../../src/loadDictionaries/loadRemoteDictionaries.ts"],"sourcesContent":["import { createIntlayerCMS } from '@intlayer/api';\nimport { dictionaryEndpoint } from '@intlayer/api/dictionary';\n// @ts-ignore @intlayer/backend is not build yet\nimport type { DictionaryAPI } from '@intlayer/backend';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { getRemoteDictionaries } from '@intlayer/dictionaries-entry/remote';\nimport type {\n Dictionary,\n DictionaryId,\n DictionaryKey,\n} from '@intlayer/types/dictionary';\nimport { fetchDistantDictionaries } from '../fetchDistantDictionaries';\nimport { sortAlphabetically } from '../utils/sortAlphabetically';\nimport type { DictionariesStatus } from './loadDictionaries';\n\nexport const formatDistantDictionaries = (\n dictionaries: (DictionaryAPI | Dictionary)[]\n): Dictionary[] =>\n dictionaries.map((dict) => ({\n ...dict,\n localId: `${dict.key}::remote::${dict.id}`,\n location: 'remote' as const,\n }));\n\nexport const loadRemoteDictionaries = async (\n configuration = getConfiguration(),\n onStatusUpdate?: (status: DictionariesStatus[]) => void,\n options?: {\n onStartRemoteCheck?: () => void;\n onStopRemoteCheck?: () => void;\n onError?: (error: Error) => void;\n }\n): Promise<Dictionary[]> => {\n const { editor } = configuration;\n const remoteDictionariesRecord = getRemoteDictionaries(configuration);\n\n const hasRemoteDictionaries = Boolean(editor.clientId && editor.clientSecret);\n\n if (!hasRemoteDictionaries) return [];\n\n try {\n options?.onStartRemoteCheck?.();\n\n const dictionary = dictionaryEndpoint(createIntlayerCMS(configuration));\n\n // Get the list of dictionary keys\n const getDictionariesKeysResult =\n await dictionary.getDictionariesUpdateTimestamp();\n\n const distantDictionaryUpdateTimeStamp: Record<\n DictionaryId,\n { key: DictionaryKey; updatedAt: number }\n > | null = getDictionariesKeysResult.data;\n\n if (!distantDictionaryUpdateTimeStamp) {\n throw new Error('No distant dictionaries found');\n }\n\n const dictionariesIdToFetch = Object.entries(\n distantDictionaryUpdateTimeStamp\n ).filter(([dictionaryId, data]) => {\n // If remote doesn't provide updatedAt, fetch to be safe\n if (!data.updatedAt) return true;\n\n // If no local cache exists, fetch\n const local: Dictionary | undefined = remoteDictionariesRecord[\n data.key\n ]?.find((dictionary) => dictionary.id === dictionaryId);\n if (!local) return true;\n\n const localUpdatedAtRaw = (local as any)?.updatedAt as\n | number\n | string\n | undefined;\n\n const localUpdatedAt =\n typeof localUpdatedAtRaw === 'number'\n ? localUpdatedAtRaw\n : localUpdatedAtRaw\n ? new Date(localUpdatedAtRaw).getTime()\n : undefined;\n\n // If local timestamp missing or older than remote, fetch\n if (typeof localUpdatedAt !== 'number') return true;\n\n return data.updatedAt > localUpdatedAt;\n });\n\n const flatRemoteDictionariesRecord: DictionaryAPI[] = Object.values(\n remoteDictionariesRecord\n ).flat();\n\n const cachedDictionaries: Dictionary[] =\n flatRemoteDictionariesRecord.filter((dictionary) => {\n const remoteUpdatedAt = dictionary.id\n ? distantDictionaryUpdateTimeStamp[dictionary.id]?.updatedAt\n : undefined;\n\n const localUpdatedAtRaw = dictionary.updatedAt;\n\n const localUpdatedAt =\n typeof localUpdatedAtRaw === 'number'\n ? localUpdatedAtRaw\n : localUpdatedAtRaw\n ? new Date(localUpdatedAtRaw).getTime()\n : undefined;\n\n // Consider as cached/imported when local exists and is up-to-date or newer\n return (\n typeof localUpdatedAt === 'number' &&\n typeof remoteUpdatedAt === 'number' &&\n localUpdatedAt >= remoteUpdatedAt\n );\n });\n\n // Report cached as already imported\n if (cachedDictionaries.length > 0) {\n onStatusUpdate?.(\n cachedDictionaries.map((dictionary) => ({\n dictionaryKey: dictionary.key,\n type: 'remote',\n status: 'imported',\n }))\n );\n }\n\n // Several qualified dictionaries can share a key, so keys are deduplicated:\n // one request per key already returns all of its siblings.\n const orderedDistantDictionaryKeys = [\n ...new Set(dictionariesIdToFetch.map(([, data]) => data.key)),\n ].sort(sortAlphabetically);\n\n // Report pending for keys to be fetched so totals are visible immediately\n if (orderedDistantDictionaryKeys.length > 0) {\n onStatusUpdate?.(\n orderedDistantDictionaryKeys.map((key) => ({\n dictionaryKey: key,\n type: 'remote',\n status: 'pending',\n }))\n );\n }\n\n const distantDictionariesData = await fetchDistantDictionaries(\n {\n dictionaryKeys: orderedDistantDictionaryKeys,\n },\n onStatusUpdate\n );\n\n const distantDictionaries: Dictionary[] = formatDistantDictionaries(\n distantDictionariesData\n );\n\n // Fetching by key also returns the up-to-date siblings of a stale\n // dictionary, so drop the cached copies the remote just sent back.\n const fetchedDictionaryIds = new Set(\n distantDictionaries.map((dictionary) => dictionary.id)\n );\n\n const notRefetchedCachedDictionaries = cachedDictionaries.filter(\n (dictionary) => !fetchedDictionaryIds.has(dictionary.id)\n );\n\n return [...notRefetchedCachedDictionaries, ...distantDictionaries];\n } catch (error) {\n options?.onError?.(error as Error);\n return [];\n } finally {\n options?.onStopRemoteCheck?.();\n }\n};\n"],"mappings":";;;;;;;;;AAeA,MAAa,6BACX,iBAEA,aAAa,KAAK,UAAU;CAC1B,GAAG;CACH,SAAS,GAAG,KAAK,IAAI,YAAY,KAAK;CACtC,UAAU;AACZ,EAAE;AAEJ,MAAa,yBAAyB,OACpC,oBAAgBA,wCAAiB,GACjC,gBACA,YAK0B;CAC1B,MAAM,EAAE,WAAW;CACnB,MAAM,+BAA2BC,2DAAsB,aAAa;CAIpE,IAAI,CAF0B,QAAQ,OAAO,YAAY,OAAO,YAEvC,GAAG,OAAO,CAAC;CAEpC,IAAI;EACF,SAAS,qBAAqB;EAQ9B,MAAM,oCAGK,UATQC,iDAAmBC,iCAAkB,aAAa,CAIpD,CAAC,CAAC,+BAA+B,EAKd,CAAC;EAErC,IAAI,CAAC,kCACH,MAAM,IAAI,MAAM,+BAA+B;EAGjD,MAAM,wBAAwB,OAAO,QACnC,gCACF,CAAC,CAAC,QAAQ,CAAC,cAAc,UAAU;GAEjC,IAAI,CAAC,KAAK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AmB,QACvD,eAAe,CAAC,qBAAqB,IAAI,WAAW,EAAE,CAGjB,GAAG,GAAG,mBAAmB;CACnE,SAAS,OAAO;EACd,SAAS,UAAU,KAAc;EACjC,OAAO,CAAC;CACV,UAAU;EACR,SAAS,oBAAoB;CAC/B;AACF"}
1
+ {"version":3,"file":"loadRemoteDictionaries.cjs","names":["getConfiguration","getRemoteDictionaries","sortAlphabetically"],"sources":["../../../src/loadDictionaries/loadRemoteDictionaries.ts"],"sourcesContent":["// @ts-ignore @intlayer/backend is not build yet\nimport type { DictionaryAPI } from '@intlayer/backend';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { getRemoteDictionaries } from '@intlayer/dictionaries-entry/remote';\nimport type {\n Dictionary,\n DictionaryId,\n DictionaryKey,\n} from '@intlayer/types/dictionary';\nimport { sortAlphabetically } from '../utils/sortAlphabetically';\nimport type { DictionariesStatus } from './loadDictionaries';\n\nexport const formatDistantDictionaries = (\n dictionaries: (DictionaryAPI | Dictionary)[]\n): Dictionary[] =>\n dictionaries.map((dict) => ({\n ...dict,\n localId: `${dict.key}::remote::${dict.id}`,\n location: 'remote' as const,\n }));\n\nexport const loadRemoteDictionaries = async (\n configuration = getConfiguration(),\n onStatusUpdate?: (status: DictionariesStatus[]) => void,\n options?: {\n onStartRemoteCheck?: () => void;\n onStopRemoteCheck?: () => void;\n onError?: (error: Error) => void;\n }\n): Promise<Dictionary[]> => {\n const { editor } = configuration;\n const remoteDictionariesRecord = getRemoteDictionaries(configuration);\n\n const hasRemoteDictionaries = Boolean(editor.clientId && editor.clientSecret);\n\n if (!hasRemoteDictionaries) return [];\n\n try {\n options?.onStartRemoteCheck?.();\n\n // Lazy: the CMS client is only needed when remote credentials are set\n const { createRemoteDictionaryClient, fetchDistantDictionaries } =\n await import('./remoteDictionaryClient');\n\n const dictionary = createRemoteDictionaryClient(configuration);\n\n // Get the list of dictionary keys\n const getDictionariesKeysResult =\n await dictionary.getDictionariesUpdateTimestamp();\n\n const distantDictionaryUpdateTimeStamp: Record<\n DictionaryId,\n { key: DictionaryKey; updatedAt: number }\n > | null = getDictionariesKeysResult.data;\n\n if (!distantDictionaryUpdateTimeStamp) {\n throw new Error('No distant dictionaries found');\n }\n\n const dictionariesIdToFetch = Object.entries(\n distantDictionaryUpdateTimeStamp\n ).filter(([dictionaryId, data]) => {\n // If remote doesn't provide updatedAt, fetch to be safe\n if (!data.updatedAt) return true;\n\n // If no local cache exists, fetch\n const local: Dictionary | undefined = remoteDictionariesRecord[\n data.key\n ]?.find((dictionary) => dictionary.id === dictionaryId);\n if (!local) return true;\n\n const localUpdatedAtRaw = (local as any)?.updatedAt as\n | number\n | string\n | undefined;\n\n const localUpdatedAt =\n typeof localUpdatedAtRaw === 'number'\n ? localUpdatedAtRaw\n : localUpdatedAtRaw\n ? new Date(localUpdatedAtRaw).getTime()\n : undefined;\n\n // If local timestamp missing or older than remote, fetch\n if (typeof localUpdatedAt !== 'number') return true;\n\n return data.updatedAt > localUpdatedAt;\n });\n\n const flatRemoteDictionariesRecord: DictionaryAPI[] = Object.values(\n remoteDictionariesRecord\n ).flat();\n\n const cachedDictionaries: Dictionary[] =\n flatRemoteDictionariesRecord.filter((dictionary) => {\n const remoteUpdatedAt = dictionary.id\n ? distantDictionaryUpdateTimeStamp[dictionary.id]?.updatedAt\n : undefined;\n\n const localUpdatedAtRaw = dictionary.updatedAt;\n\n const localUpdatedAt =\n typeof localUpdatedAtRaw === 'number'\n ? localUpdatedAtRaw\n : localUpdatedAtRaw\n ? new Date(localUpdatedAtRaw).getTime()\n : undefined;\n\n // Consider as cached/imported when local exists and is up-to-date or newer\n return (\n typeof localUpdatedAt === 'number' &&\n typeof remoteUpdatedAt === 'number' &&\n localUpdatedAt >= remoteUpdatedAt\n );\n });\n\n // Report cached as already imported\n if (cachedDictionaries.length > 0) {\n onStatusUpdate?.(\n cachedDictionaries.map((dictionary) => ({\n dictionaryKey: dictionary.key,\n type: 'remote',\n status: 'imported',\n }))\n );\n }\n\n // Several qualified dictionaries can share a key, so keys are deduplicated:\n // one request per key already returns all of its siblings.\n const orderedDistantDictionaryKeys = [\n ...new Set(dictionariesIdToFetch.map(([, data]) => data.key)),\n ].sort(sortAlphabetically);\n\n // Report pending for keys to be fetched so totals are visible immediately\n if (orderedDistantDictionaryKeys.length > 0) {\n onStatusUpdate?.(\n orderedDistantDictionaryKeys.map((key) => ({\n dictionaryKey: key,\n type: 'remote',\n status: 'pending',\n }))\n );\n }\n\n const distantDictionariesData = await fetchDistantDictionaries(\n {\n dictionaryKeys: orderedDistantDictionaryKeys,\n },\n onStatusUpdate\n );\n\n const distantDictionaries: Dictionary[] = formatDistantDictionaries(\n distantDictionariesData\n );\n\n // Fetching by key also returns the up-to-date siblings of a stale\n // dictionary, so drop the cached copies the remote just sent back.\n const fetchedDictionaryIds = new Set(\n distantDictionaries.map((dictionary) => dictionary.id)\n );\n\n const notRefetchedCachedDictionaries = cachedDictionaries.filter(\n (dictionary) => !fetchedDictionaryIds.has(dictionary.id)\n );\n\n return [...notRefetchedCachedDictionaries, ...distantDictionaries];\n } catch (error) {\n options?.onError?.(error as Error);\n return [];\n } finally {\n options?.onStopRemoteCheck?.();\n }\n};\n"],"mappings":";;;;;;AAYA,MAAa,6BACX,iBAEA,aAAa,KAAK,UAAU;CAC1B,GAAG;CACH,SAAS,GAAG,KAAK,IAAI,YAAY,KAAK;CACtC,UAAU;AACZ,EAAE;AAEJ,MAAa,yBAAyB,OACpC,oBAAgBA,wCAAiB,GACjC,gBACA,YAK0B;CAC1B,MAAM,EAAE,WAAW;CACnB,MAAM,+BAA2BC,2DAAsB,aAAa;CAIpE,IAAI,CAF0B,QAAQ,OAAO,YAAY,OAAO,YAEvC,GAAG,OAAO,CAAC;CAEpC,IAAI;EACF,SAAS,qBAAqB;EAG9B,MAAM,EAAE,8BAA8B,6BACpC,2CAAM;EAQR,MAAM,oCAGK,MATQ,6BAA6B,aAI/B,CAAC,CAAC,+BAA+B,EAKd,CAAC;EAErC,IAAI,CAAC,kCAC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AAM,sBAAoC,0BACxC,uBACF;EAIA,MAAM,uBAAuB,IAAI,IAC/B,oBAAoB,KAAK,eAAe,WAAW,EAAE,CACvD;EAMA,OAAO,CAAC,GAJ+B,mBAAmB,QACvD,eAAe,CAAC,qBAAqB,IAAI,WAAW,EAAE,CAGjB,GAAG,GAAG,mBAAmB;CACnE,SAAS,OAAO;EACd,SAAS,UAAU,KAAc;EACjC,OAAO,CAAC;CACV,UAAU;EACR,SAAS,oBAAoB;CAC/B;AACF"}
@@ -0,0 +1,18 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_fetchDistantDictionaries = require('../fetchDistantDictionaries.cjs');
3
+ let _intlayer_api = require("@intlayer/api");
4
+ let _intlayer_api_dictionary = require("@intlayer/api/dictionary");
5
+
6
+ //#region src/loadDictionaries/remoteDictionaryClient.ts
7
+ /**
8
+ * Creates the CMS dictionary client.
9
+ *
10
+ * Kept in its own module so `loadRemoteDictionaries` can import it lazily:
11
+ * `@intlayer/api` is only loaded when remote credentials are configured.
12
+ */
13
+ const createRemoteDictionaryClient = (configuration) => (0, _intlayer_api_dictionary.dictionaryEndpoint)((0, _intlayer_api.createIntlayerCMS)(configuration));
14
+
15
+ //#endregion
16
+ exports.createRemoteDictionaryClient = createRemoteDictionaryClient;
17
+ exports.fetchDistantDictionaries = require_fetchDistantDictionaries.fetchDistantDictionaries;
18
+ //# sourceMappingURL=remoteDictionaryClient.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remoteDictionaryClient.cjs","names":["dictionaryEndpoint","createIntlayerCMS"],"sources":["../../../src/loadDictionaries/remoteDictionaryClient.ts"],"sourcesContent":["import { createIntlayerCMS } from '@intlayer/api';\nimport { dictionaryEndpoint } from '@intlayer/api/dictionary';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\nexport { fetchDistantDictionaries } from '../fetchDistantDictionaries';\n\n/**\n * Creates the CMS dictionary client.\n *\n * Kept in its own module so `loadRemoteDictionaries` can import it lazily:\n * `@intlayer/api` is only loaded when remote credentials are configured.\n */\nexport const createRemoteDictionaryClient = (\n configuration: IntlayerConfig\n): ReturnType<typeof dictionaryEndpoint> =>\n dictionaryEndpoint(createIntlayerCMS(configuration));\n"],"mappings":";;;;;;;;;;;;AAYA,MAAa,gCACX,sBAEAA,iDAAmBC,iCAAkB,aAAa,CAAC"}