feat(csv-loader): add support for custom type declarations

Introduce the ability to define reusable types within CSV files using
comment lines with the format `# TypeName := schema`.

- Support parsing type declarations from comments or schema cells
- Enable recursive expansion of type names within schemas
- Integrate declared types into generated TypeScript definitions
- Allow columns to reference declared types by name
This commit is contained in:
2026-04-21 13:47:16 +08:00
parent 89ac1619e7
commit 53ccac39e6
4 changed files with 531 additions and 12 deletions
+20 -6
View File
@@ -1,6 +1,6 @@
import * as path from "path";
import { schemaToTypeString } from "../index.js";
import type { PropertyConfig } from "./types.js";
import type { PropertyConfig, TypeDeclaration } from "./types.js";
/**
* Generate TypeScript interface for the CSV data
@@ -10,6 +10,7 @@ export function generateTypeDefinition(
propertyConfigs: PropertyConfig[],
references: Set<string>,
currentFilePath?: string,
typeDeclarations: TypeDeclaration[] = [],
): string {
const typeName = resourceName ? `${resourceName}Table` : "Table";
const currentTableName = currentFilePath
@@ -44,11 +45,24 @@ export function generateTypeDefinition(
const importSection = imports.length > 0 ? imports.join("\n") + "\n\n" : "";
// Generate type declarations for user-defined types
const typeDeclarationSection =
typeDeclarations.length > 0
? typeDeclarations
.map(
(decl) =>
`type ${decl.name} = ${schemaToTypeString(decl.schema, resourceNames)};`,
)
.join("\n") + "\n\n"
: "";
const properties = propertyConfigs
.map(
(config) =>
` readonly ${config.name}: ${schemaToTypeString(config.schema, resourceNames)};`,
)
.map((config) => {
const typeStr = config.declaredTypeName
? config.declaredTypeName
: schemaToTypeString(config.schema, resourceNames);
return ` readonly ${config.name}: ${typeStr};`;
})
.join("\n");
let exportAlias = "";
@@ -58,7 +72,7 @@ export function generateTypeDefinition(
exportAlias = `\nexport type ${singularType} = ${typeName}[number];`;
}
return `${importSection}type ${typeName} = readonly {
return `${importSection}${typeDeclarationSection}type ${typeName} = readonly {
${properties}
}[];
${exportAlias}