UNPKG

brick-codegen

Version:

Better React Native native module development

803 lines (802 loc) 21.6 kB
//#region src/scanner.d.ts interface ScannedModule { name: string; path: string; specPath: string; packageJsonPath: string; version: string; hasIosImplementation: boolean; hasAndroidImplementation: boolean; brickConfig?: any; androidPackage?: string; androidModuleName?: string; androidPath?: string; } interface ScanResult { modules: ScannedModule[]; errors: string[]; warnings: string[]; } declare class Scanner { private config; constructor(config: BrickCodegenConfig); /** * Scans package.json dependencies for Brick modules * In library mode: only scans current package for .brick.ts files * In user project mode: scans dependencies for Brick modules */ scanBrickModules(): Promise<ScannedModule[]>; /** * Scans a single module to determine if it's a Brick module */ private scanSingleModule; /** * Checks if a package.json indicates a Brick module */ private isBrickModule; /** * Finds the spec file for a module */ private findSpecFile; /** * Checks if module has iOS implementation */ private hasIosImplementation; /** * Checks if module has Android implementation */ private hasAndroidImplementation; /** * Scans for local Brick modules (for development) */ private scanLocalModules; /** * Validates implementations for a module */ validateImplementations(module: ScannedModule): Promise<string[]>; /** * Validates iOS implementation */ private validateIosImplementation; /** * Validates Android implementation */ private validateAndroidImplementation; /** * Checks if a module should be excluded based on patterns */ private shouldExcludeModule; /** * Gets detailed scan results with validation */ getDetailedScanResults(): Promise<ScanResult>; /** * Scans current library for .brick.ts files (library mode only) */ private scanCurrentLibrary; private log; } //#endregion //#region src/parser.d.ts interface ParsedModule { name: string; moduleName: string; version: string; specPath: string; constants: ModuleConstant[]; methods: ModuleMethod[]; events?: ModuleEvent[]; sourceModule: ScannedModule; interfaceDefinitions: InterfaceDefinition[]; } interface ModuleMethod { name: string; params: MethodParameter[]; returnType: string; isAsync: boolean; isSync: boolean; signature: string; jsDocComment?: string; deprecated?: boolean; } interface MethodParameter { name: string; type: string; optional: boolean; defaultValue?: any; jsDocComment?: string; } interface ModuleConstant { name: string; type: string; value?: any; readonly: boolean; jsDocComment?: string; } interface ModuleEvent { name: string; payload?: string; jsDocComment?: string; } interface InterfaceDefinition { name: string; properties: InterfaceProperty[]; jsDocComment?: string; } interface InterfaceProperty { name: string; type: string; optional: boolean; jsDocComment?: string; } declare class Parser { private config; private checker?; private interfaceDefinitions; private generatedInterfaces; constructor(config: BrickCodegenConfig); /** * Parses a module specification file */ parseModuleSpec(module: ScannedModule): Promise<ParsedModule[]>; /** * Creates TypeScript source file */ private createSourceFile; /** * Extracts module information from source file */ private extractModuleInfo; /** * Visits a TypeScript AST node */ private visitNode; /** * Processes interface declaration */ private processInterface; /** * Processes type alias declaration */ private processTypeAlias; /** * Processes variable statement */ private processVariableStatement; /** * Checks if an interface is a module spec interface */ private isModuleSpecInterface; /** * Extracts module name from interface name * Example: "CalculatorModuleSpec" -> "Calculator" */ private extractModuleNameFromInterface; /** * Checks if a type alias is a module spec type */ private isModuleSpecType; /** * Checks if node has export modifier */ private hasExportModifier; /** * Extracts property from interface/type */ private extractProperty; /** * Extracts method from interface */ private extractMethod; /** * Extracts constants from a type literal */ private extractConstantsFromType; /** * Extracts supported events from array literal */ private extractSupportedEvents; /** * Extracts parameters from method signature */ private extractParameters; /** * Extracts default value from expression */ private extractDefaultValue; /** * Gets type string from type node */ private getTypeString; /** * Generates an interface name for nested object types */ private generateNestedInterfaceName; /** * Extracts nested object type as interface definition */ private extractNestedInterface; /** * Converts TypeScript type to string representation */ private typeToString; /** * Checks if a type is a Promise type */ private isPromiseType; /** * Builds method signature string */ private buildMethodSignature; /** * Extracts JSDoc comment from node */ private extractJSDocComment; /** * Checks if node is marked as deprecated */ private isDeprecated; /** * Infers type from value expression */ private inferTypeFromValue; /** * Extracts literal value from expression */ private extractLiteralValue; /** * Validates parsed module structure */ private validateParsedModule; /** * Validates method name conventions */ private isValidMethodName; /** * Validates event name conventions */ private isValidEventName; /** * Validates naming conventions */ validateNamingConventions(parsed: ParsedModule): string[]; /** * Validates types in the parsed module */ validateTypes(parsed: ParsedModule): Promise<string[]>; /** * Checks if type is valid */ private isValidType; private isCapitalCase; private isCamelCase; private isConstantCase; /** * Extracts interface definition from TypeScript AST */ private extractInterfaceDefinition; private capitalizeFirst; private log; } //#endregion //#region src/main-index.d.ts /** * Brick Codegen - Main Entry Point * Clean architecture with original functionality preserved */ interface GenerationResult { success: boolean; moduleCount: number; errors: string[]; warnings: string[]; generatedFiles: string[]; duration: number; } interface BrickCodegenConfig { projectRoot: string; outputIos?: string; outputAndroid?: string; debug?: boolean; platforms?: string[]; ios?: { projectName: string; }; libraryMode?: boolean; excludeModules?: string[]; dryRun?: boolean; verbose?: boolean; } declare class NewBrickCodegen { private config; private projectInfo; private scanner; private parser; private generator; private libraryGenerator; private platformRegistry; constructor(config: Partial<BrickCodegenConfig> & { projectRoot: string; }); /** * Creates configuration format for internal components */ private createComponentConfig; /** * Main generation method */ generate(): Promise<GenerationResult>; private runCodegen; private moveCodegenResults; private moveIOSCodegenResults; private moveAndroidCodegenResults; private filterBrickModuleFiles; private postProcessHeaderFiles; private validatePlatformSelection; private log; } //#endregion //#region src/platforms/platform-interface.d.ts interface PlatformGenerator { /** * Platform name identifier */ getPlatformName(): string; /** * Check if this generator supports the target platform */ supports(target: string): boolean; /** * Generate bridge code for the platform * @param modules Parsed module specifications * @param scannedModules All scanned brick modules from dependencies */ generateBridge(modules: ParsedModule[], scannedModules?: ScannedModule[]): Promise<string[]>; /** * Check if platform is available in current environment */ isAvailable(): boolean; } type SupportedPlatform = 'ios' | 'android'; //#endregion //#region src/platforms/android-platform.d.ts declare class AndroidPlatformGenerator implements PlatformGenerator { private config; private isNewArch; private currentOutputDir; private scannedModules; constructor(config: BrickCodegenConfig); /** * Detects if New Architecture is enabled by checking gradle.properties */ private isNewArchitecture; getPlatformName(): string; supports(target: string): boolean; /** * Main method - Generates Android bridge files */ generateBridge(modules: ParsedModule[], scannedModules?: ScannedModule[]): Promise<string[]>; isAvailable(): boolean; /** * Generates event support for Kotlin interface */ private generateKotlinEventSupport; /** * Generates Kotlin data classes for complex types and interfaces */ private generateKotlinDataClasses; /** * Generates a single Kotlin data class from TypeScript inline object type * Note: This is a fallback for inline objects. Most types should come from AST-based interfaces. */ private generateKotlinDataClass; /** * Enhanced Kotlin type mapping that recognizes interface types */ private mapTypeScriptToKotlinWithInterfaces; /** * Gets available brick modules from scanned modules * Uses the scanned modules from Scanner instead of re-scanning */ private detectBrickModules; /** * Generate build.gradle */ private generateBuildGradle; private mapTypeScriptToKotlin; /** * Maps TypeScript types to React Native bridge types for Kotlin */ private mapTypeScriptToReactNativeKotlin; private getAllMethods; private getAllEvents; private getAllConstants; /** * Checks if a string matches PascalCase pattern (used for interface names) */ private isPascalCase; private capitalize; private isPrimitiveType; private logGenerated; /** * Generates BrickModuleBase.kt interface */ private generateBrickModuleBase; /** * Generates the main Android bridge file (BrickModule.kt) - like iOS BrickModule.mm */ private generateAndroidBridge; /** * Generates library imports for data types used in BrickModuleImpl */ private generateLibraryImports; /** * Generates Kotlin implementation file (BrickModuleImpl.kt) - like iOS BrickModuleImpl.swift */ private generateKotlinImplementation; /** * Generates a Kotlin method for BrickModule (ReactMethod for Old Arch, override for New Arch) */ private generateKotlinMethod; /** * Generates constants getter for BrickModule (Old Architecture) */ private generateConstantsGetter; /** * Generates constants for New Architecture (getTypedExportedConstants) */ private generateNewArchConstants; /** * Generates supported events array */ private generateSupportedEventsArray; /** * Generates Kotlin implementation method with type conversion */ private generateKotlinImplMethod; /** * Generates constant implementation getter using type-safe casting */ private generateConstantImplGetter; /** * Generates parameter conversions for Kotlin methods with concrete types */ private generateParameterConversions; /** * Generates concrete type name for TypeScript type */ private generateConcreteTypeName; /** * Extracts interface definitions from parsed module AST */ private extractInterfaceDefinitions; /** * Generates Kotlin data class from TypeScript interface definition */ private generateKotlinDataClassFromInterface; /** * Generates the method implementation including conversions */ private generateMethodImplementation; /** * Gets default Kotlin return value */ private getDefaultKotlinReturnValue; /** * Generates Kotlin types for library mode (public API) */ generateLibraryTypes(module: ParsedModule): Promise<string>; /** * Generates Kotlin interface for library mode (public API) */ generateLibraryInterface(module: ParsedModule): Promise<string>; /** * Generates Kotlin data class for library mode */ private generateLibraryKotlinDataClass; /** * Generates Kotlin interface for library mode */ private generateLibraryModuleInterface; } //#endregion //#region src/platforms/ios-platform.d.ts declare class IOSPlatformGenerator implements PlatformGenerator { private config; private scannedModules; constructor(config: BrickCodegenConfig); getPlatformName(): string; supports(target: string): boolean; /** * Main method - Generates iOS bridge files (moved from BridgeGenerator.generateIOSBridge) */ generateBridge(modules: ParsedModule[], scannedModules?: ScannedModule[]): Promise<string[]>; isAvailable(): boolean; /** * Generates the main Objective-C bridge file (BrickModule.mm) */ private generateObjectiveCBridge; /** * Generates New Architecture method implementation */ private generateNewArchMethod; /** * Generates Old Architecture method implementation */ private generateOldArchMethod; /** * Gets the correct React Native Codegen type for complex objects */ private getReactNativeCodegenType; /** * Gets the Objective-C type for Old Architecture (uses NSDictionary for complex objects) */ private getOldArchObjCType; /** * Generates parameter conversion code for complex objects */ private generateParameterConversions; /** * Generates parameter conversion code for Old Architecture (no conversions needed) */ private generateOldArchParameterConversions; /** * Generates call parameters for Swift method calls */ private generateCallParameters; /** * Generates call parameters for Old Architecture Swift method calls */ private generateOldArchCallParameters; /** * Generates Swift implementation file (BrickModuleImpl.swift) */ private generateSwiftImplementation; /** * Generates Swift types for library mode (public API) */ generateLibraryTypes(module: ParsedModule): Promise<string>; /** * Generates Swift protocol for library mode (public API) */ generateLibraryProtocol(module: ParsedModule): Promise<string>; /** * Generates event support section for a module protocol */ private generateEventSupport; /** * Generates event method implementations for protocol extension */ private generateEventExtension; /** * Generates a single protocol method */ /** * Generates Codable structs for complex types using TypeScript AST analysis */ private generateCodableStructs; /** * Generates advanced Codable struct with proper TypeScript AST analysis */ private generateAdvancedCodableStruct; /** * Analyzes TypeScript object type and generates proper Swift types */ private analyzeTypeScriptObject; /** * Parses nested properties more accurately */ private parseNestedProperties; /** * Parses a single property declaration */ private parseProperty; /** * Generates a Swift method implementation */ private generateSwiftMethod; /** * Generates parameter conversions for Swift methods (now empty since we use typed parameters) */ private generateSwiftParameterConversions; /** * Generates the actual Swift method call */ private generateSwiftMethodCall; /** * Wraps the result for return with proper type handling */ private wrapResult; /** * Generates constant getter methods */ private generateConstantGetter; /** * Generates type aliases for interface types from external modules * This helps with New Architecture module resolution issues */ private generateTypeAliases; /** * Generates conversion helper methods */ private generateConversionHelpers; /** * Generates conversion helper for a specific type */ private generateTypeConversionHelper; /** * Generates constants getter for New Architecture */ private generateNewArchConstantsGetter; /** * Generates constants getter for Old Architecture (using NSDictionary) */ private generateOldArchConstantsGetter; /** * Generates supported events array */ private generateSupportedEventsArray; /** * Generates Swift supported events array */ private generateSwiftSupportedEventsArray; /** * Generates BrickModule.podspec for iOS integration with automatic dependencies */ private generatePodspec; /** * Generates podspec dependencies based on discovered Brick modules * Uses the scanned modules from Scanner instead of re-scanning */ private generatePodspecDependencies; private getAllMethods; private getAllEvents; private getAllConstants; private mapTypeScriptToObjC; private mapTypeScriptToSwift; private getDefaultReturnValue; /** * Maps TypeScript types to Swift types for @objc compatibility * Uses [String: Any] for complex types instead of Swift structs */ private mapTypeScriptToSwiftForObjC; private getDefaultSwiftReturnValue; private getDefaultSwiftReturnValueForObjC; private capitalize; /** * Wraps Swift return values for Objective-C compatibility */ private wrapObjCReturnValue; private log; /** * Generates Swift struct from interface definition */ private generateSwiftStruct; /** * Generates Swift struct from interface definition for library packages (with public initializers) */ private generateLibrarySwiftStruct; /** * Enhanced Swift type mapping that recognizes interface types */ private mapTypeScriptToSwiftWithInterfaces; /** * Enhanced protocol method generation with interface type support */ private generateProtocolMethod; /** * Generates Swift protocol for library packages (without interface structs) */ private generateLibraryModuleProtocol; private capitalizeFirst; private logGenerated; } //#endregion //#region src/platforms/platform-registry.d.ts declare class PlatformRegistry { private generators; private scannedModules; constructor(config: BrickCodegenConfig); /** * Set scanned modules to be passed to platform generators */ setScannedModules(modules: ScannedModule[]): void; /** * Get platform generator by name */ getGenerator(platform: SupportedPlatform): PlatformGenerator | undefined; /** * Get platform generator by name (alias for getGenerator) */ getPlatform(platform: SupportedPlatform): PlatformGenerator | undefined; /** * Get all available platforms */ getAvailablePlatforms(): SupportedPlatform[]; /** * Generate bridge code for specific platform */ generateForPlatform(platform: SupportedPlatform, modules: ParsedModule[]): Promise<string[]>; /** * Generate bridge code for all available platforms */ generateForAllPlatforms(modules: ParsedModule[]): Promise<{ [platform: string]: string[]; }>; /** * Check if a platform is supported */ supports(platform: string): boolean; /** * Check if a platform is available */ isPlatformAvailable(platform: string): boolean; /** * Get platform generator by name */ getPlatformGenerator(platform: string): PlatformGenerator | undefined; } //#endregion //#region src/generator.d.ts declare class Generator { private config; private platformRegistry?; constructor(config: BrickCodegenConfig, platformRegistry?: PlatformRegistry); /** * Main generation method - Generates .brick folder structure with package.json and NativeBrickModule.ts */ generateTypeScriptFiles(modules: ParsedModule[]): Promise<string[]>; /** * Generates package.json for .brick folder */ private generatePackageJson; /** * Generates TurboModule specification for React Native Codegen * This is the only file generated by brick-codegen */ private generateTurboModuleSpec; /** * Gets all methods from all modules */ private getAllMethods; /** * Gets all constants from all modules */ private getAllConstants; /** * Generates bridge code for all platforms using DI pattern */ generateBridgeCode(modules: ParsedModule[]): Promise<{ ios: string[]; android: string[]; allFiles: string[]; }>; /** * Main unified generation method - Generates all files including TypeScript specs and bridge code */ generateAll(modules: ParsedModule[]): Promise<string[]>; private log; private logGenerated; } //#endregion //#region src/utils/type-mapping.d.ts /** * Type mapping utilities for different platforms * Consolidates type conversion logic from signature-mapper.ts */ interface TypeMapping { typescript: string; swift: string; objectiveC: string; java: string; kotlin: string; } declare const TYPE_MAPPINGS: Record<string, TypeMapping>; type Platform = 'swift' | 'objectiveC' | 'java' | 'kotlin'; declare function mapTypeScriptType(tsType: string, platform: Platform): string; declare function generateMethodSignature(methodName: string, params: Array<{ name: string; type: string; }>, returnType: string, platform: Platform, isAsync?: boolean): string; //#endregion export { AndroidPlatformGenerator, NewBrickCodegen as BrickCodegen, type BrickCodegenConfig, Generator, IOSPlatformGenerator, Parser, Platform, PlatformGenerator, PlatformRegistry, Scanner, SupportedPlatform, TYPE_MAPPINGS, TypeMapping, generateMethodSignature, mapTypeScriptType }; //# sourceMappingURL=index.d.ts.map