|
| 1 | +import {stripIndent} from 'common-tags' |
| 2 | +import camelCase from 'lodash.camelcase' |
| 3 | + |
| 4 | +import {ZodToPythonParameterClassMapper} from '../language-mappers/zod-to-python-parameter-class-mapper.js' |
| 5 | +import {ZodToTypescriptReturnValueMapper} from '../language-mappers/zod-to-typescript-return-value-mapper.js' |
| 6 | +import {PythonTyping} from '../types.js' |
| 7 | +import {BaseGenerator} from './base-generator.js' |
| 8 | + |
| 9 | +export class PythonGenerator extends BaseGenerator { |
| 10 | + private _typings = new Set<PythonTyping>() |
| 11 | + |
| 12 | + private DATACLASS_IMPORT = 'from dataclasses import dataclass' |
| 13 | + private MUSTACHE_IMPORT = 'import pystache' |
| 14 | + private PYDANTIC_IMPORT = 'from pydantic import BaseModel' |
| 15 | + |
| 16 | + get filename(): string { |
| 17 | + return 'prefab.py' |
| 18 | + } |
| 19 | + |
| 20 | + generate(): string { |
| 21 | + // Need to genereate these before referencing _typings to ensure all required types are known |
| 22 | + const parameterClassTemplates = this.generateParameterClasses() |
| 23 | + const typings = this._typings.size > 0 ? [...this._typings].sort().join(', ') : null |
| 24 | + const accessorMethods = this.generateAccessorMethods() |
| 25 | + |
| 26 | + const additionalDependencies = new Set<string>() |
| 27 | + |
| 28 | + if (parameterClassTemplates.length > 0) { |
| 29 | + additionalDependencies.add(this.DATACLASS_IMPORT) |
| 30 | + } |
| 31 | + |
| 32 | + if (accessorMethods.length > 0) { |
| 33 | + additionalDependencies.add(this.PYDANTIC_IMPORT) |
| 34 | + } |
| 35 | + |
| 36 | + if (this.configurations().some((c) => c.hasFunction)) { |
| 37 | + additionalDependencies.add(this.MUSTACHE_IMPORT) |
| 38 | + } |
| 39 | + |
| 40 | + return stripIndent` |
| 41 | + # AUTOGENERATED by prefab-cli's 'gen' command |
| 42 | + import prefab_cloud_python |
| 43 | + from prefab_cloud_python import ContextDictOrContext |
| 44 | +
|
| 45 | + ${[...additionalDependencies].join('\n ') || '# No additional dependencies required'} |
| 46 | +
|
| 47 | + # Optional - need to make this dynamic |
| 48 | + from datetime import timedelta # for Durations |
| 49 | +
|
| 50 | + ${typings ? `from typing import ${typings}` : '# No additional typings required'} |
| 51 | +
|
| 52 | + class PrefabTypedClient: |
| 53 | + """Client for accessing Prefab configuration with type-safe methods""" |
| 54 | + def __init__(self, client=None, use_global_client=False): |
| 55 | + """ |
| 56 | + Initialize the typed client. |
| 57 | +
|
| 58 | + Args: |
| 59 | + client: A Prefab client instance. If not provided and use_global_client is False, |
| 60 | + uses the global client at initialization time. |
| 61 | + use_global_client: If True, dynamically calls prefab_cloud_python.get_client() for each request |
| 62 | + instead of storing a reference. Useful in long-running applications where |
| 63 | + the client might be reset or reconfigured. |
| 64 | + """ |
| 65 | + self._prefab = prefab_cloud_python |
| 66 | + self._use_global_client = use_global_client |
| 67 | + self._client = None if use_global_client else (client or prefab_cloud_python.get_client()) |
| 68 | +
|
| 69 | + @property |
| 70 | + def client(self): |
| 71 | + """ |
| 72 | + Returns the client to use for the current request. |
| 73 | +
|
| 74 | + If use_global_client is True, dynamically retrieves the current global client. |
| 75 | + Otherwise, returns the stored client instance. |
| 76 | + """ |
| 77 | + if self._use_global_client: |
| 78 | + return self._prefab.get_client() |
| 79 | + return self._client |
| 80 | +
|
| 81 | + ${parameterClassTemplates.join('\n\n ') || '# No parameter classes generated'} |
| 82 | +
|
| 83 | + ${accessorMethods.join('\n\n ') || '# No methods generated'} |
| 84 | + ` |
| 85 | + } |
| 86 | + |
| 87 | + private generateAccessorMethods(): string[] { |
| 88 | + const uniqueMethods: Record<string, string> = {} |
| 89 | + const schemaTypes = this.configurations().map((config) => { |
| 90 | + let methodName = camelCase(config.key) |
| 91 | + |
| 92 | + // If the method name starts with a digit, prefix it with an underscore to ensure method name is valid |
| 93 | + if (/^\d/.test(methodName)) { |
| 94 | + methodName = `_${methodName}` |
| 95 | + } |
| 96 | + |
| 97 | + if (uniqueMethods[methodName]) { |
| 98 | + throw new Error( |
| 99 | + `Method '${methodName}' is already registered. Prefab key ${config.key} conflicts with '${uniqueMethods[methodName]}'!`, |
| 100 | + ) |
| 101 | + } |
| 102 | + |
| 103 | + uniqueMethods[methodName] = config.key |
| 104 | + |
| 105 | + if (config.configType === 'FEATURE_FLAG') { |
| 106 | + return stripIndent` |
| 107 | + get ${methodName}(): boolean { |
| 108 | + return this.prefab.isEnabled('${config.key}') |
| 109 | + } |
| 110 | + ` |
| 111 | + } |
| 112 | + |
| 113 | + if (config.hasFunction) { |
| 114 | + const returnValue = new ZodToTypescriptReturnValueMapper().resolveType(config.schema) |
| 115 | + |
| 116 | + return stripIndent` |
| 117 | + ${methodName}(): PrefabTypeGeneration.ReactHookConfigurationAccessor['${config.key}'] { |
| 118 | + const raw = this.get('${config.key}') |
| 119 | + return ${returnValue} |
| 120 | + } |
| 121 | + ` |
| 122 | + } |
| 123 | + |
| 124 | + return stripIndent` |
| 125 | + get ${methodName}(): PrefabTypeGeneration.ReactHookConfigurationAccessor['${config.key}'] { |
| 126 | + return this.get('${config.key}') |
| 127 | + } |
| 128 | + ` |
| 129 | + }) |
| 130 | + |
| 131 | + return schemaTypes |
| 132 | + } |
| 133 | + |
| 134 | + private generateParameterClasses(): string[] { |
| 135 | + const uniqueClasses: Record<string, string> = {} |
| 136 | + const schemaTypes = this.configurations().map((config) => { |
| 137 | + const mapper = new ZodToPythonParameterClassMapper({fieldName: config.key}) |
| 138 | + const result = mapper.renderClass(config.schema) |
| 139 | + |
| 140 | + const className = ZodToPythonParameterClassMapper.parameterClassName(config.key) |
| 141 | + |
| 142 | + if (uniqueClasses[className]) { |
| 143 | + throw new Error( |
| 144 | + `Class '${className}' is already registered. Prefab key ${config.key} conflicts with '${uniqueClasses[className]}'!`, |
| 145 | + ) |
| 146 | + } |
| 147 | + |
| 148 | + uniqueClasses[className] = config.key |
| 149 | + |
| 150 | + if (mapper.hasAny) { |
| 151 | + this._typings.add(PythonTyping.Any) |
| 152 | + } |
| 153 | + if (mapper.hasDict) { |
| 154 | + this._typings.add(PythonTyping.Dict) |
| 155 | + } |
| 156 | + if (mapper.hasList) { |
| 157 | + this._typings.add(PythonTyping.List) |
| 158 | + } |
| 159 | + if (mapper.hasOptional) { |
| 160 | + this._typings.add(PythonTyping.Optional) |
| 161 | + } |
| 162 | + if (mapper.hasTuple) { |
| 163 | + this._typings.add(PythonTyping.Tuple) |
| 164 | + } |
| 165 | + if (mapper.hasUnion) { |
| 166 | + this._typings.add(PythonTyping.Union) |
| 167 | + } |
| 168 | + |
| 169 | + return result |
| 170 | + }) |
| 171 | + |
| 172 | + return schemaTypes |
| 173 | + } |
| 174 | +} |
0 commit comments