type-flash 1.1.4 → 1.1.7

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/dist/index.d.mts CHANGED
@@ -365,18 +365,19 @@ declare function mergeTypes(a: TSTypeNode, b: TSTypeNode): TSTypeNode;
365
365
  declare function mergeObjects(a: ObjectType, b: ObjectType): ObjectType;
366
366
  /**
367
367
  * 推断单个值的类型
368
+ * seen 循环缓存参数,默认新建 WeakSet
368
369
  */
369
- declare function inferType(value: unknown): TSTypeNode;
370
+ declare function inferType(value: unknown, seen?: WeakSet<object>): TSTypeNode;
370
371
  /**
371
372
  * 推断数组类型
372
373
  * - 统一提取元素类型
373
374
  * - 元素类型不一致时生成联合类型
374
375
  */
375
- declare function inferArrayType(arr: unknown[]): ArrayType;
376
+ declare function inferArrayType(arr: unknown[], seen: WeakSet<object>): ArrayType;
376
377
  /**
377
378
  * 推断对象类型
378
379
  */
379
- declare function inferObjectType(obj: Record<string, unknown>): ObjectType;
380
+ declare function inferObjectType(obj: Record<string, unknown>, seen: WeakSet<object>): ObjectType;
380
381
  /**
381
382
  * 判断两个类型是否结构等价
382
383
  * 用于类型去重与复用
@@ -398,7 +399,9 @@ declare function isStructurallyEqual(a: TSTypeNode, b: TSTypeNode): boolean;
398
399
  */
399
400
  declare class GenericExtractor {
400
401
  private patterns;
402
+ private seen;
401
403
  extract(type: TSTypeNode): TSTypeNode;
404
+ private extractRecursive;
402
405
  private tryMatchPattern;
403
406
  }
404
407
  /**
@@ -406,16 +409,20 @@ declare class GenericExtractor {
406
409
  */
407
410
  declare class NullHandler {
408
411
  private strict;
412
+ private seen;
409
413
  constructor(strict?: boolean);
410
414
  process(type: TSTypeNode): TSTypeNode;
415
+ private processRecursive;
411
416
  }
412
417
  /**
413
418
  * 可选属性处理器
414
419
  */
415
420
  declare class OptionalHandler {
416
421
  private markOptional;
422
+ private seen;
417
423
  constructor(markOptional?: boolean);
418
424
  process(jsonData: any, type: TSTypeNode): TSTypeNode;
425
+ private processRecursive;
419
426
  private processArrayObjects;
420
427
  }
421
428
  /**
package/dist/index.d.ts CHANGED
@@ -365,18 +365,19 @@ declare function mergeTypes(a: TSTypeNode, b: TSTypeNode): TSTypeNode;
365
365
  declare function mergeObjects(a: ObjectType, b: ObjectType): ObjectType;
366
366
  /**
367
367
  * 推断单个值的类型
368
+ * seen 循环缓存参数,默认新建 WeakSet
368
369
  */
369
- declare function inferType(value: unknown): TSTypeNode;
370
+ declare function inferType(value: unknown, seen?: WeakSet<object>): TSTypeNode;
370
371
  /**
371
372
  * 推断数组类型
372
373
  * - 统一提取元素类型
373
374
  * - 元素类型不一致时生成联合类型
374
375
  */
375
- declare function inferArrayType(arr: unknown[]): ArrayType;
376
+ declare function inferArrayType(arr: unknown[], seen: WeakSet<object>): ArrayType;
376
377
  /**
377
378
  * 推断对象类型
378
379
  */
379
- declare function inferObjectType(obj: Record<string, unknown>): ObjectType;
380
+ declare function inferObjectType(obj: Record<string, unknown>, seen: WeakSet<object>): ObjectType;
380
381
  /**
381
382
  * 判断两个类型是否结构等价
382
383
  * 用于类型去重与复用
@@ -398,7 +399,9 @@ declare function isStructurallyEqual(a: TSTypeNode, b: TSTypeNode): boolean;
398
399
  */
399
400
  declare class GenericExtractor {
400
401
  private patterns;
402
+ private seen;
401
403
  extract(type: TSTypeNode): TSTypeNode;
404
+ private extractRecursive;
402
405
  private tryMatchPattern;
403
406
  }
404
407
  /**
@@ -406,16 +409,20 @@ declare class GenericExtractor {
406
409
  */
407
410
  declare class NullHandler {
408
411
  private strict;
412
+ private seen;
409
413
  constructor(strict?: boolean);
410
414
  process(type: TSTypeNode): TSTypeNode;
415
+ private processRecursive;
411
416
  }
412
417
  /**
413
418
  * 可选属性处理器
414
419
  */
415
420
  declare class OptionalHandler {
416
421
  private markOptional;
422
+ private seen;
417
423
  constructor(markOptional?: boolean);
418
424
  process(jsonData: any, type: TSTypeNode): TSTypeNode;
425
+ private processRecursive;
419
426
  private processArrayObjects;
420
427
  }
421
428
  /**
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- "use strict";var b=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var G=Object.prototype.hasOwnProperty;var M=(n,e)=>{for(var t in e)b(n,t,{get:e[t],enumerable:!0})},K=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of U(e))!G.call(n,i)&&i!==t&&b(n,i,{get:()=>e[i],enumerable:!(r=R(e,i))||r.enumerable});return n};var E=n=>K(b({},"__esModule",{value:!0}),n);var z={};M(z,{CodeFormatter:()=>f,GenericExtractor:()=>T,NullHandler:()=>g,OptionalHandler:()=>h,TypeCollector:()=>y,TypeNamer:()=>l,applyEnhancements:()=>S,createUnion:()=>x,default:()=>q,generate:()=>$,generateFromString:()=>w,inferArrayType:()=>O,inferObjectType:()=>v,inferType:()=>u,isStructurallyEqual:()=>N,mergeObjects:()=>j,mergeTypes:()=>d});module.exports=E(z);var P={rootName:"Root",outputStyle:"interface",namingStyle:"PascalCase",sortProperties:"alpha",addExport:!0,strictNullChecks:!1,markOptional:!0,extractGenerics:!0,indentSize:2,lineEnding:`
2
- `,typeNameMap:{},typePrefix:"",typeSuffix:""};function m(n){return{kind:"primitive",type:n}}function F(){return{kind:"null"}}function L(){return{kind:"undefined"}}function _(n){return{kind:"array",elementType:n}}function A(n=[]){return{kind:"object",properties:n}}function x(n){let e=[],t=new Set;for(let r of n)if(r.kind==="union")for(let i of r.types){let o=a(i);t.has(o)||(t.add(o),e.push(i))}else{let i=a(r);t.has(i)||(t.add(i),e.push(r))}return e.length===1?e[0]:{kind:"union",types:e}}function a(n){switch(n.kind){case"primitive":return`primitive:${n.type}`;case"null":return"null";case"undefined":return"undefined";case"literal":return`literal:${typeof n.value}:${String(n.value)}`;case"array":return`array:${a(n.elementType)}`;case"object":return`object:${n.properties.map(e=>`${e.name}:${a(e.type)}:${e.optional}`).join(",")}`;case"union":return`union:${n.types.map(a).sort().join("|")}`;case"generic":return`generic:${n.name}:${n.typeArgs.map(a).join(",")}`;default:return"unknown"}}function d(n,e){return a(n)===a(e)?n:n.kind==="object"&&e.kind==="object"?j(n,e):n.kind==="array"&&e.kind==="array"?_(d(n.elementType,e.elementType)):x([n,e])}function j(n,e){let t=new Map;for(let r of n.properties)t.set(r.name,{...r});for(let r of e.properties){let i=t.get(r.name);i?(i.type=d(i.type,r.type),i.optional=i.optional||r.optional):t.set(r.name,{...r,optional:!0})}for(let[r,i]of t)e.properties.some(s=>s.name===r)||(i.optional=!0);return A(Array.from(t.values()))}function u(n){return n===null?F():n===void 0?L():typeof n=="function"?m("function"):typeof n=="string"?m("string"):typeof n=="number"?m("number"):typeof n=="boolean"?m("boolean"):Array.isArray(n)?O(n):typeof n=="object"?v(n):m("unknown")}function O(n){if(n.length===0)return{kind:"array",elementType:{kind:"primitive",type:"any"}};let e=n.map(r=>u(r)),t=e[0];for(let r=1;r<e.length;r++)t=d(t,e[r]);return{kind:"array",elementType:t}}function v(n){let e=[];for(let[t,r]of Object.entries(n)){let i=u(r);e.push({name:t,type:i,optional:!1})}return A(e)}function N(n,e){return a(n)===a(e)}function c(n){switch(n.kind){case"primitive":case"null":case"undefined":return{...n};case"literal":return{...n};case"array":return{...n,elementType:c(n.elementType)};case"object":return{...n,properties:n.properties.map(e=>({...e,type:c(e.type)}))};case"union":return{...n,types:n.types.map(e=>c(e))};case"generic":return{...n,typeArgs:n.typeArgs.map(e=>c(e))};default:return{...n}}}var l=class{constructor(e={}){this.namedTypes=new Map;this.nameCounter=new Map;this.processing=new WeakSet;this.circularRefs=new Map;this.namingStyle=e.namingStyle||"PascalCase",this.prefix=e.prefix||"",this.suffix=e.suffix||"",this.customNameMap=e.customNameMap||{}}nameType(e,t={depth:0}){if(e.kind!=="object")return null;let r=this.buildPathKey(t);if(this.customNameMap[r])return this.applyAffixes(this.customNameMap[r]);let i=this.getTypeKey(e);if(this.namedTypes.has(i))return this.namedTypes.get(i);let o=this.generateName(e,t);return o=this.formatName(o),o=this.ensureUniqueName(o),o=this.applyAffixes(o),this.namedTypes.set(i,o),o}generateName(e,t){if(e.kind==="object"){if(t.fieldName){let r=this.toPascalCase(t.fieldName);return t.parentName?`${t.parentName}${r}`:r}return t.parentName?`${t.parentName}Item`:"AnonymousObject"}return"UnknownType"}ensureUniqueName(e){let t=this.nameCounter.get(e)||0;if(t===0)return this.nameCounter.set(e,1),e;let r=`${e}${t+1}`;return this.nameCounter.set(e,t+1),r}applyAffixes(e){let t=e;return this.prefix&&(t=this.toPascalCase(this.prefix)+t),this.suffix&&(t=t+this.toPascalCase(this.suffix)),t}buildPathKey(e){return e.path||""}getTypeKey(e){return e.kind==="object"?`object:${e.properties.map(t=>`${t.name}:${this.getSimpleTypeKey(t.type)}:${t.optional}`).sort().join(",")}`:e.kind}getSimpleTypeKey(e){switch(e.kind){case"primitive":return e.type;case"null":return"null";case"undefined":return"undefined";case"array":return`array<${this.getSimpleTypeKey(e.elementType)}>`;case"object":return"object";case"union":return e.types.map(t=>this.getSimpleTypeKey(t)).sort().join("|");case"generic":return`generic:${e.name}`;default:return"unknown"}}toPascalCase(e){return e?e.replace(/[-_\s]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim().split(" ").filter(Boolean).map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join(""):""}toCamelCase(e){let t=this.toPascalCase(e);return t.charAt(0).toLowerCase()+t.slice(1)}formatName(e){return this.namingStyle==="camelCase"?this.toCamelCase(e):this.toPascalCase(e)}isCircular(e){return this.processing.has(e)}markProcessing(e){this.processing.add(e)}unmarkProcessing(e){this.processing.delete(e)}getAllNamedTypes(){return new Map(this.namedTypes)}reset(){this.namedTypes.clear(),this.nameCounter.clear(),this.processing=new WeakSet,this.circularRefs.clear()}},y=class{constructor(e){this.collected=[];this.seenStructs=new Set;this.namer=e}collect(e,t){this.collected=[],this.seenStructs.clear(),this.namer.reset();let r=this.getStructKey(e);this.namer.nameType(e,{fieldName:t,path:t,depth:0}),this.collectRecursive(e,{fieldName:t,parentName:void 0,path:t,depth:0});let i=this.collected.find(s=>s.name===t),o=this.collected.filter(s=>s.name!==t);return i?[i,...o]:this.collected}collectRecursive(e,t){let r=this.getStructKey(e);if(e.kind==="object"){let i=this.namer.nameType(e,t);if(i&&!this.seenStructs.has(r)){this.seenStructs.add(r),this.collected.push({name:i,type:c(e)});for(let o of e.properties)this.collectRecursive(o.type,{fieldName:o.name,parentName:i,path:t.path?`${t.path}.${o.name}`:o.name,depth:t.depth+1})}return}if(e.kind==="array"){this.collectRecursive(e.elementType,{fieldName:t.fieldName?t.fieldName+"Item":void 0,parentName:t.parentName,path:t.path,depth:t.depth+1});return}if(e.kind==="union"){for(let i of e.types)this.collectRecursive(i,t);return}if(e.kind==="generic"){for(let i of e.typeArgs)this.collectRecursive(i,{...t,depth:t.depth+1});return}}getStructKey(e){return e.kind==="object"?`object:${e.properties.map(t=>`${t.name}:${this.getPropTypeKey(t.type)}:${t.optional}`).sort().join("|")}`:e.kind}getPropTypeKey(e){switch(e.kind){case"primitive":return e.type;case"null":return"null";case"undefined":return"undefined";case"array":return`array:${this.getPropTypeKey(e.elementType)}`;case"object":return"object";case"union":return e.types.map(t=>this.getPropTypeKey(t)).sort().join("|");case"generic":return`generic:${e.name}`;default:return"unknown"}}};var f=class{constructor(e,t){this.allNamedTypes=[];this.options=e,this.namer=t}findTypeName(e){if(e.kind!=="object")return null;for(let t of this.allNamedTypes)if(N(t.type,e))return t.name;return null}formatTypeDef(e){let{name:t,type:r}=e,i=this.options.addExport?"export ":"";return this.formatObjectType(t,r,i)}formatObjectType(e,t,r){let i=" ".repeat(this.options.indentSize),o=this.sortProperties(t.properties),s=[];this.options.outputStyle==="interface"?s.push(`${r}interface ${e} {`):s.push(`${r}type ${e} = {`);for(let p of o){let k=this.formatPropertyName(p.name),C=p.optional?"?":"",D=this.formatType(p.type);s.push(`${i}${k}${C}: ${D};`)}return this.options.outputStyle==="interface"?s.push("}"):s.push("};"),s.join(`
3
- `)}formatType(e){if(e.kind==="object"){let t=this.findTypeName(e);if(t)return t}switch(e.kind){case"primitive":return e.type;case"null":return"null";case"undefined":return"undefined";case"array":return this.formatArrayType(e);case"object":return this.formatInlineObject(e);case"union":return this.formatUnionType(e.types);case"literal":return this.formatLiteral(e.value);case"generic":return`${e.name}<${e.typeArgs.map(t=>this.formatType(t)).join(", ")}>`;default:return"unknown"}}formatLiteral(e){return typeof e=="string"?`'${e}'`:String(e)}formatArrayType(e){let t=this.formatType(e.elementType);return e.elementType.kind==="union"?`(${t})[]`:`${t}[]`}formatInlineObject(e){let t=" ".repeat(this.options.indentSize),r=this.sortProperties(e.properties);if(r.length===0)return"{}";let i=["{"];for(let o of r){let s=this.formatPropertyName(o.name),p=o.optional?"?":"",k=this.formatType(o.type);i.push(`${t}${s}${p}: ${k};`)}return i.push("}"),i.join(`
1
+ "use strict";var b=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var U=Object.prototype.hasOwnProperty;var M=(n,e)=>{for(var t in e)b(n,t,{get:e[t],enumerable:!0})},E=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of G(e))!U.call(n,i)&&i!==t&&b(n,i,{get:()=>e[i],enumerable:!(r=D(e,i))||r.enumerable});return n};var F=n=>E(b({},"__esModule",{value:!0}),n);var z={};M(z,{CodeFormatter:()=>y,GenericExtractor:()=>T,NullHandler:()=>g,OptionalHandler:()=>h,TypeCollector:()=>f,TypeNamer:()=>l,applyEnhancements:()=>S,createUnion:()=>v,default:()=>q,generate:()=>$,generateFromString:()=>w,inferArrayType:()=>x,inferObjectType:()=>O,inferType:()=>c,isStructurallyEqual:()=>N,mergeObjects:()=>j,mergeTypes:()=>d});module.exports=F(z);var P={rootName:"Root",outputStyle:"interface",namingStyle:"PascalCase",sortProperties:"alpha",addExport:!0,strictNullChecks:!1,markOptional:!0,extractGenerics:!0,indentSize:2,lineEnding:`
2
+ `,typeNameMap:{},typePrefix:"",typeSuffix:""};function m(n){return{kind:"primitive",type:n}}function K(){return{kind:"null"}}function L(){return{kind:"undefined"}}function _(n){return{kind:"array",elementType:n}}function A(n=[]){return{kind:"object",properties:n}}function v(n){let e=[],t=new Set;for(let r of n)if(r.kind==="union")for(let i of r.types){let s=a(i);t.has(s)||(t.add(s),e.push(i))}else{let i=a(r);t.has(i)||(t.add(i),e.push(r))}return e.length===1?e[0]:{kind:"union",types:e}}function a(n){switch(n.kind){case"primitive":return`primitive:${n.type}`;case"null":return"null";case"undefined":return"undefined";case"literal":return`literal:${typeof n.value}:${String(n.value)}`;case"array":return`array:${a(n.elementType)}`;case"object":return`object:${n.properties.map(e=>`${e.name}:${a(e.type)}:${e.optional}`).join(",")}`;case"union":return`union:${n.types.map(a).sort().join("|")}`;case"generic":return`generic:${n.name}:${n.typeArgs.map(a).join(",")}`;default:return"unknown"}}function d(n,e){return a(n)===a(e)?n:n.kind==="object"&&e.kind==="object"?j(n,e):n.kind==="array"&&e.kind==="array"?_(d(n.elementType,e.elementType)):v([n,e])}function j(n,e){let t=new Map;for(let r of n.properties)t.set(r.name,{...r});for(let r of e.properties){let i=t.get(r.name);i?(i.type=d(i.type,r.type),i.optional=i.optional||r.optional):t.set(r.name,{...r,optional:!0})}for(let[r,i]of t)e.properties.some(o=>o.name===r)||(i.optional=!0);return A(Array.from(t.values()))}function c(n,e=new WeakSet){if(n===null)return K();if(n===void 0)return L();if(typeof n=="function")return m("function");if(typeof n=="string")return m("string");if(typeof n=="number")return m("number");if(typeof n=="boolean")return m("boolean");if(Array.isArray(n))return x(n,e);if(typeof n=="object"&&n!==null){let t=n;if(e.has(t))return{kind:"object",properties:[]};e.add(t);let r=O(t,e);return e.delete(t),r}return m("unknown")}function x(n,e){if(n.length===0)return{kind:"array",elementType:{kind:"primitive",type:"any"}};let t=n.map(i=>c(i,e)),r=t[0];for(let i=1;i<t.length;i++)r=d(r,t[i]);return{kind:"array",elementType:r}}function O(n,e){let t=[];for(let[r,i]of Object.entries(n)){let s=c(i,e);t.push({name:r,type:s,optional:!1})}return A(t)}function N(n,e){return a(n)===a(e)}function u(n,e=new WeakMap){if(e.has(n))return e.get(n);let t;switch(n.kind){case"primitive":return t={kind:"primitive",type:n.type},e.set(n,t),t;case"null":return t={kind:"null"},e.set(n,t),t;case"undefined":return t={kind:"undefined"},e.set(n,t),t;case"literal":return t={kind:"literal",value:n.value},e.set(n,t),t;case"array":return t={kind:"array",elementType:{}},e.set(n,t),t.elementType=u(n.elementType,e),t;case"object":return t={kind:"object",properties:[],isRecord:n.isRecord,valueType:n.valueType},e.set(n,t),t.properties=n.properties.map(r=>({name:r.name,optional:r.optional,type:u(r.type,e)})),n.valueType&&(t.valueType=u(n.valueType,e)),t;case"union":return t={kind:"union",types:[]},e.set(n,t),t.types=n.types.map(r=>u(r,e)),t;case"generic":return t={kind:"generic",name:n.name,typeArgs:[]},e.set(n,t),t.typeArgs=n.typeArgs.map(r=>u(r,e)),t;default:return t={kind:"primitive",type:"unknown"},e.set(n,t),t}}var l=class{constructor(e={}){this.namedTypes=new Map;this.nameCounter=new Map;this.processing=new WeakSet;this.circularRefs=new Map;this.namingStyle=e.namingStyle||"PascalCase",this.prefix=e.prefix||"",this.suffix=e.suffix||"",this.customNameMap=e.customNameMap||{}}nameType(e,t={depth:0}){if(e.kind!=="object")return null;let r=this.buildPathKey(t);if(this.customNameMap[r])return this.applyAffixes(this.customNameMap[r]);let i=this.getTypeKey(e);if(this.namedTypes.has(i))return this.namedTypes.get(i);let s=this.generateName(e,t);return s=this.formatName(s),s=this.ensureUniqueName(s),s=this.applyAffixes(s),this.namedTypes.set(i,s),s}generateName(e,t){if(e.kind==="object"){if(t.fieldName){let r=this.toPascalCase(t.fieldName);return t.parentName?`${t.parentName}${r}`:r}return t.parentName?`${t.parentName}Item`:"AnonymousObject"}return"UnknownType"}ensureUniqueName(e){let t=this.nameCounter.get(e)||0;if(t===0)return this.nameCounter.set(e,1),e;let r=`${e}${t+1}`;return this.nameCounter.set(e,t+1),r}applyAffixes(e){let t=e;return this.prefix&&(t=this.toPascalCase(this.prefix)+t),this.suffix&&(t=t+this.toPascalCase(this.suffix)),t}buildPathKey(e){return e.path||""}getTypeKey(e){return e.kind==="object"?`object:${e.properties.map(t=>`${t.name}:${this.getSimpleTypeKey(t.type)}:${t.optional}`).sort().join(",")}`:e.kind}getSimpleTypeKey(e){switch(e.kind){case"primitive":return e.type;case"null":return"null";case"undefined":return"undefined";case"array":return`array<${this.getSimpleTypeKey(e.elementType)}>`;case"object":return"object";case"union":return e.types.map(t=>this.getSimpleTypeKey(t)).sort().join("|");case"generic":return`generic:${e.name}`;default:return"unknown"}}toPascalCase(e){return e?e.replace(/[-_\s]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim().split(" ").filter(Boolean).map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join(""):""}toCamelCase(e){let t=this.toPascalCase(e);return t.charAt(0).toLowerCase()+t.slice(1)}formatName(e){return this.namingStyle==="camelCase"?this.toCamelCase(e):this.toPascalCase(e)}isCircular(e){return this.processing.has(e)}markProcessing(e){this.processing.add(e)}unmarkProcessing(e){this.processing.delete(e)}getAllNamedTypes(){return new Map(this.namedTypes)}reset(){this.namedTypes.clear(),this.nameCounter.clear(),this.processing=new WeakSet,this.circularRefs.clear()}},f=class{constructor(e){this.collected=[];this.seenStructs=new Set;this.namer=e}collect(e,t){this.collected=[],this.seenStructs.clear(),this.namer.reset(),this.collectRecursive(e,{fieldName:t,parentName:void 0,path:t,depth:0});let r=this.collected.find(s=>s.name===t),i=this.collected.filter(s=>s.name!==t);return r?[r,...i]:this.collected}collectRecursive(e,t){let r=this.getStructKey(e);if(e.kind==="object"){let i=this.namer.nameType(e,t);if(i&&!this.seenStructs.has(r)){this.seenStructs.add(r),this.collected.push({name:i,type:u(e)});for(let s of e.properties)this.collectRecursive(s.type,{fieldName:s.name,parentName:i,path:t.path?`${t.path}.${s.name}`:s.name,depth:t.depth+1})}return}if(e.kind==="array"){this.collectRecursive(e.elementType,{fieldName:t.fieldName?t.fieldName+"Item":void 0,parentName:t.parentName,path:t.path,depth:t.depth+1});return}if(e.kind==="union"){for(let i of e.types)this.collectRecursive(i,t);return}if(e.kind==="generic"){for(let i of e.typeArgs)this.collectRecursive(i,{...t,depth:t.depth+1});return}}getStructKey(e){return e.kind==="object"?`object:${e.properties.map(t=>`${t.name}:${this.getPropTypeKey(t.type)}:${t.optional}`).sort().join("|")}`:e.kind}getPropTypeKey(e){switch(e.kind){case"primitive":return e.type;case"null":return"null";case"undefined":return"undefined";case"array":return`array:${this.getPropTypeKey(e.elementType)}`;case"object":return"object";case"union":return e.types.map(t=>this.getPropTypeKey(t)).sort().join("|");case"generic":return`generic:${e.name}`;default:return"unknown"}}};var y=class{constructor(e,t){this.allNamedTypes=[];this.options=e,this.namer=t}findTypeName(e){if(e.kind!=="object")return null;for(let t of this.allNamedTypes)if(N(t.type,e))return t.name;return null}formatTypeDef(e){let{name:t,type:r}=e,i=this.options.addExport?"export ":"";return this.formatObjectType(t,r,i)}formatObjectType(e,t,r){let i=" ".repeat(this.options.indentSize),s=this.sortProperties(t.properties),o=[];this.options.outputStyle==="interface"?o.push(`${r}interface ${e} {`):o.push(`${r}type ${e} = {`);for(let p of s){let k=this.formatPropertyName(p.name),R=p.optional?"?":"",C=this.formatType(p.type);o.push(`${i}${k}${R}: ${C};`)}return this.options.outputStyle==="interface"?o.push("}"):o.push("};"),o.join(`
3
+ `)}formatType(e){if(e.kind==="object"){let t=this.findTypeName(e);if(t)return t}switch(e.kind){case"primitive":return e.type;case"null":return"null";case"undefined":return"undefined";case"array":return this.formatArrayType(e);case"object":return this.formatInlineObject(e);case"union":return this.formatUnionType(e.types);case"literal":return this.formatLiteral(e.value);case"generic":return`${e.name}<${e.typeArgs.map(t=>this.formatType(t)).join(", ")}>`;default:return"unknown"}}formatLiteral(e){return typeof e=="string"?`'${e}'`:String(e)}formatArrayType(e){let t=this.formatType(e.elementType);return e.elementType.kind==="union"?`(${t})[]`:`${t}[]`}formatInlineObject(e){let t=" ".repeat(this.options.indentSize),r=this.sortProperties(e.properties);if(r.length===0)return"{}";let i=["{"];for(let s of r){let o=this.formatPropertyName(s.name),p=s.optional?"?":"",k=this.formatType(s.type);i.push(`${t}${o}${p}: ${k};`)}return i.push("}"),i.join(`
4
4
  `)}formatUnionType(e){return e.map(t=>this.formatType(t)).join(" | ")}formatPropertyName(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?e:`'${e}'`}sortProperties(e){return this.options.sortProperties==="definition"?[...e]:[...e].sort((t,r)=>t.name.localeCompare(r.name))}formatAll(e){return this.allNamedTypes=e,e.map(t=>this.formatTypeDef(t)).join(`
5
5
 
6
6
  `)}generateOutput(e,t){let r=`/**
@@ -9,4 +9,4 @@
9
9
  */`,i=this.formatAll(e);return`${r}
10
10
 
11
11
  ${i}
12
- `}};var T=class{constructor(){this.patterns=[{name:"PageResult",arrayFields:["list","records","rows","items"],countFields:["total","count","totalCount"]},{name:"ListResult",arrayFields:["list","data","items"],countFields:[]},{name:"ApiResponse",arrayFields:["data"],countFields:[]}]}extract(e){if(e.kind!=="object")return e;for(let t of this.patterns){let r=this.tryMatchPattern(e,t);if(r)return r}return e}tryMatchPattern(e,t){let r=null,i=t.countFields.length===0;for(let o of e.properties)t.arrayFields.includes(o.name)&&o.type.kind==="array"&&(r={name:o.name,elementType:o.type.elementType}),t.countFields.includes(o.name)&&(i=!0);return r&&i?{kind:"generic",name:t.name,typeArgs:[r.elementType]}:null}},g=class{constructor(e=!1){this.strict=e}process(e){if(this.strict)return e;if(e.kind==="union"){let t=e.types.filter(r=>r.kind!=="null");return t.length===0?{kind:"null"}:t.length===1?t[0]:{...e,types:t}}return e.kind==="array"?{...e,elementType:this.process(e.elementType)}:e.kind==="object"?{...e,properties:e.properties.map(t=>({...t,type:this.process(t.type)}))}:e}},h=class{constructor(e=!0){this.markOptional=e}process(e,t){if(!this.markOptional)return t;if(t.kind==="array"&&Array.isArray(e)){let r=t.elementType;if(r.kind==="object"){let i=this.processArrayObjects(e,r);return{...t,elementType:i}}}return t}processArrayObjects(e,t){if(e.length<=1)return t;let r={},i=e.length;for(let o of e)if(o&&typeof o=="object")for(let s of Object.keys(o))r[s]=(r[s]||0)+1;return{...t,properties:t.properties.map(o=>{let p=(r[o.name]||0)<i;return{...o,optional:p}})}}};function S(n,e,t){let r=e;return t.markOptional&&(r=new h(t.markOptional).process(n,r)),t.extractGenerics&&(r=new T().extract(r)),r=new g(t.strictNullChecks).process(r),r}function $(n,e={}){let t={...P,...e},r=u(n);r=S(n,r,t);let i=new l({namingStyle:t.namingStyle,prefix:t.typePrefix,suffix:t.typeSuffix,customNameMap:t.typeNameMap}),s=new y(i).collect(r,t.rootName);return new f(t,i).generateOutput(s,t.rootName)}function w(n,e={}){let t=JSON.parse(n);return $(t,e)}var q={generate:$,generateFromString:w};0&&(module.exports={CodeFormatter,GenericExtractor,NullHandler,OptionalHandler,TypeCollector,TypeNamer,applyEnhancements,createUnion,generate,generateFromString,inferArrayType,inferObjectType,inferType,isStructurallyEqual,mergeObjects,mergeTypes});
12
+ `}};var T=class{constructor(){this.patterns=[{name:"PageResult",arrayFields:["list","records","rows","items"],countFields:["total","count","totalCount"]},{name:"ListResult",arrayFields:["list","data","items"],countFields:[]},{name:"ApiResponse",arrayFields:["data"],countFields:[]}];this.seen=new WeakSet}extract(e){return this.extractRecursive(e)}extractRecursive(e){if(e.kind!=="object")return e.kind==="array"?{...e,elementType:this.extractRecursive(e.elementType)}:e.kind==="union"?{...e,types:e.types.map(s=>this.extractRecursive(s))}:e.kind==="generic"?{...e,typeArgs:e.typeArgs.map(s=>this.extractRecursive(s))}:e;if(this.seen.has(e))return e;this.seen.add(e);let t=e.properties.map(s=>({...s,type:this.extractRecursive(s.type)})),r={...e,properties:t},i=null;for(let s of this.patterns){let o=this.tryMatchPattern(r,s);if(o){i=o;break}}return this.seen.delete(e),r}tryMatchPattern(e,t){let r=null,i=t.countFields.length===0;for(let s of e.properties)t.arrayFields.includes(s.name)&&s.type.kind==="array"&&(r={name:s.name,elementType:s.type.elementType}),t.countFields.includes(s.name)&&(i=!0);return r&&i?{kind:"generic",name:t.name,typeArgs:[r.elementType]}:null}},g=class{constructor(e=!1){this.seen=new WeakSet;this.strict=e}process(e){return this.processRecursive(e)}processRecursive(e){if(this.strict)return e;if(e.kind==="union"){let t=e.types.filter(r=>r.kind!=="null");return t.length===0?{kind:"null"}:t.length===1?t[0]:{...e,types:t.map(r=>this.processRecursive(r))}}if(e.kind==="array")return{...e,elementType:this.processRecursive(e.elementType)};if(e.kind==="object"){if(this.seen.has(e))return e;this.seen.add(e);let t={...e,properties:e.properties.map(r=>({...r,type:this.processRecursive(r.type)}))};return this.seen.delete(e),t}return e}},h=class{constructor(e=!0){this.seen=new WeakSet;this.markOptional=e}process(e,t){return this.markOptional?this.processRecursive(e,t):t}processRecursive(e,t){if(t.kind==="array"&&Array.isArray(e)){let r=t.elementType;if(r.kind==="object"){let i=this.processArrayObjects(e,r);return{...t,elementType:i}}return{...t,elementType:this.processRecursive(e,r)}}if(t.kind==="object"&&e&&typeof e=="object"){if(this.seen.has(t))return t;this.seen.add(t);let r=t.properties.map(i=>({...i,type:this.processRecursive(e[i.name],i.type)}));return this.seen.delete(t),{...t,properties:r}}return t.kind==="union"&&Array.isArray(e)?{...t,types:t.types.map(r=>this.processRecursive(e,r))}:t}processArrayObjects(e,t){if(e.length<=1)return t;let r={},i=e.length;for(let s of e)if(s&&typeof s=="object")for(let o of Object.keys(s))r[o]=(r[o]||0)+1;return{...t,properties:t.properties.map(s=>{let p=(r[s.name]||0)<i;return{...s,optional:p}})}}};function S(n,e,t){let r=e;return t.markOptional&&(r=new h(t.markOptional).process(n,r)),t.extractGenerics&&(r=new T().extract(r)),r=new g(t.strictNullChecks).process(r),r}function $(n,e={}){let t={...P,...e},r=c(n);r=S(n,r,t);let i=new l({namingStyle:t.namingStyle,prefix:t.typePrefix,suffix:t.typeSuffix,customNameMap:t.typeNameMap}),o=new f(i).collect(r,t.rootName);return new y(t,i).generateOutput(o,t.rootName)}function w(n,e={}){let t=JSON.parse(n);return $(t,e)}var q={generate:$,generateFromString:w};0&&(module.exports={CodeFormatter,GenericExtractor,NullHandler,OptionalHandler,TypeCollector,TypeNamer,applyEnhancements,createUnion,generate,generateFromString,inferArrayType,inferObjectType,inferType,isStructurallyEqual,mergeObjects,mergeTypes});
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  var b={rootName:"Root",outputStyle:"interface",namingStyle:"PascalCase",sortProperties:"alpha",addExport:!0,strictNullChecks:!1,markOptional:!0,extractGenerics:!0,indentSize:2,lineEnding:`
2
- `,typeNameMap:{},typePrefix:"",typeSuffix:""};function u(n){return{kind:"primitive",type:n}}function C(){return{kind:"null"}}function D(){return{kind:"undefined"}}function R(n){return{kind:"array",elementType:n}}function x(n=[]){return{kind:"object",properties:n}}function j(n){let e=[],t=new Set;for(let r of n)if(r.kind==="union")for(let i of r.types){let o=a(i);t.has(o)||(t.add(o),e.push(i))}else{let i=a(r);t.has(i)||(t.add(i),e.push(r))}return e.length===1?e[0]:{kind:"union",types:e}}function a(n){switch(n.kind){case"primitive":return`primitive:${n.type}`;case"null":return"null";case"undefined":return"undefined";case"literal":return`literal:${typeof n.value}:${String(n.value)}`;case"array":return`array:${a(n.elementType)}`;case"object":return`object:${n.properties.map(e=>`${e.name}:${a(e.type)}:${e.optional}`).join(",")}`;case"union":return`union:${n.types.map(a).sort().join("|")}`;case"generic":return`generic:${n.name}:${n.typeArgs.map(a).join(",")}`;default:return"unknown"}}function d(n,e){return a(n)===a(e)?n:n.kind==="object"&&e.kind==="object"?O(n,e):n.kind==="array"&&e.kind==="array"?R(d(n.elementType,e.elementType)):j([n,e])}function O(n,e){let t=new Map;for(let r of n.properties)t.set(r.name,{...r});for(let r of e.properties){let i=t.get(r.name);i?(i.type=d(i.type,r.type),i.optional=i.optional||r.optional):t.set(r.name,{...r,optional:!0})}for(let[r,i]of t)e.properties.some(s=>s.name===r)||(i.optional=!0);return x(Array.from(t.values()))}function l(n){return n===null?C():n===void 0?D():typeof n=="function"?u("function"):typeof n=="string"?u("string"):typeof n=="number"?u("number"):typeof n=="boolean"?u("boolean"):Array.isArray(n)?v(n):typeof n=="object"?$(n):u("unknown")}function v(n){if(n.length===0)return{kind:"array",elementType:{kind:"primitive",type:"any"}};let e=n.map(r=>l(r)),t=e[0];for(let r=1;r<e.length;r++)t=d(t,e[r]);return{kind:"array",elementType:t}}function $(n){let e=[];for(let[t,r]of Object.entries(n)){let i=l(r);e.push({name:t,type:i,optional:!1})}return x(e)}function S(n,e){return a(n)===a(e)}function c(n){switch(n.kind){case"primitive":case"null":case"undefined":return{...n};case"literal":return{...n};case"array":return{...n,elementType:c(n.elementType)};case"object":return{...n,properties:n.properties.map(e=>({...e,type:c(e.type)}))};case"union":return{...n,types:n.types.map(e=>c(e))};case"generic":return{...n,typeArgs:n.typeArgs.map(e=>c(e))};default:return{...n}}}var y=class{constructor(e={}){this.namedTypes=new Map;this.nameCounter=new Map;this.processing=new WeakSet;this.circularRefs=new Map;this.namingStyle=e.namingStyle||"PascalCase",this.prefix=e.prefix||"",this.suffix=e.suffix||"",this.customNameMap=e.customNameMap||{}}nameType(e,t={depth:0}){if(e.kind!=="object")return null;let r=this.buildPathKey(t);if(this.customNameMap[r])return this.applyAffixes(this.customNameMap[r]);let i=this.getTypeKey(e);if(this.namedTypes.has(i))return this.namedTypes.get(i);let o=this.generateName(e,t);return o=this.formatName(o),o=this.ensureUniqueName(o),o=this.applyAffixes(o),this.namedTypes.set(i,o),o}generateName(e,t){if(e.kind==="object"){if(t.fieldName){let r=this.toPascalCase(t.fieldName);return t.parentName?`${t.parentName}${r}`:r}return t.parentName?`${t.parentName}Item`:"AnonymousObject"}return"UnknownType"}ensureUniqueName(e){let t=this.nameCounter.get(e)||0;if(t===0)return this.nameCounter.set(e,1),e;let r=`${e}${t+1}`;return this.nameCounter.set(e,t+1),r}applyAffixes(e){let t=e;return this.prefix&&(t=this.toPascalCase(this.prefix)+t),this.suffix&&(t=t+this.toPascalCase(this.suffix)),t}buildPathKey(e){return e.path||""}getTypeKey(e){return e.kind==="object"?`object:${e.properties.map(t=>`${t.name}:${this.getSimpleTypeKey(t.type)}:${t.optional}`).sort().join(",")}`:e.kind}getSimpleTypeKey(e){switch(e.kind){case"primitive":return e.type;case"null":return"null";case"undefined":return"undefined";case"array":return`array<${this.getSimpleTypeKey(e.elementType)}>`;case"object":return"object";case"union":return e.types.map(t=>this.getSimpleTypeKey(t)).sort().join("|");case"generic":return`generic:${e.name}`;default:return"unknown"}}toPascalCase(e){return e?e.replace(/[-_\s]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim().split(" ").filter(Boolean).map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join(""):""}toCamelCase(e){let t=this.toPascalCase(e);return t.charAt(0).toLowerCase()+t.slice(1)}formatName(e){return this.namingStyle==="camelCase"?this.toCamelCase(e):this.toPascalCase(e)}isCircular(e){return this.processing.has(e)}markProcessing(e){this.processing.add(e)}unmarkProcessing(e){this.processing.delete(e)}getAllNamedTypes(){return new Map(this.namedTypes)}reset(){this.namedTypes.clear(),this.nameCounter.clear(),this.processing=new WeakSet,this.circularRefs.clear()}},f=class{constructor(e){this.collected=[];this.seenStructs=new Set;this.namer=e}collect(e,t){this.collected=[],this.seenStructs.clear(),this.namer.reset();let r=this.getStructKey(e);this.namer.nameType(e,{fieldName:t,path:t,depth:0}),this.collectRecursive(e,{fieldName:t,parentName:void 0,path:t,depth:0});let i=this.collected.find(s=>s.name===t),o=this.collected.filter(s=>s.name!==t);return i?[i,...o]:this.collected}collectRecursive(e,t){let r=this.getStructKey(e);if(e.kind==="object"){let i=this.namer.nameType(e,t);if(i&&!this.seenStructs.has(r)){this.seenStructs.add(r),this.collected.push({name:i,type:c(e)});for(let o of e.properties)this.collectRecursive(o.type,{fieldName:o.name,parentName:i,path:t.path?`${t.path}.${o.name}`:o.name,depth:t.depth+1})}return}if(e.kind==="array"){this.collectRecursive(e.elementType,{fieldName:t.fieldName?t.fieldName+"Item":void 0,parentName:t.parentName,path:t.path,depth:t.depth+1});return}if(e.kind==="union"){for(let i of e.types)this.collectRecursive(i,t);return}if(e.kind==="generic"){for(let i of e.typeArgs)this.collectRecursive(i,{...t,depth:t.depth+1});return}}getStructKey(e){return e.kind==="object"?`object:${e.properties.map(t=>`${t.name}:${this.getPropTypeKey(t.type)}:${t.optional}`).sort().join("|")}`:e.kind}getPropTypeKey(e){switch(e.kind){case"primitive":return e.type;case"null":return"null";case"undefined":return"undefined";case"array":return`array:${this.getPropTypeKey(e.elementType)}`;case"object":return"object";case"union":return e.types.map(t=>this.getPropTypeKey(t)).sort().join("|");case"generic":return`generic:${e.name}`;default:return"unknown"}}};var m=class{constructor(e,t){this.allNamedTypes=[];this.options=e,this.namer=t}findTypeName(e){if(e.kind!=="object")return null;for(let t of this.allNamedTypes)if(S(t.type,e))return t.name;return null}formatTypeDef(e){let{name:t,type:r}=e,i=this.options.addExport?"export ":"";return this.formatObjectType(t,r,i)}formatObjectType(e,t,r){let i=" ".repeat(this.options.indentSize),o=this.sortProperties(t.properties),s=[];this.options.outputStyle==="interface"?s.push(`${r}interface ${e} {`):s.push(`${r}type ${e} = {`);for(let p of o){let N=this.formatPropertyName(p.name),A=p.optional?"?":"",w=this.formatType(p.type);s.push(`${i}${N}${A}: ${w};`)}return this.options.outputStyle==="interface"?s.push("}"):s.push("};"),s.join(`
3
- `)}formatType(e){if(e.kind==="object"){let t=this.findTypeName(e);if(t)return t}switch(e.kind){case"primitive":return e.type;case"null":return"null";case"undefined":return"undefined";case"array":return this.formatArrayType(e);case"object":return this.formatInlineObject(e);case"union":return this.formatUnionType(e.types);case"literal":return this.formatLiteral(e.value);case"generic":return`${e.name}<${e.typeArgs.map(t=>this.formatType(t)).join(", ")}>`;default:return"unknown"}}formatLiteral(e){return typeof e=="string"?`'${e}'`:String(e)}formatArrayType(e){let t=this.formatType(e.elementType);return e.elementType.kind==="union"?`(${t})[]`:`${t}[]`}formatInlineObject(e){let t=" ".repeat(this.options.indentSize),r=this.sortProperties(e.properties);if(r.length===0)return"{}";let i=["{"];for(let o of r){let s=this.formatPropertyName(o.name),p=o.optional?"?":"",N=this.formatType(o.type);i.push(`${t}${s}${p}: ${N};`)}return i.push("}"),i.join(`
2
+ `,typeNameMap:{},typePrefix:"",typeSuffix:""};function c(n){return{kind:"primitive",type:n}}function R(){return{kind:"null"}}function C(){return{kind:"undefined"}}function D(n){return{kind:"array",elementType:n}}function v(n=[]){return{kind:"object",properties:n}}function j(n){let e=[],t=new Set;for(let r of n)if(r.kind==="union")for(let i of r.types){let s=a(i);t.has(s)||(t.add(s),e.push(i))}else{let i=a(r);t.has(i)||(t.add(i),e.push(r))}return e.length===1?e[0]:{kind:"union",types:e}}function a(n){switch(n.kind){case"primitive":return`primitive:${n.type}`;case"null":return"null";case"undefined":return"undefined";case"literal":return`literal:${typeof n.value}:${String(n.value)}`;case"array":return`array:${a(n.elementType)}`;case"object":return`object:${n.properties.map(e=>`${e.name}:${a(e.type)}:${e.optional}`).join(",")}`;case"union":return`union:${n.types.map(a).sort().join("|")}`;case"generic":return`generic:${n.name}:${n.typeArgs.map(a).join(",")}`;default:return"unknown"}}function d(n,e){return a(n)===a(e)?n:n.kind==="object"&&e.kind==="object"?x(n,e):n.kind==="array"&&e.kind==="array"?D(d(n.elementType,e.elementType)):j([n,e])}function x(n,e){let t=new Map;for(let r of n.properties)t.set(r.name,{...r});for(let r of e.properties){let i=t.get(r.name);i?(i.type=d(i.type,r.type),i.optional=i.optional||r.optional):t.set(r.name,{...r,optional:!0})}for(let[r,i]of t)e.properties.some(o=>o.name===r)||(i.optional=!0);return v(Array.from(t.values()))}function l(n,e=new WeakSet){if(n===null)return R();if(n===void 0)return C();if(typeof n=="function")return c("function");if(typeof n=="string")return c("string");if(typeof n=="number")return c("number");if(typeof n=="boolean")return c("boolean");if(Array.isArray(n))return O(n,e);if(typeof n=="object"&&n!==null){let t=n;if(e.has(t))return{kind:"object",properties:[]};e.add(t);let r=$(t,e);return e.delete(t),r}return c("unknown")}function O(n,e){if(n.length===0)return{kind:"array",elementType:{kind:"primitive",type:"any"}};let t=n.map(i=>l(i,e)),r=t[0];for(let i=1;i<t.length;i++)r=d(r,t[i]);return{kind:"array",elementType:r}}function $(n,e){let t=[];for(let[r,i]of Object.entries(n)){let s=l(i,e);t.push({name:r,type:s,optional:!1})}return v(t)}function S(n,e){return a(n)===a(e)}function u(n,e=new WeakMap){if(e.has(n))return e.get(n);let t;switch(n.kind){case"primitive":return t={kind:"primitive",type:n.type},e.set(n,t),t;case"null":return t={kind:"null"},e.set(n,t),t;case"undefined":return t={kind:"undefined"},e.set(n,t),t;case"literal":return t={kind:"literal",value:n.value},e.set(n,t),t;case"array":return t={kind:"array",elementType:{}},e.set(n,t),t.elementType=u(n.elementType,e),t;case"object":return t={kind:"object",properties:[],isRecord:n.isRecord,valueType:n.valueType},e.set(n,t),t.properties=n.properties.map(r=>({name:r.name,optional:r.optional,type:u(r.type,e)})),n.valueType&&(t.valueType=u(n.valueType,e)),t;case"union":return t={kind:"union",types:[]},e.set(n,t),t.types=n.types.map(r=>u(r,e)),t;case"generic":return t={kind:"generic",name:n.name,typeArgs:[]},e.set(n,t),t.typeArgs=n.typeArgs.map(r=>u(r,e)),t;default:return t={kind:"primitive",type:"unknown"},e.set(n,t),t}}var f=class{constructor(e={}){this.namedTypes=new Map;this.nameCounter=new Map;this.processing=new WeakSet;this.circularRefs=new Map;this.namingStyle=e.namingStyle||"PascalCase",this.prefix=e.prefix||"",this.suffix=e.suffix||"",this.customNameMap=e.customNameMap||{}}nameType(e,t={depth:0}){if(e.kind!=="object")return null;let r=this.buildPathKey(t);if(this.customNameMap[r])return this.applyAffixes(this.customNameMap[r]);let i=this.getTypeKey(e);if(this.namedTypes.has(i))return this.namedTypes.get(i);let s=this.generateName(e,t);return s=this.formatName(s),s=this.ensureUniqueName(s),s=this.applyAffixes(s),this.namedTypes.set(i,s),s}generateName(e,t){if(e.kind==="object"){if(t.fieldName){let r=this.toPascalCase(t.fieldName);return t.parentName?`${t.parentName}${r}`:r}return t.parentName?`${t.parentName}Item`:"AnonymousObject"}return"UnknownType"}ensureUniqueName(e){let t=this.nameCounter.get(e)||0;if(t===0)return this.nameCounter.set(e,1),e;let r=`${e}${t+1}`;return this.nameCounter.set(e,t+1),r}applyAffixes(e){let t=e;return this.prefix&&(t=this.toPascalCase(this.prefix)+t),this.suffix&&(t=t+this.toPascalCase(this.suffix)),t}buildPathKey(e){return e.path||""}getTypeKey(e){return e.kind==="object"?`object:${e.properties.map(t=>`${t.name}:${this.getSimpleTypeKey(t.type)}:${t.optional}`).sort().join(",")}`:e.kind}getSimpleTypeKey(e){switch(e.kind){case"primitive":return e.type;case"null":return"null";case"undefined":return"undefined";case"array":return`array<${this.getSimpleTypeKey(e.elementType)}>`;case"object":return"object";case"union":return e.types.map(t=>this.getSimpleTypeKey(t)).sort().join("|");case"generic":return`generic:${e.name}`;default:return"unknown"}}toPascalCase(e){return e?e.replace(/[-_\s]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim().split(" ").filter(Boolean).map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join(""):""}toCamelCase(e){let t=this.toPascalCase(e);return t.charAt(0).toLowerCase()+t.slice(1)}formatName(e){return this.namingStyle==="camelCase"?this.toCamelCase(e):this.toPascalCase(e)}isCircular(e){return this.processing.has(e)}markProcessing(e){this.processing.add(e)}unmarkProcessing(e){this.processing.delete(e)}getAllNamedTypes(){return new Map(this.namedTypes)}reset(){this.namedTypes.clear(),this.nameCounter.clear(),this.processing=new WeakSet,this.circularRefs.clear()}},y=class{constructor(e){this.collected=[];this.seenStructs=new Set;this.namer=e}collect(e,t){this.collected=[],this.seenStructs.clear(),this.namer.reset(),this.collectRecursive(e,{fieldName:t,parentName:void 0,path:t,depth:0});let r=this.collected.find(s=>s.name===t),i=this.collected.filter(s=>s.name!==t);return r?[r,...i]:this.collected}collectRecursive(e,t){let r=this.getStructKey(e);if(e.kind==="object"){let i=this.namer.nameType(e,t);if(i&&!this.seenStructs.has(r)){this.seenStructs.add(r),this.collected.push({name:i,type:u(e)});for(let s of e.properties)this.collectRecursive(s.type,{fieldName:s.name,parentName:i,path:t.path?`${t.path}.${s.name}`:s.name,depth:t.depth+1})}return}if(e.kind==="array"){this.collectRecursive(e.elementType,{fieldName:t.fieldName?t.fieldName+"Item":void 0,parentName:t.parentName,path:t.path,depth:t.depth+1});return}if(e.kind==="union"){for(let i of e.types)this.collectRecursive(i,t);return}if(e.kind==="generic"){for(let i of e.typeArgs)this.collectRecursive(i,{...t,depth:t.depth+1});return}}getStructKey(e){return e.kind==="object"?`object:${e.properties.map(t=>`${t.name}:${this.getPropTypeKey(t.type)}:${t.optional}`).sort().join("|")}`:e.kind}getPropTypeKey(e){switch(e.kind){case"primitive":return e.type;case"null":return"null";case"undefined":return"undefined";case"array":return`array:${this.getPropTypeKey(e.elementType)}`;case"object":return"object";case"union":return e.types.map(t=>this.getPropTypeKey(t)).sort().join("|");case"generic":return`generic:${e.name}`;default:return"unknown"}}};var m=class{constructor(e,t){this.allNamedTypes=[];this.options=e,this.namer=t}findTypeName(e){if(e.kind!=="object")return null;for(let t of this.allNamedTypes)if(S(t.type,e))return t.name;return null}formatTypeDef(e){let{name:t,type:r}=e,i=this.options.addExport?"export ":"";return this.formatObjectType(t,r,i)}formatObjectType(e,t,r){let i=" ".repeat(this.options.indentSize),s=this.sortProperties(t.properties),o=[];this.options.outputStyle==="interface"?o.push(`${r}interface ${e} {`):o.push(`${r}type ${e} = {`);for(let p of s){let N=this.formatPropertyName(p.name),A=p.optional?"?":"",w=this.formatType(p.type);o.push(`${i}${N}${A}: ${w};`)}return this.options.outputStyle==="interface"?o.push("}"):o.push("};"),o.join(`
3
+ `)}formatType(e){if(e.kind==="object"){let t=this.findTypeName(e);if(t)return t}switch(e.kind){case"primitive":return e.type;case"null":return"null";case"undefined":return"undefined";case"array":return this.formatArrayType(e);case"object":return this.formatInlineObject(e);case"union":return this.formatUnionType(e.types);case"literal":return this.formatLiteral(e.value);case"generic":return`${e.name}<${e.typeArgs.map(t=>this.formatType(t)).join(", ")}>`;default:return"unknown"}}formatLiteral(e){return typeof e=="string"?`'${e}'`:String(e)}formatArrayType(e){let t=this.formatType(e.elementType);return e.elementType.kind==="union"?`(${t})[]`:`${t}[]`}formatInlineObject(e){let t=" ".repeat(this.options.indentSize),r=this.sortProperties(e.properties);if(r.length===0)return"{}";let i=["{"];for(let s of r){let o=this.formatPropertyName(s.name),p=s.optional?"?":"",N=this.formatType(s.type);i.push(`${t}${o}${p}: ${N};`)}return i.push("}"),i.join(`
4
4
  `)}formatUnionType(e){return e.map(t=>this.formatType(t)).join(" | ")}formatPropertyName(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?e:`'${e}'`}sortProperties(e){return this.options.sortProperties==="definition"?[...e]:[...e].sort((t,r)=>t.name.localeCompare(r.name))}formatAll(e){return this.allNamedTypes=e,e.map(t=>this.formatTypeDef(t)).join(`
5
5
 
6
6
  `)}generateOutput(e,t){let r=`/**
@@ -9,4 +9,4 @@ var b={rootName:"Root",outputStyle:"interface",namingStyle:"PascalCase",sortProp
9
9
  */`,i=this.formatAll(e);return`${r}
10
10
 
11
11
  ${i}
12
- `}};var T=class{constructor(){this.patterns=[{name:"PageResult",arrayFields:["list","records","rows","items"],countFields:["total","count","totalCount"]},{name:"ListResult",arrayFields:["list","data","items"],countFields:[]},{name:"ApiResponse",arrayFields:["data"],countFields:[]}]}extract(e){if(e.kind!=="object")return e;for(let t of this.patterns){let r=this.tryMatchPattern(e,t);if(r)return r}return e}tryMatchPattern(e,t){let r=null,i=t.countFields.length===0;for(let o of e.properties)t.arrayFields.includes(o.name)&&o.type.kind==="array"&&(r={name:o.name,elementType:o.type.elementType}),t.countFields.includes(o.name)&&(i=!0);return r&&i?{kind:"generic",name:t.name,typeArgs:[r.elementType]}:null}},g=class{constructor(e=!1){this.strict=e}process(e){if(this.strict)return e;if(e.kind==="union"){let t=e.types.filter(r=>r.kind!=="null");return t.length===0?{kind:"null"}:t.length===1?t[0]:{...e,types:t}}return e.kind==="array"?{...e,elementType:this.process(e.elementType)}:e.kind==="object"?{...e,properties:e.properties.map(t=>({...t,type:this.process(t.type)}))}:e}},h=class{constructor(e=!0){this.markOptional=e}process(e,t){if(!this.markOptional)return t;if(t.kind==="array"&&Array.isArray(e)){let r=t.elementType;if(r.kind==="object"){let i=this.processArrayObjects(e,r);return{...t,elementType:i}}}return t}processArrayObjects(e,t){if(e.length<=1)return t;let r={},i=e.length;for(let o of e)if(o&&typeof o=="object")for(let s of Object.keys(o))r[s]=(r[s]||0)+1;return{...t,properties:t.properties.map(o=>{let p=(r[o.name]||0)<i;return{...o,optional:p}})}}};function k(n,e,t){let r=e;return t.markOptional&&(r=new h(t.markOptional).process(n,r)),t.extractGenerics&&(r=new T().extract(r)),r=new g(t.strictNullChecks).process(r),r}function P(n,e={}){let t={...b,...e},r=l(n);r=k(n,r,t);let i=new y({namingStyle:t.namingStyle,prefix:t.typePrefix,suffix:t.typeSuffix,customNameMap:t.typeNameMap}),s=new f(i).collect(r,t.rootName);return new m(t,i).generateOutput(s,t.rootName)}function U(n,e={}){let t=JSON.parse(n);return P(t,e)}var B={generate:P,generateFromString:U};export{m as CodeFormatter,T as GenericExtractor,g as NullHandler,h as OptionalHandler,f as TypeCollector,y as TypeNamer,k as applyEnhancements,j as createUnion,B as default,P as generate,U as generateFromString,v as inferArrayType,$ as inferObjectType,l as inferType,S as isStructurallyEqual,O as mergeObjects,d as mergeTypes};
12
+ `}};var T=class{constructor(){this.patterns=[{name:"PageResult",arrayFields:["list","records","rows","items"],countFields:["total","count","totalCount"]},{name:"ListResult",arrayFields:["list","data","items"],countFields:[]},{name:"ApiResponse",arrayFields:["data"],countFields:[]}];this.seen=new WeakSet}extract(e){return this.extractRecursive(e)}extractRecursive(e){if(e.kind!=="object")return e.kind==="array"?{...e,elementType:this.extractRecursive(e.elementType)}:e.kind==="union"?{...e,types:e.types.map(s=>this.extractRecursive(s))}:e.kind==="generic"?{...e,typeArgs:e.typeArgs.map(s=>this.extractRecursive(s))}:e;if(this.seen.has(e))return e;this.seen.add(e);let t=e.properties.map(s=>({...s,type:this.extractRecursive(s.type)})),r={...e,properties:t},i=null;for(let s of this.patterns){let o=this.tryMatchPattern(r,s);if(o){i=o;break}}return this.seen.delete(e),r}tryMatchPattern(e,t){let r=null,i=t.countFields.length===0;for(let s of e.properties)t.arrayFields.includes(s.name)&&s.type.kind==="array"&&(r={name:s.name,elementType:s.type.elementType}),t.countFields.includes(s.name)&&(i=!0);return r&&i?{kind:"generic",name:t.name,typeArgs:[r.elementType]}:null}},g=class{constructor(e=!1){this.seen=new WeakSet;this.strict=e}process(e){return this.processRecursive(e)}processRecursive(e){if(this.strict)return e;if(e.kind==="union"){let t=e.types.filter(r=>r.kind!=="null");return t.length===0?{kind:"null"}:t.length===1?t[0]:{...e,types:t.map(r=>this.processRecursive(r))}}if(e.kind==="array")return{...e,elementType:this.processRecursive(e.elementType)};if(e.kind==="object"){if(this.seen.has(e))return e;this.seen.add(e);let t={...e,properties:e.properties.map(r=>({...r,type:this.processRecursive(r.type)}))};return this.seen.delete(e),t}return e}},h=class{constructor(e=!0){this.seen=new WeakSet;this.markOptional=e}process(e,t){return this.markOptional?this.processRecursive(e,t):t}processRecursive(e,t){if(t.kind==="array"&&Array.isArray(e)){let r=t.elementType;if(r.kind==="object"){let i=this.processArrayObjects(e,r);return{...t,elementType:i}}return{...t,elementType:this.processRecursive(e,r)}}if(t.kind==="object"&&e&&typeof e=="object"){if(this.seen.has(t))return t;this.seen.add(t);let r=t.properties.map(i=>({...i,type:this.processRecursive(e[i.name],i.type)}));return this.seen.delete(t),{...t,properties:r}}return t.kind==="union"&&Array.isArray(e)?{...t,types:t.types.map(r=>this.processRecursive(e,r))}:t}processArrayObjects(e,t){if(e.length<=1)return t;let r={},i=e.length;for(let s of e)if(s&&typeof s=="object")for(let o of Object.keys(s))r[o]=(r[o]||0)+1;return{...t,properties:t.properties.map(s=>{let p=(r[s.name]||0)<i;return{...s,optional:p}})}}};function k(n,e,t){let r=e;return t.markOptional&&(r=new h(t.markOptional).process(n,r)),t.extractGenerics&&(r=new T().extract(r)),r=new g(t.strictNullChecks).process(r),r}function P(n,e={}){let t={...b,...e},r=l(n);r=k(n,r,t);let i=new f({namingStyle:t.namingStyle,prefix:t.typePrefix,suffix:t.typeSuffix,customNameMap:t.typeNameMap}),o=new y(i).collect(r,t.rootName);return new m(t,i).generateOutput(o,t.rootName)}function G(n,e={}){let t=JSON.parse(n);return P(t,e)}var H={generate:P,generateFromString:G};export{m as CodeFormatter,T as GenericExtractor,g as NullHandler,h as OptionalHandler,y as TypeCollector,f as TypeNamer,k as applyEnhancements,j as createUnion,H as default,P as generate,G as generateFromString,O as inferArrayType,$ as inferObjectType,l as inferType,S as isStructurallyEqual,x as mergeObjects,d as mergeTypes};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "type-flash",
3
- "version": "1.1.4",
3
+ "version": "1.1.7",
4
4
  "description": "JSON 智能生成 TypeScript 类型定义 - 一键从 JSON 数据生成 Interface / Type 定义",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",