All files / src/commands/contract helpers.ts

93.79% Statements 121/129
81.13% Branches 43/53
93.33% Functions 28/30
93.65% Lines 118/126

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284405854x 1x 1x 1x     1x 16x 16x   16x 578x 1895x   1895x 1937x   1937x 150791x       1937x 170x     1767x   1767x   1767x 1614x       1767x 732x     1035x   1035x 925x           16x 3x 3x 3x 45x 45x 45x 40x           16x 3x 29x 29x 29x 1x         16x 1658x   925x 98x       1x 91541x     1x 2137x 757x     1380x   1380x 114028x 387646x       1380x 761x     619x 30255x     619x 318x 370x 177x         619x     1x 1841x 27x     1814x     1x         16x 16x 16x                 16x 16x 16x   16x     16x             16x     1x 64x             380x                       1x                               1x           319407x       3909x 398x   3511x     3909x     1x 1x 543397x 1080681x 44204x   44204x       499193x     1x       1x 24637x   24637x 83x     24554x 19x     24535x       24535x       24535x     1x 15586x     1x 629x       629x     1x       498x 498x 343x     343x 343x 77x   266x 266x       2x 834x    
import type {ABI} from '@wharfkit/antelope'
import * as ts from 'typescript'
import {formatClassName} from '../../utils'
import {findAbiType, findAliasFromType, findCoreClass, findCoreType, findVariant} from './finders'
import type {TypeInterfaceDeclaration} from './interfaces'
 
export function getCoreImports(abi: ABI.Def) {
    const coreImports: string[] = []
    const coreTypes: string[] = []
 
    for (const struct of abi.structs) {
        for (const field of struct.fields) {
            const variant = findVariant(field.type, abi)
 
            for (const type of variant?.types || [field.type]) {
                const fieldTypeWithoutDecorator = extractDecorator(type).type
 
                const fieldTypeIsStruct = abi.structs.find(
                    (abiStruct) => abiStruct.name === fieldTypeWithoutDecorator
                )
 
                // We don't need to import any core classes if the field type is a struct
                if (fieldTypeIsStruct) {
                    continue
                }
 
                const {type: abiType} = findAbiType(type, abi)
 
                const coreClass = findCoreClassImport(abiType)
 
                if (coreClass) {
                    coreImports.push(coreClass)
                }
 
                // We don't need to add action types unless the struct is an action param
                if (!structIsUsedInActionParams(struct, abi)) {
                    continue
                }
 
                const coreType = findCoreType(abiType)
 
                if (coreType) {
                    coreTypes.push(coreType)
                }
            }
        }
    }
 
    if (abi.variants.length) {
        coreImports.push('Variant')
        for (const variant of abi.variants) {
            variant.types.forEach((typeString) => {
                const {type: abiType} = findAbiType(typeString, abi)
                const coreClass = findCoreClassImport(abiType)
                if (coreClass) {
                    coreImports.push(coreClass)
                }
            })
        }
    }
 
    if (abi.action_results.length) {
        for (const actionResult of abi.action_results) {
            const {type: abiType} = findAbiType(actionResult.result_type, abi)
            const coreClass = findCoreClassImport(abiType)
            if (coreClass) {
                coreImports.push(coreClass)
            }
        }
    }
 
    return {
        classes: coreImports.filter((value, index, self) => self.indexOf(value) === index),
        types: coreTypes
            .filter((value, index, self) => self.indexOf(value) === index)
            .filter((type) => !coreImports.includes(type)),
    }
}
 
function structIsActionParams(struct: ABI.Struct, abi: ABI.Def) {
    return abi.actions.some((action) => action.type === struct.name)
}
 
function structIsUsedInActionParams(struct: ABI.Struct, abi: ABI.Def) {
    if (structIsActionParams(struct, abi)) {
        return true
    }
 
    const alias = findAliasFromType(struct.name, abi)
 
    const structsUsingStruct = abi.structs.filter((abiStruct) => {
        return abiStruct.fields.some(
            (field) => extractDecorator(field.type).type === (alias || struct.name)
        )
    })
 
    if (structsUsingStruct.length === 0) {
        return false
    }
 
    let isUsedByActionStruct = abi.actions.some((action) =>
        structsUsingStruct.map((s) => s.name).includes(action.type)
    )
 
    if (!isUsedByActionStruct) {
        structsUsingStruct.forEach((structUsingStruct) => {
            if (structIsUsedInActionParams(structUsingStruct, abi)) {
                isUsedByActionStruct = true
            }
        })
    }
 
    return isUsedByActionStruct
}
 
export function findCoreClassImport(type: string) {
    if (type === 'symbol' || type === 'symbol_code') {
        return 'Asset'
    }
 
    return findCoreClass(type)
}
 
export function generateClassDeclaration(
    name: string,
    members: ts.ClassElement[],
    options: {parent?: string; export?: boolean; decorator?: ts.Decorator} = {}
) {
    const heritageClauses: ts.HeritageClause[] = []
    if (options.parent) {
        heritageClauses.push(
            ts.factory.createHeritageClause(ts.SyntaxKind.ExtendsKeyword, [
                ts.factory.createExpressionWithTypeArguments(
                    ts.factory.createIdentifier(options.parent),
                    undefined
                ),
            ])
        )
    }
    const modifiers: ts.ModifierLike[] = []
    if (options.export === true) {
        modifiers.push(ts.factory.createToken(ts.SyntaxKind.ExportKeyword))
    }
    Iif (options.decorator) {
        modifiers.push(options.decorator)
    }
    const classDeclaration = ts.factory.createClassDeclaration(
        modifiers,
        ts.factory.createIdentifier(name),
        undefined, // type parameters
        heritageClauses,
        members
    )
    return classDeclaration
}
 
export function generateImportStatement(classes, path, type = false): ts.ImportDeclaration {
    return ts.factory.createImportDeclaration(
        undefined, // modifiers
        ts.factory.createImportClause(
            type, // isTypeOnly
            undefined, // name
            ts.factory.createNamedImports(
                classes.map((className) =>
                    ts.factory.createImportSpecifier(
                        false,
                        undefined, // propertyName
                        ts.factory.createIdentifier(className) // name
                    )
                )
            ) // namedBindings
        ),
        ts.factory.createStringLiteral(path) // moduleSpecifier
    )
}
 
export function generateInterface(
    interfaceName: string,
    isExport = false,
    members: ts.TypeElement[]
): ts.InterfaceDeclaration {
    const modifiers = isExport ? [ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)] : []
 
    return ts.factory.createInterfaceDeclaration(
        modifiers,
        interfaceName,
        undefined, // typeParameters
        [], // heritageClauses
        members
    )
}
 
export function formatInternalType(
    typeString: string,
    namespace = '',
    abi: ABI.Def,
    decorator = ''
): string {
    const structNames = [...abi.structs, ...abi.variants].map((struct) => struct.name.toLowerCase())
 
    let type
 
    if (structNames.includes(typeString.toLowerCase())) {
        type = `${namespace}${formatClassName(typeString)}`
    } else {
        type = findCoreClass(typeString) || capitalize(typeString)
    }
 
    return `${type}${decorator}`
}
 
const decorators = ['?', '[]']
export function extractDecorator(type: string): {type: string; decorator?: string} {
    for (const decorator of decorators) {
        if (type.includes(decorator)) {
            type = type.replace(decorator, '')
 
            return {type, decorator}
        }
    }
 
    return {type}
}
 
export function cleanupType(type: string): string {
    return extractDecorator(parseType(trim(type))).type
}
 
export function parseType(type: string): string {
    type = type.replace('$', '')
 
    if (type === 'String') {
        return 'string'
    }
 
    if (type === 'String[]') {
        return 'string[]'
    }
 
    Iif (type === 'Boolean') {
        return 'boolean'
    }
 
    Iif (type === 'Boolean[]') {
        return 'boolean[]'
    }
 
    return type
}
 
export function trim(string: string) {
    return string.replace(/\s/g, '')
}
 
export function capitalize(string) {
    Iif (typeof string !== 'string' || string.length === 0) {
        return ''
    }
 
    return string.charAt(0).toUpperCase() + string.slice(1)
}
 
export function removeDuplicateInterfaces(
    interfaces: TypeInterfaceDeclaration[]
): TypeInterfaceDeclaration[] {
    // Reverted to original logic: Keep the first encountered interface/alias by name
    const seen: string[] = []
    return interfaces.filter((declaration) => {
        Iif (!declaration.name || !ts.isIdentifier(declaration.name)) {
            return true // Keep declarations without a simple name (or handle differently if needed)
        }
        const name = String(declaration.name.escapedText)
        if (seen.includes(name)) {
            return false // Discard if name already seen
        }
        seen.push(name) // Mark name as seen
        return true // Keep if name is new
    })
}
 
export function removeCommas(interfaceName: string): string {
    return interfaceName.replace(/\./g, '')
}