diff --git a/packages/typegen/src/util/imports.ts b/packages/typegen/src/util/imports.ts index 3b9b059a5c..839853e173 100644 --- a/packages/typegen/src/util/imports.ts +++ b/packages/typegen/src/util/imports.ts @@ -33,6 +33,43 @@ export interface TypeImports { typeToModule: Record; } +// returns the top-level types in the alternatives list, taking into account nested [], <> and () items +// E.g. for the string '[a, d | e]' we return the array ['a', 'd', 'e'] +function splitAlternatives (type: string): string[] { + const alternatives = []; + let beginOfAlternative = 1; + let level = 0; + + // we assume that the string starts with '[' + for (let i = 1; i < type.length; i++) { + if (level === 0) { + switch (type[i]) { + case ']': + case ',': + case '|': + alternatives.push(type.substring(beginOfAlternative, i).trim()); + beginOfAlternative = i + 1; + break; + } + } + + switch (type[i]) { + case '[': + case '(': + case '<': + level++; + break; + case ']': + case ')': + case '>': + level--; + break; + } + } + + return alternatives; +} + // Maps the types as found to the source location. This is used to generate the // imports in the output file, dep-duped and sorted /** @internal */ @@ -54,10 +91,13 @@ export function setImports (allDefs: Record, imports: TypeI genericTypes[type] = true; } else if ((primitiveClasses as Record)[type]) { primitiveTypes[type] = true; - } else if (type.includes('<') || type.includes('(') || (type.includes('[') && !type.includes('|'))) { + } else if (type.startsWith('[') && type.includes('|')) { + const splitTypes = splitAlternatives(type); + + setImports(allDefs, imports, splitTypes); + } else if (type.includes('<') || type.includes('(') || type.includes('[')) { // If the type is a bit special (tuple, fixed u8, nested type...), then we - // need to parse it with `getTypeDef`. We skip the case where type ~ [a | b | c ... , ... , ... w | y | z ] - // since that represents a tuple's similar types, which are covered in the next block + // need to parse it with `getTypeDef`. const typeDef = getTypeDef(type); setImports(allDefs, imports, [TypeDefInfo[typeDef.info]]); @@ -69,11 +109,6 @@ export function setImports (allDefs: Record, imports: TypeI // typeDef.sub is a TypeDef in this case setImports(allDefs, imports, [typeDef.sub.lookupName || typeDef.sub.type]); } - } else if (type.includes('[') && type.includes('|')) { - // We split the types (we already dod the check above, so safe-path should not be caught) - const splitTypes = (/\[\s?(.+?)\s?\]/.exec(type) || ['', ''])[1].split(/\s?\|\s?/); - - setImports(allDefs, imports, splitTypes); } else { // find this module inside the exports from the rest const [moduleName] = Object.entries(allDefs).find(([, { types }]): boolean =>