svelte-reflector 2.1.4 → 2.1.6

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,8 +2,7 @@ import type { AttributeProp } from "../../types/types.js";
2
2
  /** TS type literal for a single query override entry. Mirrors the
3
3
  * shape produced by each Prop's bundle entry:
4
4
  * PrimitiveProp / EnumProp → `string | null`
5
- * ArrayProp (enum) → `${type}[]`
6
- * ArrayProp (non-enum, raro) → `string[]`
5
+ * ArrayProp (enum or primitive) → `${type}[]`
7
6
  */
8
7
  export declare function queryOverrideEntryType(q: AttributeProp): string;
9
8
  /** Inline TS object type literal for the full queryOverride bag,
@@ -1,14 +1,11 @@
1
1
  /** TS type literal for a single query override entry. Mirrors the
2
2
  * shape produced by each Prop's bundle entry:
3
3
  * PrimitiveProp / EnumProp → `string | null`
4
- * ArrayProp (enum) → `${type}[]`
5
- * ArrayProp (non-enum, raro) → `string[]`
4
+ * ArrayProp (enum or primitive) → `${type}[]`
6
5
  */
7
6
  export function queryOverrideEntryType(q) {
8
- if ("isEnum" in q && q.isEnum)
9
- return `${q.type}[]`;
10
7
  if (!("rawType" in q) && !("enumName" in q))
11
- return "string[]";
8
+ return `${q.type}[]`;
12
9
  return "string | null";
13
10
  }
14
11
  /** Inline TS object type literal for the full queryOverride bag,
@@ -1,7 +1,7 @@
1
1
  import { PrimitiveProp as PrimitivePropClass } from "../../props/primitive.property.js";
2
2
  import { ArrayProp as ArrayPropClass } from "../../props/array.property.js";
3
3
  import { EnumProp as EnumPropClass } from "../../props/enum.property.js";
4
- import { isReferenceObject } from "../../helpers/helpers.js";
4
+ import { isReferenceObject, isPrimitiveEnumValues } from "../../helpers/helpers.js";
5
5
  export class MethodRequestAnalyzer {
6
6
  paths = [];
7
7
  headers = [];
@@ -49,8 +49,13 @@ export class MethodRequestAnalyzer {
49
49
  return;
50
50
  }
51
51
  if (schema.enum) {
52
- this.querys.push(new EnumPropClass({ name, required: isRequired, enums: schema.enum, isParam: true, entityName: moduleName, context }));
53
- return;
52
+ if (isPrimitiveEnumValues(schema.enum)) {
53
+ console.warn(`[reflector] Field '${moduleName}.${name}': enum=[${schema.enum.join(",")}] looks like a TS primitive type (string/number/boolean), not a real enum. Ignoring 'enum' and treating as plain primitive. Fix the @ApiProperty/@ApiQuery in the back.`);
54
+ }
55
+ else {
56
+ this.querys.push(new EnumPropClass({ name, required: isRequired, enums: schema.enum, isParam: true, entityName: moduleName, context }));
57
+ return;
58
+ }
54
59
  }
55
60
  this.querys.push(new PrimitivePropClass({ name, required: isRequired, schemaObject: schema, validator: undefined, isParam: true }));
56
61
  }
@@ -45,9 +45,12 @@ export class ModuleClassBuilder {
45
45
  bundle.push(prop.bundleBuild());
46
46
  }
47
47
  else {
48
- // ArrayProp (não-enum)
48
+ // ArrayProp (não-enum): emits EnumQueryBuilder<primitive>; só importa
49
+ // enum quando o array é realmente de enum.
49
50
  attributes.push(prop.queryBuild());
50
- this.imports.addEnumImport(prop.type);
51
+ if ("isEnum" in prop && prop.isEnum) {
52
+ this.imports.addEnumImport(prop.type);
53
+ }
51
54
  bundle.push(prop.queryBundleBuild());
52
55
  this.imports.addReflectorImport("EnumQueryBuilder");
53
56
  }
@@ -18,6 +18,35 @@ import type { ComponentsObject, PathsObject } from "../../types/open-api-spec.in
18
18
  */
19
19
  export declare class InlineSchemaPromoter {
20
20
  static promote(components: ComponentsObject, paths: PathsObject): void;
21
+ /**
22
+ * Recursively promotes inline object and array-of-object schemas nested
23
+ * inside named component schemas to their own named components, replacing
24
+ * them with a `$ref`.
25
+ *
26
+ * The rest of the pipeline already resolves `$ref` correctly (`ObjectProp`
27
+ * for object properties, `ArrayProp.getType` for array items), but it
28
+ * silently DROPS inline objects (`SchemaPropertyClassifier.classify` returns
29
+ * `null` for `type: "object"` without `$ref`) and DEGRADES inline
30
+ * arrays-of-object to `string[]` (`array.property.ts` fallback). Promoting
31
+ * them upfront routes both through the working `$ref` path, producing typed
32
+ * child classes instead of `string[]` / dropped fields.
33
+ *
34
+ * Runs after body/response promotion so it also covers the freshly promoted
35
+ * envelope schemas. Uses a worklist so newly created child schemas are
36
+ * themselves scanned for deeper nesting.
37
+ */
38
+ private static promoteNestedObjects;
39
+ /** Inline object with own `properties` (not a free-form `additionalProperties` map). */
40
+ private static extractableInlineObject;
41
+ /** `type: array` whose `items` is an inline object with `properties`. */
42
+ private static extractableInlineArrayItems;
43
+ private static reserveNestedName;
44
+ /**
45
+ * OpenAPI 3.0 forbids siblings next to `$ref`, so a nullable object property
46
+ * must wrap the ref in `allOf` + `nullable` — the form `classifyObject`
47
+ * already understands. Non-nullable properties use a bare `$ref`.
48
+ */
49
+ private static refForProperty;
21
50
  private static promoteBodies;
22
51
  private static promoteInlineBody;
23
52
  private static promoteResponses;
@@ -1,4 +1,4 @@
1
- import { capitalizeFirstLetter } from "../../helpers/helpers.js";
1
+ import { capitalizeFirstLetter, isReferenceObject } from "../../helpers/helpers.js";
2
2
  const HTTP_METHODS = ["get", "put", "post", "delete", "patch", "options", "head", "trace"];
3
3
  /**
4
4
  * Promotes inline request-body and response `data` schemas to named
@@ -21,6 +21,92 @@ export class InlineSchemaPromoter {
21
21
  static promote(components, paths) {
22
22
  InlineSchemaPromoter.promoteBodies(components, paths);
23
23
  InlineSchemaPromoter.promoteResponses(components, paths);
24
+ InlineSchemaPromoter.promoteNestedObjects(components);
25
+ }
26
+ /**
27
+ * Recursively promotes inline object and array-of-object schemas nested
28
+ * inside named component schemas to their own named components, replacing
29
+ * them with a `$ref`.
30
+ *
31
+ * The rest of the pipeline already resolves `$ref` correctly (`ObjectProp`
32
+ * for object properties, `ArrayProp.getType` for array items), but it
33
+ * silently DROPS inline objects (`SchemaPropertyClassifier.classify` returns
34
+ * `null` for `type: "object"` without `$ref`) and DEGRADES inline
35
+ * arrays-of-object to `string[]` (`array.property.ts` fallback). Promoting
36
+ * them upfront routes both through the working `$ref` path, producing typed
37
+ * child classes instead of `string[]` / dropped fields.
38
+ *
39
+ * Runs after body/response promotion so it also covers the freshly promoted
40
+ * envelope schemas. Uses a worklist so newly created child schemas are
41
+ * themselves scanned for deeper nesting.
42
+ */
43
+ static promoteNestedObjects(components) {
44
+ const schemas = components.schemas;
45
+ if (!schemas)
46
+ return;
47
+ const usedNames = new Set(Object.keys(schemas));
48
+ const queue = Object.keys(schemas);
49
+ while (queue.length > 0) {
50
+ const schemaName = queue.shift();
51
+ const schema = schemas[schemaName];
52
+ if (!schema || "$ref" in schema || !schema.properties)
53
+ continue;
54
+ for (const [propKey, propValue] of Object.entries(schema.properties)) {
55
+ if (isReferenceObject(propValue))
56
+ continue;
57
+ const inlineObject = InlineSchemaPromoter.extractableInlineObject(propValue);
58
+ if (inlineObject) {
59
+ const name = InlineSchemaPromoter.reserveNestedName(usedNames, schemaName, propKey);
60
+ schemas[name] = inlineObject;
61
+ queue.push(name);
62
+ schema.properties[propKey] = InlineSchemaPromoter.refForProperty(name, propValue.nullable);
63
+ continue;
64
+ }
65
+ const inlineItems = InlineSchemaPromoter.extractableInlineArrayItems(propValue);
66
+ if (inlineItems) {
67
+ const name = InlineSchemaPromoter.reserveNestedName(usedNames, schemaName, propKey);
68
+ schemas[name] = inlineItems;
69
+ queue.push(name);
70
+ propValue.items = { $ref: `#/components/schemas/${name}` };
71
+ }
72
+ }
73
+ }
74
+ }
75
+ /** Inline object with own `properties` (not a free-form `additionalProperties` map). */
76
+ static extractableInlineObject(value) {
77
+ if (value.type !== "object" || value.additionalProperties || !value.properties)
78
+ return null;
79
+ return value;
80
+ }
81
+ /** `type: array` whose `items` is an inline object with `properties`. */
82
+ static extractableInlineArrayItems(value) {
83
+ if (value.type !== "array" || !value.items || isReferenceObject(value.items))
84
+ return null;
85
+ const items = value.items;
86
+ if (items.type !== "object" || items.additionalProperties || !items.properties)
87
+ return null;
88
+ return items;
89
+ }
90
+ static reserveNestedName(usedNames, parent, prop) {
91
+ const base = `${parent}${capitalizeFirstLetter(prop.replaceAll(/[^a-zA-Z0-9]/g, ""))}`;
92
+ let name = base;
93
+ let suffix = 2;
94
+ while (usedNames.has(name)) {
95
+ name = `${base}${suffix++}`;
96
+ }
97
+ usedNames.add(name);
98
+ return name;
99
+ }
100
+ /**
101
+ * OpenAPI 3.0 forbids siblings next to `$ref`, so a nullable object property
102
+ * must wrap the ref in `allOf` + `nullable` — the form `classifyObject`
103
+ * already understands. Non-nullable properties use a bare `$ref`.
104
+ */
105
+ static refForProperty(name, nullable) {
106
+ const ref = { $ref: `#/components/schemas/${name}` };
107
+ if (nullable)
108
+ return { allOf: [ref], nullable: true };
109
+ return ref;
24
110
  }
25
111
  static promoteBodies(components, paths) {
26
112
  components.schemas ??= {};
@@ -2,7 +2,7 @@ import { ArrayProp } from "../../props/array.property.js";
2
2
  import { EnumProp } from "../../props/enum.property.js";
3
3
  import { ObjectProp } from "../../props/object.property.js";
4
4
  import { PrimitiveProp } from "../../props/primitive.property.js";
5
- import { isReferenceObject } from "../../helpers/helpers.js";
5
+ import { isReferenceObject, isPrimitiveEnumValues } from "../../helpers/helpers.js";
6
6
  export class SchemaPropertyClassifier {
7
7
  static classify(params) {
8
8
  const { key, value, requireds, fieldConfigs, schemaName, context } = params;
@@ -37,14 +37,19 @@ export class SchemaPropertyClassifier {
37
37
  });
38
38
  }
39
39
  if (value.enum) {
40
- return new EnumProp({
41
- enums: value.enum,
42
- name: key,
43
- required,
44
- isParam: undefined,
45
- entityName: schemaName,
46
- context,
47
- });
40
+ if (isPrimitiveEnumValues(value.enum)) {
41
+ console.warn(`[reflector] Field '${schemaName}.${key}': enum=[${value.enum.join(",")}] looks like a TS primitive type (string/number/boolean), not a real enum. Ignoring 'enum' and treating as plain primitive. Fix the @ApiProperty/@ApiQuery in the back.`);
42
+ }
43
+ else {
44
+ return new EnumProp({
45
+ enums: value.enum,
46
+ name: key,
47
+ required,
48
+ isParam: undefined,
49
+ entityName: schemaName,
50
+ context,
51
+ });
52
+ }
48
53
  }
49
54
  const config = fieldConfigs.get(key);
50
55
  const validator = config?.validator;
@@ -15,5 +15,9 @@ export declare function getEndpointAndModuleName(rawEndpoint: string): {
15
15
  };
16
16
  export declare function getEndpoint(rawEndpoint: string): string;
17
17
  export declare function getFullEndpoint(rawEndpoint: string): string;
18
+ /** True if every enum value is a TS-reserved primitive type name
19
+ * (`"string"`, `"number"`, `"boolean"`) — a sign of misused
20
+ * `@ApiProperty({ enum: String })` on the back. */
21
+ export declare function isPrimitiveEnumValues(enums: unknown[] | undefined): boolean;
18
22
  export declare function isEnumSchema(schema: SchemaObject): boolean;
19
23
  export declare function isReferenceObject(obj: unknown): obj is ReferenceObject;
@@ -88,6 +88,15 @@ export function getFullEndpoint(rawEndpoint) {
88
88
  })
89
89
  .join("/");
90
90
  }
91
+ const TS_PRIMITIVE_RESERVED = new Set(["string", "number", "integer", "boolean"]);
92
+ /** True if every enum value is a TS-reserved primitive type name
93
+ * (`"string"`, `"number"`, `"boolean"`) — a sign of misused
94
+ * `@ApiProperty({ enum: String })` on the back. */
95
+ export function isPrimitiveEnumValues(enums) {
96
+ if (!enums || enums.length === 0)
97
+ return false;
98
+ return enums.every((e) => typeof e === "string" && TS_PRIMITIVE_RESERVED.has(e.toLowerCase()));
99
+ }
91
100
  export function isEnumSchema(schema) {
92
101
  if (schema.enum)
93
102
  return true;
@@ -47,6 +47,11 @@ export class ArrayProp {
47
47
  return theType;
48
48
  }
49
49
  this._isPrimitiveType = true;
50
+ const itemType = items.type;
51
+ if (itemType === "integer")
52
+ return "number";
53
+ if (itemType === "number" || itemType === "boolean")
54
+ return itemType;
50
55
  return "string";
51
56
  }
52
57
  constructorBuild() {
@@ -83,16 +88,13 @@ export class ArrayProp {
83
88
  return `${this.name}: this.${this.name}?.values`;
84
89
  }
85
90
  queryBuild() {
86
- if (this.isEnum) {
87
- if (this.defaultValues.length === 0) {
88
- return `readonly ${this.name} = new EnumQueryBuilder<${this.type}>({ key: '${this.name}' })`;
89
- }
90
- const literal = `[${this.defaultValues
91
- .map((v) => (typeof v === "string" ? `'${v}'` : String(v)))
92
- .join(", ")}]`;
93
- return `readonly ${this.name} = new EnumQueryBuilder<${this.type}>({ key: '${this.name}', defaultValues: ${literal} })`;
91
+ if (this.defaultValues.length === 0) {
92
+ return `readonly ${this.name} = new EnumQueryBuilder<${this.type}>({ key: '${this.name}', defaultValues: [] })`;
94
93
  }
95
- return `readonly ${this.name} = new QueryBuilder({ key: '${this.name}' })`;
94
+ const literal = `[${this.defaultValues
95
+ .map((v) => (typeof v === "string" ? `'${v}'` : String(v)))
96
+ .join(", ")}]`;
97
+ return `readonly ${this.name} = new EnumQueryBuilder<${this.type}>({ key: '${this.name}', defaultValues: ${literal} })`;
96
98
  }
97
99
  staticBuild() {
98
100
  const result = this._isPrimitiveType ? "obj" : `new ${this.type}({ data: obj })`;
@@ -69,7 +69,10 @@ export class PrimitiveProp {
69
69
  };
70
70
  if (type === "string")
71
71
  return {
72
- example: `"${example}"`,
72
+ // JSON.stringify escapes embedded quotes/backslashes/newlines so a
73
+ // string example like `{"64":true}` doesn't emit invalid JS. For
74
+ // plain strings the output is identical to `"${example}"`.
75
+ example: JSON.stringify(String(example)),
73
76
  emptyExample,
74
77
  };
75
78
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "svelte-reflector",
3
- "version": "2.1.4",
3
+ "version": "2.1.6",
4
4
  "description": "Reflects zod types from openAPI schemas",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",