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 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 | 1x 1x 1x 44x 44x 443x 98x 98x 98x 98x 98x 98x 90x 90x 193x 193x 193x 90x 8x 2x 2x 6x 12x 5x 98x 490x 490x 55x 55x 4x 18x 18x 18x 45x 45x 45x 18x 514x 24x 490x 490x 13x 26x 13x 477x 477x 477x 477x 477x 32x 230x 66x 51x 44x 44x 7x 98x 102x 102x 296x 296x 296x 29x 29x 29x 44x 26x 18x 38x 18x 138x 138x 40x 40x 138x 36x 36x 36x 102x 102x 102x 1x 101x 101x 101x 2020x 4x 101x 4x 4x 80x 4x 4x 80x 80x 80x 80x 80x 4x 4x 4x 68x 1360x 4x 4x 68x 68x 4x 1x 1x 1x 6x 6x 6x 6x 6x 6x 1x 5x 4x 4x 4x 4x 80x 80x 4x 4x 4x 4x 4x 4x 4x 4x 4x 80x 4x 4x 4x 4x 4x 4x 4x 68x 68x 68x 68x 68x 4x 4x 4x 4x 4x 4x 68x 4x 4x 4x 4x 4x 4x 4x 128x 128x 128x 128x 128x 93x 128x 84x 44x 4x 4x 44x 44x 44x 18x 44x 17x 138x 138x 138x 44x 23x 21x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 4x 4x 4x 4x | import * as fs from "fs";
import * as path from "path";
import type {
Attribute,
ParsedFeature,
Schema,
VariableSchema,
VariableSchemaWithInline,
} from "@featurevisor/types";
import { Dependencies } from "../dependencies";
import { normalizeOptionValues, resolveTargets, targetIncludesFeature } from "../targeting";
export interface TypeScriptGenerationOptions {
tag?: string | string[];
target?: string | string[];
react?: boolean;
}
function shouldWrapArrayItemType(typeName: string): boolean {
const trimmed = typeName.trim();
return trimmed.includes("|") || trimmed.includes("&");
}
function formatObjectKey(key: string): string {
return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : JSON.stringify(key);
}
function buildObjectTypeFromSchema(
schema: Schema,
schemasByKey: Record<string, Schema>,
schemaTypeNames?: Record<string, string>,
): string {
const props = schema.properties;
const additional = schema.additionalProperties;
const hasProps = props && typeof props === "object" && Object.keys(props).length > 0;
const hasAdditional = additional && typeof additional === "object";
Iif (hasProps && hasAdditional) {
const requiredSet = new Set(schema.required || []);
const propEntries = Object.entries(props as Record<string, Schema>).map(([k, v]) => {
const propType = schemaToTypeScriptType(v as Schema, schemasByKey, schemaTypeNames);
const optional = !requiredSet.has(k);
return optional
? `${formatObjectKey(k)}?: ${propType}`
: `${formatObjectKey(k)}: ${propType}`;
});
const propUnion = Object.entries(props as Record<string, Schema>)
.map(([, v]) => schemaToTypeScriptType(v as Schema, schemasByKey, schemaTypeNames))
.join(" | ");
const additionalType = schemaToTypeScriptType(
additional as Schema,
schemasByKey,
schemaTypeNames,
);
const indexType = [additionalType, propUnion].filter(Boolean).join(" | ");
return `{ ${propEntries.join("; ")}; [key: string]: ${indexType} }`;
}
if (hasProps) {
const requiredSet = new Set(schema.required || []);
const entries = Object.entries(props as Record<string, Schema>)
.map(([k, v]) => {
const propType = schemaToTypeScriptType(v as Schema, schemasByKey, schemaTypeNames);
const optional = !requiredSet.has(k);
return optional
? `${formatObjectKey(k)}?: ${propType}`
: `${formatObjectKey(k)}: ${propType}`;
})
.join("; ");
return `{ ${entries} }`;
}
if (hasAdditional) {
const additionalType = schemaToTypeScriptType(
additional as Schema,
schemasByKey,
schemaTypeNames,
);
return `Record<string, ${additionalType}>`;
}
return "Record<string, unknown>";
}
function formatTypeImport(typeNames: string[], fromPath: string): string {
if (typeNames.length === 0) {
return "";
}
return `import type {\n${typeNames.map((name) => ` ${name},`).join("\n")}\n} from "${fromPath}";\n\n`;
}
/**
* Resolve a schema to its full definition, following schema references (schema: key).
*/
function resolveSchema(schema: Schema, schemasByKey: Record<string, Schema>): Schema {
Iif (schema.schema && schemasByKey[schema.schema]) {
return resolveSchema(schemasByKey[schema.schema], schemasByKey);
}
return schema;
}
/** Emit a TypeScript literal type for a primitive const value, or null if not a primitive. */
function constToLiteralType(constVal: unknown): string | null {
Iif (constVal === null || constVal === undefined) return null;
if (typeof constVal === "string") return JSON.stringify(constVal);
Eif (typeof constVal === "number") return String(constVal);
if (typeof constVal === "boolean") return constVal ? "true" : "false";
return null;
}
/** Emit a TypeScript union of literal types for an enum array (primitives only), or null. */
function enumToUnionType(enumArr: unknown[]): string | null {
Iif (enumArr.length === 0) return null;
const literals: string[] = [];
for (const v of enumArr) {
const lit = constToLiteralType(v);
Iif (lit === null) return null;
literals.push(lit);
}
return literals.join(" | ");
}
/**
* Converts a Schema (items or properties entry) to a TypeScript type string.
* Handles nested object/array and resolves schema references recursively.
* When schema has `oneOf`, emits a union of each branch type. When schema has primitive `const` or `enum`, emits a literal or union type.
* When schemaTypeNames is provided and schema is a reference (schema: key), returns that type name instead of inlining.
*/
function schemaToTypeScriptType(
schema: Schema,
schemasByKey: Record<string, Schema>,
schemaTypeNames?: Record<string, string>,
): string {
if (schema?.schema && schemaTypeNames?.[schema.schema]) {
return schemaTypeNames[schema.schema];
}
const resolved = resolveSchema(schema, schemasByKey);
if (resolved.oneOf && Array.isArray(resolved.oneOf) && resolved.oneOf.length > 0) {
const parts = resolved.oneOf.map((branch) =>
schemaToTypeScriptType(branch as Schema, schemasByKey, schemaTypeNames),
);
return parts.join(" | ");
}
const literalFromConst = resolved.const !== undefined ? constToLiteralType(resolved.const) : null;
const unionFromEnum =
resolved.enum && Array.isArray(resolved.enum) && resolved.enum.length > 0
? enumToUnionType(resolved.enum)
: null;
const type = resolved.type as string | undefined;
Iif (!type) {
return literalFromConst ?? unionFromEnum ?? "unknown";
}
switch (type) {
case "boolean":
return literalFromConst ?? unionFromEnum ?? "boolean";
case "string":
case "semver":
return literalFromConst ?? unionFromEnum ?? "string";
case "date":
return literalFromConst ?? unionFromEnum ?? "Date | string";
case "integer":
case "double":
return literalFromConst ?? unionFromEnum ?? "number";
case "array":
if (resolved.items) {
const itemType = schemaToTypeScriptType(resolved.items, schemasByKey, schemaTypeNames);
return shouldWrapArrayItemType(itemType) ? `(${itemType})[]` : `${itemType}[]`;
}
return "string[]";
case "object": {
return buildObjectTypeFromSchema(resolved, schemasByKey, schemaTypeNames);
}
default:
return "unknown";
}
}
/**
* Resolve variable schema to the schema shape used for code gen (inline or from schema reference).
*/
function getEffectiveVariableSchema(
variableSchema: VariableSchema,
schemasByKey: Record<string, Schema>,
): VariableSchemaWithInline | Schema | undefined {
Iif ("schema" in variableSchema && variableSchema.schema) {
return schemasByKey[variableSchema.schema];
}
return variableSchema as VariableSchemaWithInline;
}
function getPascalCase(str) {
// Remove special characters and split the string into an array of words
const words = str.replace(/[^a-zA-Z0-9]/g, " ").split(" ");
// Capitalize the first letter of each word and join them together
const pascalCased = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
return pascalCased;
}
function getRelativePath(from, to) {
const relativePath = path.relative(from, to);
Iif (relativePath.startsWith("..")) {
return path.join(".", relativePath);
}
return relativePath;
}
function getVariationUnionFromFeature(parsedFeature: ParsedFeature): string | null {
if (!parsedFeature.variations || parsedFeature.variations.length === 0) {
return null;
}
const values = Array.from(
new Set(parsedFeature.variations.map((variation) => JSON.stringify(variation.value))),
);
return values.length > 0 ? values.join(" | ") : null;
}
function getVariableTypeForFeaturesMap(
variableSchema: VariableSchema,
schemasByKey: Record<string, Schema>,
schemaTypeNames?: Record<string, string>,
): { typeName: string; schemaTypesUsed: string[] } {
const schemaTypesUsed: string[] = [];
const addSchemaUsed = (name: string) => {
Eif (name && !schemaTypesUsed.includes(name)) {
schemaTypesUsed.push(name);
}
};
if (
schemaTypeNames &&
"schema" in variableSchema &&
variableSchema.schema &&
schemasByKey[variableSchema.schema]
) {
const schemaTypeName = schemaTypeNames[variableSchema.schema];
addSchemaUsed(schemaTypeName);
return { typeName: schemaTypeName, schemaTypesUsed };
}
const effective = getEffectiveVariableSchema(variableSchema, schemasByKey);
Iif (!effective) {
return { typeName: "unknown", schemaTypesUsed };
}
if ("type" in effective && effective.type === "json") {
return { typeName: "unknown", schemaTypesUsed };
}
const typeName = schemaToTypeScriptType(effective as Schema, schemasByKey, schemaTypeNames);
Eif (schemaTypeNames) {
Object.values(schemaTypeNames).forEach((name) => {
if (typeName.includes(name)) {
addSchemaUsed(name);
}
});
}
return { typeName, schemaTypesUsed };
}
/**
* Generates the content of Schemas.ts: one exported type per schema key, using schema refs between schemas.
*/
function generateSchemasFileContent(
schemaKeys: string[],
schemasByKey: Record<string, Schema>,
): string {
const schemaTypeNames: Record<string, string> = {};
for (const k of schemaKeys) {
schemaTypeNames[k] = getPascalCase(k) + "Schema";
}
const lines: string[] = [];
for (const key of schemaKeys) {
const schema = schemasByKey[key];
Iif (!schema) continue;
const name = schemaTypeNames[key];
const typeStr = schemaToTypeScriptType(schema, schemasByKey, schemaTypeNames);
lines.push(`export type ${name} = ${typeStr};`);
}
return lines.join("\n") + "\n";
}
function generateAttributesFileContent(
attributes: Array<Attribute & { key: string; typescriptType: string }>,
schemaTypeNames: Record<string, string>,
): string {
const schemaTypesUsed = new Set<string>();
for (const attribute of attributes) {
Object.values(schemaTypeNames).forEach((typeName) => {
Iif (attribute.typescriptType.includes(typeName)) {
schemaTypesUsed.add(typeName);
}
});
}
const importLine = formatTypeImport(Array.from(schemaTypesUsed).sort(), "./schemas");
const lines = attributes.map((attribute) => {
const typeName = `${getPascalCase(attribute.key)}Attribute`;
return `export type ${typeName} = ${attribute.typescriptType};`;
});
return `${importLine}${lines.join("\n")}\n`;
}
const INDENT_NS = " ";
const INDENT_NS_BODY = " ";
const instanceSnippet = `
import type { Featurevisor } from "@featurevisor/sdk";
let _instance: Featurevisor;
export function setInstance(instance: Featurevisor) {
_instance = instance;
}
export function getInstance(): Featurevisor {
return _instance as Featurevisor;
}
`.trimStart();
export async function generateTypeScriptCodeForProject(
deps: Dependencies,
outputPath: string,
options: TypeScriptGenerationOptions = {},
) {
const { rootDirectoryPath, projectConfig, datasource } = deps;
const selectedTags = normalizeOptionValues(options.tag);
const shouldGenerateReact = Boolean(options.react);
const unknownTag = selectedTags.find((tag) => !projectConfig.tags.includes(tag));
if (unknownTag) {
throw new Error(
`Unknown tag "${unknownTag}". Available tags: ${projectConfig.tags.join(", ") || "none"}.`,
);
}
const selectedTargets = await resolveTargets(datasource, options.target, {
defaultToAll: false,
requireTargets: false,
});
console.log("\nGenerating TypeScript code...\n");
// Load schemas for resolving variable schema references
const schemaListKeys = await datasource.listSchemas();
const schemasByKey: Record<string, Schema> = {};
for (const key of schemaListKeys) {
try {
schemasByKey[key] = await datasource.readSchema(key);
} catch {
// Schema file may be invalid; skip for code gen
}
}
const schemaKeys = Object.keys(schemasByKey);
const hasSchemasFile = schemaKeys.length > 0;
Eif (hasSchemasFile) {
const schemasContent = generateSchemasFileContent(schemaKeys, schemasByKey);
const schemasFilePath = path.join(outputPath, "schemas.ts");
fs.writeFileSync(schemasFilePath, schemasContent);
console.log(
`Schemas type file written at: ${getRelativePath(rootDirectoryPath, schemasFilePath)}`,
);
}
const schemaTypeNames: Record<string, string> = {};
for (const k of schemaKeys) {
schemaTypeNames[k] = getPascalCase(k) + "Schema";
}
// instance
const instanceFilePath = path.join(outputPath, "instance.ts");
fs.writeFileSync(instanceFilePath, instanceSnippet);
console.log(`Instance file written at: ${getRelativePath(rootDirectoryPath, instanceFilePath)}`);
// attributes
const attributeFiles = await datasource.listAttributes();
const attributes: (Attribute & { typescriptType: string })[] = [];
const attributeTypeNames: Record<string, string> = {};
for (const attributeKey of attributeFiles) {
const parsedAttribute = await datasource.readAttribute(attributeKey);
Iif (parsedAttribute.archived) {
continue;
}
const typescriptType = schemaToTypeScriptType(
parsedAttribute as Schema,
schemasByKey,
hasSchemasFile ? schemaTypeNames : undefined,
);
attributes.push({
...parsedAttribute,
key: attributeKey,
typescriptType,
});
attributeTypeNames[attributeKey] = `${getPascalCase(attributeKey)}Attribute`;
}
const attributesFileContent = generateAttributesFileContent(
attributes as Array<Attribute & { key: string; typescriptType: string }>,
hasSchemasFile ? schemaTypeNames : {},
);
const attributesFilePath = path.join(outputPath, "attributes.ts");
fs.writeFileSync(attributesFilePath, attributesFileContent);
console.log(
`Attributes type file written at: ${getRelativePath(rootDirectoryPath, attributesFilePath)}`,
);
// context
const contextImport = formatTypeImport(Object.values(attributeTypeNames).sort(), "./attributes");
const attributeProperties = attributes
.map((attribute) => {
return ` ${formatObjectKey(attribute.key)}?: ${attributeTypeNames[attribute.key]};`;
})
.join("\n");
const contextContent = `
import type { AttributeKey, AttributeValue } from "@featurevisor/sdk";
${contextImport}export interface Context {
${attributeProperties}
[key: AttributeKey]: AttributeValue;
}
`.trimStart();
const contextTypeFilePath = path.join(outputPath, "context.ts");
fs.writeFileSync(contextTypeFilePath, contextContent);
console.log(
`Context type file written at: ${getRelativePath(rootDirectoryPath, contextTypeFilePath)}`,
);
// features
const featureFiles = await datasource.listFeatures();
const parsedFeatures: {
featureKey: string;
parsedFeature: ParsedFeature;
}[] = [];
for (const featureKey of featureFiles) {
const parsedFeature = (await datasource.readFeature(featureKey)) as ParsedFeature;
Iif (typeof parsedFeature.archived !== "undefined" && parsedFeature.archived) {
continue;
}
const featureTags = Array.isArray(parsedFeature.tags) ? parsedFeature.tags : [];
const matchesSelectedTag = selectedTags.some((tag) => featureTags.includes(tag));
const matchesSelectedTarget = selectedTargets.some((target) =>
targetIncludesFeature(target, featureKey, parsedFeature),
);
if (
(selectedTags.length > 0 || selectedTargets.length > 0) &&
!matchesSelectedTag &&
!matchesSelectedTarget
) {
continue;
}
parsedFeatures.push({ featureKey, parsedFeature });
}
const featuresTypeSchemasUsed = new Set<string>();
const featureTypeEntries = parsedFeatures
.map(({ featureKey, parsedFeature }) => {
const featureLines: string[] = [];
const variationUnion = getVariationUnionFromFeature(parsedFeature);
if (variationUnion) {
featureLines.push(`${INDENT_NS_BODY}variation: ${variationUnion};`);
}
if (parsedFeature.variablesSchema) {
for (const [variableKey, variableSchema] of Object.entries(parsedFeature.variablesSchema)) {
const { typeName, schemaTypesUsed } = getVariableTypeForFeaturesMap(
variableSchema,
schemasByKey,
hasSchemasFile ? schemaTypeNames : undefined,
);
schemaTypesUsed.forEach((name) => featuresTypeSchemasUsed.add(name));
featureLines.push(`${INDENT_NS_BODY}${formatObjectKey(variableKey)}: ${typeName};`);
}
}
if (featureLines.length === 0) {
return `${INDENT_NS}${formatObjectKey(featureKey)}: null;`;
}
return `${INDENT_NS}${formatObjectKey(featureKey)}: {\n${featureLines.join("\n")}\n${INDENT_NS}};`;
})
.join("\n");
const featuresSchemasImportLine = formatTypeImport(
[...featuresTypeSchemasUsed].sort(),
"./schemas",
);
const featuresFileContent = `
${featuresSchemasImportLine}export type Features = {
${featureTypeEntries}
};
export type FeatureKey = keyof Features;
export type VariableKey<F extends FeatureKey> = Features[F] extends Record<string, unknown>
? Extract<Exclude<keyof Features[F], "variation">, string>
: never;
export type VariableType<F extends FeatureKey, V extends VariableKey<F>> = Features[F] extends Record<string, unknown>
? Features[F][V]
: never;
export type Variation<F extends FeatureKey> = Features[F] extends { variation: infer V }
? V
: never;
`.trimStart();
const featuresFilePath = path.join(outputPath, "features.ts");
fs.writeFileSync(featuresFilePath, featuresFileContent);
console.log(`Features file written at: ${getRelativePath(rootDirectoryPath, featuresFilePath)}`);
const functionsFileContent = `
import { FeatureKey, Variation, VariableKey, VariableType } from "./features";
import { Context } from "./context";
import { getInstance } from "./instance";
export function isEnabled(featureKey: FeatureKey, context: Context = {}): boolean {
return getInstance().isEnabled(featureKey, context);
}
export function getVariation<F extends FeatureKey>(
featureKey: F,
context: Context = {},
): Variation<F> | null {
return getInstance().getVariation(featureKey, context) as Variation<F> | null;
}
export function getVariable<F extends FeatureKey, V extends VariableKey<F>>(
featureKey: F,
variableKey: V,
context: Context = {},
): VariableType<F, V> | null {
return getInstance().getVariable(featureKey, variableKey, context) as VariableType<F, V> | null;
}
`.trimStart();
const functionsFilePath = path.join(outputPath, "functions.ts");
fs.writeFileSync(functionsFilePath, functionsFileContent);
console.log(
`Functions file written at: ${getRelativePath(rootDirectoryPath, functionsFilePath)}`,
);
if (shouldGenerateReact) {
const reactFileContent = `
import {
useFlag as useFlagOriginal,
useVariation as useVariationOriginal,
useVariable as useVariableOriginal,
} from "@featurevisor/react";
import type { FeatureKey, Variation, VariableKey, VariableType } from "./features";
import type { Context } from "./context";
export function useFlag(featureKey: FeatureKey, context: Context = {}): boolean {
return useFlagOriginal(featureKey, context);
}
export function useVariation<F extends FeatureKey>(
featureKey: F,
context: Context = {},
): Variation<F> | null {
return useVariationOriginal(featureKey, context) as Variation<F> | null;
}
export function useVariable<F extends FeatureKey, V extends VariableKey<F>>(
featureKey: F,
variableKey: V,
context: Context = {},
): VariableType<F, V> | null {
return useVariableOriginal(featureKey, variableKey, context) as VariableType<F, V> | null;
}
`.trimStart();
const reactFilePath = path.join(outputPath, "react.ts");
fs.writeFileSync(reactFilePath, reactFileContent);
console.log(`React file written at: ${getRelativePath(rootDirectoryPath, reactFilePath)}`);
}
// index
const indexContent =
[
`export * from "./attributes";`,
`export * from "./context";`,
`export * from "./instance";`,
...(hasSchemasFile ? [`export * from "./schemas";`] : []),
`export * from "./features";`,
`export * from "./functions";`,
...(shouldGenerateReact ? [`export * from "./react";`] : []),
].join("\n") + "\n";
const indexFilePath = path.join(outputPath, "index.ts");
fs.writeFileSync(indexFilePath, indexContent);
console.log(`Index file written at: ${getRelativePath(rootDirectoryPath, indexFilePath)}`);
}
|