instanceOf.js.flow 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // @flow strict
  2. import inspect from './inspect';
  3. /**
  4. * A replacement for instanceof which includes an error warning when multi-realm
  5. * constructors are detected.
  6. */
  7. declare function instanceOf(
  8. value: mixed,
  9. constructor: mixed,
  10. ): boolean %checks(value instanceof constructor);
  11. // See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production
  12. // See: https://webpack.js.org/guides/production/
  13. export default process.env.NODE_ENV === 'production'
  14. ? // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')
  15. // eslint-disable-next-line no-shadow
  16. function instanceOf(value: mixed, constructor: mixed): boolean {
  17. return value instanceof constructor;
  18. }
  19. : // eslint-disable-next-line no-shadow
  20. function instanceOf(value: any, constructor: any): boolean {
  21. if (value instanceof constructor) {
  22. return true;
  23. }
  24. if (typeof value === 'object' && value !== null) {
  25. const className = constructor.prototype[Symbol.toStringTag];
  26. const valueClassName =
  27. // We still need to support constructor's name to detect conflicts with older versions of this library.
  28. Symbol.toStringTag in value
  29. ? value[Symbol.toStringTag]
  30. : value.constructor?.name;
  31. if (className === valueClassName) {
  32. const stringifiedValue = inspect(value);
  33. throw new Error(
  34. `Cannot use ${className} "${stringifiedValue}" from another module or realm.
  35. Ensure that there is only one instance of "graphql" in the node_modules
  36. directory. If different versions of "graphql" are the dependencies of other
  37. relied on modules, use "resolutions" to ensure only one version is installed.
  38. https://yarnpkg.com/en/docs/selective-version-resolutions
  39. Duplicate "graphql" modules cannot be used at the same time since different
  40. versions may have different capabilities and behavior. The data from one
  41. version used in the function from another could produce confusing and
  42. spurious results.`,
  43. );
  44. }
  45. }
  46. return false;
  47. };