svelte-reflector 1.0.35 → 1.0.37

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.
@@ -2,11 +2,15 @@ import type { SchemaObject } from "./types/open-api-spec.interface.js";
2
2
  export declare class ArrayProp {
3
3
  name: string;
4
4
  type: string;
5
- isSpecial: boolean;
5
+ isRequired: boolean;
6
+ isParam: boolean;
7
+ private isPrimitiveType;
6
8
  constructor(params: {
7
9
  name: string;
8
10
  schemaObject: SchemaObject;
9
11
  schemaName: string;
12
+ required: boolean;
13
+ isParam?: boolean;
10
14
  });
11
15
  private treatName;
12
16
  private getType;
@@ -1,11 +1,15 @@
1
1
  export class ArrayProp {
2
2
  name;
3
3
  type;
4
- isSpecial = false;
4
+ isRequired;
5
+ isParam;
6
+ isPrimitiveType = false;
5
7
  constructor(params) {
6
- const { name, schemaObject, schemaName } = params;
8
+ const { name, schemaObject, schemaName, required, isParam } = params;
7
9
  this.name = this.treatName(name);
8
10
  this.type = this.getType({ schemaObject, schemaName });
11
+ this.isRequired = required;
12
+ this.isParam = !!isParam;
9
13
  }
10
14
  treatName(name) {
11
15
  let newName = name;
@@ -16,37 +20,45 @@ export class ArrayProp {
16
20
  }
17
21
  getType(params) {
18
22
  const { schemaObject, schemaName } = params;
19
- const teste = schemaObject.items;
20
- if (!teste)
23
+ const items = schemaObject.items;
24
+ if (!items)
21
25
  return schemaName;
22
- this.isSpecial = true;
23
- if ("$ref" in teste) {
24
- return teste.$ref.split("/").at(-1);
26
+ if ("$ref" in items) {
27
+ const theType = items.$ref.split("/").at(-1);
28
+ return theType;
25
29
  }
26
- if (teste.enum && teste.type === "string") {
27
- return "string";
28
- }
29
- return teste.type ?? "string";
30
+ this.isPrimitiveType = true;
31
+ // if (teste.enum && teste.type === "string") {
32
+ // return "string";
33
+ // }
34
+ return "string";
30
35
  }
31
36
  constructorBuild() {
32
- const result = this.isSpecial ? "" : `.map((param) => new ${this.type}(param))`;
33
- return `this.${this.name} = params?.${this.name}${result} ?? []`;
37
+ const result = this.isPrimitiveType ? "" : `.map((param) => new ${this.type}({ data: param }))`;
38
+ return `this.${this.name} = params?.data?.${this.name}${result} ?? []`;
34
39
  }
35
40
  classBuild() {
36
- const sanitizedType = this.isSpecial ? this.type : `${this.type}[]`;
37
- return `${this.name}: ${sanitizedType}[]`;
41
+ const required = this.isRequired ? "" : "?";
42
+ const sanitizedType = this.isPrimitiveType ? this.type : `${this.type}`;
43
+ return `${this.name}${required}: ${sanitizedType}[]`;
38
44
  }
39
45
  interfaceBuild() {
40
- const sanitizedType = this.isSpecial ? this.type : `${this.type}Interface`;
41
- return `${this.name}: ${sanitizedType}[]`;
46
+ const required = this.isRequired ? "" : "?";
47
+ const sanitizedType = this.isPrimitiveType ? this.type : `${this.type}Interface`;
48
+ return `${this.name}${required}: ${sanitizedType}[]`;
42
49
  }
50
+ // toInterfaceArrayBuild() {
51
+ // const required = this.isRequired ? "" : "?";
52
+ // const sanitizedType = this.isPrimitiveType ? this.type : `${this.type}Interface`;
53
+ // return `${this.name}${required}: ${sanitizedType}[]`;
54
+ // }
43
55
  bundleBuild() {
44
- const result = this.isSpecial ? "" : ".map((obj) => obj.bundle())";
56
+ const result = this.isPrimitiveType ? "" : ".map((obj) => obj.bundle())";
45
57
  return `${this.name}: this.${this.name}${result}`;
46
58
  }
47
59
  staticBuild() {
48
- const result = this.isSpecial ? "obj" : `new ${this.type}(obj)`;
49
- const aType = this.isSpecial ? this.type : `${this.type}Interface`;
60
+ const result = this.isPrimitiveType ? "obj" : `new ${this.type}({ data: obj })`;
61
+ const aType = this.isPrimitiveType ? this.type : `${this.type}Interface`;
50
62
  return `
51
63
  static from(data: ${aType}[]) {
52
64
  return data.map((obj) => ${result});
package/dist/main.js CHANGED
@@ -5,6 +5,7 @@ import { getEndpoint, splitByUppercase } from "./helpers/helpers.js";
5
5
  import { Schema } from "./schema.js";
6
6
  import { Module } from "./module.js";
7
7
  import { baseDir, generatedDir } from "./vars.global.js";
8
+ import { ReflectorFile } from "./reflector.js";
8
9
  // import { Module } from "./module.js";
9
10
  export class Reflector {
10
11
  components;
@@ -106,73 +107,7 @@ export class Reflector {
106
107
  ...treatedSchemas,
107
108
  ].join("\n\n"));
108
109
  this.schemaFile.save();
109
- const buildFunctions = `
110
- import toast from "$lib/utils/toast.svelte";
111
-
112
- type ValidatorResult = string | null;
113
- type ValidatorFn<T> = (v: T) => ValidatorResult;
114
- type Partial<T> = {
115
- [K in Exclude<keyof T, 'bundle'>]?: BuildedInput<T[K]>;
116
- } & {
117
- bundle: unknown;
118
- };
119
-
120
- export class Behavior<TSuccess = unknown, TError = unknown> {
121
- onError?: (e: TError) => void;
122
- onSuccess?: (v: TSuccess) => void;
123
- }
124
-
125
- export class BuildedInput<T> {
126
- value = $state<T>(null as any);
127
- display = $state<T>(null as any);
128
- required: boolean;
129
- placeholder: T;
130
- readonly validator?: ValidatorFn<T>;
131
-
132
- constructor(params: { key?: T | undefined; example: T; required: boolean; validator?: ValidatorFn<T> }) {
133
- const { example, required, key, validator } = params;
134
-
135
- const initial = key ?? example;
136
-
137
- this.value = initial;
138
- this.display = initial;
139
- this.required = required;
140
- this.placeholder = example;
141
-
142
- if (validator) {
143
- this.validator = validator;
144
- }
145
- }
146
-
147
- validate(): ValidatorResult {
148
- if (!this.validator) return null;
149
- return this.validator(this.value);
150
- }
151
- }
152
-
153
- export function build<T>(params: {
154
- key?: T | undefined;
155
- example: T;
156
- required: boolean;
157
- validator?: ValidatorFn<T>;
158
- }): BuildedInput<T> {
159
- return new BuildedInput(params);
160
- }
161
-
162
- export function isFormValid<T>(schema: Partial<T>): boolean {
163
- delete schema.bundle;
164
-
165
- const arrayOfBuildedInputs = Object.values(schema) as BuildedInput<unknown>[];
166
-
167
- const isValid = arrayOfBuildedInputs.every((a) => a.validate() === null);
168
-
169
- if (!isValid) {
170
- toast.error('Erro ao fazer a requisição', 'Um ou mais campos preenchidos estão incorretos.');
171
- }
172
-
173
- return isValid;
174
- }
175
- `;
110
+ const buildFunctions = new ReflectorFile().fileContent;
176
111
  this.typesSrc.changeData(buildFunctions);
177
112
  this.typesSrc.save();
178
113
  this.fieldsFile.changeData(`
package/dist/method.js CHANGED
@@ -39,10 +39,10 @@ export class Method {
39
39
  const { required, name, description, schema, in: inParam } = object;
40
40
  if ("$ref" in schema)
41
41
  continue;
42
- const properties = { name, required: !!required, schemaObject: schema, validator: undefined };
42
+ const properties = { name, required: !!required, schemaObject: schema, validator: undefined, isParam: true };
43
43
  if (inParam === "query") {
44
44
  if (schema.type === "array") {
45
- this.querys.push(new ArrayProp({ name, schemaObject: schema, schemaName: "" }));
45
+ this.querys.push(new ArrayProp({ name, schemaObject: schema, schemaName: "", isParam: true, required: !!required }));
46
46
  }
47
47
  else {
48
48
  this.querys.push(new PrimitiveProp(properties));
@@ -91,7 +91,7 @@ export class Method {
91
91
  else if (this.request.attributeType === "entity") {
92
92
  if (this.request.responseType) {
93
93
  const entityName = treatByUppercase(this.request.responseType);
94
- beforeResponse.push(`this.${entityName} = new ${this.request.responseType}(response)`);
94
+ beforeResponse.push(`this.${entityName} = new ${this.request.responseType}({ data: response })`);
95
95
  }
96
96
  let querys = this.querys.length > 0 ? `queryData: {${this.querys.map((q) => q.name).join(",")}}` : "";
97
97
  const inside = `
@@ -114,7 +114,7 @@ export class Method {
114
114
  if (hasHeaders) {
115
115
  headers = `const headers = this.headers.bundle()`;
116
116
  }
117
- const outside = ["this.loading = true", data, headers].join("\n");
117
+ const outside = [data, headers].join("\n");
118
118
  const inside = `
119
119
  const response = await api.${this.request.apiType}<${responseType}>({
120
120
  endpoint,
@@ -142,7 +142,7 @@ export class Method {
142
142
  if (!this.request.responseType) {
143
143
  // this.isValid = false;
144
144
  }
145
- return this.request.responseType ? `new ${this.request.responseType}(response)` : "null";
145
+ return this.request.responseType ? `new ${this.request.responseType}({ data: response })` : "null";
146
146
  };
147
147
  getAdditionalMethod(params) {
148
148
  const { attributeType, name } = params;
@@ -179,6 +179,8 @@ export class Method {
179
179
  ${description}
180
180
  async ${this.name}(behavior: Behavior<${this.responseTypeInterface}> = new Behavior()) {
181
181
  const {onError, onSuccess} = behavior
182
+
183
+ this.loading = true
182
184
  ${this.getProps()}
183
185
  const endpoint = ${endpoint}
184
186
 
package/dist/module.js CHANGED
@@ -26,7 +26,6 @@ export class Module {
26
26
  moduleName: this.name,
27
27
  });
28
28
  });
29
- // const { cookies, headers, paths, querys } = this.getParameters();
30
29
  const allBuilded = this.masterBuilder({
31
30
  methods: this.methods,
32
31
  });
@@ -58,7 +57,7 @@ export class Module {
58
57
  class ${name} {
59
58
  ${attributes.join(";")}
60
59
 
61
- constructor(params?: ${name}Interface){
60
+ constructor(params?: { data?: ${name}Interface, empty?: boolean }){
62
61
  ${constructorThis.join(";")}
63
62
  }
64
63
 
@@ -150,6 +149,8 @@ export class Module {
150
149
  }
151
150
  else if (attributeType === "list") {
152
151
  methodsAttributes.add(`list = $state<${responseType}['data']>([])`);
152
+ this.reflectorImports.add("genericArrayBundler");
153
+ methodsAttributes.add(`bundledList = $derived(genericArrayBundler(this.list))`);
153
154
  methodsInit.add("this.clearList()");
154
155
  methodsClear.add(`clearList() { this.list = [] }`);
155
156
  }
@@ -249,7 +250,7 @@ export class Module {
249
250
  if(isEmpty) return this.forms
250
251
 
251
252
  return {
252
- ${form.map((f) => `${f.name}: new ${f.type}()`)}
253
+ ${form.map((f) => `${f.name}: new ${f.type}({ empty: true })`)}
253
254
  }
254
255
  }
255
256
  `;
@@ -9,7 +9,7 @@ export class ObjectProp {
9
9
  this.required = isRequired ?? true; // tem que ver isso daí
10
10
  }
11
11
  constructorBuild() {
12
- return `this.${this.name} = new ${this.type}(params?.${this.name})`;
12
+ return `this.${this.name} = new ${this.type}({ data: params?.data?.${this.name}, empty: params?.empty ?? false })`;
13
13
  }
14
14
  classBuild() {
15
15
  const req = this.required ? "" : "?";
@@ -1,23 +1,28 @@
1
1
  import type { SchemaObject } from "./types/open-api-spec.interface.js";
2
+ type AbstractType = string | boolean | Date | number | undefined;
2
3
  export declare class PrimitiveProp {
3
4
  name: string;
4
- type: string;
5
+ type: AbstractType;
5
6
  isSpecial: boolean;
7
+ isParam: boolean;
6
8
  private readonly required;
7
9
  private readonly rawType;
8
10
  private readonly buildedConst;
11
+ private readonly emptyExample;
9
12
  constructor(params: {
10
13
  name: string;
11
14
  schemaObject: SchemaObject;
12
15
  required: boolean;
13
16
  validator: string | undefined;
17
+ isParam?: boolean;
14
18
  });
15
19
  private treatName;
16
- private buildConst;
17
20
  private getEmptyExample;
21
+ private buildConst;
18
22
  private thisDot;
19
23
  constructorBuild(): string;
20
24
  classBuild(): string;
21
25
  interfaceBuild(): string;
22
26
  bundleBuild(): string;
23
27
  }
28
+ export {};
@@ -1,22 +1,26 @@
1
+ const emptyString = "''";
1
2
  export class PrimitiveProp {
2
3
  name;
3
4
  type;
4
5
  isSpecial = false;
6
+ isParam;
5
7
  required;
6
8
  rawType;
7
9
  buildedConst;
10
+ emptyExample;
8
11
  constructor(params) {
9
- const { name, schemaObject, required, validator } = params;
12
+ const { name, schemaObject, required, validator, isParam } = params;
10
13
  const { example: rawExample, type: rawType } = schemaObject;
11
14
  const type = rawType ?? "string";
12
- const example = rawExample ?? this.getEmptyExample({ type, schemaObject });
13
- // const buildedType = required ? type : `${type} | undefined`;
15
+ this.emptyExample = this.getEmptyExample({ type, schemaObject });
16
+ const example = rawExample;
14
17
  const buildedType = type;
15
18
  this.name = this.treatName(name);
16
19
  this.rawType = type ?? "any";
17
20
  this.type = `BuildedInput<${buildedType}>`;
18
21
  this.required = required;
19
- this.buildedConst = this.buildConst({ example, name: this.name, required, type, validator });
22
+ this.isParam = !!isParam;
23
+ this.buildedConst = this.buildConst({ example, name: this.name, required, type, validator, emptyExample: this.emptyExample });
20
24
  }
21
25
  treatName(name) {
22
26
  let newName = name;
@@ -26,8 +30,23 @@ export class PrimitiveProp {
26
30
  }
27
31
  return newName;
28
32
  }
33
+ getEmptyExample(params) {
34
+ const { schemaObject, type } = params;
35
+ if (type === "number") {
36
+ return 1;
37
+ }
38
+ else if (type === "boolean") {
39
+ return false;
40
+ }
41
+ else if (schemaObject.enum) {
42
+ return `"${schemaObject.enum[0]}"`;
43
+ }
44
+ else {
45
+ return "''";
46
+ }
47
+ }
29
48
  buildConst(params) {
30
- const { example, name, required, type, validator } = params;
49
+ const { example, name, required, type, validator, emptyExample } = params;
31
50
  const getValidator = (type) => {
32
51
  if (type === "string") {
33
52
  return "emptyString";
@@ -44,26 +63,25 @@ export class PrimitiveProp {
44
63
  }
45
64
  return "";
46
65
  };
47
- const sanitizedExample = type === "boolean" || type === "number" ? example : `"${example}"`;
66
+ const sanitizedExample = () => {
67
+ if (this.isParam || !example) {
68
+ return emptyExample;
69
+ }
70
+ if (type === "string") {
71
+ return `"${example}"`;
72
+ }
73
+ return example;
74
+ };
75
+ const buildedExample = () => {
76
+ if (this.emptyExample === sanitizedExample()) {
77
+ return sanitizedExample();
78
+ }
79
+ return `params?.empty ? ${this.emptyExample} : ${sanitizedExample()}`;
80
+ };
48
81
  return `
49
- build({ key: params?.${name}, example: ${sanitizedExample}, required: ${required}, ${buildedValidator()}})
82
+ build({ key: params?.data?.${name}, example: ${buildedExample()}, required: ${required}, ${buildedValidator()}})
50
83
  `;
51
84
  }
52
- getEmptyExample(params) {
53
- const { schemaObject, type } = params;
54
- if (type === "number") {
55
- return 1;
56
- }
57
- else if (type === "boolean") {
58
- return false;
59
- }
60
- else if (schemaObject.enum) {
61
- return `'${schemaObject.enum[0]}'`;
62
- }
63
- else {
64
- return "";
65
- }
66
- }
67
85
  thisDot() {
68
86
  return `this${this.isSpecial ? "" : "."}`;
69
87
  }
@@ -82,12 +100,3 @@ export class PrimitiveProp {
82
100
  return `${this.name}: ${this.thisDot()}${this.name}?.value`;
83
101
  }
84
102
  }
85
- // class Teste {
86
- // ["x-two-factor-code"]: string;
87
- // constructor() {
88
- // this["x-two-factor-code"] = "aaaaaaa";
89
- // }
90
- // bundle() {
91
- // return { ["x-two-factor-code"]: this["x-two-factor-code"] };
92
- // }
93
- // }
@@ -0,0 +1,7 @@
1
+ export declare class ReflectorFile {
2
+ private readonly imports;
3
+ private readonly types;
4
+ private readonly classes;
5
+ private readonly functions;
6
+ fileContent: string;
7
+ }
@@ -0,0 +1,86 @@
1
+ export class ReflectorFile {
2
+ imports = ['import toast from "$lib/utils/toast.svelte"'].join(";");
3
+ types = [
4
+ "type ValidatorResult = string | null",
5
+ "type ValidatorFn<T> = (v: T) => ValidatorResult",
6
+ "type BundleResult<T> = T extends { bundle: () => infer R } ? R : T;",
7
+ `type Partial<T> = {
8
+ [K in Exclude<keyof T, "bundle">]?: BuildedInput<T[K]>;
9
+ } & {
10
+ bundle: unknown;
11
+ }`,
12
+ ].join(";");
13
+ classes = [
14
+ `export class Behavior<TSuccess = unknown, TError = unknown> {
15
+ onError?: (e: TError) => void;
16
+ onSuccess?: (v: TSuccess) => void;
17
+ }`,
18
+ `export class BuildedInput<T> {
19
+ value = $state<T>(null as any);
20
+ display = $state<T>(null as any);
21
+ required: boolean;
22
+ placeholder: T;
23
+ readonly validator?: ValidatorFn<T>;
24
+
25
+ constructor(params: { key?: T | undefined; example: T; required: boolean; validator?: ValidatorFn<T> }) {
26
+ const { example, required, key, validator } = params;
27
+
28
+ const initial = key ?? example;
29
+
30
+ this.value = initial;
31
+ this.display = initial;
32
+ this.required = required;
33
+ this.placeholder = example;
34
+
35
+ if (validator) {
36
+ this.validator = validator;
37
+ }
38
+ }
39
+
40
+ validate(): ValidatorResult {
41
+ if (!this.validator) return null;
42
+ return this.validator(this.value);
43
+ }
44
+ }`,
45
+ ].join(";");
46
+ functions = [
47
+ `export function build<T>(params: {
48
+ key?: T | undefined;
49
+ example: T;
50
+ required: boolean;
51
+ validator?: ValidatorFn<T>;
52
+ }): BuildedInput<T> {
53
+ return new BuildedInput(params);
54
+ }`,
55
+ `export function isFormValid<T>(schema: Partial<T>): boolean {
56
+ delete schema.bundle;
57
+
58
+ const arrayOfBuildedInputs = Object.values(schema) as BuildedInput<unknown>[];
59
+
60
+ const isValid = arrayOfBuildedInputs.every((a) => a.validate() === null);
61
+
62
+ if (!isValid) {
63
+ toast.error('Erro ao fazer a requisição', 'Um ou mais campos preenchidos estão incorretos.');
64
+ }
65
+
66
+ return isValid;
67
+ }`,
68
+ `export function genericArrayBundler<T>(data: T[]): BundleResult<T>[] {
69
+ return data.map((item) => {
70
+ if (typeof (item as any)?.bundle === 'function') {
71
+ return (item as any).bundle();
72
+ }
73
+ return item;
74
+ });
75
+ }`,
76
+ ].join(";");
77
+ fileContent = `
78
+ ${this.imports}
79
+
80
+ ${this.types}
81
+
82
+ ${this.classes}
83
+
84
+ ${this.functions}
85
+ `;
86
+ }
package/dist/schema.js CHANGED
@@ -43,7 +43,7 @@ export class Schema {
43
43
  if (type === "object")
44
44
  continue;
45
45
  if (type === "array") {
46
- this.arrayProps.push(new ArrayProp({ schemaObject: value, schemaName: this.name, name: key }));
46
+ this.arrayProps.push(new ArrayProp({ schemaObject: value, schemaName: this.name, name: key, required }));
47
47
  }
48
48
  else {
49
49
  this.primitiveProps.push(new PrimitiveProp({ name: key, schemaObject: value, required, validator }));
@@ -80,7 +80,7 @@ export class Schema {
80
80
  export class ${this.name} {
81
81
  ${keys.join(";")}
82
82
 
83
- constructor(params?: ${this.name}Interface) {
83
+ constructor(params?: { data?: ${this.name}Interface | undefined, empty?: boolean }) {
84
84
  ${constructorThis.join(";\n")}
85
85
  }
86
86
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "svelte-reflector",
3
- "version": "1.0.35",
3
+ "version": "1.0.37",
4
4
  "description": "Reflects zod types from openAPI schemas",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",