type-flash 1.3.0 → 1.3.1
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/README.md +2 -7
- package/bin/type-flash.js +0 -6
- package/dist/index.d.mts +10 -15
- package/dist/index.d.ts +10 -15
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -215,9 +215,6 @@ type-flash -i user.json -s type
|
|
|
215
215
|
#### 常用选项示例
|
|
216
216
|
|
|
217
217
|
```bash
|
|
218
|
-
# 严格空值模式(保留 null 为独立类型)
|
|
219
|
-
type-flash -i user.json --strict-null
|
|
220
|
-
|
|
221
218
|
# 添加类型前缀/后缀
|
|
222
219
|
type-flash -i user.json --prefix I --suffix DTO -o user.ts
|
|
223
220
|
|
|
@@ -279,7 +276,6 @@ curl.exe https://api.example.com/users | type-flash -n UserList
|
|
|
279
276
|
| `--naming-style <s>` | 命名风格: `PascalCase` \| `camelCase` | `PascalCase` |
|
|
280
277
|
| `--sort <order>` | 属性排序: `alpha` \| `definition` | `alpha` |
|
|
281
278
|
| `--no-export` | 不添加 export 关键字 | - |
|
|
282
|
-
| `--strict-null` | 严格空值模式(保留 null 类型) | - |
|
|
283
279
|
| `--no-optional` | 不标记可选属性 | - |
|
|
284
280
|
| `--indent <n>` | 缩进空格数 | `2` |
|
|
285
281
|
| `--prefix <prefix>` | 类型名前缀 | - |
|
|
@@ -300,7 +296,6 @@ curl.exe https://api.example.com/users | type-flash -n UserList
|
|
|
300
296
|
| `namingStyle` | `'PascalCase' \| 'camelCase'` | `'PascalCase'` | 生成的类型名命名风格 |
|
|
301
297
|
| `sortProperties` | `'alpha' \| 'definition'` | `'alpha'` | 属性排序方式,字母序或定义序 |
|
|
302
298
|
| `addExport` | `boolean` | `true` | 是否添加 export 关键字 |
|
|
303
|
-
| `strictNullChecks` | `boolean` | `false` | 是否启用严格空值模式,保留 null 为独立类型 |
|
|
304
299
|
| `markOptional` | `boolean` | `true` | 是否自动标记可选属性 |
|
|
305
300
|
| `indentSize` | `number` | `2` | 缩进空格数 |
|
|
306
301
|
| `lineEnding` | `string` | `'\n'` | 行尾换行符 |
|
|
@@ -350,8 +345,8 @@ const code = generate(jsonData, {
|
|
|
350
345
|
### Q: 生成的类型名为什么是 UserProfile 而不是 Profile?
|
|
351
346
|
A: type-flash 默认会用父级类型名 + 字段名来生成子类型名,避免重名。如果想自定义类型名,可以使用 `typeNameMap` 配置。
|
|
352
347
|
|
|
353
|
-
### Q: 为什么数组里的 null
|
|
354
|
-
A:
|
|
348
|
+
### Q: 为什么数组里的 null 会保留?
|
|
349
|
+
A: 联合类型中的 `null` 会如实保留,例如 `(string | null)[]` 或 `string | null`,与 JSON 数据结构一致。
|
|
355
350
|
|
|
356
351
|
### Q: 支持循环引用的 JSON 吗?
|
|
357
352
|
A: 支持。type-flash 会自动检测循环引用并生成合法的 type alias,不会出现栈溢出。
|
package/bin/type-flash.js
CHANGED
|
@@ -22,7 +22,6 @@ function parseArgs() {
|
|
|
22
22
|
namingStyle: 'PascalCase',
|
|
23
23
|
sortProperties: 'alpha',
|
|
24
24
|
addExport: true,
|
|
25
|
-
strictNullChecks: false,
|
|
26
25
|
markOptional: true,
|
|
27
26
|
indentSize: 2,
|
|
28
27
|
typePrefix: '',
|
|
@@ -61,9 +60,6 @@ function parseArgs() {
|
|
|
61
60
|
case '--no-export':
|
|
62
61
|
options.addExport = false;
|
|
63
62
|
break;
|
|
64
|
-
case '--strict-null':
|
|
65
|
-
options.strictNullChecks = true;
|
|
66
|
-
break;
|
|
67
63
|
case '--no-optional':
|
|
68
64
|
options.markOptional = false;
|
|
69
65
|
break;
|
|
@@ -110,7 +106,6 @@ type-flash - JSON 智能生成 TypeScript 类型定义
|
|
|
110
106
|
--naming-style <s> 命名风格: PascalCase | camelCase (默认: PascalCase)
|
|
111
107
|
--sort <order> 属性排序: alpha | definition (默认: alpha)
|
|
112
108
|
--no-export 不添加 export 语句
|
|
113
|
-
--strict-null 严格空值模式
|
|
114
109
|
--no-optional 不标记可选属性
|
|
115
110
|
--indent <n> 缩进空格数 (默认: 2)
|
|
116
111
|
--prefix <prefix> 类型名前缀
|
|
@@ -233,7 +228,6 @@ async function main() {
|
|
|
233
228
|
namingStyle: options.namingStyle,
|
|
234
229
|
sortProperties: options.sortProperties,
|
|
235
230
|
addExport: options.addExport,
|
|
236
|
-
strictNullChecks: options.strictNullChecks,
|
|
237
231
|
markOptional: options.markOptional,
|
|
238
232
|
indentSize: options.indentSize,
|
|
239
233
|
typePrefix: options.typePrefix,
|
package/dist/index.d.mts
CHANGED
|
@@ -99,8 +99,6 @@ interface GenerateOptions {
|
|
|
99
99
|
sortProperties?: SortOrder;
|
|
100
100
|
/** 是否添加 export 语句,默认 true */
|
|
101
101
|
addExport?: boolean;
|
|
102
|
-
/** 是否严格空值(null 单独类型),默认 false */
|
|
103
|
-
strictNullChecks?: boolean;
|
|
104
102
|
/** 是否将可选属性标记为 ?,默认 true */
|
|
105
103
|
markOptional?: boolean;
|
|
106
104
|
/** 缩进空格数,默认 2 */
|
|
@@ -383,26 +381,21 @@ declare function inferObjectType(obj: Record<string, unknown>, seen?: WeakSet<ob
|
|
|
383
381
|
declare function isStructurallyEqual(a: TSTypeNode, b: TSTypeNode): boolean;
|
|
384
382
|
|
|
385
383
|
/**
|
|
384
|
+
|
|
386
385
|
* type-flash - 增强功能模块
|
|
386
|
+
|
|
387
387
|
*
|
|
388
|
+
|
|
388
389
|
* 核心功能:
|
|
389
|
-
|
|
390
|
-
* - 空值处理
|
|
390
|
+
|
|
391
391
|
* - 可选属性处理
|
|
392
|
-
*/
|
|
393
392
|
|
|
394
|
-
/**
|
|
395
|
-
* 空值处理器
|
|
396
393
|
*/
|
|
397
|
-
|
|
398
|
-
private strict;
|
|
399
|
-
private seen;
|
|
400
|
-
constructor(strict?: boolean);
|
|
401
|
-
process(type: TSTypeNode): TSTypeNode;
|
|
402
|
-
private processRecursive;
|
|
403
|
-
}
|
|
394
|
+
|
|
404
395
|
/**
|
|
396
|
+
|
|
405
397
|
* 可选属性处理器
|
|
398
|
+
|
|
406
399
|
*/
|
|
407
400
|
declare class OptionalHandler {
|
|
408
401
|
private markOptional;
|
|
@@ -413,7 +406,9 @@ declare class OptionalHandler {
|
|
|
413
406
|
private processArrayObjects;
|
|
414
407
|
}
|
|
415
408
|
/**
|
|
409
|
+
|
|
416
410
|
* 应用所有增强功能
|
|
411
|
+
|
|
417
412
|
*/
|
|
418
413
|
declare function applyEnhancements(jsonData: any, type: TSTypeNode, options: GenerateOptions): TSTypeNode;
|
|
419
414
|
|
|
@@ -443,4 +438,4 @@ declare const _default: {
|
|
|
443
438
|
generateFromString: typeof generateFromString;
|
|
444
439
|
};
|
|
445
440
|
|
|
446
|
-
export { type ArrayType, CodeFormatter, type GenerateOptions, type GenericType, type NamingStyle,
|
|
441
|
+
export { type ArrayType, CodeFormatter, type GenerateOptions, type GenericType, type NamingStyle, type ObjectType, OptionalHandler, type OutputStyle, type PrimitiveType, type PropertyDef, type SortOrder, type TSTypeNode, TypeCollector, TypeNamer, type UnionType, applyEnhancements, createUnion, _default as default, generate, generateFromString, inferArrayType, inferObjectType, inferType, isStructurallyEqual, mergeObjects, mergeTypes };
|
package/dist/index.d.ts
CHANGED
|
@@ -99,8 +99,6 @@ interface GenerateOptions {
|
|
|
99
99
|
sortProperties?: SortOrder;
|
|
100
100
|
/** 是否添加 export 语句,默认 true */
|
|
101
101
|
addExport?: boolean;
|
|
102
|
-
/** 是否严格空值(null 单独类型),默认 false */
|
|
103
|
-
strictNullChecks?: boolean;
|
|
104
102
|
/** 是否将可选属性标记为 ?,默认 true */
|
|
105
103
|
markOptional?: boolean;
|
|
106
104
|
/** 缩进空格数,默认 2 */
|
|
@@ -383,26 +381,21 @@ declare function inferObjectType(obj: Record<string, unknown>, seen?: WeakSet<ob
|
|
|
383
381
|
declare function isStructurallyEqual(a: TSTypeNode, b: TSTypeNode): boolean;
|
|
384
382
|
|
|
385
383
|
/**
|
|
384
|
+
|
|
386
385
|
* type-flash - 增强功能模块
|
|
386
|
+
|
|
387
387
|
*
|
|
388
|
+
|
|
388
389
|
* 核心功能:
|
|
389
|
-
|
|
390
|
-
* - 空值处理
|
|
390
|
+
|
|
391
391
|
* - 可选属性处理
|
|
392
|
-
*/
|
|
393
392
|
|
|
394
|
-
/**
|
|
395
|
-
* 空值处理器
|
|
396
393
|
*/
|
|
397
|
-
|
|
398
|
-
private strict;
|
|
399
|
-
private seen;
|
|
400
|
-
constructor(strict?: boolean);
|
|
401
|
-
process(type: TSTypeNode): TSTypeNode;
|
|
402
|
-
private processRecursive;
|
|
403
|
-
}
|
|
394
|
+
|
|
404
395
|
/**
|
|
396
|
+
|
|
405
397
|
* 可选属性处理器
|
|
398
|
+
|
|
406
399
|
*/
|
|
407
400
|
declare class OptionalHandler {
|
|
408
401
|
private markOptional;
|
|
@@ -413,7 +406,9 @@ declare class OptionalHandler {
|
|
|
413
406
|
private processArrayObjects;
|
|
414
407
|
}
|
|
415
408
|
/**
|
|
409
|
+
|
|
416
410
|
* 应用所有增强功能
|
|
411
|
+
|
|
417
412
|
*/
|
|
418
413
|
declare function applyEnhancements(jsonData: any, type: TSTypeNode, options: GenerateOptions): TSTypeNode;
|
|
419
414
|
|
|
@@ -443,4 +438,4 @@ declare const _default: {
|
|
|
443
438
|
generateFromString: typeof generateFromString;
|
|
444
439
|
};
|
|
445
440
|
|
|
446
|
-
export { type ArrayType, CodeFormatter, type GenerateOptions, type GenericType, type NamingStyle,
|
|
441
|
+
export { type ArrayType, CodeFormatter, type GenerateOptions, type GenericType, type NamingStyle, type ObjectType, OptionalHandler, type OutputStyle, type PrimitiveType, type PropertyDef, type SortOrder, type TSTypeNode, TypeCollector, TypeNamer, type UnionType, applyEnhancements, createUnion, _default as default, generate, generateFromString, inferArrayType, inferObjectType, inferType, isStructurallyEqual, mergeObjects, mergeTypes };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var S=Object.defineProperty;var
|
|
2
|
-
`,typeNameMap:{},typePrefix:"",typeSuffix:""};function u(n){return{kind:"primitive",type:n}}function L(){return{kind:"null"}}function W(){return{kind:"undefined"}}function K(n){return{kind:"array",elementType:n}}function w(n=[]){return{kind:"object",properties:n}}function b(n){let e=[],t=new Set;for(let r of n)if(r.kind==="union")for(let i of r.types){let o=p(i);t.has(o)||(t.add(o),e.push(i))}else{let i=p(r);t.has(i)||(t.add(i),e.push(r))}return e.length===1?e[0]:{kind:"union",types:e}}function p(n,e=new Set){if(e.has(n))return"circular";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:${p(n.elementType,e)}`;case"object":{e.add(n);let t=`object:${n.properties.map(r=>`${r.name}:${p(r.type,e)}:${r.optional}`).sort().join(",")}`;return e.delete(n),t}case"union":return`union:${n.types.map(t=>p(t,e)).sort().join("|")}`;case"generic":return`generic:${n.name}:${n.typeArgs.map(t=>p(t,e)).join(",")}`;default:return"unknown"}}function T(n,e){return p(n)===p(e)?n:n.kind==="object"&&e.kind==="object"?j(n,e):n.kind==="array"&&e.kind==="array"?K(T(n.elementType,e.elementType)):b([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=T(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 w(Array.from(t.values()))}function _(n){if(n instanceof Date||n instanceof RegExp||typeof Buffer!="undefined"&&Buffer.isBuffer(n))return u("string");let e=Object.prototype.toString.call(n);return e==="[object Date]"||e==="[object RegExp]"?u("string"):e==="[object Map]"||e==="[object Set]"||e==="[object WeakMap]"||e==="[object WeakSet]"?u("unknown"):null}function c(n,e=new WeakSet,t=new WeakMap){if(n===null)return L();if(n===void 0)return W();if(typeof n=="function")return u("Function");if(typeof n=="string")return u("string");if(typeof n=="number")return u("number");if(typeof n=="boolean")return u("boolean");if(Array.isArray(n))return O(n,e,t);if(typeof n=="object"&&n!==null){let r=_(n);if(r)return r;let i=n;if(e.has(i)){let a=t.get(i);if(a)return a}e.add(i);let o=w([]);t.set(i,o);let s=[];for(let[a,d]of Object.entries(i))s.push({name:a,type:c(d,e,t),optional:!1});return o.properties=s,e.delete(i),o}return u("unknown")}function O(n,e,t=new WeakMap){if(n.length===0)return{kind:"array",elementType:{kind:"primitive",type:"unknown"}};let r=n.map(o=>c(o,e,t)),i=r[0];for(let o=1;o<r.length;o++)i=T(i,r[o]);return{kind:"array",elementType:i}}function $(n,e=new WeakSet,t=new WeakMap){return c(n,e,t)}function N(n,e){return n===e?!0:p(n)===p(e)}function l(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=l(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:l(r.type,e)})),n.valueType&&(t.valueType=l(n.valueType,e)),t;case"union":return t={kind:"union",types:[]},e.set(n,t),t.types=n.types.map(r=>l(r,e)),t;case"generic":return t={kind:"generic",name:n.name,typeArgs:[]},e.set(n,t),t.typeArgs=n.typeArgs.map(r=>l(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 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 p(e)}getSimpleTypeKey(e){return p(e)}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(o=>o.name===t),i=this.collected.filter(o=>o.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:l(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 p(e)}};var m=class{constructor(e,t){this.allNamedTypes=[];this.options=e,this.namer=t}get eol(){return this.options.lineEnding}joinLines(e){return e.join(this.eol)}findTypeName(e){if(e.kind!=="object")return null;for(let t of this.allNamedTypes)if(t.type===e||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 a of o){let d=this.formatPropertyName(a.name),P=a.optional?"?":"",R=this.formatType(a.type);s.push(`${i}${d}${P}: ${R};`)}return this.options.outputStyle==="interface"?s.push("}"):s.push("};"),this.joinLines(s)}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),a=o.optional?"?":"",d=this.formatType(o.type);i.push(`${t}${s}${a}: ${d};`)}return i.push("}"),this.joinLines(i)}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(`${this.eol}${this.eol}`)}generateOutput(e,t){let r=this.joinLines(["/**"," * Generated by type-flash",` * Root type: ${t}`," */"]),i=this.formatAll(e);return`${r}${this.eol}${this.eol}${i}${this.eol}`}};var 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==="null")return{kind:"primitive",type:"unknown"};if(e.kind==="union"){let t=e.types.filter(r=>r.kind!=="null");return t.length===0?{kind:"primitive",type:"unknown"}:t.length===1?this.processRecursive(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===e?{...r}:{...r,type:this.processRecursive(r.type)})};for(let r of t.properties)r.type===e&&(r.type=t);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:t.properties.map(i=>i.type===t?{...i}:{...i,type:this.processRecursive(e[i.name],i.type)})};for(let i of r.properties)i.type===t&&(i.type=r);return this.seen.delete(t),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 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 a=(r[o.name]||0)<i;return{...o,optional:a}})}}};function k(n,e,t){let r=e;return t.markOptional&&(r=new h(t.markOptional).process(n,r)),r=new g(t.strictNullChecks).process(r),r}function v(n,e={}){let t={...x,...e},r=c(n);r=k(n,r,t);let i=new f({namingStyle:t.namingStyle,prefix:t.typePrefix,suffix:t.typeSuffix,customNameMap:t.typeNameMap}),s=new y(i).collect(r,t.rootName);return new m(t,i).generateOutput(s,t.rootName)}function A(n,e={}){let t=JSON.parse(n);return v(t,e)}var q={generate:v,generateFromString:A};0&&(module.exports={CodeFormatter,NullHandler,OptionalHandler,TypeCollector,TypeNamer,applyEnhancements,createUnion,generate,generateFromString,inferArrayType,inferObjectType,inferType,isStructurallyEqual,mergeObjects,mergeTypes});
|
|
1
|
+
"use strict";var S=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var D=Object.prototype.hasOwnProperty;var M=(r,e)=>{for(var t in e)S(r,t,{get:e[t],enumerable:!0})},U=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of C(e))!D.call(r,i)&&i!==t&&S(r,i,{get:()=>e[i],enumerable:!(n=R(e,i))||n.enumerable});return r};var E=r=>U(S({},"__esModule",{value:!0}),r);var q={};M(q,{CodeFormatter:()=>m,OptionalHandler:()=>g,TypeCollector:()=>y,TypeNamer:()=>f,applyEnhancements:()=>N,createUnion:()=>k,default:()=>_,generate:()=>O,generateFromString:()=>A,inferArrayType:()=>j,inferObjectType:()=>$,inferType:()=>l,isStructurallyEqual:()=>h,mergeObjects:()=>b,mergeTypes:()=>d});module.exports=E(q);var x={rootName:"Root",outputStyle:"interface",namingStyle:"PascalCase",sortProperties:"alpha",addExport:!0,markOptional:!0,indentSize:2,lineEnding:`
|
|
2
|
+
`,typeNameMap:{},typePrefix:"",typeSuffix:""};function u(r){return{kind:"primitive",type:r}}function G(){return{kind:"null"}}function L(){return{kind:"undefined"}}function W(r){return{kind:"array",elementType:r}}function v(r=[]){return{kind:"object",properties:r}}function k(r){let e=[],t=new Set;for(let n of r)if(n.kind==="union")for(let i of n.types){let o=p(i);t.has(o)||(t.add(o),e.push(i))}else{let i=p(n);t.has(i)||(t.add(i),e.push(n))}return e.length===1?e[0]:{kind:"union",types:e}}function p(r,e=new Set){if(e.has(r))return"circular";switch(r.kind){case"primitive":return`primitive:${r.type}`;case"null":return"null";case"undefined":return"undefined";case"literal":return`literal:${typeof r.value}:${String(r.value)}`;case"array":return`array:${p(r.elementType,e)}`;case"object":{e.add(r);let t=`object:${r.properties.map(n=>`${n.name}:${p(n.type,e)}:${n.optional}`).sort().join(",")}`;return e.delete(r),t}case"union":return`union:${r.types.map(t=>p(t,e)).sort().join("|")}`;case"generic":return`generic:${r.name}:${r.typeArgs.map(t=>p(t,e)).join(",")}`;default:return"unknown"}}function d(r,e){return p(r)===p(e)?r:r.kind==="object"&&e.kind==="object"?b(r,e):r.kind==="array"&&e.kind==="array"?W(d(r.elementType,e.elementType)):k([r,e])}function b(r,e){let t=new Map;for(let n of r.properties)t.set(n.name,{...n});for(let n of e.properties){let i=t.get(n.name);i?(i.type=d(i.type,n.type),i.optional=i.optional||n.optional):t.set(n.name,{...n,optional:!0})}for(let[n,i]of t)e.properties.some(s=>s.name===n)||(i.optional=!0);return v(Array.from(t.values()))}function K(r){if(r instanceof Date||r instanceof RegExp||typeof Buffer!="undefined"&&Buffer.isBuffer(r))return u("string");let e=Object.prototype.toString.call(r);return e==="[object Date]"||e==="[object RegExp]"?u("string"):e==="[object Map]"||e==="[object Set]"||e==="[object WeakMap]"||e==="[object WeakSet]"?u("unknown"):null}function l(r,e=new WeakSet,t=new WeakMap){if(r===null)return G();if(r===void 0)return L();if(typeof r=="function")return u("Function");if(typeof r=="string")return u("string");if(typeof r=="number")return u("number");if(typeof r=="boolean")return u("boolean");if(Array.isArray(r))return j(r,e,t);if(typeof r=="object"&&r!==null){let n=K(r);if(n)return n;let i=r;if(e.has(i)){let a=t.get(i);if(a)return a}e.add(i);let o=v([]);t.set(i,o);let s=[];for(let[a,T]of Object.entries(i))s.push({name:a,type:l(T,e,t),optional:!1});return o.properties=s,e.delete(i),o}return u("unknown")}function j(r,e,t=new WeakMap){if(r.length===0)return{kind:"array",elementType:{kind:"primitive",type:"unknown"}};let n=r.map(o=>l(o,e,t)),i=n[0];for(let o=1;o<n.length;o++)i=d(i,n[o]);return{kind:"array",elementType:i}}function $(r,e=new WeakSet,t=new WeakMap){return l(r,e,t)}function h(r,e){return r===e?!0:p(r)===p(e)}function c(r,e=new WeakMap){if(e.has(r))return e.get(r);let t;switch(r.kind){case"primitive":return t={kind:"primitive",type:r.type},e.set(r,t),t;case"null":return t={kind:"null"},e.set(r,t),t;case"undefined":return t={kind:"undefined"},e.set(r,t),t;case"literal":return t={kind:"literal",value:r.value},e.set(r,t),t;case"array":return t={kind:"array",elementType:{}},e.set(r,t),t.elementType=c(r.elementType,e),t;case"object":return t={kind:"object",properties:[],isRecord:r.isRecord,valueType:r.valueType},e.set(r,t),t.properties=r.properties.map(n=>({name:n.name,optional:n.optional,type:c(n.type,e)})),r.valueType&&(t.valueType=c(r.valueType,e)),t;case"union":return t={kind:"union",types:[]},e.set(r,t),t.types=r.types.map(n=>c(n,e)),t;case"generic":return t={kind:"generic",name:r.name,typeArgs:[]},e.set(r,t),t.typeArgs=r.typeArgs.map(n=>c(n,e)),t;default:return t={kind:"primitive",type:"unknown"},e.set(r,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 n=this.buildPathKey(t);if(this.customNameMap[n])return this.applyAffixes(this.customNameMap[n]);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 n=this.toPascalCase(t.fieldName);return t.parentName?`${t.parentName}${n}`:n}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 n=`${e}${t+1}`;return this.nameCounter.set(e,t+1),n}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 p(e)}getSimpleTypeKey(e){return p(e)}toPascalCase(e){return e?e.replace(/[-_\s]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim().split(" ").filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.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 n=this.collected.find(o=>o.name===t),i=this.collected.filter(o=>o.name!==t);return n?[n,...i]:this.collected}collectRecursive(e,t){let n=this.getStructKey(e);if(e.kind==="object"){let i=this.namer.nameType(e,t);if(i&&!this.seenStructs.has(n)){this.seenStructs.add(n),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 p(e)}};var m=class{constructor(e,t){this.allNamedTypes=[];this.options=e,this.namer=t}get eol(){return this.options.lineEnding}joinLines(e){return e.join(this.eol)}findTypeName(e){if(e.kind!=="object")return null;for(let t of this.allNamedTypes)if(t.type===e||h(t.type,e))return t.name;return null}formatTypeDef(e){let{name:t,type:n}=e,i=this.options.addExport?"export ":"";return this.formatObjectType(t,n,i)}formatObjectType(e,t,n){let i=" ".repeat(this.options.indentSize),o=this.sortProperties(t.properties),s=[];this.options.outputStyle==="interface"?s.push(`${n}interface ${e} {`):s.push(`${n}type ${e} = {`);for(let a of o){let T=this.formatPropertyName(a.name),P=a.optional?"?":"",w=this.formatType(a.type);s.push(`${i}${T}${P}: ${w};`)}return this.options.outputStyle==="interface"?s.push("}"):s.push("};"),this.joinLines(s)}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),n=this.sortProperties(e.properties);if(n.length===0)return"{}";let i=["{"];for(let o of n){let s=this.formatPropertyName(o.name),a=o.optional?"?":"",T=this.formatType(o.type);i.push(`${t}${s}${a}: ${T};`)}return i.push("}"),this.joinLines(i)}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,n)=>t.name.localeCompare(n.name))}formatAll(e){return this.allNamedTypes=e,e.map(t=>this.formatTypeDef(t)).join(`${this.eol}${this.eol}`)}generateOutput(e,t){let n=this.joinLines(["/**"," * Generated by type-flash",` * Root type: ${t}`," */"]),i=this.formatAll(e);return`${n}${this.eol}${this.eol}${i}${this.eol}`}};var g=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 n=t.elementType;if(n.kind==="object"){let i=this.processArrayObjects(e,n);return{...t,elementType:i}}return{...t,elementType:this.processRecursive(e,n)}}if(t.kind==="object"&&e&&typeof e=="object"){if(this.seen.has(t))return t;this.seen.add(t);let n={...t,properties:t.properties.map(i=>i.type===t?{...i}:{...i,type:this.processRecursive(e[i.name],i.type)})};for(let i of n.properties)i.type===t&&(i.type=n);return this.seen.delete(t),n}return t.kind==="union"&&Array.isArray(e)?{...t,types:t.types.map(n=>this.processRecursive(e,n))}:t}processArrayObjects(e,t){if(e.length<=1)return t;let n={},i=e.length;for(let o of e)if(o&&typeof o=="object")for(let s of Object.keys(o))n[s]=(n[s]||0)+1;return{...t,properties:t.properties.map(o=>{let a=(n[o.name]||0)<i;return{...o,optional:a}})}}};function N(r,e,t){return t.markOptional?new g(t.markOptional).process(r,e):e}function O(r,e={}){let t={...x,...e},n=l(r);n=N(r,n,t);let i=new f({namingStyle:t.namingStyle,prefix:t.typePrefix,suffix:t.typeSuffix,customNameMap:t.typeNameMap}),s=new y(i).collect(n,t.rootName);return new m(t,i).generateOutput(s,t.rootName)}function A(r,e={}){let t=JSON.parse(r);return O(t,e)}var _={generate:O,generateFromString:A};0&&(module.exports={CodeFormatter,OptionalHandler,TypeCollector,TypeNamer,applyEnhancements,createUnion,generate,generateFromString,inferArrayType,inferObjectType,inferType,isStructurallyEqual,mergeObjects,mergeTypes});
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var S={rootName:"Root",outputStyle:"interface",namingStyle:"PascalCase",sortProperties:"alpha",addExport:!0,
|
|
2
|
-
`,typeNameMap:{},typePrefix:"",typeSuffix:""};function u(n){return{kind:"primitive",type:n}}function A(){return{kind:"null"}}function P(){return{kind:"undefined"}}function R(n){return{kind:"array",elementType:n}}function b(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=p(i);t.has(o)||(t.add(o),e.push(i))}else{let i=p(r);t.has(i)||(t.add(i),e.push(r))}return e.length===1?e[0]:{kind:"union",types:e}}function p(n,e=new Set){if(e.has(n))return"circular";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:${p(n.elementType,e)}`;case"object":{e.add(n);let t=`object:${n.properties.map(r=>`${r.name}:${p(r.type,e)}:${r.optional}`).sort().join(",")}`;return e.delete(n),t}case"union":return`union:${n.types.map(t=>p(t,e)).sort().join("|")}`;case"generic":return`generic:${n.name}:${n.typeArgs.map(t=>p(t,e)).join(",")}`;default:return"unknown"}}function T(n,e){return p(n)===p(e)?n:n.kind==="object"&&e.kind==="object"?O(n,e):n.kind==="array"&&e.kind==="array"?R(T(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=T(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 b(Array.from(t.values()))}function C(n){if(n instanceof Date||n instanceof RegExp||typeof Buffer!="undefined"&&Buffer.isBuffer(n))return u("string");let e=Object.prototype.toString.call(n);return e==="[object Date]"||e==="[object RegExp]"?u("string"):e==="[object Map]"||e==="[object Set]"||e==="[object WeakMap]"||e==="[object WeakSet]"?u("unknown"):null}function c(n,e=new WeakSet,t=new WeakMap){if(n===null)return A();if(n===void 0)return P();if(typeof n=="function")return u("Function");if(typeof n=="string")return u("string");if(typeof n=="number")return u("number");if(typeof n=="boolean")return u("boolean");if(Array.isArray(n))return v(n,e,t);if(typeof n=="object"&&n!==null){let r=C(n);if(r)return r;let i=n;if(e.has(i)){let a=t.get(i);if(a)return a}e.add(i);let o=b([]);t.set(i,o);let s=[];for(let[a,f]of Object.entries(i))s.push({name:a,type:c(f,e,t),optional:!1});return o.properties=s,e.delete(i),o}return u("unknown")}function v(n,e,t=new WeakMap){if(n.length===0)return{kind:"array",elementType:{kind:"primitive",type:"unknown"}};let r=n.map(o=>c(o,e,t)),i=r[0];for(let o=1;o<r.length;o++)i=T(i,r[o]);return{kind:"array",elementType:i}}function D(n,e=new WeakSet,t=new WeakMap){return c(n,e,t)}function N(n,e){return n===e?!0:p(n)===p(e)}function l(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=l(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:l(r.type,e)})),n.valueType&&(t.valueType=l(n.valueType,e)),t;case"union":return t={kind:"union",types:[]},e.set(n,t),t.types=n.types.map(r=>l(r,e)),t;case"generic":return t={kind:"generic",name:n.name,typeArgs:[]},e.set(n,t),t.typeArgs=n.typeArgs.map(r=>l(r,e)),t;default:return t={kind:"primitive",type:"unknown"},e.set(n,t),t}}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 p(e)}getSimpleTypeKey(e){return p(e)}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()}},m=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(o=>o.name===t),i=this.collected.filter(o=>o.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:l(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 p(e)}};var d=class{constructor(e,t){this.allNamedTypes=[];this.options=e,this.namer=t}get eol(){return this.options.lineEnding}joinLines(e){return e.join(this.eol)}findTypeName(e){if(e.kind!=="object")return null;for(let t of this.allNamedTypes)if(t.type===e||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 a of o){let f=this.formatPropertyName(a.name),w=a.optional?"?":"",$=this.formatType(a.type);s.push(`${i}${f}${w}: ${$};`)}return this.options.outputStyle==="interface"?s.push("}"):s.push("};"),this.joinLines(s)}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),a=o.optional?"?":"",f=this.formatType(o.type);i.push(`${t}${s}${a}: ${f};`)}return i.push("}"),this.joinLines(i)}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(`${this.eol}${this.eol}`)}generateOutput(e,t){let r=this.joinLines(["/**"," * Generated by type-flash",` * Root type: ${t}`," */"]),i=this.formatAll(e);return`${r}${this.eol}${this.eol}${i}${this.eol}`}};var 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==="null")return{kind:"primitive",type:"unknown"};if(e.kind==="union"){let t=e.types.filter(r=>r.kind!=="null");return t.length===0?{kind:"primitive",type:"unknown"}:t.length===1?this.processRecursive(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===e?{...r}:{...r,type:this.processRecursive(r.type)})};for(let r of t.properties)r.type===e&&(r.type=t);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:t.properties.map(i=>i.type===t?{...i}:{...i,type:this.processRecursive(e[i.name],i.type)})};for(let i of r.properties)i.type===t&&(i.type=r);return this.seen.delete(t),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 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 a=(r[o.name]||0)<i;return{...o,optional:a}})}}};function k(n,e,t){let r=e;return t.markOptional&&(r=new h(t.markOptional).process(n,r)),r=new g(t.strictNullChecks).process(r),r}function x(n,e={}){let t={...S,...e},r=c(n);r=k(n,r,t);let i=new y({namingStyle:t.namingStyle,prefix:t.typePrefix,suffix:t.typeSuffix,customNameMap:t.typeNameMap}),s=new m(i).collect(r,t.rootName);return new d(t,i).generateOutput(s,t.rootName)}function M(n,e={}){let t=JSON.parse(n);return x(t,e)}var V={generate:x,generateFromString:M};export{d as CodeFormatter,g as NullHandler,h as OptionalHandler,m as TypeCollector,y as TypeNamer,k as applyEnhancements,j as createUnion,V as default,x as generate,M as generateFromString,v as inferArrayType,D as inferObjectType,c as inferType,N as isStructurallyEqual,O as mergeObjects,T as mergeTypes};
|
|
1
|
+
var S={rootName:"Root",outputStyle:"interface",namingStyle:"PascalCase",sortProperties:"alpha",addExport:!0,markOptional:!0,indentSize:2,lineEnding:`
|
|
2
|
+
`,typeNameMap:{},typePrefix:"",typeSuffix:""};function u(r){return{kind:"primitive",type:r}}function A(){return{kind:"null"}}function P(){return{kind:"undefined"}}function w(r){return{kind:"array",elementType:r}}function k(r=[]){return{kind:"object",properties:r}}function b(r){let e=[],t=new Set;for(let n of r)if(n.kind==="union")for(let i of n.types){let o=p(i);t.has(o)||(t.add(o),e.push(i))}else{let i=p(n);t.has(i)||(t.add(i),e.push(n))}return e.length===1?e[0]:{kind:"union",types:e}}function p(r,e=new Set){if(e.has(r))return"circular";switch(r.kind){case"primitive":return`primitive:${r.type}`;case"null":return"null";case"undefined":return"undefined";case"literal":return`literal:${typeof r.value}:${String(r.value)}`;case"array":return`array:${p(r.elementType,e)}`;case"object":{e.add(r);let t=`object:${r.properties.map(n=>`${n.name}:${p(n.type,e)}:${n.optional}`).sort().join(",")}`;return e.delete(r),t}case"union":return`union:${r.types.map(t=>p(t,e)).sort().join("|")}`;case"generic":return`generic:${r.name}:${r.typeArgs.map(t=>p(t,e)).join(",")}`;default:return"unknown"}}function d(r,e){return p(r)===p(e)?r:r.kind==="object"&&e.kind==="object"?j(r,e):r.kind==="array"&&e.kind==="array"?w(d(r.elementType,e.elementType)):b([r,e])}function j(r,e){let t=new Map;for(let n of r.properties)t.set(n.name,{...n});for(let n of e.properties){let i=t.get(n.name);i?(i.type=d(i.type,n.type),i.optional=i.optional||n.optional):t.set(n.name,{...n,optional:!0})}for(let[n,i]of t)e.properties.some(s=>s.name===n)||(i.optional=!0);return k(Array.from(t.values()))}function R(r){if(r instanceof Date||r instanceof RegExp||typeof Buffer!="undefined"&&Buffer.isBuffer(r))return u("string");let e=Object.prototype.toString.call(r);return e==="[object Date]"||e==="[object RegExp]"?u("string"):e==="[object Map]"||e==="[object Set]"||e==="[object WeakMap]"||e==="[object WeakSet]"?u("unknown"):null}function l(r,e=new WeakSet,t=new WeakMap){if(r===null)return A();if(r===void 0)return P();if(typeof r=="function")return u("Function");if(typeof r=="string")return u("string");if(typeof r=="number")return u("number");if(typeof r=="boolean")return u("boolean");if(Array.isArray(r))return O(r,e,t);if(typeof r=="object"&&r!==null){let n=R(r);if(n)return n;let i=r;if(e.has(i)){let a=t.get(i);if(a)return a}e.add(i);let o=k([]);t.set(i,o);let s=[];for(let[a,f]of Object.entries(i))s.push({name:a,type:l(f,e,t),optional:!1});return o.properties=s,e.delete(i),o}return u("unknown")}function O(r,e,t=new WeakMap){if(r.length===0)return{kind:"array",elementType:{kind:"primitive",type:"unknown"}};let n=r.map(o=>l(o,e,t)),i=n[0];for(let o=1;o<n.length;o++)i=d(i,n[o]);return{kind:"array",elementType:i}}function C(r,e=new WeakSet,t=new WeakMap){return l(r,e,t)}function h(r,e){return r===e?!0:p(r)===p(e)}function c(r,e=new WeakMap){if(e.has(r))return e.get(r);let t;switch(r.kind){case"primitive":return t={kind:"primitive",type:r.type},e.set(r,t),t;case"null":return t={kind:"null"},e.set(r,t),t;case"undefined":return t={kind:"undefined"},e.set(r,t),t;case"literal":return t={kind:"literal",value:r.value},e.set(r,t),t;case"array":return t={kind:"array",elementType:{}},e.set(r,t),t.elementType=c(r.elementType,e),t;case"object":return t={kind:"object",properties:[],isRecord:r.isRecord,valueType:r.valueType},e.set(r,t),t.properties=r.properties.map(n=>({name:n.name,optional:n.optional,type:c(n.type,e)})),r.valueType&&(t.valueType=c(r.valueType,e)),t;case"union":return t={kind:"union",types:[]},e.set(r,t),t.types=r.types.map(n=>c(n,e)),t;case"generic":return t={kind:"generic",name:r.name,typeArgs:[]},e.set(r,t),t.typeArgs=r.typeArgs.map(n=>c(n,e)),t;default:return t={kind:"primitive",type:"unknown"},e.set(r,t),t}}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 n=this.buildPathKey(t);if(this.customNameMap[n])return this.applyAffixes(this.customNameMap[n]);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 n=this.toPascalCase(t.fieldName);return t.parentName?`${t.parentName}${n}`:n}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 n=`${e}${t+1}`;return this.nameCounter.set(e,t+1),n}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 p(e)}getSimpleTypeKey(e){return p(e)}toPascalCase(e){return e?e.replace(/[-_\s]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim().split(" ").filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.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()}},m=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 n=this.collected.find(o=>o.name===t),i=this.collected.filter(o=>o.name!==t);return n?[n,...i]:this.collected}collectRecursive(e,t){let n=this.getStructKey(e);if(e.kind==="object"){let i=this.namer.nameType(e,t);if(i&&!this.seenStructs.has(n)){this.seenStructs.add(n),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 p(e)}};var T=class{constructor(e,t){this.allNamedTypes=[];this.options=e,this.namer=t}get eol(){return this.options.lineEnding}joinLines(e){return e.join(this.eol)}findTypeName(e){if(e.kind!=="object")return null;for(let t of this.allNamedTypes)if(t.type===e||h(t.type,e))return t.name;return null}formatTypeDef(e){let{name:t,type:n}=e,i=this.options.addExport?"export ":"";return this.formatObjectType(t,n,i)}formatObjectType(e,t,n){let i=" ".repeat(this.options.indentSize),o=this.sortProperties(t.properties),s=[];this.options.outputStyle==="interface"?s.push(`${n}interface ${e} {`):s.push(`${n}type ${e} = {`);for(let a of o){let f=this.formatPropertyName(a.name),v=a.optional?"?":"",$=this.formatType(a.type);s.push(`${i}${f}${v}: ${$};`)}return this.options.outputStyle==="interface"?s.push("}"):s.push("};"),this.joinLines(s)}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),n=this.sortProperties(e.properties);if(n.length===0)return"{}";let i=["{"];for(let o of n){let s=this.formatPropertyName(o.name),a=o.optional?"?":"",f=this.formatType(o.type);i.push(`${t}${s}${a}: ${f};`)}return i.push("}"),this.joinLines(i)}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,n)=>t.name.localeCompare(n.name))}formatAll(e){return this.allNamedTypes=e,e.map(t=>this.formatTypeDef(t)).join(`${this.eol}${this.eol}`)}generateOutput(e,t){let n=this.joinLines(["/**"," * Generated by type-flash",` * Root type: ${t}`," */"]),i=this.formatAll(e);return`${n}${this.eol}${this.eol}${i}${this.eol}`}};var g=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 n=t.elementType;if(n.kind==="object"){let i=this.processArrayObjects(e,n);return{...t,elementType:i}}return{...t,elementType:this.processRecursive(e,n)}}if(t.kind==="object"&&e&&typeof e=="object"){if(this.seen.has(t))return t;this.seen.add(t);let n={...t,properties:t.properties.map(i=>i.type===t?{...i}:{...i,type:this.processRecursive(e[i.name],i.type)})};for(let i of n.properties)i.type===t&&(i.type=n);return this.seen.delete(t),n}return t.kind==="union"&&Array.isArray(e)?{...t,types:t.types.map(n=>this.processRecursive(e,n))}:t}processArrayObjects(e,t){if(e.length<=1)return t;let n={},i=e.length;for(let o of e)if(o&&typeof o=="object")for(let s of Object.keys(o))n[s]=(n[s]||0)+1;return{...t,properties:t.properties.map(o=>{let a=(n[o.name]||0)<i;return{...o,optional:a}})}}};function N(r,e,t){return t.markOptional?new g(t.markOptional).process(r,e):e}function x(r,e={}){let t={...S,...e},n=l(r);n=N(r,n,t);let i=new y({namingStyle:t.namingStyle,prefix:t.typePrefix,suffix:t.typeSuffix,customNameMap:t.typeNameMap}),s=new m(i).collect(n,t.rootName);return new T(t,i).generateOutput(s,t.rootName)}function D(r,e={}){let t=JSON.parse(r);return x(t,e)}var Z={generate:x,generateFromString:D};export{T as CodeFormatter,g as OptionalHandler,m as TypeCollector,y as TypeNamer,N as applyEnhancements,b as createUnion,Z as default,x as generate,D as generateFromString,O as inferArrayType,C as inferObjectType,l as inferType,h as isStructurallyEqual,j as mergeObjects,d as mergeTypes};
|