mushroom-cli 1.1.0-alpha.1 → 1.1.0-alpha.12

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/README.md CHANGED
@@ -26,6 +26,10 @@ Config gen javascript driver
26
26
 
27
27
  npx mr config gen projectName js-driver ./src/api/mushroom.api.js [alias aliasName] [roles Admin,User-Contributor] [tarball tarballName]
28
28
 
29
+ Config gen typescript driver
30
+
31
+ npx mr config gen projectName ts-driver ./src/api/mushroom.api.ts [alias aliasName] [roles Admin,User-Contributor]
32
+
29
33
  Config gen entities for Mushroom project in CSharp and using MongoDb
30
34
 
31
35
  npx mr config gen projectName c#-mongo ./API/Generated.cs [alias aliasName]
@@ -44,10 +48,18 @@ Generate database docs (html format)
44
48
 
45
49
  npx mr gen projectName[@aliasName] db-docs [tmp]
46
50
 
51
+ Generate npm package (tarball file)
52
+
53
+ npx mr gen projectName[@aliasName] js-driver-tarball
54
+
47
55
  Generate javascript driver
48
56
 
49
57
  npx mr gen projectName[@aliasName] js-driver
50
58
 
59
+ Generate typescript driver
60
+
61
+ npx mr gen projectName[@aliasName] ts-driver
62
+
51
63
  Generate entities for Mushroom project in CSharp and using MongoDb
52
64
 
53
65
  npx mr gen projectName[@aliasName] c#-mongo
package/check-update.js CHANGED
@@ -2,7 +2,7 @@ const fetch = require('node-fetch');
2
2
 
3
3
 
4
4
  function checkUpdate() {
5
- return fetch('https://registry.npmjs.org/mushroom-cli/latest')
5
+ return fetch('https://registry.npmjs.org/mushroom-cli/')
6
6
  .then(res => res.json());
7
7
  }
8
8
 
package/common.js CHANGED
@@ -1,11 +1,11 @@
1
1
  const fs = require("fs");
2
2
 
3
- function ensureFolder(path) {
3
+ function ensureFolder(path, isFolder) {
4
4
  const index = path.lastIndexOf("/");
5
- if (index <= 0){
5
+ if (!isFolder && index <= 0){
6
6
  return;
7
7
  }
8
- path = path.substr(0, index);
8
+ if (!isFolder) path = path.substring(0, index);
9
9
  if (path === "." || path === "..")
10
10
  return;
11
11
 
package/config.js CHANGED
@@ -75,8 +75,8 @@ function configGenDocs(args, mushroomConfig, projectName){
75
75
  const strRoles = args[index];
76
76
  if (strRoles) {
77
77
  const minusIndex = strRoles.indexOf("-");
78
- let grantedRoles = minusIndex == -1 ? strRoles : strRoles.substr(0, minusIndex);
79
- const deniedRoles = minusIndex == -1 ? "" : strRoles.substr(minusIndex + 1);
78
+ let grantedRoles = minusIndex == -1 ? strRoles : strRoles.substring(0, minusIndex);
79
+ const deniedRoles = minusIndex == -1 ? "" : strRoles.substring(minusIndex + 1);
80
80
  if (!grantedRoles)
81
81
  grantedRoles = "*";
82
82
  parameters.allowRoles = grantedRoles.split(",");
@@ -173,8 +173,8 @@ function configGenJavascriptDriver(args, mushroomConfig, projectName){
173
173
  const strRoles = args[index];
174
174
  if (strRoles) {
175
175
  const minusIndex = strRoles.indexOf("-");
176
- let grantedRoles = minusIndex == -1 ? strRoles : strRoles.substr(0, minusIndex);
177
- const deniedRoles = minusIndex == -1 ? "" : strRoles.substr(minusIndex + 1);
176
+ let grantedRoles = minusIndex == -1 ? strRoles : strRoles.substring(0, minusIndex);
177
+ const deniedRoles = minusIndex == -1 ? "" : strRoles.substring(minusIndex + 1);
178
178
  if (!grantedRoles)
179
179
  grantedRoles = "*";
180
180
  parameters.allowRoles = grantedRoles.split(",");
@@ -233,8 +233,8 @@ function configGenTypescriptDriver(args, mushroomConfig, projectName){
233
233
  const strRoles = args[index];
234
234
  if (strRoles) {
235
235
  const minusIndex = strRoles.indexOf("-");
236
- let grantedRoles = minusIndex == -1 ? strRoles : strRoles.substr(0, minusIndex);
237
- const deniedRoles = minusIndex == -1 ? "" : strRoles.substr(minusIndex + 1);
236
+ let grantedRoles = minusIndex == -1 ? strRoles : strRoles.substring(0, minusIndex);
237
+ const deniedRoles = minusIndex == -1 ? "" : strRoles.substring(minusIndex + 1);
238
238
  if (!grantedRoles)
239
239
  grantedRoles = "*";
240
240
  parameters.allowRoles = grantedRoles.split(",");
@@ -325,8 +325,8 @@ function configGenCSharpDriver(args, mushroomConfig, projectName){
325
325
  const strRoles = args[index];
326
326
  if (strRoles) {
327
327
  const minusIndex = strRoles.indexOf("-");
328
- let grantedRoles = minusIndex == -1 ? strRoles : strRoles.substr(0, minusIndex);
329
- const deniedRoles = minusIndex == -1 ? "" : strRoles.substr(minusIndex + 1);
328
+ let grantedRoles = minusIndex == -1 ? strRoles : strRoles.substring(0, minusIndex);
329
+ const deniedRoles = minusIndex == -1 ? "" : strRoles.substring(minusIndex + 1);
330
330
  if (!grantedRoles)
331
331
  grantedRoles = "*";
332
332
  parameters.allowRoles = grantedRoles.split(",");
@@ -9,6 +9,8 @@ function processGenDocs(aliasProject, entities, source, html, args, projectName,
9
9
  console.log('Received html');
10
10
  console.log("Parsing html");
11
11
 
12
+ const roles = aliasProject.allowRoles.includes("*") ? source.roles : source.roles?.filter(r => aliasProject.allowRoles.includes(r.name));
13
+
12
14
  html = html.replace(/^\uFEFF/, '');
13
15
  html = html.replace(/<script src=(["'])\/\//g, "<script src=$1http://");
14
16
  html = html.replace("</body>", `<script data-mt-cond='{"x": 1}'>
@@ -16,9 +18,11 @@ function processGenDocs(aliasProject, entities, source, html, args, projectName,
16
18
  window.data.description = ${JSON.stringify(source.description)};
17
19
  window.data.rootUrl = ${JSON.stringify(common.getRootUrl(source))};
18
20
  window.data.environmentVariables = ${JSON.stringify(source.environmentVariables)};
21
+ window.data.roles = ${JSON.stringify(roles)};
19
22
  window.data.entities = ${JSON.stringify(entities)};
20
23
  window.data.features = ${JSON.stringify(aliasProject.features)};
21
- try{
24
+ try {
25
+ console.info("MUSHROOM-CLI: START");
22
26
  window.generateDocument();
23
27
  console.info("MUSHROOM-CLI: FINISH");
24
28
  }
@@ -31,6 +35,12 @@ function processGenDocs(aliasProject, entities, source, html, args, projectName,
31
35
  return new Promise((resolve, reject) => {
32
36
  const virtualConsole = new jsdom.VirtualConsole();
33
37
  virtualConsole.on("info", function(msg, err) {
38
+ if (typeof msg != "string") return;
39
+
40
+ if (msg.indexOf("MUSHROOM-CLI:") === 0) {
41
+ console.log("GenDocEngine:" + msg.substring("MUSHROOM-CLI:".length));
42
+ }
43
+
34
44
  if (msg === "MUSHROOM-CLI: FAIL"){
35
45
  dom = null;
36
46
  reject(err);
package/gen/gen-csharp.js CHANGED
@@ -3,6 +3,31 @@ const common = require("../common.js");
3
3
  const package = require("./../package.json");
4
4
 
5
5
  //#region shared function
6
+ const newLine = `
7
+ `;
8
+ const header = `// NOTE: This file was generated by Mushroom CLI (https://www.npmjs.com/package/mushroom-cli), please do not modify
9
+ // NOTE: Version and compatibility information: please see in Info.cs file
10
+
11
+ // ReSharper disable CheckNamespace
12
+ // ReSharper disable CommentTypo
13
+ // ReSharper disable EmptyNamespace
14
+ // ReSharper disable IdentifierTypo
15
+ // ReSharper disable InconsistentNaming
16
+ // ReSharper disable PartialTypeWithSinglePart
17
+ // ReSharper disable RedundantUsingDirective
18
+ // ReSharper disable StringLiteralTypo
19
+ // ReSharper disable UnusedMember.Global
20
+ // ReSharper disable UnusedMember.Local
21
+ // ReSharper disable UnusedParameter.Local
22
+ // ReSharper disable UnusedTypeParameter
23
+
24
+
25
+ using MongoDB.Bson;
26
+ using MongoDB.Bson.Serialization.Attributes;
27
+ using MongoDB.Driver;
28
+ using JsonPropertyAttribute = Newtonsoft.Json.JsonPropertyAttribute;
29
+ using NullValueHandling = Newtonsoft.Json.NullValueHandling;`;
30
+
6
31
  function singleLine(str) {
7
32
  if (!str)
8
33
  return "";
@@ -25,7 +50,7 @@ function toCSharpName(str) {
25
50
  return "_";
26
51
  const name = toVietnameseNonTongue(str).replace(/\W/g, "_");
27
52
  const c = name.charAt(0);
28
- return ('0' <= c && c <= '9' ? '_' : "") + c.toUpperCase() + name.substr(1);
53
+ return ('0' <= c && c <= '9' ? '_' : "") + c.toUpperCase() + name.substring(1);
29
54
  }
30
55
 
31
56
  function getCSharpTypeFromMushroomType(source, type, required) {
@@ -143,7 +168,8 @@ function generateCSharpClassMongoDb(source, className, fields, isRoot, descripti
143
168
  content +=
144
169
  ` /// <summary>
145
170
  /// ${singleLine(description)}
146
- /// </summary>\r\n`;
171
+ /// </summary>
172
+ `;
147
173
  }
148
174
  var supperClass = "";
149
175
  if (isRoot) {
@@ -171,12 +197,12 @@ function generateCSharpClassMongoDb(source, className, fields, isRoot, descripti
171
197
  type = field.codeHint.type.csharp;
172
198
  }
173
199
  else if (field.type === "object") {
174
- strClasses += generateCSharpClassMongoDb(source, className + "_" + propertyName, field.fields, false, null, out) + "\r\n";
200
+ strClasses += generateCSharpClassMongoDb(source, className + "_" + propertyName, field.fields, false, null, out) + newLine;
175
201
  type = className + "_" + propertyName;
176
202
  }
177
203
  else if (field.type === "array") {
178
204
  if (field.items.type === "object") {
179
- strClasses += generateCSharpClassMongoDb(source, className + "_" + propertyName, field.items.fields, false, null, out) + "\r\n";
205
+ strClasses += generateCSharpClassMongoDb(source, className + "_" + propertyName, field.items.fields, false, null, out) + newLine;
180
206
  type = `System.Collections.Generic.List<${className}_${propertyName}>`;
181
207
  } else {
182
208
  type = `System.Collections.Generic.List<${getCSharpTypeFromMushroomType(source, field.items.type, field.items.validation && field.items.validation.required)}>`;
@@ -190,34 +216,34 @@ function generateCSharpClassMongoDb(source, className, fields, isRoot, descripti
190
216
  `;
191
217
 
192
218
  if (isRoot && fieldName === "id") {
193
- content += ` [BsonId${field.type === "AutoId" && source.idType === "GUID" ? "(IdGenerator = typeof(MongoDB.Bson.Serialization.IdGenerators.GuidGenerator))" : ""}]\r\n`;
219
+ content += ` [BsonId${field.type === "AutoId" && source.idType === "GUID" ? "(IdGenerator = typeof(MongoDB.Bson.Serialization.IdGenerators.GuidGenerator))" : ""}]${newLine}`;
194
220
  }
195
221
  content += ` [BsonElement("${isRoot && fieldName === "id" ? "_id" : fieldName}")]
196
222
  [BsonIgnoreIfNull]
197
223
  [JsonProperty(PropertyName = "${fieldName}", NullValueHandling = NullValueHandling.Ignore)]
198
224
  `;
199
225
  if ((field.type === "AutoId" || field.type === "IdRef") && source.idType === "ObjectId") {
200
- content += " [BsonRepresentation(BsonType.ObjectId)]\r\n";
226
+ content += " [BsonRepresentation(BsonType.ObjectId)]" + newLine;
201
227
  }
202
228
  if (field.type === "AutoId" && source.idType === "GUID") {
203
- content += " [BsonRepresentation(BsonType.String)]\r\n";
229
+ content += " [BsonRepresentation(BsonType.String)]" + newLine;
204
230
  }
205
231
  if (field.type === "datetime") {
206
- content += " [BsonDateTimeOptions(Kind = System.DateTimeKind.Local)]\r\n";
232
+ content += " [BsonDateTimeOptions(Kind = System.DateTimeKind.Local)]" + newLine;
207
233
  }
208
234
  if (field.type === "array") {
209
235
  if ((field.items.type === "AutoId" || field.items.type === "IdRef") && source.idType === "ObjectId") {
210
- content += " [BsonRepresentation(BsonType.ObjectId)]\r\n";
236
+ content += " [BsonRepresentation(BsonType.ObjectId)]" + newLine;
211
237
  }
212
238
  if (field.items.type === "AutoId" && source.idType === "GUID") {
213
- content += " [BsonRepresentation(BsonType.String)]\r\n";
239
+ content += " [BsonRepresentation(BsonType.String)]" + newLine;
214
240
  }
215
241
  if (field.items.type === "datetime") {
216
- content += " [BsonDateTimeOptions(Kind = System.DateTimeKind.Local)]\r\n";
242
+ content += " [BsonDateTimeOptions(Kind = System.DateTimeKind.Local)]" + newLine;
217
243
  }
218
244
  }
219
245
 
220
- content += ` public ${type} ${propertyName} { get; set; }\r\n\r\n`;
246
+ content += ` public ${type} ${propertyName} { get; set; }${newLine}${newLine}`;
221
247
 
222
248
  strEnumClasses += generateEnumClass(source, out, field, `${className.toUpperCase()}_${propertyName.toUpperCase()}_ENUM`);
223
249
  }
@@ -233,14 +259,14 @@ function generateCSharpClassMongoDb(source, className, fields, isRoot, descripti
233
259
  //console.log("strEnumClasses("+typeof(strEnumClasses)+"):" + strEnumClasses);
234
260
  }
235
261
 
236
- return strClasses + "\r\n" + content;
262
+ return strClasses + newLine + content;
237
263
  }
238
264
 
239
265
  function getCSharpFunc(methodName, methodType) {
240
266
  if (methodType === "static") return methodName;
241
267
  const idx = methodName.lastIndexOf('.');
242
268
  if (idx === -1) return methodName;
243
- return `new ${methodName.substr(0, idx)}()${methodName.substr(idx)}`;
269
+ return `new ${methodName.substring(0, idx)}()${methodName.substring(idx)}`;
244
270
  }
245
271
 
246
272
  function genCSharpMongoDbClasses(args, projectName, project, alias, source) {
@@ -250,6 +276,11 @@ function genCSharpMongoDbClasses(args, projectName, project, alias, source) {
250
276
  throw new Error(`Not found gen c#-mongo configuration. Please run 'npx mr config ${projectName} gen c#-mongo OUTPUT_FILE.cs${alias === "default" ? "" : " alias " + alias}' first`);
251
277
  }
252
278
 
279
+ if (aliasProject.outputToFolder) {
280
+ genCSharpMongoDbClassesToFolder(projectName, alias, source, aliasProject);
281
+ return;
282
+ }
283
+
253
284
  const entities = common.getEntities(source, aliasProject.allowRoles, true);
254
285
 
255
286
  const namespace = toCSharpName(source.name);
@@ -268,7 +299,7 @@ function genCSharpMongoDbClasses(args, projectName, project, alias, source) {
268
299
  collectionNames += ` public static string ${className}CollectionName => "${entities[entityName].storageName}";
269
300
  public static IMongoCollection<Resources.${className}> ${className}Collection => GetDatabase().GetCollection<Resources.${className}>(${className}CollectionName);
270
301
  `;
271
- resourceNames += ` public static string ${className} => "${entityName}";\r\n`;
302
+ resourceNames += ` public static string ${className} => "${entityName}";${newLine}`;
272
303
  strClasses += generateCSharpClassMongoDb(source, className, entities[entityName].fields, true, entities[entityName].description, out);
273
304
 
274
305
  const actions = entities[entityName].actions || {};
@@ -360,7 +391,7 @@ function genCSharpMongoDbClasses(args, projectName, project, alias, source) {
360
391
  }
361
392
  return prev;
362
393
  }, {});
363
- const strDelegatorReferences = Object.keys(delegators).map(method => delegators[method].map(ev => ` // ${ev.source}`).join("\r\n") + "\r\n" + ` RegisterCustomMethod(${getCSharpFunc(method, delegators[method][0].type)});`).join("\r\n");
394
+ const strDelegatorReferences = Object.keys(delegators).map(method => delegators[method].map(ev => ` // ${ev.source}`).join(newLine) + newLine + ` RegisterCustomMethod(${getCSharpFunc(method, delegators[method][0].type)});`).join(newLine);
364
395
 
365
396
  const viewHandlers = (out.viewHandlers || []).reduce((prev, cur) => {
366
397
  if (cur.method in prev) {
@@ -373,7 +404,7 @@ function genCSharpMongoDbClasses(args, projectName, project, alias, source) {
373
404
  }
374
405
  return prev;
375
406
  }, {});
376
- const strViewHandlerReferences = Object.keys(viewHandlers).map(method => viewHandlers[method].map(ev => ` // ${ev.source}`).join("\r\n") + "\r\n" + ` RegisterCustomViewMethod(${getCSharpFunc(method, viewHandlers[method][0].type)});`).join("\r\n");
407
+ const strViewHandlerReferences = Object.keys(viewHandlers).map(method => viewHandlers[method].map(ev => ` // ${ev.source}`).join(newLine) + newLine + ` RegisterCustomViewMethod(${getCSharpFunc(method, viewHandlers[method][0].type)});`).join(newLine);
377
408
 
378
409
  const eventHandlers = (out.eventHandlers || []).reduce((prev, cur) => {
379
410
  if (cur.method in prev) {
@@ -386,18 +417,18 @@ function genCSharpMongoDbClasses(args, projectName, project, alias, source) {
386
417
  }
387
418
  return prev;
388
419
  }, {});
389
- const strEventHandlerReferences = Object.keys(eventHandlers).map(method => eventHandlers[method].map(ev => ` // ${ev.source}`).join("\r\n") + "\r\n" + ` RegisterEvent(${getCSharpFunc(method, eventHandlers[method][0].type)});`).join("\r\n");
420
+ const strEventHandlerReferences = Object.keys(eventHandlers).map(method => eventHandlers[method].map(ev => ` // ${ev.source}`).join(newLine) + newLine + ` RegisterEvent(${getCSharpFunc(method, eventHandlers[method][0].type)});`).join(newLine);
390
421
 
391
422
  const strJobReferences = Array.isArray(source.jobs)
392
423
  ? source.jobs
393
424
  .filter(job => job !== null && typeof(job) === "object" && job.action && typeof (job.action) === "string" && job.action.indexOf("lib:") === 0)
394
- .map(job => ` RegisterJob<${job.action.substr(4).split(',')[0]}>();`)
395
- .join("\r\n")
425
+ .map(job => ` RegisterJob<${job.action.substring(4).split(',')[0]}>();`)
426
+ .join(newLine)
396
427
  : "";
397
428
 
398
429
  const code = `// This file was generated by Mushroom CLI ${package.version} (https://www.npmjs.com/package/mushroom-cli), please do not modify
399
430
 
400
- // NOTE: Compatible with Mushroom Server version 0.2.18 or higher
431
+ // NOTE: Compatible with Mushroom Server version 0.2.18 or higher (https://www.nuget.org/packages/Mushroom/)
401
432
 
402
433
  // ReSharper disable RedundantUsingDirective
403
434
  // ReSharper disable InconsistentNaming
@@ -488,6 +519,359 @@ ${strJobReferences}
488
519
  console.log(`Generated CSharp MongoDb Classes for ${projectName}@${alias} to ${aliasProject.output}`);
489
520
  });
490
521
  }
522
+
523
+ function generateCSharpClassMongoDbToFolder(source, className, fields, isRoot, description, out, aliasProject) {
524
+ var content = "";
525
+ const namespace = toCSharpName(source.name);
526
+ if (description) {
527
+ content +=
528
+ ` /// <summary>
529
+ /// ${singleLine(description)}
530
+ /// </summary>
531
+ `;
532
+ }
533
+ var supperClass = "";
534
+ if (isRoot) {
535
+ // thêm cho trường hợp không khai báo id hoặc id.type
536
+ if (!fields.id) {
537
+ fields.id = {
538
+ type: "AutoId"
539
+ };
540
+ }
541
+ if (!fields.id.type) fields.id.type = "AutoId";
542
+
543
+ supperClass = " : Mushroom.Models.IResource<" + getCSharpTypeFromMushroomType(source, fields.id.type, true) + ">";
544
+ }
545
+ content += ` public class ${className}${supperClass}
546
+ {
547
+ `;
548
+ for (var fieldName in fields) {
549
+ if (!fields.hasOwnProperty(fieldName))
550
+ continue;
551
+
552
+ var field = fields[fieldName];
553
+ var type;
554
+ var propertyName = toCSharpName(fieldName);
555
+ if (field.codeHint && field.codeHint.type && field.codeHint.type.csharp) {
556
+ type = field.codeHint.type.csharp;
557
+ }
558
+ else if (field.type === "object") {
559
+ generateCSharpClassMongoDbToFolder(source, className + "_" + propertyName, field.fields, false, null, out, aliasProject) + newLine;
560
+ type = className + "_" + propertyName;
561
+ }
562
+ else if (field.type === "array") {
563
+ if (field.items.type === "object") {
564
+ generateCSharpClassMongoDbToFolder(source, className + "_" + propertyName, field.items.fields, false, null, out, aliasProject) + newLine;
565
+ type = `System.Collections.Generic.List<${className}_${propertyName}>`;
566
+ } else {
567
+ type = `System.Collections.Generic.List<${getCSharpTypeFromMushroomType(source, field.items.type, field.items.validation && field.items.validation.required)}>`;
568
+ }
569
+ } else
570
+ type = getCSharpTypeFromMushroomType(source, field.type, field.validation && field.validation.required);
571
+ content +=
572
+ ` /// <summary>
573
+ /// ${singleLine(field.description)}
574
+ /// </summary>
575
+ `;
576
+
577
+ if (isRoot && fieldName === "id") {
578
+ content += ` [BsonId${field.type === "AutoId" && source.idType === "GUID" ? "(IdGenerator = typeof(MongoDB.Bson.Serialization.IdGenerators.GuidGenerator))" : ""}]${newLine}`;
579
+ }
580
+ content += ` [BsonElement("${isRoot && fieldName === "id" ? "_id" : fieldName}")]
581
+ [BsonIgnoreIfNull]
582
+ [JsonProperty(PropertyName = "${fieldName}", NullValueHandling = NullValueHandling.Ignore)]
583
+ `;
584
+ if ((field.type === "AutoId" || field.type === "IdRef") && source.idType === "ObjectId") {
585
+ content += " [BsonRepresentation(BsonType.ObjectId)]" + newLine;
586
+ }
587
+ if (field.type === "AutoId" && source.idType === "GUID") {
588
+ content += " [BsonRepresentation(BsonType.String)]" + newLine;
589
+ }
590
+ if (field.type === "datetime") {
591
+ content += " [BsonDateTimeOptions(Kind = System.DateTimeKind.Local)]" + newLine;
592
+ }
593
+ if (field.type === "array") {
594
+ if ((field.items.type === "AutoId" || field.items.type === "IdRef") && source.idType === "ObjectId") {
595
+ content += " [BsonRepresentation(BsonType.ObjectId)]" + newLine;
596
+ }
597
+ if (field.items.type === "AutoId" && source.idType === "GUID") {
598
+ content += " [BsonRepresentation(BsonType.String)]" + newLine;
599
+ }
600
+ if (field.items.type === "datetime") {
601
+ content += " [BsonDateTimeOptions(Kind = System.DateTimeKind.Local)]" + newLine;
602
+ }
603
+ }
604
+
605
+ content += ` public ${type} ${propertyName} { get; set; }
606
+
607
+ `;
608
+
609
+ let strEnumClasses = generateEnumClass(source, {}, field, `${className.toUpperCase()}_${propertyName.toUpperCase()}_ENUM`);
610
+
611
+ const match = strEnumClasses.match(/public static class\s+(\w+)/);
612
+ if (!match) continue;
613
+ common.ensureFolder(aliasProject.output + "/Enums", true);
614
+ strEnumClasses = `${header}
615
+
616
+ namespace ${namespace}.Enums
617
+ {
618
+ ${strEnumClasses}
619
+ }
620
+ `;
621
+
622
+ fs.writeFileSync(aliasProject.output + "/Enums/" + match[1] + ".cs", strEnumClasses);
623
+ }
624
+
625
+ content += ` [BsonExtraElements]
626
+ public System.Collections.Generic.Dictionary<string, object> Mushroom_ExtraProperties { get; set; }
627
+
628
+ }
629
+ `;
630
+
631
+ //return strClasses + newLine + content;
632
+ common.ensureFolder(aliasProject.output + "/Resources", true);
633
+
634
+ content = `${header}
635
+
636
+ namespace ${namespace}.Resources
637
+ {
638
+ ${content}
639
+ }
640
+ `;
641
+
642
+ fs.writeFileSync(aliasProject.output + "/Resources/" + className + ".cs", content);
643
+ }
644
+
645
+ function genCSharpMongoDbClassesToFolder(projectName, alias, source, aliasProject) {
646
+
647
+ if (fs.existsSync(aliasProject.output)) {
648
+ try {
649
+ fs.unlinkSync(aliasProject.output); // xóa file nếu có
650
+ } catch(e) {}
651
+ try {
652
+ fs.rmdirSync(aliasProject.output); // xóa thư mục nếu có
653
+ } catch(e) {}
654
+ }
655
+ fs.mkdirSync(aliasProject.output, { recursive: true, mode: 0755 });
656
+
657
+ const entities = common.getEntities(source, aliasProject.allowRoles, true);
658
+
659
+ const namespace = toCSharpName(source.name);
660
+
661
+ let collectionNames = "";
662
+ let resourceNames = "";
663
+
664
+ const out = {};
665
+ for (let entityName in entities) {
666
+ if (!entities.hasOwnProperty(entityName))
667
+ continue;
668
+
669
+ const className = toCSharpName(entityName);
670
+ collectionNames += ` public static string ${className}CollectionName => "${entities[entityName].storageName}";
671
+ public static IMongoCollection<Resources.${className}> ${className}Collection => GetDatabase().GetCollection<Resources.${className}>(${className}CollectionName);
672
+ `;
673
+ resourceNames += ` public static string ${className} => "${entityName}";
674
+ `;
675
+ //strClasses += generateCSharpClassMongoDbToFolder(source, className, entities[entityName].fields, true, entities[entityName].description, out);
676
+
677
+ generateCSharpClassMongoDbToFolder(source, className, entities[entityName].fields, true, entities[entityName].description, out, aliasProject);
678
+
679
+ const actions = entities[entityName].actions || {};
680
+ for (let actionName in actions) {
681
+ const action = actions[actionName];
682
+ if (!Array.isArray(action))
683
+ continue;
684
+
685
+ action.forEach(a => {
686
+ if (!a)
687
+ return;
688
+ if (typeof a.delegator === "string" && a.delegator.indexOf("lib:") === 0) {
689
+ out.delegators = out.delegators || [];
690
+ const method = a.delegator.substr(4, a.delegator.length - 4);
691
+ let type = a.codeHint && a.codeHint.delegator && a.codeHint.delegator.csharp
692
+ ? a.codeHint.delegator.csharp.methodType
693
+ : null;
694
+ if (type !== "non-static") type = "static";
695
+ out.delegators.push({
696
+ method: method,
697
+ source: `entity: ${entityName}, action: ${actionName}, grant: ${a.grant}`,
698
+ type: type
699
+ });
700
+ }
701
+
702
+ if (!a.events && !(typeof a.events === "object")) return;
703
+
704
+ for (let eventName in a.events) {
705
+ if (!Array.isArray(a.events[eventName])) return;
706
+
707
+ out.eventHandlers = out.eventHandlers || [];
708
+ a.events[eventName].forEach((ev, i) => {
709
+ if (typeof ev !== "string" || ev.indexOf("lib:") !== 0) return;
710
+ const method = ev.substr(4, ev.length - 4);
711
+ let type = a.codeHint && a.codeHint.events
712
+ && Array.isArray(a.codeHint.events[eventName])
713
+ && a.codeHint.events[eventName][i]
714
+ && a.codeHint.events[eventName][i].csharp
715
+ ? a.codeHint.events[eventName][i].csharp.methodType
716
+ : null;
717
+ if (type !== "non-static") type = "static";
718
+ out.eventHandlers.push({
719
+ method: method,
720
+ source: `entity: ${entityName}, action: ${actionName}, grant: ${a.grant}, event: ${eventName}`,
721
+ type: type
722
+ });
723
+ });
724
+ }
725
+ });
726
+ }
727
+
728
+ const views = entities[entityName].views || {};
729
+ for (let viewName in views) {
730
+ const view = views[viewName];
731
+ if (!Array.isArray(view))
732
+ continue;
733
+
734
+ view.forEach(v => {
735
+ if (!v) return;
736
+
737
+ if (typeof v.query === "string" && v.query.indexOf("lib:") === 0) {
738
+ out.viewHandlers = out.viewHandlers || [];
739
+ const method = v.query.substr(4, v.query.length - 4);
740
+ let type = v.codeHint && v.codeHint.query && v.codeHint.query.csharp
741
+ ? v.codeHint.query.csharp.methodType
742
+ : null;
743
+ if (type !== "non-static") type = "static";
744
+ out.viewHandlers.push({
745
+ method: method,
746
+ source: `entity: ${entityName}, view: ${viewName}, grant: ${v.grant}`,
747
+ type: type
748
+ });
749
+ }
750
+ });
751
+ }
752
+ }
753
+
754
+
755
+ const delegators = (out.delegators || []).reduce((prev, cur) => {
756
+ if (cur.method in prev) {
757
+ if (prev[cur.method].indexOf(cur.source) === -1) {
758
+ prev[cur.method].push(cur);
759
+ }
760
+ }
761
+ else {
762
+ prev[cur.method] = [cur];
763
+ }
764
+ return prev;
765
+ }, {});
766
+ const strDelegatorReferences = Object.keys(delegators).map(method => delegators[method].map(ev => ` // ${ev.source}`).join(newLine) + newLine + ` RegisterCustomMethod(${getCSharpFunc(method, delegators[method][0].type)});`).join(newLine);
767
+
768
+ const viewHandlers = (out.viewHandlers || []).reduce((prev, cur) => {
769
+ if (cur.method in prev) {
770
+ if (prev[cur.method].indexOf(cur.source) === -1) {
771
+ prev[cur.method].push(cur);
772
+ }
773
+ }
774
+ else {
775
+ prev[cur.method] = [cur];
776
+ }
777
+ return prev;
778
+ }, {});
779
+ const strViewHandlerReferences = Object.keys(viewHandlers).map(method => viewHandlers[method].map(ev => ` // ${ev.source}`).join(newLine) + newLine + ` RegisterCustomViewMethod(${getCSharpFunc(method, viewHandlers[method][0].type)});`).join(newLine);
780
+
781
+ const eventHandlers = (out.eventHandlers || []).reduce((prev, cur) => {
782
+ if (cur.method in prev) {
783
+ if (prev[cur.method].indexOf(cur.source) === -1) {
784
+ prev[cur.method].push(cur);
785
+ }
786
+ }
787
+ else {
788
+ prev[cur.method] = [cur];
789
+ }
790
+ return prev;
791
+ }, {});
792
+ const strEventHandlerReferences = Object.keys(eventHandlers).map(method => eventHandlers[method].map(ev => ` // ${ev.source}`).join(newLine) + newLine + ` RegisterEvent(${getCSharpFunc(method, eventHandlers[method][0].type)});`).join(newLine);
793
+
794
+ const strJobReferences = Array.isArray(source.jobs)
795
+ ? source.jobs
796
+ .filter(job => job !== null && typeof(job) === "object" && job.action && typeof (job.action) === "string" && job.action.indexOf("lib:") === 0)
797
+ .map(job => ` RegisterJob<${job.action.substring(4).split(',')[0]}>();`)
798
+ .join(newLine)
799
+ : "";
800
+
801
+ const dbConnectorFileContent = `${header}
802
+
803
+ namespace ${namespace}
804
+ {
805
+ public static class DbConnector
806
+ {
807
+ ${collectionNames}
808
+ public static IMongoDatabase GetDatabase() => Mushroom.MushroomDaoFactory.GetDbAdapter() as IMongoDatabase;
809
+
810
+ public static async System.Threading.Tasks.Task<T> FindByIdAsync<T, TId>(this IMongoCollection<T> collection, TId id) where T : Mushroom.Models.IResource<TId>
811
+ {
812
+ return await (await collection.FindAsync(Builders<T>.Filter.Eq(doc => doc.Id, id))).FirstOrDefaultAsync();
813
+ }
814
+
815
+ public static async System.Threading.Tasks.Task<T> FindByIdAsync<T, TId>(this IMongoCollection<T> collection, TId id, FindOptions<T> findOptions) where T : Mushroom.Models.IResource<TId>
816
+ {
817
+ return await (await collection.FindAsync(Builders<T>.Filter.Eq(doc => doc.Id, id), findOptions)).FirstOrDefaultAsync();
818
+ }
819
+
820
+ public static async System.Threading.Tasks.Task<T> FindByIdAsync<T, TId>(this IMongoCollection<T> collection, TId id, ProjectionDefinition<T> projection) where T : Mushroom.Models.IResource<TId>
821
+ {
822
+ return await (await collection.FindAsync(Builders<T>.Filter.Eq(doc => doc.Id, id), new FindOptions<T> { Projection = projection })).FirstOrDefaultAsync();
823
+ }
824
+ }
825
+ }
826
+ `;
827
+
828
+ const resourceNamesFileContent = `${header}
829
+
830
+ namespace ${namespace}
831
+ {
832
+ public static class ResourceNames
833
+ {
834
+ ${resourceNames}
835
+ }
836
+ }
837
+ `;
838
+
839
+ const refactorHelperFileContent = `${header}
840
+
841
+ #if DEBUG
842
+ namespace ${namespace}
843
+ {
844
+ class RefactorHelper
845
+ {
846
+ private RefactorHelper() { }
847
+ private void RegisterCustomMethod(System.Func<Mushroom.ActionArguments, System.Threading.Tasks.Task> fn) { }
848
+ private void RegisterCustomMethod(System.Action<Mushroom.ActionArguments> fn) { }
849
+ private void RegisterCustomViewMethod(System.Func<Mushroom.ViewArguments, System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<object>>> fn) { }
850
+ private void RegisterCustomViewMethod(System.Action<Mushroom.ViewArguments> fn) { }
851
+ private void RegisterEvent(System.Func<object, Mushroom.ActionArguments, System.Threading.Tasks.Task> fn) { }
852
+ private void RegisterEvent(System.Action<object, Mushroom.ActionArguments> fn) { }
853
+ private void RegisterJob<T>() where T : Mushroom.Job.JobBase { }
854
+ private void Help()
855
+ {
856
+ ${strDelegatorReferences}
857
+ ${strViewHandlerReferences}
858
+ ${strEventHandlerReferences}
859
+ ${strJobReferences}
860
+ }
861
+ }
862
+ }
863
+ #endif
864
+ `;
865
+
866
+ const infoFileContent = `// Mushroom CLI version: ${package.version}${newLine}// Compatible with Mushroom Server version: 0.2.18 or higher (https://www.nuget.org/packages/Mushroom/)`
867
+
868
+ fs.writeFileSync(aliasProject.output + "/DbConnector.cs", dbConnectorFileContent);
869
+ fs.writeFileSync(aliasProject.output + "/ResourceNames.cs", resourceNamesFileContent);
870
+ fs.writeFileSync(aliasProject.output + "/RefactorHelper.cs", refactorHelperFileContent);
871
+ fs.writeFileSync(aliasProject.output + "/Info.cs", infoFileContent);
872
+
873
+ console.log(`Generated CSharp MongoDb Classes for ${projectName}@${alias} to folder ${aliasProject.output}`);
874
+ }
491
875
  //#endregion
492
876
 
493
877
  //#region CSharp Driver
@@ -515,12 +899,12 @@ function generateCSharpClassDriver(source, className, fields, description, out)
515
899
  const propertyName = toCSharpName(fieldName);
516
900
  let type;
517
901
  if (field.type === "object") {
518
- strClasses += generateCSharpClassDriver(source, className + "_" + propertyName, field.fields, null, out) + "\r\n";
902
+ strClasses += generateCSharpClassDriver(source, className + "_" + propertyName, field.fields, null, out) + newLine;
519
903
  type = className + "_" + propertyName;
520
904
  }
521
905
  else if (field.type === "array") {
522
906
  if (field.items.type === "object") {
523
- strClasses += generateCSharpClassDriver(source, className + "_" + propertyName, field.items.fields, null, out) + "\r\n";
907
+ strClasses += generateCSharpClassDriver(source, className + "_" + propertyName, field.items.fields, null, out) + newLine;
524
908
  type = `System.Collections.Generic.List<${className}_${propertyName}>`;
525
909
  } else {
526
910
  type = `System.Collections.Generic.List<${getCSharpTypeFromMushroomType(source, field.items.type, field.items.validation && field.items.validation.required)}>`;
@@ -545,8 +929,8 @@ function generateCSharpClassDriver(source, className, fields, description, out)
545
929
  }
546
930
 
547
931
 
548
- content += " }\r\n";
549
- return strClasses + "\r\n" + content;
932
+ content += " }" + newLine;
933
+ return strClasses + newLine + content;
550
934
  }
551
935
 
552
936
  function genCSharpDriver(args, projectName, project, alias, source) {
@@ -578,8 +962,8 @@ function genCSharpDriver(args, projectName, project, alias, source) {
578
962
  var className = toCSharpName(entityName);
579
963
 
580
964
  strClasses += generateCSharpClassDriver(source, className, entities[entityName].fields, entities[entityName].description, out);
581
- codeStaticCtor += ` ${className} = new ${className}Connector(client);\r\n`;
582
- codeStaticProperties += ` public static ${className}Connector ${className} { get; }\r\n\r\n`;
965
+ codeStaticCtor += ` ${className} = new ${className}Connector(client);${newLine}`;
966
+ codeStaticProperties += ` public static ${className}Connector ${className} { get; }${newLine}${newLine}`;
583
967
 
584
968
  var entity = entities[entityName];
585
969
 
@@ -689,7 +1073,7 @@ function genCSharpDriver(args, projectName, project, alias, source) {
689
1073
  if (actionName.indexOf("_raw_http_method_"))
690
1074
  break;
691
1075
 
692
- var customMethod = toCSharpName(actionName.substr("_raw_http_method_".length));
1076
+ var customMethod = toCSharpName(actionName.substring("_raw_http_method_".length));
693
1077
 
694
1078
  codeConnectors += ` public async System.Threading.Tasks.Task<${className}${customMethod}Result> ${customMethod}(${className}${customMethod}Arg arg)
695
1079
  {
@@ -738,11 +1122,11 @@ function genCSharpDriver(args, projectName, project, alias, source) {
738
1122
 
739
1123
  partial void BuildCustomUrl();
740
1124
 
741
- private string OriginUrl => "${entityName}s/${actionName.substr("_raw_http_method_".length)}";
1125
+ private string OriginUrl => "${entityName}s/${actionName.substring("_raw_http_method_".length)}";
742
1126
 
743
- private string CustomUrl { get; set; } = "${entityName}s/${actionName.substr("_raw_http_method_".length)}";
1127
+ private string CustomUrl { get; set; } = "${entityName}s/${actionName.substring("_raw_http_method_".length)}";
744
1128
 
745
- public override string Method { get; } = "${actionName.substr("_raw_http_method_".length)}";
1129
+ public override string Method { get; } = "${actionName.substring("_raw_http_method_".length)}";
746
1130
 
747
1131
  public ${className}${customMethod}Body Data { get; set; }
748
1132
 
@@ -833,15 +1217,15 @@ function genCSharpDriver(args, projectName, project, alias, source) {
833
1217
  ${viewExtraClass}`;
834
1218
  }
835
1219
 
836
- codeConnectors += " }\r\n\r\n";
1220
+ codeConnectors += " }" + newLine + newLine;
837
1221
  }
838
1222
 
839
1223
  if (out.strEnumClasses)
840
1224
  strEnumClasses += out.strEnumClasses;
841
1225
 
842
- const code = `// This file was generated by Mushroom CLI (https://www.npmjs.com/package/mushroom-cli), please do not modify
1226
+ const code = `// This file was generated by Mushroom CLI ${package.version} (https://www.npmjs.com/package/mushroom-cli), please do not modify
843
1227
 
844
- // Require package: Mushroom.Driver version 1.4.0 or later https://www.nuget.org/packages/Mushroom.Driver/
1228
+ // Require package: Mushroom.Driver version 1.4.0 or later (https://www.nuget.org/packages/Mushroom.Driver/)
845
1229
 
846
1230
  // ReSharper disable InconsistentNaming
847
1231
  // ReSharper disable PartialTypeWithSinglePart
@@ -3,6 +3,7 @@ const path = require('path');
3
3
  var targz = require('targz');
4
4
  const javascriptDriverGenerator = require("./gen-js-driver");
5
5
  const typescriptDriverGenerator = require("./gen-ts-driver");
6
+ const package = require("./../package.json");
6
7
 
7
8
  function compressAsync(src, dest, folderName) {
8
9
  return new Promise((resolve, reject) => {
@@ -37,9 +38,18 @@ async function genJavascriptDriverTarball(args, projectName, project, alias, sou
37
38
  tarballName = tarballName.toLowerCase().replace(/[^a-z-]/g, "-");
38
39
 
39
40
  const dirPath = path.join(path.dirname(aliasProject.output), tarballName);
40
- //const mainFileName = path.basename(aliasProject.output);
41
- //const dtsFileName = mainFileName.replace(/\.js$/i, ".d.ts");
42
41
 
42
+ const versionGroup = package.version.match(/([^-]+)(-(\w+).*)?/);
43
+ const currentDistTag = versionGroup[3] ? versionGroup[3] : "latest";
44
+
45
+ const dependencies = [`"mushroomjs": "${currentDistTag}"`];
46
+ if (Array.isArray(aliasProject.features) && aliasProject.features.includes("auth")) {
47
+ dependencies.push(`"mushroomjs-auth": "${currentDistTag}"`);
48
+ }
49
+ if (Array.isArray(aliasProject.features) && aliasProject.features.includes("file")) {
50
+ dependencies.push(`"mushroomjs-file": "${currentDistTag}"`);
51
+ }
52
+
43
53
  const packageContent = `{
44
54
  "version": "1.0.${new Date().getTime()}",
45
55
  "name": "${tarballName}",
@@ -47,7 +57,7 @@ async function genJavascriptDriverTarball(args, projectName, project, alias, sou
47
57
  "main": "${tarballName}.js",
48
58
  "types": "${tarballName}.d.ts",
49
59
  "dependencies": {
50
- "mushroomjs": "^1.1.0-alpha.5"${Array.isArray(aliasProject.features) && aliasProject.features.includes("auth") ? ',\n "mushroomjs-auth": "^1.1.0-alpha.4"' : ""}${Array.isArray(aliasProject.features) && aliasProject.features.includes("file") ? ',\n "mushroomjs-file": "^1.1.0-alpha.1"' : ""}
60
+ ${dependencies.join(',\n ')}
51
61
  }
52
62
  }`;
53
63
 
@@ -30,12 +30,42 @@ function genJavascriptDriverString(aliasProject, source) {
30
30
 
31
31
  const entities = common.getEntities(source, aliasProject.allowRoles);
32
32
 
33
- let code = `import mushroom from "mushroomjs";
33
+ let extensionsImportLines = [];
34
+ let extensionsExportLines = [];
35
+ let extensionsCodeLines = [];
36
+
37
+ if (Array.isArray(aliasProject.features)) {
38
+ if (aliasProject.features.includes("auth")) {
39
+ extensionsImportLines.push('//import * as AuthExtension from "mushroomjs-auth";');
40
+ extensionsImportLines.push('var AuthExtension = require("mushroomjs-auth");');
41
+ extensionsExportLines.push('Auth: AuthExtension');
42
+ extensionsCodeLines.push("AuthExtension.useAuth(AuthExtension.AuthLocalStorage);");
43
+ }
44
+ if (aliasProject.features.includes("file")) {
45
+ extensionsImportLines.push('//import * as FileExtension from "mushroomjs-file";');
46
+ extensionsImportLines.push('var FileExtension = require("mushroomjs-file");');
47
+ extensionsExportLines.push('File: FileExtension');
48
+ extensionsCodeLines.push("FileExtension.useFile();");
49
+ }
50
+ }
34
51
 
35
- "use strict";
52
+ let code = `//import mushroom, {defineAsyncResource} from "mushroomjs";
53
+ Object.defineProperty(exports, "__esModule", { value: true });
54
+ var mushroom_1 = require("mushroomjs");
55
+ var mushroom = mushroom_1.default;
56
+ var defineAsyncResource = mushroom_1.defineAsyncResource;
36
57
 
58
+ //export * from "mushroomjs";
59
+ for (var m in mushroom_1) exports[m] = mushroom_1[m];
37
60
 
38
- const rootApiUrl = ${JSON.stringify(common.getRootUrl(source))};
61
+ ${extensionsImportLines.join("\n")}
62
+ //export const extensions = {
63
+ var extensions = {
64
+ ${extensionsExportLines.join(",\n ")}
65
+ };
66
+ exports.extensions = extensions;
67
+
68
+ "use strict";
39
69
 
40
70
  `;
41
71
  for (let entityName in entities) {
@@ -61,13 +91,16 @@ const rootApiUrl = ${JSON.stringify(common.getRootUrl(source))};
61
91
 
62
92
  views[viewName] = {};
63
93
  }
64
- code += `mushroom._defineAsyncResource({name:${JSON.stringify(entityName)},actions:${JSON.stringify(actions)},views:${JSON.stringify(views)}});
94
+ code += `defineAsyncResource({name:${JSON.stringify(entityName)},actions:${JSON.stringify(actions)},views:${JSON.stringify(views)}});
65
95
  `;
66
96
  }
67
97
  code += `
68
- mushroom.$using(rootApiUrl);
98
+ mushroom.$using(${JSON.stringify(common.getRootUrl(source))});
99
+
100
+ ${extensionsCodeLines.join('\n')}
69
101
 
70
- export default mushroom;`;
102
+ //export default mushroom;
103
+ exports.default = mushroom;`;
71
104
 
72
105
  return code;
73
106
  }
@@ -38,7 +38,7 @@ function toTypeScriptClassName(str) {
38
38
  return "_";
39
39
  const name = toVietnameseNonTongue(str).replace(/\W/g, "_");
40
40
  const c = name.charAt(0);
41
- return ('0' <= c && c <= '9' ? '_' : "") + c.toUpperCase() + name.substr(1);
41
+ return ('0' <= c && c <= '9' ? '_' : "") + c.toUpperCase() + name.substring(1);
42
42
  }
43
43
 
44
44
  function getCSharpTypeFromMushroomType(type) {
@@ -104,9 +104,32 @@ function genTypescriptDriverString(aliasProject, source) {
104
104
 
105
105
  const entities = common.getEntities(source, aliasProject.allowRoles);
106
106
 
107
+ let extensionsImportLines = [];
108
+ let extensionsExportLines = [];
109
+ let extensionsTypes = [];
110
+ let extensionsCodeLines = [];
111
+
112
+ if (Array.isArray(aliasProject.features)) {
113
+ if (aliasProject.features.includes("auth")) {
114
+ extensionsImportLines.push('import * as AuthExtension from "mushroomjs-auth";');
115
+ extensionsExportLines.push('File: FileExtension');
116
+ extensionsTypes.push("AuthExtension.IMushroomAuth & ");
117
+ extensionsCodeLines.push("AuthExtension.useAuth(AuthExtension.AuthLocalStorage);");
118
+ }
119
+ if (aliasProject.features.includes("file")) {
120
+ extensionsImportLines.push('import * as FileExtension from "mushroomjs-file";');
121
+ extensionsExportLines.push('Auth: AuthExtension');
122
+ extensionsTypes.push("FileExtension.IMushroomFile & ");
123
+ extensionsCodeLines.push("FileExtension.useFile();");
124
+ }
125
+ }
126
+
107
127
  let code = `import mushroom, { defineAsyncResource, defineAsyncView, fireEvent, createRestfulAsyncFunction, IdType, IMushroom, Mushroom, MushroomRequest, MushroomRequestSetting, MushroomRestfulRequest, MushroomResponse, MushroomResourceBase, MushroomListResource, MushroomFindByIdResource, MushroomCreateResource, MushroomBatchCreateResource, MushroomUpdateResource, MushroomBatchUpdateResource, MushroomPartialUpdateResource, MushroomDeleteResource, MushroomBatchDeleteResource, MushroomExtensibleResource, MushroomViewFunction, MushroomError } from "mushroomjs";
108
- ${Array.isArray(aliasProject.features) && aliasProject.features.includes("auth") ? 'import { IMushroomAuth, useAuth, AuthLocalStorage } from "mushroomjs-auth";' : ""}
109
- ${Array.isArray(aliasProject.features) && aliasProject.features.includes("file") ? 'import { IMushroomFile, useFile } from "mushroomjs-file";' : ""}
128
+ export * from "mushroomjs";
129
+ ${extensionsImportLines.join("\n")}
130
+ export const extensions = {
131
+ ${extensionsExportLines.join(",\n ")}
132
+ };
110
133
 
111
134
  export type ISODateValue = string | Date;
112
135
  export type IdValue = ${source.idType == "AutoIncInt" || source.idType == "AutoIncLong" ? "number" : "string"};
@@ -119,7 +142,7 @@ export type IdValue = ${source.idType == "AutoIncInt" || source.idType == "AutoI
119
142
 
120
143
  const entity = entities[entityName];
121
144
  const typescriptClassName = toTypeScriptClassName(entityName);
122
- code += `interface ${typescriptClassName} ${generateTypescriptClass(entity.fields)};
145
+ code += `export interface ${typescriptClassName} ${generateTypescriptClass(entity.fields)};
123
146
  `;
124
147
 
125
148
 
@@ -173,7 +196,7 @@ export type IdValue = ${source.idType == "AutoIncInt" || source.idType == "AutoI
173
196
  }
174
197
  default: {
175
198
  if (actionName.indexOf("_raw_http_method_") === 0) {
176
- customMethodCode += ` ${actionName.substr("_raw_http_method_".length)}Async: (rawRequest: MushroomRequest) => Promise<MushroomResponse<any>>,
199
+ customMethodCode += ` ${actionName.substring("_raw_http_method_".length)}Async: (rawRequest: MushroomRequest) => Promise<MushroomResponse<any>>,
177
200
  `;
178
201
  break;
179
202
  }
@@ -186,7 +209,7 @@ export type IdValue = ${source.idType == "AutoIncInt" || source.idType == "AutoI
186
209
  }
187
210
 
188
211
  if (customMethodCode) {
189
- code += `interface ${typescriptClassName}$CustomMethodResource {
212
+ code += `export interface ${typescriptClassName}$CustomMethodResource {
190
213
  ${customMethodCode}}
191
214
  `;
192
215
  iApiClassBody += ` & ${typescriptClassName}$CustomMethodResource`;
@@ -204,7 +227,7 @@ ${customMethodCode}}
204
227
 
205
228
  const viewParameterTypes = viewRoles.map(view => {
206
229
  const type = `${typescriptClassName}$ViewsResource_${viewName}View_${view.grant === "*" ? "" : toTypeScriptClassName(view.grant)}Parameters`;
207
- code += `interface ${type} ${generateTypescriptClassFromViewParameters(view.parameters)};
230
+ code += `export interface ${type} ${generateTypescriptClassFromViewParameters(view.parameters)};
208
231
  `;
209
232
  return `MushroomViewFunction<any, ${type}>`;
210
233
  });
@@ -213,7 +236,7 @@ ${customMethodCode}}
213
236
  }
214
237
 
215
238
  if (viewCode) {
216
- code += `interface ${typescriptClassName}$ViewsResource {
239
+ code += `export interface ${typescriptClassName}$ViewsResource {
217
240
  views: {${viewCode}
218
241
  }
219
242
  }
@@ -230,14 +253,14 @@ ${customMethodCode}}
230
253
  }
231
254
 
232
255
  code += `
233
- ${Array.isArray(aliasProject.features) && aliasProject.features.includes("auth") ? "useAuth(AuthLocalStorage);" : ""}
234
- ${Array.isArray(aliasProject.features) && aliasProject.features.includes("auth") ? "useFile();" : ""}
235
256
  mushroom.$using(${JSON.stringify(common.getRootUrl(source))});
236
257
 
237
- interface IApi extends IMushroom {
258
+ ${extensionsCodeLines.join('\n')}
259
+
260
+ export interface IApi extends IMushroom {
238
261
  ${iApiClassBody}};
239
262
 
240
- type Api = ${Array.isArray(aliasProject.features) && aliasProject.features.includes("auth") ? "IMushroomAuth & " : ""}${Array.isArray(aliasProject.features) && aliasProject.features.includes("file") ? "IMushroomFile & " : ""}IApi;
263
+ export type Api = ${extensionsTypes.join('')}IApi;
241
264
 
242
265
  export default mushroom as Api;`;
243
266
 
@@ -251,9 +274,29 @@ function genDtsString(aliasProject, source) {
251
274
 
252
275
  const entities = common.getEntities(source, aliasProject.allowRoles);
253
276
 
277
+ let extensionsImportLines = [];
278
+ let extensionsExportLines = [];
279
+ let extensionsTypes = [];
280
+
281
+ if (Array.isArray(aliasProject.features)) {
282
+ if (aliasProject.features.includes("auth")) {
283
+ extensionsImportLines.push('import * as AuthExtension from "mushroomjs-auth";');
284
+ extensionsExportLines.push('Auth: AuthExtension');
285
+ extensionsTypes.push("AuthExtension.IMushroomAuth & ");
286
+ }
287
+ if (aliasProject.features.includes("file")) {
288
+ extensionsImportLines.push('import * as FileExtension from "mushroomjs-file";');
289
+ extensionsExportLines.push('File: FileExtension');
290
+ extensionsTypes.push("FileExtension.IMushroomFile & ");
291
+ }
292
+ }
293
+
254
294
  let code = `import { IdType, IMushroom, Mushroom, MushroomRequest, MushroomRequestSetting, MushroomRestfulRequest, MushroomResponse, MushroomResourceBase, MushroomListResource, MushroomFindByIdResource, MushroomCreateResource, MushroomBatchCreateResource, MushroomUpdateResource, MushroomBatchUpdateResource, MushroomPartialUpdateResource, MushroomDeleteResource, MushroomBatchDeleteResource, MushroomExtensibleResource, MushroomViewFunction, MushroomError } from "mushroomjs";
255
- ${Array.isArray(aliasProject.features) && aliasProject.features.includes("auth") ? 'import { IMushroomAuth } from "mushroomjs-auth";' : ""}
256
- ${Array.isArray(aliasProject.features) && aliasProject.features.includes("file") ? 'import { IMushroomFile } from "mushroomjs-file";' : ""}
295
+ export * from "mushroomjs";
296
+ ${extensionsImportLines.join("\n")}
297
+ export declare const extensions = {
298
+ ${extensionsExportLines.join(",\n ")}
299
+ };
257
300
 
258
301
  export declare type ISODateValue = string | Date;
259
302
  export declare type IdValue = ${source.idType == "AutoIncInt" || source.idType == "AutoIncLong" ? "number" : "string"};
@@ -266,7 +309,7 @@ export declare type IdValue = ${source.idType == "AutoIncInt" || source.idType =
266
309
 
267
310
  const entity = entities[entityName];
268
311
  const typescriptClassName = toTypeScriptClassName(entityName);
269
- code += `interface ${typescriptClassName} ${generateTypescriptClass(entity.fields)};
312
+ code += `export interface ${typescriptClassName} ${generateTypescriptClass(entity.fields)};
270
313
  `;
271
314
 
272
315
 
@@ -320,7 +363,7 @@ export declare type IdValue = ${source.idType == "AutoIncInt" || source.idType =
320
363
  }
321
364
  default: {
322
365
  if (actionName.indexOf("_raw_http_method_") === 0) {
323
- customMethodCode += ` ${actionName.substr("_raw_http_method_".length)}Async: (rawRequest: MushroomRequest) => Promise<MushroomResponse<any>>,
366
+ customMethodCode += ` ${actionName.substring("_raw_http_method_".length)}Async: (rawRequest: MushroomRequest) => Promise<MushroomResponse<any>>,
324
367
  `;
325
368
  break;
326
369
  }
@@ -333,7 +376,7 @@ export declare type IdValue = ${source.idType == "AutoIncInt" || source.idType =
333
376
  }
334
377
 
335
378
  if (customMethodCode) {
336
- code += `interface ${typescriptClassName}$CustomMethodResource {
379
+ code += `export interface ${typescriptClassName}$CustomMethodResource {
337
380
  ${customMethodCode}}
338
381
  `;
339
382
  iApiClassBody += ` & ${typescriptClassName}$CustomMethodResource`;
@@ -351,7 +394,7 @@ ${customMethodCode}}
351
394
 
352
395
  const viewParameterTypes = viewRoles.map(view => {
353
396
  const type = `${typescriptClassName}$ViewsResource_${viewName}View_${view.grant === "*" ? "" : toTypeScriptClassName(view.grant)}Parameters`;
354
- code += `interface ${type} ${generateTypescriptClassFromViewParameters(view.parameters)};
397
+ code += `export interface ${type} ${generateTypescriptClassFromViewParameters(view.parameters)};
355
398
  `;
356
399
  return `MushroomViewFunction<any, ${type}>`;
357
400
  });
@@ -360,7 +403,7 @@ ${customMethodCode}}
360
403
  }
361
404
 
362
405
  if (viewCode) {
363
- code += `interface ${typescriptClassName}$ViewsResource {
406
+ code += `export interface ${typescriptClassName}$ViewsResource {
364
407
  views: {${viewCode}
365
408
  }
366
409
  }
@@ -373,10 +416,10 @@ ${customMethodCode}}
373
416
  }
374
417
 
375
418
  code += `
376
- interface IApi extends IMushroom {
419
+ export interface IApi extends IMushroom {
377
420
  ${iApiClassBody}};
378
421
 
379
- declare type Api = ${Array.isArray(aliasProject.features) && aliasProject.features.includes("auth") ? "IMushroomAuth & " : ""}${Array.isArray(aliasProject.features) && aliasProject.features.includes("file") ? "IMushroomFile & " : ""}IApi;
422
+ declare type Api = ${extensionsTypes.join('')}IApi;
380
423
  declare const _default: Api;
381
424
  export default _default;`;
382
425
 
package/gen.js CHANGED
@@ -24,8 +24,8 @@ async function gen(args) {
24
24
 
25
25
  const atIndex = projectName.indexOf("@");
26
26
  if (atIndex !== -1) {
27
- alias = projectName.substr(atIndex + 1);
28
- projectName = projectName.substr(0, atIndex);
27
+ alias = projectName.substring(atIndex + 1);
28
+ projectName = projectName.substring(0, atIndex);
29
29
  if (!projectName) {
30
30
  help(args);
31
31
  return;
@@ -205,7 +205,7 @@ function processMasterFile(basePath, master) {
205
205
  action.defaultSortings = action.sorting.split(',').map(f => {
206
206
  const c = f.charAt(0);
207
207
  return {
208
- field: c === "+" || c === "-" ? f.substr(1) : f,
208
+ field: c === "+" || c === "-" ? f.substring(1) : f,
209
209
  type: c === "-" ? "Desc" : "Asc"
210
210
  }
211
211
  });
@@ -216,7 +216,7 @@ function processMasterFile(basePath, master) {
216
216
  action.allowSortings = action.allowSorting.split(',').map(f => {
217
217
  const c = f.charAt(0);
218
218
  return {
219
- field: c === "+" || c === "-" ? f.substr(1) : f,
219
+ field: c === "+" || c === "-" ? f.substring(1) : f,
220
220
  type: c === "-" ? "Desc" : c === "+" ? "Asc" : "Both"
221
221
  }
222
222
  });
package/mr.js CHANGED
@@ -8,6 +8,10 @@ const help = require("./help.js");
8
8
  const package = require("./package.json");
9
9
  const checkUpdate = require("./check-update");
10
10
 
11
+ const versionGroup = package.version.match(/([^-]+)(-(\w+).*)?/);
12
+ const currentDistTag = versionGroup[3] ? versionGroup[3] : "latest";
13
+ console.log("Mushroom CLI version " + package.version);
14
+
11
15
  async function run(args) {
12
16
  let debugMode = false;
13
17
  if (args.indexOf("--debug") !== -1) {
@@ -59,8 +63,8 @@ async function run(args) {
59
63
  if (checkUpdateTask !== null)
60
64
  try {
61
65
  var data = await checkUpdateTask;
62
- if (data.version && data.version !== package.version) {
63
- console.warn("YOUR mushroom-cli VERSION IS NOT LATEST. PLEASE RUN: npm i mushroom-cli@" + data.version);
66
+ if (data["dist-tags"] && data["dist-tags"][currentDistTag] && data["dist-tags"][currentDistTag] !== package.version) {
67
+ console.warn(`YOUR mushroom-cli VERSION IS NOT LATEST (dist-tags: ${currentDistTag}). PLEASE RUN: npm i mushroom-cli@${data["dist-tags"][currentDistTag]}`);
64
68
  }
65
69
  }
66
70
  catch(e) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mushroom-cli",
3
- "version": "1.1.0-alpha.1",
3
+ "version": "1.1.0-alpha.12",
4
4
  "description": "Mushroom CLI",
5
5
  "main": "mr.js",
6
6
  "scripts": {
@@ -17,10 +17,10 @@
17
17
  "author": "suco2007",
18
18
  "license": "ISC",
19
19
  "dependencies": {
20
- "jsdom": "^16.2.2",
21
- "json5": "^2.1.2",
22
- "node-fetch": "^2.6.0",
23
- "open": "^7.0.3",
20
+ "jsdom": "^19.0.0",
21
+ "json5": "^2.2.1",
22
+ "node-fetch": "^3.2.3",
23
+ "open": "^8.4.0",
24
24
  "readline-sync": "^1.4.10",
25
25
  "targz": "^1.0.1"
26
26
  }