|
1 | | -import { join } from 'node:path' |
2 | | -import type { DevupApiOptions } from '@devup-api/core' |
3 | | -import { createUrlMap, generateInterface } from '@devup-api/generator' |
4 | | -import { |
5 | | - createTmpDirAsync, |
6 | | - readOpenapiAsync, |
7 | | - writeInterfaceAsync, |
8 | | -} from '@devup-api/utils' |
9 | | -import type { Compiler } from 'webpack' |
10 | | -import { DefinePlugin } from 'webpack' |
11 | | - |
12 | | -export class devupApiWebpackPlugin { |
13 | | - options: DevupApiOptions |
14 | | - private initialized = false |
15 | | - |
16 | | - constructor(options?: DevupApiOptions) { |
17 | | - this.options = options || {} |
18 | | - } |
19 | | - |
20 | | - apply(compiler: Compiler): void { |
21 | | - // Perform async operations before compilation |
22 | | - compiler.hooks.beforeCompile.tapAsync( |
23 | | - 'devup-api', |
24 | | - async (_params, callback) => { |
25 | | - // Guard: only run once |
26 | | - if (this.initialized) { |
27 | | - callback() |
28 | | - return |
29 | | - } |
30 | | - |
31 | | - try { |
32 | | - this.initialized = true |
33 | | - |
34 | | - const tempDir = await createTmpDirAsync(this.options?.tempDir) |
35 | | - const schema = await readOpenapiAsync(this.options?.openapiFile) |
36 | | - |
37 | | - // Generate interface file |
38 | | - await writeInterfaceAsync( |
39 | | - join(tempDir, 'api.d.ts'), |
40 | | - generateInterface(schema, this.options), |
41 | | - ) |
42 | | - |
43 | | - // Create urlMap and set environment variable |
44 | | - const urlMap = createUrlMap(schema, this.options) |
45 | | - const define: Record<string, string> = {} |
46 | | - if (urlMap) { |
47 | | - define['process.env.DEVUP_API_URL_MAP'] = JSON.stringify(urlMap) |
48 | | - } |
49 | | - |
50 | | - // Add DefinePlugin to webpack configuration |
51 | | - if (Object.keys(define).length > 0) { |
52 | | - new DefinePlugin(define).apply(compiler) |
53 | | - } |
54 | | - |
55 | | - callback() |
56 | | - } catch (error) { |
57 | | - this.initialized = false |
58 | | - callback(error as Error) |
59 | | - } |
60 | | - }, |
61 | | - ) |
62 | | - } |
63 | | -} |
| 1 | +export * from './plugin' |
| 2 | +export { devupApiWebpackPlugin as default } from './plugin' |
0 commit comments