duplicate-polyfills-conformance-check.ts 6.9 KB
Newer Older
J
Joe Haddad 已提交
1 2 3 4 5
// eslint-disable-next-line import/no-extraneous-dependencies
import { namedTypes } from 'ast-types'
// eslint-disable-next-line import/no-extraneous-dependencies
import { NodePath } from 'ast-types/lib/node-path'
import { types } from 'next/dist/compiled/recast'
6 7 8 9
import {
  CONFORMANCE_ERROR_PREFIX,
  CONFORMANCE_WARNING_PREFIX,
} from '../constants'
J
Joe Haddad 已提交
10 11 12 13 14 15 16
import {
  IConformanceTestResult,
  IConformanceTestStatus,
  IGetAstNodeResult,
  IParsedModuleDetails,
  IWebpackConformanceTest,
} from '../TestInterface'
17 18 19 20
import {
  isNodeCreatingScriptElement,
  reducePropsToObject,
} from '../utils/ast-utils'
J
Joe Haddad 已提交
21
import { getLocalFileName } from '../utils/file-utils'
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

function getMessage(
  property: string,
  request: string,
  isWarning: Boolean = false
): string {
  if (isWarning) {
    return `${CONFORMANCE_WARNING_PREFIX}: Found a ${property} polyfill in ${getLocalFileName(
      request
    )}.`
  }
  return `${CONFORMANCE_ERROR_PREFIX}: Found a ${property} polyfill in ${getLocalFileName(
    request
  )}.`
}

export interface DuplicatePolyfillsConformanceTestSettings {
  BlockedAPIToBePolyfilled?: string[]
}

const BANNED_LEFT_OBJECT_TYPES = ['Identifier', 'ThisExpression']

export class DuplicatePolyfillsConformanceCheck
  implements IWebpackConformanceTest {
  private BlockedAPIs: string[] = []
  constructor(options: DuplicatePolyfillsConformanceTestSettings = {}) {
    this.BlockedAPIs = options.BlockedAPIToBePolyfilled || []
  }
  public getAstNode(): IGetAstNodeResult[] {
    const EARLY_EXIT_SUCCESS_RESULT: IConformanceTestResult = {
      result: IConformanceTestStatus.SUCCESS,
    }
    return [
      {
        visitor: 'visitAssignmentExpression',
        inspectNode: (
          path: NodePath<namedTypes.AssignmentExpression>,
          { request }: IParsedModuleDetails
        ): IConformanceTestResult => {
          const { node } = path
          const left = node.left as namedTypes.MemberExpression
          /**
           * We're only interested in code like `foo.fetch = bar;`.
           * For anything else we exit with a success.
           * Also foo in foo.bar needs to be either Identifier or `this` and not someFunction().fetch;
           */
          if (
            left.type !== 'MemberExpression' ||
            !BANNED_LEFT_OBJECT_TYPES.includes(left.object.type) ||
            left.property.type !== 'Identifier'
          ) {
            return EARLY_EXIT_SUCCESS_RESULT
          }
          if (!this.BlockedAPIs.includes(left.property.name)) {
            return EARLY_EXIT_SUCCESS_RESULT
          }
          /**
           * Here we know the code is `foo.(fetch/URL) = something.
           * If foo === this/self, fail it immediately.
           * check for this.[fetch|URL(...BlockedAPIs)]/ self.[fetch|URL(...BlockedAPIs)]
           **/
          if (isNodeThisOrSelf(left.object)) {
            return {
              result: IConformanceTestStatus.FAILED,
              warnings: [
                {
                  message: getMessage(left.property.name, request),
                },
              ],
            }
          }
          /**
           * we now are sure the code under examination is
           * `globalVar.[fetch|URL(...BlockedAPIs)] = something`
           **/
          const objectName = (left.object as namedTypes.Identifier).name
          const allBindings = path.scope.lookup(objectName)
          if (!allBindings) {
            /**
             * we have absolutely no idea where globalVar came from,
             * so lets just exit
             **/
            return EARLY_EXIT_SUCCESS_RESULT
          }

          try {
            const sourcePath = allBindings.bindings[objectName][0]
            const originPath = sourcePath.parentPath
            const {
              node: originNode,
            }: { node: namedTypes.VariableDeclarator } = originPath
            if (
              originNode.type === 'VariableDeclarator' &&
              isNodeThisOrSelf(originNode.init)
            ) {
              return {
                result: IConformanceTestStatus.FAILED,
                warnings: [
                  {
                    message: getMessage(left.property.name, request),
                  },
                ],
              }
            }
            if (
              originPath.name === 'params' &&
              originPath.parentPath.firstInStatement()
            ) {
              /**
               * We do not know what will be the value of this param at runtime so we just throw a warning.
               * ```
               * (function(scope){
               *  ....
               *  scope.fetch = new Fetch();
               * })(.....)
               * ```
               */
              return {
                result: IConformanceTestStatus.FAILED,
                warnings: [
                  {
                    message: getMessage(left.property.name, request, true),
                  },
                ],
              }
            }
          } catch (e) {
            return EARLY_EXIT_SUCCESS_RESULT
          }

          return EARLY_EXIT_SUCCESS_RESULT
        },
      },
      {
        visitor: 'visitCallExpression',
        inspectNode: (path: NodePath, { request }: IParsedModuleDetails) => {
          const { node }: { node: types.namedTypes.CallExpression } = path
          if (!node.arguments || node.arguments.length < 2) {
            return EARLY_EXIT_SUCCESS_RESULT
          }
          if (isNodeCreatingScriptElement(node)) {
            const propsNode = node
              .arguments[1] as types.namedTypes.ObjectExpression
            if (!propsNode.properties) {
              return EARLY_EXIT_SUCCESS_RESULT
            }
            const props: {
              [key: string]: string
            } = reducePropsToObject(propsNode)
            if (!('src' in props)) {
              return EARLY_EXIT_SUCCESS_RESULT
            }
            const foundBannedPolyfill = doesScriptLoadBannedAPIfromPolyfillIO(
              props.src,
              this.BlockedAPIs
            )
            if (foundBannedPolyfill) {
              return {
                result: IConformanceTestStatus.FAILED,
                warnings: [
                  {
                    message: `${CONFORMANCE_WARNING_PREFIX}: Found polyfill.io loading polyfill for ${foundBannedPolyfill}.`,
                  },
                ],
              }
            }
          }
          return EARLY_EXIT_SUCCESS_RESULT
        },
      },
    ]
  }
}

function isNodeThisOrSelf(node: any): boolean {
  return (
    node.type === 'ThisExpression' ||
    (node.type === 'Identifier' && node.name === 'self')
  )
}

function doesScriptLoadBannedAPIfromPolyfillIO(
  source: string,
  blockedAPIs: string[]
): string | undefined {
  const url = new URL(source)
  if (url.hostname === 'polyfill.io' && url.searchParams.has('features')) {
    const requestedAPIs = (url.searchParams.get('features') || '').split(',')
J
Joe Haddad 已提交
210
    return blockedAPIs.find((api) => requestedAPIs.includes(api))
211 212
  }
}