@intlayer/chokidar 3.2.1 → 3.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/cjs/chokidar/watcher.cjs +14 -9
  2. package/dist/cjs/chokidar/watcher.cjs.map +1 -1
  3. package/dist/cjs/cleanOutputDir.cjs +38 -0
  4. package/dist/cjs/cleanOutputDir.cjs.map +1 -0
  5. package/dist/cjs/fetchDistantDictionaries.cjs +5 -5
  6. package/dist/cjs/fetchDistantDictionaries.cjs.map +1 -1
  7. package/dist/cjs/fetchDistantDictionaryKeys.cjs +5 -5
  8. package/dist/cjs/fetchDistantDictionaryKeys.cjs.map +1 -1
  9. package/dist/cjs/loadDictionaries/loadDictionaries.cjs +5 -6
  10. package/dist/cjs/loadDictionaries/loadDictionaries.cjs.map +1 -1
  11. package/dist/cjs/log.cjs +20 -30
  12. package/dist/cjs/log.cjs.map +1 -1
  13. package/dist/cjs/transpiler/dictionary_to_main/createDictionaryList.cjs +12 -2
  14. package/dist/cjs/transpiler/dictionary_to_main/createDictionaryList.cjs.map +1 -1
  15. package/dist/cjs/transpiler/dictionary_to_type/createModuleAugmentation.cjs +12 -2
  16. package/dist/cjs/transpiler/dictionary_to_type/createModuleAugmentation.cjs.map +1 -1
  17. package/dist/cjs/utils.cjs +3 -0
  18. package/dist/cjs/utils.cjs.map +1 -1
  19. package/dist/esm/chokidar/watcher.mjs +4 -9
  20. package/dist/esm/chokidar/watcher.mjs.map +1 -1
  21. package/dist/esm/cleanOutputDir.mjs +14 -0
  22. package/dist/esm/cleanOutputDir.mjs.map +1 -0
  23. package/dist/esm/fetchDistantDictionaries.mjs +4 -4
  24. package/dist/esm/fetchDistantDictionaries.mjs.map +1 -1
  25. package/dist/esm/fetchDistantDictionaryKeys.mjs +4 -4
  26. package/dist/esm/fetchDistantDictionaryKeys.mjs.map +1 -1
  27. package/dist/esm/loadDictionaries/loadDictionaries.mjs +5 -6
  28. package/dist/esm/loadDictionaries/loadDictionaries.mjs.map +1 -1
  29. package/dist/esm/log.mjs +20 -30
  30. package/dist/esm/log.mjs.map +1 -1
  31. package/dist/esm/transpiler/dictionary_to_main/createDictionaryList.mjs +2 -2
  32. package/dist/esm/transpiler/dictionary_to_main/createDictionaryList.mjs.map +1 -1
  33. package/dist/esm/transpiler/dictionary_to_type/createModuleAugmentation.mjs +2 -2
  34. package/dist/esm/transpiler/dictionary_to_type/createModuleAugmentation.mjs.map +1 -1
  35. package/dist/esm/utils.mjs +2 -0
  36. package/dist/esm/utils.mjs.map +1 -1
  37. package/dist/types/chokidar/watcher.d.ts.map +1 -1
  38. package/dist/types/cleanOutputDir.d.ts +2 -0
  39. package/dist/types/cleanOutputDir.d.ts.map +1 -0
  40. package/dist/types/fetchDistantDictionaryKeys.d.ts.map +1 -1
  41. package/dist/types/loadDictionaries/loadDictionaries.d.ts.map +1 -1
  42. package/dist/types/log.d.ts.map +1 -1
  43. package/dist/types/utils.d.ts +1 -0
  44. package/dist/types/utils.d.ts.map +1 -1
  45. package/package.json +13 -12
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
  var watcher_exports = {};
20
30
  __export(watcher_exports, {
@@ -24,7 +34,8 @@ module.exports = __toCommonJS(watcher_exports);
24
34
  var import_path = require("path");
25
35
  var import_config = require("@intlayer/config");
26
36
  var import_chokidar = require("chokidar");
27
- var import_glob = require("glob");
37
+ var import_fast_glob = __toESM(require("fast-glob"));
38
+ var import_cleanOutputDir = require('../cleanOutputDir.cjs');
28
39
  var import_loadDictionaries = require('../loadDictionaries/loadDictionaries.cjs');
29
40
  var import_loadLocalDictionaries = require('../loadDictionaries/loadLocalDictionaries.cjs');
30
41
  var import_declaration_file_to_dictionary = require('../transpiler/declaration_file_to_dictionary/index.cjs');
@@ -36,7 +47,8 @@ const watch = (options) => {
36
47
  verbose: true
37
48
  });
38
49
  const { watchedFilesPatternWithPath, baseDir } = content;
39
- const files = (0, import_glob.sync)(watchedFilesPatternWithPath);
50
+ (0, import_cleanOutputDir.cleanOutputDir)();
51
+ const files = import_fast_glob.default.sync(watchedFilesPatternWithPath);
40
52
  return (0, import_chokidar.watch)(watchedFilesPatternWithPath, {
41
53
  persistent: true,
42
54
  // Make the watcher persistent
@@ -47,13 +59,8 @@ const watch = (options) => {
47
59
  const dictionaries = await (0, import_loadDictionaries.loadDictionaries)(files);
48
60
  const dictionariesPaths = await (0, import_declaration_file_to_dictionary.buildDictionary)(dictionaries);
49
61
  await (0, import_dictionary_to_type.createTypes)(dictionariesPaths);
50
- console.info(`${LOG_PREFIX}TypeScript types built`);
51
62
  (0, import_dictionary_to_type.createModuleAugmentation)();
52
- console.info(`${LOG_PREFIX}Intlayer module augmentation built`);
53
63
  (0, import_createDictionaryList.createDictionaryList)();
54
- console.info(`${LOG_PREFIX}Intlayer dictionary list built`);
55
- }).on("unlink", (filePath) => {
56
- console.info("Removed file detected: ", (0, import_path.relative)(baseDir, filePath));
57
64
  }).on("add", async (filePath) => {
58
65
  console.info(
59
66
  `${LOG_PREFIX}Additional file detected: `,
@@ -62,9 +69,7 @@ const watch = (options) => {
62
69
  const localeDictionaries = await (0, import_loadLocalDictionaries.loadLocalDictionaries)(filePath);
63
70
  const dictionaries = await (0, import_declaration_file_to_dictionary.buildDictionary)(localeDictionaries);
64
71
  await (0, import_dictionary_to_type.createTypes)(dictionaries);
65
- console.info(`${LOG_PREFIX}TypeScript types built`);
66
72
  (0, import_dictionary_to_type.createModuleAugmentation)();
67
- console.info(`${LOG_PREFIX}Intlayer module augmentation built`);
68
73
  (0, import_createDictionaryList.createDictionaryList)();
69
74
  }).on("change", async (filePath) => {
70
75
  console.info("Change detected: ", (0, import_path.relative)(baseDir, filePath));
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/chokidar/watcher.ts"],"sourcesContent":["import { relative } from 'path';\nimport { getConfiguration } from '@intlayer/config';\n/** @ts-ignore remove error Module '\"chokidar\"' has no exported member 'ChokidarOptions' */\nimport { type ChokidarOptions, watch as chokidarWatch } from 'chokidar';\nimport { sync } from 'glob';\nimport { loadDictionaries } from '../loadDictionaries/loadDictionaries';\nimport { loadLocalDictionaries } from '../loadDictionaries/loadLocalDictionaries';\nimport { buildDictionary } from '../transpiler/declaration_file_to_dictionary/index';\nimport { createDictionaryList } from '../transpiler/dictionary_to_main/createDictionaryList';\nimport {\n createTypes,\n createModuleAugmentation,\n} from '../transpiler/dictionary_to_type/index';\n\nconst LOG_PREFIX = '[intlayer] ';\n\n// Initialize chokidar watcher (non-persistent)\nexport const watch = (options?: ChokidarOptions) => {\n const { content } = getConfiguration({\n verbose: true,\n });\n\n const { watchedFilesPatternWithPath, baseDir } = content;\n\n const files: string[] = sync(watchedFilesPatternWithPath);\n\n /** @ts-ignore remove error Expected 0-1 arguments, but got 2. */\n return chokidarWatch(watchedFilesPatternWithPath, {\n persistent: true, // Make the watcher persistent\n ignoreInitial: true, // Process existing files\n ...options,\n })\n .on('ready', async () => {\n const dictionaries = await loadDictionaries(files);\n\n // Build locale dictionaries\n const dictionariesPaths = await buildDictionary(dictionaries);\n\n await createTypes(dictionariesPaths);\n console.info(`${LOG_PREFIX}TypeScript types built`);\n\n createModuleAugmentation();\n console.info(`${LOG_PREFIX}Intlayer module augmentation built`);\n\n createDictionaryList();\n console.info(`${LOG_PREFIX}Intlayer dictionary list built`);\n })\n .on('unlink', (filePath) => {\n // Process the file with the functionToRun\n console.info('Removed file detected: ', relative(baseDir, filePath));\n })\n .on('add', async (filePath) => {\n // Process the file with the functionToRun\n console.info(\n `${LOG_PREFIX}Additional file detected: `,\n relative(baseDir, filePath)\n );\n\n const localeDictionaries = await loadLocalDictionaries(filePath);\n const dictionaries = await buildDictionary(localeDictionaries);\n\n await createTypes(dictionaries);\n console.info(`${LOG_PREFIX}TypeScript types built`);\n\n createModuleAugmentation();\n console.info(`${LOG_PREFIX}Intlayer module augmentation built`);\n\n createDictionaryList();\n })\n .on('change', async (filePath) => {\n // Process the file with the functionToRun\n console.info('Change detected: ', relative(baseDir, filePath));\n\n const localeDictionaries = await loadLocalDictionaries(filePath);\n const dictionaries = await buildDictionary(localeDictionaries);\n\n await createTypes(dictionaries);\n console.info(`${LOG_PREFIX}TypeScript types built`);\n })\n .on('error', (error) => {\n console.error('Watcher error:', error);\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAyB;AACzB,oBAAiC;AAEjC,sBAA6D;AAC7D,kBAAqB;AACrB,8BAAiC;AACjC,mCAAsC;AACtC,4CAAgC;AAChC,kCAAqC;AACrC,gCAGO;AAEP,MAAM,aAAa;AAGZ,MAAM,QAAQ,CAAC,YAA8B;AAClD,QAAM,EAAE,QAAQ,QAAI,gCAAiB;AAAA,IACnC,SAAS;AAAA,EACX,CAAC;AAED,QAAM,EAAE,6BAA6B,QAAQ,IAAI;AAEjD,QAAM,YAAkB,kBAAK,2BAA2B;AAGxD,aAAO,gBAAAA,OAA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ar/watcher.ts"],"sourcesContent":["import { relative } from 'path';\nimport { getConfiguration } from '@intlayer/config';\n/** @ts-ignore remove error Module '\"chokidar\"' has no exported member 'ChokidarOptions' */\nimport { type ChokidarOptions, watch as chokidarWatch } from 'chokidar';\nimport fg from 'fast-glob';\nimport { cleanOutputDir } from '../cleanOutputDir';\nimport { loadDictionaries } from '../loadDictionaries/loadDictionaries';\nimport { loadLocalDictionaries } from '../loadDictionaries/loadLocalDictionaries';\nimport { buildDictionary } from '../transpiler/declaration_file_to_dictionary/index';\nimport { createDictionaryList } from '../transpiler/dictionary_to_main/createDictionaryList';\nimport {\n createTypes,\n createModuleAugmentation,\n} from '../transpiler/dictionary_to_type/index';\n\nconst LOG_PREFIX = '[intlayer] ';\n\n// Initialize chokidar watcher (non-persistent)\nexport const watch = (options?: ChokidarOptions) => {\n const { content } = getConfiguration({\n verbose: true,\n });\n\n const { watchedFilesPatternWithPath, baseDir } = content;\n\n cleanOutputDir();\n\n const files: string[] = fg.sync(watchedFilesPatternWithPath);\n\n /** @ts-ignore remove error Expected 0-1 arguments, but got 2. */\n return chokidarWatch(watchedFilesPatternWithPath, {\n persistent: true, // Make the watcher persistent\n ignoreInitial: true, // Process existing files\n ...options,\n })\n .on('ready', async () => {\n const dictionaries = await loadDictionaries(files);\n\n // Build locale dictionaries\n const dictionariesPaths = await buildDictionary(dictionaries);\n\n await createTypes(dictionariesPaths);\n\n createModuleAugmentation();\n\n createDictionaryList();\n })\n .on('add', async (filePath) => {\n // Process the file with the functionToRun\n console.info(\n `${LOG_PREFIX}Additional file detected: `,\n relative(baseDir, filePath)\n );\n\n const localeDictionaries = await loadLocalDictionaries(filePath);\n\n const dictionaries = await buildDictionary(localeDictionaries);\n\n await createTypes(dictionaries);\n\n createModuleAugmentation();\n\n createDictionaryList();\n })\n .on('change', async (filePath) => {\n // Process the file with the functionToRun\n console.info('Change detected: ', relative(baseDir, filePath));\n\n const localeDictionaries = await loadLocalDictionaries(filePath);\n const dictionaries = await buildDictionary(localeDictionaries);\n\n await createTypes(dictionaries);\n console.info(`${LOG_PREFIX}TypeScript types built`);\n })\n .on('error', (error) => {\n console.error('Watcher error:', error);\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAyB;AACzB,oBAAiC;AAEjC,sBAA6D;AAC7D,uBAAe;AACf,4BAA+B;AAC/B,8BAAiC;AACjC,mCAAsC;AACtC,4CAAgC;AAChC,kCAAqC;AACrC,gCAGO;AAEP,MAAM,aAAa;AAGZ,MAAM,QAAQ,CAAC,YAA8B;AAClD,QAAM,EAAE,QAAQ,QAAI,gCAAiB;AAAA,IACnC,SAAS;AAAA,EACX,CAAC;AAED,QAAM,EAAE,6BAA6B,QAAQ,IAAI;AAEjD,4CAAe;AAEf,QAAM,QAAkB,iBAAAA,QAAG,KAAK,2BAA2B;AAG3D,aAAO,gBAAAC,OAAc,6BAA6B;AAAA,IAChD,YAAY;AAAA;AAAA,IACZ,eAAe;AAAA;AAAA,IACf,GAAG;AAAA,EACL,CAAC,EACE,GAAG,SAAS,YAAY;AACvB,UAAM,eAAe,UAAM,0CAAiB,KAAK;AAGjD,UAAM,oBAAoB,UAAM,uDAAgB,YAAY;AAE5D,cAAM,uCAAY,iBAAiB;AAEnC,4DAAyB;AAEzB,0DAAqB;AAAA,EACvB,CAAC,EACA,GAAG,OAAO,OAAO,aAAa;AAE7B,YAAQ;AAAA,MACN,GAAG,UAAU;AAAA,UACb,sBAAS,SAAS,QAAQ;AAAA,IAC5B;AAEA,UAAM,qBAAqB,UAAM,oDAAsB,QAAQ;AAE/D,UAAM,eAAe,UAAM,uDAAgB,kBAAkB;AAE7D,cAAM,uCAAY,YAAY;AAE9B,4DAAyB;AAEzB,0DAAqB;AAAA,EACvB,CAAC,EACA,GAAG,UAAU,OAAO,aAAa;AAEhC,YAAQ,KAAK,yBAAqB,sBAAS,SAAS,QAAQ,CAAC;AAE7D,UAAM,qBAAqB,UAAM,oDAAsB,QAAQ;AAC/D,UAAM,eAAe,UAAM,uDAAgB,kBAAkB;AAE7D,cAAM,uCAAY,YAAY;AAC9B,YAAQ,KAAK,GAAG,UAAU,wBAAwB;AAAA,EACpD,CAAC,EACA,GAAG,SAAS,CAAC,UAAU;AACtB,YAAQ,MAAM,kBAAkB,KAAK;AAAA,EACvC,CAAC;AACL;","names":["fg","chokidarWatch"]}
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var cleanOutputDir_exports = {};
20
+ __export(cleanOutputDir_exports, {
21
+ cleanOutputDir: () => cleanOutputDir
22
+ });
23
+ module.exports = __toCommonJS(cleanOutputDir_exports);
24
+ var import_fs = require("fs");
25
+ var import_config = require("@intlayer/config");
26
+ const cleanOutputDir = () => {
27
+ const { content } = (0, import_config.getConfiguration)();
28
+ const { resultDir } = content;
29
+ if ((0, import_fs.existsSync)(resultDir)) {
30
+ (0, import_fs.rmSync)(resultDir, { recursive: true });
31
+ }
32
+ (0, import_fs.mkdirSync)(resultDir);
33
+ };
34
+ // Annotate the CommonJS export names for ESM import in node:
35
+ 0 && (module.exports = {
36
+ cleanOutputDir
37
+ });
38
+ //# sourceMappingURL=cleanOutputDir.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/cleanOutputDir.ts"],"sourcesContent":["import { existsSync, rmSync, mkdirSync } from 'fs';\nimport { getConfiguration } from '@intlayer/config';\n\nexport const cleanOutputDir = () => {\n const { content } = getConfiguration();\n\n const { resultDir } = content;\n\n // Delete the dictionary directory dictionariesDir\n if (existsSync(resultDir)) {\n rmSync(resultDir, { recursive: true });\n }\n\n // Create the dictionary directory dictionariesDir\n mkdirSync(resultDir);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAA8C;AAC9C,oBAAiC;AAE1B,MAAM,iBAAiB,MAAM;AAClC,QAAM,EAAE,QAAQ,QAAI,gCAAiB;AAErC,QAAM,EAAE,UAAU,IAAI;AAGtB,UAAI,sBAAW,SAAS,GAAG;AACzB,0BAAO,WAAW,EAAE,WAAW,KAAK,CAAC;AAAA,EACvC;AAGA,2BAAU,SAAS;AACrB;","names":[]}
@@ -37,22 +37,22 @@ var import_p_limit = __toESM(require("p-limit"));
37
37
  var import_log = require('./log.cjs');
38
38
  const fetchDistantDictionaries = async (options) => {
39
39
  try {
40
- const {
41
- editor: { clientId, clientSecret }
42
- } = (0, import_config.getConfiguration)();
40
+ const config = (0, import_config.getConfiguration)();
41
+ const { clientId, clientSecret } = config.editor;
42
+ const intlayerAPI = (0, import_libs.getIntlayerAPI)(void 0, config);
43
43
  if (!clientId || !clientSecret) {
44
44
  throw new Error(
45
45
  "Missing OAuth2 client ID or client secret. To get access token go to https://intlayer.org/dashboard/project."
46
46
  );
47
47
  }
48
- const oAuth2TokenResult = await import_libs.intlayerAPI.auth.getOAuth2AccessToken();
48
+ const oAuth2TokenResult = await intlayerAPI.auth.getOAuth2AccessToken();
49
49
  const oAuth2AccessToken = oAuth2TokenResult.data?.accessToken;
50
50
  const distantDictionariesKeys = options.dictionaryKeys;
51
51
  const limit = (0, import_p_limit.default)(5);
52
52
  const processDictionary = async (dictionaryKey) => {
53
53
  import_log.logger.updateStatus(dictionaryKey, "distant", { status: "fetching" });
54
54
  try {
55
- const getDictionaryResult = await import_libs.intlayerAPI.dictionary.getDictionary(
55
+ const getDictionaryResult = await intlayerAPI.dictionary.getDictionary(
56
56
  dictionaryKey,
57
57
  void 0,
58
58
  {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/fetchDistantDictionaries.ts"],"sourcesContent":["// @ts-ignore @intlayer/backend not build yet\nimport { type DictionaryAPI } from '@intlayer/backend';\nimport { getConfiguration } from '@intlayer/config';\n// @ts-ignore @intlayer/design-system not build yet\nimport { intlayerAPI } from '@intlayer/design-system/libs';\nimport pLimit from 'p-limit';\nimport { logger } from './log';\n\ntype FetchDistantDictionariesOptions = {\n dictionaryKeys: string[];\n newDictionariesPath?: string;\n logPrefix?: string;\n};\n\n/**\n * Fetch distant dictionaries and update the logger with their statuses.\n */\nexport const fetchDistantDictionaries = async (\n options: FetchDistantDictionariesOptions\n): Promise<DictionaryAPI[]> => {\n try {\n const {\n editor: { clientId, clientSecret },\n } = getConfiguration();\n\n if (!clientId || !clientSecret) {\n throw new Error(\n 'Missing OAuth2 client ID or client secret. To get access token go to https://intlayer.org/dashboard/project.'\n );\n }\n\n const oAuth2TokenResult = await intlayerAPI.auth.getOAuth2AccessToken();\n\n const oAuth2AccessToken = oAuth2TokenResult.data?.accessToken;\n\n const distantDictionariesKeys = options.dictionaryKeys;\n\n // Process dictionaries in parallel with a concurrency limit\n const limit = pLimit(5); // Adjust the limit as needed\n\n const processDictionary = async (\n dictionaryKey: string\n ): Promise<DictionaryAPI | undefined> => {\n logger.updateStatus(dictionaryKey, 'distant', { status: 'fetching' });\n\n try {\n // Fetch the dictionary\n const getDictionaryResult = await intlayerAPI.dictionary.getDictionary(\n dictionaryKey,\n undefined,\n {\n headers: { Authorization: `Bearer ${oAuth2AccessToken}` },\n }\n );\n\n const distantDictionary = getDictionaryResult.data;\n\n if (!distantDictionary) {\n throw new Error(`Dictionary ${dictionaryKey} not found on remote`);\n }\n\n logger.updateStatus(dictionaryKey, 'distant', { status: 'imported' });\n\n return distantDictionary;\n } catch (error) {\n logger.updateStatus(dictionaryKey, 'distant', {\n status: 'error',\n error: error as Error,\n errorMessage: `${options?.logPrefix ?? ''}Error fetching dictionary ${dictionaryKey}: ${error}`,\n });\n return undefined;\n }\n };\n\n const fetchPromises = distantDictionariesKeys.map((dictionaryKey) =>\n limit(() => processDictionary(dictionaryKey))\n );\n\n const result = await Promise.all(fetchPromises);\n\n // Output any error messages\n const statuses = logger.getStatuses();\n for (const statusObj of statuses) {\n const currentState = statusObj.state.find((s) => s.type === 'distant');\n if (currentState && currentState.errorMessage) {\n console.error(currentState.errorMessage);\n }\n }\n\n // Remove undefined values\n const filteredResult = result.filter(\n (dict): dict is DictionaryAPI => dict !== undefined\n );\n\n return filteredResult;\n } catch (error) {\n console.error(error);\n return [];\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,oBAAiC;AAEjC,kBAA4B;AAC5B,qBAAmB;AACnB,iBAAuB;AAWhB,MAAM,2BAA2B,OACtC,YAC6B;AAC7B,MAAI;AACF,UAAM;AAAA,MACJ,QAAQ,EAAE,UAAU,aAAa;AAAA,IACnC,QAAI,gCAAiB;AAErB,QAAI,CAAC,YAAY,CAAC,cAAc;AAC9B,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,UAAM,oBAAoB,MAAM,wBAAY,KAAK,qBAAqB;AAEtE,UAAM,oBAAoB,kBAAkB,MAAM;AAElD,UAAM,0BAA0B,QAAQ;AAGxC,UAAM,YAAQ,eAAAA,SAAO,CAAC;AAEtB,UAAM,oBAAoB,OACxB,kBACuC;AACvC,wBAAO,aAAa,eAAe,WAAW,EAAE,QAAQ,WAAW,CAAC;AAEpE,UAAI;AAEF,cAAM,sBAAsB,MAAM,wBAAY,WAAW;AAAA,UACvD;AAAA,UACA;AAAA,UACA;AAAA,YACE,SAAS,EAAE,eAAe,UAAU,iBAAiB,GAAG;AAAA,UAC1D;AAAA,QACF;AAEA,cAAM,oBAAoB,oBAAoB;AAE9C,YAAI,CAAC,mBAAmB;AACtB,gBAAM,IAAI,MAAM,cAAc,aAAa,sBAAsB;AAAA,QACnE;AAEA,0BAAO,aAAa,eAAe,WAAW,EAAE,QAAQ,WAAW,CAAC;AAEpE,eAAO;AAAA,MACT,SAAS,OAAO;AACd,0BAAO,aAAa,eAAe,WAAW;AAAA,UAC5C,QAAQ;AAAA,UACR;AAAA,UACA,cAAc,GAAG,SAAS,aAAa,EAAE,6BAA6B,aAAa,KAAK,KAAK;AAAA,QAC/F,CAAC;AACD,eAAO;AAAA,MACT;AAAA,IACF;AAEA,UAAM,gBAAgB,wBAAwB;AAAA,MAAI,CAAC,kBACjD,MAAM,MAAM,kBAAkB,aAAa,CAAC;AAAA,IAC9C;AAEA,UAAM,SAAS,MAAM,QAAQ,IAAI,aAAa;AAG9C,UAAM,WAAW,kBAAO,YAAY;AACpC,eAAW,aAAa,UAAU;AAChC,YAAM,eAAe,UAAU,MAAM,KAAK,CAAC,MAAM,EAAE,SAAS,SAAS;AACrE,UAAI,gBAAgB,aAAa,cAAc;AAC7C,gBAAQ,MAAM,aAAa,YAAY;AAAA,MACzC;AAAA,IACF;AAGA,UAAM,iBAAiB,OAAO;AAAA,MAC5B,CAAC,SAAgC,SAAS;AAAA,IAC5C;AAEA,WAAO;AAAA,EACT,SAAS,OAAO;AACd,YAAQ,MAAM,KAAK;AACnB,WAAO,CAAC;AAAA,EACV;AACF;","names":["pLimit"]}
1
+ {"version":3,"sources":["../../src/fetchDistantDictionaries.ts"],"sourcesContent":["// @ts-ignore @intlayer/backend not build yet\nimport { type DictionaryAPI } from '@intlayer/backend';\nimport { getConfiguration } from '@intlayer/config';\n// @ts-ignore @intlayer/design-system not build yet\nimport { getIntlayerAPI } from '@intlayer/design-system/libs';\nimport pLimit from 'p-limit';\nimport { logger } from './log';\n\ntype FetchDistantDictionariesOptions = {\n dictionaryKeys: string[];\n newDictionariesPath?: string;\n logPrefix?: string;\n};\n\n/**\n * Fetch distant dictionaries and update the logger with their statuses.\n */\nexport const fetchDistantDictionaries = async (\n options: FetchDistantDictionariesOptions\n): Promise<DictionaryAPI[]> => {\n try {\n const config = getConfiguration();\n const { clientId, clientSecret } = config.editor;\n const intlayerAPI = getIntlayerAPI(undefined, config);\n\n if (!clientId || !clientSecret) {\n throw new Error(\n 'Missing OAuth2 client ID or client secret. To get access token go to https://intlayer.org/dashboard/project.'\n );\n }\n\n const oAuth2TokenResult = await intlayerAPI.auth.getOAuth2AccessToken();\n\n const oAuth2AccessToken = oAuth2TokenResult.data?.accessToken;\n\n const distantDictionariesKeys = options.dictionaryKeys;\n\n // Process dictionaries in parallel with a concurrency limit\n const limit = pLimit(5); // Adjust the limit as needed\n\n const processDictionary = async (\n dictionaryKey: string\n ): Promise<DictionaryAPI | undefined> => {\n logger.updateStatus(dictionaryKey, 'distant', { status: 'fetching' });\n\n try {\n // Fetch the dictionary\n const getDictionaryResult = await intlayerAPI.dictionary.getDictionary(\n dictionaryKey,\n undefined,\n {\n headers: { Authorization: `Bearer ${oAuth2AccessToken}` },\n }\n );\n\n const distantDictionary = getDictionaryResult.data;\n\n if (!distantDictionary) {\n throw new Error(`Dictionary ${dictionaryKey} not found on remote`);\n }\n\n logger.updateStatus(dictionaryKey, 'distant', { status: 'imported' });\n\n return distantDictionary;\n } catch (error) {\n logger.updateStatus(dictionaryKey, 'distant', {\n status: 'error',\n error: error as Error,\n errorMessage: `${options?.logPrefix ?? ''}Error fetching dictionary ${dictionaryKey}: ${error}`,\n });\n return undefined;\n }\n };\n\n const fetchPromises = distantDictionariesKeys.map((dictionaryKey) =>\n limit(() => processDictionary(dictionaryKey))\n );\n\n const result = await Promise.all(fetchPromises);\n\n // Output any error messages\n const statuses = logger.getStatuses();\n for (const statusObj of statuses) {\n const currentState = statusObj.state.find((s) => s.type === 'distant');\n if (currentState && currentState.errorMessage) {\n console.error(currentState.errorMessage);\n }\n }\n\n // Remove undefined values\n const filteredResult = result.filter(\n (dict): dict is DictionaryAPI => dict !== undefined\n );\n\n return filteredResult;\n } catch (error) {\n console.error(error);\n return [];\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,oBAAiC;AAEjC,kBAA+B;AAC/B,qBAAmB;AACnB,iBAAuB;AAWhB,MAAM,2BAA2B,OACtC,YAC6B;AAC7B,MAAI;AACF,UAAM,aAAS,gCAAiB;AAChC,UAAM,EAAE,UAAU,aAAa,IAAI,OAAO;AAC1C,UAAM,kBAAc,4BAAe,QAAW,MAAM;AAEpD,QAAI,CAAC,YAAY,CAAC,cAAc;AAC9B,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,UAAM,oBAAoB,MAAM,YAAY,KAAK,qBAAqB;AAEtE,UAAM,oBAAoB,kBAAkB,MAAM;AAElD,UAAM,0BAA0B,QAAQ;AAGxC,UAAM,YAAQ,eAAAA,SAAO,CAAC;AAEtB,UAAM,oBAAoB,OACxB,kBACuC;AACvC,wBAAO,aAAa,eAAe,WAAW,EAAE,QAAQ,WAAW,CAAC;AAEpE,UAAI;AAEF,cAAM,sBAAsB,MAAM,YAAY,WAAW;AAAA,UACvD;AAAA,UACA;AAAA,UACA;AAAA,YACE,SAAS,EAAE,eAAe,UAAU,iBAAiB,GAAG;AAAA,UAC1D;AAAA,QACF;AAEA,cAAM,oBAAoB,oBAAoB;AAE9C,YAAI,CAAC,mBAAmB;AACtB,gBAAM,IAAI,MAAM,cAAc,aAAa,sBAAsB;AAAA,QACnE;AAEA,0BAAO,aAAa,eAAe,WAAW,EAAE,QAAQ,WAAW,CAAC;AAEpE,eAAO;AAAA,MACT,SAAS,OAAO;AACd,0BAAO,aAAa,eAAe,WAAW;AAAA,UAC5C,QAAQ;AAAA,UACR;AAAA,UACA,cAAc,GAAG,SAAS,aAAa,EAAE,6BAA6B,aAAa,KAAK,KAAK;AAAA,QAC/F,CAAC;AACD,eAAO;AAAA,MACT;AAAA,IACF;AAEA,UAAM,gBAAgB,wBAAwB;AAAA,MAAI,CAAC,kBACjD,MAAM,MAAM,kBAAkB,aAAa,CAAC;AAAA,IAC9C;AAEA,UAAM,SAAS,MAAM,QAAQ,IAAI,aAAa;AAG9C,UAAM,WAAW,kBAAO,YAAY;AACpC,eAAW,aAAa,UAAU;AAChC,YAAM,eAAe,UAAU,MAAM,KAAK,CAAC,MAAM,EAAE,SAAS,SAAS;AACrE,UAAI,gBAAgB,aAAa,cAAc;AAC7C,gBAAQ,MAAM,aAAa,YAAY;AAAA,MACzC;AAAA,IACF;AAGA,UAAM,iBAAiB,OAAO;AAAA,MAC5B,CAAC,SAAgC,SAAS;AAAA,IAC5C;AAEA,WAAO;AAAA,EACT,SAAS,OAAO;AACd,YAAQ,MAAM,KAAK;AACnB,WAAO,CAAC;AAAA,EACV;AACF;","names":["pLimit"]}
@@ -24,17 +24,17 @@ module.exports = __toCommonJS(fetchDistantDictionaryKeys_exports);
24
24
  var import_config = require("@intlayer/config");
25
25
  var import_libs = require("@intlayer/design-system/libs");
26
26
  const fetchDistantDictionaryKeys = async () => {
27
- const {
28
- editor: { clientId, clientSecret }
29
- } = (0, import_config.getConfiguration)();
27
+ const config = (0, import_config.getConfiguration)();
28
+ const { clientId, clientSecret } = config.editor;
30
29
  if (!clientId || !clientSecret) {
31
30
  throw new Error(
32
31
  "Missing OAuth2 client ID or client secret. To get access token go to https://intlayer.org/dashboard/project."
33
32
  );
34
33
  }
35
- const oAuth2TokenResult = await import_libs.intlayerAPI.auth.getOAuth2AccessToken();
34
+ const intlayerAPI = (0, import_libs.getIntlayerAPI)(void 0, config);
35
+ const oAuth2TokenResult = await intlayerAPI.auth.getOAuth2AccessToken();
36
36
  const oAuth2AccessToken = oAuth2TokenResult.data?.accessToken;
37
- const getDictionariesKeysResult = await import_libs.intlayerAPI.dictionary.getDictionariesKeys({
37
+ const getDictionariesKeysResult = await intlayerAPI.dictionary.getDictionariesKeys({
38
38
  headers: { Authorization: `Bearer ${oAuth2AccessToken}` }
39
39
  });
40
40
  if (!getDictionariesKeysResult.data) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/fetchDistantDictionaryKeys.ts"],"sourcesContent":["import { getConfiguration } from '@intlayer/config';\n// @ts-ignore @intlayer/design-system not build yet\nimport { intlayerAPI } from '@intlayer/design-system/libs';\n\nexport const fetchDistantDictionaryKeys = async (): Promise<string[]> => {\n const {\n editor: { clientId, clientSecret },\n } = getConfiguration();\n\n if (!clientId || !clientSecret) {\n throw new Error(\n 'Missing OAuth2 client ID or client secret. To get access token go to https://intlayer.org/dashboard/project.'\n );\n }\n\n const oAuth2TokenResult = await intlayerAPI.auth.getOAuth2AccessToken();\n\n const oAuth2AccessToken = oAuth2TokenResult.data?.accessToken;\n\n // Get the list of dictionary keys\n const getDictionariesKeysResult =\n await intlayerAPI.dictionary.getDictionariesKeys({\n headers: { Authorization: `Bearer ${oAuth2AccessToken}` },\n });\n\n if (!getDictionariesKeysResult.data) {\n throw new Error('No distant dictionaries found');\n }\n\n const distantDictionariesKeys: string[] = getDictionariesKeysResult.data;\n\n // Apply any filtering if needed\n return distantDictionariesKeys;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAiC;AAEjC,kBAA4B;AAErB,MAAM,6BAA6B,YAA+B;AACvE,QAAM;AAAA,IACJ,QAAQ,EAAE,UAAU,aAAa;AAAA,EACnC,QAAI,gCAAiB;AAErB,MAAI,CAAC,YAAY,CAAC,cAAc;AAC9B,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,oBAAoB,MAAM,wBAAY,KAAK,qBAAqB;AAEtE,QAAM,oBAAoB,kBAAkB,MAAM;AAGlD,QAAM,4BACJ,MAAM,wBAAY,WAAW,oBAAoB;AAAA,IAC/C,SAAS,EAAE,eAAe,UAAU,iBAAiB,GAAG;AAAA,EAC1D,CAAC;AAEH,MAAI,CAAC,0BAA0B,MAAM;AACnC,UAAM,IAAI,MAAM,+BAA+B;AAAA,EACjD;AAEA,QAAM,0BAAoC,0BAA0B;AAGpE,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/fetchDistantDictionaryKeys.ts"],"sourcesContent":["import { getConfiguration } from '@intlayer/config';\n// @ts-ignore @intlayer/design-system not build yet\nimport { getIntlayerAPI } from '@intlayer/design-system/libs';\n\nexport const fetchDistantDictionaryKeys = async (): Promise<string[]> => {\n const config = getConfiguration();\n const { clientId, clientSecret } = config.editor;\n\n if (!clientId || !clientSecret) {\n throw new Error(\n 'Missing OAuth2 client ID or client secret. To get access token go to https://intlayer.org/dashboard/project.'\n );\n }\n\n const intlayerAPI = getIntlayerAPI(undefined, config);\n\n const oAuth2TokenResult = await intlayerAPI.auth.getOAuth2AccessToken();\n\n const oAuth2AccessToken = oAuth2TokenResult.data?.accessToken;\n\n // Get the list of dictionary keys\n const getDictionariesKeysResult =\n await intlayerAPI.dictionary.getDictionariesKeys({\n headers: { Authorization: `Bearer ${oAuth2AccessToken}` },\n });\n\n if (!getDictionariesKeysResult.data) {\n throw new Error('No distant dictionaries found');\n }\n\n const distantDictionariesKeys: string[] = getDictionariesKeysResult.data;\n\n // Apply any filtering if needed\n return distantDictionariesKeys;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAiC;AAEjC,kBAA+B;AAExB,MAAM,6BAA6B,YAA+B;AACvE,QAAM,aAAS,gCAAiB;AAChC,QAAM,EAAE,UAAU,aAAa,IAAI,OAAO;AAE1C,MAAI,CAAC,YAAY,CAAC,cAAc;AAC9B,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,kBAAc,4BAAe,QAAW,MAAM;AAEpD,QAAM,oBAAoB,MAAM,YAAY,KAAK,qBAAqB;AAEtE,QAAM,oBAAoB,kBAAkB,MAAM;AAGlD,QAAM,4BACJ,MAAM,YAAY,WAAW,oBAAoB;AAAA,IAC/C,SAAS,EAAE,eAAe,UAAU,iBAAiB,GAAG;AAAA,EAC1D,CAAC;AAEH,MAAI,CAAC,0BAA0B,MAAM;AACnC,UAAM,IAAI,MAAM,+BAA+B;AAAA,EACjD;AAEA,QAAM,0BAAoC,0BAA0B;AAGpE,SAAO;AACT;","names":[]}
@@ -36,14 +36,13 @@ var import_deepmerge = __toESM(require("deepmerge"));
36
36
  var import_fetchDistantDictionaryKeys = require('../fetchDistantDictionaryKeys.cjs');
37
37
  var import_log = require('../log.cjs');
38
38
  var import_mergeDictionaries = require('../mergeDictionaries.cjs');
39
+ var import_utils = require('../utils.cjs');
39
40
  var import_loadContentDeclaration = require('./loadContentDeclaration.cjs');
40
41
  var import_loadDistantDictionaries = require('./loadDistantDictionaries.cjs');
41
42
  const LOG_PREFIX = "[intlayer] ";
42
43
  const loadDictionaries = async (contentDeclarationsPaths) => {
43
44
  try {
44
- const { editor } = (0, import_config.getConfiguration)({
45
- verbose: true
46
- });
45
+ const { editor } = (0, import_config.getConfiguration)();
47
46
  console.info(`${LOG_PREFIX}Dictionaries:`);
48
47
  const files = Array.isArray(contentDeclarationsPaths) ? contentDeclarationsPaths : [contentDeclarationsPaths];
49
48
  const localDictionaries = await (0, import_loadContentDeclaration.loadContentDeclarations)(files);
@@ -57,9 +56,10 @@ const loadDictionaries = async (contentDeclarationsPaths) => {
57
56
  let mergedDictionaries = localDictionaries;
58
57
  if (editor.clientId && editor.clientSecret) {
59
58
  distantDictionaryKeys = await (0, import_fetchDistantDictionaryKeys.fetchDistantDictionaryKeys)();
60
- import_log.logger.addDictionaryKeys("distant", distantDictionaryKeys);
59
+ const orderedDistantDictionaryKeys = distantDictionaryKeys.sort(import_utils.sortAlphabetically);
60
+ import_log.logger.addDictionaryKeys("distant", orderedDistantDictionaryKeys);
61
61
  distantDictionaries = await (0, import_loadDistantDictionaries.loadDistantDictionaries)({
62
- dictionaryKeys: distantDictionaryKeys
62
+ dictionaryKeys: orderedDistantDictionaryKeys
63
63
  });
64
64
  if (editor.dictionaryPriorityStrategy === "distant_first") {
65
65
  mergedDictionaries = (0, import_deepmerge.default)(localDictionaries, distantDictionaries, {
@@ -74,7 +74,6 @@ const loadDictionaries = async (contentDeclarationsPaths) => {
74
74
  import_log.logger.stop();
75
75
  return mergedDictionaries;
76
76
  } catch (error) {
77
- console.error(error);
78
77
  import_log.logger.stop();
79
78
  throw error;
80
79
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/loadDictionaries/loadDictionaries.ts"],"sourcesContent":["// @ts-ignore @intlayer/backend not build yet\nimport { type DictionaryAPI } from '@intlayer/backend';\nimport { getConfiguration } from '@intlayer/config';\nimport { Dictionary } from '@intlayer/core';\nimport merge from 'deepmerge';\nimport { fetchDistantDictionaryKeys } from '../fetchDistantDictionaryKeys';\nimport { logger } from '../log';\nimport { mergeByKey } from '../mergeDictionaries';\nimport { loadContentDeclarations } from './loadContentDeclaration';\nimport { loadDistantDictionaries } from './loadDistantDictionaries';\n\nconst LOG_PREFIX = '[intlayer] ';\n\nexport const loadDictionaries = async (\n contentDeclarationsPaths: string[] | string\n): Promise<Dictionary[]> => {\n try {\n const { editor } = getConfiguration({\n verbose: true,\n });\n\n console.info(`${LOG_PREFIX}Dictionaries:`);\n\n const files = Array.isArray(contentDeclarationsPaths)\n ? contentDeclarationsPaths\n : [contentDeclarationsPaths];\n\n const localDictionaries: Dictionary[] =\n await loadContentDeclarations(files);\n const localDictionaryKeys = localDictionaries.map((dict) => dict.key);\n\n // Initialize the logger with both local and distant dictionaries\n logger.init(localDictionaryKeys, []);\n\n // Update logger statuses for local dictionaries\n for (const dict of localDictionaries) {\n logger.updateStatus(dict.key, 'local', { status: 'built' });\n }\n\n let distantDictionaries: DictionaryAPI[] = [];\n let distantDictionaryKeys: string[] = [];\n let mergedDictionaries = localDictionaries;\n\n if (editor.clientId && editor.clientSecret) {\n // Fetch distant dictionary keys\n distantDictionaryKeys = await fetchDistantDictionaryKeys();\n\n // Add distant dictionaries to the logger\n logger.addDictionaryKeys('distant', distantDictionaryKeys);\n\n // Fetch distant dictionaries\n distantDictionaries = await loadDistantDictionaries({\n dictionaryKeys: distantDictionaryKeys,\n });\n if (editor.dictionaryPriorityStrategy === 'distant_first') {\n // Merge the dictionaries\n mergedDictionaries = merge(localDictionaries, distantDictionaries, {\n arrayMerge: mergeByKey('key'),\n });\n } else {\n // Merge the dictionaries\n mergedDictionaries = merge(distantDictionaries, localDictionaries, {\n arrayMerge: mergeByKey('key'),\n });\n }\n }\n\n // Ensure the logger is stopped\n logger.stop();\n\n return mergedDictionaries;\n } catch (error) {\n console.error(error);\n // Ensure the logger is stopped\n logger.stop();\n throw error; // Re-throw the error after logging\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,oBAAiC;AAEjC,uBAAkB;AAClB,wCAA2C;AAC3C,iBAAuB;AACvB,+BAA2B;AAC3B,oCAAwC;AACxC,qCAAwC;AAExC,MAAM,aAAa;AAEZ,MAAM,mBAAmB,OAC9B,6BAC0B;AAC1B,MAAI;AACF,UAAM,EAAE,OAAO,QAAI,gCAAiB;AAAA,MAClC,SAAS;AAAA,IACX,CAAC;AAED,YAAQ,KAAK,GAAG,UAAU,eAAe;AAEzC,UAAM,QAAQ,MAAM,QAAQ,wBAAwB,IAChD,2BACA,CAAC,wBAAwB;AAE7B,UAAM,oBACJ,UAAM,uDAAwB,KAAK;AACrC,UAAM,sBAAsB,kBAAkB,IAAI,CAAC,SAAS,KAAK,GAAG;AAGpE,sBAAO,KAAK,qBAAqB,CAAC,CAAC;AAGnC,eAAW,QAAQ,mBAAmB;AACpC,wBAAO,aAAa,KAAK,KAAK,SAAS,EAAE,QAAQ,QAAQ,CAAC;AAAA,IAC5D;AAEA,QAAI,sBAAuC,CAAC;AAC5C,QAAI,wBAAkC,CAAC;AACvC,QAAI,qBAAqB;AAEzB,QAAI,OAAO,YAAY,OAAO,cAAc;AAE1C,8BAAwB,UAAM,8DAA2B;AAGzD,wBAAO,kBAAkB,WAAW,qBAAqB;AAGzD,4BAAsB,UAAM,wDAAwB;AAAA,QAClD,gBAAgB;AAAA,MAClB,CAAC;AACD,UAAI,OAAO,+BAA+B,iBAAiB;AAEzD,iCAAqB,iBAAAA,SAAM,mBAAmB,qBAAqB;AAAA,UACjE,gBAAY,qCAAW,KAAK;AAAA,QAC9B,CAAC;AAAA,MACH,OAAO;AAEL,iCAAqB,iBAAAA,SAAM,qBAAqB,mBAAmB;AAAA,UACjE,gBAAY,qCAAW,KAAK;AAAA,QAC9B,CAAC;AAAA,MACH;AAAA,IACF;AAGA,sBAAO,KAAK;AAEZ,WAAO;AAAA,EACT,SAAS,OAAO;AACd,YAAQ,MAAM,KAAK;AAEnB,sBAAO,KAAK;AACZ,UAAM;AAAA,EACR;AACF;","names":["merge"]}
1
+ {"version":3,"sources":["../../../src/loadDictionaries/loadDictionaries.ts"],"sourcesContent":["// @ts-ignore @intlayer/backend not build yet\nimport { type DictionaryAPI } from '@intlayer/backend';\nimport { getConfiguration } from '@intlayer/config';\nimport { Dictionary } from '@intlayer/core';\nimport merge from 'deepmerge';\nimport { fetchDistantDictionaryKeys } from '../fetchDistantDictionaryKeys';\nimport { logger } from '../log';\nimport { mergeByKey } from '../mergeDictionaries';\nimport { sortAlphabetically } from '../utils';\nimport { loadContentDeclarations } from './loadContentDeclaration';\nimport { loadDistantDictionaries } from './loadDistantDictionaries';\n\nconst LOG_PREFIX = '[intlayer] ';\n\nexport const loadDictionaries = async (\n contentDeclarationsPaths: string[] | string\n): Promise<Dictionary[]> => {\n try {\n const { editor } = getConfiguration();\n\n console.info(`${LOG_PREFIX}Dictionaries:`);\n\n const files = Array.isArray(contentDeclarationsPaths)\n ? contentDeclarationsPaths\n : [contentDeclarationsPaths];\n\n const localDictionaries: Dictionary[] =\n await loadContentDeclarations(files);\n const localDictionaryKeys = localDictionaries.map((dict) => dict.key);\n\n // Initialize the logger with both local and distant dictionaries\n logger.init(localDictionaryKeys, []);\n\n // Update logger statuses for local dictionaries\n for (const dict of localDictionaries) {\n logger.updateStatus(dict.key, 'local', { status: 'built' });\n }\n\n let distantDictionaries: DictionaryAPI[] = [];\n let distantDictionaryKeys: string[] = [];\n let mergedDictionaries = localDictionaries;\n\n if (editor.clientId && editor.clientSecret) {\n // Fetch distant dictionary keys\n distantDictionaryKeys = await fetchDistantDictionaryKeys();\n\n const orderedDistantDictionaryKeys =\n distantDictionaryKeys.sort(sortAlphabetically);\n // Add distant dictionaries to the logger\n logger.addDictionaryKeys('distant', orderedDistantDictionaryKeys);\n\n // Fetch distant dictionaries\n distantDictionaries = await loadDistantDictionaries({\n dictionaryKeys: orderedDistantDictionaryKeys,\n });\n if (editor.dictionaryPriorityStrategy === 'distant_first') {\n // Merge the dictionaries\n mergedDictionaries = merge(localDictionaries, distantDictionaries, {\n arrayMerge: mergeByKey('key'),\n });\n } else {\n // Merge the dictionaries\n mergedDictionaries = merge(distantDictionaries, localDictionaries, {\n arrayMerge: mergeByKey('key'),\n });\n }\n }\n\n // Ensure the logger is stopped\n logger.stop();\n\n return mergedDictionaries;\n } catch (error) {\n // Ensure the logger is stopped\n logger.stop();\n\n throw error; // Re-throw the error after logging\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,oBAAiC;AAEjC,uBAAkB;AAClB,wCAA2C;AAC3C,iBAAuB;AACvB,+BAA2B;AAC3B,mBAAmC;AACnC,oCAAwC;AACxC,qCAAwC;AAExC,MAAM,aAAa;AAEZ,MAAM,mBAAmB,OAC9B,6BAC0B;AAC1B,MAAI;AACF,UAAM,EAAE,OAAO,QAAI,gCAAiB;AAEpC,YAAQ,KAAK,GAAG,UAAU,eAAe;AAEzC,UAAM,QAAQ,MAAM,QAAQ,wBAAwB,IAChD,2BACA,CAAC,wBAAwB;AAE7B,UAAM,oBACJ,UAAM,uDAAwB,KAAK;AACrC,UAAM,sBAAsB,kBAAkB,IAAI,CAAC,SAAS,KAAK,GAAG;AAGpE,sBAAO,KAAK,qBAAqB,CAAC,CAAC;AAGnC,eAAW,QAAQ,mBAAmB;AACpC,wBAAO,aAAa,KAAK,KAAK,SAAS,EAAE,QAAQ,QAAQ,CAAC;AAAA,IAC5D;AAEA,QAAI,sBAAuC,CAAC;AAC5C,QAAI,wBAAkC,CAAC;AACvC,QAAI,qBAAqB;AAEzB,QAAI,OAAO,YAAY,OAAO,cAAc;AAE1C,8BAAwB,UAAM,8DAA2B;AAEzD,YAAM,+BACJ,sBAAsB,KAAK,+BAAkB;AAE/C,wBAAO,kBAAkB,WAAW,4BAA4B;AAGhE,4BAAsB,UAAM,wDAAwB;AAAA,QAClD,gBAAgB;AAAA,MAClB,CAAC;AACD,UAAI,OAAO,+BAA+B,iBAAiB;AAEzD,iCAAqB,iBAAAA,SAAM,mBAAmB,qBAAqB;AAAA,UACjE,gBAAY,qCAAW,KAAK;AAAA,QAC9B,CAAC;AAAA,MACH,OAAO;AAEL,iCAAqB,iBAAAA,SAAM,qBAAqB,mBAAmB;AAAA,UACjE,gBAAY,qCAAW,KAAK;AAAA,QAC9B,CAAC;AAAA,MACH;AAAA,IACF;AAGA,sBAAO,KAAK;AAEZ,WAAO;AAAA,EACT,SAAS,OAAO;AAEd,sBAAO,KAAK;AAEZ,UAAM;AAAA,EACR;AACF;","names":["merge"]}
package/dist/cjs/log.cjs CHANGED
@@ -31,7 +31,8 @@ __export(log_exports, {
31
31
  logger: () => logger
32
32
  });
33
33
  module.exports = __toCommonJS(log_exports);
34
- var readline = __toESM(require("readline"));
34
+ var import_log_update = __toESM(require("log-update"));
35
+ var import_utils = require('./utils.cjs');
35
36
  class Logger {
36
37
  dictionariesStatuses = [];
37
38
  spinnerFrames = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
@@ -56,7 +57,11 @@ class Logger {
56
57
  }
57
58
  init(localDictionariesKeys, distantDictionariesKeys) {
58
59
  const allKeys = Array.from(
59
- /* @__PURE__ */ new Set([...localDictionariesKeys, ...distantDictionariesKeys])
60
+ new Set(
61
+ [...localDictionariesKeys, ...distantDictionariesKeys].sort(
62
+ import_utils.sortAlphabetically
63
+ )
64
+ )
60
65
  );
61
66
  this.maxDictionaryKeyLength = allKeys.reduce(
62
67
  (max, key) => key.length > max ? key.length : max,
@@ -83,10 +88,8 @@ class Logger {
83
88
  state: states
84
89
  };
85
90
  });
86
- for (const statusObj of this.dictionariesStatuses) {
87
- process.stdout.write(this.getStatusLine(statusObj) + "\n");
88
- }
89
91
  this.startSpinner();
92
+ this.updateAllStatusLines();
90
93
  }
91
94
  // New method to add dictionary keys after initialization
92
95
  addDictionaryKeys(type, dictionaryKeys) {
@@ -109,7 +112,6 @@ class Logger {
109
112
  spinnerFrameIndex: 0
110
113
  };
111
114
  statusObj.state.push(newState);
112
- process.stdout.write(this.getStatusLine(statusObj) + "\n");
113
115
  } else {
114
116
  const existingState = statusObj.state.find((s) => s.type === type);
115
117
  if (!existingState) {
@@ -119,22 +121,10 @@ class Logger {
119
121
  spinnerFrameIndex: 0
120
122
  };
121
123
  statusObj.state.push(newState);
122
- const lineIndex = this.dictionariesStatuses.indexOf(statusObj);
123
- readline.moveCursor(
124
- process.stdout,
125
- 0,
126
- -(this.dictionariesStatuses.length - lineIndex)
127
- );
128
- readline.clearLine(process.stdout, 0);
129
- process.stdout.write(this.getStatusLine(statusObj) + "\n");
130
- readline.moveCursor(
131
- process.stdout,
132
- 0,
133
- this.dictionariesStatuses.length - lineIndex - 1
134
- );
135
124
  }
136
125
  }
137
126
  }
127
+ this.updateAllStatusLines();
138
128
  }
139
129
  startSpinner() {
140
130
  if (!this.spinnerTimer) {
@@ -151,7 +141,11 @@ class Logger {
151
141
  }
152
142
  stop() {
153
143
  this.stopSpinner();
154
- this.updateAllStatusLines();
144
+ import_log_update.default.clear();
145
+ const lines = this.dictionariesStatuses.map(
146
+ (statusObj) => this.getStatusLine(statusObj)
147
+ );
148
+ console.log(lines.join("\n"));
155
149
  }
156
150
  updateStatus(dictionaryKey, type, status) {
157
151
  const statusObj = this.dictionariesStatuses.find(
@@ -189,8 +183,8 @@ class Logger {
189
183
  state: [newState]
190
184
  });
191
185
  }
186
+ this.updateAllStatusLines();
192
187
  }
193
- // Rest of the Logger class remains the same...
194
188
  getStatusIcon(status) {
195
189
  const statusIcons = {
196
190
  pending: "\u23F2",
@@ -204,7 +198,7 @@ class Logger {
204
198
  }
205
199
  getStatusLine(statusObj) {
206
200
  const keyPadding = this.maxDictionaryKeyLength - statusObj.dictionaryKey.length;
207
- const paddedKey = statusObj.dictionaryKey + " ".repeat(keyPadding);
201
+ const paddedKey = `${statusObj.dictionaryKey}${" ".repeat(keyPadding)}`;
208
202
  const states = statusObj.state.map((state) => {
209
203
  let colorStart = "";
210
204
  let colorEnd = "";
@@ -229,19 +223,15 @@ class Logger {
229
223
  return `- ${paddedKey} ${states.join(" ")}`;
230
224
  }
231
225
  updateAllStatusLines() {
232
- readline.moveCursor(process.stdout, 0, -this.dictionariesStatuses.length);
233
- for (const statusObj of this.dictionariesStatuses) {
234
- readline.clearLine(process.stdout, 0);
235
- if (typeof statusObj?.state === "undefined") {
236
- return;
237
- }
226
+ const lines = this.dictionariesStatuses.map((statusObj) => {
238
227
  statusObj.state.forEach((state) => {
239
228
  if (state.status === "fetching") {
240
229
  state.spinnerFrameIndex = (state.spinnerFrameIndex + 1) % this.spinnerFrames.length;
241
230
  }
242
231
  });
243
- process.stdout.write(this.getStatusLine(statusObj) + "\n");
244
- }
232
+ return this.getStatusLine(statusObj);
233
+ });
234
+ (0, import_log_update.default)(lines.join("\n"));
245
235
  }
246
236
  getStatuses() {
247
237
  return this.dictionariesStatuses;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/log.ts"],"sourcesContent":["import * as readline from 'readline';\n\nexport type State = {\n type: 'local' | 'distant';\n status: 'pending' | 'fetching' | 'fetched' | 'error' | 'imported' | 'built';\n icon?: string;\n error?: Error;\n errorMessage?: string;\n spinnerFrameIndex?: number;\n};\n\nexport type DictionariesStatus = {\n dictionaryKey: string;\n state: State[];\n};\n\nclass Logger {\n private dictionariesStatuses: DictionariesStatus[] = [];\n private spinnerFrames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\n private spinnerTimer: NodeJS.Timeout | null = null;\n private maxDictionaryKeyLength: number = 0;\n\n // ANSI color codes\n private RESET = '\\x1b[0m';\n private GREEN = '\\x1b[32m';\n private RED = '\\x1b[31m';\n private BLUE = '\\x1b[34m';\n private GREY = '\\x1b[90m';\n private GREY_DARK = '\\x1b[90m';\n\n // Singleton instance\n private static instance: Logger;\n\n private constructor() {}\n\n public static getInstance(): Logger {\n if (!Logger.instance) {\n Logger.instance = new Logger();\n }\n return Logger.instance;\n }\n\n public init(\n localDictionariesKeys: string[],\n distantDictionariesKeys: string[]\n ) {\n const allKeys = Array.from(\n new Set([...localDictionariesKeys, ...distantDictionariesKeys])\n );\n\n this.maxDictionaryKeyLength = allKeys.reduce(\n (max, key) => (key.length > max ? key.length : max),\n 0\n );\n\n this.dictionariesStatuses = allKeys.map((dictionaryKey) => {\n const states: State[] = [];\n if (localDictionariesKeys.includes(dictionaryKey)) {\n states.push({\n type: 'local',\n status: 'pending',\n spinnerFrameIndex: 0,\n });\n }\n if (distantDictionariesKeys.includes(dictionaryKey)) {\n states.push({\n type: 'distant',\n status: 'pending',\n spinnerFrameIndex: 0,\n });\n }\n return {\n dictionaryKey,\n state: states,\n };\n });\n\n // Output initial statuses\n for (const statusObj of this.dictionariesStatuses) {\n process.stdout.write(this.getStatusLine(statusObj) + '\\n');\n }\n\n // Start spinner timer\n this.startSpinner();\n }\n\n // New method to add dictionary keys after initialization\n public addDictionaryKeys(\n type: 'local' | 'distant',\n dictionaryKeys: string[]\n ) {\n for (const dictionaryKey of dictionaryKeys) {\n // Update maxDictionaryKeyLength if the new key is longer\n if (dictionaryKey.length > this.maxDictionaryKeyLength) {\n this.maxDictionaryKeyLength = dictionaryKey.length;\n }\n\n let statusObj = this.dictionariesStatuses.find(\n (ds) => ds.dictionaryKey === dictionaryKey\n );\n\n if (!statusObj) {\n // If the dictionaryKey doesn't exist yet, create a new DictionariesStatus\n statusObj = {\n dictionaryKey,\n state: [],\n };\n this.dictionariesStatuses.push(statusObj);\n\n const newState: State = {\n type,\n status: 'pending',\n spinnerFrameIndex: 0,\n };\n statusObj.state.push(newState);\n\n // Output the new status line\n process.stdout.write(this.getStatusLine(statusObj) + '\\n');\n } else {\n const existingState = statusObj.state.find((s) => s.type === type);\n if (!existingState) {\n // Add new state for the type\n const newState: State = {\n type,\n status: 'pending',\n spinnerFrameIndex: 0,\n };\n statusObj.state.push(newState);\n\n // Update the existing line\n const lineIndex = this.dictionariesStatuses.indexOf(statusObj);\n // Move cursor up to the lineIndex from the bottom\n readline.moveCursor(\n process.stdout,\n 0,\n -(this.dictionariesStatuses.length - lineIndex)\n );\n readline.clearLine(process.stdout, 0);\n process.stdout.write(this.getStatusLine(statusObj) + '\\n');\n // Move cursor back to the bottom\n readline.moveCursor(\n process.stdout,\n 0,\n this.dictionariesStatuses.length - lineIndex - 1\n );\n }\n }\n }\n // No need to redraw all status lines\n }\n\n private startSpinner() {\n if (!this.spinnerTimer) {\n this.spinnerTimer = setInterval(() => {\n this.updateAllStatusLines();\n }, 100); // Update every 100ms\n }\n }\n\n private stopSpinner() {\n if (this.spinnerTimer) {\n clearInterval(this.spinnerTimer);\n this.spinnerTimer = null;\n }\n }\n\n public stop() {\n this.stopSpinner();\n // Update statuses one last time\n this.updateAllStatusLines();\n }\n\n public updateStatus(\n dictionaryKey: string,\n type: 'local' | 'distant',\n status: Partial<State>\n ) {\n const statusObj = this.dictionariesStatuses.find(\n (ds) => ds.dictionaryKey === dictionaryKey\n );\n if (statusObj) {\n const state = statusObj.state.find((s) => s.type === type);\n if (state) {\n // Update existing state\n Object.assign(state, status);\n } else {\n // If the state for this type doesn't exist yet, add it\n if (status.status === undefined) {\n status.status = 'pending'; // Provide default status\n }\n const newState: State = {\n type,\n status: status.status,\n icon: status.icon ?? '',\n error: status.error,\n errorMessage: status.errorMessage,\n spinnerFrameIndex: status.spinnerFrameIndex ?? 0,\n };\n statusObj.state.push(newState);\n }\n } else {\n // If the status object doesn't exist, create it\n const newState: State = {\n type,\n status: status.status ?? 'pending',\n icon: status.icon ?? '',\n error: status.error,\n errorMessage: status.errorMessage,\n spinnerFrameIndex: status.spinnerFrameIndex ?? 0,\n };\n this.dictionariesStatuses.push({\n dictionaryKey,\n state: [newState],\n });\n }\n }\n\n // Rest of the Logger class remains the same...\n\n private getStatusIcon(status: string): string {\n const statusIcons: Record<string, string> = {\n pending: '⏲',\n fetching: '', // Spinner handled separately\n built: '✔',\n imported: '✔',\n error: '✖',\n };\n return statusIcons[status] ?? '';\n }\n\n private getStatusLine(statusObj: DictionariesStatus): string {\n const keyPadding =\n this.maxDictionaryKeyLength - statusObj.dictionaryKey.length;\n const paddedKey = statusObj.dictionaryKey + ' '.repeat(keyPadding);\n\n const states = statusObj.state.map((state) => {\n let colorStart = '';\n let colorEnd = '';\n let icon = this.getStatusIcon(state.status);\n if (state.status === 'fetching') {\n // Use spinner frame\n icon =\n this.spinnerFrames[\n state.spinnerFrameIndex! % this.spinnerFrames.length\n ];\n colorStart = this.BLUE;\n colorEnd = this.RESET;\n } else if (state.status === 'error') {\n colorStart = this.RED;\n colorEnd = this.RESET;\n } else if (state.status === 'imported' || state.status === 'built') {\n colorStart = this.GREEN;\n colorEnd = this.RESET;\n } else {\n colorStart = this.GREY;\n colorEnd = this.RESET;\n }\n\n // Format the status block\n const statusBlock = `${this.GREY_DARK}[${state.type}: ${colorStart}${icon} ${state.status}${this.GREY_DARK}]${colorEnd}`;\n\n return `${colorStart}${statusBlock}${colorEnd}`;\n });\n\n return `- ${paddedKey} ${states.join(' ')}`;\n }\n\n private updateAllStatusLines() {\n // Move cursor up to the first status line\n readline.moveCursor(process.stdout, 0, -this.dictionariesStatuses.length);\n\n for (const statusObj of this.dictionariesStatuses) {\n // Clear the line\n readline.clearLine(process.stdout, 0);\n\n if (typeof statusObj?.state === 'undefined') {\n return;\n }\n\n statusObj.state.forEach((state) => {\n if (state.status === 'fetching') {\n // Update spinner frame\n state.spinnerFrameIndex =\n (state.spinnerFrameIndex! + 1) % this.spinnerFrames.length;\n }\n });\n\n // Write the status line\n process.stdout.write(this.getStatusLine(statusObj) + '\\n');\n }\n }\n\n public getStatuses() {\n return this.dictionariesStatuses;\n }\n}\n\nexport const logger = Logger.getInstance();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,eAA0B;AAgB1B,MAAM,OAAO;AAAA,EACH,uBAA6C,CAAC;AAAA,EAC9C,gBAAgB,CAAC,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,QAAG;AAAA,EACjE,eAAsC;AAAA,EACtC,yBAAiC;AAAA;AAAA,EAGjC,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AAAA,EACP,YAAY;AAAA;AAAA,EAGpB,OAAe;AAAA,EAEP,cAAc;AAAA,EAAC;AAAA,EAEvB,OAAc,cAAsB;AAClC,QAAI,CAAC,OAAO,UAAU;AACpB,aAAO,WAAW,IAAI,OAAO;AAAA,IAC/B;AACA,WAAO,OAAO;AAAA,EAChB;AAAA,EAEO,KACL,uBACA,yBACA;AACA,UAAM,UAAU,MAAM;AAAA,MACpB,oBAAI,IAAI,CAAC,GAAG,uBAAuB,GAAG,uBAAuB,CAAC;AAAA,IAChE;AAEA,SAAK,yBAAyB,QAAQ;AAAA,MACpC,CAAC,KAAK,QAAS,IAAI,SAAS,MAAM,IAAI,SAAS;AAAA,MAC/C;AAAA,IACF;AAEA,SAAK,uB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UAAU,GAAG,IAAI,IAAI,MAAM,MAAM,GAAG,KAAK,SAAS,IAAI,QAAQ;AAEtH,aAAO,GAAG,UAAU,GAAG,WAAW,GAAG,QAAQ;AAAA,IAC/C,CAAC;AAED,WAAO,KAAK,SAAS,IAAI,OAAO,KAAK,GAAG,CAAC;AAAA,EAC3C;AAAA,EAEQ,uBAAuB;AAE7B,aAAS,WAAW,QAAQ,QAAQ,GAAG,CAAC,KAAK,qBAAqB,MAAM;AAExE,eAAW,aAAa,KAAK,sBAAsB;AAEjD,eAAS,UAAU,QAAQ,QAAQ,CAAC;AAEpC,UAAI,OAAO,WAAW,UAAU,aAAa;AAC3C;AAAA,MACF;AAEA,gBAAU,MAAM,QAAQ,CAAC,UAAU;AACjC,YAAI,MAAM,WAAW,YAAY;AAE/B,gBAAM,qBACH,MAAM,oBAAqB,KAAK,KAAK,cAAc;AAAA,QACxD;AAAA,MACF,CAAC;AAGD,cAAQ,OAAO,MAAM,KAAK,cAAc,SAAS,IAAI,IAAI;AAAA,IAC3D;AAAA,EACF;AAAA,EAEO,cAAc;AACnB,WAAO,KAAK;AAAA,EACd;AACF;AAEO,MAAM,SAAS,OAAO,YAAY;","names":[]}
1
+ {"version":3,"sources":["../../src/log.ts"],"sourcesContent":["import logUpdate from 'log-update';\nimport { sortAlphabetically } from './utils';\n\nexport type State = {\n type: 'local' | 'distant';\n status: 'pending' | 'fetching' | 'fetched' | 'error' | 'imported' | 'built';\n icon?: string;\n error?: Error;\n errorMessage?: string;\n spinnerFrameIndex?: number;\n};\n\nexport type DictionariesStatus = {\n dictionaryKey: string;\n state: State[];\n};\n\nclass Logger {\n private dictionariesStatuses: DictionariesStatus[] = [];\n private spinnerFrames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\n private spinnerTimer: NodeJS.Timeout | null = null;\n private maxDictionaryKeyLength: number = 0;\n\n // ANSI color codes\n private RESET = '\\x1b[0m';\n private GREEN = '\\x1b[32m';\n private RED = '\\x1b[31m';\n private BLUE = '\\x1b[34m';\n private GREY = '\\x1b[90m';\n private GREY_DARK = '\\x1b[90m';\n\n // Singleton instance\n private static instance: Logger;\n\n private constructor() {}\n\n public static getInstance(): Logger {\n if (!Logger.instance) {\n Logger.instance = new Logger();\n }\n return Logger.instance;\n }\n\n public init(\n localDictionariesKeys: string[],\n distantDictionariesKeys: string[]\n ) {\n const allKeys = Array.from(\n new Set(\n [...localDictionariesKeys, ...distantDictionariesKeys].sort(\n sortAlphabetically\n )\n )\n );\n\n this.maxDictionaryKeyLength = allKeys.reduce(\n (max, key) => (key.length > max ? key.length : max),\n 0\n );\n\n this.dictionariesStatuses = allKeys.map((dictionaryKey) => {\n const states: State[] = [];\n\n if (localDictionariesKeys.includes(dictionaryKey)) {\n states.push({\n type: 'local',\n status: 'pending',\n spinnerFrameIndex: 0,\n });\n }\n if (distantDictionariesKeys.includes(dictionaryKey)) {\n states.push({\n type: 'distant',\n status: 'pending',\n spinnerFrameIndex: 0,\n });\n }\n\n return {\n dictionaryKey,\n state: states,\n };\n });\n\n // Start spinner timer\n this.startSpinner();\n\n // Update all status lines (this will output the initial statuses)\n this.updateAllStatusLines();\n }\n\n // New method to add dictionary keys after initialization\n public addDictionaryKeys(\n type: 'local' | 'distant',\n dictionaryKeys: string[]\n ) {\n for (const dictionaryKey of dictionaryKeys) {\n // Update maxDictionaryKeyLength if the new key is longer\n if (dictionaryKey.length > this.maxDictionaryKeyLength) {\n this.maxDictionaryKeyLength = dictionaryKey.length;\n }\n\n let statusObj = this.dictionariesStatuses.find(\n (ds) => ds.dictionaryKey === dictionaryKey\n );\n\n if (!statusObj) {\n // If the dictionaryKey doesn't exist yet, create a new DictionariesStatus\n\n statusObj = {\n dictionaryKey,\n state: [],\n };\n this.dictionariesStatuses.push(statusObj);\n\n const newState: State = {\n type,\n status: 'pending',\n spinnerFrameIndex: 0,\n };\n statusObj.state.push(newState);\n } else {\n const existingState = statusObj.state.find((s) => s.type === type);\n if (!existingState) {\n // Add new state for the type\n\n const newState: State = {\n type,\n status: 'pending',\n spinnerFrameIndex: 0,\n };\n statusObj.state.push(newState);\n }\n }\n }\n\n // Call updateAllStatusLines() to refresh the output\n this.updateAllStatusLines();\n }\n\n private startSpinner() {\n if (!this.spinnerTimer) {\n this.spinnerTimer = setInterval(() => {\n this.updateAllStatusLines();\n }, 100); // Update every 100ms\n }\n }\n\n private stopSpinner() {\n if (this.spinnerTimer) {\n clearInterval(this.spinnerTimer);\n this.spinnerTimer = null;\n }\n }\n\n public stop() {\n this.stopSpinner();\n logUpdate.clear(); // Clear the logUpdate output\n const lines = this.dictionariesStatuses.map((statusObj) =>\n this.getStatusLine(statusObj)\n );\n console.log(lines.join('\\n')); // Output final statuses\n }\n\n public updateStatus(\n dictionaryKey: string,\n type: 'local' | 'distant',\n status: Partial<State>\n ) {\n const statusObj = this.dictionariesStatuses.find(\n (ds) => ds.dictionaryKey === dictionaryKey\n );\n if (statusObj) {\n const state = statusObj.state.find((s) => s.type === type);\n if (state) {\n // Update existing state\n Object.assign(state, status);\n } else {\n // If the state for this type doesn't exist yet, add it\n if (status.status === undefined) {\n status.status = 'pending'; // Provide default status\n }\n const newState: State = {\n type,\n status: status.status,\n icon: status.icon ?? '',\n error: status.error,\n errorMessage: status.errorMessage,\n spinnerFrameIndex: status.spinnerFrameIndex ?? 0,\n };\n statusObj.state.push(newState);\n }\n } else {\n // If the status object doesn't exist, create it\n const newState: State = {\n type,\n status: status.status ?? 'pending',\n icon: status.icon ?? '',\n error: status.error,\n errorMessage: status.errorMessage,\n spinnerFrameIndex: status.spinnerFrameIndex ?? 0,\n };\n this.dictionariesStatuses.push({\n dictionaryKey,\n state: [newState],\n });\n }\n\n // Update the display after status change\n this.updateAllStatusLines();\n }\n\n private getStatusIcon(status: string): string {\n const statusIcons: Record<string, string> = {\n pending: '⏲',\n fetching: '', // Spinner handled separately\n built: '✔',\n imported: '✔',\n error: '✖',\n };\n return statusIcons[status] ?? '';\n }\n\n private getStatusLine(statusObj: DictionariesStatus): string {\n const keyPadding =\n this.maxDictionaryKeyLength - statusObj.dictionaryKey.length;\n const paddedKey = `${statusObj.dictionaryKey}${' '.repeat(keyPadding)}`;\n\n const states = statusObj.state.map((state) => {\n let colorStart = '';\n let colorEnd = '';\n let icon = this.getStatusIcon(state.status);\n if (state.status === 'fetching') {\n // Use spinner frame\n icon =\n this.spinnerFrames[\n state.spinnerFrameIndex! % this.spinnerFrames.length\n ];\n colorStart = this.BLUE;\n colorEnd = this.RESET;\n } else if (state.status === 'error') {\n colorStart = this.RED;\n colorEnd = this.RESET;\n } else if (state.status === 'imported' || state.status === 'built') {\n colorStart = this.GREEN;\n colorEnd = this.RESET;\n } else {\n colorStart = this.GREY;\n colorEnd = this.RESET;\n }\n\n // Format the status block\n const statusBlock = `${this.GREY_DARK}[${state.type}: ${colorStart}${icon} ${state.status}${this.GREY_DARK}]${colorEnd}`;\n\n return `${colorStart}${statusBlock}${colorEnd}`;\n });\n\n return `- ${paddedKey} ${states.join(' ')}`;\n }\n\n private updateAllStatusLines() {\n const lines = this.dictionariesStatuses.map((statusObj) => {\n statusObj.state.forEach((state) => {\n if (state.status === 'fetching') {\n // Update spinner frame\n state.spinnerFrameIndex =\n (state.spinnerFrameIndex! + 1) % this.spinnerFrames.length;\n }\n });\n return this.getStatusLine(statusObj);\n });\n\n logUpdate(lines.join('\\n'));\n }\n\n public getStatuses() {\n return this.dictionariesStatuses;\n }\n}\n\nexport const logger = Logger.getInstance();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAsB;AACtB,mBAAmC;AAgBnC,MAAM,OAAO;AAAA,EACH,uBAA6C,CAAC;AAAA,EAC9C,gBAAgB,CAAC,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,QAAG;AAAA,EACjE,eAAsC;AAAA,EACtC,yBAAiC;AAAA;AAAA,EAGjC,QAAQ;AAAA,EACR,Q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AAW,MAAM,WAAW,SAAS;AACnC,qBAAa,KAAK;AAClB,mBAAW,KAAK;AAAA,MAClB,WAAW,MAAM,WAAW,cAAc,MAAM,WAAW,SAAS;AAClE,qBAAa,KAAK;AAClB,mBAAW,KAAK;AAAA,MAClB,OAAO;AACL,qBAAa,KAAK;AAClB,mBAAW,KAAK;AAAA,MAClB;AAGA,YAAM,cAAc,GAAG,KAAK,SAAS,IAAI,MAAM,IAAI,KAAK,UAAU,GAAG,IAAI,IAAI,MAAM,MAAM,GAAG,KAAK,SAAS,IAAI,QAAQ;AAEtH,aAAO,GAAG,UAAU,GAAG,WAAW,GAAG,QAAQ;AAAA,IAC/C,CAAC;AAED,WAAO,KAAK,SAAS,IAAI,OAAO,KAAK,GAAG,CAAC;AAAA,EAC3C;AAAA,EAEQ,uBAAuB;AAC7B,UAAM,QAAQ,KAAK,qBAAqB,IAAI,CAAC,cAAc;AACzD,gBAAU,MAAM,QAAQ,CAAC,UAAU;AACjC,YAAI,MAAM,WAAW,YAAY;AAE/B,gBAAM,qBACH,MAAM,oBAAqB,KAAK,KAAK,cAAc;AAAA,QACxD;AAAA,MACF,CAAC;AACD,aAAO,KAAK,cAAc,SAAS;AAAA,IACrC,CAAC;AAED,0BAAAA,SAAU,MAAM,KAAK,IAAI,CAAC;AAAA,EAC5B;AAAA,EAEO,cAAc;AACnB,WAAO,KAAK;AAAA,EACd;AACF;AAEO,MAAM,SAAS,OAAO,YAAY;","names":["logUpdate"]}
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
  var createDictionaryList_exports = {};
20
30
  __export(createDictionaryList_exports, {
@@ -24,7 +34,7 @@ module.exports = __toCommonJS(createDictionaryList_exports);
24
34
  var import_fs = require("fs");
25
35
  var import_path = require("path");
26
36
  var import_config = require("@intlayer/config");
27
- var import_glob = require("glob");
37
+ var import_fast_glob = __toESM(require("fast-glob"));
28
38
  var import_utils = require('../../utils.cjs');
29
39
  const { content } = (0, import_config.getConfiguration)();
30
40
  const { dictionariesDir, mainDir } = content;
@@ -63,7 +73,7 @@ const createDictionaryList = () => {
63
73
  if (!(0, import_fs.existsSync)(mainDir)) {
64
74
  (0, import_fs.mkdirSync)(mainDir, { recursive: true });
65
75
  }
66
- const dictionaries = (0, import_glob.sync)(`${dictionariesDir}/**/*.json`);
76
+ const dictionaries = import_fast_glob.default.sync(`${dictionariesDir}/**/*.json`);
67
77
  const cjsContent = generateDictionaryListContent(dictionaries, "cjs");
68
78
  (0, import_fs.writeFileSync)((0, import_path.resolve)(mainDir, "dictionaries.cjs"), cjsContent);
69
79
  const esmContent = generateDictionaryListContent(dictionaries, "esm");
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/transpiler/dictionary_to_main/createDictionaryList.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'fs';\nimport { basename, extname, relative, resolve } from 'path';\nimport { getConfiguration } from '@intlayer/config';\nimport { sync } from 'glob';\nimport { getFileHash } from '../../utils';\n\nconst { content } = getConfiguration();\nconst { dictionariesDir, mainDir } = content;\n\n/**\n * This function generates the content of the dictionary list file\n */\nconst generateDictionaryListContent = (\n dictionaries: string[],\n format: 'cjs' | 'esm' = 'esm'\n): string => {\n let content = '';\n\n const dictionariesRef = dictionaries.map((dictionaryPath) => ({\n relativePath: relative(mainDir, dictionaryPath),\n id: basename(dictionaryPath, extname(dictionaryPath)), // Get the base name as the dictionary id\n hash: `_${getFileHash(dictionaryPath)}`, // Get the hash of the dictionary to avoid conflicts\n }));\n\n // Import all dictionaries\n dictionariesRef.forEach((dictionary) => {\n if (format === 'esm')\n content += `import ${dictionary.hash} from '${dictionary.relativePath}';\\n`;\n if (format === 'cjs')\n content += `const ${dictionary.hash} = require('${dictionary.relativePath}');\\n`;\n });\n\n content += '\\n';\n\n // Format Dictionary Map\n const formattedDictionaryMap: string = dictionariesRef\n .map((dictionary) => `\"${dictionary.id}\": ${dictionary.hash}`)\n .join(',\\n');\n\n if (format === 'esm')\n content += `export default {\\n${formattedDictionaryMap}\\n};\\n`;\n if (format === 'cjs')\n content += `module.exports = {\\n${formattedDictionaryMap}\\n};\\n`;\n\n return content;\n};\n\n/**\n * This function generates a list of dictionaries in the main directory\n */\nexport const createDictionaryList = () => {\n // Create main directory if it doesn't exist\n if (!existsSync(mainDir)) {\n mkdirSync(mainDir, { recursive: true });\n }\n\n const dictionaries: string[] = sync(`${dictionariesDir}/**/*.json`);\n\n // Create the dictionary list file\n const cjsContent = generateDictionaryListContent(dictionaries, 'cjs');\n writeFileSync(resolve(mainDir, 'dictionaries.cjs'), cjsContent);\n\n const esmContent = generateDictionaryListContent(dictionaries, 'esm');\n writeFileSync(resolve(mainDir, 'dictionaries.mjs'), esmContent);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAAqD;AACrD,kBAAqD;AACrD,oBAAiC;AACjC,kBAAqB;AACrB,mBAA4B;AAE5B,MAAM,EAAE,QAAQ,QA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ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'fs';\nimport { basename, extname, relative, resolve } from 'path';\nimport { getConfiguration } from '@intlayer/config';\nimport fg from 'fast-glob';\nimport { getFileHash } from '../../utils';\n\nconst { content } = getConfiguration();\nconst { dictionariesDir, mainDir } = content;\n\n/**\n * This function generates the content of the dictionary list file\n */\nconst generateDictionaryListContent = (\n dictionaries: string[],\n format: 'cjs' | 'esm' = 'esm'\n): string => {\n let content = '';\n\n const dictionariesRef = dictionaries.map((dictionaryPath) => ({\n relativePath: relative(mainDir, dictionaryPath),\n id: basename(dictionaryPath, extname(dictionaryPath)), // Get the base name as the dictionary id\n hash: `_${getFileHash(dictionaryPath)}`, // Get the hash of the dictionary to avoid conflicts\n }));\n\n // Import all dictionaries\n dictionariesRef.forEach((dictionary) => {\n if (format === 'esm')\n content += `import ${dictionary.hash} from '${dictionary.relativePath}';\\n`;\n if (format === 'cjs')\n content += `const ${dictionary.hash} = require('${dictionary.relativePath}');\\n`;\n });\n\n content += '\\n';\n\n // Format Dictionary Map\n const formattedDictionaryMap: string = dictionariesRef\n .map((dictionary) => `\"${dictionary.id}\": ${dictionary.hash}`)\n .join(',\\n');\n\n if (format === 'esm')\n content += `export default {\\n${formattedDictionaryMap}\\n};\\n`;\n if (format === 'cjs')\n content += `module.exports = {\\n${formattedDictionaryMap}\\n};\\n`;\n\n return content;\n};\n\n/**\n * This function generates a list of dictionaries in the main directory\n */\nexport const createDictionaryList = () => {\n // Create main directory if it doesn't exist\n if (!existsSync(mainDir)) {\n mkdirSync(mainDir, { recursive: true });\n }\n\n const dictionaries: string[] = fg.sync(`${dictionariesDir}/**/*.json`);\n\n // Create the dictionary list file\n const cjsContent = generateDictionaryListContent(dictionaries, 'cjs');\n writeFileSync(resolve(mainDir, 'dictionaries.cjs'), cjsContent);\n\n const esmContent = generateDictionaryListContent(dictionaries, 'esm');\n writeFileSync(resolve(mainDir, 'dictionaries.mjs'), esmContent);\n};\n"],"mappings":";;;;;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GAAG,UAAU;AAE9D,QAAM,aAAa,8BAA8B,cAAc,KAAK;AACpE,mCAAc,qBAAQ,SAAS,kBAAkB,GAAG,UAAU;AAChE;","names":["content","fg"]}
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
  var createModuleAugmentation_exports = {};
20
30
  __export(createModuleAugmentation_exports, {
@@ -25,7 +35,7 @@ module.exports = __toCommonJS(createModuleAugmentation_exports);
25
35
  var import_fs = require("fs");
26
36
  var import_path = require("path");
27
37
  var import_config = require("@intlayer/config");
28
- var import_glob = require("glob");
38
+ var import_fast_glob = __toESM(require("fast-glob"));
29
39
  var import_utils = require('../../utils.cjs');
30
40
  const { content, internationalization } = (0, import_config.getConfiguration)();
31
41
  const { typesDir, moduleAugmentationDir } = content;
@@ -78,7 +88,7 @@ const createModuleAugmentation = () => {
78
88
  if (!(0, import_fs.existsSync)(moduleAugmentationDir)) {
79
89
  (0, import_fs.mkdirSync)(moduleAugmentationDir, { recursive: true });
80
90
  }
81
- const dictionaries = (0, import_glob.sync)(`${typesDir}/**/*.d.ts`);
91
+ const dictionaries = import_fast_glob.default.sync(`${typesDir}/**/*.d.ts`);
82
92
  const tsContent = generateTypeIndexContent(dictionaries);
83
93
  (0, import_fs.writeFileSync)((0, import_path.join)(moduleAugmentationDir, "intlayer.d.ts"), tsContent);
84
94
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/transpiler/dictionary_to_type/createModuleAugmentation.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'fs';\nimport { basename, join, relative } from 'path';\nimport { Locales, getConfiguration } from '@intlayer/config';\nimport { sync } from 'glob';\nimport { getFileHash, transformToCamelCase } from '../../utils';\n\nconst { content, internationalization } = getConfiguration();\nconst { typesDir, moduleAugmentationDir } = content;\nconst { locales, strictMode } = internationalization;\n\nexport const getTypeName = (id: string): string =>\n transformToCamelCase(`${id}Content`);\n\n/**\n * This function generates the content of the module augmentation file\n */\nconst generateTypeIndexContent = (typeFiles: string[]): string => {\n let content = \"/* eslint-disable */\\nimport { Locales } from 'intlayer';\\n\";\n\n const dictionariesRef = typeFiles.map((dictionaryPath) => ({\n relativePath: relative(moduleAugmentationDir, dictionaryPath),\n id: basename(dictionaryPath, '.d.ts'), // Get the base name as the dictionary id\n hash: `_${getFileHash(dictionaryPath)}`, // Get the hash of the dictionary to avoid conflicts\n }));\n\n // Import all dictionaries\n dictionariesRef.forEach((dictionary) => {\n const typeName = getTypeName(dictionary.id);\n content += `import type { ${typeName} as ${dictionary.hash} } from '${dictionary.relativePath}';\\n`;\n });\n\n content += '\\n';\n\n // Format Dictionary Map\n const formattedDictionaryMap: string = dictionariesRef\n .map((dictionary) => ` \"${dictionary.id}\": ${dictionary.hash};`)\n .join('\\n');\n\n const formatLocales = locales\n .map((locale) => {\n for (const key in Locales) {\n if (Locales[key as keyof typeof Locales] === locale) {\n return `Locales.${key}`;\n }\n }\n })\n .join(' | ');\n\n const strictModeRecord =\n strictMode === 'strict'\n ? `interface IConfigLocales<Content> extends Record<ExtractedLocales, Content> {}`\n : strictMode === 'required_only'\n ? `interface IConfigLocales<Content> extends Record<ExtractedLocales, Content>, Partial<Record<ExcludedLocales, Content>> {}`\n : `interface IConfigLocales<Content> extends Partial<Record<Locales, Content>> {}`;\n\n /**\n * Write the module augmentation to extend the intlayer module with the dictionaries types\n * Will suggest the type resulting of the dictionaries\n *\n * declare module 'intlayer' {\n * interface IntlayerDictionaryTypesConnector = {\n * dictionaries: {\n * id: DictionaryType;\n * }\n * }\n *\n * type ConfigLocales = Locales.ENGLISH | Locales.FRENCH | Locales.SPANISH;\n * type ExtractedLocales = Extract<Locales, ConfigLocales>;\n * type ExcludedLocales = Exclude<Locales, ConfigLocales>;\n *\n * interface IConfigLocales<Content> extends Record<ExtractedLocales, Content>, Partial<Record<ExcludedLocales, Content>> {}\n *\n *\n * }\n * See https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation\n */\n content += `declare module 'intlayer' {\\n`;\n content += ` interface IntlayerDictionaryTypesConnector {\\n${formattedDictionaryMap}\\n }\\n\\n`;\n content += ` type ConfigLocales = ${formatLocales};\\n`;\n content += ` type ExtractedLocales = Extract<Locales, ConfigLocales>;\\n`;\n content += ` type ExcludedLocales = Exclude<Locales, ConfigLocales>;\\n\\n`;\n content += ` ${strictModeRecord}\\n`;\n content += `}`;\n\n return content;\n};\n\n/**\n * This function generates a index file merging all the types\n */\nexport const createModuleAugmentation = () => {\n // Create main directory if it doesn't exist\n if (!existsSync(moduleAugmentationDir)) {\n mkdirSync(moduleAugmentationDir, { recursive: true });\n }\n\n const dictionaries: string[] = sync(`${typesDir}/**/*.d.ts`);\n // Create the dictionary list file\n\n const tsContent = generateTypeIndexContent(dictionaries);\n writeFileSync(join(moduleAugmentationDir, 'intlayer.d.ts'), tsContent);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAAqD;AACrD,kB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BAAgB;AAAA;AAChC,EAAAA,YAAW;AAEX,SAAOA;AACT;AAKO,MAAM,2BAA2B,MAAM;AAE5C,MAAI,KAAC,sBAAW,qBAAqB,GAAG;AACtC,6BAAU,uBAAuB,EAAE,WAAW,KAAK,CAAC;AAAA,EACtD;AAEA,QAAM,mBAAyB,kBAAK,GAAG,QAAQ,YAAY;AAG3D,QAAM,YAAY,yBAAyB,YAAY;AACvD,mCAAc,kBAAK,uBAAuB,eAAe,GAAG,SAAS;AACvE;","names":["content"]}
1
+ {"version":3,"sources":["../../../../src/transpiler/dictionary_to_type/createModuleAugmentation.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'fs';\nimport { basename, join, relative } from 'path';\nimport { Locales, getConfiguration } from '@intlayer/config';\nimport fg from 'fast-glob';\nimport { getFileHash, transformToCamelCase } from '../../utils';\n\nconst { content, internationalization } = getConfiguration();\nconst { typesDir, moduleAugmentationDir } = content;\nconst { locales, strictMode } = internationalization;\n\nexport const getTypeName = (id: string): string =>\n transformToCamelCase(`${id}Content`);\n\n/**\n * This function generates the content of the module augmentation file\n */\nconst generateTypeIndexContent = (typeFiles: string[]): string => {\n let content = \"/* eslint-disable */\\nimport { Locales } from 'intlayer';\\n\";\n\n const dictionariesRef = typeFiles.map((dictionaryPath) => ({\n relativePath: relative(moduleAugmentationDir, dictionaryPath),\n id: basename(dictionaryPath, '.d.ts'), // Get the base name as the dictionary id\n hash: `_${getFileHash(dictionaryPath)}`, // Get the hash of the dictionary to avoid conflicts\n }));\n\n // Import all dictionaries\n dictionariesRef.forEach((dictionary) => {\n const typeName = getTypeName(dictionary.id);\n content += `import type { ${typeName} as ${dictionary.hash} } from '${dictionary.relativePath}';\\n`;\n });\n\n content += '\\n';\n\n // Format Dictionary Map\n const formattedDictionaryMap: string = dictionariesRef\n .map((dictionary) => ` \"${dictionary.id}\": ${dictionary.hash};`)\n .join('\\n');\n\n const formatLocales = locales\n .map((locale) => {\n for (const key in Locales) {\n if (Locales[key as keyof typeof Locales] === locale) {\n return `Locales.${key}`;\n }\n }\n })\n .join(' | ');\n\n const strictModeRecord =\n strictMode === 'strict'\n ? `interface IConfigLocales<Content> extends Record<ExtractedLocales, Content> {}`\n : strictMode === 'required_only'\n ? `interface IConfigLocales<Content> extends Record<ExtractedLocales, Content>, Partial<Record<ExcludedLocales, Content>> {}`\n : `interface IConfigLocales<Content> extends Partial<Record<Locales, Content>> {}`;\n\n /**\n * Write the module augmentation to extend the intlayer module with the dictionaries types\n * Will suggest the type resulting of the dictionaries\n *\n * declare module 'intlayer' {\n * interface IntlayerDictionaryTypesConnector = {\n * dictionaries: {\n * id: DictionaryType;\n * }\n * }\n *\n * type ConfigLocales = Locales.ENGLISH | Locales.FRENCH | Locales.SPANISH;\n * type ExtractedLocales = Extract<Locales, ConfigLocales>;\n * type ExcludedLocales = Exclude<Locales, ConfigLocales>;\n *\n * interface IConfigLocales<Content> extends Record<ExtractedLocales, Content>, Partial<Record<ExcludedLocales, Content>> {}\n *\n *\n * }\n * See https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation\n */\n content += `declare module 'intlayer' {\\n`;\n content += ` interface IntlayerDictionaryTypesConnector {\\n${formattedDictionaryMap}\\n }\\n\\n`;\n content += ` type ConfigLocales = ${formatLocales};\\n`;\n content += ` type ExtractedLocales = Extract<Locales, ConfigLocales>;\\n`;\n content += ` type ExcludedLocales = Exclude<Locales, ConfigLocales>;\\n\\n`;\n content += ` ${strictModeRecord}\\n`;\n content += `}`;\n\n return content;\n};\n\n/**\n * This function generates a index file merging all the types\n */\nexport const createModuleAugmentation = () => {\n // Create main directory if it doesn't exist\n if (!existsSync(moduleAugmentationDir)) {\n mkdirSync(moduleAugmentationDir, { recursive: true });\n }\n\n const dictionaries: string[] = fg.sync(`${typesDir}/**/*.d.ts`);\n // Create the dictionary list file\n\n const tsContent = generateTypeIndexContent(dictionaries);\n writeFileSync(join(moduleAugmentationDir, 'intlayer.d.ts'), tsContent);\n};\n"],"mappings":";;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