-
-
Notifications
You must be signed in to change notification settings - Fork 139
Expand file tree
/
Copy pathplugin-runner.ts
More file actions
458 lines (401 loc) · 17 KB
/
plugin-runner.ts
File metadata and controls
458 lines (401 loc) · 17 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
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
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-var-requires */
import { DataModel, isPlugin, isTypeDef, Model, Plugin } from '@zenstackhq/language/ast';
import {
createProject,
emitProject,
getDataModels,
getLiteral,
getLiteralArray,
hasValidationAttributes,
PluginError,
resolvePath,
saveProject,
type OptionValue,
type PluginDeclaredOptions,
type PluginFunction,
type PluginOptions,
type PluginResult,
} from '@zenstackhq/sdk';
import { type DMMF } from '@zenstackhq/sdk/prisma';
import colors from 'colors';
import ora from 'ora';
import path from 'path';
import type { Project } from 'ts-morph';
import { CorePlugins, ensureDefaultOutputFolder } from '../plugins/plugin-utils';
import telemetry from '../telemetry';
import { getVersion } from '../utils/version-utils';
type PluginInfo = {
name: string;
description?: string;
provider: string;
options: PluginDeclaredOptions;
run: PluginFunction;
dependencies: string[];
module: any;
};
export type PluginRunnerOptions = {
schema: Model;
schemaPath: string;
output?: string;
withPlugins?: string[];
withoutPlugins?: string[];
defaultPlugins: boolean;
compile: boolean;
};
/**
* ZenStack plugin runner
*/
export class PluginRunner {
/**
* Runs a series of nested generators
*/
async run(runnerOptions: PluginRunnerOptions): Promise<void> {
const version = getVersion();
console.log(colors.bold(`⌛️ ZenStack CLI v${version}, running plugins`));
ensureDefaultOutputFolder(runnerOptions);
const plugins: PluginInfo[] = [];
const pluginDecls = runnerOptions.schema.declarations.filter((d): d is Plugin => isPlugin(d));
for (const pluginDecl of pluginDecls) {
const pluginProvider = this.getPluginProvider(pluginDecl);
if (!pluginProvider) {
console.error(`Plugin ${pluginDecl.name} has invalid provider option`);
throw new PluginError('', `Plugin ${pluginDecl.name} has invalid provider option`);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let pluginModule: any;
try {
pluginModule = this.loadPluginModule(pluginProvider, runnerOptions.schemaPath);
} catch (err) {
console.error(`Unable to load plugin module ${pluginProvider}: ${err}`);
throw new PluginError('', `Unable to load plugin module ${pluginProvider}`);
}
if (!pluginModule.default || typeof pluginModule.default !== 'function') {
console.error(`Plugin provider ${pluginProvider} is missing a default function export`);
throw new PluginError('', `Plugin provider ${pluginProvider} is missing a default function export`);
}
const dependencies = this.getPluginDependencies(pluginModule);
const pluginOptions: PluginDeclaredOptions = {
provider: pluginProvider,
};
pluginDecl.fields.forEach((f) => {
const value = getLiteral(f.value) ?? getLiteralArray(f.value);
if (value === undefined) {
throw new PluginError(pluginDecl.name, `Invalid option value for ${f.name}`);
}
pluginOptions[f.name] = value;
});
plugins.push({
name: pluginDecl.name,
description: this.getPluginDescription(pluginModule),
provider: pluginProvider,
dependencies,
options: pluginOptions,
run: pluginModule.default as PluginFunction,
module: pluginModule,
});
}
const preprocessorPlugins = plugins.filter((p) => p.options.preprocessor);
const otherPlugins = plugins.filter((p) => !p.options.preprocessor);
// calculate all plugins (including core plugins implicitly enabled)
const { corePlugins, userPlugins } = this.calculateAllPlugins(
runnerOptions,
otherPlugins,
);
const allPlugins = [...corePlugins, ...userPlugins];
// check dependencies
for (const plugin of allPlugins) {
for (const dep of plugin.dependencies) {
if (!allPlugins.find((p) => p.provider === dep)) {
console.error(`Plugin ${plugin.provider} depends on "${dep}" but it's not declared`);
throw new PluginError(
plugin.name,
`Plugin ${plugin.provider} depends on "${dep}" but it's not declared`
);
}
}
}
if (allPlugins.length === 0) {
console.log(colors.yellow('No plugins configured.'));
return;
}
const warnings: string[] = [];
// run core plugins first
let dmmf: DMMF.Document | undefined = undefined;
let shortNameMap: Map<string, string> | undefined;
let prismaClientPath = '@prisma/client';
let prismaClientDtsPath: string | undefined = undefined;
const project = createProject();
const runUserPlugins = async (plugins: PluginInfo[]) => {
for (const { name, description, run, options: pluginOptions } of plugins) {
const options = { ...pluginOptions, prismaClientPath, prismaClientDtsPath };
const r = await this.runPlugin(
name,
description,
run,
runnerOptions,
options as PluginOptions,
dmmf,
shortNameMap,
project,
false
);
warnings.push(...(r?.warnings ?? [])); // the null-check is for backward compatibility
}
};
// run preprocessor plugins
await runUserPlugins(preprocessorPlugins);
for (const { name, description, run, options: pluginOptions } of corePlugins) {
const options = { ...pluginOptions, prismaClientPath };
const r = await this.runPlugin(
name,
description,
run,
runnerOptions,
options,
dmmf,
shortNameMap,
project,
true
);
warnings.push(...(r?.warnings ?? [])); // the null-check is for backward compatibility
if (r.dmmf) {
// use the DMMF returned by the plugin
dmmf = r.dmmf;
}
if (r.shortNameMap) {
// use the model short name map returned by the plugin
shortNameMap = r.shortNameMap;
}
if (r.prismaClientPath) {
// use the prisma client path returned by the plugin
prismaClientPath = r.prismaClientPath;
prismaClientDtsPath = r.prismaClientDtsPath;
}
}
// compile code generated by core plugins
await compileProject(project, runnerOptions);
// run user plugins
await runUserPlugins(userPlugins);
console.log(colors.green(colors.bold('\n👻 All plugins completed successfully!')));
warnings.forEach((w) => console.warn(colors.yellow(w)));
console.log(`Don't forget to restart your dev server to let the changes take effect.`);
}
private calculateAllPlugins(options: PluginRunnerOptions, plugins: PluginInfo[]) {
const corePlugins: PluginInfo[] = [];
let zodImplicitlyAdded = false;
// 1. @core/prisma
const existingPrisma = plugins.find((p) => p.provider === CorePlugins.Prisma);
if (existingPrisma) {
corePlugins.push(existingPrisma);
plugins.splice(plugins.indexOf(existingPrisma), 1);
} else if (options.defaultPlugins) {
corePlugins.push(this.makeCorePlugin(CorePlugins.Prisma, options.schemaPath, {}));
}
const hasValidation = this.hasValidation(options.schema);
// 2. @core/enhancer
const existingEnhancer = plugins.find((p) => p.provider === CorePlugins.Enhancer);
if (existingEnhancer) {
// enhancer should load zod schemas if there're validation rules
existingEnhancer.options.withZodSchemas = hasValidation;
corePlugins.push(existingEnhancer);
plugins.splice(plugins.indexOf(existingEnhancer), 1);
} else {
if (options.defaultPlugins) {
corePlugins.push(
this.makeCorePlugin(CorePlugins.Enhancer, options.schemaPath, {
// enhancer should load zod schemas if there're validation rules
withZodSchemas: hasValidation,
})
);
}
}
// 3. @core/zod
const existingZod = plugins.find((p) => p.provider === CorePlugins.Zod);
if (existingZod && !existingZod.options.output) {
// we can reuse the user-provided zod plugin if it didn't specify a custom output path
plugins.splice(plugins.indexOf(existingZod), 1);
corePlugins.push(existingZod);
}
if (
!corePlugins.some((p) => p.provider === CorePlugins.Zod) &&
options.defaultPlugins &&
corePlugins.some((p) => p.provider === CorePlugins.Enhancer) &&
hasValidation
) {
// ensure "@core/zod" is enabled if "@core/enhancer" is enabled and there're validation rules
zodImplicitlyAdded = true;
corePlugins.push(this.makeCorePlugin(CorePlugins.Zod, options.schemaPath, { modelOnly: true }));
}
// collect core plugins introduced by dependencies
plugins.forEach((plugin) => {
// TODO: generalize this
const isTrpcPlugin =
plugin.provider === '@zenstackhq/trpc' ||
// for testing
(process.env.ZENSTACK_TEST && plugin.provider.includes('trpc'));
for (const dep of plugin.dependencies) {
if (dep.startsWith('@core/')) {
const existing = corePlugins.find((p) => p.provider === dep);
if (existing) {
// TODO: generalize this
if (existing.provider === '@core/zod') {
// Zod plugin can be automatically enabled in `modelOnly` mode, however
// other plugin (tRPC) for now requires it to run in full mode
if (existing.options.modelOnly) {
delete existing.options.modelOnly;
}
if (
isTrpcPlugin &&
zodImplicitlyAdded // don't do it for user defined zod plugin
) {
// pass trpc plugin's `generateModels` option down to zod plugin
existing.options.generateModels = plugin.options.generateModels;
}
}
} else {
// add core dependency
const depOptions: Record<string, OptionValue | OptionValue[]> = {};
// TODO: generalize this
if (dep === '@core/zod' && isTrpcPlugin) {
// pass trpc plugin's `generateModels` option down to zod plugin
depOptions.generateModels = plugin.options.generateModels;
}
corePlugins.push(this.makeCorePlugin(dep, options.schemaPath, depOptions));
}
}
}
});
return { corePlugins, userPlugins: plugins };
}
private makeCorePlugin(
provider: string,
schemaPath: string,
options: Record<string, OptionValue | OptionValue[]>
): PluginInfo {
const pluginModule = require(this.getPluginModulePath(provider, schemaPath));
const pluginName = this.getPluginName(pluginModule, provider);
return {
name: pluginName,
description: this.getPluginDescription(pluginModule),
provider: provider,
dependencies: [],
options: { ...options, provider },
run: pluginModule.default,
module: pluginModule,
};
}
private hasValidation(schema: Model) {
return getDataModels(schema).some((model) => hasValidationAttributes(model) || this.hasTypeDefFields(model));
}
private hasTypeDefFields(model: DataModel) {
return model.fields.some((f) => isTypeDef(f.type.reference?.ref));
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private getPluginName(pluginModule: any, pluginProvider: string) {
return typeof pluginModule.name === 'string' ? (pluginModule.name as string) : pluginProvider;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private getPluginDescription(pluginModule: any) {
return typeof pluginModule.description === 'string' ? (pluginModule.description as string) : undefined;
}
private getPluginDependencies(pluginModule: any) {
return Array.isArray(pluginModule.dependencies) ? (pluginModule.dependencies as string[]) : [];
}
private getPluginProvider(plugin: Plugin) {
const providerField = plugin.fields.find((f) => f.name === 'provider');
return getLiteral<string>(providerField?.value);
}
private async runPlugin(
name: string,
description: string | undefined,
run: PluginFunction,
runnerOptions: PluginRunnerOptions,
options: PluginDeclaredOptions,
dmmf: DMMF.Document | undefined,
shortNameMap: Map<string, string> | undefined,
project: Project,
isCorePlugin: boolean
) {
if (!isCorePlugin && !this.isPluginEnabled(name, runnerOptions)) {
ora(`Plugin "${name}" is skipped`).start().warn();
return { warnings: [] };
}
const title = description ?? `Running plugin ${colors.cyan(name)}`;
const spinner = ora(title).start();
try {
const r = await telemetry.trackSpan<PluginResult | void>(
'cli:plugin:start',
'cli:plugin:complete',
'cli:plugin:error',
{
plugin: name,
options,
},
async () => {
const finalOptions = {
...options,
schemaPath: runnerOptions.schemaPath,
shortNameMap,
} as PluginOptions;
return await run(runnerOptions.schema, finalOptions, dmmf, {
output: runnerOptions.output,
compile: runnerOptions.compile,
tsProject: project,
});
}
);
spinner.succeed();
if (typeof r === 'object') {
return r;
} else {
return { warnings: [] };
}
} catch (err) {
spinner.fail();
throw err;
}
}
private isPluginEnabled(name: string, runnerOptions: PluginRunnerOptions) {
if (runnerOptions.withPlugins && !runnerOptions.withPlugins.includes(name)) {
return false;
}
if (runnerOptions.withoutPlugins && runnerOptions.withoutPlugins.includes(name)) {
return false;
}
return true;
}
private getPluginModulePath(provider: string, schemaPath: string) {
if (process.env.ZENSTACK_TEST === '1' && provider.startsWith('@zenstackhq/')) {
// test code runs with its own sandbox of node_modules, make sure we don't
// accidentally resolve to the external ones
return path.resolve(`node_modules/${provider}`);
}
let pluginModulePath = provider;
if (provider.startsWith('@core/')) {
pluginModulePath = provider.replace(/^@core/, path.join(__dirname, '../plugins'));
} else {
try {
// direct require
require.resolve(pluginModulePath);
} catch {
// relative
pluginModulePath = resolvePath(provider, { schemaPath });
}
}
return pluginModulePath;
}
private loadPluginModule(provider: string, schemaPath: string) {
const pluginModulePath = this.getPluginModulePath(provider, schemaPath);
return require(pluginModulePath);
}
}
async function compileProject(project: Project, runnerOptions: PluginRunnerOptions) {
if (runnerOptions.compile !== false) {
// emit
await emitProject(project);
} else {
// otherwise save ts files
await saveProject(project);
}
}