File size: 1,326 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import findUp from 'next/dist/compiled/find-up'
import path from 'path'
import fs from 'fs'
import type { NextConfig } from '../../server/config-shared'

const EVENT_SWC_PLUGIN_PRESENT = 'NEXT_SWC_PLUGIN_DETECTED'
type SwcPluginsEvent = {
  eventName: string
  payload: {
    pluginName: string
    pluginVersion?: string
  }
}

export async function eventSwcPlugins(
  dir: string,
  config: NextConfig
): Promise<Array<SwcPluginsEvent>> {
  try {
    const packageJsonPath = await findUp('package.json', { cwd: dir })
    if (!packageJsonPath) {
      return []
    }

    const { dependencies = {}, devDependencies = {} } = require(packageJsonPath)

    const deps = { ...devDependencies, ...dependencies }
    const swcPluginPackages =
      config.experimental?.swcPlugins?.map(([name, _]) => name) ?? []

    return swcPluginPackages.map((plugin) => {
      // swc plugins can be non-npm pkgs with absolute path doesn't have version
      const version = deps[plugin] ?? undefined
      let pluginName = plugin
      if (fs.existsSync(pluginName)) {
        pluginName = path.basename(plugin, '.wasm')
      }

      return {
        eventName: EVENT_SWC_PLUGIN_PRESENT,
        payload: {
          pluginName: pluginName,
          pluginVersion: version,
        },
      }
    })
  } catch (_) {
    return []
  }
}