@intlayer/chokidar 3.5.3 → 3.5.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/chokidar/watcher.cjs +48 -19
- package/dist/cjs/chokidar/watcher.cjs.map +1 -1
- package/dist/cjs/fetchDistantDictionaries.cjs +2 -2
- package/dist/cjs/fetchDistantDictionaries.cjs.map +1 -1
- package/dist/cjs/getDictionariesPath.cjs +50 -0
- package/dist/cjs/getDictionariesPath.cjs.map +1 -0
- package/dist/cjs/loadDictionaries/loadDictionaries.cjs +4 -3
- package/dist/cjs/loadDictionaries/loadDictionaries.cjs.map +1 -1
- package/dist/cjs/log.cjs +6 -2
- package/dist/cjs/log.cjs.map +1 -1
- package/dist/cjs/transpiler/declaration_file_to_dictionary/intlayer_dictionary/processContentDeclaration.cjs +2 -1
- package/dist/cjs/transpiler/declaration_file_to_dictionary/intlayer_dictionary/processContentDeclaration.cjs.map +1 -1
- package/dist/cjs/transpiler/dictionary_to_main/createDictionaryList.cjs +5 -15
- package/dist/cjs/transpiler/dictionary_to_main/createDictionaryList.cjs.map +1 -1
- package/dist/esm/chokidar/watcher.mjs +49 -20
- package/dist/esm/chokidar/watcher.mjs.map +1 -1
- package/dist/esm/fetchDistantDictionaries.mjs +3 -3
- package/dist/esm/fetchDistantDictionaries.mjs.map +1 -1
- package/dist/esm/getDictionariesPath.mjs +16 -0
- package/dist/esm/getDictionariesPath.mjs.map +1 -0
- package/dist/esm/loadDictionaries/loadDictionaries.mjs +5 -4
- package/dist/esm/loadDictionaries/loadDictionaries.mjs.map +1 -1
- package/dist/esm/log.mjs +6 -2
- package/dist/esm/log.mjs.map +1 -1
- package/dist/esm/transpiler/declaration_file_to_dictionary/intlayer_dictionary/processContentDeclaration.mjs +2 -1
- package/dist/esm/transpiler/declaration_file_to_dictionary/intlayer_dictionary/processContentDeclaration.mjs.map +1 -1
- package/dist/esm/transpiler/dictionary_to_main/createDictionaryList.mjs +5 -5
- package/dist/esm/transpiler/dictionary_to_main/createDictionaryList.mjs.map +1 -1
- package/dist/types/chokidar/watcher.d.ts.map +1 -1
- package/dist/types/getDictionariesPath.d.ts +5 -0
- package/dist/types/getDictionariesPath.d.ts.map +1 -0
- package/dist/types/loadDictionaries/loadDictionaries.d.ts.map +1 -1
- package/dist/types/log.d.ts +1 -0
- package/dist/types/log.d.ts.map +1 -1
- package/dist/types/transpiler/declaration_file_to_dictionary/intlayer_dictionary/processContentDeclaration.d.ts.map +1 -1
- package/package.json +12 -11
|
@@ -36,12 +36,12 @@ var import_config = require("@intlayer/config");
|
|
|
36
36
|
var import_chokidar = require("chokidar");
|
|
37
37
|
var import_fast_glob = __toESM(require("fast-glob"));
|
|
38
38
|
var import_cleanOutputDir = require('../cleanOutputDir.cjs');
|
|
39
|
+
var import_getDictionariesPath = require('../getDictionariesPath.cjs');
|
|
39
40
|
var import_loadDictionaries = require('../loadDictionaries/loadDictionaries.cjs');
|
|
40
41
|
var import_loadLocalDictionaries = require('../loadDictionaries/loadLocalDictionaries.cjs');
|
|
41
42
|
var import_declaration_file_to_dictionary = require('../transpiler/declaration_file_to_dictionary/index.cjs');
|
|
42
43
|
var import_createDictionaryList = require('../transpiler/dictionary_to_main/createDictionaryList.cjs');
|
|
43
44
|
var import_dictionary_to_type = require('../transpiler/dictionary_to_type/index.cjs');
|
|
44
|
-
const LOG_PREFIX = "[intlayer] ";
|
|
45
45
|
const watch = (options) => {
|
|
46
46
|
const { content } = (0, import_config.getConfiguration)({
|
|
47
47
|
verbose: true
|
|
@@ -56,33 +56,62 @@ const watch = (options) => {
|
|
|
56
56
|
...options
|
|
57
57
|
}).on("ready", async () => {
|
|
58
58
|
(0, import_cleanOutputDir.cleanOutputDir)();
|
|
59
|
+
(0, import_config.appLogger)("Output directory cleaned", {
|
|
60
|
+
isVerbose: true
|
|
61
|
+
});
|
|
59
62
|
const dictionaries = await (0, import_loadDictionaries.loadDictionaries)(files);
|
|
60
63
|
const dictionariesPaths = await (0, import_declaration_file_to_dictionary.buildDictionary)(dictionaries);
|
|
61
64
|
await (0, import_dictionary_to_type.createTypes)(dictionariesPaths);
|
|
62
|
-
console.info(
|
|
63
|
-
`${LOG_PREFIX}${dictionariesPaths.length} dictionaries built`
|
|
64
|
-
);
|
|
65
|
-
(0, import_dictionary_to_type.createModuleAugmentation)();
|
|
66
65
|
(0, import_createDictionaryList.createDictionaryList)();
|
|
66
|
+
(0, import_config.appLogger)("Dictionaries built");
|
|
67
|
+
(0, import_dictionary_to_type.createModuleAugmentation)();
|
|
68
|
+
(0, import_config.appLogger)("Module augmentation built", {
|
|
69
|
+
isVerbose: true
|
|
70
|
+
});
|
|
67
71
|
}).on("add", async (filePath) => {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
);
|
|
72
|
+
(0, import_config.appLogger)(`Additional file detected: ${(0, import_path.relative)(baseDir, filePath)}`, {
|
|
73
|
+
isVerbose: true
|
|
74
|
+
});
|
|
72
75
|
const localeDictionaries = await (0, import_loadLocalDictionaries.loadLocalDictionaries)(filePath);
|
|
73
|
-
const
|
|
74
|
-
await (0, import_dictionary_to_type.createTypes)(
|
|
75
|
-
(0, import_dictionary_to_type.createModuleAugmentation)();
|
|
76
|
+
const dictionariesPaths = await (0, import_declaration_file_to_dictionary.buildDictionary)(localeDictionaries);
|
|
77
|
+
await (0, import_dictionary_to_type.createTypes)(dictionariesPaths);
|
|
76
78
|
(0, import_createDictionaryList.createDictionaryList)();
|
|
79
|
+
(0, import_config.appLogger)("Dictionaries built", {
|
|
80
|
+
isVerbose: true
|
|
81
|
+
});
|
|
82
|
+
(0, import_dictionary_to_type.createModuleAugmentation)();
|
|
83
|
+
(0, import_config.appLogger)("Module augmentation built", {
|
|
84
|
+
isVerbose: true
|
|
85
|
+
});
|
|
77
86
|
}).on("change", async (filePath) => {
|
|
78
|
-
|
|
87
|
+
(0, import_config.appLogger)(`Change detected: ${(0, import_path.relative)(baseDir, filePath)}`, {
|
|
88
|
+
isVerbose: true
|
|
89
|
+
});
|
|
79
90
|
const localeDictionaries = await (0, import_loadLocalDictionaries.loadLocalDictionaries)(filePath);
|
|
80
|
-
const
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
91
|
+
const updatedDictionariesPaths = await (0, import_declaration_file_to_dictionary.buildDictionary)(localeDictionaries);
|
|
92
|
+
const allDictionariesPaths = (0, import_getDictionariesPath.getDictionariesPath)();
|
|
93
|
+
await (0, import_dictionary_to_type.createTypes)(updatedDictionariesPaths);
|
|
94
|
+
(0, import_config.appLogger)("TypeScript types built", {
|
|
95
|
+
isVerbose: true
|
|
96
|
+
});
|
|
97
|
+
if (updatedDictionariesPaths.some(
|
|
98
|
+
(updatedDictionaryPath) => allDictionariesPaths.includes(updatedDictionaryPath)
|
|
99
|
+
)) {
|
|
100
|
+
(0, import_createDictionaryList.createDictionaryList)();
|
|
101
|
+
(0, import_config.appLogger)("Dictionary list built", {
|
|
102
|
+
isVerbose: true
|
|
103
|
+
});
|
|
104
|
+
(0, import_dictionary_to_type.createModuleAugmentation)();
|
|
105
|
+
(0, import_config.appLogger)("Module augmentation built", {
|
|
106
|
+
isVerbose: true
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
}).on(
|
|
110
|
+
"error",
|
|
111
|
+
(error) => (0, import_config.appLogger)("Watcher error: " + error, {
|
|
112
|
+
level: "error"
|
|
113
|
+
})
|
|
114
|
+
);
|
|
86
115
|
};
|
|
87
116
|
// Annotate the CommonJS export names for ESM import in node:
|
|
88
117
|
0 && (module.exports = {
|
|
@@ -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 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\
|
|
1
|
+
{"version":3,"sources":["../../../src/chokidar/watcher.ts"],"sourcesContent":["import { relative } from 'path';\nimport { appLogger, 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 { getDictionariesPath } from '../getDictionariesPath';\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\n// Initialize chokidar watcher (non-persistent)\nexport const watch = (options?: ChokidarOptions) => {\n const { content } = getConfiguration({\n verbose: true,\n });\n\n const { watchedFilesPatternWithPath, baseDir, watch: isWatchMode } = content;\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: isWatchMode, // Make the watcher persistent\n ignoreInitial: true, // Process existing files\n ...options,\n })\n .on('ready', async () => {\n cleanOutputDir();\n\n appLogger('Output directory cleaned', {\n isVerbose: true,\n });\n\n const dictionaries = await loadDictionaries(files);\n\n // Build locale dictionaries\n const dictionariesPaths = await buildDictionary(dictionaries);\n\n await createTypes(dictionariesPaths);\n\n createDictionaryList();\n\n appLogger('Dictionaries built');\n\n createModuleAugmentation();\n\n appLogger('Module augmentation built', {\n isVerbose: true,\n });\n })\n .on('add', async (filePath) => {\n // Process the file with the functionToRun\n appLogger(`Additional file detected: ${relative(baseDir, filePath)}`, {\n isVerbose: true,\n });\n\n const localeDictionaries = await loadLocalDictionaries(filePath);\n\n const dictionariesPaths = await buildDictionary(localeDictionaries);\n\n await createTypes(dictionariesPaths);\n\n createDictionaryList();\n\n appLogger('Dictionaries built', {\n isVerbose: true,\n });\n\n createModuleAugmentation();\n\n appLogger('Module augmentation built', {\n isVerbose: true,\n });\n })\n .on('change', async (filePath) => {\n // Process the file with the functionToRun\n appLogger(`Change detected: ${relative(baseDir, filePath)}`, {\n isVerbose: true,\n });\n\n const localeDictionaries = await loadLocalDictionaries(filePath);\n const updatedDictionariesPaths =\n await buildDictionary(localeDictionaries);\n const allDictionariesPaths: string[] = getDictionariesPath();\n\n await createTypes(updatedDictionariesPaths);\n appLogger('TypeScript types built', {\n isVerbose: true,\n });\n\n if (\n updatedDictionariesPaths.some((updatedDictionaryPath) =>\n allDictionariesPaths.includes(updatedDictionaryPath)\n )\n ) {\n createDictionaryList();\n\n appLogger('Dictionary list built', {\n isVerbose: true,\n });\n\n createModuleAugmentation();\n\n appLogger('Module augmentation built', {\n isVerbose: true,\n });\n }\n })\n .on('error', (error) =>\n appLogger('Watcher error: ' + error, {\n level: 'error',\n })\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAyB;AACzB,oBAA4C;AAE5C,sBAA6D;AAC7D,uBAAe;AACf,4BAA+B;AAC/B,iCAAoC;AACpC,8BAAiC;AACjC,mCAAsC;AACtC,4CAAgC;AAChC,kCAAqC;AACrC,gCAGO;AAGA,MAAM,QAAQ,CAAC,YAA8B;AAClD,QAAM,EAAE,QAAQ,QAAI,gCAAiB;AAAA,IACnC,SAAS;AAAA,EACX,CAAC;AAED,QAAM,EAAE,6BA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CAAC;AAED,QACE,yBAAyB;AAAA,MAAK,CAAC,0BAC7B,qBAAqB,SAAS,qBAAqB;AAAA,IACrD,GACA;AACA,4DAAqB;AAErB,mCAAU,yBAAyB;AAAA,QACjC,WAAW;AAAA,MACb,CAAC;AAED,8DAAyB;AAEzB,mCAAU,6BAA6B;AAAA,QACrC,WAAW;AAAA,MACb,CAAC;AAAA,IACH;AAAA,EACF,CAAC,EACA;AAAA,IAAG;AAAA,IAAS,CAAC,cACZ,yBAAU,oBAAoB,OAAO;AAAA,MACnC,OAAO;AAAA,IACT,CAAC;AAAA,EACH;AACJ;","names":["fg","chokidarWatch"]}
|
|
@@ -96,7 +96,7 @@ const fetchDistantDictionaries = async (options) => {
|
|
|
96
96
|
for (const statusObj of statuses) {
|
|
97
97
|
const currentState = statusObj.state.find((s) => s.type === "distant");
|
|
98
98
|
if (currentState && currentState.errorMessage) {
|
|
99
|
-
|
|
99
|
+
(0, import_config.appLogger)(currentState.errorMessage, { level: "error" });
|
|
100
100
|
}
|
|
101
101
|
}
|
|
102
102
|
const filteredResult = result.filter(
|
|
@@ -104,7 +104,7 @@ const fetchDistantDictionaries = async (options) => {
|
|
|
104
104
|
);
|
|
105
105
|
return filteredResult;
|
|
106
106
|
} catch (error) {
|
|
107
|
-
|
|
107
|
+
(0, import_config.appLogger)(error, { level: "error" });
|
|
108
108
|
return [];
|
|
109
109
|
}
|
|
110
110
|
};
|
|
@@ -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 { 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); //
|
|
1
|
+
{"version":3,"sources":["../../src/fetchDistantDictionaries.ts"],"sourcesContent":["// @ts-ignore @intlayer/backend not build yet\nimport { type DictionaryAPI } from '@intlayer/backend';\nimport { appLogger, 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); // Limit the number of concurrent requests\n\n const processDictionary = async (\n dictionaryKey: string\n ): Promise<DictionaryAPI | undefined> => {\n logger.updateStatus([\n {\n dictionaryKey,\n type: 'distant',\n status: { status: 'fetching' },\n },\n ]);\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([\n { dictionaryKey, type: 'distant', status: { status: 'imported' } },\n ]);\n\n return distantDictionary;\n } catch (error) {\n logger.updateStatus([\n {\n dictionaryKey,\n type: 'distant',\n status: {\n status: 'error',\n error: error as Error,\n errorMessage: `${options?.logPrefix ?? ''}Error fetching dictionary ${dictionaryKey}: ${error}`,\n },\n },\n ]);\n return undefined;\n }\n };\n\n const fetchPromises = distantDictionariesKeys.map((dictionaryKey) =>\n limit(async () => await 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 appLogger(currentState.errorMessage, { level: 'error' });\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 appLogger(error, { level: 'error' });\n return [];\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,oBAA4C;AAE5C,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,YA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a,UAAU;AAChC,YAAM,eAAe,UAAU,MAAM,KAAK,CAAC,MAAM,EAAE,SAAS,SAAS;AACrE,UAAI,gBAAgB,aAAa,cAAc;AAC7C,qCAAU,aAAa,cAAc,EAAE,OAAO,QAAQ,CAAC;AAAA,MACzD;AAAA,IACF;AAGA,UAAM,iBAAiB,OAAO;AAAA,MAC5B,CAAC,SAAgC,SAAS;AAAA,IAC5C;AAEA,WAAO;AAAA,EACT,SAAS,OAAO;AACd,iCAAU,OAAO,EAAE,OAAO,QAAQ,CAAC;AACnC,WAAO,CAAC;AAAA,EACV;AACF;","names":["pLimit"]}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
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
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
var getDictionariesPath_exports = {};
|
|
30
|
+
__export(getDictionariesPath_exports, {
|
|
31
|
+
getDictionariesPath: () => getDictionariesPath
|
|
32
|
+
});
|
|
33
|
+
module.exports = __toCommonJS(getDictionariesPath_exports);
|
|
34
|
+
var import_fs = require("fs");
|
|
35
|
+
var import_config = require("@intlayer/config");
|
|
36
|
+
var import_fast_glob = __toESM(require("fast-glob"));
|
|
37
|
+
const { content } = (0, import_config.getConfiguration)();
|
|
38
|
+
const { dictionariesDir, mainDir } = content;
|
|
39
|
+
const getDictionariesPath = () => {
|
|
40
|
+
if (!(0, import_fs.existsSync)(mainDir)) {
|
|
41
|
+
(0, import_fs.mkdirSync)(mainDir, { recursive: true });
|
|
42
|
+
}
|
|
43
|
+
const dictionariesPath = import_fast_glob.default.sync(`${dictionariesDir}/**/*.json`);
|
|
44
|
+
return dictionariesPath;
|
|
45
|
+
};
|
|
46
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
47
|
+
0 && (module.exports = {
|
|
48
|
+
getDictionariesPath
|
|
49
|
+
});
|
|
50
|
+
//# sourceMappingURL=getDictionariesPath.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/getDictionariesPath.ts"],"sourcesContent":["import { existsSync, mkdirSync } from 'fs';\nimport { getConfiguration } from '@intlayer/config';\nimport fg from 'fast-glob';\n\nconst { content } = getConfiguration();\nconst { dictionariesDir, mainDir } = content;\n\n/**\n * This function generates a list of dictionaries in the main directory\n */\nexport const getDictionariesPath = () => {\n // Create main directory if it doesn't exist\n if (!existsSync(mainDir)) {\n mkdirSync(mainDir, { recursive: true });\n }\n\n const dictionariesPath: string[] = fg.sync(`${dictionariesDir}/**/*.json`);\n\n return dictionariesPath;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAAsC;AACtC,oBAAiC;AACjC,uBAAe;AAEf,MAAM,EAAE,QAAQ,QAAI,gCAAiB;AACrC,MAAM,EAAE,iBAAiB,QAAQ,IAAI;AAK9B,MAAM,sBAAsB,MAAM;AAEvC,MAAI,KAAC,sBAAW,OAAO,GAAG;AACxB,6BAAU,SAAS,EAAE,WAAW,KAAK,CAAC;AAAA,EACxC;AAEA,QAAM,mBAA6B,iBAAAA,QAAG,KAAK,GAAG,eAAe,YAAY;AAEzE,SAAO;AACT;","names":["fg"]}
|
|
@@ -39,11 +39,10 @@ var import_mergeDictionaries = require('../mergeDictionaries.cjs');
|
|
|
39
39
|
var import_utils = require('../utils.cjs');
|
|
40
40
|
var import_loadContentDeclaration = require('./loadContentDeclaration.cjs');
|
|
41
41
|
var import_loadDistantDictionaries = require('./loadDistantDictionaries.cjs');
|
|
42
|
-
const LOG_PREFIX = "[intlayer] ";
|
|
43
42
|
const loadDictionaries = async (contentDeclarationsPaths) => {
|
|
44
43
|
try {
|
|
45
44
|
const { editor } = (0, import_config.getConfiguration)();
|
|
46
|
-
|
|
45
|
+
(0, import_config.appLogger)("Dictionaries:", { isVerbose: true });
|
|
47
46
|
const files = Array.isArray(contentDeclarationsPaths) ? contentDeclarationsPaths : [contentDeclarationsPaths];
|
|
48
47
|
const localDictionaries = await (0, import_loadContentDeclaration.loadContentDeclarations)(files);
|
|
49
48
|
const localDictionaryKeys = localDictionaries.map((dict) => dict.key);
|
|
@@ -76,7 +75,9 @@ const loadDictionaries = async (contentDeclarationsPaths) => {
|
|
|
76
75
|
});
|
|
77
76
|
}
|
|
78
77
|
} catch (_error) {
|
|
79
|
-
|
|
78
|
+
(0, import_config.appLogger)("Error during fetching distant dictionaries", {
|
|
79
|
+
level: "error"
|
|
80
|
+
});
|
|
80
81
|
}
|
|
81
82
|
}
|
|
82
83
|
import_log.logger.stop();
|
|
@@ -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 { sortAlphabetically } from '../utils';\nimport { loadContentDeclarations } from './loadContentDeclaration';\nimport { loadDistantDictionaries } from './loadDistantDictionaries';\n\
|
|
1
|
+
{"version":3,"sources":["../../../src/loadDictionaries/loadDictionaries.ts"],"sourcesContent":["// @ts-ignore @intlayer/backend not build yet\nimport { type DictionaryAPI } from '@intlayer/backend';\nimport { appLogger, 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\nexport const loadDictionaries = async (\n contentDeclarationsPaths: string[] | string\n): Promise<Dictionary[]> => {\n try {\n const { editor } = getConfiguration();\n\n appLogger('Dictionaries:', { isVerbose: true });\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 logger.updateStatus(\n localDictionaries.map((dict) => ({\n dictionaryKey: dict.key,\n type: 'local',\n status: { status: 'built' },\n }))\n );\n\n let distantDictionaries: DictionaryAPI[] = [];\n let distantDictionaryKeys: string[] = [];\n let mergedDictionaries = localDictionaries;\n\n if (editor.clientId && editor.clientSecret) {\n try {\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 } catch (_error) {\n appLogger('Error during fetching distant dictionaries', {\n level: 'error',\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,oBAA4C;AAE5C,uBAAkB;AAClB,wCAA2C;AAC3C,iBAAuB;AACvB,+BAA2B;AAC3B,mBAAmC;AACnC,oCAAwC;AACxC,qCAAwC;AAEjC,MAAM,mBAAmB,OAC9B,6BAC0B;AAC1B,MAAI;AACF,UAAM,EAAE,OAAO,QAAI,gCAAiB;AAEpC,iCAAU,iBAAiB,EAAE,WAAW,KAAK,CAAC;AAE9C,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,sBAAO;AAAA,MACL,kBAAkB,IAAI,CAAC,UAAU;AAAA,QAC/B,eAAe,KAAK;AAAA,QACpB,MAAM;AAAA,QACN,QAAQ,EAAE,QAAQ,QAAQ;AAAA,MAC5B,EAAE;AAAA,IACJ;AAEA,QAAI,sBAAuC,CAAC;AAC5C,QAAI,wBAAkC,CAAC;AACvC,QAAI,qBAAqB;AAEzB,QAAI,OAAO,YAAY,OAAO,cAAc;AAC1C,UAAI;AAEF,gCAAwB,UAAM,8DAA2B;AAEzD,cAAM,+BACJ,sBAAsB,KAAK,+BAAkB;AAE/C,0BAAO,kBAAkB,WAAW,4BAA4B;AAGhE,8BAAsB,UAAM,wDAAwB;AAAA,UAClD,gBAAgB;AAAA,QAClB,CAAC;AACD,YAAI,OAAO,+BAA+B,iBAAiB;AAEzD,mCAAqB,iBAAAA,SAAM,mBAAmB,qBAAqB;AAAA,YACjE,gBAAY,qCAAW,KAAK;AAAA,UAC9B,CAAC;AAAA,QACH,OAAO;AAEL,mCAAqB,iBAAAA,SAAM,qBAAqB,mBAAmB;AAAA,YACjE,gBAAY,qCAAW,KAAK;AAAA,UAC9B,CAAC;AAAA,QACH;AAAA,MACF,SAAS,QAAQ;AACf,qCAAU,8CAA8C;AAAA,UACtD,OAAO;AAAA,QACT,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
|
@@ -33,6 +33,7 @@ __export(log_exports, {
|
|
|
33
33
|
module.exports = __toCommonJS(log_exports);
|
|
34
34
|
var import_readline = __toESM(require("readline"));
|
|
35
35
|
var import_utils = require('./utils.cjs');
|
|
36
|
+
var import_config = require("@intlayer/config");
|
|
36
37
|
const LINE_DETECTOR = "\u200B\u200B\u200B";
|
|
37
38
|
const SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
|
|
38
39
|
const RESET = "\x1B[0m";
|
|
@@ -50,9 +51,11 @@ class Logger {
|
|
|
50
51
|
originalStdoutWrite = null;
|
|
51
52
|
extraLines = 0;
|
|
52
53
|
isUpdating = false;
|
|
54
|
+
config;
|
|
53
55
|
// Singleton instance
|
|
54
56
|
static instance;
|
|
55
57
|
constructor() {
|
|
58
|
+
this.config = (0, import_config.getConfiguration)();
|
|
56
59
|
}
|
|
57
60
|
static getInstance() {
|
|
58
61
|
if (!Logger.instance) {
|
|
@@ -146,6 +149,7 @@ class Logger {
|
|
|
146
149
|
}
|
|
147
150
|
// Method to update the terminal output
|
|
148
151
|
updateOutput(content) {
|
|
152
|
+
if (this.config.log.mode !== "verbose") return;
|
|
149
153
|
if (!this.originalStdoutWrite) {
|
|
150
154
|
this.originalStdoutWrite = process.stdout.write.bind(process.stdout);
|
|
151
155
|
this.extraLines = 0;
|
|
@@ -256,7 +260,7 @@ class Logger {
|
|
|
256
260
|
const statusBlock = `${GREY_DARK}[${state.type}: ${colorStart}${icon} ${state.status}${GREY_DARK}]${colorEnd}`;
|
|
257
261
|
return `${colorStart}${statusBlock}${colorEnd}`;
|
|
258
262
|
});
|
|
259
|
-
return
|
|
263
|
+
return `${this.config.log.prefix}- ${paddedKey} ${states.join(" ")}`;
|
|
260
264
|
}
|
|
261
265
|
// Replace logUpdate calls with your custom methods
|
|
262
266
|
updateAllStatusLines() {
|
|
@@ -273,7 +277,7 @@ class Logger {
|
|
|
273
277
|
let content;
|
|
274
278
|
if (lines.length > maxVisibleLines) {
|
|
275
279
|
const visibleLines = lines.slice(0, maxVisibleLines - 5);
|
|
276
|
-
const summary =
|
|
280
|
+
const summary = `${this.config.log.prefix}... and ${lines.length - visibleLines.length} more`;
|
|
277
281
|
content = LINE_DETECTOR + visibleLines.join("\n") + "\n" + summary;
|
|
278
282
|
} else {
|
|
279
283
|
content = lines.join("\n");
|
package/dist/cjs/log.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/log.ts"],"sourcesContent":["import readline from 'readline';\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\nconst LINE_DETECTOR = '\\u200B\\u200B\\u200B'; // Three zero-width spaces\nconst SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\n\n// ANSI color codes\nconst RESET = '\\x1b[0m';\nconst GREEN = '\\x1b[32m';\nconst RED = '\\x1b[31m';\nconst BLUE = '\\x1b[34m';\nconst GREY = '\\x1b[90m';\nconst GREY_DARK = '\\x1b[90m';\n\nclass Logger {\n private dictionariesStatuses: DictionariesStatus[] = [];\n private spinnerTimer: NodeJS.Timeout | null = null;\n private maxDictionaryKeyLength: number = 0;\n private previousLineCount: number = 0;\n private lineDifCounter: number = 0;\n private originalStdoutWrite:\n | ((\n chunk: string | Uint8Array, // `chunk` can be either a string or a Uint8Array\n encoding?: BufferEncoding, // `encoding` is optional and should be a BufferEncoding\n callback?: (err?: Error | null) => void // `callback` is optional and a function\n ) => boolean)\n | null = null;\n private extraLines: number = 0;\n private isUpdating: boolean = false;\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 // Method to update the terminal output\n private updateOutput(content: string) {\n // Monkey-patch process.stdout.write to keep track of extra lines\n if (!this.originalStdoutWrite) {\n this.originalStdoutWrite = process.stdout.write.bind(process.stdout);\n this.extraLines = 0;\n\n const write = (\n chunk: string | Uint8Array, // `chunk` can be either a string or a Uint8Array\n encoding?: BufferEncoding, // `encoding` is optional and should be a BufferEncoding\n callback?: (err?: Error | null) => void // `callback` is optional and a function\n ) => {\n const str = typeof chunk === 'string' ? chunk : chunk.toString();\n const newLines = (str.match(/\\n/g) ?? []).length;\n\n // If the write is not initiated by Logger's updateOutput method\n if (!this.isUpdating) {\n this.extraLines += newLines;\n }\n\n return this.originalStdoutWrite!(chunk, encoding, callback);\n };\n\n process.stdout.write = write as typeof process.stdout.write;\n }\n\n // Set a flag to indicate that updateOutput is running\n this.isUpdating = true;\n\n // Adjust lineDifCounter if LINE_DETECTOR is not the first line\n const contentLines = content.split('\\n');\n const indexOfLineDetector = contentLines.indexOf(LINE_DETECTOR.trim());\n\n if (indexOfLineDetector > 0) {\n // LINE_DETECTOR is not at the first line\n this.lineDifCounter = indexOfLineDetector;\n } else {\n this.lineDifCounter = 0;\n }\n\n // Calculate total lines to move up\n const totalLinesToMoveUp =\n this.previousLineCount + this.lineDifCounter + this.extraLines;\n\n // Move cursor up by totalLinesToMoveUp\n readline.moveCursor(process.stdout, 0, -totalLinesToMoveUp);\n\n // Clear all lines downwards\n readline.clearScreenDown(process.stdout);\n\n // Write the updated content\n contentLines.forEach((line) => {\n process.stdout.write(`${line}\\x1b[K\\n`);\n });\n\n // Update previousLineCount\n this.previousLineCount = contentLines.length;\n\n // Reset extraLines counter and updating flag\n this.extraLines = 0;\n this.isUpdating = false;\n }\n\n public stop() {\n this.stopSpinner();\n }\n\n public updateStatus(\n dictionaries: {\n dictionaryKey: string;\n type: 'local' | 'distant';\n status: Partial<State>;\n }[]\n ) {\n for (const { dictionaryKey, type, status } of dictionaries) {\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 // 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 = SPINNER_FRAMES[state.spinnerFrameIndex! % SPINNER_FRAMES.length];\n colorStart = BLUE;\n colorEnd = RESET;\n } else if (state.status === 'error') {\n colorStart = RED;\n colorEnd = RESET;\n } else if (state.status === 'imported' || state.status === 'built') {\n colorStart = GREEN;\n colorEnd = RESET;\n } else {\n colorStart = GREY;\n colorEnd = RESET;\n }\n\n // Format the status block\n const statusBlock = `${GREY_DARK}[${state.type}: ${colorStart}${icon} ${state.status}${GREY_DARK}]${colorEnd}`;\n\n return `${colorStart}${statusBlock}${colorEnd}`;\n });\n\n return `- ${paddedKey} ${states.join(' ')}`;\n }\n\n // Replace logUpdate calls with your custom methods\n private updateAllStatusLines() {\n const terminalHeight = process.stdout.rows;\n const maxVisibleLines = terminalHeight - 1;\n\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) % SPINNER_FRAMES.length;\n }\n });\n return this.getStatusLine(statusObj);\n });\n\n let content;\n\n if (lines.length > maxVisibleLines) {\n const visibleLines = lines.slice(0, maxVisibleLines - 5);\n const summary = `... and ${lines.length - visibleLines.length} more`;\n content = LINE_DETECTOR + visibleLines.join('\\n') + '\\n' + summary;\n } else {\n content = lines.join('\\n');\n }\n\n this.updateOutput(content);\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,sBAAqB;AACrB,mBAAmC;AAgBnC,MAAM,gBAAgB;AACtB,MAAM,iBAAiB,CAAC,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,QAAG;AAGxE,MAAM,QAAQ;AACd,MAAM,QAAQ;AACd,MAAM,MAAM;AACZ,MAAM,OAAO;AACb,MAAM,OAAO;AACb,MAAM,YAAY;AAElB,MAAM,OAAO;AAAA,EACH,uBAA6C,CAAC;AAAA,EAC9C,eAAsC;AAAA,EACtC,yBAAiC;AAAA,EACjC,oBAA4B;AAAA,EAC5B,iBAAyB;AAAA,EACzB,sBAMG;AAAA,EACH,aAAqB;AAAA,EACrB,aAAsB;AAAA;AAAA,EAG9B,OAAe;AAAA,EAEP,cAAc;AAAA,EAAC;AAAA,EAEvB,OAAc,cAAsB;AAClC,QAAI,CAAC,OAAO,UAAU;AACpB,aAAO,WAAW,IAAI,OAAO;AAAA,IAC/B;AACA,WAA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AAC,UAAU;AACjC,YAAI,MAAM,WAAW,YAAY;AAE/B,gBAAM,qBACH,MAAM,oBAAqB,KAAK,eAAe;AAAA,QACpD;AAAA,MACF,CAAC;AACD,aAAO,KAAK,cAAc,SAAS;AAAA,IACrC,CAAC;AAED,QAAI;AAEJ,QAAI,MAAM,SAAS,iBAAiB;AAClC,YAAM,eAAe,MAAM,MAAM,GAAG,kBAAkB,CAAC;AACvD,YAAM,UAAU,WAAW,MAAM,SAAS,aAAa,MAAM;AAC7D,gBAAU,gBAAgB,aAAa,KAAK,IAAI,IAAI,OAAO;AAAA,IAC7D,OAAO;AACL,gBAAU,MAAM,KAAK,IAAI;AAAA,IAC3B;AAEA,SAAK,aAAa,OAAO;AAAA,EAC3B;AAAA,EAEO,cAAc;AACnB,WAAO,KAAK;AAAA,EACd;AACF;AAEO,MAAM,SAAS,OAAO,YAAY;","names":["readline"]}
|
|
1
|
+
{"version":3,"sources":["../../src/log.ts"],"sourcesContent":["import readline from 'readline';\nimport { sortAlphabetically } from './utils';\nimport { getConfiguration, IntlayerConfig } from '@intlayer/config';\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\nconst LINE_DETECTOR = '\\u200B\\u200B\\u200B'; // Three zero-width spaces\nconst SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\n\n// ANSI color codes\nconst RESET = '\\x1b[0m';\nconst GREEN = '\\x1b[32m';\nconst RED = '\\x1b[31m';\nconst BLUE = '\\x1b[34m';\nconst GREY = '\\x1b[90m';\nconst GREY_DARK = '\\x1b[90m';\n\nclass Logger {\n private dictionariesStatuses: DictionariesStatus[] = [];\n private spinnerTimer: NodeJS.Timeout | null = null;\n private maxDictionaryKeyLength: number = 0;\n private previousLineCount: number = 0;\n private lineDifCounter: number = 0;\n private originalStdoutWrite:\n | ((\n chunk: string | Uint8Array, // `chunk` can be either a string or a Uint8Array\n encoding?: BufferEncoding, // `encoding` is optional and should be a BufferEncoding\n callback?: (err?: Error | null) => void // `callback` is optional and a function\n ) => boolean)\n | null = null;\n private extraLines: number = 0;\n private isUpdating: boolean = false;\n private config: IntlayerConfig;\n\n // Singleton instance\n private static instance: Logger;\n\n private constructor() {\n this.config = getConfiguration();\n }\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 // Method to update the terminal output\n private updateOutput(content: string) {\n if (this.config.log.mode !== 'verbose') return;\n\n // Monkey-patch process.stdout.write to keep track of extra lines\n if (!this.originalStdoutWrite) {\n this.originalStdoutWrite = process.stdout.write.bind(process.stdout);\n this.extraLines = 0;\n\n const write = (\n chunk: string | Uint8Array, // `chunk` can be either a string or a Uint8Array\n encoding?: BufferEncoding, // `encoding` is optional and should be a BufferEncoding\n callback?: (err?: Error | null) => void // `callback` is optional and a function\n ) => {\n const str = typeof chunk === 'string' ? chunk : chunk.toString();\n const newLines = (str.match(/\\n/g) ?? []).length;\n\n // If the write is not initiated by Logger's updateOutput method\n if (!this.isUpdating) {\n this.extraLines += newLines;\n }\n\n return this.originalStdoutWrite!(chunk, encoding, callback);\n };\n\n process.stdout.write = write as typeof process.stdout.write;\n }\n\n // Set a flag to indicate that updateOutput is running\n this.isUpdating = true;\n\n // Adjust lineDifCounter if LINE_DETECTOR is not the first line\n const contentLines = content.split('\\n');\n const indexOfLineDetector = contentLines.indexOf(LINE_DETECTOR.trim());\n\n if (indexOfLineDetector > 0) {\n // LINE_DETECTOR is not at the first line\n this.lineDifCounter = indexOfLineDetector;\n } else {\n this.lineDifCounter = 0;\n }\n\n // Calculate total lines to move up\n const totalLinesToMoveUp =\n this.previousLineCount + this.lineDifCounter + this.extraLines;\n\n // Move cursor up by totalLinesToMoveUp\n readline.moveCursor(process.stdout, 0, -totalLinesToMoveUp);\n\n // Clear all lines downwards\n readline.clearScreenDown(process.stdout);\n\n // Write the updated content\n contentLines.forEach((line) => {\n process.stdout.write(`${line}\\x1b[K\\n`);\n });\n\n // Update previousLineCount\n this.previousLineCount = contentLines.length;\n\n // Reset extraLines counter and updating flag\n this.extraLines = 0;\n this.isUpdating = false;\n }\n\n public stop() {\n this.stopSpinner();\n }\n\n public updateStatus(\n dictionaries: {\n dictionaryKey: string;\n type: 'local' | 'distant';\n status: Partial<State>;\n }[]\n ) {\n for (const { dictionaryKey, type, status } of dictionaries) {\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 // 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 = SPINNER_FRAMES[state.spinnerFrameIndex! % SPINNER_FRAMES.length];\n colorStart = BLUE;\n colorEnd = RESET;\n } else if (state.status === 'error') {\n colorStart = RED;\n colorEnd = RESET;\n } else if (state.status === 'imported' || state.status === 'built') {\n colorStart = GREEN;\n colorEnd = RESET;\n } else {\n colorStart = GREY;\n colorEnd = RESET;\n }\n\n // Format the status block\n const statusBlock = `${GREY_DARK}[${state.type}: ${colorStart}${icon} ${state.status}${GREY_DARK}]${colorEnd}`;\n\n return `${colorStart}${statusBlock}${colorEnd}`;\n });\n\n return `${this.config.log.prefix}- ${paddedKey} ${states.join(' ')}`;\n }\n\n // Replace logUpdate calls with your custom methods\n private updateAllStatusLines() {\n const terminalHeight = process.stdout.rows;\n const maxVisibleLines = terminalHeight - 1;\n\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) % SPINNER_FRAMES.length;\n }\n });\n return this.getStatusLine(statusObj);\n });\n\n let content;\n\n if (lines.length > maxVisibleLines) {\n const visibleLines = lines.slice(0, maxVisibleLines - 5);\n const summary = `${this.config.log.prefix}... and ${lines.length - visibleLines.length} more`;\n content = LINE_DETECTOR + visibleLines.join('\\n') + '\\n' + summary;\n } else {\n content = lines.join('\\n');\n }\n\n this.updateOutput(content);\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,sBAAqB;AACrB,m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AAEO,MAAM,SAAS,OAAO,YAAY;","names":["readline"]}
|
|
@@ -21,6 +21,7 @@ __export(processContentDeclaration_exports, {
|
|
|
21
21
|
processContentDeclaration: () => processContentDeclaration
|
|
22
22
|
});
|
|
23
23
|
module.exports = __toCommonJS(processContentDeclaration_exports);
|
|
24
|
+
var import_client = require("@intlayer/config/client");
|
|
24
25
|
const processFunctionResults = async (entry) => {
|
|
25
26
|
if (entry && typeof entry === "object") {
|
|
26
27
|
const promises = [];
|
|
@@ -63,7 +64,7 @@ const processContentDeclaration = async (contentDeclaration) => {
|
|
|
63
64
|
content
|
|
64
65
|
};
|
|
65
66
|
} catch (error) {
|
|
66
|
-
|
|
67
|
+
(0, import_client.logger)(`Error processing module: ${error}`, { level: "error" });
|
|
67
68
|
}
|
|
68
69
|
};
|
|
69
70
|
// Annotate the CommonJS export names for ESM import in node:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/transpiler/declaration_file_to_dictionary/intlayer_dictionary/processContentDeclaration.ts"],"sourcesContent":["import type {\n Content,\n DeclarationContent,\n Dictionary,\n FlatContent,\n FlatContentValue,\n} from '@intlayer/core';\n\n/**\n * Function to replace function and async function fields with their results in the object\n */\nconst processFunctionResults = async (entry: Content): Promise<FlatContent> => {\n if (entry && typeof entry === 'object') {\n const promises: Promise<void>[] = [];\n const result: FlatContent = {};\n\n for (const key of Object.keys(entry)) {\n const field = entry?.[key];\n const isArray = Array.isArray(field);\n\n if (typeof field === 'object' && isArray) {\n result[key] = (await Promise.all(\n field.map(async (el) => {\n return await processFunctionResults(el as Content);\n })\n )) as unknown as FlatContentValue;\n } else if (typeof field === 'object') {\n result[key] = (await processFunctionResults(\n field as Content\n )) as FlatContentValue;\n } else if (typeof field === 'function') {\n // Wait for the function to resolve if it's an async function\n const promise = (async () => {\n // Execute the function and await the result if it's a Promise\n const value = await field();\n\n result[key] = value as FlatContentValue;\n })();\n promises.push(promise);\n } else {\n result[key] = field as FlatContentValue;\n }\n }\n\n // Wait for all async operations to complete\n await Promise.all(promises);\n\n return result;\n }\n\n return entry as FlatContent;\n};\n\n/**\n * Function to load, process the module and return the Intlayer DeclarationContent from the module file\n */\nexport const processContentDeclaration = async (\n contentDeclaration: DeclarationContent\n): Promise<Dictionary | undefined> => {\n try {\n const content = (await processFunctionResults(\n contentDeclaration.content\n )) as DeclarationContent['content'];\n\n return {\n ...contentDeclaration,\n content,\n } as Dictionary;\n } catch (error) {\n
|
|
1
|
+
{"version":3,"sources":["../../../../../src/transpiler/declaration_file_to_dictionary/intlayer_dictionary/processContentDeclaration.ts"],"sourcesContent":["import { logger } from '@intlayer/config/client';\nimport type {\n Content,\n DeclarationContent,\n Dictionary,\n FlatContent,\n FlatContentValue,\n} from '@intlayer/core';\n\n/**\n * Function to replace function and async function fields with their results in the object\n */\nconst processFunctionResults = async (entry: Content): Promise<FlatContent> => {\n if (entry && typeof entry === 'object') {\n const promises: Promise<void>[] = [];\n const result: FlatContent = {};\n\n for (const key of Object.keys(entry)) {\n const field = entry?.[key];\n const isArray = Array.isArray(field);\n\n if (typeof field === 'object' && isArray) {\n result[key] = (await Promise.all(\n field.map(async (el) => {\n return await processFunctionResults(el as Content);\n })\n )) as unknown as FlatContentValue;\n } else if (typeof field === 'object') {\n result[key] = (await processFunctionResults(\n field as Content\n )) as FlatContentValue;\n } else if (typeof field === 'function') {\n // Wait for the function to resolve if it's an async function\n const promise = (async () => {\n // Execute the function and await the result if it's a Promise\n const value = await field();\n\n result[key] = value as FlatContentValue;\n })();\n promises.push(promise);\n } else {\n result[key] = field as FlatContentValue;\n }\n }\n\n // Wait for all async operations to complete\n await Promise.all(promises);\n\n return result;\n }\n\n return entry as FlatContent;\n};\n\n/**\n * Function to load, process the module and return the Intlayer DeclarationContent from the module file\n */\nexport const processContentDeclaration = async (\n contentDeclaration: DeclarationContent\n): Promise<Dictionary | undefined> => {\n try {\n const content = (await processFunctionResults(\n contentDeclaration.content\n )) as DeclarationContent['content'];\n\n return {\n ...contentDeclaration,\n content,\n } as Dictionary;\n } catch (error) {\n logger(`Error processing module: ${error}`, { level: 'error' });\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAuB;AAYvB,MAAM,yBAAyB,OAAO,UAAyC;AAC7E,MAAI,SAAS,OAAO,UAAU,UAAU;AACtC,UAAM,WAA4B,CAAC;AACnC,UAAM,SAAsB,CAAC;AAE7B,eAAW,OAAO,OAAO,KAAK,KAAK,GAAG;AACpC,YAAM,QAAQ,QAAQ,GAAG;AACzB,YAAM,UAAU,MAAM,QAAQ,KAAK;AAEnC,UAAI,OAAO,UAAU,YAAY,SAAS;AACxC,eAAO,GAAG,IAAK,MAAM,QAAQ;AAAA,UAC3B,MAAM,IAAI,OAAO,OAAO;AACtB,mBAAO,MAAM,uBAAuB,EAAa;AAAA,UACnD,CAAC;AAAA,QACH;AAAA,MACF,WAAW,OAAO,UAAU,UAAU;AACpC,eAAO,GAAG,IAAK,MAAM;AAAA,UACnB;AAAA,QACF;AAAA,MACF,WAAW,OAAO,UAAU,YAAY;AAEtC,cAAM,WAAW,YAAY;AAE3B,gBAAM,QAAQ,MAAM,MAAM;AAE1B,iBAAO,GAAG,IAAI;AAAA,QAChB,GAAG;AACH,iBAAS,KAAK,OAAO;AAAA,MACvB,OAAO;AACL,eAAO,GAAG,IAAI;AAAA,MAChB;AAAA,IACF;AAGA,UAAM,QAAQ,IAAI,QAAQ;AAE1B,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAKO,MAAM,4BAA4B,OACvC,uBACoC;AACpC,MAAI;AACF,UAAM,UAAW,MAAM;AAAA,MACrB,mBAAmB;AAAA,IACrB;AAEA,WAAO;AAAA,MACL,GAAG;AAAA,MACH;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AACd,8BAAO,4BAA4B,KAAK,IAAI,EAAE,OAAO,QAAQ,CAAC;AAAA,EAChE;AACF;","names":[]}
|
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __create = Object.create;
|
|
3
2
|
var __defProp = Object.defineProperty;
|
|
4
3
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
4
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
5
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
6
|
var __export = (target, all) => {
|
|
9
7
|
for (var name in all)
|
|
@@ -17,14 +15,6 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
17
15
|
}
|
|
18
16
|
return to;
|
|
19
17
|
};
|
|
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
|
-
));
|
|
28
18
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
19
|
var createDictionaryList_exports = {};
|
|
30
20
|
__export(createDictionaryList_exports, {
|
|
@@ -34,10 +24,10 @@ module.exports = __toCommonJS(createDictionaryList_exports);
|
|
|
34
24
|
var import_fs = require("fs");
|
|
35
25
|
var import_path = require("path");
|
|
36
26
|
var import_config = require("@intlayer/config");
|
|
37
|
-
var
|
|
27
|
+
var import_getDictionariesPath = require('../../getDictionariesPath.cjs');
|
|
38
28
|
var import_utils = require('../../utils.cjs');
|
|
39
29
|
const { content } = (0, import_config.getConfiguration)();
|
|
40
|
-
const {
|
|
30
|
+
const { mainDir } = content;
|
|
41
31
|
const generateDictionaryListContent = (dictionaries, format = "esm") => {
|
|
42
32
|
let content2 = "";
|
|
43
33
|
const dictionariesRef = dictionaries.map((dictionaryPath) => ({
|
|
@@ -73,10 +63,10 @@ const createDictionaryList = () => {
|
|
|
73
63
|
if (!(0, import_fs.existsSync)(mainDir)) {
|
|
74
64
|
(0, import_fs.mkdirSync)(mainDir, { recursive: true });
|
|
75
65
|
}
|
|
76
|
-
const
|
|
77
|
-
const cjsContent = generateDictionaryListContent(
|
|
66
|
+
const dictionariesPath = (0, import_getDictionariesPath.getDictionariesPath)();
|
|
67
|
+
const cjsContent = generateDictionaryListContent(dictionariesPath, "cjs");
|
|
78
68
|
(0, import_fs.writeFileSync)((0, import_path.resolve)(mainDir, "dictionaries.cjs"), cjsContent);
|
|
79
|
-
const esmContent = generateDictionaryListContent(
|
|
69
|
+
const esmContent = generateDictionaryListContent(dictionariesPath, "esm");
|
|
80
70
|
(0, import_fs.writeFileSync)((0, import_path.resolve)(mainDir, "dictionaries.mjs"), esmContent);
|
|
81
71
|
};
|
|
82
72
|
// Annotate the CommonJS export names for ESM import in node:
|
|
@@ -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
|
|
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 { getDictionariesPath } from '../../getDictionariesPath';\nimport { getFileHash } from '../../utils';\n\nconst { content } = getConfiguration();\nconst { 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 dictionariesPath: string[] = getDictionariesPath();\n\n // Create the dictionary list file\n const cjsContent = generateDictionaryListContent(dictionariesPath, 'cjs');\n writeFileSync(resolve(mainDir, 'dictionaries.cjs'), cjsContent);\n\n const esmContent = generateDictionaryListContent(dictionariesPath, 'esm');\n writeFileSync(resolve(mainDir, 'dictionaries.mjs'), esmContent);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAAqD;AACrD,kBAAqD;AACrD,oBAAiC;AACjC,iCAAoC;AACpC,mBAA4B;AAE5B,MAAM,EAAE,QAAQ,QAAI,gCAAiB;AACrC,MAAM,EAAE,QAAQ,IAAI;AAKpB,MAAM,gCAAgC,CACpC,cACA,SAAwB,UACb;AACX,MAAIA,WAAU;AAEd,QAAM,kBAAkB,aAAa,IAAI,CAAC,oBAAoB;AAAA,IAC5D,kBAAc,sBAAS,SAAS,cAAc;AAAA,IAC9C,QAAI,sBAAS,oBAAgB,qBAAQ,cAAc,CAAC;AAAA;AAAA,IACpD,MAAM,QAAI,0BAAY,cAAc,CAAC;AAAA;AAAA,EACvC,EAAE;AAGF,kBAAgB,QAAQ,CAAC,eAAe;AACtC,QAAI,WAAW;AACb,MAAAA,YAAW,UAAU,WAAW,IAAI,UAAU,WAAW,YAAY;AAAA;AACvE,QAAI,WAAW;AACb,MAAAA,YAAW,SAAS,WAAW,IAAI,eAAe,WAAW,YAAY;AAAA;AAAA,EAC7E,CAAC;AAED,EAAAA,YAAW;AAGX,QAAM,yBAAiC,gBACpC,IAAI,CAAC,eAAe,IAAI,WAAW,EAAE,MAAM,WAAW,IAAI,EAAE,EAC5D,KAAK,KAAK;AAEb,MAAI,WAAW;AACb,IAAAA,YAAW;AAAA,EAAqB,sBAAsB;AAAA;AAAA;AACxD,MAAI,WAAW;AACb,IAAAA,YAAW;AAAA,EAAuB,sBAAsB;AAAA;AAAA;AAE1D,SAAOA;AACT;AAKO,MAAM,uBAAuB,MAAM;AAExC,MAAI,KAAC,sBAAW,OAAO,GAAG;AACxB,6BAAU,SAAS,EAAE,WAAW,KAAK,CAAC;AAAA,EACxC;AAEA,QAAM,uBAA6B,gDAAoB;AAGvD,QAAM,aAAa,8BAA8B,kBAAkB,KAAK;AACxE,mCAAc,qBAAQ,SAAS,kBAAkB,GAAG,UAAU;AAE9D,QAAM,aAAa,8BAA8B,kBAAkB,KAAK;AACxE,mCAAc,qBAAQ,SAAS,kBAAkB,GAAG,UAAU;AAChE;","names":["content"]}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { relative } from "path";
|
|
2
|
-
import { getConfiguration } from "@intlayer/config";
|
|
2
|
+
import { appLogger, getConfiguration } from "@intlayer/config";
|
|
3
3
|
import { watch as chokidarWatch } from "chokidar";
|
|
4
4
|
import fg from "fast-glob";
|
|
5
5
|
import { cleanOutputDir } from '../cleanOutputDir.mjs';
|
|
6
|
+
import { getDictionariesPath } from '../getDictionariesPath.mjs';
|
|
6
7
|
import { loadDictionaries } from '../loadDictionaries/loadDictionaries.mjs';
|
|
7
8
|
import { loadLocalDictionaries } from '../loadDictionaries/loadLocalDictionaries.mjs';
|
|
8
9
|
import { buildDictionary } from '../transpiler/declaration_file_to_dictionary/index.mjs';
|
|
@@ -11,7 +12,6 @@ import {
|
|
|
11
12
|
createTypes,
|
|
12
13
|
createModuleAugmentation
|
|
13
14
|
} from '../transpiler/dictionary_to_type/index.mjs';
|
|
14
|
-
const LOG_PREFIX = "[intlayer] ";
|
|
15
15
|
const watch = (options) => {
|
|
16
16
|
const { content } = getConfiguration({
|
|
17
17
|
verbose: true
|
|
@@ -26,33 +26,62 @@ const watch = (options) => {
|
|
|
26
26
|
...options
|
|
27
27
|
}).on("ready", async () => {
|
|
28
28
|
cleanOutputDir();
|
|
29
|
+
appLogger("Output directory cleaned", {
|
|
30
|
+
isVerbose: true
|
|
31
|
+
});
|
|
29
32
|
const dictionaries = await loadDictionaries(files);
|
|
30
33
|
const dictionariesPaths = await buildDictionary(dictionaries);
|
|
31
34
|
await createTypes(dictionariesPaths);
|
|
32
|
-
console.info(
|
|
33
|
-
`${LOG_PREFIX}${dictionariesPaths.length} dictionaries built`
|
|
34
|
-
);
|
|
35
|
-
createModuleAugmentation();
|
|
36
35
|
createDictionaryList();
|
|
36
|
+
appLogger("Dictionaries built");
|
|
37
|
+
createModuleAugmentation();
|
|
38
|
+
appLogger("Module augmentation built", {
|
|
39
|
+
isVerbose: true
|
|
40
|
+
});
|
|
37
41
|
}).on("add", async (filePath) => {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
);
|
|
42
|
+
appLogger(`Additional file detected: ${relative(baseDir, filePath)}`, {
|
|
43
|
+
isVerbose: true
|
|
44
|
+
});
|
|
42
45
|
const localeDictionaries = await loadLocalDictionaries(filePath);
|
|
43
|
-
const
|
|
44
|
-
await createTypes(
|
|
45
|
-
createModuleAugmentation();
|
|
46
|
+
const dictionariesPaths = await buildDictionary(localeDictionaries);
|
|
47
|
+
await createTypes(dictionariesPaths);
|
|
46
48
|
createDictionaryList();
|
|
49
|
+
appLogger("Dictionaries built", {
|
|
50
|
+
isVerbose: true
|
|
51
|
+
});
|
|
52
|
+
createModuleAugmentation();
|
|
53
|
+
appLogger("Module augmentation built", {
|
|
54
|
+
isVerbose: true
|
|
55
|
+
});
|
|
47
56
|
}).on("change", async (filePath) => {
|
|
48
|
-
|
|
57
|
+
appLogger(`Change detected: ${relative(baseDir, filePath)}`, {
|
|
58
|
+
isVerbose: true
|
|
59
|
+
});
|
|
49
60
|
const localeDictionaries = await loadLocalDictionaries(filePath);
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
61
|
+
const updatedDictionariesPaths = await buildDictionary(localeDictionaries);
|
|
62
|
+
const allDictionariesPaths = getDictionariesPath();
|
|
63
|
+
await createTypes(updatedDictionariesPaths);
|
|
64
|
+
appLogger("TypeScript types built", {
|
|
65
|
+
isVerbose: true
|
|
66
|
+
});
|
|
67
|
+
if (updatedDictionariesPaths.some(
|
|
68
|
+
(updatedDictionaryPath) => allDictionariesPaths.includes(updatedDictionaryPath)
|
|
69
|
+
)) {
|
|
70
|
+
createDictionaryList();
|
|
71
|
+
appLogger("Dictionary list built", {
|
|
72
|
+
isVerbose: true
|
|
73
|
+
});
|
|
74
|
+
createModuleAugmentation();
|
|
75
|
+
appLogger("Module augmentation built", {
|
|
76
|
+
isVerbose: true
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
}).on(
|
|
80
|
+
"error",
|
|
81
|
+
(error) => appLogger("Watcher error: " + error, {
|
|
82
|
+
level: "error"
|
|
83
|
+
})
|
|
84
|
+
);
|
|
56
85
|
};
|
|
57
86
|
export {
|
|
58
87
|
watch
|
|
@@ -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 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\
|
|
1
|
+
{"version":3,"sources":["../../../src/chokidar/watcher.ts"],"sourcesContent":["import { relative } from 'path';\nimport { appLogger, 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 { getDictionariesPath } from '../getDictionariesPath';\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\n// Initialize chokidar watcher (non-persistent)\nexport const watch = (options?: ChokidarOptions) => {\n const { content } = getConfiguration({\n verbose: true,\n });\n\n const { watchedFilesPatternWithPath, baseDir, watch: isWatchMode } = content;\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: isWatchMode, // Make the watcher persistent\n ignoreInitial: true, // Process existing files\n ...options,\n })\n .on('ready', async () => {\n cleanOutputDir();\n\n appLogger('Output directory cleaned', {\n isVerbose: true,\n });\n\n const dictionaries = await loadDictionaries(files);\n\n // Build locale dictionaries\n const dictionariesPaths = await buildDictionary(dictionaries);\n\n await createTypes(dictionariesPaths);\n\n createDictionaryList();\n\n appLogger('Dictionaries built');\n\n createModuleAugmentation();\n\n appLogger('Module augmentation built', {\n isVerbose: true,\n });\n })\n .on('add', async (filePath) => {\n // Process the file with the functionToRun\n appLogger(`Additional file detected: ${relative(baseDir, filePath)}`, {\n isVerbose: true,\n });\n\n const localeDictionaries = await loadLocalDictionaries(filePath);\n\n const dictionariesPaths = await buildDictionary(localeDictionaries);\n\n await createTypes(dictionariesPaths);\n\n createDictionaryList();\n\n appLogger('Dictionaries built', {\n isVerbose: true,\n });\n\n createModuleAugmentation();\n\n appLogger('Module augmentation built', {\n isVerbose: true,\n });\n })\n .on('change', async (filePath) => {\n // Process the file with the functionToRun\n appLogger(`Change detected: ${relative(baseDir, filePath)}`, {\n isVerbose: true,\n });\n\n const localeDictionaries = await loadLocalDictionaries(filePath);\n const updatedDictionariesPaths =\n await buildDictionary(localeDictionaries);\n const allDictionariesPaths: string[] = getDictionariesPath();\n\n await createTypes(updatedDictionariesPaths);\n appLogger('TypeScript types built', {\n isVerbose: true,\n });\n\n if (\n updatedDictionariesPaths.some((updatedDictionaryPath) =>\n allDictionariesPaths.includes(updatedDictionaryPath)\n )\n ) {\n createDictionaryList();\n\n appLogger('Dictionary list built', {\n isVerbose: true,\n });\n\n createModuleAugmentation();\n\n appLogger('Module augmentation built', {\n isVerbose: true,\n });\n }\n })\n .on('error', (error) =>\n appLogger('Watcher error: ' + error, {\n level: 'error',\n })\n );\n};\n"],"mappings":"AAAA,SAAS,gBAAgB;AACzB,SAAS,WAAW,wBAAwB;AAE5C,SAA+B,SAAS,qBAAqB;AAC7D,OAAO,QAAQ;AACf,SAAS,sBAAsB;AAC/B,SAAS,2BAA2B;AACpC,SAAS,wBAAwB;AACjC,SAAS,6BAA6B;AACtC,SAAS,uBAAuB;AAChC,SAAS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AAM,2BACJ,MAAM,gBAAgB,kBAAkB;AAC1C,UAAM,uBAAiC,oBAAoB;AAE3D,UAAM,YAAY,wBAAwB;AAC1C,cAAU,0BAA0B;AAAA,MAClC,WAAW;AAAA,IACb,CAAC;AAED,QACE,yBAAyB;AAAA,MAAK,CAAC,0BAC7B,qBAAqB,SAAS,qBAAqB;AAAA,IACrD,GACA;AACA,2BAAqB;AAErB,gBAAU,yBAAyB;AAAA,QACjC,WAAW;AAAA,MACb,CAAC;AAED,+BAAyB;AAEzB,gBAAU,6BAA6B;AAAA,QACrC,WAAW;AAAA,MACb,CAAC;AAAA,IACH;AAAA,EACF,CAAC,EACA;AAAA,IAAG;AAAA,IAAS,CAAC,UACZ,UAAU,oBAAoB,OAAO;AAAA,MACnC,OAAO;AAAA,IACT,CAAC;AAAA,EACH;AACJ;","names":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getConfiguration } from "@intlayer/config";
|
|
1
|
+
import { appLogger, getConfiguration } from "@intlayer/config";
|
|
2
2
|
import { getIntlayerAPI } from "@intlayer/design-system/libs";
|
|
3
3
|
import pLimit from "p-limit";
|
|
4
4
|
import { logger } from './log.mjs';
|
|
@@ -63,7 +63,7 @@ const fetchDistantDictionaries = async (options) => {
|
|
|
63
63
|
for (const statusObj of statuses) {
|
|
64
64
|
const currentState = statusObj.state.find((s) => s.type === "distant");
|
|
65
65
|
if (currentState && currentState.errorMessage) {
|
|
66
|
-
|
|
66
|
+
appLogger(currentState.errorMessage, { level: "error" });
|
|
67
67
|
}
|
|
68
68
|
}
|
|
69
69
|
const filteredResult = result.filter(
|
|
@@ -71,7 +71,7 @@ const fetchDistantDictionaries = async (options) => {
|
|
|
71
71
|
);
|
|
72
72
|
return filteredResult;
|
|
73
73
|
} catch (error) {
|
|
74
|
-
|
|
74
|
+
appLogger(error, { level: "error" });
|
|
75
75
|
return [];
|
|
76
76
|
}
|
|
77
77
|
};
|
|
@@ -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 { 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); //
|
|
1
|
+
{"version":3,"sources":["../../src/fetchDistantDictionaries.ts"],"sourcesContent":["// @ts-ignore @intlayer/backend not build yet\nimport { type DictionaryAPI } from '@intlayer/backend';\nimport { appLogger, 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); // Limit the number of concurrent requests\n\n const processDictionary = async (\n dictionaryKey: string\n ): Promise<DictionaryAPI | undefined> => {\n logger.updateStatus([\n {\n dictionaryKey,\n type: 'distant',\n status: { status: 'fetching' },\n },\n ]);\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([\n { dictionaryKey, type: 'distant', status: { status: 'imported' } },\n ]);\n\n return distantDictionary;\n } catch (error) {\n logger.updateStatus([\n {\n dictionaryKey,\n type: 'distant',\n status: {\n status: 'error',\n error: error as Error,\n errorMessage: `${options?.logPrefix ?? ''}Error fetching dictionary ${dictionaryKey}: ${error}`,\n },\n },\n ]);\n return undefined;\n }\n };\n\n const fetchPromises = distantDictionariesKeys.map((dictionaryKey) =>\n limit(async () => await 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 appLogger(currentState.errorMessage, { level: 'error' });\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 appLogger(error, { level: 'error' });\n return [];\n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,YAC/F;AAAA,UACF;AAAA,QACF,CAAC;AACD,eAAO;AAAA,MACT;AAAA,IACF;AAEA,UAAM,gBAAgB,wBAAwB;AAAA,MAAI,CAAC,kBACjD,MAAM,YAAY,MAAM,kBAAkB,aAAa,CAAC;AAAA,IAC1D;AAEA,UAAM,SAAS,MAAM,QAAQ,IAAI,aAAa;AAG9C,UAAM,WAAW,OAAO,YAAY;AACpC,eAAW,aAAa,UAAU;AAChC,YAAM,eAAe,UAAU,MAAM,KAAK,CAAC,MAAM,EAAE,SAAS,SAAS;AACrE,UAAI,gBAAgB,aAAa,cAAc;AAC7C,kBAAU,aAAa,cAAc,EAAE,OAAO,QAAQ,CAAC;AAAA,MACzD;AAAA,IACF;AAGA,UAAM,iBAAiB,OAAO;AAAA,MAC5B,CAAC,SAAgC,SAAS;AAAA,IAC5C;AAEA,WAAO;AAAA,EACT,SAAS,OAAO;AACd,cAAU,OAAO,EAAE,OAAO,QAAQ,CAAC;AACnC,WAAO,CAAC;AAAA,EACV;AACF;","names":[]}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { existsSync, mkdirSync } from "fs";
|
|
2
|
+
import { getConfiguration } from "@intlayer/config";
|
|
3
|
+
import fg from "fast-glob";
|
|
4
|
+
const { content } = getConfiguration();
|
|
5
|
+
const { dictionariesDir, mainDir } = content;
|
|
6
|
+
const getDictionariesPath = () => {
|
|
7
|
+
if (!existsSync(mainDir)) {
|
|
8
|
+
mkdirSync(mainDir, { recursive: true });
|
|
9
|
+
}
|
|
10
|
+
const dictionariesPath = fg.sync(`${dictionariesDir}/**/*.json`);
|
|
11
|
+
return dictionariesPath;
|
|
12
|
+
};
|
|
13
|
+
export {
|
|
14
|
+
getDictionariesPath
|
|
15
|
+
};
|
|
16
|
+
//# sourceMappingURL=getDictionariesPath.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/getDictionariesPath.ts"],"sourcesContent":["import { existsSync, mkdirSync } from 'fs';\nimport { getConfiguration } from '@intlayer/config';\nimport fg from 'fast-glob';\n\nconst { content } = getConfiguration();\nconst { dictionariesDir, mainDir } = content;\n\n/**\n * This function generates a list of dictionaries in the main directory\n */\nexport const getDictionariesPath = () => {\n // Create main directory if it doesn't exist\n if (!existsSync(mainDir)) {\n mkdirSync(mainDir, { recursive: true });\n }\n\n const dictionariesPath: string[] = fg.sync(`${dictionariesDir}/**/*.json`);\n\n return dictionariesPath;\n};\n"],"mappings":"AAAA,SAAS,YAAY,iBAAiB;AACtC,SAAS,wBAAwB;AACjC,OAAO,QAAQ;AAEf,MAAM,EAAE,QAAQ,IAAI,iBAAiB;AACrC,MAAM,EAAE,iBAAiB,QAAQ,IAAI;AAK9B,MAAM,sBAAsB,MAAM;AAEvC,MAAI,CAAC,WAAW,OAAO,GAAG;AACxB,cAAU,SAAS,EAAE,WAAW,KAAK,CAAC;AAAA,EACxC;AAEA,QAAM,mBAA6B,GAAG,KAAK,GAAG,eAAe,YAAY;AAEzE,SAAO;AACT;","names":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getConfiguration } from "@intlayer/config";
|
|
1
|
+
import { appLogger, getConfiguration } from "@intlayer/config";
|
|
2
2
|
import merge from "deepmerge";
|
|
3
3
|
import { fetchDistantDictionaryKeys } from '../fetchDistantDictionaryKeys.mjs';
|
|
4
4
|
import { logger } from '../log.mjs';
|
|
@@ -6,11 +6,10 @@ import { mergeByKey } from '../mergeDictionaries.mjs';
|
|
|
6
6
|
import { sortAlphabetically } from '../utils.mjs';
|
|
7
7
|
import { loadContentDeclarations } from './loadContentDeclaration.mjs';
|
|
8
8
|
import { loadDistantDictionaries } from './loadDistantDictionaries.mjs';
|
|
9
|
-
const LOG_PREFIX = "[intlayer] ";
|
|
10
9
|
const loadDictionaries = async (contentDeclarationsPaths) => {
|
|
11
10
|
try {
|
|
12
11
|
const { editor } = getConfiguration();
|
|
13
|
-
|
|
12
|
+
appLogger("Dictionaries:", { isVerbose: true });
|
|
14
13
|
const files = Array.isArray(contentDeclarationsPaths) ? contentDeclarationsPaths : [contentDeclarationsPaths];
|
|
15
14
|
const localDictionaries = await loadContentDeclarations(files);
|
|
16
15
|
const localDictionaryKeys = localDictionaries.map((dict) => dict.key);
|
|
@@ -43,7 +42,9 @@ const loadDictionaries = async (contentDeclarationsPaths) => {
|
|
|
43
42
|
});
|
|
44
43
|
}
|
|
45
44
|
} catch (_error) {
|
|
46
|
-
|
|
45
|
+
appLogger("Error during fetching distant dictionaries", {
|
|
46
|
+
level: "error"
|
|
47
|
+
});
|
|
47
48
|
}
|
|
48
49
|
}
|
|
49
50
|
logger.stop();
|
|
@@ -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 { sortAlphabetically } from '../utils';\nimport { loadContentDeclarations } from './loadContentDeclaration';\nimport { loadDistantDictionaries } from './loadDistantDictionaries';\n\
|
|
1
|
+
{"version":3,"sources":["../../../src/loadDictionaries/loadDictionaries.ts"],"sourcesContent":["// @ts-ignore @intlayer/backend not build yet\nimport { type DictionaryAPI } from '@intlayer/backend';\nimport { appLogger, 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\nexport const loadDictionaries = async (\n contentDeclarationsPaths: string[] | string\n): Promise<Dictionary[]> => {\n try {\n const { editor } = getConfiguration();\n\n appLogger('Dictionaries:', { isVerbose: true });\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 logger.updateStatus(\n localDictionaries.map((dict) => ({\n dictionaryKey: dict.key,\n type: 'local',\n status: { status: 'built' },\n }))\n );\n\n let distantDictionaries: DictionaryAPI[] = [];\n let distantDictionaryKeys: string[] = [];\n let mergedDictionaries = localDictionaries;\n\n if (editor.clientId && editor.clientSecret) {\n try {\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 } catch (_error) {\n appLogger('Error during fetching distant dictionaries', {\n level: 'error',\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":"AAEA,SAAS,WAAW,wBAAwB;AAE5C,OAAO,WAAW;AAClB,SAAS,kCAAkC;AAC3C,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAC3B,SAAS,0BAA0B;AAC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AAO;AAEd,WAAO,KAAK;AAEZ,UAAM;AAAA,EACR;AACF;","names":[]}
|
package/dist/esm/log.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import readline from "readline";
|
|
2
2
|
import { sortAlphabetically } from './utils.mjs';
|
|
3
|
+
import { getConfiguration } from "@intlayer/config";
|
|
3
4
|
const LINE_DETECTOR = "\u200B\u200B\u200B";
|
|
4
5
|
const SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
|
|
5
6
|
const RESET = "\x1B[0m";
|
|
@@ -17,9 +18,11 @@ class Logger {
|
|
|
17
18
|
originalStdoutWrite = null;
|
|
18
19
|
extraLines = 0;
|
|
19
20
|
isUpdating = false;
|
|
21
|
+
config;
|
|
20
22
|
// Singleton instance
|
|
21
23
|
static instance;
|
|
22
24
|
constructor() {
|
|
25
|
+
this.config = getConfiguration();
|
|
23
26
|
}
|
|
24
27
|
static getInstance() {
|
|
25
28
|
if (!Logger.instance) {
|
|
@@ -113,6 +116,7 @@ class Logger {
|
|
|
113
116
|
}
|
|
114
117
|
// Method to update the terminal output
|
|
115
118
|
updateOutput(content) {
|
|
119
|
+
if (this.config.log.mode !== "verbose") return;
|
|
116
120
|
if (!this.originalStdoutWrite) {
|
|
117
121
|
this.originalStdoutWrite = process.stdout.write.bind(process.stdout);
|
|
118
122
|
this.extraLines = 0;
|
|
@@ -223,7 +227,7 @@ class Logger {
|
|
|
223
227
|
const statusBlock = `${GREY_DARK}[${state.type}: ${colorStart}${icon} ${state.status}${GREY_DARK}]${colorEnd}`;
|
|
224
228
|
return `${colorStart}${statusBlock}${colorEnd}`;
|
|
225
229
|
});
|
|
226
|
-
return
|
|
230
|
+
return `${this.config.log.prefix}- ${paddedKey} ${states.join(" ")}`;
|
|
227
231
|
}
|
|
228
232
|
// Replace logUpdate calls with your custom methods
|
|
229
233
|
updateAllStatusLines() {
|
|
@@ -240,7 +244,7 @@ class Logger {
|
|
|
240
244
|
let content;
|
|
241
245
|
if (lines.length > maxVisibleLines) {
|
|
242
246
|
const visibleLines = lines.slice(0, maxVisibleLines - 5);
|
|
243
|
-
const summary =
|
|
247
|
+
const summary = `${this.config.log.prefix}... and ${lines.length - visibleLines.length} more`;
|
|
244
248
|
content = LINE_DETECTOR + visibleLines.join("\n") + "\n" + summary;
|
|
245
249
|
} else {
|
|
246
250
|
content = lines.join("\n");
|
package/dist/esm/log.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/log.ts"],"sourcesContent":["import readline from 'readline';\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\nconst LINE_DETECTOR = '\\u200B\\u200B\\u200B'; // Three zero-width spaces\nconst SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\n\n// ANSI color codes\nconst RESET = '\\x1b[0m';\nconst GREEN = '\\x1b[32m';\nconst RED = '\\x1b[31m';\nconst BLUE = '\\x1b[34m';\nconst GREY = '\\x1b[90m';\nconst GREY_DARK = '\\x1b[90m';\n\nclass Logger {\n private dictionariesStatuses: DictionariesStatus[] = [];\n private spinnerTimer: NodeJS.Timeout | null = null;\n private maxDictionaryKeyLength: number = 0;\n private previousLineCount: number = 0;\n private lineDifCounter: number = 0;\n private originalStdoutWrite:\n | ((\n chunk: string | Uint8Array, // `chunk` can be either a string or a Uint8Array\n encoding?: BufferEncoding, // `encoding` is optional and should be a BufferEncoding\n callback?: (err?: Error | null) => void // `callback` is optional and a function\n ) => boolean)\n | null = null;\n private extraLines: number = 0;\n private isUpdating: boolean = false;\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 // Method to update the terminal output\n private updateOutput(content: string) {\n // Monkey-patch process.stdout.write to keep track of extra lines\n if (!this.originalStdoutWrite) {\n this.originalStdoutWrite = process.stdout.write.bind(process.stdout);\n this.extraLines = 0;\n\n const write = (\n chunk: string | Uint8Array, // `chunk` can be either a string or a Uint8Array\n encoding?: BufferEncoding, // `encoding` is optional and should be a BufferEncoding\n callback?: (err?: Error | null) => void // `callback` is optional and a function\n ) => {\n const str = typeof chunk === 'string' ? chunk : chunk.toString();\n const newLines = (str.match(/\\n/g) ?? []).length;\n\n // If the write is not initiated by Logger's updateOutput method\n if (!this.isUpdating) {\n this.extraLines += newLines;\n }\n\n return this.originalStdoutWrite!(chunk, encoding, callback);\n };\n\n process.stdout.write = write as typeof process.stdout.write;\n }\n\n // Set a flag to indicate that updateOutput is running\n this.isUpdating = true;\n\n // Adjust lineDifCounter if LINE_DETECTOR is not the first line\n const contentLines = content.split('\\n');\n const indexOfLineDetector = contentLines.indexOf(LINE_DETECTOR.trim());\n\n if (indexOfLineDetector > 0) {\n // LINE_DETECTOR is not at the first line\n this.lineDifCounter = indexOfLineDetector;\n } else {\n this.lineDifCounter = 0;\n }\n\n // Calculate total lines to move up\n const totalLinesToMoveUp =\n this.previousLineCount + this.lineDifCounter + this.extraLines;\n\n // Move cursor up by totalLinesToMoveUp\n readline.moveCursor(process.stdout, 0, -totalLinesToMoveUp);\n\n // Clear all lines downwards\n readline.clearScreenDown(process.stdout);\n\n // Write the updated content\n contentLines.forEach((line) => {\n process.stdout.write(`${line}\\x1b[K\\n`);\n });\n\n // Update previousLineCount\n this.previousLineCount = contentLines.length;\n\n // Reset extraLines counter and updating flag\n this.extraLines = 0;\n this.isUpdating = false;\n }\n\n public stop() {\n this.stopSpinner();\n }\n\n public updateStatus(\n dictionaries: {\n dictionaryKey: string;\n type: 'local' | 'distant';\n status: Partial<State>;\n }[]\n ) {\n for (const { dictionaryKey, type, status } of dictionaries) {\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 // 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 = SPINNER_FRAMES[state.spinnerFrameIndex! % SPINNER_FRAMES.length];\n colorStart = BLUE;\n colorEnd = RESET;\n } else if (state.status === 'error') {\n colorStart = RED;\n colorEnd = RESET;\n } else if (state.status === 'imported' || state.status === 'built') {\n colorStart = GREEN;\n colorEnd = RESET;\n } else {\n colorStart = GREY;\n colorEnd = RESET;\n }\n\n // Format the status block\n const statusBlock = `${GREY_DARK}[${state.type}: ${colorStart}${icon} ${state.status}${GREY_DARK}]${colorEnd}`;\n\n return `${colorStart}${statusBlock}${colorEnd}`;\n });\n\n return `- ${paddedKey} ${states.join(' ')}`;\n }\n\n // Replace logUpdate calls with your custom methods\n private updateAllStatusLines() {\n const terminalHeight = process.stdout.rows;\n const maxVisibleLines = terminalHeight - 1;\n\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) % SPINNER_FRAMES.length;\n }\n });\n return this.getStatusLine(statusObj);\n });\n\n let content;\n\n if (lines.length > maxVisibleLines) {\n const visibleLines = lines.slice(0, maxVisibleLines - 5);\n const summary = `... and ${lines.length - visibleLines.length} more`;\n content = LINE_DETECTOR + visibleLines.join('\\n') + '\\n' + summary;\n } else {\n content = lines.join('\\n');\n }\n\n this.updateOutput(content);\n }\n\n public getStatuses() {\n return this.dictionariesStatuses;\n }\n}\n\nexport const logger = Logger.getInstance();\n"],"mappings":"AAAA,OAAO,cAAc;AACrB,SAAS,0BAA0B;AAgBnC,MAAM,gBAAgB;AACtB,MAAM,iBAAiB,CAAC,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,UAAK,QAAG;AAGxE,MAAM,QAAQ;AACd,MAAM,QAAQ;AACd,MAAM,MAAM;AACZ,MAAM,OAAO;AACb,MAAM,OAAO;AACb,MAAM,YAAY;AAElB,MAAM,OAAO;AAAA,EACH,uBAA6C,CAAC;AAAA,EAC9C,eAAsC;AAAA,EACtC,yBAAiC;AAAA,EACjC,oBAA4B;AAAA,EAC5B,iBAAyB;AAAA,EACzB,sBAMG;AAAA,EACH,aAAqB;AAAA,EACrB,aAAs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AuB;AAC7B,UAAM,iBAAiB,QAAQ,OAAO;AACtC,UAAM,kBAAkB,iBAAiB;AAEzC,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,eAAe;AAAA,QACpD;AAAA,MACF,CAAC;AACD,aAAO,KAAK,cAAc,SAAS;AAAA,IACrC,CAAC;AAED,QAAI;AAEJ,QAAI,MAAM,SAAS,iBAAiB;AAClC,YAAM,eAAe,MAAM,MAAM,GAAG,kBAAkB,CAAC;AACvD,YAAM,UAAU,WAAW,MAAM,SAAS,aAAa,MAAM;AAC7D,gBAAU,gBAAgB,aAAa,KAAK,IAAI,IAAI,OAAO;AAAA,IAC7D,OAAO;AACL,gBAAU,MAAM,KAAK,IAAI;AAAA,IAC3B;AAEA,SAAK,aAAa,OAAO;AAAA,EAC3B;AAAA,EAEO,cAAc;AACnB,WAAO,KAAK;AAAA,EACd;AACF;AAEO,MAAM,SAAS,OAAO,YAAY;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/log.ts"],"sourcesContent":["import readline from 'readline';\nimport { sortAlphabetically } from './utils';\nimport { getConfiguration, IntlayerConfig } from '@intlayer/config';\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\nconst LINE_DETECTOR = '\\u200B\\u200B\\u200B'; // Three zero-width spaces\nconst SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\n\n// ANSI color codes\nconst RESET = '\\x1b[0m';\nconst GREEN = '\\x1b[32m';\nconst RED = '\\x1b[31m';\nconst BLUE = '\\x1b[34m';\nconst GREY = '\\x1b[90m';\nconst GREY_DARK = '\\x1b[90m';\n\nclass Logger {\n private dictionariesStatuses: DictionariesStatus[] = [];\n private spinnerTimer: NodeJS.Timeout | null = null;\n private maxDictionaryKeyLength: number = 0;\n private previousLineCount: number = 0;\n private lineDifCounter: number = 0;\n private originalStdoutWrite:\n | ((\n chunk: string | Uint8Array, // `chunk` can be either a string or a Uint8Array\n encoding?: BufferEncoding, // `encoding` is optional and should be a BufferEncoding\n callback?: (err?: Error | null) => void // `callback` is optional and a function\n ) => boolean)\n | null = null;\n private extraLines: number = 0;\n private isUpdating: boolean = false;\n private config: IntlayerConfig;\n\n // Singleton instance\n private static instance: Logger;\n\n private constructor() {\n this.config = getConfiguration();\n }\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 // Method to update the terminal output\n private updateOutput(content: string) {\n if (this.config.log.mode !== 'verbose') return;\n\n // Monkey-patch process.stdout.write to keep track of extra lines\n if (!this.originalStdoutWrite) {\n this.originalStdoutWrite = process.stdout.write.bind(process.stdout);\n this.extraLines = 0;\n\n const write = (\n chunk: string | Uint8Array, // `chunk` can be either a string or a Uint8Array\n encoding?: BufferEncoding, // `encoding` is optional and should be a BufferEncoding\n callback?: (err?: Error | null) => void // `callback` is optional and a function\n ) => {\n const str = typeof chunk === 'string' ? chunk : chunk.toString();\n const newLines = (str.match(/\\n/g) ?? []).length;\n\n // If the write is not initiated by Logger's updateOutput method\n if (!this.isUpdating) {\n this.extraLines += newLines;\n }\n\n return this.originalStdoutWrite!(chunk, encoding, callback);\n };\n\n process.stdout.write = write as typeof process.stdout.write;\n }\n\n // Set a flag to indicate that updateOutput is running\n this.isUpdating = true;\n\n // Adjust lineDifCounter if LINE_DETECTOR is not the first line\n const contentLines = content.split('\\n');\n const indexOfLineDetector = contentLines.indexOf(LINE_DETECTOR.trim());\n\n if (indexOfLineDetector > 0) {\n // LINE_DETECTOR is not at the first line\n this.lineDifCounter = indexOfLineDetector;\n } else {\n this.lineDifCounter = 0;\n }\n\n // Calculate total lines to move up\n const totalLinesToMoveUp =\n this.previousLineCount + this.lineDifCounter + this.extraLines;\n\n // Move cursor up by totalLinesToMoveUp\n readline.moveCursor(process.stdout, 0, -totalLinesToMoveUp);\n\n // Clear all lines downwards\n readline.clearScreenDown(process.stdout);\n\n // Write the updated content\n contentLines.forEach((line) => {\n process.stdout.write(`${line}\\x1b[K\\n`);\n });\n\n // Update previousLineCount\n this.previousLineCount = contentLines.length;\n\n // Reset extraLines counter and updating flag\n this.extraLines = 0;\n this.isUpdating = false;\n }\n\n public stop() {\n this.stopSpinner();\n }\n\n public updateStatus(\n dictionaries: {\n dictionaryKey: string;\n type: 'local' | 'distant';\n status: Partial<State>;\n }[]\n ) {\n for (const { dictionaryKey, type, status } of dictionaries) {\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 // 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 = SPINNER_FRAMES[state.spinnerFrameIndex! % SPINNER_FRAMES.length];\n colorStart = BLUE;\n colorEnd = RESET;\n } else if (state.status === 'error') {\n colorStart = RED;\n colorEnd = RESET;\n } else if (state.status === 'imported' || state.status === 'built') {\n colorStart = GREEN;\n colorEnd = RESET;\n } else {\n colorStart = GREY;\n colorEnd = RESET;\n }\n\n // Format the status block\n const statusBlock = `${GREY_DARK}[${state.type}: ${colorStart}${icon} ${state.status}${GREY_DARK}]${colorEnd}`;\n\n return `${colorStart}${statusBlock}${colorEnd}`;\n });\n\n return `${this.config.log.prefix}- ${paddedKey} ${states.join(' ')}`;\n }\n\n // Replace logUpdate calls with your custom methods\n private updateAllStatusLines() {\n const terminalHeight = process.stdout.rows;\n const maxVisibleLines = terminalHeight - 1;\n\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) % SPINNER_FRAMES.length;\n }\n });\n return this.getStatusLine(statusObj);\n });\n\n let content;\n\n if (lines.length > maxVisibleLines) {\n const visibleLines = lines.slice(0, maxVisibleLines - 5);\n const summary = `${this.config.log.prefix}... and ${lines.length - visibleLines.length} more`;\n content = LINE_DETECTOR + visibleLines.join('\\n') + '\\n' + summary;\n } else {\n content = lines.join('\\n');\n }\n\n this.updateOutput(content);\n }\n\n public getStatuses()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AAK,aAAa,OAAO;AAAA,EAC3B;AAAA,EAEO,cAAc;AACnB,WAAO,KAAK;AAAA,EACd;AACF;AAEO,MAAM,SAAS,OAAO,YAAY;","names":[]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { logger } from "@intlayer/config/client";
|
|
1
2
|
const processFunctionResults = async (entry) => {
|
|
2
3
|
if (entry && typeof entry === "object") {
|
|
3
4
|
const promises = [];
|
|
@@ -40,7 +41,7 @@ const processContentDeclaration = async (contentDeclaration) => {
|
|
|
40
41
|
content
|
|
41
42
|
};
|
|
42
43
|
} catch (error) {
|
|
43
|
-
|
|
44
|
+
logger(`Error processing module: ${error}`, { level: "error" });
|
|
44
45
|
}
|
|
45
46
|
};
|
|
46
47
|
export {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/transpiler/declaration_file_to_dictionary/intlayer_dictionary/processContentDeclaration.ts"],"sourcesContent":["import type {\n Content,\n DeclarationContent,\n Dictionary,\n FlatContent,\n FlatContentValue,\n} from '@intlayer/core';\n\n/**\n * Function to replace function and async function fields with their results in the object\n */\nconst processFunctionResults = async (entry: Content): Promise<FlatContent> => {\n if (entry && typeof entry === 'object') {\n const promises: Promise<void>[] = [];\n const result: FlatContent = {};\n\n for (const key of Object.keys(entry)) {\n const field = entry?.[key];\n const isArray = Array.isArray(field);\n\n if (typeof field === 'object' && isArray) {\n result[key] = (await Promise.all(\n field.map(async (el) => {\n return await processFunctionResults(el as Content);\n })\n )) as unknown as FlatContentValue;\n } else if (typeof field === 'object') {\n result[key] = (await processFunctionResults(\n field as Content\n )) as FlatContentValue;\n } else if (typeof field === 'function') {\n // Wait for the function to resolve if it's an async function\n const promise = (async () => {\n // Execute the function and await the result if it's a Promise\n const value = await field();\n\n result[key] = value as FlatContentValue;\n })();\n promises.push(promise);\n } else {\n result[key] = field as FlatContentValue;\n }\n }\n\n // Wait for all async operations to complete\n await Promise.all(promises);\n\n return result;\n }\n\n return entry as FlatContent;\n};\n\n/**\n * Function to load, process the module and return the Intlayer DeclarationContent from the module file\n */\nexport const processContentDeclaration = async (\n contentDeclaration: DeclarationContent\n): Promise<Dictionary | undefined> => {\n try {\n const content = (await processFunctionResults(\n contentDeclaration.content\n )) as DeclarationContent['content'];\n\n return {\n ...contentDeclaration,\n content,\n } as Dictionary;\n } catch (error) {\n
|
|
1
|
+
{"version":3,"sources":["../../../../../src/transpiler/declaration_file_to_dictionary/intlayer_dictionary/processContentDeclaration.ts"],"sourcesContent":["import { logger } from '@intlayer/config/client';\nimport type {\n Content,\n DeclarationContent,\n Dictionary,\n FlatContent,\n FlatContentValue,\n} from '@intlayer/core';\n\n/**\n * Function to replace function and async function fields with their results in the object\n */\nconst processFunctionResults = async (entry: Content): Promise<FlatContent> => {\n if (entry && typeof entry === 'object') {\n const promises: Promise<void>[] = [];\n const result: FlatContent = {};\n\n for (const key of Object.keys(entry)) {\n const field = entry?.[key];\n const isArray = Array.isArray(field);\n\n if (typeof field === 'object' && isArray) {\n result[key] = (await Promise.all(\n field.map(async (el) => {\n return await processFunctionResults(el as Content);\n })\n )) as unknown as FlatContentValue;\n } else if (typeof field === 'object') {\n result[key] = (await processFunctionResults(\n field as Content\n )) as FlatContentValue;\n } else if (typeof field === 'function') {\n // Wait for the function to resolve if it's an async function\n const promise = (async () => {\n // Execute the function and await the result if it's a Promise\n const value = await field();\n\n result[key] = value as FlatContentValue;\n })();\n promises.push(promise);\n } else {\n result[key] = field as FlatContentValue;\n }\n }\n\n // Wait for all async operations to complete\n await Promise.all(promises);\n\n return result;\n }\n\n return entry as FlatContent;\n};\n\n/**\n * Function to load, process the module and return the Intlayer DeclarationContent from the module file\n */\nexport const processContentDeclaration = async (\n contentDeclaration: DeclarationContent\n): Promise<Dictionary | undefined> => {\n try {\n const content = (await processFunctionResults(\n contentDeclaration.content\n )) as DeclarationContent['content'];\n\n return {\n ...contentDeclaration,\n content,\n } as Dictionary;\n } catch (error) {\n logger(`Error processing module: ${error}`, { level: 'error' });\n }\n};\n"],"mappings":"AAAA,SAAS,cAAc;AAYvB,MAAM,yBAAyB,OAAO,UAAyC;AAC7E,MAAI,SAAS,OAAO,UAAU,UAAU;AACtC,UAAM,WAA4B,CAAC;AACnC,UAAM,SAAsB,CAAC;AAE7B,eAAW,OAAO,OAAO,KAAK,KAAK,GAAG;AACpC,YAAM,QAAQ,QAAQ,GAAG;AACzB,YAAM,UAAU,MAAM,QAAQ,KAAK;AAEnC,UAAI,OAAO,UAAU,YAAY,SAAS;AACxC,eAAO,GAAG,IAAK,MAAM,QAAQ;AAAA,UAC3B,MAAM,IAAI,OAAO,OAAO;AACtB,mBAAO,MAAM,uBAAuB,EAAa;AAAA,UACnD,CAAC;AAAA,QACH;AAAA,MACF,WAAW,OAAO,UAAU,UAAU;AACpC,eAAO,GAAG,IAAK,MAAM;AAAA,UACnB;AAAA,QACF;AAAA,MACF,WAAW,OAAO,UAAU,YAAY;AAEtC,cAAM,WAAW,YAAY;AAE3B,gBAAM,QAAQ,MAAM,MAAM;AAE1B,iBAAO,GAAG,IAAI;AAAA,QAChB,GAAG;AACH,iBAAS,KAAK,OAAO;AAAA,MACvB,OAAO;AACL,eAAO,GAAG,IAAI;AAAA,MAChB;AAAA,IACF;AAGA,UAAM,QAAQ,IAAI,QAAQ;AAE1B,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAKO,MAAM,4BAA4B,OACvC,uBACoC;AACpC,MAAI;AACF,UAAM,UAAW,MAAM;AAAA,MACrB,mBAAmB;AAAA,IACrB;AAEA,WAAO;AAAA,MACL,GAAG;AAAA,MACH;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AACd,WAAO,4BAA4B,KAAK,IAAI,EAAE,OAAO,QAAQ,CAAC;AAAA,EAChE;AACF;","names":[]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { existsSync, mkdirSync, writeFileSync } from "fs";
|
|
2
2
|
import { basename, extname, relative, resolve } from "path";
|
|
3
3
|
import { getConfiguration } from "@intlayer/config";
|
|
4
|
-
import
|
|
4
|
+
import { getDictionariesPath } from '../../getDictionariesPath.mjs';
|
|
5
5
|
import { getFileHash } from '../../utils.mjs';
|
|
6
6
|
const { content } = getConfiguration();
|
|
7
|
-
const {
|
|
7
|
+
const { mainDir } = content;
|
|
8
8
|
const generateDictionaryListContent = (dictionaries, format = "esm") => {
|
|
9
9
|
let content2 = "";
|
|
10
10
|
const dictionariesRef = dictionaries.map((dictionaryPath) => ({
|
|
@@ -40,10 +40,10 @@ const createDictionaryList = () => {
|
|
|
40
40
|
if (!existsSync(mainDir)) {
|
|
41
41
|
mkdirSync(mainDir, { recursive: true });
|
|
42
42
|
}
|
|
43
|
-
const
|
|
44
|
-
const cjsContent = generateDictionaryListContent(
|
|
43
|
+
const dictionariesPath = getDictionariesPath();
|
|
44
|
+
const cjsContent = generateDictionaryListContent(dictionariesPath, "cjs");
|
|
45
45
|
writeFileSync(resolve(mainDir, "dictionaries.cjs"), cjsContent);
|
|
46
|
-
const esmContent = generateDictionaryListContent(
|
|
46
|
+
const esmContent = generateDictionaryListContent(dictionariesPath, "esm");
|
|
47
47
|
writeFileSync(resolve(mainDir, "dictionaries.mjs"), esmContent);
|
|
48
48
|
};
|
|
49
49
|
export {
|
|
@@ -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
|
|
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 { getDictionariesPath } from '../../getDictionariesPath';\nimport { getFileHash } from '../../utils';\n\nconst { content } = getConfiguration();\nconst { 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 dictionariesPath: string[] = getDictionariesPath();\n\n // Create the dictionary list file\n const cjsContent = generateDictionaryListContent(dictionariesPath, 'cjs');\n writeFileSync(resolve(mainDir, 'dictionaries.cjs'), cjsContent);\n\n const esmContent = generateDictionaryListContent(dictionariesPath, 'esm');\n writeFileSync(resolve(mainDir, 'dictionaries.mjs'), esmContent);\n};\n"],"mappings":"AAAA,SAAS,YAAY,WAAW,qBAAqB;AACrD,SAAS,UAAU,SAAS,UAAU,eAAe;AACrD,SAAS,wBAAwB;AACjC,SAAS,2BAA2B;AACpC,SAAS,mBAAmB;AAE5B,MAAM,EAAE,QAAQ,IAAI,iBAAiB;AACrC,MAAM,EAAE,QAAQ,IAAI;AAKpB,MAAM,gCAAgC,CACpC,cACA,S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MAAM,UAAU,CAAC;
|
|
1
|
+
{"version":3,"file":"watcher.d.ts","sourceRoot":"","sources":["../../../src/chokidar/watcher.ts"],"names":[],"mappings":"AAEA,2FAA2F;AAC3F,OAAO,EAAE,KAAK,eAAe,EAA0B,MAAM,UAAU,CAAC;AAcxE,eAAO,MAAM,KAAK,aAAc,eAAe,QAsG9C,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"getDictionariesPath.d.ts","sourceRoot":"","sources":["../../src/getDictionariesPath.ts"],"names":[],"mappings":"AAOA;;GAEG;AACH,eAAO,MAAM,mBAAmB,gBAS/B,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loadDictionaries.d.ts","sourceRoot":"","sources":["../../../src/loadDictionaries/loadDictionaries.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"loadDictionaries.d.ts","sourceRoot":"","sources":["../../../src/loadDictionaries/loadDictionaries.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAS5C,eAAO,MAAM,gBAAgB,6BACD,MAAM,EAAE,GAAG,MAAM,KAC1C,OAAO,CAAC,UAAU,EAAE,CAwEtB,CAAC"}
|
package/dist/types/log.d.ts
CHANGED
package/dist/types/log.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"log.d.ts","sourceRoot":"","sources":["../../src/log.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"log.d.ts","sourceRoot":"","sources":["../../src/log.ts"],"names":[],"mappings":"AAIA,MAAM,MAAM,KAAK,GAAG;IAClB,IAAI,EAAE,OAAO,GAAG,SAAS,CAAC;IAC1B,MAAM,EAAE,SAAS,GAAG,UAAU,GAAG,SAAS,GAAG,OAAO,GAAG,UAAU,GAAG,OAAO,CAAC;IAC5E,IAAI,CAAC,EA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"file":"processContentDeclaration.d.ts","sourceRoot":"","sources":["../../../../../src/transpiler/declaration_file_to_dictionary/intlayer_dictionary/processContentDeclaration.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"processContentDeclaration.d.ts","sourceRoot":"","sources":["../../../../../src/transpiler/declaration_file_to_dictionary/intlayer_dictionary/processContentDeclaration.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAEV,kBAAkB,EAClB,UAAU,EAGX,MAAM,gBAAgB,CAAC;AA+CxB;;GAEG;AACH,eAAO,MAAM,yBAAyB,uBAChB,kBAAkB,KACrC,OAAO,CAAC,UAAU,GAAG,SAAS,CAahC,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@intlayer/chokidar",
|
|
3
|
-
"version": "3.5.
|
|
3
|
+
"version": "3.5.5",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Chokidar application for IntLayer - Transpile IntLayer declaration files into dictionaries.",
|
|
6
6
|
"keywords": [
|
|
@@ -67,11 +67,11 @@
|
|
|
67
67
|
"quicktype-core": "^23.0.170",
|
|
68
68
|
"react": "^18.3.1",
|
|
69
69
|
"rimraf": "^6.0.1",
|
|
70
|
-
"@intlayer/
|
|
71
|
-
"@intlayer/
|
|
72
|
-
"@intlayer/design-system": "^3.5.
|
|
73
|
-
"intlayer": "^3.5.
|
|
74
|
-
"@intlayer/
|
|
70
|
+
"@intlayer/config": "^3.5.5",
|
|
71
|
+
"@intlayer/core": "^3.5.5",
|
|
72
|
+
"@intlayer/design-system": "^3.5.5",
|
|
73
|
+
"intlayer": "^3.5.5",
|
|
74
|
+
"@intlayer/backend": "^3.5.5"
|
|
75
75
|
},
|
|
76
76
|
"devDependencies": {
|
|
77
77
|
"@changesets/cli": "2.27.10",
|
|
@@ -91,11 +91,12 @@
|
|
|
91
91
|
"@utils/tsup-config": "^1.0.4"
|
|
92
92
|
},
|
|
93
93
|
"peerDependencies": {
|
|
94
|
-
"
|
|
95
|
-
"@intlayer/
|
|
96
|
-
"intlayer": "^3.5.
|
|
97
|
-
"@intlayer/core": "^3.5.
|
|
98
|
-
"@intlayer/
|
|
94
|
+
"fast-glob": "^3.3.2",
|
|
95
|
+
"@intlayer/backend": "^3.5.5",
|
|
96
|
+
"@intlayer/config": "^3.5.5",
|
|
97
|
+
"@intlayer/core": "^3.5.5",
|
|
98
|
+
"@intlayer/design-system": "^3.5.5",
|
|
99
|
+
"intlayer": "^3.5.5"
|
|
99
100
|
},
|
|
100
101
|
"engines": {
|
|
101
102
|
"node": ">=14.18"
|