@codenotch/codenotch.cli 1.0.35 → 1.0.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/commands/generate/index.d.ts +3 -0
  2. package/dist/commands/generate/index.js +42 -0
  3. package/dist/commands/generate/index.js.map +1 -0
  4. package/dist/commands/index.js +2 -0
  5. package/dist/commands/index.js.map +1 -1
  6. package/dist/commands/project/new.js +32 -124
  7. package/dist/commands/project/new.js.map +1 -1
  8. package/dist/commands/system/info.js +0 -7
  9. package/dist/commands/system/info.js.map +1 -1
  10. package/dist/commands/validation/ValidationUtils.d.ts +3 -13
  11. package/dist/commands/validation/ValidationUtils.js +2 -58
  12. package/dist/commands/validation/ValidationUtils.js.map +1 -1
  13. package/dist/commands/validation/files/AppManifestValidator.js +5 -20
  14. package/dist/commands/validation/files/AppManifestValidator.js.map +1 -1
  15. package/dist/commands/validation/files/ScriptValidator.d.ts +6 -2
  16. package/dist/commands/validation/files/ScriptValidator.js.map +1 -1
  17. package/dist/commands/validation/validate.js +8 -44
  18. package/dist/commands/validation/validate.js.map +1 -1
  19. package/dist/models/Codenotch.d.ts +0 -205
  20. package/dist/models/Codenotch.js +0 -211
  21. package/dist/models/Codenotch.js.map +1 -1
  22. package/dist/utils/BuildUtils.d.ts +5 -21
  23. package/dist/utils/BuildUtils.js +4 -109
  24. package/dist/utils/BuildUtils.js.map +1 -1
  25. package/dist/utils/ConsoleUtils.d.ts +5 -0
  26. package/dist/utils/ConsoleUtils.js +25 -0
  27. package/dist/utils/ConsoleUtils.js.map +1 -1
  28. package/dist/utils/GitHubAuthUtils.js.map +1 -1
  29. package/dist/utils/ManifestUtils.d.ts +24 -0
  30. package/dist/utils/ManifestUtils.js +53 -0
  31. package/dist/utils/ManifestUtils.js.map +1 -0
  32. package/dist/utils/ProjectCompilationUtils.d.ts +4 -30
  33. package/dist/utils/ProjectCompilationUtils.js +64 -750
  34. package/dist/utils/ProjectCompilationUtils.js.map +1 -1
  35. package/dist/utils/ProjectUtils.d.ts +2 -2
  36. package/dist/utils/ProjectUtils.js +0 -29
  37. package/dist/utils/ProjectUtils.js.map +1 -1
  38. package/dist/utils/ServeUtils.d.ts +0 -1
  39. package/dist/utils/ServeUtils.js +1 -24
  40. package/dist/utils/ServeUtils.js.map +1 -1
  41. package/dist/utils/ShellUtils.js.map +1 -1
  42. package/package.json +2 -3
  43. package/dist/commands/validation/files/BpmnValidator.d.ts +0 -5
  44. package/dist/commands/validation/files/BpmnValidator.js +0 -32
  45. package/dist/commands/validation/files/BpmnValidator.js.map +0 -1
  46. package/dist/commands/validation/files/DbSchemaValidator.d.ts +0 -5
  47. package/dist/commands/validation/files/DbSchemaValidator.js +0 -16
  48. package/dist/commands/validation/files/DbSchemaValidator.js.map +0 -1
  49. package/dist/commands/validation/files/DocumentValidator.d.ts +0 -5
  50. package/dist/commands/validation/files/DocumentValidator.js +0 -12
  51. package/dist/commands/validation/files/DocumentValidator.js.map +0 -1
  52. package/dist/commands/validation/files/I18nValidator.d.ts +0 -5
  53. package/dist/commands/validation/files/I18nValidator.js +0 -13
  54. package/dist/commands/validation/files/I18nValidator.js.map +0 -1
  55. package/dist/commands/validation/files/ManifestCacheValidator.d.ts +0 -5
  56. package/dist/commands/validation/files/ManifestCacheValidator.js +0 -121
  57. package/dist/commands/validation/files/ManifestCacheValidator.js.map +0 -1
  58. package/dist/commands/validation/files/ManifestValidator.d.ts +0 -5
  59. package/dist/commands/validation/files/ManifestValidator.js +0 -14
  60. package/dist/commands/validation/files/ManifestValidator.js.map +0 -1
  61. package/dist/commands/validation/files/TableValidator.d.ts +0 -5
  62. package/dist/commands/validation/files/TableValidator.js +0 -19
  63. package/dist/commands/validation/files/TableValidator.js.map +0 -1
  64. package/dist/models/DbModels.d.ts +0 -221
  65. package/dist/models/DbModels.js +0 -130
  66. package/dist/models/DbModels.js.map +0 -1
  67. package/dist/models/OpenApiModels.d.ts +0 -115
  68. package/dist/models/OpenApiModels.js +0 -103
  69. package/dist/models/OpenApiModels.js.map +0 -1
  70. package/dist/utils/I18nUtils.d.ts +0 -9
  71. package/dist/utils/I18nUtils.js +0 -54
  72. package/dist/utils/I18nUtils.js.map +0 -1
  73. package/dist/utils/OpenAPIUtils.d.ts +0 -33
  74. package/dist/utils/OpenAPIUtils.js +0 -279
  75. package/dist/utils/OpenAPIUtils.js.map +0 -1
@@ -4,86 +4,36 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const path_1 = __importDefault(require("path"));
7
- const Codenotch_1 = require("../models/Codenotch");
8
- const DbModels_1 = require("../models/DbModels");
9
7
  const FileUtils_1 = __importDefault(require("./FileUtils"));
10
- const OpenAPIUtils_1 = require("./OpenAPIUtils");
11
- const StringUtils_1 = __importDefault(require("./StringUtils"));
12
- const js2xmlparser_1 = require("js2xmlparser");
13
- const BuildUtils_1 = __importDefault(require("./BuildUtils"));
14
8
  const ConsoleUtils_1 = __importDefault(require("./ConsoleUtils"));
15
- const codenotch_core_workflow_1 = require("@codenotch/codenotch.core.workflow");
16
- const codenotch_core_1 = require("@codenotch/codenotch.core");
17
9
  const chalk_1 = __importDefault(require("chalk"));
18
10
  const MANIFEST_FILE_NAME = "manifest.json";
19
11
  const DB_SCHEMA_FILE_NAME = "db-schema.xml";
20
- const MANIFEST_CACHE_FILE_NAME = "manifest.cache.json";
21
- const OPENAPI_FILE_NAME = "openapi.json";
22
12
  class ProjectCompilationUtils {
23
13
  /**
24
14
  * Create a new folder that contains a compiled version of the project
25
15
  * We have to compile the project because some files need to be modified a bit in order to work when deployed
26
16
  * In-place compilation, the files in the source folder will be modified/deleted and the output will be generated in the same folder
27
- * For example auml files have to include their i18n data
28
17
  * /!\Warning/!\ This will modify/delete files in the source folder, make sure to know what you are doing !!!
29
18
  * @param project current project
30
19
  * @returns the path to the compiled project
31
20
  */
32
21
  static async compileProject(targetPath) {
33
- let context = { targetPath: targetPath, processes: {}, documents: {}, tables: {}, files: [], errors: [], warnings: [] };
22
+ // TODO: Generate kinda DB schema (read all .ts/.js files that declare a table)
23
+ // TODO: Generate openapi.json (read all .ts/.js files that declare a process)
24
+ // TODO: Generate ts files for i18n (one per *.i18n.csv)
25
+ const context = {
26
+ targetPath: targetPath,
27
+ files: FileUtils_1.default.getAllFilesFromPath(targetPath, ['node_modules', '.codenotch', '.git', 'dist', 'build', 'out', '.github']),
28
+ errors: [],
29
+ warnings: []
30
+ };
34
31
  // Rebuild manifest from cache if it exists, otherwise generate it from project files
35
32
  console.log(chalk_1.default.cyan('→') + ' Generating manifest...');
36
- const fullManifest = await this.generateManifest(context);
37
- context.manifest = fullManifest;
38
- ConsoleUtils_1.default.check(`Manifest generated (${fullManifest.processes.length} process(es), ${fullManifest.reactApplications?.length ?? 0} React app(s))`);
39
- console.log(chalk_1.default.cyan('→') + ' Generating OpenAPI spec...');
40
- const openApi = await OpenAPIUtils_1.OpenApiUtils.generateOpenApi(context);
41
- if (openApi)
42
- ConsoleUtils_1.default.check('OpenAPI spec generated');
43
- console.log(chalk_1.default.cyan('→') + ' Generating database schema...');
44
- const dbSchema = await this.generateDbSchema(context);
45
- if (dbSchema && dbSchema.trim() !== '')
46
- ConsoleUtils_1.default.check('Database schema generated');
47
- // Compile package versions
48
- //compiledProject.manifest.packages = await this.compileSdkPackages(compiledProject.manifest);
49
- //TODO I don't like the idea of the cli fetching latest versions of each package, maybe they should be fixed ? or resolution happens at deployment ?
50
- // --> the problem is specific to auml components which we'll probably get rid of
51
- // Compile auml files
52
- //await this.compileAumlFiles(compiledProject.manifestCache, compiledProject);
53
- //TODO aka add i18n into the files, I think we could find a better way to do that, or at least only add relevant i18n
54
- // --> the problem is specific to auml components which we'll probably get rid of
55
- //TODO i18n for React apps
56
- // Build React apps if any
57
- const reactApps = fullManifest.reactApplications ?? [];
58
- for (let reactApp of reactApps) {
59
- try {
60
- console.log(chalk_1.default.cyan('→') + ` Building React app "${reactApp.applicationName}"...`);
61
- const appPath = path_1.default.join(targetPath, reactApp.file);
62
- const buildPath = await BuildUtils_1.default.buildApp2(appPath);
63
- // The build result is generated in .codenotch/appname-dist, we need to adapt the manifest to point to the generated index.html file
64
- reactApp.file = StringUtils_1.default.toRelativePath(path_1.default.join(buildPath, 'index.html'), targetPath);
65
- ConsoleUtils_1.default.check(`React app "${reactApp.applicationName}" built`);
66
- }
67
- catch (e) {
68
- context.errors.push(`Failed to build React application "${reactApp.applicationName}": ${e instanceof Error ? e.message : String(e)}`);
69
- }
70
- }
71
- // Create/update the files
72
- FileUtils_1.default.writeFileSync(path_1.default.join(targetPath, MANIFEST_FILE_NAME), JSON.stringify(fullManifest, null, 4));
73
- const dbSchemaPath = path_1.default.join(targetPath, DB_SCHEMA_FILE_NAME);
74
- if (await FileUtils_1.default.exists(dbSchemaPath)) {
75
- FileUtils_1.default.delete(dbSchemaPath);
76
- }
77
- if (dbSchema && dbSchema.trim() !== '')
78
- FileUtils_1.default.writeFileSync(dbSchemaPath, dbSchema);
79
- const openapiPath = path_1.default.join(targetPath, OPENAPI_FILE_NAME);
80
- if (await FileUtils_1.default.exists(openapiPath)) {
81
- FileUtils_1.default.delete(openapiPath);
82
- }
83
- if (openApi)
84
- FileUtils_1.default.writeFileSync(openapiPath, JSON.stringify(openApi, null, 4));
85
- // Remove manifest cache
86
- FileUtils_1.default.delete(path_1.default.join(targetPath, MANIFEST_CACHE_FILE_NAME));
33
+ context.manifest = await this.generateManifest(context);
34
+ ConsoleUtils_1.default.check(`Manifest generated`);
35
+ // Overwrite manifest
36
+ FileUtils_1.default.writeFileSync(path_1.default.join(targetPath, MANIFEST_FILE_NAME), JSON.stringify(context.manifest, null, 4));
87
37
  // Remove .npmrc if exists, we don't want to expose it
88
38
  FileUtils_1.default.delete(path_1.default.join(targetPath, '.npmrc'));
89
39
  if (context.errors.length > 0) {
@@ -104,167 +54,32 @@ class ProjectCompilationUtils {
104
54
  * @returns the path to the compiled project
105
55
  */
106
56
  static async compileTestProject(targetPath) {
107
- let context = { targetPath: targetPath, processes: {}, documents: {}, tables: {}, files: [], errors: [], warnings: [] };
57
+ const context = { targetPath: targetPath, files: [], errors: [], warnings: [] };
108
58
  // Rebuild manifest from cache if it exists, otherwise generate it from project files
109
- const fullManifest = await this.generateManifest(context);
110
- context.manifest = fullManifest;
111
- const dbSchema = await this.generateDbSchema(context);
59
+ context.manifest = await this.generateManifest(context);
112
60
  // Create/update the files
113
- FileUtils_1.default.writeFileSync(path_1.default.join(targetPath, MANIFEST_FILE_NAME), JSON.stringify(fullManifest, null, 4));
114
- FileUtils_1.default.writeFileSync(path_1.default.join(targetPath, DB_SCHEMA_FILE_NAME), dbSchema);
61
+ FileUtils_1.default.writeFileSync(path_1.default.join(targetPath, MANIFEST_FILE_NAME), JSON.stringify(context.manifest, null, 4));
62
+ const dbSchema = await this.generateDbSchema(context);
63
+ if (dbSchema) {
64
+ FileUtils_1.default.writeFileSync(path_1.default.join(targetPath, DB_SCHEMA_FILE_NAME), dbSchema);
65
+ }
115
66
  return {
116
67
  errors: context.errors,
117
68
  warnings: context.warnings
118
69
  };
119
70
  }
120
71
  static async generateDbSchema(context) {
121
- try {
122
- if (!context.manifest) {
123
- throw new Error("Manifest is required to generate db schema");
124
- }
125
- let tablesResult = Object.values(context.tables);
126
- // Update db schema
127
- let dbSchema = ProjectCompilationUtils.GetXMLFromTableDefinition(tablesResult, context.manifest.version);
128
- return dbSchema;
129
- }
130
- catch (e) {
131
- context.errors.push(`Failed to generate database schema: ${e instanceof Error ? e.message : String(e)}`);
132
- return '';
133
- }
134
- }
135
- static GetXMLFromTableDefinition(definitions, version = "0.0.1") {
136
- let DatabaseSchema = {
137
- Tables: {
138
- Table: []
139
- },
140
- "@": { Version: version }
141
- };
142
- definitions.forEach(definition => {
143
- let definitionModel = {
144
- "@": {
145
- Name: definition.Name,
146
- Description: definition.Description
147
- },
148
- Id: {
149
- "@": {
150
- Name: definition.Id.Name,
151
- }
152
- },
153
- CreatedAt: {
154
- "@": {
155
- Name: definition.CreatedAt.Name,
156
- }
157
- },
158
- UpdatedAt: {
159
- "@": {
160
- Name: definition.UpdatedAt.Name,
161
- }
162
- }
163
- };
164
- definition.Fields?.forEach(field => {
165
- let resultfield = {
166
- "@": Object.assign({}, field)
167
- };
168
- delete resultfield["@"].Type;
169
- if (field.Type === DbModels_1.FieldTypes.Enum) {
170
- resultfield["Value"] = resultfield["@"].Value;
171
- delete resultfield["@"].Value;
172
- }
173
- if (Array.isArray(definitionModel[field.Type])) {
174
- definitionModel[field.Type].push(resultfield);
175
- }
176
- else if (definitionModel[field.Type]) {
177
- definitionModel[field.Type] = [definitionModel[field.Type]];
178
- definitionModel[field.Type].push(resultfield);
179
- }
180
- else {
181
- definitionModel[field.Type] = resultfield;
182
- }
183
- });
184
- DatabaseSchema.Tables.Table.push(definitionModel);
185
- });
186
- let result = (0, js2xmlparser_1.parse)("DatabaseSchema", DatabaseSchema, { format: { doubleQuotes: true } });
187
- return result;
188
- }
189
- /*
190
- private static async compileAumlFiles(manifest: IWorkspaceCache, workspace: IWorkspaceRoot) {
191
-
192
- // Auml files need to include their i18n data
193
- let globali18ns = await I18nUtils.getCompiledGlobali18n(workspace, true);
194
-
195
- await I18nUtils.injectI18nIntoFiles(manifest.applications.map(x => x.file), workspace, globali18ns.values, globali18ns.files);
196
-
197
- if (manifest.expressComponents)
198
- await I18nUtils.injectI18nIntoFiles(manifest.expressComponents.map((x: any) => x.file), workspace, globali18ns.values, globali18ns.files);
199
-
200
- if (manifest.pdfs)
201
- await I18nUtils.injectI18nIntoFiles(manifest.pdfs.map(x => x.file), workspace, globali18ns.values, globali18ns.files);
202
-
203
- if (manifest.htmls)
204
- await I18nUtils.injectI18nIntoFiles(manifest.htmls.map(x => x.file), workspace, globali18ns.values, globali18ns.files);
205
-
206
- if (manifest.emails)
207
- await I18nUtils.injectI18nIntoFiles(manifest.emails.map(x => x.file), workspace, globali18ns.values, globali18ns.files);
208
-
209
-
210
- // Assets can also contain auml files
211
- let assetsPath = workspace + '/assets';
212
- var assetFiles = await ElectronUtil.getFileSystem(assetsPath).getAllFilesFromPath(assetsPath);
213
- var aumlAssetsFiles = assetFiles
214
- .filter(x => x.endsWith(".auml")) // We only want auml files
215
- .map(x => x.replace(workspace.path, '')); // Remove the project path part
216
- await I18nUtils.injectI18nIntoFiles(aumlAssetsFiles, workspace, globali18ns.values, globali18ns.files);
217
- }
218
- */
219
- /**
220
- * Will lock the version of all packages that use the "latest"
221
- */
222
- /* TODO
223
- private static async compileSdkPackages(manifest: IScenarioProjectManifest): Promise<{ [packageSource: string]: string }> {
224
- let results: {
225
- [packageSource: string]: string;
226
- } = {};
227
-
228
- for (let packageKey of Object.keys(manifest.packages)) {
229
-
230
- let version = manifest.packages[packageKey];
231
- if (version === "latest") {
232
- // We need to lock the version of all packages that use the "latest"
233
- // because otherwise we expose ourselves to a lot of potential problems due to unexpected changes in our dependencies
234
-
235
- // Get the latest version from the table storage
236
- var split = packageKey.split('/');
237
-
238
- let company = "";
239
- let packageName = split[0];
240
-
241
- if (split.length === 2) {
242
- company = split[0].substring(1);
243
- packageName = split[1];
244
- }
245
-
246
- let latestVersion = await PackageUtils.getPackageLatestVersion(packageName, version, company);
247
-
248
- results[packageKey] = latestVersion;
249
- }
250
- else {
251
- results[packageKey] = version;
252
- }
253
- }
254
-
255
- return results;
72
+ // TODO: Generate DB schema (read all .ts/.js files that declare a table)
73
+ throw new Error('Not implemented.');
256
74
  }
257
- */
258
75
  static getManifestFileType(file) {
259
76
  file = file.toLowerCase();
260
77
  let fileType = file.endsWith('.table') ? 'table' :
261
- file.endsWith('.bpmn') ? 'bpmn' :
262
- file.endsWith('.auml') ? 'auml' :
263
- file.endsWith('.jschema') ? 'document' :
264
- file.endsWith('.tsx') ? 'jsxtsx' :
265
- file.endsWith('.jsx') ? 'jsxtsx' :
266
- file.endsWith('.i18n.csv') ? 'i18n' :
267
- file.endsWith('.js') ? 'script' : '';
78
+ file.endsWith('.jschema') ? 'document' :
79
+ file.endsWith('.tsx') ? 'jsxtsx' :
80
+ file.endsWith('.jsx') ? 'jsxtsx' :
81
+ file.endsWith('.i18n.csv') ? 'i18n' :
82
+ file.endsWith('.js') ? 'script' : '';
268
83
  return fileType;
269
84
  }
270
85
  /**
@@ -274,27 +89,13 @@ class ProjectCompilationUtils {
274
89
  static async generateManifest(context) {
275
90
  const projectPath = context.targetPath;
276
91
  // Obtain the manifest, this part only contains user defined properties, the rest will be generated from files or taken from the cache
277
- let manifest = await FileUtils_1.default.readJsonFileAsync(path_1.default.join(projectPath, MANIFEST_FILE_NAME));
92
+ const manifest = await FileUtils_1.default.readJsonFileAsync(path_1.default.join(projectPath, MANIFEST_FILE_NAME));
278
93
  if (!manifest) {
279
94
  throw new Error("Cannot find manifest file in project");
280
95
  }
281
96
  // Ensure arrays are defined
282
- manifest.postInstallationProcesses = manifest.postInstallationProcesses ?? [];
283
97
  manifest.languages = manifest.languages ?? [];
284
- manifest.dependencies = manifest.dependencies ?? [];
285
- manifest.packages = manifest.packages ?? [];
286
98
  manifest.roles = manifest.roles ?? [];
287
- manifest.reactApplications = manifest.reactApplications ?? [];
288
- manifest.apis = manifest.apis ?? [];
289
- manifest.applications = manifest.applications ?? [];
290
- manifest.emails = manifest.emails ?? [];
291
- manifest.htmls = manifest.htmls ?? [];
292
- manifest.expressComponents = manifest.expressComponents ?? [];
293
- manifest.pdfs = manifest.pdfs ?? [];
294
- manifest.scripts = manifest.scripts ?? [];
295
- manifest.tableDataSources = manifest.tableDataSources ?? [];
296
- manifest.documentDataSources = manifest.documentDataSources ?? [];
297
- manifest.processes = manifest.processes ?? [];
298
99
  // Ensure version is defined
299
100
  if ((manifest.version ?? '').trim() === '') {
300
101
  manifest.version = '0.0.1';
@@ -316,535 +117,48 @@ class ProjectCompilationUtils {
316
117
  if (manifest.languages.length === 0) {
317
118
  manifest.languages = ["en"];
318
119
  }
319
- /* This is more optimized yes, but it lead to problems difficult to debug as it behaves differently depending on the cache, better to have a predictable behaviour
320
- try
321
- {
322
- let manifestCache = context.ignoreCache ? null : await FileUtils.readJsonFileAsync<ProjectManifest>(path.join(projectPath, MANIFEST_CACHE_FILE_NAME));
323
-
324
- // If a cache is present, skip discovering local files, typically inside the ide
325
- if(manifestCache) {
326
-
327
- manifest = {
328
- ...manifest,
329
- ...manifestCache
330
- }
331
-
332
- // We still need to populate the context
333
- //TODO
334
-
335
- return manifest;
336
- }
337
- }
338
- catch {}
339
- */
340
- // No cache, we need to discover files to generate the full manifest
341
- const projectFiles = FileUtils_1.default.getAllFilesFromPath(projectPath, ['node_modules', '.codenotch', '.git', 'dist', 'build', 'out']);
342
- context.files = projectFiles;
343
- //#region tables
344
- manifest.tableDataSources = [];
345
- // Read all tables
346
- let tablesFiles = projectFiles.filter(file => file.endsWith(".table"));
347
- for (let i = 0; i < tablesFiles.length; i++) {
348
- let tablefile = tablesFiles[i];
349
- let tableDefinition = (await FileUtils_1.default.readJsonFileAsync(tablefile));
350
- manifest.tableDataSources.push({
351
- file: StringUtils_1.default.toRelativePath(tablefile, projectPath),
352
- name: tableDefinition.Name,
353
- });
354
- context.tables[tableDefinition.Name] = tableDefinition;
355
- }
356
- //#endregion
357
- //#region documents
358
- manifest.documentDataSources = [];
359
- let datastores = projectFiles.filter(file => file.endsWith(".jschema"));
360
- for (let i = 0; i < datastores.length; i++) {
361
- let datastoreFile = datastores[i];
362
- let document = (await FileUtils_1.default.readJsonFileAsync(datastoreFile));
363
- manifest.documentDataSources.push({
364
- file: StringUtils_1.default.toRelativePath(datastoreFile, projectPath),
365
- name: document.name,
366
- });
367
- context.documents[document.name] = document;
368
- }
369
- //#endregion
370
- //#region processes
371
- manifest.processes = [];
372
- manifest.apis = [];
373
- //TODO handle dependencies too ? for now, it will issue warnings for external calls it cannot verify
374
- let serviceName = manifest.serviceName;
375
- let provider = new codenotch_core_workflow_1.StaticWorkflowDataProvider([manifest], serviceName, Object.values(context.tables).map(t => ({ service: serviceName, model: t })), Object.values(context.documents).map(d => ({ service: serviceName, model: d })));
376
- let bpmns = projectFiles.filter(file => file.endsWith(".bpmn"));
377
- for (let i = 0; i < bpmns.length; i++) {
378
- let bpmnFile = bpmns[i];
379
- await this.generateManifestBpmn(bpmnFile, projectPath, manifest, provider, context);
380
- }
381
- // Ensure all processes defined here are really in the project
382
- manifest.postInstallationProcesses = manifest.postInstallationProcesses.filter((x) => manifest.processes.find((y) => y.processName === x.processName) !== undefined);
383
- //#endregion
384
- //#region jsxtsx
385
- manifest.reactApplications = [];
386
- // Each file ending with .jsx or .tsx with a .manifest.json is considered as a React application
387
- const jsxs = projectFiles.filter(file => file.endsWith(".jsx"));
388
- const tsxs = projectFiles.filter(file => file.endsWith(".tsx"));
389
- let jsxtsxs = [...jsxs, ...tsxs];
390
- for (let i = 0; i < jsxtsxs.length; i++) {
391
- await this.generateManifestReactApp(jsxtsxs[i], projectPath, manifest);
392
- }
393
- //#endregion
394
- /* TODO see if we need that, shouldn't the react build already contain the translations§
395
- let isNodeApp = await FileUtils.exists(FileUtils.normalize(`${project.path}/package.json`));
396
- //#region i18n
397
-
398
- if (isNodeApp && (updateAll || fileType === 'i18n')) {
399
-
400
- let allI18nValues = await I18nUtils.getAllI18nFiles(project.path);
401
- let codenotchOverridePath = StringUtils.normalizePath(`${project.path}/typings/i18n.d.ts`);
402
- let translations: { key: string; argumentCount: number; }[] = [];
403
- for (let item of allI18nValues) {
404
- let allValues = item.values.map(c => c.value).join(' ');
405
- let argMatchs = [...allValues.matchAll(/({([\d ]*)})/gm)];
406
- let argCount = 0;
407
- for (let i = 0; i < argMatchs.length; i++) {
408
- if (allValues.includes(`{${i}}`)) {
409
- argCount++;
410
- }
411
- else {
412
- break;
413
- }
414
- }
415
- translations.push({
416
- key: item.key,
417
- argumentCount: argCount
418
- });
419
- }
420
- translations = translations.sort((a, b) => a.key.localeCompare(b.key));
421
- let codenotchOverride = TsxCompiler.createCodenotchReactI18NOverride(translations);
422
- await FileUtils.writeFileAsync(codenotchOverridePath, codenotchOverride);
423
-
424
-
425
- TsxCompiler.createFile(codenotchOverridePath, codenotchOverride);
426
- }
427
-
428
- if (processChanged && isNodeApp) {
429
- let codenotchOverridePath = StringUtils.normalizePath(`${project.path}/typings/process.d.ts`);
430
- let codenotchOverride = TsxCompiler.createCodenotchReactProcessOverride(manifestCache.processes);
431
- await IdeServices.Files.writeFileAsync(codenotchOverridePath, codenotchOverride);
432
- TsxCompiler.createFile(codenotchOverridePath, codenotchOverride);
433
- }
434
- */
435
- //#endregion
436
- //#region auml
437
- manifest.emails = [];
438
- manifest.pdfs = [];
439
- manifest.applications = [];
440
- manifest.expressComponents = [];
441
- manifest.htmls = [];
442
- let aumls = projectFiles.filter(file => file.endsWith(".auml"));
443
- for (let i = 0; i < aumls.length; i++) {
444
- let aumlFile = aumls[i];
445
- await this.generateManifestAumlApp(aumlFile, projectPath, manifest);
446
- }
447
- // Try add a default index
448
- let hasIndexApp = (manifest.index ?? '').trim() !== '';
449
- if (hasIndexApp === false) {
450
- manifest.index = manifest.applications.length > 0 ? manifest.applications[0].applicationName : undefined;
451
- }
452
- else {
453
- let appExists = manifest.applications.find(c => c.applicationName === manifest?.index) !== undefined;
454
- if (appExists === false) {
455
- manifest.index = undefined;
456
- }
457
- }
458
- //#endregion
459
- //#region scripts
460
- manifest.scripts = [];
461
- let scripts = projectFiles.filter(file => file.endsWith(".js") &&
462
- file.endsWith(".test.js") === false &&
463
- file.endsWith(".spec.js") === false &&
464
- file.endsWith(".config.js") === false);
465
- for (let i = 0; i < scripts.length; i++) {
466
- let scriptFile = scripts[i];
467
- manifest.scripts.push({
468
- file: StringUtils_1.default.toRelativePath(scriptFile, projectPath)
469
- });
470
- }
471
- //#endregion
472
120
  return manifest;
473
121
  }
474
- static async parseBpmn(rawBpmn, provider) {
475
- let validator = new codenotch_core_workflow_1.BpmnToWorkflowDeserializer();
476
- let result = await validator.parse(rawBpmn, provider);
477
- //TODO handle warnigns and errors with BpmnValidator
478
- //return result.bpmn;
479
- return result ?? null;
480
- }
481
- static async generateManifestBpmn(filepath, projectPath, manifest, provider, compilation) {
482
- try {
483
- let bpmnRaw = (await FileUtils_1.default.readFileAsync(filepath));
484
- let model = null;
485
- try {
486
- model = await this.parseBpmn(bpmnRaw, provider);
487
- if (!model) {
488
- compilation.errors.push(`Cannot parse bpmn file ${filepath}`);
489
- return;
490
- }
491
- }
492
- catch (e) {
493
- compilation.errors.push(`Error while parsing bpmn file ${filepath}: ${e.message}`);
494
- return;
495
- }
496
- let processHash = await StringUtils_1.default.sha256(bpmnRaw);
497
- let pools = model.items.filter((e) => e.type === codenotch_core_workflow_1.WorkflowItemType.Pool);
498
- // If there is only one process (ie no pools) we can rely on model.processId
499
- if (!pools || pools.length === 0) {
500
- // Default pool
501
- let pool = {
502
- type: codenotch_core_workflow_1.WorkflowItemType.Pool,
503
- orientation: 'horizontal',
504
- id: "defaultPool",
505
- processId: model.processId,
506
- name: model.processId,
507
- lanes: [],
508
- isTransaction: false,
509
- ignoreLogs: false,
510
- minThreads: 1,
511
- maxThreads: -1,
512
- poolType: codenotch_core_workflow_1.WorkflowPoolType.Public,
513
- x: 0,
514
- y: 0,
515
- width: 800,
516
- height: 600,
517
- priority: codenotch_core_workflow_1.WorkflowPoolPriority.Medium
518
- };
519
- this.generateManifestProcess(filepath, projectPath, pool, model.items, processHash, manifest);
520
- compilation.processes[model.processId] = model;
521
- }
522
- else {
523
- // Otherwise, we need to register each process
524
- for (let pool of pools) {
525
- //TODO other way than checking position ?
526
- //let poolElements = model.elements.filter((e: any) => e instanceof BpmnNodeModel && WorkflowUtils.belongsToPoolOrLane(pool, e));
527
- let poolElements = model.items;
528
- this.generateManifestProcess(filepath, projectPath, pool, poolElements, processHash, manifest);
529
- compilation.processes[pool.processId] = model;
530
- }
531
- }
532
- }
533
- catch (e) {
534
- compilation.errors.push(`Error while parsing bpmn file ${filepath}: ${e.message}`);
535
- }
536
- }
537
- static generateManifestProcess(bpmnFilePath, projectPath, pool, processElements, processHash, manifest) {
538
- try {
539
- // Process and StartEvents
540
- let process = new Codenotch_1.ProjectManifestProcess();
541
- process.file = StringUtils_1.default.toRelativePath(bpmnFilePath, projectPath);
542
- process.processName = `${pool.processId}`;
543
- let startEvents = processElements.filter(c => c.type === codenotch_core_workflow_1.WorkflowItemType.StartEvent ||
544
- c.type === codenotch_core_workflow_1.WorkflowItemType.SignalStartEvent ||
545
- c.type === codenotch_core_workflow_1.WorkflowItemType.ApiStartEvent ||
546
- c.type === codenotch_core_workflow_1.WorkflowItemType.WebhookStartEvent ||
547
- c.type === codenotch_core_workflow_1.WorkflowItemType.TimerStartEvent ||
548
- c.type === codenotch_core_workflow_1.WorkflowItemType.MessageStartEvent ||
549
- c.type === codenotch_core_workflow_1.WorkflowItemType.StandardStartEvent);
550
- let endEvents = processElements.filter(c => c.type === codenotch_core_workflow_1.WorkflowItemType.EndEvent ||
551
- c.type === codenotch_core_workflow_1.WorkflowItemType.ErrorEndEvent ||
552
- c.type === codenotch_core_workflow_1.WorkflowItemType.CancelEndEvent ||
553
- c.type === codenotch_core_workflow_1.WorkflowItemType.SignalEndEvent ||
554
- c.type === codenotch_core_workflow_1.WorkflowItemType.MessageEndEvent ||
555
- c.type === codenotch_core_workflow_1.WorkflowItemType.WebhookEndEvent ||
556
- c.type === codenotch_core_workflow_1.WorkflowItemType.StandardEndEvent ||
557
- c.type === codenotch_core_workflow_1.WorkflowItemType.TerminateEndEvent ||
558
- c.type === codenotch_core_workflow_1.WorkflowItemType.EscalationEndEvent ||
559
- c.type === codenotch_core_workflow_1.WorkflowItemType.CompensationEndEvent ||
560
- c.type === codenotch_core_workflow_1.WorkflowItemType.CallbackEndEvent);
561
- let signals = processElements.filter(c => c.type === codenotch_core_workflow_1.WorkflowItemType.SignalStartEvent ||
562
- c.type === codenotch_core_workflow_1.WorkflowItemType.SignalEndEvent ||
563
- c.type === codenotch_core_workflow_1.WorkflowItemType.ThrowSignalIntermediateEvent ||
564
- c.type === codenotch_core_workflow_1.WorkflowItemType.CatchSignalIntermediateEvent);
565
- startEvents.forEach(startEvent => {
566
- let processStart = new Codenotch_1.ProjectManifestProcessStartEvent();
567
- processStart.kind = 'not implemented';
568
- switch (startEvent.type) {
569
- case codenotch_core_workflow_1.WorkflowItemType.StartEvent:
570
- processStart.kind = 'manual';
571
- break;
572
- case codenotch_core_workflow_1.WorkflowItemType.SignalStartEvent:
573
- processStart.kind = 'signal';
574
- break;
575
- case codenotch_core_workflow_1.WorkflowItemType.ApiStartEvent:
576
- processStart.kind = 'api';
577
- break;
578
- case codenotch_core_workflow_1.WorkflowItemType.WebhookStartEvent:
579
- processStart.kind = 'webhook';
580
- break;
581
- case codenotch_core_workflow_1.WorkflowItemType.TimerStartEvent:
582
- processStart.kind = 'timer';
583
- break;
584
- case codenotch_core_workflow_1.WorkflowItemType.MessageStartEvent:
585
- processStart.kind = 'message';
586
- break;
587
- case codenotch_core_workflow_1.WorkflowItemType.StandardStartEvent:
588
- processStart.kind = 'standard';
589
- break;
590
- }
591
- processStart.nodeId = startEvent.id;
592
- processStart.scope = pool.type;
593
- //TODO This not yet supported
594
- //processStart.roles = WorkflowUtils.getRolesOfStartNode(startEvent as BpmnNodeModel, pool.swimlanes);
595
- let evtNode = startEvent;
596
- let eventDefinitions = evtNode.eventDefinitions;
597
- // Only take the first definition into account
598
- //TODO ?
599
- if (eventDefinitions && eventDefinitions.length > 0) {
600
- let evtDef = eventDefinitions[0];
601
- if (evtNode.outputs && evtNode.outputs.length > 0) {
602
- let parameters = evtNode.outputs[0].outputVariables;
603
- let input = {
604
- id: 'input',
605
- value: '',
606
- name: 'input',
607
- type: codenotch_core_1.VariableType.object,
608
- objectType: parameters,
609
- isSecret: false
610
- };
611
- processStart.input = ProjectCompilationUtils.ProcessVariableToJsonSchema(input);
612
- }
613
- else {
614
- processStart.input = {};
615
- }
616
- }
617
- process.startEvents.push(processStart);
618
- });
619
- signals.forEach(signal => {
620
- let processSignal = new Codenotch_1.ProjectManigestSignal();
621
- processSignal.type = 'not implemented';
622
- let eventNode = signal;
623
- let signalModel = eventNode.eventDefinitions[0];
624
- processSignal.signalId = signalModel.signalId;
625
- switch (signal.type) {
626
- case codenotch_core_workflow_1.WorkflowItemType.SignalStartEvent:
627
- processSignal.type = 'start';
628
- break;
629
- case codenotch_core_workflow_1.WorkflowItemType.SignalEndEvent:
630
- processSignal.type = 'end';
631
- break;
632
- case codenotch_core_workflow_1.WorkflowItemType.ThrowSignalIntermediateEvent:
633
- processSignal.type = 'throw';
634
- break;
635
- case codenotch_core_workflow_1.WorkflowItemType.CatchSignalIntermediateEvent:
636
- processSignal.type = 'catch';
637
- break;
638
- }
639
- process.signals.push(processSignal);
640
- });
641
- // Create a merged output from all end events of the process
642
- //let mergedOutput: CodeVariable[] = [];
643
- //TODO not sure we need the end event, we don't really use it and it takes space in the manifest
644
- /*
645
- endEvents.forEach(endEvent => {
646
-
647
- let eventDefinitions = (endEvent as EventNodeModel).eventDefinitions;
648
-
649
- // We are only interested in data definition, other definitions don't change the process output
650
- let dataDef = eventDefinitions.find((x: any) => x instanceof DataEventDefinitionModel) as DataEventDefinitionModel;
651
-
652
- // For api end events...
653
- if (dataDef === undefined) {
654
- dataDef = eventDefinitions.find((x: any) => x instanceof CallbackEventDefinitionModel) as CallbackEventDefinitionModel;
655
- }
656
-
657
- // Add parameters to the merged output
658
- if (dataDef)
659
- mergedOutput = mergedOutput.concat(dataDef.parameters as any);
660
- });
661
-
662
-
663
- // Remove duplicates (variables with the same name)
664
- let seen = new Set();
665
- mergedOutput = mergedOutput.filter(x => seen.has(x.name) ? false : seen.add(x.name));
122
+ }
123
+ exports.default = ProjectCompilationUtils;
124
+ class TypescriptUtils {
125
+ /**
126
+ * Read TS table definition file like:
127
+ * ```ts
128
+ import { defineEntity, type InferEntity, p } from '@codenotch/orm';
129
+
130
+ export const User = defineEntity({
131
+ name: 'User',
132
+ properties: {
133
+ id: p.integer().primary(),
134
+ fullName: p.string(),
135
+ email: p.string()
136
+ },
137
+ });
666
138
 
667
- let output: CodeVariable = {
668
- name: 'output',
669
- type: VariableType.MAP,
670
- childVariables: mergedOutput,
671
- listElement: null,
672
- isSecret: false,
673
- enum: null
674
- };
675
- process.endEvent = ProjectCompilationUtils.ProcessVariableToJsonSchema(output);
676
- */
677
- process.priority = pool.priority;
678
- process.minThreads = pool.minThreads;
679
- process.maxThreads = pool.maxThreads;
680
- // Each process has a unique hash that can be used to optimize the deployment
681
- //@ts-ignore
682
- process.hash = processHash;
683
- manifest.processes.push(process);
684
- // Apis
685
- processElements.forEach(e => {
686
- let eventDefinitions = e.eventDefinitions;
687
- if (eventDefinitions) {
688
- eventDefinitions.forEach((def) => {
689
- if (def.route && def.method) {
690
- let api = new Codenotch_1.ProjectManifestApi();
691
- api.method = def.method;
692
- api.path = def.route;
693
- api.bpmn = process.processName;
694
- api.startNode = e.id;
695
- api.accept = def.accept;
696
- api.whitelist = def.whitelist;
697
- api.priority = pool.priority;
698
- api.minThreads = pool.minThreads;
699
- api.maxThreads = pool.maxThreads;
700
- def.parameters.forEach((p) => {
701
- // TODO ?
702
- });
703
- manifest.apis.push(api);
704
- }
705
- });
706
- }
707
- });
708
- }
709
- catch (e) {
710
- console.log("Cannot save bpmn", bpmnFilePath, e);
711
- }
712
- }
713
- static ProcessVariableToJsonSchema(variable) {
714
- let schema = {};
715
- schema.type = ProjectCompilationUtils.ProcessVariableTypeToJsonSchemaTypeName(variable.type);
716
- if (variable.type === codenotch_core_1.VariableType.object) {
717
- schema.properties = {};
718
- for (let child of variable.objectType ?? []) {
719
- schema.properties[child.name] = ProjectCompilationUtils.ProcessVariableToJsonSchema(child);
720
- }
721
- }
722
- else if (variable.type === codenotch_core_1.VariableType.array) {
723
- if (variable.arrayType)
724
- schema.items = ProjectCompilationUtils.ProcessVariableToJsonSchema(variable.arrayType);
725
- }
726
- return schema;
139
+ export type IUser = InferEntity<typeof User>;
140
+ * ```
141
+ *
142
+ * And returns the table structure(s) (can have multiple table in one file)
143
+ */
144
+ static async parseTablesFromScript(ts) {
145
+ // TODO
146
+ return [];
727
147
  }
728
- static ProcessVariableTypeToJsonSchemaTypeName(type) {
729
- switch (type) {
730
- case codenotch_core_1.VariableType.string:
731
- return "string";
732
- case codenotch_core_1.VariableType.int:
733
- return "integer";
734
- case codenotch_core_1.VariableType.float:
735
- return "number";
736
- case codenotch_core_1.VariableType.bool:
737
- return "boolean";
738
- case codenotch_core_1.VariableType.array:
739
- return "array";
740
- case codenotch_core_1.VariableType.object:
741
- return "object";
742
- case codenotch_core_1.VariableType.enum:
743
- return "string";
744
- case codenotch_core_1.VariableType.function:
745
- return "object";
746
- }
148
+ /**
149
+ * Find all file (recursivly) in a given folder (workspacePath) that contains a table declaration ('defineEntity').
150
+ */
151
+ static async discoverTableFiles(workspacePath) {
747
152
  }
748
- static async generateManifestReactApp(filePath, projectPath, manifest) {
749
- try {
750
- let ext = filePath.split('.').pop();
751
- let manifestPath = filePath.replace(`.${ext}`, '.manifest.json');
752
- if (await FileUtils_1.default.exists(manifestPath) === false) {
753
- return;
754
- }
755
- let appManifest = JSON.parse((await FileUtils_1.default.readFileAsync(manifestPath)));
756
- let fileName = StringUtils_1.default.getFilenameFromUri(filePath);
757
- let reactAppmanifest = new Codenotch_1.ProjectManifestReactApplication();
758
- reactAppmanifest.file = StringUtils_1.default.toRelativePath(filePath, projectPath);
759
- reactAppmanifest.roles = appManifest.auml?.roles ?? [];
760
- reactAppmanifest.scope = appManifest.auml?.scope ?? 'Public';
761
- reactAppmanifest.applicationName = fileName.replace(`.${ext}`, '');
762
- manifest.reactApplications = manifest.reactApplications ?? [];
763
- manifest.reactApplications.push(reactAppmanifest);
764
- }
765
- catch (e) {
766
- console.error("Cannot generateManifestReactApp", filePath, e);
767
- }
153
+ /**
154
+ * Find all file (recursivly) in a given folder (workspacePath) that contains a table declaration ('defineDocument').
155
+ */
156
+ static async discoverDocumentFiles(workspacePath) {
768
157
  }
769
- static async generateManifestAumlApp(filePath, projectPath, manifest) {
770
- try {
771
- // Read file
772
- let auml = await FileUtils_1.default.readFileAsync(filePath);
773
- if (!auml) {
774
- return;
775
- }
776
- let fileName = filePath.includes("/") ? filePath.split("/").pop() :
777
- filePath.includes("\\") ? filePath.split("\\").pop() :
778
- filePath;
779
- // Figure out if this is an application or an express component
780
- let trimmedAuml = auml.replace(/^\s+|\s+$/g, '');
781
- if (trimmedAuml.startsWith("<Application")) {
782
- // Application
783
- let application = new Codenotch_1.ProjectManifestApplication();
784
- application.file = StringUtils_1.default.toRelativePath(filePath, projectPath);
785
- application.roles = [];
786
- let match = auml.match(/<Application[^>]*?Name="(.*?)"/);
787
- application.applicationName = fileName.replace(".auml", "");
788
- if (match) {
789
- let appName = match[1];
790
- if (appName) {
791
- application.applicationName = appName;
792
- }
793
- }
794
- // Roles are now defined manually in manifest editor
795
- // Search for roles in the application
796
- match = auml.match(/<Application[^>]*?Role="(.*?)"/);
797
- if (match) {
798
- application.roles = [match[1]];
799
- }
800
- // Search for a scope in the application
801
- match = auml.match(/<Application[^>]*?Scope="(.*?)"/);
802
- if (match) {
803
- let scope = match[1];
804
- if (scope !== "Internal" && scope !== "External")
805
- application.scope = "Public"; // if scope is not recognized, default to public
806
- else
807
- application.scope = scope;
808
- }
809
- else {
810
- application.scope = "Public";
811
- }
812
- manifest.applications.push(application);
813
- }
814
- else if (trimmedAuml.startsWith("<Component")) {
815
- let findComponentNameRegexp = /<Component[^>]*?Name="([\S]*?)"/m;
816
- let match = auml.match(findComponentNameRegexp);
817
- if (match) {
818
- // Express component
819
- let expressComponent = new Codenotch_1.ProjectManifestExpressComponent();
820
- expressComponent.componentName = match[1];
821
- expressComponent.file = StringUtils_1.default.toRelativePath(filePath, projectPath);
822
- manifest.expressComponents.push(expressComponent);
823
- }
824
- }
825
- else if (trimmedAuml.startsWith("<PDF")) {
826
- let pdf = new Codenotch_1.ProjectManifestPdf();
827
- pdf.name = fileName.replace(".auml", "");
828
- pdf.file = StringUtils_1.default.toRelativePath(filePath, projectPath);
829
- manifest.pdfs.push(pdf);
830
- }
831
- else if (trimmedAuml.startsWith("<Email")) {
832
- let email = new Codenotch_1.ProjectManifestEmail();
833
- email.name = fileName.replace(".auml", "");
834
- email.file = StringUtils_1.default.toRelativePath(filePath, projectPath);
835
- manifest.emails.push(email);
836
- }
837
- else if (trimmedAuml.startsWith("<HTML")) {
838
- let html = new Codenotch_1.ProjectManifestHtml();
839
- html.name = fileName.replace(".auml", "");
840
- html.file = StringUtils_1.default.toRelativePath(filePath, projectPath);
841
- manifest.htmls.push(html);
842
- }
843
- }
844
- catch (e) {
845
- console.error("Cannot save auml", filePath, e);
846
- }
158
+ /**
159
+ * Find all file (recursivly) in a given folder (workspacePath) that contains a table declaration ('process').
160
+ */
161
+ static async discoverProcessFiles(workspacePath) {
847
162
  }
848
163
  }
849
- exports.default = ProjectCompilationUtils;
850
164
  //# sourceMappingURL=ProjectCompilationUtils.js.map