@an5/orm 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,79 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { Model } from './types';
4
+
5
+ export class MetadataGenerator {
6
+ constructor(private outputPath: string) {}
7
+
8
+ public generate(models: Model[]) {
9
+ let metaContent = '// This file is auto-generated. Do not edit directly.\n\n';
10
+
11
+ metaContent += 'export const modelToTable: Record<string, string> = {\n';
12
+ for (const model of models) {
13
+ const props = this.getAllPropertyVariations(model.name);
14
+ const fullTableName = `[${model.schemaName}].[${model.tableName}]`;
15
+ for (const prop of props) {
16
+ metaContent += ` ${prop}: "${fullTableName}",\n`;
17
+ }
18
+ }
19
+ metaContent += '};\n\n';
20
+
21
+ metaContent += 'export const modelFields: Record<string, Record<string, { ts: string; sql: string }>> = {\n';
22
+ for (const model of models) {
23
+ const props = this.getAllPropertyVariations(model.name);
24
+ const fieldsStr = `{ ${model.fields.map(f => `${f.name}: { ts: "${f.type}${f.isOptional ? '?' : ''}", sql: "${f.sqlType}" }`).join(', ')} }`;
25
+ for (const prop of props) {
26
+ metaContent += ` ${prop}: ${fieldsStr},\n`;
27
+ }
28
+ }
29
+ metaContent += '};\n\n';
30
+
31
+ metaContent += 'export interface RelationDef {\n modelName: string;\n relationType: "many" | "one";\n foreignKey: string;\n localKey: string;\n}\n\n';
32
+
33
+ metaContent += 'export const relationMap: Record<string, Record<string, RelationDef>> = {\n';
34
+ for (const model of models) {
35
+ const props = this.getAllPropertyVariations(model.name);
36
+ let relationsContent = ` {\n`;
37
+ for (const rel of model.relations) {
38
+ relationsContent += ` ${rel.name}: { modelName: "${this.toCamelCase(rel.type)}", relationType: "${rel.isArray ? 'many' : 'one'}", foreignKey: "${rel.foreignKey || 'id'}", localKey: "${rel.localKey || 'id'}" },\n`;
39
+ }
40
+ relationsContent += ` }`;
41
+
42
+ for (const prop of props) {
43
+ metaContent += ` ${prop}: ${relationsContent},\n`;
44
+ }
45
+ }
46
+ metaContent += '};\n';
47
+
48
+ fs.writeFileSync(this.outputPath, metaContent);
49
+ }
50
+
51
+ private getAllPropertyVariations(modelName: string): string[] {
52
+ const variations = new Set<string>();
53
+
54
+ // 1. Standard camelCase (e.g. User -> user, McpServer -> mcpServer)
55
+ variations.add(this.toCamelCase(modelName));
56
+
57
+ // 2. Handle known acronyms at start (e.g. LLMProvider -> lLMProvider)
58
+ // This is already handled by toCamelCase if it only lowercases the first letter.
59
+ // But we might want 'llmProvider' as well.
60
+ const acronyms = ['LLM', 'AI', 'MCP', 'IT', 'QC', 'HR', 'MR', 'WH', 'SSIS', 'API', 'URL', 'ID', 'JSON'];
61
+
62
+ for (const acronym of acronyms) {
63
+ if (modelName.startsWith(acronym)) {
64
+ // e.g. LLMProvider -> llmProvider
65
+ variations.add(acronym.toLowerCase() + modelName.slice(acronym.length));
66
+
67
+ // e.g. LLMProvider -> lLMProvider (Prisma style)
68
+ variations.add(acronym[0].toLowerCase() + acronym.slice(1) + modelName.slice(acronym.length));
69
+ }
70
+ }
71
+
72
+ return Array.from(variations);
73
+ }
74
+
75
+ private toCamelCase(str: string): string {
76
+ if (!str) return '';
77
+ return str[0].toLowerCase() + str.slice(1);
78
+ }
79
+ }
@@ -0,0 +1,202 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { Model, Field, Relation } from './types';
4
+
5
+ // SQL Server type → TypeScript type mapping
6
+ const AN5_TO_TS: Record<string, string> = {
7
+ // String types
8
+ 'NVARCHAR': 'string',
9
+ 'VARCHAR': 'string',
10
+ 'CHAR': 'string',
11
+ 'NCHAR': 'string',
12
+ 'TEXT': 'string',
13
+ 'NTEXT': 'string',
14
+ 'XML': 'string',
15
+ // Numeric types
16
+ 'INT': 'number',
17
+ 'SMALLINT': 'number',
18
+ 'TINYINT': 'number',
19
+ 'BIGINT': 'number | bigint',
20
+ 'FLOAT': 'number',
21
+ 'REAL': 'number',
22
+ 'DECIMAL': 'number',
23
+ 'NUMERIC': 'number',
24
+ 'MONEY': 'number',
25
+ 'SMALLMONEY': 'number',
26
+ // Boolean
27
+ 'BIT': 'boolean',
28
+ // Date types
29
+ 'DATETIME': 'Date',
30
+ 'DATETIME2': 'Date',
31
+ 'SMALLDATETIME': 'Date',
32
+ 'DATE': 'Date',
33
+ 'TIME': 'Date',
34
+ 'DATETIMEOFFSET': 'Date',
35
+ // Binary types
36
+ 'VARBINARY': 'Buffer',
37
+ 'BINARY': 'Buffer',
38
+ 'IMAGE': 'Buffer',
39
+ // Other
40
+ 'UNIQUEIDENTIFIER': 'string',
41
+ 'SQL_VARIANT': 'any',
42
+ 'ROWVERSION': 'Buffer',
43
+ 'HIERARCHYID': 'string',
44
+ 'GEOGRAPHY': 'string',
45
+ 'GEOMETRY': 'string',
46
+ 'VECTOR': 'number[] | string',
47
+ };
48
+
49
+ // Parse base type from "NVARCHAR(255)" → "NVARCHAR"
50
+ function parseSqlType(raw: string): { base: string; params: string } {
51
+ const match = raw.match(/^(\w+)(?:\((.+)\))?$/);
52
+ if (!match) return { base: raw, params: '' };
53
+ return { base: match[1].toUpperCase(), params: match[2] || '' };
54
+ }
55
+
56
+ // Map SQL Server type to TypeScript type
57
+ export function sqlTypeToTs(sqlType: string): string {
58
+ const { base } = parseSqlType(sqlType);
59
+ return AN5_TO_TS[base] || 'any';
60
+ }
61
+
62
+ export class SchemaParser {
63
+ private schemaText: string = '';
64
+
65
+ constructor(private schemaDir: string) {}
66
+
67
+ public async parse(): Promise<Model[]> {
68
+ this.loadSchema();
69
+ const lines = this.schemaText.split('\n');
70
+ const models: Model[] = [];
71
+ let currentModel: Model | null = null;
72
+
73
+ for (let line of lines) {
74
+ line = line.trim();
75
+ if (!line || line.startsWith('//')) continue;
76
+
77
+ const modelHeaderMatch = line.match(/^model\s+(\w+)\s*\{/);
78
+ if (modelHeaderMatch) {
79
+ const modelName = modelHeaderMatch[1];
80
+ currentModel = {
81
+ name: modelName,
82
+ tableName: modelName.toLowerCase() + 's',
83
+ schemaName: 'dbo',
84
+ fields: [],
85
+ relations: []
86
+ };
87
+ models.push(currentModel);
88
+ continue;
89
+ }
90
+
91
+ if (line === '}') {
92
+ currentModel = null;
93
+ continue;
94
+ }
95
+
96
+ if (currentModel) {
97
+ this.parseModelLine(line, currentModel);
98
+ }
99
+ }
100
+
101
+ this.postProcessRelations(models);
102
+ return models;
103
+ }
104
+
105
+ private loadSchema() {
106
+ if (fs.existsSync(this.schemaDir)) {
107
+ const files = fs.readdirSync(this.schemaDir).filter(f => f.endsWith('.an5'));
108
+ for (const file of files) {
109
+ this.schemaText += fs.readFileSync(path.join(this.schemaDir, file), 'utf8') + '\n';
110
+ }
111
+ } else {
112
+ throw new Error(`No schema directory found at ${this.schemaDir}`);
113
+ }
114
+ }
115
+
116
+ private parseModelLine(line: string, model: Model) {
117
+ if (line.startsWith('@@map')) {
118
+ const mapMatch = line.match(/@@map\("(.+)"\)/);
119
+ if (mapMatch) model.tableName = mapMatch[1];
120
+ return;
121
+ }
122
+ if (line.startsWith('@@schema')) {
123
+ const schemaMatch = line.match(/@@schema\("(.+)"\)/);
124
+ if (schemaMatch) model.schemaName = schemaMatch[1];
125
+ return;
126
+ }
127
+ if (line.startsWith('@@unique')) {
128
+ const uniqueMatch = line.match(/@@unique\(\[([\w,\s]+)\]\)/);
129
+ if (uniqueMatch) {
130
+ const fields = uniqueMatch[1].split(',').map(f => f.trim());
131
+ model.compoundUniques = model.compoundUniques || [];
132
+ model.compoundUniques.push(fields);
133
+ }
134
+ return;
135
+ }
136
+ if (line.startsWith('@@description')) {
137
+ const descMatch = line.match(/@@description\("(.+)"\)/);
138
+ if (descMatch) model.description = descMatch[1];
139
+ return;
140
+ }
141
+ if (line.startsWith('@@')) return;
142
+
143
+ const parts = line.split(/\s+/);
144
+ const fieldName = parts[0];
145
+ let fieldType = parts[1];
146
+ if (!fieldName || !fieldType) return;
147
+
148
+ const isArray = fieldType.endsWith('[]');
149
+ const isOptional = fieldType.endsWith('?');
150
+ const cleanType = fieldType.replace('[]', '').replace('?', '');
151
+
152
+ // Parse SQL Server type (e.g., "NVARCHAR(255)" → base="NVARCHAR")
153
+ const { base: sqlBase } = parseSqlType(cleanType);
154
+
155
+ let tsType = 'any';
156
+ let isRelation = false;
157
+
158
+ // Check if it's a known SQL Server type
159
+ if (AN5_TO_TS[sqlBase]) {
160
+ tsType = sqlTypeToTs(cleanType);
161
+ } else if (cleanType[0] === cleanType[0].toUpperCase() && !cleanType.includes('(')) {
162
+ // Uppercase without parens = likely a relation to another model
163
+ tsType = cleanType;
164
+ isRelation = true;
165
+ }
166
+
167
+ if (isRelation) {
168
+ let foreignKey = '', localKey = '', relationName = '';
169
+ const nameMatch = line.match(/@relation\("(\w+)"/);
170
+ if (nameMatch) relationName = nameMatch[1];
171
+ const relationMatch = line.match(/@relation\((?:.*fields:\s*\[(\w+)\],)?\s*(?:.*references:\s*\[(\w+)\],?)?.*\)/);
172
+ if (relationMatch) {
173
+ foreignKey = relationMatch[1] || '';
174
+ localKey = relationMatch[2] || '';
175
+ }
176
+ model.relations.push({ name: fieldName, type: tsType, isArray, isOptional, foreignKey, localKey, relationName });
177
+ } else {
178
+ const hasDefault = line.includes('@default') || line.includes('@updatedAt') || line.includes('@id');
179
+ const isId = line.includes('@id');
180
+ let description: string | undefined;
181
+ const descMatch = line.match(/@description\("(.+)"\)/);
182
+ if (descMatch) description = descMatch[1];
183
+ model.fields.push({ name: fieldName, type: tsType, sqlType: cleanType, isOptional, hasDefault, isId, description });
184
+ }
185
+ }
186
+
187
+ private postProcessRelations(models: Model[]) {
188
+ for (const model of models) {
189
+ for (const rel of model.relations) {
190
+ if (!rel.foreignKey || !rel.localKey) {
191
+ const targetModel = models.find(m => m.name === rel.type);
192
+ if (targetModel) {
193
+ let opposite = rel.relationName ?
194
+ targetModel.relations.find(r => r.type === model.name && r.relationName === rel.relationName && r.foreignKey && r.localKey) :
195
+ targetModel.relations.find(r => r.type === model.name && r.foreignKey && r.localKey);
196
+ if (opposite) { rel.foreignKey = opposite.foreignKey; rel.localKey = opposite.localKey; }
197
+ }
198
+ }
199
+ }
200
+ }
201
+ }
202
+ }
@@ -0,0 +1,90 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { Model } from './types';
4
+
5
+ export class PythonGenerator {
6
+ constructor(private outputPath: string) {}
7
+
8
+ public generate(models: Model[]) {
9
+ let pyContent = '# This file is auto-generated. Do not edit directly.\n\n';
10
+
11
+ // 1. MODEL_TO_TABLE
12
+ pyContent += 'MODEL_TO_TABLE = {\n';
13
+ for (const model of models) {
14
+ const props = this.getAllPropertyVariations(model.name);
15
+ const fullTableName = `[${model.schemaName}].[${model.tableName}]`;
16
+ for (const prop of props) {
17
+ pyContent += ` "${prop}": "${fullTableName}",\n`;
18
+ }
19
+ }
20
+ pyContent += '}\n\n';
21
+
22
+ // 2. MODEL_FIELDS
23
+ pyContent += 'MODEL_FIELDS = {\n';
24
+ for (const model of models) {
25
+ const props = this.getAllPropertyVariations(model.name);
26
+ const fieldsStr = `{ ${model.fields.map(f => `"${f.name}": "${f.type}${f.isOptional ? '?' : ''}"`).join(', ')} }`;
27
+ for (const prop of props) {
28
+ pyContent += ` "${prop}": ${fieldsStr},\n`;
29
+ }
30
+ }
31
+ pyContent += '}\n\n';
32
+
33
+ // 3. RELATION_MAP
34
+ pyContent += 'RELATION_MAP = {\n';
35
+ for (const model of models) {
36
+ const props = this.getAllPropertyVariations(model.name);
37
+ let relationsContent = `{\n`;
38
+ for (const rel of model.relations) {
39
+ relationsContent += ` "${rel.name}": {\n`;
40
+ relationsContent += ` "modelName": "${this.toCamelCase(rel.type)}",\n`;
41
+ relationsContent += ` "relationType": "${rel.isArray ? 'many' : 'one'}",\n`;
42
+ relationsContent += ` "foreignKey": "${rel.foreignKey || 'id'}",\n`;
43
+ relationsContent += ` "localKey": "${rel.localKey || 'id'}"\n`;
44
+ relationsContent += ` },\n`;
45
+ }
46
+ relationsContent += ` }`;
47
+
48
+ for (const prop of props) {
49
+ pyContent += ` "${prop}": ${relationsContent},\n`;
50
+ }
51
+ }
52
+ pyContent += '}\n';
53
+
54
+ fs.writeFileSync(this.outputPath, pyContent);
55
+ }
56
+
57
+ private getAllPropertyVariations(modelName: string): string[] {
58
+ const variations = new Set<string>();
59
+
60
+ // 1. camelCase (User -> user, McpServer -> mcpServer)
61
+ variations.add(this.toCamelCase(modelName));
62
+
63
+ // 2. snake_case (User -> user, McpServer -> mcp_server)
64
+ variations.add(this.toSnakeCase(modelName));
65
+
66
+ const acronyms = ['LLM', 'AI', 'MCP', 'IT', 'QC', 'HR', 'MR', 'WH', 'SSIS', 'API', 'URL', 'ID', 'JSON'];
67
+ for (const acronym of acronyms) {
68
+ if (modelName.startsWith(acronym)) {
69
+ variations.add(acronym.toLowerCase() + modelName.slice(acronym.length));
70
+ variations.add(acronym[0].toLowerCase() + acronym.slice(1) + modelName.slice(acronym.length));
71
+ variations.add(this.toSnakeCase(acronym.toLowerCase() + modelName.slice(acronym.length)));
72
+ }
73
+ }
74
+
75
+ return Array.from(variations);
76
+ }
77
+
78
+ private toCamelCase(str: string): string {
79
+ if (!str) return '';
80
+ return str[0].toLowerCase() + str.slice(1);
81
+ }
82
+
83
+ private toSnakeCase(str: string): string {
84
+ if (!str) return '';
85
+ return str
86
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
87
+ .replace(/([a-z\d])([A-Z])/g, '$1_$2')
88
+ .toLowerCase();
89
+ }
90
+ }
@@ -0,0 +1,29 @@
1
+ export interface Field {
2
+ name: string;
3
+ type: string; // TypeScript type (string, number, boolean, Date, etc.)
4
+ sqlType: string; // SQL Server type (NVARCHAR(255), INT, DATETIME2, etc.)
5
+ isOptional: boolean;
6
+ hasDefault: boolean;
7
+ isId: boolean;
8
+ description?: string;
9
+ }
10
+
11
+ export interface Relation {
12
+ name: string;
13
+ type: string;
14
+ isArray: boolean;
15
+ isOptional: boolean;
16
+ foreignKey: string;
17
+ localKey: string;
18
+ relationName: string;
19
+ }
20
+
21
+ export interface Model {
22
+ name: string;
23
+ tableName: string;
24
+ schemaName: string;
25
+ fields: Field[];
26
+ relations: Relation[];
27
+ compoundUniques?: string[][];
28
+ description?: string;
29
+ }
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@an5/orm",
3
+ "version": "1.0.0",
4
+ "description": "The lightweight ORM for SQL Server with support for TypeScript, Python, and .NET (C#).",
5
+ "license": "MIT",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "files": [
9
+ "dist/**/*.{js,d.ts}",
10
+ "generator/src/**/*.ts",
11
+ "README.md"
12
+ ],
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/an5ORM/an5Orm.git"
16
+ },
17
+ "scripts": {
18
+ "generate": "npx tsx generator/src/index.ts",
19
+ "db:push": "npx tsx push.ts",
20
+ "db:pull": "npx tsx pull.ts",
21
+ "db:seed": "npx tsx seed.ts",
22
+ "db:cleanup": "npx tsx cleanup.ts",
23
+ "db:migrate": "npx tsx migrate.ts",
24
+ "db:migrate:diff": "npx tsx migrate.ts diff",
25
+ "db:migrate:generate": "npx tsx migrate.ts generate",
26
+ "db:migrate:status": "npx tsx migrate.ts status",
27
+ "release:cli": "npx tsx scripts/release-cli.ts",
28
+ "release": "node scripts/release.js",
29
+ "test": "node test/smoke.test.js",
30
+ "test:unit": "node test/unit.test.js",
31
+ "test:generator": "node test/generator.test.js"
32
+ },
33
+ "dependencies": {
34
+ "@an5/adapters": "^0.1.0",
35
+ "bcryptjs": "^2.4.3",
36
+ "dotenv": "^16.4.5",
37
+ "mssql": "^12.5.5"
38
+ },
39
+ "devDependencies": {
40
+ "@types/bcryptjs": "^2.4.6",
41
+ "@types/mssql": "^9.1.8",
42
+ "@types/node": "^20.11.0",
43
+ "tsx": "^4.7.1",
44
+ "typescript": "^6.0.3"
45
+ },
46
+ "publishConfig": {
47
+ "access": "public"
48
+ }
49
+ }