-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzmodel-parser.ts
More file actions
220 lines (186 loc) · 6.31 KB
/
zmodel-parser.ts
File metadata and controls
220 lines (186 loc) · 6.31 KB
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
import * as fs from 'fs'
import * as path from 'path'
import { CliError } from './cli-error'
type DatabaseProvider = 'sqlite' | 'postgresql' | 'mysql'
export interface DatasourceConfig {
provider: DatabaseProvider
url: string
}
export interface GeneratorConfig {
provider: string
output?: string
engineType?: string
}
export interface ZModelConfig {
datasource: DatasourceConfig
generator: GeneratorConfig
prismaSchemaPath?: string
}
/**
* Remove comments from zmodel schema content
*/
function removeComments(content: string): string {
// Remove multi-line comments (/** ... */)
content = content.replace(/\/\*[\s\S]*?\*\//g, '')
// Remove single-line comments (//...)
content = content.replace(/^\s*\/\/.*$/gm, '')
return content
}
/**
* Try to load datasource URL from prisma.config.ts
*/
function loadPrismaConfig(schemaDir: string): string | null {
const configPath = path.join(schemaDir, 'prisma.config.ts')
if (!fs.existsSync(configPath)) {
return null
}
try {
const configContent = fs.readFileSync(configPath, 'utf-8')
// Create a sandbox environment to evaluate the config
const env = (varName: string) => {
const value = process.env[varName]
if (!value) {
throw new CliError(`Environment variable ${varName} is not set`)
}
return value
}
// Extract the export default statement and the config object
// Handle: export default defineConfig({ ... })
const defineConfigMatch = configContent.match(
/export\s+default\s+defineConfig\s*\(\s*(\{[\s\S]*?\})\s*\)/
)
// Handle: export default { ... }
const directExportMatch = configContent.match(/export\s+default\s+(\{[\s\S]*?\})(?:\s*;|\s*$)/m)
let configObjectStr = defineConfigMatch?.[1] || directExportMatch?.[1]
if (!configObjectStr) {
return null
}
// Use Function constructor to safely evaluate the object literal
// This is safer than eval as it doesn't have access to the local scope
const configFn = new Function('env', `return ${configObjectStr}`)
const config = configFn(env)
return config?.datasource?.url
} catch (error) {
if (error instanceof Error) {
throw error
}
console.warn(`Warning: Failed to parse prisma.config.ts: ${error}`)
return null
}
}
/**
* Parse datasource configuration from zmodel schema
*/
function parseDatasource(
content: string,
schemaDir: string,
datasourceUrlOverride?: string
): DatasourceConfig {
// Match datasource block
const datasourceMatch = content.match(/datasource\s+\w+\s*\{([^}]+)\}/s)
if (!datasourceMatch) {
throw new CliError('No datasource block found in zmodel schema')
}
const datasourceBlock = datasourceMatch[1]
// Extract provider
const providerMatch = datasourceBlock.match(/provider\s*=\s*['"]([^'"]+)['"]/)
if (!providerMatch) {
throw new CliError('No provider found in datasource block')
}
const provider = providerMatch[1] as DatabaseProvider
// If CLI override is provided, use it
if (datasourceUrlOverride) {
return { provider, url: datasourceUrlOverride }
}
// Extract url value using single regex (could be string literal, env() call, or expression)
const urlMatch = datasourceBlock.match(/url\s*=\s*([^\n]+)/)
let url: string | null = null
if (urlMatch) {
const urlValueStr = urlMatch[1].trim()
// Create env helper function
const env = (varName: string) => {
const value = process.env[varName]
if (!value) {
throw new CliError(`Environment variable ${varName} is not set`)
}
return value
}
try {
// Use Function constructor to evaluate the url value
const urlFn = new Function('env', `return ${urlValueStr}`)
url = urlFn(env)
} catch (evalError) {
if (evalError instanceof CliError) {
throw evalError
}
throw new CliError(
'Could not evaluate datasource url from schema, you could provide it via -d option.'
)
}
} else {
url = loadPrismaConfig(schemaDir)
// If still no URL found, throw error
if (url == null) {
throw new CliError(
'No datasource URL found. For Prisma 7, ensure prisma.config.ts exists with datasource configuration or directly provide the URL via -d option.'
)
}
}
if (!url) {
throw new CliError('datasource url has no value, you could provide it via -d option.')
}
return { provider, url }
}
/**
* Parse generator configuration from zmodel schema
*/
function parseGenerator(content: string): GeneratorConfig {
// Match generator block for prisma client
const generatorMatch = content.match(/generator\s+\w+\s*\{([^}]+)\}/s)
if (!generatorMatch) {
throw new CliError(
'No generator block found in zmodel schema.\nZenStack V3 is not supported, V3 will have built-in proxy support soon.'
)
}
const generatorBlock = generatorMatch[1]
// Extract provider
const providerMatch = generatorBlock.match(/provider\s*=\s*['"]([^'"]+)['"]/)
if (!providerMatch) {
throw new CliError('No provider found in generator block')
}
const provider = providerMatch[1]
// Extract output (optional)
const outputMatch = generatorBlock.match(/output\s*=\s*['"]([^'"]+)['"]/)
const output = outputMatch ? outputMatch[1] : undefined
// Extract engineType (optional)
const engineTypeMatch = generatorBlock.match(/engineType\s*=\s*['"]([^'"]+)['"]/)
const engineType = engineTypeMatch ? engineTypeMatch[1] : undefined
return { provider, output, engineType }
}
/**
* Parse plugin block for '@core/prisma' provider and extract output
*/
export function parsePrismaSchemaPath(content: string): string | undefined {
const match = content.match(
/plugin\s+\w+\s*\{[^}]*provider\s*=\s*['"]@core\/prisma['"][^}]*output\s*=\s*['"]([^'"]+)['"][^}]*\}/s
)
return match ? match[1] : undefined
}
/**
* Parse zmodel schema file and extract datasource and generator configuration
*/
export function parseZModelSchema(
zmodelPath: string,
datasourceUrlOverride?: string
): ZModelConfig {
const content = removeComments(fs.readFileSync(zmodelPath, 'utf-8'))
const schemaDir = path.dirname(zmodelPath)
const datasource = parseDatasource(content, schemaDir, datasourceUrlOverride)
const generator = parseGenerator(content)
const prismaSchemaPath = parsePrismaSchemaPath(content)
return {
datasource,
generator,
prismaSchemaPath,
}
}