Skip to content

Commit d2b839b

Browse files
committed
chore: wip
1 parent c00745b commit d2b839b

File tree

1 file changed

+85
-77
lines changed

1 file changed

+85
-77
lines changed

src/extract.ts

Lines changed: 85 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ export async function extract(filePath: string): Promise<string> {
1111
}
1212

1313
export function generateDtsTypes(sourceCode: string): string {
14+
console.log('Starting generateDtsTypes')
1415
const lines = sourceCode.split('\n')
1516
const dtsLines: string[] = []
1617
const imports: string[] = []
@@ -23,37 +24,46 @@ export function generateDtsTypes(sourceCode: string): string {
2324

2425
for (let i = 0; i < lines.length; i++) {
2526
const line = lines[i]
27+
console.log(`Processing line ${i + 1}: ${line}`)
2628

2729
// Handle comments
2830
if (line.trim().startsWith('/**') || line.trim().startsWith('*') || line.trim().startsWith('*/')) {
2931
if (line.trim().startsWith('/**'))
3032
lastCommentBlock = ''
3133
lastCommentBlock += `${line}\n`
34+
console.log('Comment line added to lastCommentBlock')
3235
continue
3336
}
3437

3538
if (line.trim().startsWith('import')) {
36-
imports.push(line)
39+
const processedImport = processImport(line)
40+
imports.push(processedImport)
41+
console.log(`Processed import: ${processedImport}`)
3742
continue
3843
}
3944

4045
if (line.trim().startsWith('export') && (line.includes('{') || line.includes('*') || line.includes('from'))) {
4146
exports.push(line)
47+
console.log(`Export line added: ${line}`)
4248
continue
4349
}
4450

4551
if (isMultiLineDeclaration || line.trim().startsWith('export')) {
4652
currentDeclaration += `${line}\n`
4753
bracketCount += (line.match(/\{/g) || []).length - (line.match(/\}/g) || []).length
54+
console.log(`Current declaration: ${currentDeclaration.trim()}, Bracket count: ${bracketCount}`)
4855

4956
if (bracketCount === 0 || (i === lines.length - 1)) {
5057
if (lastCommentBlock) {
5158
dtsLines.push(lastCommentBlock.trimEnd())
59+
console.log(`Comment block added to dtsLines: ${lastCommentBlock.trimEnd()}`)
5260
lastCommentBlock = ''
5361
}
5462
const processed = processDeclaration(currentDeclaration.trim())
55-
if (processed)
63+
if (processed) {
5664
dtsLines.push(processed)
65+
console.log(`Processed declaration added to dtsLines: ${processed}`)
66+
}
5767
isMultiLineDeclaration = false
5868
currentDeclaration = ''
5969
bracketCount = 0
@@ -73,121 +83,119 @@ export function generateDtsTypes(sourceCode: string): string {
7383
...exports,
7484
].filter(Boolean).join('\n'))
7585

86+
console.log('Final result:', result)
7687
return result
7788
}
7889

79-
function processDeclaration(declaration: string): string {
80-
// Remove comments
81-
const declWithoutComments = declaration.replace(/\/\/.*$/gm, '').trim()
82-
const trimmed = declWithoutComments
83-
84-
if (trimmed.startsWith('export const')) {
85-
return processConstDeclaration(trimmed)
90+
function processImport(importLine: string): string {
91+
console.log(`Processing import: ${importLine}`)
92+
if (importLine.includes('type')) {
93+
const processed = importLine.replace('import', 'import type').replace('type type', 'type')
94+
console.log(`Processed import: ${processed}`)
95+
return processed
8696
}
87-
else if (trimmed.startsWith('export interface')) {
88-
return processInterfaceDeclaration(trimmed)
97+
return importLine
98+
}
99+
100+
function processDeclaration(declaration: string): string {
101+
console.log(`Processing declaration: ${declaration}`)
102+
if (declaration.startsWith('export const')) {
103+
return processConstDeclaration(declaration)
89104
}
90-
else if (trimmed.startsWith('export type')) {
91-
return processTypeDeclaration(trimmed)
105+
else if (declaration.startsWith('export interface')) {
106+
return processInterfaceDeclaration(declaration)
92107
}
93-
else if (trimmed.startsWith('export function') || trimmed.startsWith('export async function')) {
94-
return processFunctionDeclaration(trimmed)
108+
else if (declaration.startsWith('export type')) {
109+
return processTypeDeclaration(declaration)
95110
}
96-
else if (trimmed.startsWith('export default')) {
97-
return `${trimmed};`
111+
else if (declaration.startsWith('export function') || declaration.startsWith('export async function')) {
112+
return processFunctionDeclaration(declaration)
98113
}
99-
else if (trimmed.startsWith('export')) {
100-
return trimmed.endsWith(';') ? trimmed : `${trimmed};`
114+
else if (declaration.startsWith('export default')) {
115+
return `${declaration};`
101116
}
102-
103-
return ''
117+
console.log(`Declaration not processed: ${declaration}`)
118+
return declaration
104119
}
105120

106121
function processConstDeclaration(declaration: string): string {
122+
console.log(`Processing const declaration: ${declaration}`)
107123
const equalIndex = declaration.indexOf('=')
108124
if (equalIndex === -1)
109-
return declaration // No value assigned
125+
return declaration
110126

111127
const name = declaration.slice(0, equalIndex).trim().replace('export const', '').trim()
112128
const value = declaration.slice(equalIndex + 1).trim().replace(/;$/, '')
113129

114-
// Handle object literals
115130
if (value.startsWith('{')) {
116131
const objectType = parseObjectLiteral(value)
117-
return `export declare const ${name}: ${objectType};`
132+
const result = `export declare const ${name}: ${objectType};`
133+
console.log(`Processed const declaration: ${result}`)
134+
return result
118135
}
119136
else {
120-
const valueType = preserveValueType(value)
121-
return `export declare const ${name}: ${valueType};`
137+
const valueType = inferValueType(value)
138+
const result = `export declare const ${name}: ${valueType};`
139+
console.log(`Processed const declaration: ${result}`)
140+
return result
122141
}
123142
}
124143

125144
function processInterfaceDeclaration(declaration: string): string {
126-
const lines = declaration.split('\n')
127-
const interfaceName = lines[0].split('interface')[1].split('{')[0].trim()
128-
const interfaceBody = lines.slice(1, -1).join('\n')
129-
return `export declare interface ${interfaceName} {\n${interfaceBody}\n}`
145+
console.log(`Processing interface declaration: ${declaration}`)
146+
const result = declaration.replace('export interface', 'export declare interface')
147+
console.log(`Processed interface declaration: ${result}`)
148+
return result
130149
}
131150

132151
function processTypeDeclaration(declaration: string): string {
133-
return declaration.replace('export type', 'export declare type')
152+
console.log(`Processing type declaration: ${declaration}`)
153+
const result = declaration.replace('export type', 'export declare type')
154+
console.log(`Processed type declaration: ${result}`)
155+
return result
134156
}
135157

136158
function processFunctionDeclaration(declaration: string): string {
137-
// Remove the function body
138-
const functionSignature = declaration.split('{')[0].trim()
139-
return `export declare ${functionSignature.replace('export ', '')};`
159+
console.log(`Processing function declaration: ${declaration}`)
160+
const functionBody = declaration.match(/\{[\s\S]*\}/)?.[0] || ''
161+
const result = `export declare ${declaration.replace(functionBody, '').trim()};`
162+
console.log(`Processed function declaration: ${result}`)
163+
return result
140164
}
141165

142166
function parseObjectLiteral(objectLiteral: string): string {
143-
// Remove the opening and closing braces and newlines
144-
const content = objectLiteral.replace(/^\{|\}$/g, '').replace(/\n/g, ' ').trim()
145-
146-
const pairs = content.split(',').map(pair => pair.trim()).filter(Boolean)
147-
148-
const parsedProperties = pairs.map((pair) => {
149-
const [key, ...valueParts] = pair.split(':')
150-
const value = valueParts.join(':').trim()
151-
152-
if (value.startsWith('\'') || value.startsWith('"')) {
153-
// For string literals, keep as is
154-
return ` ${key.trim()}: ${value};`
155-
}
156-
else {
157-
// For other types, use preserveValueType
158-
const preservedValue = preserveValueType(value)
159-
return ` ${key.trim()}: ${preservedValue};`
160-
}
167+
console.log(`Parsing object literal: ${objectLiteral}`)
168+
const content = objectLiteral.replace(/^\{|\}$/g, '').split(',').map(pair => pair.trim())
169+
const parsedProperties = content.map((pair) => {
170+
const [key, value] = pair.split(':').map(p => p.trim())
171+
return ` ${key}: ${inferValueType(value)};`
161172
})
162-
163-
return `{\n${parsedProperties.join('\n')}\n}`
173+
const result = `{\n${parsedProperties.join('\n')}\n}`
174+
console.log(`Parsed object literal: ${result}`)
175+
return result
164176
}
165177

166-
function preserveValueType(value: string): string {
167-
value = value.trim()
168-
if (value === 'true' || value === 'false') {
169-
return 'boolean' // Use boolean type for true and false
170-
}
171-
else if (!Number.isNaN(Number(value))) {
172-
return 'number' // Use number type for numeric values
173-
}
174-
else if (value.startsWith('[') && value.endsWith(']')) {
175-
return 'any[]' // Generic array type
176-
}
177-
else if ((value.startsWith('\'') && value.endsWith('\'')) || (value.startsWith('"') && value.endsWith('"'))) {
178-
return 'string' // Use string type for string literals
179-
}
180-
else {
181-
return 'any' // Default to any for other cases
182-
}
178+
function inferValueType(value: string): string {
179+
console.log(`Inferring value type for: ${value}`)
180+
if (value === 'true' || value === 'false')
181+
return value
182+
if (!Number.isNaN(Number(value)))
183+
return value
184+
if (value.startsWith('\'') || value.startsWith('"'))
185+
return value
186+
console.log(`Defaulting to string for: ${value}`)
187+
return 'string' // Default to string for other cases
183188
}
184189

185190
function cleanOutput(output: string): string {
186-
return output
187-
.replace(/\{\s*\}/g, '{}') // Replace empty objects with {}
188-
.replace(/\s*;\s*(?=\}|$)/g, ';') // Clean up semicolons before closing braces or end of string
189-
.replace(/\n+/g, '\n') // Remove multiple consecutive newlines
190-
.replace(/;\n\}/g, ';\n }') // Add indentation to closing brace of object literals
191-
.replace(/\{;/g, '{') // Remove unnecessary semicolons after opening braces
191+
console.log('Cleaning output')
192+
const result = output
193+
.replace(/\{\s*\}/g, '{}')
194+
.replace(/\s*;\s*(?=\}|$)/g, ';')
195+
.replace(/\n+/g, '\n')
196+
.replace(/;\n\}/g, ';\n }')
197+
.replace(/\{;/g, '{')
192198
.trim()
199+
console.log('Cleaned output:', result)
200+
return result
193201
}

0 commit comments

Comments
 (0)