mushroom-cli 1.2.0-alpha.11 → 1.2.0-alpha.13

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 (43) hide show
  1. package/README.md +233 -223
  2. package/dist/check-update.js +5 -0
  3. package/dist/common.js +260 -0
  4. package/dist/config.js +394 -0
  5. package/dist/docs/docs.v2.js +1907 -0
  6. package/dist/gen/gen-api-docs-v1.js +110 -0
  7. package/dist/gen/gen-api-docs.js +295 -0
  8. package/{gen → dist/gen}/gen-csharp.js +1265 -1399
  9. package/{gen → dist/gen}/gen-db-docs.js +204 -222
  10. package/{gen → dist/gen}/gen-js-driver-tarball.js +81 -101
  11. package/{gen → dist/gen}/gen-js-driver.js +116 -133
  12. package/{gen → dist/gen}/gen-ts-driver.js +427 -467
  13. package/{gen.js → dist/gen.js} +109 -124
  14. package/{help.js → dist/help.js} +53 -55
  15. package/dist/init/init-json.js +91 -0
  16. package/dist/init/init-netcore.js +30 -0
  17. package/dist/init.js +23 -0
  18. package/dist/master-file/master-file.js +185 -0
  19. package/dist/merge.js +70 -0
  20. package/dist/mr.js +75 -0
  21. package/dist/types.js +1 -0
  22. package/dist/update/tsCode.js +82 -0
  23. package/dist/update.js +20 -0
  24. package/package.json +55 -29
  25. package/check-update.js +0 -9
  26. package/common.js +0 -283
  27. package/config.js +0 -445
  28. package/docs/docs.v2.js +0 -1633
  29. package/gen/gen-api-docs-v1.js +0 -125
  30. package/gen/gen-api-docs.js +0 -298
  31. package/init/init-json.js +0 -106
  32. package/init/init-netcore.js +0 -32
  33. package/init.js +0 -28
  34. package/master-file/master-file.js +0 -234
  35. package/merge.js +0 -84
  36. package/mr.js +0 -82
  37. package/update/tsCode.js +0 -20
  38. package/update.js +0 -24
  39. /package/{docs → dist/docs}/doc-mt.js +0 -0
  40. /package/{docs → dist/docs}/docs.html +0 -0
  41. /package/{docs → dist/docs}/docs.v2.html +0 -0
  42. /package/{docs → dist/docs}/mt-dom-1.0.js +0 -0
  43. /package/{docs → dist/docs}/mt.extension.js +0 -0
@@ -0,0 +1,110 @@
1
+ import fs from 'fs';
2
+ import open from 'open';
3
+ import jsdom, { JSDOM } from 'jsdom';
4
+ import { fileURLToPath } from 'url';
5
+ import path from 'path';
6
+ import * as common from '../common.js';
7
+ const __filename = fileURLToPath(import.meta.url);
8
+ const __dirname = path.dirname(__filename);
9
+ function processGenDocs(aliasProject, entities, source, html, args, projectName, alias) {
10
+ common.logInfo('Received html');
11
+ common.logInfo('Parsing html');
12
+ const roles = aliasProject.allowRoles?.includes('*')
13
+ ? source.roles
14
+ : source.roles?.filter((r) => aliasProject.allowRoles?.includes(r.name));
15
+ html = html.replace(/^\uFEFF/, '');
16
+ html = html.replace(/<script src="([^"]+)" data-mt-cond='\{"lazy-load": 1\}'><\/script>/g, (scriptTag, src) => `<script data-mt-cond='{"x": 1}'>${fs.readFileSync(__dirname + '/../docs/' + src).toString()}</script>`);
17
+ html = html.replace('</body>', `<script data-mt-cond='{"x": 1}'>
18
+ window.data.name = ${JSON.stringify(source.name)};
19
+ window.data.description = ${JSON.stringify(source.description)};
20
+ window.data.rootUrl = ${JSON.stringify(common.getRootUrl(source))};
21
+ window.data.environmentVariables = ${JSON.stringify(source.environmentVariables)};
22
+ window.data.roles = ${JSON.stringify(roles)};
23
+ window.data.entities = ${JSON.stringify(entities)};
24
+ window.data.features = ${JSON.stringify(aliasProject.features)};
25
+ try {
26
+ console.info("MUSHROOM-CLI: START");
27
+ window.generateDocument();
28
+ console.info("MUSHROOM-CLI: FINISH");
29
+ }
30
+ catch (e) {
31
+ console.info("MUSHROOM-CLI: FAIL", e);
32
+ }
33
+ window.close();
34
+ </script></body>`);
35
+ return new Promise((resolve, reject) => {
36
+ const virtualConsole = new jsdom.VirtualConsole();
37
+ virtualConsole.on('info', function (msg, err) {
38
+ if (typeof msg != 'string')
39
+ return;
40
+ if (msg.indexOf('MUSHROOM-CLI:') === 0) {
41
+ common.logInfo('GenDocEngine:', msg.substring('MUSHROOM-CLI:'.length));
42
+ }
43
+ if (msg === 'MUSHROOM-CLI: FAIL') {
44
+ reject(err);
45
+ return;
46
+ }
47
+ if (msg !== 'MUSHROOM-CLI: FINISH')
48
+ return;
49
+ const code = '<!DOCTYPE html>' + dom.window.document.documentElement.outerHTML;
50
+ if (args[3] === 'tmp') {
51
+ const htmlFilePath = aliasProject.output + '_tmp.html';
52
+ common.logInfo('Writing to', htmlFilePath);
53
+ fs.writeFile(htmlFilePath, code, (err) => {
54
+ if (err) {
55
+ reject(err);
56
+ return;
57
+ }
58
+ common.logInfo('Opening file', htmlFilePath);
59
+ open(htmlFilePath)
60
+ .then(() => {
61
+ setTimeout(() => {
62
+ fs.unlink(htmlFilePath, (ex) => {
63
+ if (ex)
64
+ common.logError('Unable to delete file', htmlFilePath);
65
+ });
66
+ }, 1000);
67
+ })
68
+ .catch(() => common.logError('Unable to open', htmlFilePath));
69
+ resolve();
70
+ });
71
+ return;
72
+ }
73
+ common.ensureFolder(aliasProject.output);
74
+ common.logInfo('Writing to', aliasProject.output);
75
+ fs.writeFile(aliasProject.output, code, (err) => {
76
+ if (err) {
77
+ reject(err);
78
+ return;
79
+ }
80
+ common.logInfo(`Generated API docs for ${projectName}@${alias} to ${aliasProject.output}`);
81
+ resolve();
82
+ });
83
+ });
84
+ const dom = new JSDOM(html, {
85
+ runScripts: 'dangerously',
86
+ resources: 'usable',
87
+ virtualConsole: virtualConsole,
88
+ });
89
+ common.logInfo('Rendering API document');
90
+ });
91
+ }
92
+ export default async function genDocs(args, projectName, project, alias, source) {
93
+ const aliasProject = ((project.docs || {}).alias || {})[alias];
94
+ if (!aliasProject) {
95
+ throw new Error(`Not found gen docs configuration. Please run 'npx mushroom-cli config ${projectName} gen docs OUTPUT_FILE.html${alias === 'default' ? '' : ' alias ' + alias}' first`);
96
+ }
97
+ common.logWarning('[DEPRECATED] Use GenDocEngine v1');
98
+ const entities = common.getEntities(source, aliasProject.allowRoles);
99
+ if (Array.isArray(aliasProject.entities)) {
100
+ for (const entityName in entities) {
101
+ if (Object.hasOwnProperty.call(entities, entityName)) {
102
+ if (aliasProject.entities.every((re) => !new RegExp(re).test(entityName))) {
103
+ delete entities[entityName];
104
+ }
105
+ }
106
+ }
107
+ }
108
+ const html = fs.readFileSync(__dirname + '/../docs/docs.html').toString();
109
+ await processGenDocs(aliasProject, entities, source, html, args, projectName, alias);
110
+ }
@@ -0,0 +1,295 @@
1
+ import fs from 'fs';
2
+ import open from 'open';
3
+ import { minify } from 'minify';
4
+ import { fileURLToPath } from 'url';
5
+ import path from 'path';
6
+ import * as common from '../common.js';
7
+ const __filename = fileURLToPath(import.meta.url);
8
+ const __dirname = path.dirname(__filename);
9
+ function reserveWhitelist(obj, whitelist) {
10
+ if (!obj && typeof obj !== 'object')
11
+ return null;
12
+ for (const m in obj) {
13
+ if (!whitelist.includes(m))
14
+ delete obj[m];
15
+ }
16
+ return obj;
17
+ }
18
+ const environmentVariableWhitelist = ['type', 'description'];
19
+ function filterEnvironmentVariables(environmentVariables) {
20
+ if (!environmentVariables)
21
+ return;
22
+ Object.values(environmentVariables).forEach((env) => reserveWhitelist(env, environmentVariableWhitelist));
23
+ }
24
+ const entityWhitelist = ['name', 'description', 'actions', 'views', 'features', 'fields'];
25
+ const actionWhitelist = ['grant', 'deny', 'matches', 'description', 'exclude'];
26
+ const findByIdWhitelist = [...actionWhitelist, 'returnableFields', 'defaultFields'];
27
+ const findManyWhitelist = [
28
+ ...findByIdWhitelist,
29
+ 'allowFilteringFields',
30
+ 'requiredFilteringFields',
31
+ 'allowSortings',
32
+ 'defaultSortings',
33
+ 'pagingType',
34
+ 'maxPageSize',
35
+ 'pageSize',
36
+ 'includeTotal',
37
+ 'cache',
38
+ ];
39
+ const generalWhitelist = [...actionWhitelist, 'codeHint'];
40
+ const entityFeatureWhitelist = ['vn_text'];
41
+ const vnTextWhitelist = ['fields', 'channels'];
42
+ const vnTextChannelWhitelist = ['fields', 'name'];
43
+ const actionCodeHintWhitelist = ['delegator'];
44
+ const actionCodeHintDelegatorWhitelist = ['param', 'requestBody'];
45
+ const fieldsOnlyWhitelist = ['fields'];
46
+ const viewWhitelist = ['grant', 'deny', 'description', 'parameters', 'emptyResult', 'codeHint'];
47
+ const viewCodeHintWhitelist = ['output'];
48
+ function filterEntities(entities) {
49
+ Object.values(entities).forEach((entity) => {
50
+ filterEntityFields(entity);
51
+ if (!reserveWhitelist(entity, entityWhitelist))
52
+ return;
53
+ const entityActions = entity.actions ?? {};
54
+ Object.keys(entityActions).forEach((actionName) => {
55
+ const actions = entityActions[actionName];
56
+ switch (actionName) {
57
+ case 'findMany':
58
+ actions.forEach((action) => reserveWhitelist(action, findManyWhitelist));
59
+ break;
60
+ case 'findById':
61
+ actions.forEach((action) => reserveWhitelist(action, findByIdWhitelist));
62
+ break;
63
+ case 'createOne':
64
+ case 'createMany':
65
+ case 'updateOne':
66
+ case 'updateMany':
67
+ case 'updatePartially':
68
+ case 'deleteOne':
69
+ case 'deleteMany':
70
+ actions.forEach((action) => reserveWhitelist(action, actionWhitelist));
71
+ break;
72
+ default:
73
+ actions.forEach((action) => {
74
+ reserveWhitelist(action, generalWhitelist);
75
+ if (!action.codeHint)
76
+ return;
77
+ if (!reserveWhitelist(action.codeHint, actionCodeHintWhitelist))
78
+ return;
79
+ if (!action.codeHint.delegator)
80
+ return;
81
+ if (!reserveWhitelist(action.codeHint.delegator, actionCodeHintDelegatorWhitelist))
82
+ return;
83
+ reserveWhitelist(action.codeHint.delegator.param, fieldsOnlyWhitelist);
84
+ reserveWhitelist(action.codeHint.delegator.requestBody, fieldsOnlyWhitelist);
85
+ });
86
+ break;
87
+ }
88
+ });
89
+ const entityViews = entity.views ?? {};
90
+ Object.keys(entityViews).forEach((viewName) => {
91
+ const views = entityViews[viewName];
92
+ views.forEach((view) => {
93
+ reserveWhitelist(view, viewWhitelist);
94
+ if (!view.codeHint)
95
+ return;
96
+ if (!reserveWhitelist(view.codeHint, viewCodeHintWhitelist))
97
+ return;
98
+ reserveWhitelist(view.codeHint.output, fieldsOnlyWhitelist);
99
+ });
100
+ });
101
+ if (entity.features) {
102
+ reserveWhitelist(entity.features, entityFeatureWhitelist);
103
+ reserveWhitelist(entity.features.vn_text, vnTextWhitelist);
104
+ entity.features.vn_text.channels?.forEach((channel) => reserveWhitelist(channel, vnTextChannelWhitelist));
105
+ }
106
+ });
107
+ }
108
+ function flattenFields(fields, dict, prefix) {
109
+ dict ?? (dict = {});
110
+ prefix ?? (prefix = '');
111
+ for (const m in fields) {
112
+ const path = prefix ? prefix + '.' + m : m;
113
+ dict[path] = false;
114
+ const config = fields[m];
115
+ if (config.type == 'object') {
116
+ flattenFields(config.fields ?? {}, dict, path);
117
+ }
118
+ else if (config.type == 'array' && config.items && config.items.type == 'object') {
119
+ flattenFields(config.items.fields ?? {}, dict, path);
120
+ }
121
+ }
122
+ return dict;
123
+ }
124
+ function removeDisallowedFields(fields, dict) {
125
+ const allowFields = Object.keys(dict);
126
+ if (!allowFields.length)
127
+ return;
128
+ reserveWhitelist(fields, allowFields);
129
+ for (const m in fields) {
130
+ const config = fields[m];
131
+ if (config.type == 'object') {
132
+ removeDisallowedFields(config.fields ?? {}, dict[m]);
133
+ }
134
+ else if (config.type == 'array' && config.items && config.items.type == 'object') {
135
+ removeDisallowedFields(config.items.fields ?? {}, dict[m]);
136
+ }
137
+ }
138
+ }
139
+ function markAllowFields(allowFields, dict) {
140
+ if (!Array.isArray(allowFields))
141
+ return;
142
+ allowFields.forEach((field) => (dict[field] = true));
143
+ }
144
+ function markIncludedFields(excludedFields, dict) {
145
+ if (!Array.isArray(excludedFields))
146
+ return;
147
+ for (const m in dict) {
148
+ if (!dict[m] && !excludedFields.includes(m))
149
+ dict[m] = true;
150
+ }
151
+ }
152
+ function filterEntityFields(entity) {
153
+ const dict = flattenFields(entity.fields);
154
+ const entityActions = entity.actions ?? {};
155
+ Object.keys(entityActions).forEach((actionName) => {
156
+ const actions = entityActions[actionName];
157
+ switch (actionName) {
158
+ case 'findMany':
159
+ case 'findById':
160
+ actions.forEach((action) => {
161
+ markAllowFields(action.returnableFields, dict);
162
+ markAllowFields(action.defaultFields, dict);
163
+ });
164
+ break;
165
+ case 'createOne':
166
+ case 'createMany':
167
+ case 'updateOne':
168
+ case 'updateMany':
169
+ case 'updatePartially':
170
+ actions.forEach((action) => markIncludedFields(action.exclude, dict));
171
+ break;
172
+ }
173
+ });
174
+ const allowFields = Object.keys(dict).filter((m) => dict[m]);
175
+ [...allowFields].forEach((shortField) => {
176
+ shortField += '.';
177
+ allowFields
178
+ .map((longerField, i) => (longerField.includes(shortField) ? i : -1))
179
+ .filter((i) => i !== -1)
180
+ .reverse()
181
+ .forEach((i) => allowFields.splice(i, 1));
182
+ });
183
+ const whitelist = {};
184
+ allowFields.forEach((fields) => {
185
+ let obj = whitelist;
186
+ fields.split('.').forEach((name) => {
187
+ let child = obj[name];
188
+ if (!child)
189
+ child = obj[name] = {};
190
+ obj = child;
191
+ });
192
+ });
193
+ Object.keys(entityActions).forEach((actionName) => {
194
+ const actions = entityActions[actionName];
195
+ switch (actionName) {
196
+ case 'createOne':
197
+ case 'createMany':
198
+ case 'updateOne':
199
+ case 'updateMany':
200
+ case 'updatePartially':
201
+ actions.forEach((action) => (action.exclude = action.exclude?.filter((field) => allowFields.includes(field))));
202
+ break;
203
+ }
204
+ });
205
+ removeDisallowedFields(entity.fields, whitelist);
206
+ }
207
+ async function writeDocs(filePath, strTemplate, strData) {
208
+ const placeholder = '<script id="INJECT-JAVASCRIPT-HERE"></script>';
209
+ const idx = strTemplate.indexOf(placeholder);
210
+ fs.writeFileSync(filePath, strTemplate.substring(0, idx));
211
+ fs.appendFileSync(filePath, '<script>window.docs = ');
212
+ fs.appendFileSync(filePath, strData);
213
+ fs.appendFileSync(filePath, ';\n');
214
+ fs.appendFileSync(filePath, fs.readFileSync(path.join(__dirname, '../docs/docs.v2.js')));
215
+ fs.appendFileSync(filePath, '</script>');
216
+ fs.appendFileSync(filePath, strTemplate.substring(idx + placeholder.length));
217
+ fs.writeFileSync(filePath, await minify(filePath, {
218
+ html: {
219
+ removeComments: true,
220
+ collapseWhitespace: true,
221
+ collapseBooleanAttributes: true,
222
+ removeAttributeQuotes: true,
223
+ removeRedundantAttributes: true,
224
+ useShortDoctype: true,
225
+ removeEmptyAttributes: true,
226
+ removeEmptyElements: false,
227
+ removeOptionalTags: true,
228
+ removeScriptTypeAttributes: false,
229
+ removeStyleLinkTypeAttributes: true,
230
+ minifyJS: true,
231
+ minifyCSS: true,
232
+ html5: true,
233
+ },
234
+ }));
235
+ }
236
+ export default async function genDocs(args, projectName, project, alias, source) {
237
+ const aliasProject = ((project.docs || {}).alias || {})[alias];
238
+ if (!aliasProject) {
239
+ throw new Error(`Not found gen docs configuration. Please run 'npx mushroom-cli config ${projectName} gen docs OUTPUT_FILE.html${alias === 'default' ? '' : ' alias ' + alias}' first`);
240
+ }
241
+ common.logInfo('Use GenDocEngine v1.2');
242
+ const entities = common.getEntities(source, aliasProject.allowRoles);
243
+ if (Array.isArray(aliasProject.entities)) {
244
+ for (const entityName in entities) {
245
+ if (Object.hasOwnProperty.call(entities, entityName)) {
246
+ if (aliasProject.entities.every((re) => !new RegExp(re).test(entityName))) {
247
+ delete entities[entityName];
248
+ }
249
+ }
250
+ }
251
+ }
252
+ filterEnvironmentVariables(source.environmentVariables);
253
+ filterEntities(entities);
254
+ const data = JSON.stringify({
255
+ info: {
256
+ name: source.name,
257
+ rootUrl: source.codeHint?.rootUrl ?? source.rootUrl,
258
+ description: source.description,
259
+ security: source.security === undefined
260
+ ? undefined
261
+ : {
262
+ crossDomain: source.security.crossDomain,
263
+ allowOrigins: source.security.allowOrigins,
264
+ },
265
+ },
266
+ features: aliasProject.features,
267
+ roles: common.filterRoles(source.roles ?? [], aliasProject.allowRoles ?? ['*']),
268
+ environmentVariables: source.environmentVariables,
269
+ entities: entities,
270
+ });
271
+ const html = fs.readFileSync(__dirname + '/../docs/docs.v2.html').toString();
272
+ if (args[3] === 'tmp') {
273
+ const htmlFilePath = aliasProject.output + '_tmp.html';
274
+ common.logInfo('Writing to', htmlFilePath);
275
+ await writeDocs(htmlFilePath, html, data);
276
+ common.logInfo('Opening file ', htmlFilePath);
277
+ try {
278
+ await open(htmlFilePath);
279
+ setTimeout(() => {
280
+ fs.unlink(htmlFilePath, (ex) => {
281
+ if (ex)
282
+ common.logError('Unable to delete file', htmlFilePath);
283
+ });
284
+ }, 1000);
285
+ }
286
+ catch {
287
+ common.logError('Unable to open', htmlFilePath);
288
+ }
289
+ return;
290
+ }
291
+ common.ensureFolder(aliasProject.output);
292
+ common.logInfo('Writing to', aliasProject.output);
293
+ await writeDocs(aliasProject.output, html, data);
294
+ common.logInfo(`Generated API docs for ${projectName}@${alias} to ${aliasProject.output}`);
295
+ }