@necessarylion/adonis-autoswagger 0.0.4 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/adonis_helpers.d.ts +21 -0
  2. package/dist/{adonishelpers.js → adonis_helpers.js} +17 -2
  3. package/dist/auto_swagger.d.ts +28 -0
  4. package/dist/{autoswagger.js → auto_swagger.js} +43 -394
  5. package/dist/example.d.ts +47 -0
  6. package/dist/example.js +48 -1
  7. package/dist/file.d.ts +44 -0
  8. package/dist/file.js +93 -0
  9. package/dist/helpers.d.ts +11 -2
  10. package/dist/helpers.js +11 -25
  11. package/dist/index.d.ts +1 -1
  12. package/dist/index.js +2 -2
  13. package/dist/parsers/comment_parser.d.ts +10 -0
  14. package/dist/parsers/comment_parser.js +417 -0
  15. package/dist/parsers/enum_parser.d.ts +5 -0
  16. package/dist/parsers/enum_parser.js +51 -0
  17. package/dist/parsers/helpers.d.ts +13 -0
  18. package/dist/parsers/helpers.js +38 -0
  19. package/dist/parsers/index.d.ts +6 -0
  20. package/dist/parsers/index.js +22 -0
  21. package/dist/parsers/interface_parser.d.ts +13 -0
  22. package/dist/parsers/interface_parser.js +249 -0
  23. package/dist/parsers/model_parser.d.ts +11 -0
  24. package/dist/parsers/model_parser.js +234 -0
  25. package/dist/parsers/route_parser.d.ts +10 -0
  26. package/dist/parsers/route_parser.js +46 -0
  27. package/dist/parsers/validator_parser.d.ts +7 -0
  28. package/dist/parsers/validator_parser.js +192 -0
  29. package/dist/schema.d.ts +46 -0
  30. package/dist/schema.js +266 -0
  31. package/dist/types.d.ts +16 -17
  32. package/dist/ui.d.ts +31 -0
  33. package/dist/ui.js +157 -0
  34. package/package.json +2 -2
  35. package/dist/adonishelpers.d.ts +0 -6
  36. package/dist/autoswagger.d.ts +0 -30
  37. package/dist/parsers.d.ts +0 -83
  38. package/dist/parsers.js +0 -1142
  39. /package/dist/{scalarCustomCss.d.ts → scalar_custom_css.d.ts} +0 -0
  40. /package/dist/{scalarCustomCss.js → scalar_custom_css.js} +0 -0
@@ -0,0 +1,192 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ValidatorParser = void 0;
7
+ const example_1 = __importDefault(require("../example"));
8
+ const lodash_1 = __importDefault(require("lodash"));
9
+ class ValidatorParser {
10
+ exampleGenerator;
11
+ constructor() {
12
+ this.exampleGenerator = new example_1.default({});
13
+ }
14
+ async validatorToObject(validator) {
15
+ const obj = {
16
+ type: "object",
17
+ ...this.#parseSchema(validator.toJSON()["schema"]["schema"], validator.toJSON()["refs"]),
18
+ };
19
+ const testObj = this.#objToTest(obj["properties"]);
20
+ return await this.#parsePropsAndMeta(obj, testObj, validator);
21
+ }
22
+ async #parsePropsAndMeta(obj, testObj, validator) {
23
+ const { SimpleMessagesProvider } = require("@vinejs/vine");
24
+ const [e] = await validator.tryValidate(testObj, {
25
+ messagesProvider: new SimpleMessagesProvider({
26
+ required: "REQUIRED",
27
+ string: "TYPE",
28
+ object: "TYPE",
29
+ number: "TYPE",
30
+ boolean: "TYPE",
31
+ }),
32
+ });
33
+ // if no errors, this means all object-fields are of type number (which we use by default)
34
+ // and we can return the object
35
+ if (e === null) {
36
+ obj["example"] = testObj;
37
+ return obj;
38
+ }
39
+ const messages = e.messages;
40
+ for (const message of messages) {
41
+ const error = message["message"];
42
+ let objField = message["field"].replace(".", ".properties.");
43
+ if (message["field"].includes(".0")) {
44
+ objField = objField.replaceAll(`.0`, ".items");
45
+ }
46
+ if (error === "TYPE") {
47
+ lodash_1.default.set(obj["properties"], objField, {
48
+ ...lodash_1.default.get(obj["properties"], objField),
49
+ type: message["rule"],
50
+ example: this.exampleGenerator.exampleByType(message["rule"]),
51
+ });
52
+ if (message["rule"] === "string") {
53
+ if (lodash_1.default.get(obj["properties"], objField)["minimum"]) {
54
+ lodash_1.default.set(obj["properties"], objField, {
55
+ ...lodash_1.default.get(obj["properties"], objField),
56
+ minLength: lodash_1.default.get(obj["properties"], objField)["minimum"],
57
+ });
58
+ lodash_1.default.unset(obj["properties"], objField + ".minimum");
59
+ }
60
+ if (lodash_1.default.get(obj["properties"], objField)["maximum"]) {
61
+ lodash_1.default.set(obj["properties"], objField, {
62
+ ...lodash_1.default.get(obj["properties"], objField),
63
+ maxLength: lodash_1.default.get(obj["properties"], objField)["maximum"],
64
+ });
65
+ lodash_1.default.unset(obj["properties"], objField + ".maximum");
66
+ }
67
+ }
68
+ lodash_1.default.set(testObj, message["field"], this.exampleGenerator.exampleByType(message["rule"]));
69
+ }
70
+ if (error === "FORMAT") {
71
+ lodash_1.default.set(obj["properties"], objField, {
72
+ ...lodash_1.default.get(obj["properties"], objField),
73
+ format: message["rule"],
74
+ type: "string",
75
+ example: this.exampleGenerator.exampleByValidatorRule(message["rule"]),
76
+ });
77
+ lodash_1.default.set(testObj, message["field"], this.exampleGenerator.exampleByValidatorRule(message["rule"]));
78
+ }
79
+ }
80
+ obj["example"] = testObj;
81
+ return obj;
82
+ }
83
+ #objToTest(obj) {
84
+ const res = {};
85
+ Object.keys(obj).forEach((key) => {
86
+ if (obj[key]["type"] === "object") {
87
+ res[key] = this.#objToTest(obj[key]["properties"]);
88
+ }
89
+ else if (obj[key]["type"] === "array") {
90
+ if (obj[key]["items"]["type"] === "object") {
91
+ res[key] = [this.#objToTest(obj[key]["items"]["properties"])];
92
+ }
93
+ else {
94
+ res[key] = [obj[key]["items"]["example"]];
95
+ }
96
+ }
97
+ else {
98
+ res[key] = obj[key]["example"];
99
+ }
100
+ });
101
+ return res;
102
+ }
103
+ #parseSchema(json, refs) {
104
+ const obj = {};
105
+ const required = [];
106
+ for (const property of json["properties"]) {
107
+ let meta = this.#getMetaFromValidations(property["validations"], refs);
108
+ const type = property["type"];
109
+ const field = property["fieldName"];
110
+ if (type === "object") {
111
+ console.log(field, property);
112
+ obj[field] = { type: "object", ...this.#parseSchema(property, refs) };
113
+ }
114
+ else {
115
+ // if array
116
+ if (type === "array") {
117
+ if (property["each"]["type"] === "object") {
118
+ obj[field] = {
119
+ type: "array",
120
+ items: {
121
+ type: "object",
122
+ ...this.#parseSchema(property["each"], refs),
123
+ },
124
+ };
125
+ }
126
+ else {
127
+ const meta = this.#getMetaFromValidations(property["each"]["validations"], refs);
128
+ obj[field] = {
129
+ type: "array",
130
+ items: {
131
+ type: this.#getType(property["each"]["type"]),
132
+ ...meta,
133
+ example: meta.example ??
134
+ meta.minimum ??
135
+ this.exampleGenerator.exampleByType("number"),
136
+ },
137
+ };
138
+ }
139
+ }
140
+ else {
141
+ obj[field] = {
142
+ type: this.#getType(type),
143
+ example: meta.example ??
144
+ meta.minimum ??
145
+ this.exampleGenerator.exampleByType("number"),
146
+ ...meta,
147
+ };
148
+ }
149
+ }
150
+ if (!property["isOptional"])
151
+ required.push(property["fieldName"]);
152
+ }
153
+ const result = { properties: obj };
154
+ if (required.length > 0)
155
+ result["required"] = required;
156
+ return result;
157
+ }
158
+ #getType(type) {
159
+ if (type == "literal") {
160
+ return "string";
161
+ }
162
+ return type;
163
+ }
164
+ #getMetaFromValidations(validations, refs) {
165
+ let meta = {};
166
+ for (const validation of validations) {
167
+ if (refs[validation["ruleFnId"]].options?.example) {
168
+ meta = {
169
+ ...meta,
170
+ example: refs[validation["ruleFnId"]].options.example,
171
+ };
172
+ }
173
+ if (refs[validation["ruleFnId"]].options?.min) {
174
+ meta = { ...meta, minimum: refs[validation["ruleFnId"]].options.min };
175
+ }
176
+ if (refs[validation["ruleFnId"]].options?.max) {
177
+ meta = { ...meta, maximum: refs[validation["ruleFnId"]].options.max };
178
+ }
179
+ if (refs[validation["ruleFnId"]].options?.choices) {
180
+ meta = { ...meta, enum: refs[validation["ruleFnId"]].options.choices };
181
+ }
182
+ if (refs[validation["ruleFnId"]].options?.toString().includes("/")) {
183
+ meta = {
184
+ ...meta,
185
+ pattern: refs[validation["ruleFnId"]].options.toString(),
186
+ };
187
+ }
188
+ }
189
+ return meta;
190
+ }
191
+ }
192
+ exports.ValidatorParser = ValidatorParser;
@@ -0,0 +1,46 @@
1
+ import { InterfaceParser, ModelParser, ValidatorParser, EnumParser, CommentParser, RouteParser } from "./parsers/index";
2
+ import { FileService } from "./file";
3
+ import { options } from "./types";
4
+ export declare class SchemaService {
5
+ protected options: options;
6
+ protected schemas: Record<string, any>;
7
+ protected commentParser: CommentParser;
8
+ protected modelParser: ModelParser;
9
+ protected interfaceParser: InterfaceParser;
10
+ protected enumParser: EnumParser;
11
+ protected routeParser: RouteParser;
12
+ protected validatorParser: ValidatorParser;
13
+ protected customPaths: Record<string, any>;
14
+ protected fileService: FileService;
15
+ constructor(options: options);
16
+ /**
17
+ * Get all schemas
18
+ * @returns
19
+ */
20
+ getSchemas(): Promise<Record<string, any>>;
21
+ /**
22
+ * Get all validators
23
+ * @returns
24
+ */
25
+ getValidators(): Promise<Record<string, any>>;
26
+ /**
27
+ * Get all serializers
28
+ * @returns
29
+ */
30
+ getSerializers(): Promise<Record<string, any>>;
31
+ /**
32
+ * Get all models
33
+ * @returns
34
+ */
35
+ getModels(): Promise<Record<string, any>>;
36
+ /**
37
+ * Get all interfaces
38
+ * @returns
39
+ */
40
+ getInterfaces(): Promise<Record<string, any>>;
41
+ /**
42
+ * Get all enums
43
+ * @returns
44
+ */
45
+ getEnums(): Promise<Record<string, any>>;
46
+ }
package/dist/schema.js ADDED
@@ -0,0 +1,266 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.SchemaService = void 0;
7
+ const path_1 = __importDefault(require("path"));
8
+ const util_1 = __importDefault(require("util"));
9
+ const fs_1 = __importDefault(require("fs"));
10
+ const index_1 = require("./parsers/index");
11
+ const example_1 = require("./example");
12
+ const file_1 = require("./file");
13
+ const fs_2 = require("fs");
14
+ class SchemaService {
15
+ options;
16
+ schemas = {};
17
+ commentParser;
18
+ modelParser;
19
+ interfaceParser;
20
+ enumParser;
21
+ routeParser;
22
+ validatorParser;
23
+ customPaths = {};
24
+ fileService;
25
+ constructor(options) {
26
+ this.options = options;
27
+ this.modelParser = new index_1.ModelParser(this.options.snakeCase);
28
+ this.interfaceParser = new index_1.InterfaceParser(this.options.snakeCase);
29
+ this.validatorParser = new index_1.ValidatorParser();
30
+ this.enumParser = new index_1.EnumParser();
31
+ this.fileService = new file_1.FileService();
32
+ }
33
+ /**
34
+ * Get all schemas
35
+ * @returns
36
+ */
37
+ async getSchemas() {
38
+ let schemas = {
39
+ Any: {
40
+ description: "Any JSON object not defined as schema",
41
+ },
42
+ };
43
+ schemas = {
44
+ ...schemas,
45
+ ...(await this.getInterfaces()),
46
+ ...(await this.getSerializers()),
47
+ ...(await this.getModels()),
48
+ ...(await this.getValidators()),
49
+ ...(await this.getEnums()),
50
+ };
51
+ return schemas;
52
+ }
53
+ /**
54
+ * Get all validators
55
+ * @returns
56
+ */
57
+ async getValidators() {
58
+ const validators = {};
59
+ let p6 = path_1.default.join(this.options.appPath, "validators");
60
+ if (typeof this.customPaths["#validators"] !== "undefined") {
61
+ // it's v6
62
+ p6 = p6.replaceAll("app/validators", this.customPaths["#validators"]);
63
+ p6 = p6.replaceAll("app\\validators", this.customPaths["#validators"]);
64
+ }
65
+ if (!(0, fs_2.existsSync)(p6)) {
66
+ if (this.options.debug) {
67
+ console.log("Validators paths don't exist", p6);
68
+ }
69
+ return validators;
70
+ }
71
+ const files = await this.fileService.getFiles(p6, []);
72
+ if (this.options.debug) {
73
+ console.log("Found validator files", files);
74
+ }
75
+ try {
76
+ for (let file of files) {
77
+ if (/^[a-zA-Z]:/.test(file)) {
78
+ file = "file:///" + file;
79
+ }
80
+ const val = await import(file);
81
+ for (const [key, value] of Object.entries(val)) {
82
+ if (value.constructor.name.includes("VineValidator")) {
83
+ validators[key] = await this.validatorParser.validatorToObject(value);
84
+ validators[key].description = key + " (Validator)";
85
+ }
86
+ }
87
+ }
88
+ }
89
+ catch (e) {
90
+ console.log("**You are probably using 'node ace serve --hmr', which is not supported yet. Use 'node ace serve --watch' instead.**");
91
+ console.error(e.message);
92
+ }
93
+ return validators;
94
+ }
95
+ /**
96
+ * Get all serializers
97
+ * @returns
98
+ */
99
+ async getSerializers() {
100
+ const serializers = {};
101
+ let p6 = path_1.default.join(this.options.appPath, "serializers");
102
+ if (typeof this.customPaths["#serializers"] !== "undefined") {
103
+ // it's v6
104
+ p6 = p6.replaceAll("app/serializers", this.customPaths["#serializers"]);
105
+ p6 = p6.replaceAll("app\\serializers", this.customPaths["#serializers"]);
106
+ }
107
+ if (!(0, fs_2.existsSync)(p6)) {
108
+ if (this.options.debug) {
109
+ console.log("Serializers paths don't exist", p6);
110
+ }
111
+ return serializers;
112
+ }
113
+ const files = await this.fileService.getFiles(p6, []);
114
+ if (this.options.debug) {
115
+ console.log("Found serializer files", files);
116
+ }
117
+ for (let file of files) {
118
+ if (/^[a-zA-Z]:/.test(file)) {
119
+ file = "file:///" + file;
120
+ }
121
+ const val = await import(file);
122
+ for (const [key, value] of Object.entries(val)) {
123
+ if (key.indexOf("Serializer") > -1) {
124
+ serializers[key] = value;
125
+ }
126
+ }
127
+ }
128
+ return serializers;
129
+ }
130
+ /**
131
+ * Get all models
132
+ * @returns
133
+ */
134
+ async getModels() {
135
+ const models = {};
136
+ let p = path_1.default.join(this.options.appPath, "Models");
137
+ let p6 = path_1.default.join(this.options.appPath, "models");
138
+ if (typeof this.customPaths["#models"] !== "undefined") {
139
+ // it's v6
140
+ p6 = p6.replaceAll("app/models", this.customPaths["#models"]);
141
+ p6 = p6.replaceAll("app\\models", this.customPaths["#models"]);
142
+ }
143
+ if (!(0, fs_2.existsSync)(p) && !(0, fs_2.existsSync)(p6)) {
144
+ if (this.options.debug) {
145
+ console.log("Model paths don't exist", p, p6);
146
+ }
147
+ return models;
148
+ }
149
+ if ((0, fs_2.existsSync)(p6)) {
150
+ p = p6;
151
+ }
152
+ const files = await this.fileService.getFiles(p, []);
153
+ const readFile = util_1.default.promisify(fs_1.default.readFile);
154
+ if (this.options.debug) {
155
+ console.log("Found model files", files);
156
+ }
157
+ for (let file of files) {
158
+ file = file.replace(".js", "");
159
+ const data = await readFile(file, "utf8");
160
+ file = file.replace(".ts", "");
161
+ const split = file.split("/");
162
+ let name = split[split.length - 1].replace(".ts", "");
163
+ file = file.replace("app/", "/app/");
164
+ const parsed = this.modelParser.parseModelProperties(data);
165
+ if (parsed.name !== "") {
166
+ name = parsed.name;
167
+ }
168
+ let schema = {
169
+ type: "object",
170
+ properties: parsed.props,
171
+ description: name + " (Model)",
172
+ };
173
+ if (parsed.required.length > 0) {
174
+ schema["required"] = parsed.required;
175
+ }
176
+ if (name.toLowerCase().includes("readme.md"))
177
+ continue;
178
+ models[name] = schema;
179
+ }
180
+ return models;
181
+ }
182
+ /**
183
+ * Get all interfaces
184
+ * @returns
185
+ */
186
+ async getInterfaces() {
187
+ let interfaces = {
188
+ ...example_1.ExampleInterfaces.paginationInterface(),
189
+ };
190
+ let p = path_1.default.join(this.options.appPath, "Interfaces");
191
+ let p6 = path_1.default.join(this.options.appPath, "interfaces");
192
+ if (typeof this.customPaths["#interfaces"] !== "undefined") {
193
+ // it's v6
194
+ p6 = p6.replaceAll("app/interfaces", this.customPaths["#interfaces"]);
195
+ p6 = p6.replaceAll("app\\interfaces", this.customPaths["#interfaces"]);
196
+ }
197
+ if (!(0, fs_2.existsSync)(p) && !(0, fs_2.existsSync)(p6)) {
198
+ if (this.options.debug) {
199
+ console.log("Interface paths don't exist", p, p6);
200
+ }
201
+ return interfaces;
202
+ }
203
+ if ((0, fs_2.existsSync)(p6)) {
204
+ p = p6;
205
+ }
206
+ const files = await this.fileService.getFiles(p, []);
207
+ if (this.options.debug) {
208
+ console.log("Found interfaces files", files);
209
+ }
210
+ const readFile = util_1.default.promisify(fs_1.default.readFile);
211
+ for (let file of files) {
212
+ file = file.replace(".js", "");
213
+ const data = await readFile(file, "utf8");
214
+ file = file.replace(".ts", "");
215
+ interfaces = {
216
+ ...interfaces,
217
+ ...this.interfaceParser.parseInterfaces(data),
218
+ };
219
+ }
220
+ return interfaces;
221
+ }
222
+ /**
223
+ * Get all enums
224
+ * @returns
225
+ */
226
+ async getEnums() {
227
+ let enums = {};
228
+ const enumParser = new index_1.EnumParser();
229
+ let p = path_1.default.join(this.options.appPath, "Types");
230
+ let p6 = path_1.default.join(this.options.appPath, "types");
231
+ if (typeof this.customPaths["#types"] !== "undefined") {
232
+ // it's v6
233
+ p6 = p6.replaceAll("app/types", this.customPaths["#types"]);
234
+ p6 = p6.replaceAll("app\\types", this.customPaths["#types"]);
235
+ }
236
+ if (!(0, fs_2.existsSync)(p) && !(0, fs_2.existsSync)(p6)) {
237
+ if (this.options.debug) {
238
+ console.log("Enum paths don't exist", p, p6);
239
+ }
240
+ return enums;
241
+ }
242
+ if ((0, fs_2.existsSync)(p6)) {
243
+ p = p6;
244
+ }
245
+ const files = await this.fileService.getFiles(p, []);
246
+ if (this.options.debug) {
247
+ console.log("Found enum files", files);
248
+ }
249
+ const readFile = util_1.default.promisify(fs_1.default.readFile);
250
+ for (let file of files) {
251
+ file = file.replace(".js", "");
252
+ const data = await readFile(file, "utf8");
253
+ file = file.replace(".ts", "");
254
+ const split = file.split("/");
255
+ const name = split[split.length - 1].replace(".ts", "");
256
+ file = file.replace("app/", "/app/");
257
+ const parsedEnums = enumParser.parseEnums(data);
258
+ enums = {
259
+ ...enums,
260
+ ...parsedEnums,
261
+ };
262
+ }
263
+ return enums;
264
+ }
265
+ }
266
+ exports.SchemaService = SchemaService;
package/dist/types.d.ts CHANGED
@@ -29,32 +29,31 @@ export interface common {
29
29
  * Adonis routes
30
30
  */
31
31
  export interface AdonisRouteMeta {
32
- resolvedHandler: {
33
- type: string;
32
+ resolvedHandler?: {
33
+ type?: string;
34
34
  namespace?: string;
35
35
  method?: string;
36
36
  };
37
- resolvedMiddleware: Array<{
38
- type: string;
37
+ resolvedMiddleware?: Array<{
38
+ type?: string;
39
39
  args?: any[];
40
40
  }>;
41
41
  }
42
- export interface v6Handler {
42
+ export interface V6Handler {
43
43
  method?: string;
44
- moduleNameOrPath?: string;
45
- reference: string | any[];
46
- name: string;
44
+ moduleNameOrPath?: any;
45
+ reference?: any;
46
+ handle?: any;
47
+ name?: any;
47
48
  }
48
49
  export interface AdonisRoute {
49
- methods: string[];
50
- pattern: string;
51
- meta: AdonisRouteMeta;
52
- middleware: string[] | any;
50
+ methods?: string[];
51
+ pattern?: string;
52
+ meta?: AdonisRouteMeta;
53
+ middleware?: string[] | any;
53
54
  name?: string;
54
- params: string[];
55
- handler?: string | v6Handler;
56
- }
57
- export interface AdonisRoutes {
58
- root: AdonisRoute[];
55
+ params?: string[];
56
+ handler?: any;
59
57
  }
58
+ export type AdonisRoutes = Record<string, AdonisRoute[]>;
60
59
  export declare const standardTypes: string[];
package/dist/ui.d.ts ADDED
@@ -0,0 +1,31 @@
1
+ import type { options } from "./types";
2
+ export declare class UIService {
3
+ /**
4
+ * Swagger UI
5
+ * @param url string
6
+ * @param options options
7
+ * @returns
8
+ */
9
+ ui(url: string, options?: options): string;
10
+ /**
11
+ * Rapidoc UI
12
+ * @param url string
13
+ * @param style string
14
+ * @returns
15
+ */
16
+ rapidoc(url: string, style?: string): string;
17
+ /**
18
+ * Scalar UI
19
+ * @param url string
20
+ * @param proxyUrl string
21
+ * @returns
22
+ */
23
+ scalar(url: string, proxyUrl?: string): string;
24
+ /**
25
+ * Stoplight UI
26
+ * @param url string
27
+ * @param theme "light" | "dark"
28
+ * @returns
29
+ */
30
+ stoplight(url: string, theme?: "light" | "dark"): string;
31
+ }