-
Notifications
You must be signed in to change notification settings - Fork 0
feat: implement new typescript code generators #149
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
mjfaga
merged 1 commit into
typesafe-improvements
from
mfaga-remove-react-zod-dependency
Jun 17, 2025
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| import {z} from 'zod' | ||
|
|
||
| import {ZodToTypescriptMapper} from '../language-mappers/zod-to-typescript-mapper.js' | ||
| import {SchemaExtractor} from '../schema-extractor.js' | ||
| import {BaseGenerator, BaseGeneratorArgs} from './base-generator.js' | ||
|
|
||
| export abstract class BaseTypescriptGenerator extends BaseGenerator { | ||
| protected MUSTACHE_IMPORT = "import Mustache from 'mustache'" | ||
| private schemaExtractor: SchemaExtractor | ||
|
|
||
| constructor({configFile, log}: BaseGeneratorArgs) { | ||
| super({configFile, log}) | ||
| this.schemaExtractor = new SchemaExtractor(log) | ||
| } | ||
|
|
||
| protected configurations() { | ||
| return this.configFile.configs | ||
| .filter((config) => config.configType === 'FEATURE_FLAG' || config.configType === 'CONFIG') | ||
| .filter((config) => config.rows.length > 0) | ||
| .sort((a, b) => a.key.localeCompare(b.key)) | ||
| .map((config) => { | ||
| const schema = this.schemaExtractor.execute({ | ||
| config, | ||
| configFile: this.configFile, | ||
| durationTypeMap: this.durationTypeMap, | ||
| }) | ||
|
|
||
| return { | ||
| configType: config.configType, | ||
| hasFunction: schema && new ZodToTypescriptMapper().resolveType(schema).includes('=>'), | ||
| key: config.key, | ||
| schema, | ||
| sendToClientSdk: config.sendToClientSdk ?? false, | ||
| } | ||
| }) | ||
| } | ||
|
|
||
| protected durationTypeMap(): z.ZodTypeAny { | ||
| return z.number() | ||
| } | ||
|
|
||
| abstract get filename(): string | ||
| abstract generate(): string | ||
| } |
105 changes: 105 additions & 0 deletions
105
src/codegen/code-generators/node-typescript-generator.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| import {stripIndent} from 'common-tags' | ||
| import camelCase from 'lodash.camelcase' | ||
|
|
||
| import {ZodToTypescriptMapper, type ZodToTypescriptMapperTarget} from '../language-mappers/zod-to-typescript-mapper.js' | ||
| import {ZodToTypescriptReturnValueMapper} from '../language-mappers/zod-to-typescript-return-value-mapper.js' | ||
| import {BaseTypescriptGenerator} from './base-typescript-generator.js' | ||
|
|
||
| export class NodeTypeScriptGenerator extends BaseTypescriptGenerator { | ||
| get filename(): string { | ||
| return 'prefab-server.ts' | ||
| } | ||
|
|
||
| generate(): string { | ||
| return stripIndent` | ||
| /* eslint-disable */ | ||
| // AUTOGENERATED by prefab-cli's 'gen' command | ||
| import {Prefab, Contexts} from '@prefab-cloud/prefab-cloud-node' | ||
| ${this.additionalDependencies().join('\n') || '// No additional dependencies required'} | ||
|
|
||
| type ContextObj = Record<string, Record<string, unknown>> | ||
|
|
||
| declare namespace PrefabTypeGeneration { | ||
| export type NodeServerConfigurationRaw = { | ||
| ${this.generateSchemaTypes('raw').join('\n ') || '// No types generated'} | ||
| } | ||
|
|
||
| export type NodeServerConfigurationAccessor = { | ||
| ${this.generateSchemaTypes().join('\n ') || '// No types generated'} | ||
| } | ||
| } | ||
|
|
||
| export class PrefabTypesafeNode { | ||
| constructor(private prefab: Prefab) { } | ||
|
|
||
| get<K extends keyof PrefabTypeGeneration.NodeServerConfigurationRaw>(key: K, contexts?: Contexts | ContextObj): PrefabTypeGeneration.NodeServerConfigurationRaw[K] { | ||
| return this.prefab.get(key, contexts) as PrefabTypeGeneration.NodeServerConfigurationRaw[K] | ||
| } | ||
|
|
||
| ${this.generateAccessorMethods().join('\n\n ') || '// No methods generated'} | ||
| } | ||
| ` | ||
| } | ||
|
|
||
| private additionalDependencies(): string[] { | ||
| const dependencies: string[] = [] | ||
| const hasFunctions = this.configurations().some((c) => c.hasFunction) | ||
|
|
||
| if (hasFunctions) { | ||
| dependencies.push(this.MUSTACHE_IMPORT) | ||
| } | ||
|
|
||
| return dependencies | ||
| } | ||
|
|
||
| private generateAccessorMethods(): string[] { | ||
| const uniqueMethods: Record<string, string> = {} | ||
| const schemaTypes = this.configurations().map((config) => { | ||
| let methodName = camelCase(config.key) | ||
|
|
||
| // If the method name starts with a digit, prefix it with an underscore to ensure method name is valid | ||
| if (/^\d/.test(methodName)) { | ||
| methodName = `_${methodName}` | ||
| } | ||
|
|
||
| console.log(config.key, methodName) | ||
|
|
||
| if (uniqueMethods[methodName]) { | ||
| throw new Error( | ||
| `Method '${methodName}' is already registered. Prefab key ${config.key} conflicts with '${uniqueMethods[methodName]}'!`, | ||
| ) | ||
| } | ||
|
|
||
| uniqueMethods[methodName] = config.key | ||
|
|
||
| if (config.hasFunction) { | ||
| const returnValue = new ZodToTypescriptReturnValueMapper().resolveType(config.schema) | ||
|
|
||
| return stripIndent` | ||
| ${methodName}(contexts?: Contexts | ContextObj): PrefabTypeGeneration.NodeServerConfigurationAccessor['${config.key}'] { | ||
| const raw = this.get('${config.key}', contexts) | ||
| return ${returnValue} | ||
| } | ||
| ` | ||
| } | ||
|
|
||
| return stripIndent` | ||
| ${methodName}(contexts?: Contexts | ContextObj): PrefabTypeGeneration.NodeServerConfigurationAccessor['${config.key}'] { | ||
| return this.get('${config.key}', contexts) | ||
| } | ||
| ` | ||
| }) | ||
|
|
||
| return schemaTypes | ||
| } | ||
|
|
||
| private generateSchemaTypes(target: ZodToTypescriptMapperTarget = 'accessor'): string[] { | ||
| const schemaTypes = this.configurations().flatMap((config) => { | ||
| const mapper = new ZodToTypescriptMapper({fieldName: config.key, target}) | ||
|
|
||
| return mapper.renderField(config.schema) | ||
| }) | ||
|
|
||
| return schemaTypes | ||
| } | ||
| } | ||
123 changes: 123 additions & 0 deletions
123
src/codegen/code-generators/react-typescript-generator.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| import {stripIndent} from 'common-tags' | ||
| import camelCase from 'lodash.camelcase' | ||
| import {z} from 'zod' | ||
|
|
||
| import {ZodToTypescriptMapper, type ZodToTypescriptMapperTarget} from '../language-mappers/zod-to-typescript-mapper.js' | ||
| import {ZodToTypescriptReturnValueMapper} from '../language-mappers/zod-to-typescript-return-value-mapper.js' | ||
| import {BaseTypescriptGenerator} from './base-typescript-generator.js' | ||
|
|
||
| export class ReactTypeScriptGenerator extends BaseTypescriptGenerator { | ||
| get filename(): string { | ||
| return 'prefab-client.ts' | ||
| } | ||
|
|
||
| protected durationTypeMap(): z.ZodTypeAny { | ||
| return z.object({ms: z.number(), seconds: z.number()}) | ||
| } | ||
|
|
||
| generate(): string { | ||
| return stripIndent` | ||
| /* eslint-disable */ | ||
| // AUTOGENERATED by prefab-cli's 'gen' command | ||
| import { Prefab } from "@prefab-cloud/prefab-cloud-js" | ||
| import { createPrefabHook } from "@prefab-cloud/prefab-cloud-react" | ||
| ${this.additionalDependencies().join('\n') || '// No additional dependencies required'} | ||
|
|
||
| declare namespace PrefabTypeGeneration { | ||
| export type ReactHookConfigurationRaw = { | ||
| ${this.generateSchemaTypes('raw').join('\n ') || '// No types generated'} | ||
| } | ||
|
|
||
| export type ReactHookConfigurationAccessor = { | ||
| ${this.generateSchemaTypes().join('\n ') || '// No types generated'} | ||
| } | ||
| } | ||
|
|
||
| export class PrefabTypesafeReact { | ||
| constructor(private prefab: Prefab) { } | ||
|
|
||
| get<K extends keyof PrefabTypeGeneration.ReactHookConfigurationRaw>(key: K): PrefabTypeGeneration.ReactHookConfigurationRaw[K] { | ||
| return this.prefab.get(key) as PrefabTypeGeneration.ReactHookConfigurationRaw[K] | ||
| } | ||
|
|
||
| ${this.generateAccessorMethods().join('\n\n ') || '// No methods generated'} | ||
| } | ||
|
|
||
| export const usePrefab = createPrefabHook(PrefabTypesafeReact) | ||
| ` | ||
| } | ||
|
|
||
| private additionalDependencies(): string[] { | ||
| const dependencies: string[] = [] | ||
| const hasFunctions = this.filteredConfigurations().some((c) => c.hasFunction) | ||
|
|
||
| if (hasFunctions) { | ||
| dependencies.push(this.MUSTACHE_IMPORT) | ||
| } | ||
|
|
||
| return dependencies | ||
| } | ||
|
|
||
| private filteredConfigurations() { | ||
| return this.configurations().filter( | ||
| (config) => config.configType === 'FEATURE_FLAG' || config.sendToClientSdk === true, | ||
| ) | ||
| } | ||
|
|
||
| private generateAccessorMethods(): string[] { | ||
| const uniqueMethods: Record<string, string> = {} | ||
| const schemaTypes = this.filteredConfigurations().map((config) => { | ||
| let methodName = camelCase(config.key) | ||
|
|
||
| // If the method name starts with a digit, prefix it with an underscore to ensure method name is valid | ||
| if (/^\d/.test(methodName)) { | ||
| methodName = `_${methodName}` | ||
| } | ||
|
|
||
| if (uniqueMethods[methodName]) { | ||
| throw new Error( | ||
| `Method '${methodName}' is already registered. Prefab key ${config.key} conflicts with '${uniqueMethods[methodName]}'!`, | ||
| ) | ||
| } | ||
|
|
||
| uniqueMethods[methodName] = config.key | ||
|
|
||
| if (config.configType === 'FEATURE_FLAG') { | ||
| return stripIndent` | ||
| get ${methodName}(): boolean { | ||
| return this.prefab.isEnabled('${config.key}') | ||
| } | ||
| ` | ||
| } | ||
|
|
||
| if (config.hasFunction) { | ||
| const returnValue = new ZodToTypescriptReturnValueMapper().resolveType(config.schema) | ||
|
|
||
| return stripIndent` | ||
| ${methodName}(): PrefabTypeGeneration.ReactHookConfigurationAccessor['${config.key}'] { | ||
| const raw = this.get('${config.key}') | ||
| return ${returnValue} | ||
| } | ||
| ` | ||
| } | ||
|
|
||
| return stripIndent` | ||
| get ${methodName}(): PrefabTypeGeneration.ReactHookConfigurationAccessor['${config.key}'] { | ||
| return this.get('${config.key}') | ||
| } | ||
| ` | ||
| }) | ||
|
|
||
| return schemaTypes | ||
| } | ||
|
|
||
| private generateSchemaTypes(target: ZodToTypescriptMapperTarget = 'accessor'): string[] { | ||
| const schemaTypes = this.filteredConfigurations().map((config) => { | ||
| const mapper = new ZodToTypescriptMapper({fieldName: config.key, target}) | ||
|
|
||
| return mapper.renderField(config.schema) | ||
| }) | ||
|
|
||
| return schemaTypes | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| import {z} from 'zod' | ||
|
|
||
| export class JsonToZodMapper { | ||
| resolve(data: unknown): z.ZodTypeAny { | ||
| if (Array.isArray(data)) { | ||
| if (data.length > 0) { | ||
| // Check if all elements in the array have the same type | ||
| const firstItem = data[0] | ||
|
|
||
| const isHomogeneous = data.every((item) => { | ||
| const itemsMatch = typeof item === typeof firstItem | ||
|
|
||
| // Special handling for objects and arrays | ||
| if (typeof firstItem === 'object') { | ||
| if (Array.isArray(item)) { | ||
| return Array.isArray(firstItem) | ||
| } | ||
|
|
||
| return !Array.isArray(firstItem) | ||
| } | ||
|
|
||
| return itemsMatch | ||
| }) | ||
|
|
||
| // For homogeneous arrays, use the first element's type | ||
| if (isHomogeneous) { | ||
| return z.array(this.resolve(data[0])) | ||
| } | ||
|
|
||
| // Explicitly do not handle mixed-type arrays | ||
| // They could be tuples or heterogeneous arrays | ||
| // Instead, we return an array of unknowns | ||
| } | ||
|
|
||
| return z.array(z.unknown()) | ||
| } | ||
|
|
||
| if (typeof data === 'object' && data !== null) { | ||
| const shape: Record<string, z.ZodTypeAny> = {} | ||
| const dataRecord = data as Record<string, unknown> | ||
| for (const key in dataRecord) { | ||
| if (Object.hasOwn(dataRecord, key)) { | ||
| shape[key] = this.resolve(dataRecord[key]) | ||
| } | ||
| } | ||
|
|
||
| return z.object(shape) | ||
| } | ||
|
|
||
| if (typeof data === 'string') { | ||
| return z.string() | ||
| } | ||
|
|
||
| if (typeof data === 'number') { | ||
| return z.number() | ||
| } | ||
|
|
||
| if (typeof data === 'boolean') { | ||
| return z.boolean() | ||
| } | ||
|
|
||
| if (data === null) { | ||
| return z.null() | ||
| } | ||
|
|
||
| console.warn(`Unknown json type:`, data) | ||
|
|
||
| // If the type is not recognized, default to 'any' | ||
| return z.any() | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.