svelte-reflector 1.0.9 → 1.0.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.
Files changed (59) hide show
  1. package/dist/generate-doc.js +3 -0
  2. package/dist/helpers/helpers.d.ts +4 -0
  3. package/dist/helpers/helpers.js +38 -2
  4. package/dist/main.js +11 -8
  5. package/dist/method.d.ts +9 -4
  6. package/dist/method.js +68 -53
  7. package/dist/module.d.ts +8 -1
  8. package/dist/module.js +89 -23
  9. package/dist/property.d.ts +8 -1
  10. package/dist/property.js +55 -22
  11. package/dist/reflector/controllers/admin/account/admin-account.module.svelte.d.ts +7 -0
  12. package/dist/reflector/controllers/admin/account/admin-account.module.svelte.js +28 -0
  13. package/dist/reflector/controllers/admin/account/owner/account-owner.module.svelte.d.ts +15 -0
  14. package/dist/reflector/controllers/admin/account/owner/account-owner.module.svelte.js +79 -0
  15. package/dist/reflector/controllers/admin/kyc/config/kyc-config.module.svelte.d.ts +49 -0
  16. package/dist/reflector/controllers/admin/kyc/config/kyc-config.module.svelte.js +303 -0
  17. package/dist/reflector/controllers/admin/policy/system/policy-system.module.svelte.d.ts +9 -0
  18. package/dist/reflector/controllers/admin/policy/system/policy-system.module.svelte.js +36 -0
  19. package/dist/reflector/controllers/admin/smtp/config/smtp-config.module.svelte.d.ts +19 -0
  20. package/dist/reflector/controllers/admin/smtp/config/smtp-config.module.svelte.js +82 -0
  21. package/dist/reflector/controllers/customer/kyc/file-upload/kyc-file-upload.module.svelte.d.ts +37 -0
  22. package/dist/reflector/controllers/customer/kyc/file-upload/kyc-file-upload.module.svelte.js +228 -0
  23. package/dist/reflector/controllers/member/account/member-account.module.svelte.d.ts +11 -0
  24. package/dist/reflector/controllers/member/account/member-account.module.svelte.js +54 -0
  25. package/dist/reflector/controllers/owner/account/owner-account.module.svelte.d.ts +11 -0
  26. package/dist/reflector/controllers/owner/account/owner-account.module.svelte.js +54 -0
  27. package/dist/reflector/controllers/owner/kyc/config/kyc-config.module.svelte.d.ts +49 -0
  28. package/dist/reflector/controllers/owner/kyc/config/kyc-config.module.svelte.js +303 -0
  29. package/dist/reflector/controllers/owner/kyc/self/create-or-update/self-create-or-update.module.svelte.d.ts +33 -0
  30. package/dist/reflector/controllers/owner/kyc/self/create-or-update/self-create-or-update.module.svelte.js +197 -0
  31. package/dist/reflector/controllers/owner/policy/owner-policy.module.svelte.d.ts +9 -0
  32. package/dist/reflector/controllers/owner/policy/owner-policy.module.svelte.js +36 -0
  33. package/dist/reflector/controllers/owner/smtp/config/smtp-config.module.svelte.d.ts +19 -0
  34. package/dist/reflector/controllers/owner/smtp/config/smtp-config.module.svelte.js +82 -0
  35. package/dist/reflector/controllers/public/auth/sign-in-firebase/auth-sign-in-firebase.module.svelte.d.ts +29 -0
  36. package/dist/reflector/controllers/public/auth/sign-in-firebase/auth-sign-in-firebase.module.svelte.js +223 -0
  37. package/dist/reflector/controllers/public/reset-password/tenant/send-recovery-email/tenant-send-recovery-email.module.svelte.d.ts +13 -0
  38. package/dist/reflector/controllers/public/reset-password/tenant/send-recovery-email/tenant-send-recovery-email.module.svelte.js +49 -0
  39. package/dist/reflector/controllers/restricted/account/avatar-file-upload/account-avatar-file-upload.module.svelte.d.ts +19 -0
  40. package/dist/reflector/controllers/restricted/account/avatar-file-upload/account-avatar-file-upload.module.svelte.js +114 -0
  41. package/dist/reflector/controllers/restricted/bank/restricted-bank.module.svelte.d.ts +15 -0
  42. package/dist/reflector/controllers/restricted/bank/restricted-bank.module.svelte.js +78 -0
  43. package/dist/reflector/controllers/restricted/files/presigned-url/files-presigned-url.module.svelte.d.ts +11 -0
  44. package/dist/reflector/controllers/restricted/files/presigned-url/files-presigned-url.module.svelte.js +56 -0
  45. package/dist/reflector/controllers/restricted/notification/restricted-notification.module.svelte.d.ts +9 -0
  46. package/dist/reflector/controllers/restricted/notification/restricted-notification.module.svelte.js +36 -0
  47. package/dist/reflector/controllers/restricted/two-factor-auth/status/two-factor-auth-status.module.svelte.d.ts +15 -0
  48. package/dist/reflector/controllers/restricted/two-factor-auth/status/two-factor-auth-status.module.svelte.js +68 -0
  49. package/dist/reflector/reflector.types.d.ts +4 -0
  50. package/dist/reflector/reflector.types.js +4 -0
  51. package/dist/reflector/schemas.d.ts +357 -0
  52. package/dist/reflector/schemas.js +1709 -0
  53. package/dist/request.d.ts +2 -0
  54. package/dist/request.js +8 -0
  55. package/dist/schema.d.ts +4 -1
  56. package/dist/schema.js +24 -6
  57. package/dist/zodProperty.d.ts +32 -0
  58. package/dist/zodProperty.js +123 -0
  59. package/package.json +1 -1
@@ -4,6 +4,7 @@ import axios from "axios";
4
4
  import * as path from "node:path";
5
5
  import * as fs from "node:fs";
6
6
  import { Reflector } from "./main.js";
7
+ import { Source } from "./file.js";
7
8
  /** ajuda a pegar a 1ª env definida dentre várias chaves possíveis */
8
9
  function pickEnv(...keys) {
9
10
  for (const k of keys) {
@@ -44,6 +45,8 @@ export async function reflector(manual = false) {
44
45
  try {
45
46
  const documentation = await axios.get(DOC_URL, { timeout: 15000 });
46
47
  data = documentation.data;
48
+ const backup = new Source({ path: "src/reflector/backup.json", data: JSON.stringify(data) });
49
+ backup.save();
47
50
  }
48
51
  catch (e) {
49
52
  console.warn(`[reflector] Não foi possível obter a documentação em ${DOC_URL}. Carregando cópia local...`);
@@ -3,9 +3,13 @@ export declare function sanitizeKey(name: string): string;
3
3
  export declare function sanitizeNumber(texto: string): string;
4
4
  export declare function capitalizeFirstLetter(text: string): string;
5
5
  export declare function splitByUppercase(text: string): string[];
6
+ export declare function treatByUppercase(text?: string): string;
6
7
  export declare function createDangerMessage(text: string): void;
8
+ export declare function getFilteredEntities(rawEndpoint: string): string[];
7
9
  export declare function getEndpointAndModuleName(rawEndpoint: string): {
8
10
  baseEndpoint: string;
9
11
  moduleName: string;
10
12
  };
11
13
  export declare function getEndpoint(rawEndpoint: string): string;
14
+ export declare function testeEndpoint(rawEndpoint: string): string;
15
+ export declare function treatenEnum(enums: string[]): string;
@@ -7,6 +7,7 @@
7
7
  // if (!lhs) return "";
8
8
  // return `${lhs.trim()} = ${cleaned}`;
9
9
  // }
10
+ const trashWords = new Set(["Kyc", "Get", "Customer", "Response", "Res", "Self", "Admin"]);
10
11
  export function toCamelCase(str) {
11
12
  return str
12
13
  .split("-")
@@ -34,16 +35,38 @@ export function capitalizeFirstLetter(text) {
34
35
  export function splitByUppercase(text) {
35
36
  return text.split(/(?=[A-Z])/);
36
37
  }
38
+ export function treatByUppercase(text) {
39
+ const base = (text ?? "").trim();
40
+ const raw = base.length > 0 ? base : "entity";
41
+ // Se splitByUppercase tiver tipagem "string[] | undefined", isso resolve.
42
+ const parts = (splitByUppercase(raw) ?? [])
43
+ .map((p) => p.trim())
44
+ .filter((p) => p.length > 0)
45
+ .filter((p) => !trashWords.has(p));
46
+ if (parts.length === 0)
47
+ return "entity";
48
+ const words = parts.length === 1 ? [parts[0], "Entity"] : parts;
49
+ const first = words[0];
50
+ if (!first)
51
+ return "entity"; // deixa o TS 100% feliz
52
+ let out = first.charAt(0).toLowerCase() + first.slice(1);
53
+ for (let i = 1; i < words.length; i++) {
54
+ const w = words[i];
55
+ if (!w)
56
+ continue;
57
+ out += w.charAt(0).toUpperCase() + w.slice(1);
58
+ }
59
+ return out.length > 0 ? out : "entity";
60
+ }
37
61
  export function createDangerMessage(text) {
38
62
  console.log("\x1b[31m%s\x1b[0m", `[!] ${text}`);
39
63
  }
40
- function getFilteredEntities(rawEndpoint) {
64
+ export function getFilteredEntities(rawEndpoint) {
41
65
  const splittedEntitys = rawEndpoint.split("/");
42
66
  return splittedEntitys.filter((item) => item !== "" && !item.includes("{"));
43
67
  }
44
68
  export function getEndpointAndModuleName(rawEndpoint) {
45
69
  const filteredEntitys = getFilteredEntities(rawEndpoint);
46
- // console.log(filteredEntitys);
47
70
  const moduleName = filteredEntitys.map((x) => sanitizeKey(capitalizeFirstLetter(x))).join("");
48
71
  const baseEndpoint = filteredEntitys.join("/");
49
72
  return { baseEndpoint: getEndpoint(baseEndpoint), moduleName };
@@ -52,3 +75,16 @@ export function getEndpoint(rawEndpoint) {
52
75
  const filteredEntitys = getFilteredEntities(rawEndpoint);
53
76
  return filteredEntitys.join("/");
54
77
  }
78
+ export function testeEndpoint(rawEndpoint) {
79
+ const teste = rawEndpoint.split("/");
80
+ const a = teste
81
+ .filter((t) => t !== "")
82
+ .map((str) => {
83
+ return str.includes("}") ? `$${str}` : str;
84
+ });
85
+ return a.join("/");
86
+ }
87
+ export function treatenEnum(enums) {
88
+ const a = enums.map((e) => `"${e}"`);
89
+ return ` z.literal([${a}])`;
90
+ }
package/dist/main.js CHANGED
@@ -1,17 +1,16 @@
1
1
  import * as path from "node:path";
2
2
  import * as fs from "node:fs";
3
3
  import { Source } from "./file.js";
4
- import { getEndpoint, getEndpointAndModuleName, splitByUppercase } from "./helpers/helpers.js";
4
+ import { getEndpoint, splitByUppercase, testeEndpoint } from "./helpers/helpers.js";
5
5
  import { Schema } from "./schema.js";
6
6
  import { Module } from "./module.js";
7
- // const defaultMethods = ["get", "patch", "post", "put", "delete"] as const;
8
7
  export class Reflector {
9
8
  components;
10
9
  paths;
11
10
  dir = "src";
12
11
  generatedDir = `${this.dir}/reflector`;
13
12
  localDoc = new Source({ path: path.resolve(process.cwd(), `${this.dir}/backup.json`) });
14
- src = new Source({ path: path.resolve(process.cwd(), this.generatedDir) });
13
+ src = new Source({ path: path.resolve(process.cwd(), `${this.generatedDir}/controllers`) });
15
14
  typesSrc = new Source({ path: path.resolve(process.cwd(), `${this.generatedDir}/reflector.types.ts`) });
16
15
  schemaFile = new Source({ path: path.resolve(process.cwd(), `${this.generatedDir}/schemas.ts`) });
17
16
  files;
@@ -35,11 +34,12 @@ export class Reflector {
35
34
  if ("$ref" in object || !object.properties)
36
35
  continue;
37
36
  const properties = object.properties;
38
- schemas.push(new Schema({
37
+ const schema = {
39
38
  properties,
40
39
  name: key,
41
40
  requireds: object.required || [],
42
- }));
41
+ };
42
+ schemas.push(new Schema({ ...schema, isEmpty: false }), new Schema({ ...schema, isEmpty: true }));
43
43
  }
44
44
  console.log(`${schemas.length} schemas gerados com sucesso.`);
45
45
  return schemas;
@@ -74,15 +74,18 @@ export class Reflector {
74
74
  return new Module({
75
75
  name,
76
76
  ...info,
77
- dir: this.generatedDir,
77
+ dir: `${this.generatedDir}/controllers`,
78
78
  });
79
79
  });
80
80
  return modules;
81
81
  }
82
82
  build() {
83
- this.schemaFile.changeData([`import z from 'zod';`, ...this.schemas.map((s) => `${s.schema} ${s.type}`)].join("\n\n"));
83
+ const treatedSchemas = this.schemas.map((s) => {
84
+ return `${s.schema} ${s.type}`;
85
+ });
86
+ this.schemaFile.changeData([`import z from 'zod';`, ...treatedSchemas].join("\n\n"));
84
87
  this.schemaFile.save();
85
- this.typesSrc.changeData("export class Behavior { onError?: () => void; onSuccess?: () => void }");
88
+ this.typesSrc.changeData("export class Behavior { onError?: (e) => void; onSuccess?: () => void }");
86
89
  this.typesSrc.save();
87
90
  for (const module of this.modules) {
88
91
  if (module.methods.length === 0)
package/dist/method.d.ts CHANGED
@@ -1,18 +1,23 @@
1
1
  import { Request } from "./request.js";
2
- import { ZodProperty } from "./property.js";
2
+ import { ZodProperty } from "./zodProperty.js";
3
3
  import type { ReflectorOperation } from "./types/types.js";
4
4
  export declare class Method {
5
5
  name: string;
6
- zodProperties: ZodProperty[];
7
6
  description: string | undefined;
8
7
  endpoint: string;
9
8
  request: Request;
9
+ paths: ZodProperty[];
10
+ headers: ZodProperty[];
11
+ querys: ZodProperty[];
12
+ cookies: ZodProperty[];
10
13
  constructor(params: {
11
14
  operation: ReflectorOperation;
12
15
  moduleName: string;
13
16
  });
14
- private getParams;
17
+ private buildZodProperties;
18
+ private readonly gee;
19
+ private getProps;
15
20
  private buildCallMethod;
16
- private buildDescription;
17
21
  build(): string;
22
+ private buildDescription;
18
23
  }
package/dist/method.js CHANGED
@@ -1,81 +1,95 @@
1
1
  import { Request } from "./request.js";
2
- import { ZodProperty } from "./property.js";
3
- import { createDangerMessage, getEndpoint } from "./helpers/helpers.js";
2
+ import { ZodProperty } from "./zodProperty.js";
3
+ import { createDangerMessage, getEndpoint, testeEndpoint, treatByUppercase } from "./helpers/helpers.js";
4
4
  export class Method {
5
5
  name;
6
- zodProperties;
6
+ // zodProperties: ZodProperty[];
7
7
  description;
8
8
  endpoint;
9
9
  request;
10
+ paths = [];
11
+ headers = [];
12
+ querys = [];
13
+ cookies = [];
10
14
  constructor(params) {
11
15
  const { operation } = params;
12
16
  this.request = new Request(operation);
13
17
  this.description = operation.description ?? operation.summary;
14
18
  this.endpoint = operation.endpoint;
15
19
  this.name = operation.operationId?.split("_")[1] ?? this.request.apiType;
16
- const { parameters } = this.getParams(params);
17
- this.zodProperties = parameters;
20
+ this.buildZodProperties(params);
18
21
  }
19
- getParams(params) {
22
+ buildZodProperties(params) {
20
23
  const { operation } = params;
21
- if (!operation.parameters || operation.parameters?.length === 0) {
22
- return { parameters: [] };
23
- }
24
- const parameters = [];
24
+ if (!operation.parameters || operation.parameters?.length === 0)
25
+ return;
25
26
  for (const object of operation.parameters) {
26
27
  if ("$ref" in object)
27
28
  continue;
28
29
  if (!object.schema)
29
30
  continue;
30
- const { required, name, description, schema } = object;
31
+ const { required, name, description, schema, in: inParam } = object;
31
32
  if ("$ref" in schema)
32
33
  continue;
33
- parameters.push(new ZodProperty({
34
+ const zodPropertie = {
34
35
  name,
35
36
  example: schema.default,
36
37
  schemaObject: schema,
37
38
  type: schema.type,
38
39
  description: description ?? "",
39
40
  required: required || true,
40
- }));
41
+ isEmpty: false,
42
+ inParam,
43
+ };
44
+ if (inParam === "query") {
45
+ this.querys.push(new ZodProperty(zodPropertie));
46
+ }
47
+ else if (inParam === "header") {
48
+ this.headers.push(new ZodProperty(zodPropertie));
49
+ }
50
+ else if (inParam === "path") {
51
+ this.paths.push(new ZodProperty(zodPropertie));
52
+ }
53
+ else if (inParam === "cookie") {
54
+ this.paths.push(new ZodProperty(zodPropertie));
55
+ }
41
56
  }
42
- return { parameters };
57
+ }
58
+ gee = (props) => {
59
+ return props.map((x) => x.name).join(",");
60
+ };
61
+ getProps() {
62
+ const headers = this.gee(this.headers);
63
+ const querys = this.gee(this.querys);
64
+ const paths = this.gee(this.paths);
65
+ const cookies = this.gee(this.cookies);
66
+ return `
67
+ ${querys.length > 0 ? `const {${querys}} = repo.intercept.bundle(this.querys)` : ""};
68
+ ${paths.length > 0 ? `const {${paths}} = repo.intercept.bundle(this.paths)` : ""};
69
+ ${cookies.length > 0 ? `const {${cookies}} = repo.intercept.bundle(this.cookies)` : ""};
70
+ `;
43
71
  }
44
72
  buildCallMethod() {
45
- const afterResponse = [];
46
73
  const beforeResponse = [];
47
- const props = this.zodProperties.map((x) => x.name).join(",");
48
- const parameters = `
49
- const bundle = repo.intercept.bundle(this.parameters)
50
- const {${props}} = bundle
51
- `;
52
- const query = `
53
- queryData: {${props}}
54
- `;
74
+ // const props = this.getProps();
55
75
  if (this.request.apiType === "get") {
56
- if (this.zodProperties.length > 0) {
57
- afterResponse.push(parameters);
58
- beforeResponse.push(`\n`);
59
- }
60
76
  if (this.request.attributeType === "list") {
61
- beforeResponse.push(`const {data: { data }, ...params} = response`, "\n\n", `this.list = data`, `repo.intercept.rebuild(this.parameters, params)`);
77
+ beforeResponse.push(`const {data: { data, ...params }} = response`, "\n\n", `this.list = data`, "repo.intercept.rebuild(this.querys, params)");
62
78
  const inside = `
63
- ${afterResponse.join(";")}
64
79
  const response = await repo.api.get<{data: ${this.request.responseType}}, unknown>({
65
80
  endpoint,
66
- ${query}
81
+ queryData: { ${this.gee(this.querys)} }
67
82
  })
68
83
  ${beforeResponse.join(";")}
69
84
  `;
70
85
  return { inside, outside: "" };
71
86
  }
72
87
  else if (this.request.attributeType === "entity") {
73
- beforeResponse.push(`this.entity = response`);
88
+ const entityName = treatByUppercase(this.request.responseType);
89
+ beforeResponse.push(`this.${entityName} = response`);
74
90
  const inside = `
75
- ${afterResponse.join(";")}
76
91
  const response = await repo.api.get<${this.request.responseType}, unknown>({
77
92
  endpoint,
78
- ${query}
79
93
  })
80
94
  ${beforeResponse.join(";")}
81
95
  `;
@@ -83,54 +97,53 @@ export class Method {
83
97
  }
84
98
  }
85
99
  else if (this.request.apiType === "post" || this.request.apiType === "put" || this.request.apiType === "patch") {
86
- let data = "";
100
+ let data;
101
+ let headers;
87
102
  if (this.request.bodyType) {
88
103
  data = `const data = repo.intercept.bundle(this.forms.${this.name})`;
89
104
  }
90
- const outside = ["this.loading = true", data].join("\n");
105
+ const hasHeaders = this.request.parameters.some((p) => p.in === "header");
106
+ const hasData = this.request.bodyType;
107
+ if (hasHeaders) {
108
+ headers = `const headers = repo.intercept.bundle(this.headers)`;
109
+ }
110
+ const outside = ["this.loading = true", data, headers].join("\n");
91
111
  const inside = `
92
- const response = await repo.api.post<${this.request.responseType}>({
112
+ const response = await repo.api.${this.request.apiType}<${this.request.responseType}>({
93
113
  endpoint,
94
- data
114
+ ${hasData ? "data," : ""}
115
+ ${hasHeaders ? "headers," : ""}
95
116
  })
96
117
  `;
97
118
  return { outside, inside };
98
119
  }
99
120
  else if (this.request.apiType === "delete") {
100
- const props = this.zodProperties.map((x) => x.name).join(",");
101
- const propsString = props.length > 0 ? `const {${props}} = this.parameters` : "";
102
121
  const inside = `
103
- ${propsString}
104
-
105
122
  const response = await repo.api.delete<${this.request.responseType ?? "null"}, unknown>({
106
123
  endpoint,
107
- ${query}
108
124
  })
109
-
110
- this.clearEntity()
111
125
  `;
112
126
  const outside = "";
113
127
  return { inside, outside };
114
128
  }
115
129
  return { inside: "", outside: "" };
116
130
  }
117
- buildDescription() {
118
- return `/** ${this.description ?? ""} */`;
119
- }
120
131
  build() {
121
132
  const { inside, outside } = this.buildCallMethod();
122
133
  if (this.name === "list")
123
134
  this.name = "listAll";
124
- const hasProprierties = this.zodProperties.length > 0;
135
+ const hasProprierties = this.querys.length > 0;
125
136
  if (!hasProprierties && this.request.apiType === "delete") {
126
137
  createDangerMessage(`${this.name} não vai funcionar, pois não aceita parâmetros na requisição.`);
127
138
  }
128
139
  const description = this.buildDescription();
140
+ const a = "`";
129
141
  return `
130
142
  ${description}
131
143
  async ${this.name}(behavior: Behavior = new Behavior()) {
132
144
  const {onError, onSuccess} = behavior
133
- const endpoint = "${getEndpoint(this.endpoint)}"
145
+ ${this.getProps()}
146
+ const endpoint = ${a}${testeEndpoint(this.endpoint)}${a}
134
147
 
135
148
  ${outside}
136
149
 
@@ -139,13 +152,15 @@ export class Method {
139
152
  onSuccess?.()
140
153
 
141
154
  return response
142
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
143
155
  } catch(e) {
144
- onError?.()
156
+ onError?.(e)
157
+ } finally {
158
+ this.loading = false
145
159
  }
146
-
147
- this.loading = false
148
160
  }
149
161
  `;
150
162
  }
163
+ buildDescription() {
164
+ return `/** ${this.description ?? ""} */`;
165
+ }
151
166
  }
package/dist/module.d.ts CHANGED
@@ -1,14 +1,19 @@
1
1
  import { Source } from "./file.js";
2
2
  import { Method } from "./method.js";
3
3
  import type { ReflectorOperation } from "./types/types.js";
4
+ import { ZodProperty } from "./zodProperty.js";
4
5
  export declare class Module {
5
6
  readonly name: string;
6
7
  readonly path: string;
7
8
  readonly moduleName: string;
8
9
  readonly src: Source;
9
10
  imports: Set<string>;
10
- parameters: string[];
11
11
  methods: Method[];
12
+ querys: ZodProperty[];
13
+ paths: ZodProperty[];
14
+ headers: ZodProperty[];
15
+ cookies: ZodProperty[];
16
+ moduleConstructor: string;
12
17
  constructor(params: {
13
18
  name: string;
14
19
  moduleName: string;
@@ -16,6 +21,7 @@ export declare class Module {
16
21
  path: string;
17
22
  dir: string;
18
23
  });
24
+ private buildZObject;
19
25
  private creator;
20
26
  private getPath;
21
27
  private getAdditionalMethod;
@@ -23,6 +29,7 @@ export declare class Module {
23
29
  private getParameters;
24
30
  private buildImports;
25
31
  private buildClass;
32
+ private buildConstructor;
26
33
  buildFile(params: {
27
34
  moduleAttributes: string[];
28
35
  moduleTypes: string[];
package/dist/module.js CHANGED
@@ -1,16 +1,21 @@
1
1
  import * as path from "node:path";
2
2
  import * as fs from "node:fs";
3
3
  import { Source } from "./file.js";
4
- import { capitalizeFirstLetter, createDangerMessage } from "./helpers/helpers.js";
4
+ import { capitalizeFirstLetter, createDangerMessage, treatByUppercase } from "./helpers/helpers.js";
5
5
  import { Method } from "./method.js";
6
+ import { ZodProperty } from "./zodProperty.js";
6
7
  export class Module {
7
8
  name;
8
9
  path;
9
10
  moduleName;
10
11
  src;
11
12
  imports;
12
- parameters;
13
13
  methods;
14
+ querys = [];
15
+ paths = [];
16
+ headers = [];
17
+ cookies = [];
18
+ moduleConstructor;
14
19
  constructor(params) {
15
20
  const { name, operations, path, dir, moduleName } = params;
16
21
  this.moduleName = moduleName;
@@ -18,6 +23,8 @@ export class Module {
18
23
  "// AUTO GERADO. QUEM ALTERAR GOSTA DE RAPAZES!\n",
19
24
  'import repo from "$repository/main"',
20
25
  'import { Behavior } from "$reflector/reflector.types";',
26
+ 'import { PUBLIC_ENVIRONMENT } from "$env/static/public";',
27
+ 'import z from "zod";',
21
28
  ]);
22
29
  this.name = capitalizeFirstLetter(name);
23
30
  this.path = path;
@@ -30,7 +37,6 @@ export class Module {
30
37
  // não vão entrar metodos que não tiverem uma resposta tipada
31
38
  this.methods = methods.filter((op) => {
32
39
  const responseTypeOk = op.request.responseType;
33
- const propertiesOk = op.zodProperties.length > 0;
34
40
  if (op.request.apiType === "delete")
35
41
  return true;
36
42
  if (!responseTypeOk) {
@@ -38,24 +44,47 @@ export class Module {
38
44
  }
39
45
  return responseTypeOk;
40
46
  });
41
- this.parameters = this.getParameters();
42
- const { moduleAttributes, moduleTypes, moduleInit, moduleClear } = this.creator();
47
+ const { cookies, headers, paths, querys } = this.getParameters();
48
+ this.querys.push(...querys);
49
+ this.headers.push(...headers);
50
+ this.paths.push(...paths);
51
+ this.cookies.push(...cookies);
52
+ const { moduleAttributes, moduleTypes, moduleInit, moduleClear, form } = this.creator();
53
+ this.moduleConstructor = this.buildConstructor(form);
43
54
  //sempre por último
44
55
  this.src = new Source({
45
56
  path: this.getPath(dir),
46
57
  data: this.buildFile({ moduleAttributes, moduleTypes, moduleInit, moduleClear }),
47
58
  });
48
59
  }
60
+ buildZObject(props) {
61
+ const teste = `z.object({${props.map((p) => p.buildedProp)}})`;
62
+ return teste;
63
+ }
49
64
  creator() {
50
65
  const buildedModuleTypes = [];
51
66
  const moduleAttributes = new Set().add("loading = $state<boolean>(false)");
52
67
  const moduleInit = new Set([]);
53
68
  const moduleClear = new Set([]);
54
- if (this.parameters.length > 0) {
55
- buildedModuleTypes.push(`const ParametersSchema = z.object({${this.parameters}})`);
56
- moduleAttributes.add(`parameters = $state(repo.newForm(ParametersSchema))`);
57
- moduleInit.add(`this.clearParameters()`);
58
- moduleClear.add(`clearParameters() { this.parameters = repo.newForm(ParametersSchema) }`);
69
+ const getXablau = (params) => {
70
+ const { name, objets } = params;
71
+ const capitalizedName = capitalizeFirstLetter(name);
72
+ buildedModuleTypes.push(`const ${capitalizedName}Schema = ${this.buildZObject(objets)}`);
73
+ moduleAttributes.add(`${name} = $state(repo.newForm(${capitalizedName}Schema))`);
74
+ moduleInit.add(`this.clear${capitalizeFirstLetter(capitalizedName)}()`);
75
+ moduleClear.add(`clear${capitalizedName}() { this.${name} = repo.newForm(${capitalizedName}Schema) }`);
76
+ };
77
+ if (this.querys.length > 0) {
78
+ getXablau({ name: "querys", objets: this.querys });
79
+ }
80
+ if (this.headers.length > 0) {
81
+ getXablau({ name: "headers", objets: this.headers });
82
+ }
83
+ if (this.paths.length > 0) {
84
+ getXablau({ name: "paths", objets: this.paths });
85
+ }
86
+ if (this.cookies.length > 0) {
87
+ getXablau({ name: "cookies", objets: this.cookies });
59
88
  }
60
89
  const form = [];
61
90
  for (const method of this.methods) {
@@ -67,22 +96,23 @@ export class Module {
67
96
  });
68
97
  }
69
98
  if (attributeType === "entity") {
70
- moduleAttributes.add(`entity = $state<${responseType} | undefined>()`);
71
- moduleInit.add("this.clearEntity()");
72
- moduleClear.add(`clearEntity() { this.entity = undefined }`);
99
+ const entityName = treatByUppercase(method.request.responseType);
100
+ moduleAttributes.add(`${entityName} = $state<${responseType} | undefined>()`);
101
+ moduleInit.add(`this.clear${capitalizeFirstLetter(entityName)}()`);
102
+ moduleClear.add(`clear${capitalizeFirstLetter(entityName)}() { this.${entityName} = undefined }`);
73
103
  }
74
104
  else if (attributeType === "list") {
75
105
  moduleAttributes.add(`list = $state<${responseType}['data']>([])`);
76
106
  moduleInit.add("this.clearList()");
77
107
  moduleClear.add(`clearList() { this.list = [] }`);
78
108
  }
79
- if (attributeType === "list" || this.parameters.length > 0) {
109
+ if (attributeType === "list" || this.querys.length > 0 || this.headers.length > 0) {
80
110
  this.imports.add(`import z from "zod";`);
81
111
  }
82
112
  }
83
113
  const formSet = new Set();
84
114
  for (const f of form) {
85
- formSet.add(`${f.name}: repo.newForm(${f.type}Schema)`);
115
+ formSet.add(`${f.name}: repo.newForm(Empty${f.type}Schema)`);
86
116
  }
87
117
  if (formSet.size > 0) {
88
118
  moduleAttributes.add(`
@@ -94,7 +124,7 @@ export class Module {
94
124
  this.clearForms()
95
125
  `);
96
126
  moduleClear.add(`
97
- clearForms() { this.forms = { ${Array.from(formSet)} } }
127
+ clearForms() { this.forms = this.buildForms(true) };
98
128
  `);
99
129
  }
100
130
  return {
@@ -102,6 +132,7 @@ export class Module {
102
132
  moduleTypes: buildedModuleTypes,
103
133
  moduleInit: Array.from(moduleInit),
104
134
  moduleClear: Array.from(moduleClear),
135
+ form,
105
136
  };
106
137
  }
107
138
  getPath(dir) {
@@ -140,23 +171,36 @@ export class Module {
140
171
  });
141
172
  }
142
173
  getParameters() {
143
- const set = new Set();
174
+ const queryMap = new Map();
175
+ const headerMap = new Map();
176
+ const pathMap = new Map();
177
+ const cookieMap = new Map();
144
178
  for (const method of this.methods) {
145
- for (const param of method.zodProperties) {
146
- set.add(param.buildedProp);
147
- }
179
+ const { headers, cookies, paths, querys } = method;
180
+ headers.forEach((h) => headerMap.set(h.name, h));
181
+ cookies.forEach((c) => cookieMap.set(c.name, c));
182
+ paths.forEach((p) => pathMap.set(p.name, p));
183
+ querys.forEach((q) => queryMap.set(q.name, q));
148
184
  }
149
- return Array.from(set);
185
+ return {
186
+ headers: Array.from(headerMap.values()),
187
+ cookies: Array.from(cookieMap.values()),
188
+ paths: Array.from(pathMap.values()),
189
+ querys: Array.from(queryMap.values()),
190
+ };
150
191
  }
151
192
  buildImports() {
152
193
  const entries = new Set();
153
194
  for (const method of this.methods) {
154
195
  const { bodyType, responseType, apiType } = method.request;
155
- if (bodyType)
196
+ if (bodyType) {
156
197
  entries.add(`${bodyType}Schema`);
198
+ entries.add(`Empty${bodyType}Schema`);
199
+ }
157
200
  if (responseType) {
158
- if (apiType === "delete")
201
+ if (apiType === "delete") {
159
202
  entries.add(`${responseType}Schema`);
203
+ }
160
204
  entries.add(`type ${responseType}`);
161
205
  }
162
206
  }
@@ -171,6 +215,8 @@ export class Module {
171
215
  export class ${this.moduleName}Module {
172
216
  ${moduleAttributes.join(";")}
173
217
 
218
+ ${this.moduleConstructor}
219
+
174
220
  ${this.buildMethods().join("\n")}
175
221
 
176
222
  ${moduleClear.join("\n\n")}
@@ -181,6 +227,26 @@ export class Module {
181
227
  }
182
228
  `;
183
229
  }
230
+ buildConstructor(form) {
231
+ if (form.length === 0)
232
+ return "";
233
+ const teste = `
234
+ constructor(params?: { empty: boolean }) {
235
+ const isEmpty = params?.empty || PUBLIC_ENVIRONMENT != 'DEV'
236
+
237
+ this.forms = this.buildForms(isEmpty);
238
+ }
239
+
240
+ private buildForms(isEmpty: boolean) {
241
+ if(isEmpty) return this.forms
242
+
243
+ return {
244
+ ${form.map((f) => `${f.name}: repo.newForm(${f.type}Schema)`)}
245
+ }
246
+ }
247
+ `;
248
+ return teste;
249
+ }
184
250
  buildFile(params) {
185
251
  const { moduleInit, moduleTypes, moduleAttributes, moduleClear } = params;
186
252
  return `